Improve Remote Python Executor error handling and allow for structured response
[ccsdk/cds.git] / ms / command-executor / src / main / python / command_executor_server.py
1 #!/usr/bin/python
2
3 #
4 # Copyright (C) 2019 Bell Canada.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 #      http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 import logging
19 import os, sys
20 import proto.CommandExecutor_pb2_grpc as CommandExecutor_pb2_grpc
21
22 from command_executor_handler import CommandExecutorHandler
23 import utils
24
25 _ONE_DAY_IN_SECONDS = 60 * 60 * 24
26
27
28 class CommandExecutorServer(CommandExecutor_pb2_grpc.CommandExecutorServiceServicer):
29
30     def __init__(self):
31         self.logger = logging.getLogger(self.__class__.__name__)
32
33     def prepareEnv(self, request, context):
34         blueprint_id = utils.get_blueprint_id(request)
35         self.logger.info("{} - Received prepareEnv request".format(blueprint_id))
36         self.logger.info(request)
37
38         results = []
39         handler = CommandExecutorHandler(request)
40         if not handler.prepare_env(request, results):
41             self.logger.info("{} - Failed to prepare python environment. {}".format(blueprint_id, results))
42             return utils.build_response(request, results, {}, False)
43         self.logger.info("{} - Package installation logs {}".format(blueprint_id, results))
44         return utils.build_response(request, results, {}, True)
45
46     def executeCommand(self, request, context):
47         blueprint_id = utils.get_blueprint_id(request)
48         self.logger.info("{} - Received executeCommand request".format(blueprint_id))
49         if os.environ.get('CE_DEBUG','false') == "true":
50             self.logger.info(request)
51
52         log_results = []
53         payload_result = {}
54         handler = CommandExecutorHandler(request)
55         payload_result = handler.execute_command(request, log_results)
56         if not payload_result["cds_return_code"]:
57             self.logger.info("{} - Failed to executeCommand. {}".format(blueprint_id, log_results))
58         else:
59             self.logger.info("{} - Execution finished successfully.".format(blueprint_id))
60
61         ret = utils.build_response(request, log_results, payload_result, payload_result["cds_return_code"])
62         self.logger.info("Payload returned %s" % payload_result)
63
64         return ret