Merge "Creating findOneBluePrintModel (configuration)"
[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             self.create_venv()
49             if not self.activate_venv():
50                 return False
51
52             f = open(self.installed, "w+")
53             if not self.install_packages(request, CommandExecutor_pb2.pip, f, results):
54                 return False
55             f.write("\r\n")
56             results.append("\n")
57             if not self.install_packages(request, CommandExecutor_pb2.ansible_galaxy, f, results):
58                 return False
59             f.close()
60         else:
61             f = open(self.installed, "r")
62             results.append(f.read())
63             f.close()
64
65         # deactivate_venv(blueprint_id)
66         return True
67
68     def execute_command(self, request, results):
69
70         if not self.activate_venv():
71             return False
72
73         cmd = "cd " + self.venv_home
74
75         if "ansible-playbook" in request.command:
76             cmd = cmd + "; " + request.command + " -e 'ansible_python_interpreter=" + self.venv_home + "/bin/python'"
77         else:
78             cmd = cmd + "; " + request.command + " " + re.escape(MessageToJson(request.properties))
79
80         payload_result = {}
81         payload_section = []
82         is_payload_section = False
83
84         ### extract the original header request into sys-env variables
85         ### RequestID
86         request_id = request.requestId
87         ### Sub-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 }
91
92         try:
93             with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
94                                   shell=True, bufsize=1, universal_newlines=True, env=updated_env) as newProcess:
95                 while True:
96                     output = newProcess.stdout.readline()
97                     if output == '' and newProcess.poll() is not None:
98                         break
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
104                         output = ''
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())
112                     else:
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))
117             results.append(e)
118             payload_result["cds_return_code"] = False
119             return payload_result
120
121         # deactivate_venv(blueprint_id)
122
123         payload_result["cds_return_code"] = rc
124         return payload_result
125
126     def install_packages(self, request, type, f, results):
127         success = self.install_python_packages('UTILITY', results)
128
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)
136                     else:
137                         success = self.install_ansible_packages(p, results)
138                     if not success:
139                         f.close()
140                         os.remove(self.installed)
141                         return False
142         return True
143
144     def install_python_packages(self, package, results):
145         self.logger.info(
146             "{} - Install Python package({}) in Python Virtual Environment".format(self.blueprint_id, package))
147
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/"]
152         else:
153             command = ["pip", "install", package]
154
155         env = dict(os.environ)
156         if "https_proxy" in os.environ:
157             env['https_proxy'] = os.environ['https_proxy']
158
159         try:
160             results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
161             results.append("\n")
162             return True
163         except CalledProcessError as e:
164             results.append(e.stderr.decode())
165             return False
166
167     def install_ansible_packages(self, package, results):
168         self.logger.info(
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"]
171
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']
176
177         try:
178             results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
179             results.append("\n")
180             return True
181         except CalledProcessError as e:
182             results.append(e.stderr.decode())
183             return False
184
185     def create_venv(self):
186         self.logger.info("{} - Create Python Virtual Environment".format(self.blueprint_id))
187         try:
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:
193             self.logger.info(
194                 "{} - Failed to provision Python Virtual Environment. Error: {}".format(self.blueprint_id, err))
195
196     def activate_venv(self):
197         self.logger.info("{} - Activate Python Virtual Environment".format(self.blueprint_id))
198
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(':'))))"
203
204         path = "%s/bin/activate_this.py" % self.venv_home
205         try:
206             exec (open(path).read(), {'__file__': path})
207             exec (fixpathenvvar)
208             self.logger.info("Running with PATH : {}".format(os.environ['PATH']))
209             return True
210         except Exception as err:
211             self.logger.info(
212                 "{} - Failed to activate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))
213             return False
214
215     def deactivate_venv(self):
216         self.logger.info("{} - Deactivate Python Virtual Environment".format(self.blueprint_id))
217         command = ["deactivate"]
218         try:
219             subprocess.run(command, check=True)
220         except Exception as err:
221             self.logger.info(
222                 "{} - Failed to deactivate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))