Merge "refactor vping"
[functest.git] / testcases / vnf / vIMS / orchestrator.py
1 #!/usr/bin/python
2 # coding: utf8
3 #######################################################################
4 #
5 #   Copyright (c) 2015 Orange
6 #   valentin.boucher@orange.com
7 #
8 # All rights reserved. This program and the accompanying materials
9 # are made available under the terms of the Apache License, Version 2.0
10 # which accompanies this distribution, and is available at
11 # http://www.apache.org/licenses/LICENSE-2.0
12 ########################################################################
13 import subprocess32 as subprocess
14 import os
15 import shutil
16 import yaml
17 from git import Repo
18
19
20 class orchestrator:
21
22     def __init__(self, testcase_dir, inputs={}, logger=None):
23         self.testcase_dir = testcase_dir
24         self.blueprint_dir = testcase_dir + 'cloudify-manager-blueprint/'
25         self.input_file = 'inputs.yaml'
26         self.manager_blueprint = False
27         self.config = inputs
28         self.logger = logger
29         self.manager_up = False
30
31     def set_credentials(self, username, password, tenant_name, auth_url):
32         self.config['keystone_username'] = username
33         self.config['keystone_password'] = password
34         self.config['keystone_url'] = auth_url
35         self.config['keystone_tenant_name'] = tenant_name
36
37     def set_flavor_id(self, flavor_id):
38         self.config['flavor_id'] = flavor_id
39
40     def set_image_id(self, image_id):
41         self.config['image_id'] = image_id
42
43     def set_external_network_name(self, external_network_name):
44         self.config['external_network_name'] = external_network_name
45
46     def set_ssh_user(self, ssh_user):
47         self.config['ssh_user'] = ssh_user
48
49     def set_nova_url(self, nova_url):
50         self.config['nova_url'] = nova_url
51
52     def set_neutron_url(self, neutron_url):
53         self.config['neutron_url'] = neutron_url
54
55     def set_nameservers(self, nameservers):
56         if 0 < len(nameservers):
57             self.config['dns_subnet_1'] = nameservers[0]
58
59     def set_logger(self, logger):
60         self.logger = logger
61
62     def download_manager_blueprint(self, manager_blueprint_url,
63                                    manager_blueprint_branch):
64         if self.manager_blueprint:
65             if self.logger:
66                 self.logger.info(
67                     "cloudify manager server blueprint is "
68                     "already downloaded !")
69         else:
70             if self.logger:
71                 self.logger.info(
72                     "Downloading the cloudify manager server blueprint")
73             download_result = download_blueprints(
74                 manager_blueprint_url,
75                 manager_blueprint_branch,
76                 self.blueprint_dir)
77
78             if not download_result:
79                 if self.logger:
80                     self.logger.error("Failed to download manager blueprint")
81                 exit(-1)
82             else:
83                 self.manager_blueprint = True
84
85     def manager_up(self):
86         return self.manager_up
87
88     def deploy_manager(self):
89         if self.manager_blueprint:
90             if self.logger:
91                 self.logger.info("Writing the inputs file")
92             with open(self.blueprint_dir + "inputs.yaml", "w") as f:
93                 f.write(yaml.dump(self.config, default_style='"'))
94             f.close()
95
96             # Ensure no ssh key file already exists
97             key_files = ["/.ssh/cloudify-manager-kp.pem",
98                          "/.ssh/cloudify-agent-kp.pem"]
99             home = os.path.expanduser("~")
100
101             for key_file in key_files:
102                 if os.path.isfile(home + key_file):
103                     os.remove(home + key_file)
104
105             if self.logger:
106                 self.logger.info("Launching the cloudify-manager deployment")
107             script = "set -e; "
108             script += ("source " + self.testcase_dir +
109                        "venv_cloudify/bin/activate; ")
110             script += "cd " + self.testcase_dir + "; "
111             script += "cfy init -r; "
112             script += "cd cloudify-manager-blueprint; "
113             script += ("cfy local create-requirements -o requirements.txt " +
114                        "-p openstack-manager-blueprint.yaml; ")
115             script += "pip install -r requirements.txt; "
116             script += ("cfy bootstrap --install-plugins " +
117                        "-p openstack-manager-blueprint.yaml -i inputs.yaml; ")
118             cmd = "/bin/bash -c '" + script + "'"
119             error = execute_command(cmd, self.logger)
120             if error:
121                 return error
122
123             if self.logger:
124                 self.logger.info("Cloudify-manager server is UP !")
125
126             self.manager_up = True
127
128     def undeploy_manager(self):
129         if self.logger:
130             self.logger.info("Launching the cloudify-manager undeployment")
131
132         self.manager_up = False
133
134         script = "source " + self.testcase_dir + "venv_cloudify/bin/activate; "
135         script += "cd " + self.testcase_dir + "; "
136         script += "cfy teardown -f --ignore-deployments; "
137         cmd = "/bin/bash -c '" + script + "'"
138         execute_command(cmd, self.logger)
139
140         if self.logger:
141             self.logger.info(
142                 "Cloudify-manager server has been successfully removed!")
143
144     def download_upload_and_deploy_blueprint(self, blueprint, config,
145                                              bp_name, dep_name):
146         if self.logger:
147             self.logger.info("Downloading the {0} blueprint".format(
148                 blueprint['file_name']))
149         download_result = download_blueprints(blueprint['url'],
150                                               blueprint['branch'],
151                                               self.testcase_dir +
152                                               blueprint['destination_folder'])
153
154         if not download_result:
155             if self.logger:
156                 self.logger.error(
157                     "Failed to download blueprint {0}".
158                     format(blueprint['file_name']))
159             exit(-1)
160
161         if self.logger:
162             self.logger.info("Writing the inputs file")
163
164         with open(self.testcase_dir + blueprint['destination_folder'] +
165                   "/inputs.yaml", "w") as f:
166             f.write(yaml.dump(config, default_style='"'))
167
168         f.close()
169
170         if self.logger:
171             self.logger.info("Launching the {0} deployment".format(bp_name))
172         script = "source " + self.testcase_dir + "venv_cloudify/bin/activate; "
173         script += ("cd " + self.testcase_dir +
174                    blueprint['destination_folder'] + "; ")
175         script += ("cfy blueprints upload -b " +
176                    bp_name + " -p openstack-blueprint.yaml; ")
177         script += ("cfy deployments create -b " + bp_name +
178                    " -d " + dep_name + " --inputs inputs.yaml; ")
179         script += ("cfy executions start -w install -d " +
180                    dep_name + " --timeout 1800; ")
181
182         cmd = "/bin/bash -c '" + script + "'"
183         error = execute_command(cmd, self.logger, 2000)
184         if error:
185             return error
186         if self.logger:
187             self.logger.info("The deployment of {0} is ended".format(dep_name))
188
189     def undeploy_deployment(self, dep_name):
190         if self.logger:
191             self.logger.info("Launching the {0} undeployment".format(dep_name))
192         script = "source " + self.testcase_dir + "venv_cloudify/bin/activate; "
193         script += "cd " + self.testcase_dir + "; "
194         script += ("cfy executions start -w uninstall -d " + dep_name +
195                    " --timeout 1800 ; ")
196         script += "cfy deployments delete -d " + dep_name + "; "
197
198         cmd = "/bin/bash -c '" + script + "'"
199         try:
200             execute_command(cmd, self.logger)
201         except:
202             if self.logger:
203                 self.logger.error("Clearwater undeployment failed")
204
205
206 def execute_command(cmd, logger, timeout=1800):
207     """
208     Execute Linux command
209     """
210     if logger:
211         logger.debug('Executing command : {}'.format(cmd))
212     timeout_exception = False
213     output_file = "output.txt"
214     f = open(output_file, 'w+')
215     try:
216         p = subprocess.call(cmd, shell=True, stdout=f,
217                             stderr=subprocess.STDOUT, timeout=timeout)
218     except subprocess.TimeoutExpired:
219         timeout_exception = True
220         if logger:
221             logger.error("TIMEOUT when executing command %s" % cmd)
222         pass
223
224     f.close()
225     f = open(output_file, 'r')
226     result = f.read()
227     if result != "" and logger:
228         logger.debug(result)
229     if p == 0:
230         return False
231     else:
232         if logger and not timeout_exception:
233             logger.error("Error when executing command %s" % cmd)
234         f = open(output_file, 'r')
235         lines = f.readlines()
236         result = lines[len(lines) - 3]
237         result += lines[len(lines) - 2]
238         result += lines[len(lines) - 1]
239         return result
240
241
242 def download_blueprints(blueprint_url, branch, dest_path):
243     if os.path.exists(dest_path):
244         shutil.rmtree(dest_path)
245     try:
246         Repo.clone_from(blueprint_url, dest_path, branch=branch)
247         return True
248     except:
249         return False