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