summaryrefslogtreecommitdiffstats
path: root/ms/command-executor/src/main/python/command_executor_handler.py
blob: c920dda89392ce61dc8cb25ceb4566f0146715a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#
# Copyright (C) 2019 Bell Canada.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from builtins import Exception, open, dict
from subprocess import CalledProcessError, PIPE
from google.protobuf.json_format import MessageToJson

import logging
import os
import re
import subprocess
import virtualenv
import venv
import utils
import proto.CommandExecutor_pb2 as CommandExecutor_pb2
import email.parser
import json

REQUIREMENTS_TXT = "requirements.txt"


class CommandExecutorHandler():

    def __init__(self, request):
        self.request = request
        self.logger = logging.getLogger(self.__class__.__name__)
        self.blueprint_id = utils.get_blueprint_id(request)
        self.venv_home = '/opt/app/onap/blueprints/deploy/' + self.blueprint_id
        self.installed = self.venv_home + '/.installed'

    def is_installed(self):
        return os.path.exists(self.installed)

    def prepare_env(self, request, results):
        if not self.is_installed():
            self.create_venv()
            if not self.activate_venv():
                return False

            f = open(self.installed, "w+")
            if not self.install_packages(request, CommandExecutor_pb2.pip, f, results):
                return False
            f.write("\r\n")
            results.append("\n")
            if not self.install_packages(request, CommandExecutor_pb2.ansible_galaxy, f, results):
                return False
            f.close()
        else:
            f = open(self.installed, "r")
            results.append(f.read())
            f.close()

        # deactivate_venv(blueprint_id)
        return True

    def execute_command(self, request, results):

        if not self.activate_venv():
            return False

        cmd = "cd " + self.venv_home

        if "ansible-playbook" in request.command:
            cmd = cmd + "; " + request.command + " -e 'ansible_python_interpreter=" + self.venv_home + "/bin/python'"
        else:
            cmd = cmd + "; " + request.command + " " + re.escape(MessageToJson(request.properties))

        payload_result = {}
        payload_section = []
        is_payload_section = False

        try:
            with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                                  shell=True, bufsize=1, universal_newlines=True) as newProcess:
                while True:
                    output = newProcess.stdout.readline()
                    if output == '' and newProcess.poll() is not None:
                        break
                    if output.startswith('BEGIN_EXTRA_PAYLOAD'):
                        is_payload_section = True
                        output = newProcess.stdout.readline()
                    if output.startswith('END_EXTRA_PAYLOAD'):
                        is_payload_section = False
                        output = ''
                        payload = '\n'.join(payload_section)
                        msg = email.parser.Parser().parsestr(payload)
                        for part in msg.get_payload():
                            payload_result = json.loads(part.get_payload())
                    if output and not is_payload_section:
                        self.logger.info(output.strip())
                        results.append(output.strip())
                    else:
                        payload_section.append(output.strip())
                rc = newProcess.poll()
        except Exception as e:
            self.logger.info("{} - Failed to execute command. Error: {}".format(self.blueprint_id, e))
            results.append(e)
            payload_result["cds_return_code"] = False
            return payload_result

        # deactivate_venv(blueprint_id)

        payload_result["cds_return_code"] = rc
        return payload_result

    def install_packages(self, request, type, f, results):
        success = self.install_python_packages('UTILITY', results)

        for package in request.packages:
            if package.type == type:
                f.write("Installed %s packages:\r\n" % CommandExecutor_pb2.PackageType.Name(type))
                for p in package.package:
                    f.write("   %s\r\n" % p)
                    if package.type == CommandExecutor_pb2.pip:
                        success = self.install_python_packages(p, results)
                    else:
                        success = self.install_ansible_packages(p, results)
                    if not success:
                        f.close()
                        os.remove(self.installed)
                        return False
        return True

    def install_python_packages(self, package, results):
        self.logger.info(
            "{} - Install Python package({}) in Python Virtual Environment".format(self.blueprint_id, package))

        if REQUIREMENTS_TXT == package:
            command = ["pip", "install", "-r", self.venv_home + "/Environments/" + REQUIREMENTS_TXT]
        elif package == 'UTILITY':
            command = ["cp", "-r", "./cds_utils", self.venv_home + "/lib/python3.6/site-packages/"]
        else:
            command = ["pip", "install", package]

        env = dict(os.environ)
        if "https_proxy" in os.environ:
            env['https_proxy'] = os.environ['https_proxy']

        try:
            results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
            results.append("\n")
            return True
        except CalledProcessError as e:
            results.append(e.stderr.decode())
            return False

    def install_ansible_packages(self, package, results):
        self.logger.info(
            "{} - Install Ansible Role package({}) in Python Virtual Environment".format(self.blueprint_id, package))
        command = ["ansible-galaxy", "install", package, "-p", self.venv_home + "/Scripts/ansible/roles"]

        env = dict(os.environ)
        if "http_proxy" in os.environ:
            # ansible galaxy uses https_proxy environment variable, but requires it to be set with http proxy value.
            env['https_proxy'] = os.environ['http_proxy']

        try:
            results.append(subprocess.run(command, check=True, stdout=PIPE, stderr=PIPE, env=env).stdout.decode())
            results.append("\n")
            return True
        except CalledProcessError as e:
            results.append(e.stderr.decode())
            return False

    def create_venv(self):
        self.logger.info("{} - Create Python Virtual Environment".format(self.blueprint_id))
        try:
            bin_dir = self.venv_home + "/bin"
            # venv doesn't populate the activate_this.py script, hence we use from virtualenv
            venv.create(self.venv_home, with_pip=True, system_site_packages=True)
            virtualenv.writefile(os.path.join(bin_dir, "activate_this.py"), virtualenv.ACTIVATE_THIS)
        except Exception as err:
            self.logger.info(
                "{} - Failed to provision Python Virtual Environment. Error: {}".format(self.blueprint_id, err))

    def activate_venv(self):
        self.logger.info("{} - Activate Python Virtual Environment".format(self.blueprint_id))

        # Fix: The python generated activate_this.py script concatenates the env bin dir to PATH on every call
        #      eventually this process PATH variable was so big (128Kb) that no child process could be spawn
        #      This script will remove all duplicates; while keeping the order of the PATH folders
        fixpathenvvar = "os.environ['PATH']=os.pathsep.join(list(dict.fromkeys(os.environ['PATH'].split(':'))))"

        path = "%s/bin/activate_this.py" % self.venv_home
        try:
            exec (open(path).read(), {'__file__': path})
            exec (fixpathenvvar)
            self.logger.info("Running with PATH : {}".format(os.environ['PATH']))
            return True
        except Exception as err:
            self.logger.info(
                "{} - Failed to activate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))
            return False

    def deactivate_venv(self):
        self.logger.info("{} - Deactivate Python Virtual Environment".format(self.blueprint_id))
        command = ["deactivate"]
        try:
            subprocess.run(command, check=True)
        except Exception as err:
            self.logger.info(
                "{} - Failed to deactivate Python Virtual Environment. Error: {}".format(self.blueprint_id, err))