Improve Remote Python Executor error handling and allow for structured response
[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         try:
85             with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
86                                   shell=True, bufsize=1, universal_newlines=True) as newProcess:
87                 while True:
88                     output = newProcess.stdout.readline()
89                     if output == '' and newProcess.poll() is not None:
90                         break
91                     if output.startswith('BEGIN_EXTRA_PAYLOAD'):
92                         is_payload_section = True
93                         output = newProcess.stdout.readline()
94                     if output.startswith('END_EXTRA_PAYLOAD'):
95                         is_payload_section = False
96                         output = ''
97                         payload = '\n'.join(payload_section)
98                         msg = email.parser.Parser().parsestr(payload)
99                         for part in msg.get_payload():
100                             payload_result = json.loads(part.get_payload())
101                     if output and not is_payload_section:
102                         self.logger.info(output.strip())
103                         results.append(output.strip())
104                     else:
105                         payload_section.append(output.strip())
106                 rc = newProcess.poll()
107         except Exception as e:
108             self.logger.info("{} - Failed to execute command. Error: {}".format(self.blueprint_id, e))
109             results.append(e)
110             payload_result["cds_return_code"] = False
111             return payload_result
112
113         # deactivate_venv(blueprint_id)
114
115         payload_result["cds_return_code"] = rc
116         return payload_result
117
118     def install_packages(self, request, type, f, results):
119         success = self.install_python_packages('UTILITY', results)
120
121         for package in request.packages:
122             if package.type == type:
123                 f.write("Installed %s packages:\r\n" % CommandExecutor_pb2.PackageType.Name(type))
124                 for p in package.package:
125                     f.write("   %s\r\n" % p)
126                     if package.type == CommandExecutor_pb2.pip:
127                         success = self.install_python_packages(p, results)
128                     else:
129                         success = self.install_ansible_packages(p, results)
130                     if not success:
131                         f.close()
132                         os.remove(self.installed)
133                         return False
134         return True
135
136     def install_python_packages(self, package, results):
137         self.logger.info(
138             "{} - Install Python package({}) in Python Virtual Environment".format(self.blueprint_id, package))
139
140         if REQUIREMENTS_TXT == package:
141             command = ["pip", "install", "-r", self.venv_home + "/Environments/" + REQUIREMENTS_TXT]
142         elif package == 'UTILITY':
143             command = ["cp", "-r", "./cds_utils", self.venv_home + "/lib/python3.6/site-packages/"]
144         else:
145             command = ["pip", "install", package]
146
147         env = dict(os.environ)
148         if "https_proxy" in os.environ:
149             env['https_proxy'] = os.environ['https_proxy']
150
151         try:
152             results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
153             results.append("\n")
154             return True
155         except CalledProcessError as e:
156             results.append(e.stderr.decode())
157             return False
158
159     def install_ansible_packages(self, package, results):
160         self.logger.info(
161             "{} - Install Ansible Role package({}) in Python Virtual Environment".format(self.blueprint_id, package))
162         command = ["ansible-galaxy", "install", package, "-p", self.venv_home + "/Scripts/ansible/roles"]
163
164         env = dict(os.environ)
165         if "http_proxy" in os.environ:
166             # ansible galaxy uses https_proxy environment variable, but requires it to be set with http proxy value.
167             env['https_proxy'] = os.environ['http_proxy']
168
169         try:
170             results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
171             results.append("\n")
172             return True
173         except CalledProcessError as e:
174             results.append(e.stderr.decode())
175             return False
176
177     def create_venv(self):
178         self.logger.info("{} - Create Python Virtual Environment".format(self.blueprint_id))
179         try:
180             bin_dir = self.venv_home + "/bin"
181             # venv doesn't populate the activate_this.py script, hence we use from virtualenv
182             venv.create(self.venv_home, with_pip=True, system_site_packages=True)
183             virtualenv.writefile(os.path.join(bin_dir, "activate_this.py"), virtualenv.ACTIVATE_THIS)
184         except Exception as err:
185             self.logger.info(
186                 "{} - Failed to provision Python Virtual Environment. Error: {}".format(self.blueprint_id, err))
187
188     def activate_venv(self):
189         self.logger.info("{} - Activate Python Virtual Environment".format(self.blueprint_id))
190
191         # Fix: The python generated activate_this.py script concatenates the env bin dir to PATH on every call
192         #      eventually this process PATH variable was so big (128Kb) that no child process could be spawn
193         #      This script will remove all duplicates; while keeping the order of the PATH folders
194         fixpathenvvar = "os.environ['PATH']=os.pathsep.join(list(dict.fromkeys(os.environ['PATH'].split(':'))))"
195
196         path = "%s/bin/activate_this.py" % self.venv_home
197         try:
198             exec (open(path).read(), {'__file__': path})
199             exec (fixpathenvvar)
200             self.logger.info("Running with PATH : {}".format(os.environ['PATH']))
201             return True
202         except Exception as err:
203             self.logger.info(
204                 "{} - Failed to activate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))
205             return False
206
207     def deactivate_venv(self):
208         self.logger.info("{} - Deactivate Python Virtual Environment".format(self.blueprint_id))
209         command = ["deactivate"]
210         try:
211             subprocess.run(command, check=True)
212         except Exception as err:
213             self.logger.info(
214                 "{} - Failed to deactivate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))