cmd-exec server-side timeout.
[ccsdk/cds.git] / ms / command-executor / src / main / python / command_executor_handler.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 builtins import Exception, open, dict
17 from subprocess import CalledProcessError, PIPE, TimeoutExpired
18 from google.protobuf.json_format import MessageToJson
19 import tempfile
20 import logging
21 import os
22 import re
23 import subprocess
24 import virtualenv
25 import venv
26 import utils
27 import proto.CommandExecutor_pb2 as CommandExecutor_pb2
28
29 REQUIREMENTS_TXT = "requirements.txt"
30
31
32 class CommandExecutorHandler():
33
34     def __init__(self, request):
35         self.request = request
36         self.logger = logging.getLogger(self.__class__.__name__)
37         self.blueprint_id = utils.get_blueprint_id(request)
38         self.execution_timeout = utils.get_blueprint_timeout(request)
39         self.venv_home = '/opt/app/onap/blueprints/deploy/' + self.blueprint_id
40         self.installed = self.venv_home + '/.installed'
41
42     def is_installed(self):
43         return os.path.exists(self.installed)
44
45     def prepare_env(self, request):
46         results_log = []
47         if not self.is_installed():
48             create_venv_status = self.create_venv()
49             if not create_venv_status[utils.CDS_IS_SUCCESSFUL_KEY]:
50                 err_msg = "ERROR: failed to prepare environment for request {} due to error in creating virtual Python env. Original error {}".format(self.blueprint_id, create_venv_status[utils.ERR_MSG_KEY])
51                 self.logger.error(err_msg)
52                 return utils.build_ret_data(False, error=err_msg)
53
54             activate_venv_status = self.activate_venv()
55             if not activate_venv_status[utils.CDS_IS_SUCCESSFUL_KEY]:
56                 err_msg = "ERROR: failed to prepare environment for request {} due Python venv_activation. Original error {}".format(self.blueprint_id, activate_venv_status[utils.ERR_MSG_KEY])
57                 self.logger.error(err_msg)
58                 return utils.build_ret_data(False, error=err_msg)
59             try:
60                 with open(self.installed, "w+") as f:
61                     if not self.install_packages(request, CommandExecutor_pb2.pip, f, results_log):
62                         err_msg = "ERROR: failed to prepare environment for request {} during pip package install.".format(self.blueprint_id)
63                         return utils.build_ret_data(False, results_log=results_log, error=err_msg)
64                     f.write("\r\n") # TODO: is \r needed?
65                     results_log.append("\n")
66                     if not self.install_packages(request, CommandExecutor_pb2.ansible_galaxy, f, results_log):
67                         err_msg = "ERROR: failed to prepare environment for request {} during Ansible install.".format(self.blueprint_id)
68                         return utils.build_ret_data(False, results_log=results_log, error=err_msg)
69             except Exception as ex:
70                 err_msg = "ERROR: failed to prepare environment for request {} during installing packages. Exception: {}".format(self.blueprint_id, ex)
71                 self.logger.error(err_msg)
72                 return utils.build_ret_data(False, error=err_msg)
73         else:
74             try:
75                 with open(self.installed, "r") as f:
76                     results_log.append(f.read())
77             except Exception as ex:
78                 err_msg="ERROR: failed to prepare environment during reading 'installed' file {}. Exception: {}".format(self.installed, ex)
79                 return utils.build_ret_data(False, error=err_msg)
80
81         # deactivate_venv(blueprint_id)
82         return utils.build_ret_data(True, results_log=results_log)
83
84     def execute_command(self, request):
85         # STDOUT/STDERR output of the process
86         results_log = []
87         # encoded payload returned by the process
88         result = {}
89         # workaround for when packages are not specified, we may not want to go through the install step
90         # can just call create_venv from here.
91         if not self.is_installed():
92             self.create_venv()
93         try:
94             if not self.is_installed():
95                 create_venv_status = self.create_venv
96                 if not create_venv_status[utils.CDS_IS_SUCCESSFUL_KEY]:
97                     err_msg = "{} - Failed to execute command during venv creation. Original error: {}".format(self.blueprint_id, create_venv_status[utils.ERR_MSG_KEY])
98                     return utils.build_ret_data(False, error=err_msg)
99             activate_response = self.activate_venv()
100             if not activate_response[utils.CDS_IS_SUCCESSFUL_KEY]:
101                 orig_error = activate_response[utils.ERR_MSG_KEY]
102                 err_msg = "{} - Failed to execute command during environment activation. Original error: {}".format(self.blueprint_id, orig_error)
103                 return utils.build_ret_data(False, error=err_msg)
104
105             cmd = "cd " + self.venv_home
106
107             ### TODO: replace with os.environ['VIRTUAL_ENV']?
108             if "ansible-playbook" in request.command:
109                 cmd = cmd + "; " + request.command + " -e 'ansible_python_interpreter=" + self.venv_home + "/bin/python'"
110             else:
111                 cmd = cmd + "; " + request.command + " " + re.escape(MessageToJson(request.properties))
112
113             ### extract the original header request into sys-env variables
114             ### RequestID
115             request_id = request.requestId
116             ### Sub-requestID
117             subrequest_id = request.correlationId
118             request_id_map = {'CDS_REQUEST_ID':request_id, 'CDS_CORRELATION_ID':subrequest_id}
119             updated_env =  { **os.environ, **request_id_map }
120             self.logger.info("Running blueprint {} with timeout: {}".format(self.blueprint_id, self.execution_timeout))
121
122             with tempfile.TemporaryFile(mode="w+") as tmp:
123                 try:
124                     completed_subprocess = subprocess.run(cmd, stdout=tmp, stderr=subprocess.STDOUT, shell=True,
125                                                 env=updated_env, timeout=self.execution_timeout)
126                 except TimeoutExpired:
127                     timeout_err_msg = "Running command {} failed due to timeout of {} seconds.".format(self.blueprint_id, self.execution_timeout)
128                     self.logger.error(timeout_err_msg)
129                     utils.parse_cmd_exec_output(tmp, self.logger, result, results_log)
130                     return utils.build_ret_data(False, results_log=results_log, error=timeout_err_msg)
131
132                 utils.parse_cmd_exec_output(tmp, self.logger, result, results_log)
133                 rc = completed_subprocess.returncode
134         except Exception as e:
135             err_msg = "{} - Failed to execute command. Error: {}".format(self.blueprint_id, e)
136             result.update(utils.build_ret_data(False, results_log=results_log, error=err_msg))
137             return result
138
139         # deactivate_venv(blueprint_id)
140         #Since return code is only used to check if it's zero (success), we can just return success flag instead.
141         self.logger.debug("python return_code : {}".format(rc))
142         is_execution_successful = rc == 0
143         result.update(utils.build_ret_data(is_execution_successful, results_log=results_log))
144         return result
145
146     def install_packages(self, request, type, f, results):
147         success = self.install_python_packages('UTILITY', results)
148
149         for package in request.packages:
150             if package.type == type:
151                 f.write("Installed %s packages:\r\n" % CommandExecutor_pb2.PackageType.Name(type))
152                 for p in package.package:
153                     f.write("   %s\r\n" % p)
154                     if package.type == CommandExecutor_pb2.pip:
155                         success = self.install_python_packages(p, results)
156                     else:
157                         success = self.install_ansible_packages(p, results)
158                     if not success:
159                         f.close()
160                         os.remove(self.installed)
161                         return False
162         return True
163
164     def install_python_packages(self, package, results):
165         self.logger.info(
166             "{} - Install Python package({}) in Python Virtual Environment".format(self.blueprint_id, package))
167
168         if REQUIREMENTS_TXT == package:
169             command = ["pip", "install", "-r", self.venv_home + "/Environments/" + REQUIREMENTS_TXT]
170         elif package == 'UTILITY':
171             # TODO: fix python version that is hardcoded here, may fail if python image is upgraded
172             command = ["cp", "-r", "./cds_utils", self.venv_home + "/lib/python3.6/site-packages/"]
173         else:
174             command = ["pip", "install", package]
175
176         env = dict(os.environ)
177         if "https_proxy" in os.environ:
178             env['https_proxy'] = os.environ['https_proxy']
179             self.logger.info("Using https_proxy: ", env['https_proxy'])
180
181         try:
182             results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
183             results.append("\n")
184             self.logger.info("install_python_packages {} succeeded".format(package))
185             return True
186         except CalledProcessError as e:
187             results.append(e.stderr.decode())
188             self.logger.error("install_python_packages {} failed".format(package))
189             return False
190
191     def install_ansible_packages(self, package, results):
192         self.logger.info(
193             "{} - Install Ansible Role package({}) in Python Virtual Environment".format(self.blueprint_id, package))
194         command = ["ansible-galaxy", "install", package, "-p", self.venv_home + "/Scripts/ansible/roles"]
195
196         env = dict(os.environ)
197         if "http_proxy" in os.environ:
198             # ansible galaxy uses https_proxy environment variable, but requires it to be set with http proxy value.
199             env['https_proxy'] = os.environ['http_proxy']
200
201         try:
202             results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
203             results.append("\n")
204             return True
205         except CalledProcessError as e:
206             results.append(e.stderr.decode())
207             return False
208
209     # Returns a map with 'status' and 'err_msg'.
210     # 'status' True indicates success.
211     # 'err_msg' indicates an error occurred. The presence of err_msg may not be fatal,
212     # status should be set to False for fatal errors.
213     def create_venv(self):
214         self.logger.info("{} - Create Python Virtual Environment".format(self.blueprint_id))
215         try:
216             bin_dir = self.venv_home + "/bin"
217             # venv doesn't populate the activate_this.py script, hence we use from virtualenv
218             venv.create(self.venv_home, with_pip=True, system_site_packages=True)
219             virtualenv.writefile(os.path.join(bin_dir, "activate_this.py"), virtualenv.ACTIVATE_THIS)
220             self.logger.info("{} - Creation of Python Virtual Environment finished.".format(self.blueprint_id))
221             return utils.build_ret_data(True)
222         except Exception as err:
223             err_msg = "{} - Failed to provision Python Virtual Environment. Error: {}".format(self.blueprint_id, err)
224             self.logger.info(err_msg)
225             return utils.build_ret_data(False, error=err_msg)
226
227     # return map cds_is_successful and err_msg. Status is True on success. err_msg may existence doesn't necessarily indicate fatal condition.
228     # the 'status' should be set to False to indicate error.
229     def activate_venv(self):
230         self.logger.info("{} - Activate Python Virtual Environment".format(self.blueprint_id))
231
232         # Fix: The python generated activate_this.py script concatenates the env bin dir to PATH on every call
233         #      eventually this process PATH variable was so big (128Kb) that no child process could be spawn
234         #      This script will remove all duplicates; while keeping the order of the PATH folders
235         fixpathenvvar = "os.environ['PATH']=os.pathsep.join(list(dict.fromkeys(os.environ['PATH'].split(':'))))"
236
237         path = "%s/bin/activate_this.py" % self.venv_home
238         try:
239             with open(path) as activate_this_script:
240                 exec (activate_this_script.read(), {'__file__': path})
241             exec (fixpathenvvar)
242             self.logger.info("Running with PATH : {}".format(os.environ['PATH']))
243             return utils.build_ret_data(True)
244         except Exception as err:
245             err_msg ="{} - Failed to activate Python Virtual Environment. Error: {}".format(self.blueprint_id, err)
246             self.logger.info( err_msg)
247             return utils.build_ret_data(False, error=err_msg)
248
249     def deactivate_venv(self):
250         self.logger.info("{} - Deactivate Python Virtual Environment".format(self.blueprint_id))
251         command = ["deactivate"]
252         try:
253             subprocess.run(command, check=True)
254         except Exception as err:
255             self.logger.info(
256                 "{} - Failed to deactivate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))
257
258