diff options
Diffstat (limited to 'lib/srtgui/api.py')
-rw-r--r-- | lib/srtgui/api.py | 153 |
1 files changed, 125 insertions, 28 deletions
diff --git a/lib/srtgui/api.py b/lib/srtgui/api.py index 761839a8..2478fb9e 100644 --- a/lib/srtgui/api.py +++ b/lib/srtgui/api.py @@ -2,6 +2,7 @@ # BitBake Toaster Implementation # # Copyright (C) 2016-2018 Intel Corporation +# Copyright (C) 2018-2023 Wind River Systems # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as @@ -28,6 +29,7 @@ import re import json from django.http import JsonResponse +from django.views.generic import View logger = logging.getLogger("srt") @@ -54,38 +56,71 @@ def error_log(severity,description): error = ErrorLog.objects.create(severity=severity,description=description,) error.save() +# Quote parameters if spaces +def parameter_join(a): + str = [] + for s in a: + if (' ' in s) or (0 == len(s)): + str.append('"%s"' % s) + else: + str.append(s) + return ' '.join(str) + + +# # Sub Process calls +# +# Enforce that all scripts run from the SRT_BASE_DIR context +# + def execute_process(*args): + # Only string-type parameters allowed cmd_list = [] for arg in args: + if not arg: continue if isinstance(arg, (list, tuple)): # Flatten all the way down for a in arg: - cmd_list.append(a) + if not a: continue + cmd_list.append(str(a)) else: - cmd_list.append(arg) - - # Python < 3.5 compatible - if sys.version_info < (3,5): - process = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - try: - stdout, stderr = process.communicate(input) - except: - process.kill() - process.wait() - raise - retcode = process.poll() - return retcode, stdout, stderr - else: - result = subprocess.run(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - return result.returncode,result.stdout,result.stderr + cmd_list.append(str(arg)) + + srt_base_dir = os.environ.get('SRT_BASE_DIR') + if srt_base_dir and (srt_base_dir != os.getcwd()): + os.chdir(srt_base_dir) + _log(f"FOOBAR:CHDIR{srt_base_dir}") + if cmd_list[0].startswith('bin/') or cmd_list[0].startswith('./bin'): + cmd_list[0] = os.path.join(srt_base_dir,cmd_list[0]) + _log(f"FOOBAR:{cmd_list[0]}:{os.getcwd()}") + + result = subprocess.run(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return(result.returncode,result.stdout.decode('utf-8'),result.stderr.decode('utf-8')) + +# For Jobs, with captured output +def execute_process_close_fds(cmnd): + srt_base_dir = os.environ.get('SRT_BASE_DIR') + if srt_base_dir and (srt_base_dir != os.getcwd()): + os.chdir(srt_base_dir) + if cmnd[0].startswith('bin/') or cmnd[0].startswith('./bin'): + cmnd[0] = os.path.join(srt_base_dir,cmnd[0]) + subprocess.Popen(cmnd,close_fds=True) + +# For Jobs, with captured output +def execute_system(cmnd): + srt_base_dir = os.environ.get('SRT_BASE_DIR') + if srt_base_dir and (srt_base_dir != os.getcwd()): + os.chdir(srt_base_dir) + if cmnd.startswith('bin/') or cmnd.startswith('./bin'): + cmnd = srt_base_dir + '/' + cmnd[0] + return os.system(cmnd) # # Update CVE datasource list: (a) fetch alt sources, (b) refresh preview sources # # #### TODO -def update_cve_datasources(source_filter=''): +def update_cve_datasources(source_filter='',force_update_source=True): # Attach all matching CVE sources _log("Alternate1:%s" % (cve_object.name)) query_set = DataSource.objects.filter(data="cve") @@ -98,12 +133,13 @@ def update_cve_datasources(source_filter=''): _log("Alternate CVE source %s for %s (created=%s)" % (ds.key,cve_object.name,created)) # Force update the CVE summary data from sources - result_returncode,result_stdout,result_stderr = execute_process( - './bin/nist/srtool_nist.py', - '--update-cve-list', - cve_object.name, - '--force' - ) + if force_update_source: + result_returncode,result_stdout,result_stderr = execute_process( + os.path.join(os.environ.get('SRT_BASE_DIR'),'bin/nist/srtool_nist.py'), + '--update-cve-list', + cve_object.name, + '--force' + ) # # Extract Upstream CVE record details @@ -123,14 +159,19 @@ def readCveDetails_Upstream(cve, cve_datasource): v.description = "ERROR(%s):missing lookup command" % (cve_datasource.description) return v lookup_command = lookup_command.replace('%command%','--cve-detail=%s' % cve.name) - result_returncode,result_stdout,result_stderr = execute_process(lookup_command.split(' ')) + lookup_commands = lookup_command.split(' ') + # Convert local SRT bin calls to absolute path calls + if not lookup_commands[0].startswith('/'): + lookup_commands[0] = os.path.join(os.environ.get('SRT_BASE_DIR', './'),lookup_commands[0]) + # Execute the call + result_returncode,result_stdout,result_stderr = execute_process(*lookup_commands) #_log("SRT_%s=%s|%s|%s" % (cve_datasource.key,result_returncode,result_stdout,result_stderr)) if 0 != result_returncode: result_stdout = str(result_stdout) v.description = "ERROR(%s):%s" % (result_returncode,result_stderr) return v - for line in result_stdout.decode("utf-8").splitlines(): + for line in result_stdout.splitlines(): try: name = line[:line.index('=')] value = line[line.index('=')+1:].replace("[EOL]","\n") @@ -175,7 +216,7 @@ def readCveDetails_Upstream(cve, cve_datasource): elif name == 'ATTRIBUTES': # Returned metadata lookup_attributes = value - _log("NOTE:readCveDetails_Upstream:%s:%s" % (v.name,v.cvssV2_severity)) + #_log("NOTE:readCveDetails_Upstream:%s:%s:%s:%s:" % (v.name,v.cvssV2_severity,cve_datasource.description,v.description[:20])) # Check for metadata special cases if cve_datasource.LOOKUP_MISSING in lookup_attributes: @@ -345,7 +386,7 @@ def summaryCveDetails(cve,cve_sources): # No data sources if not cve_main: - return cve_detail,cve_html + return readCveDetails_None(cve),cve_html # Merge the data into summary record summaryMerge(cve_detail,cve_main,cve_local,cve_html,'description') @@ -724,3 +765,59 @@ def publishMarkNone(cve_list,date_start,date_stop): cvehistory = CveHistory(cve=cve, comment=Update.MARK_UNMARK, date=mid_date, author='SRTool') cvehistory.save() + +class XhrJobRequest(View): +# from orm.models import Job + + def get(self, request, *args, **kwargs): + return HttpResponse() + + def post(self, request, *args, **kwargs): + """ + Job control + + Entry point: /xhr_jobrequest/<project_id> + Method: POST + + Args: + id: id of job to change + jobCancel = job_request_id ... + jobDelete = id ... + + Returns: + {"error": "ok"} + or + {"error": <error message>} + """ + +# project = Project.objects.get(pk=kwargs['pid']) + + if 'jobCancel' in request.POST: + for i in request.POST['jobCancel'].strip().split(" "): + try: + job = Job.objects.get(pk=i) + job.cancel() + except Job.DoesNotExist: + return error_response('No such job request id %s' % i) + + return error_response('ok') + + if 'jobDelete' in request.POST: + for i in request.POST['jobDelete'].strip().split(" "): + try: + Job.objects.select_for_update().get( + sprint=sprint, + pk=i, + state__lte=Job.INPROGRESS).delete() + + except Job.DoesNotExist: + pass + return error_response("ok") + + response = HttpResponse() + response.status_code = 500 + return response + + + + |