06004b551de08d8591780c666462e78952452212
[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             ### if properties are defined we add them to the command
108             properties = ""
109             if request.properties is not None and len(request.properties) > 0:
110                 properties = " " + re.escape(MessageToJson(request.properties))
111
112             ### TODO: replace with os.environ['VIRTUAL_ENV']?
113             if "ansible-playbook" in request.command:
114                 cmd = cmd + "; " + request.command + " -e 'ansible_python_interpreter=" + self.venv_home + "/bin/python'"
115             else:
116                 cmd = cmd + "; " + request.command + properties
117
118             ### extract the original header request into sys-env variables
119             ### RequestID
120             request_id = request.requestId
121             ### Sub-requestID
122             subrequest_id = request.correlationId
123             request_id_map = {'CDS_REQUEST_ID':request_id, 'CDS_CORRELATION_ID':subrequest_id}
124             updated_env =  { **os.environ, **request_id_map }
125             self.logger.info("Running blueprint {} with timeout: {}".format(self.blueprint_id, self.execution_timeout))
126
127             with tempfile.TemporaryFile(mode="w+") as tmp:
128                 try:
129                     completed_subprocess = subprocess.run(cmd, stdout=tmp, stderr=subprocess.STDOUT, shell=True,
130                                                 env=updated_env, timeout=self.execution_timeout)
131                 except TimeoutExpired:
132                     timeout_err_msg = "Running command {} failed due to timeout of {} seconds.".format(self.blueprint_id, self.execution_timeout)
133                     self.logger.error(timeout_err_msg)
134                     utils.parse_cmd_exec_output(tmp, self.logger, result, results_log)
135                     return utils.build_ret_data(False, results_log=results_log, error=timeout_err_msg)
136
137                 utils.parse_cmd_exec_output(tmp, self.logger, result, results_log)
138                 rc = completed_subprocess.returncode
139         except Exception as e:
140             err_msg = "{} - Failed to execute command. Error: {}".format(self.blueprint_id, e)
141             result.update(utils.build_ret_data(False, results_log=results_log, error=err_msg))
142             return result
143
144         # deactivate_venv(blueprint_id)
145         #Since return code is only used to check if it's zero (success), we can just return success flag instead.
146         self.logger.debug("python return_code : {}".format(rc))
147         is_execution_successful = rc == 0
148         result.update(utils.build_ret_data(is_execution_successful, results_log=results_log))
149         return result
150
151     def install_packages(self, request, type, f, results):
152         success = self.install_python_packages('UTILITY', results)
153
154         for package in request.packages:
155             if package.type == type:
156                 f.write("Installed %s packages:\r\n" % CommandExecutor_pb2.PackageType.Name(type))
157                 for p in package.package:
158                     f.write("   %s\r\n" % p)
159                     if package.type == CommandExecutor_pb2.pip:
160                         success = self.install_python_packages(p, results)
161                     else:
162                         success = self.install_ansible_packages(p, results)
163                     if not success:
164                         f.close()
165                         os.remove(self.installed)
166                         return False
167         return True
168
169     def install_python_packages(self, package, results):
170         self.logger.info(
171             "{} - Install Python package({}) in Python Virtual Environment".format(self.blueprint_id, package))
172
173         if REQUIREMENTS_TXT == package:
174             command = ["pip", "install", "-r", self.venv_home + "/Environments/" + REQUIREMENTS_TXT]
175         elif package == 'UTILITY':
176             # TODO: fix python version that is hardcoded here, may fail if python image is upgraded
177             command = ["cp", "-r", "./cds_utils", self.venv_home + "/lib/python3.6/site-packages/"]
178         else:
179             command = ["pip", "install", package]
180
181         env = dict(os.environ)
182         if "https_proxy" in os.environ:
183             env['https_proxy'] = os.environ['https_proxy']
184             self.logger.info("Using https_proxy: ", env['https_proxy'])
185
186         try:
187             results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
188             results.append("\n")
189             self.logger.info("install_python_packages {} succeeded".format(package))
190             return True
191         except CalledProcessError as e:
192             results.append(e.stderr.decode())
193             self.logger.error("install_python_packages {} failed".format(package))
194             return False
195
196     def install_ansible_packages(self, package, results):
197         self.logger.info(
198             "{} - Install Ansible Role package({}) in Python Virtual Environment".format(self.blueprint_id, package))
199         command = ["ansible-galaxy", "install", package, "-p", self.venv_home + "/Scripts/ansible/roles"]
200
201         env = dict(os.environ)
202         if "http_proxy" in os.environ:
203             # ansible galaxy uses https_proxy environment variable, but requires it to be set with http proxy value.
204             env['https_proxy'] = os.environ['http_proxy']
205
206         try:
207             results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
208             results.append("\n")
209             return True
210         except CalledProcessError as e:
211             results.append(e.stderr.decode())
212             return False
213
214     # Returns a map with 'status' and 'err_msg'.
215     # 'status' True indicates success.
216     # 'err_msg' indicates an error occurred. The presence of err_msg may not be fatal,
217     # status should be set to False for fatal errors.
218     def create_venv(self):
219         self.logger.info("{} - Create Python Virtual Environment".format(self.blueprint_id))
220         try:
221             bin_dir = self.venv_home + "/bin"
222             # venv doesn't populate the activate_this.py script, hence we use from virtualenv
223             venv.create(self.venv_home, with_pip=True, system_site_packages=True)
224             virtualenv.writefile(os.path.join(bin_dir, "activate_this.py"), virtualenv.ACTIVATE_THIS)
225             self.logger.info("{} - Creation of Python Virtual Environment finished.".format(self.blueprint_id))
226             return utils.build_ret_data(True)
227         except Exception as err:
228             err_msg = "{} - Failed to provision Python Virtual Environment. Error: {}".format(self.blueprint_id, err)
229             self.logger.info(err_msg)
230             return utils.build_ret_data(False, error=err_msg)
231
232     # return map cds_is_successful and err_msg. Status is True on success. err_msg may existence doesn't necessarily indicate fatal condition.
233     # the 'status' should be set to False to indicate error.
234     def activate_venv(self):
235         self.logger.info("{} - Activate Python Virtual Environment".format(self.blueprint_id))
236
237         # Fix: The python generated activate_this.py script concatenates the env bin dir to PATH on every call
238         #      eventually this process PATH variable was so big (128Kb) that no child process could be spawn
239         #      This script will remove all duplicates; while keeping the order of the PATH folders
240         fixpathenvvar = "os.environ['PATH']=os.pathsep.join(list(dict.fromkeys(os.environ['PATH'].split(':'))))"
241
242         path = "%s/bin/activate_this.py" % self.venv_home
243         try:
244             with open(path) as activate_this_script:
245                 exec (activate_this_script.read(), {'__file__': path})
246             exec (fixpathenvvar)
247             self.logger.info("Running with PATH : {}".format(os.environ['PATH']))
248             return utils.build_ret_data(True)
249         except Exception as err:
250             err_msg ="{} - Failed to activate Python Virtual Environment. Error: {}".format(self.blueprint_id, err)
251             self.logger.info( err_msg)
252             return utils.build_ret_data(False, error=err_msg)
253
254     def deactivate_venv(self):
255         self.logger.info("{} - Deactivate Python Virtual Environment".format(self.blueprint_id))
256         command = ["deactivate"]
257         try:
258             subprocess.run(command, check=True)
259         except Exception as err:
260             self.logger.info(
261                 "{} - Failed to deactivate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))
262
263