2 # Copyright (C) 2019 Bell Canada.
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 from builtins import Exception, open, dict
17 from subprocess import CalledProcessError, PIPE
18 from google.protobuf.json_format import MessageToJson
27 import proto.CommandExecutor_pb2 as CommandExecutor_pb2
31 REQUIREMENTS_TXT = "requirements.txt"
34 class CommandExecutorHandler:
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'
43 def is_installed(self):
44 return os.path.exists(self.installed)
46 def prepare_env(self, request, results):
47 if not self.is_installed():
49 if not self.activate_venv():
52 f = open(self.installed, "w+")
53 if not self.install_packages(request, CommandExecutor_pb2.pip, f, results):
57 if not self.install_packages(request, CommandExecutor_pb2.ansible_galaxy, f, results):
61 f = open(self.installed, "r")
62 results.append(f.read())
65 # deactivate_venv(blueprint_id)
68 def execute_command(self, request, results):
70 if not self.activate_venv():
73 cmd = "cd " + self.venv_home
75 if "ansible-playbook" in request.command:
76 cmd = cmd + "; " + request.command + " -e 'ansible_python_interpreter=" + self.venv_home + "/bin/python'"
78 cmd = cmd + "; " + request.command + " " + re.escape(MessageToJson(request.properties))
82 is_payload_section = False
84 ### extract the original header request into sys-env variables
86 request_id = request.requestId
88 subrequest_id = request.correlationId
89 request_id_map = {'CDS_REQUEST_ID':request_id, 'CDS_CORRELATION_ID':subrequest_id}
90 updated_env = { **os.environ, **request_id_map }
93 with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
94 shell=True, bufsize=1, universal_newlines=True, env=updated_env) as newProcess:
96 output = newProcess.stdout.readline()
97 if output == '' and newProcess.poll() is not None:
99 if output.startswith('BEGIN_EXTRA_PAYLOAD'):
100 is_payload_section = True
101 output = newProcess.stdout.readline()
102 if output.startswith('END_EXTRA_PAYLOAD'):
103 is_payload_section = False
105 payload = '\n'.join(payload_section)
106 msg = email.parser.Parser().parsestr(payload)
107 for part in msg.get_payload():
108 payload_result = json.loads(part.get_payload())
109 if output and not is_payload_section:
110 self.logger.info(output.strip())
111 results.append(output.strip())
113 payload_section.append(output.strip())
114 rc = newProcess.poll()
115 except Exception as e:
116 self.logger.info("{} - Failed to execute command. Error: {}".format(self.blueprint_id, e))
118 payload_result["cds_return_code"] = False
119 return payload_result
121 # deactivate_venv(blueprint_id)
123 payload_result["cds_return_code"] = rc
124 return payload_result
126 def install_packages(self, request, type, f, results):
127 success = self.install_python_packages('UTILITY', results)
129 for package in request.packages:
130 if package.type == type:
131 f.write("Installed %s packages:\r\n" % CommandExecutor_pb2.PackageType.Name(type))
132 for p in package.package:
133 f.write(" %s\r\n" % p)
134 if package.type == CommandExecutor_pb2.pip:
135 success = self.install_python_packages(p, results)
137 success = self.install_ansible_packages(p, results)
140 os.remove(self.installed)
144 def install_python_packages(self, package, results):
146 "{} - Install Python package({}) in Python Virtual Environment".format(self.blueprint_id, package))
148 if REQUIREMENTS_TXT == package:
149 command = ["pip", "install", "-r", self.venv_home + "/Environments/" + REQUIREMENTS_TXT]
150 elif package == 'UTILITY':
151 command = ["cp", "-r", "./cds_utils", self.venv_home + "/lib/python3.6/site-packages/"]
153 command = ["pip", "install", package]
155 env = dict(os.environ)
156 if "https_proxy" in os.environ:
157 env['https_proxy'] = os.environ['https_proxy']
160 results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
163 except CalledProcessError as e:
164 results.append(e.stderr.decode())
167 def install_ansible_packages(self, package, results):
169 "{} - Install Ansible Role package({}) in Python Virtual Environment".format(self.blueprint_id, package))
170 command = ["ansible-galaxy", "install", package, "-p", self.venv_home + "/Scripts/ansible/roles"]
172 env = dict(os.environ)
173 if "http_proxy" in os.environ:
174 # ansible galaxy uses https_proxy environment variable, but requires it to be set with http proxy value.
175 env['https_proxy'] = os.environ['http_proxy']
178 results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
181 except CalledProcessError as e:
182 results.append(e.stderr.decode())
185 def create_venv(self):
186 self.logger.info("{} - Create Python Virtual Environment".format(self.blueprint_id))
188 bin_dir = self.venv_home + "/bin"
189 # venv doesn't populate the activate_this.py script, hence we use from virtualenv
190 venv.create(self.venv_home, with_pip=True, system_site_packages=True)
191 virtualenv.writefile(os.path.join(bin_dir, "activate_this.py"), virtualenv.ACTIVATE_THIS)
192 except Exception as err:
194 "{} - Failed to provision Python Virtual Environment. Error: {}".format(self.blueprint_id, err))
196 def activate_venv(self):
197 self.logger.info("{} - Activate Python Virtual Environment".format(self.blueprint_id))
199 # Fix: The python generated activate_this.py script concatenates the env bin dir to PATH on every call
200 # eventually this process PATH variable was so big (128Kb) that no child process could be spawn
201 # This script will remove all duplicates; while keeping the order of the PATH folders
202 fixpathenvvar = "os.environ['PATH']=os.pathsep.join(list(dict.fromkeys(os.environ['PATH'].split(':'))))"
204 path = "%s/bin/activate_this.py" % self.venv_home
206 exec (open(path).read(), {'__file__': path})
208 self.logger.info("Running with PATH : {}".format(os.environ['PATH']))
210 except Exception as err:
212 "{} - Failed to activate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))
215 def deactivate_venv(self):
216 self.logger.info("{} - Deactivate Python Virtual Environment".format(self.blueprint_id))
217 command = ["deactivate"]
219 subprocess.run(command, check=True)
220 except Exception as err:
222 "{} - Failed to deactivate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))