cmd-exec server-side timeout.
[ccsdk/cds.git] / ms / command-executor / src / main / python / utils.py
1 #
2 # Copyright (C) 2019 Bell Canada.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #      http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16 from google.protobuf.timestamp_pb2 import Timestamp
17
18 import proto.CommandExecutor_pb2 as CommandExecutor_pb2
19 import json
20 import email.parser
21
22 CDS_IS_SUCCESSFUL_KEY = "cds_is_successful"
23 ERR_MSG_KEY = "err_msg"
24 RESULTS_KEY = "results"
25 RESULTS_LOG_KEY = "results_log"
26 RESPONSE_MAX_SIZE = 4 * 1024 * 1024 # 4Mb
27
28 def get_blueprint_id(request):
29   blueprint_name = request.identifiers.blueprintName
30   blueprint_version = request.identifiers.blueprintVersion
31   return blueprint_name + '/' + blueprint_version
32
33 def get_blueprint_timeout(request):
34   return request.timeOut
35
36 # Create a response for grpc. Fills in the timestamp as well as removes cds_is_successful element
37 def build_grpc_response(request_id, response):
38   if response[CDS_IS_SUCCESSFUL_KEY]:
39     status = CommandExecutor_pb2.SUCCESS
40   else:
41     status = CommandExecutor_pb2.FAILURE
42
43   response.pop(CDS_IS_SUCCESSFUL_KEY)
44   logs = response.pop(RESULTS_LOG_KEY)
45
46   # Payload should only contains response data returned from the executed script and/or the error message
47   payload = json.dumps(response)
48
49   timestamp = Timestamp()
50   timestamp.GetCurrentTime()
51
52   execution_output = CommandExecutor_pb2.ExecutionOutput(requestId=request_id,
53                                              response=logs,
54                                              status=status,
55                                              payload=payload,
56                                              timestamp=timestamp)
57
58   return truncate_execution_output(execution_output)
59
60 # build a ret data structure used to populate the ExecutionOutput
61 def build_ret_data(cds_is_successful, results_log=[], error=None):
62   ret_data = {
63     CDS_IS_SUCCESSFUL_KEY: cds_is_successful,
64     RESULTS_LOG_KEY: results_log
65   }
66   if error:
67     ret_data[ERR_MSG_KEY] = error
68   return ret_data
69
70 # Truncate execution logs to make sure gRPC response doesn't exceed the gRPC buffer capacity
71 def truncate_execution_output(execution_output):
72   sum_truncated_chars = 0
73   if execution_output.ByteSize() > RESPONSE_MAX_SIZE:
74     while execution_output.ByteSize() > RESPONSE_MAX_SIZE:
75         removed_item = execution_output.response.pop()
76         sum_truncated_chars += len(removed_item)
77     execution_output.response.append("[...] TRUNCATED CHARS : {}".format(sum_truncated_chars))
78   return execution_output
79
80
81 # Read temp file 'outputfile' into results_log and split out the returned payload into payload_result
82 def parse_cmd_exec_output(outputfile, logger, payload_result, results_log):
83   payload_section = []
84   is_payload_section = False
85   outputfile.seek(0)
86   while True:
87     output = outputfile.readline()
88     if output == '':
89       break
90     if output.startswith('BEGIN_EXTRA_PAYLOAD'):
91       is_payload_section = True
92       output = outputfile.readline()
93     if output.startswith('END_EXTRA_PAYLOAD'):
94       is_payload_section = False
95       output = ''
96       payload = '\n'.join(payload_section)
97       msg = email.parser.Parser().parsestr(payload)
98       for part in msg.get_payload():
99         payload_result.update(json.loads(part.get_payload()))
100     if output and not is_payload_section:
101       logger.info(output.strip())
102       results_log.append(output.strip())
103     else:
104       payload_section.append(output.strip())
105