Added configuration of ssh_user_regex parameter
[functest.git] / testcases / features / promise.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2015 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Maintainer : jose.lausuch@ericsson.com
11 #
12 import argparse
13 import json
14 import logging
15 import os
16 import requests
17 import subprocess
18 import sys
19 import time
20 import yaml
21
22 import keystoneclient.v2_0.client as ksclient
23 import glanceclient.client as glclient
24 import novaclient.client as nvclient
25 from neutronclient.v2_0 import client as ntclient
26
27 parser = argparse.ArgumentParser()
28
29 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
30 parser.add_argument("-r", "--report",
31                     help="Create json result file",
32                     action="store_true")
33 args = parser.parse_args()
34
35 with open('/home/opnfv/functest/conf/config_functest.yaml') as f:
36     functest_yaml = yaml.safe_load(f)
37
38 dirs = functest_yaml.get('general').get('directories')
39 FUNCTEST_REPO = dirs.get('dir_repo_functest')
40 PROMISE_REPO = dirs.get('dir_repo_promise')
41 TEST_DB = functest_yaml.get('results').get('test_db_url')
42
43 TENANT_NAME = functest_yaml.get('promise').get('general').get('tenant_name')
44 TENANT_DESCRIPTION = functest_yaml.get('promise').get(
45     'general').get('tenant_description')
46 USER_NAME = functest_yaml.get('promise').get('general').get('user_name')
47 USER_PWD = functest_yaml.get('promise').get('general').get('user_pwd')
48 IMAGE_NAME = functest_yaml.get('promise').get('general').get('image_name')
49 FLAVOR_NAME = functest_yaml.get('promise').get('general').get('flavor_name')
50 FLAVOR_VCPUS = functest_yaml.get('promise').get('general').get('flavor_vcpus')
51 FLAVOR_RAM = functest_yaml.get('promise').get('general').get('flavor_ram')
52 FLAVOR_DISK = functest_yaml.get('promise').get('general').get('flavor_disk')
53
54
55 GLANCE_IMAGE_FILENAME = functest_yaml.get('general'). \
56     get('openstack').get('image_file_name')
57 GLANCE_IMAGE_FORMAT = functest_yaml.get('general'). \
58     get('openstack').get('image_disk_format')
59 GLANCE_IMAGE_PATH = functest_yaml.get('general'). \
60     get('directories').get('dir_functest_data') + "/" + GLANCE_IMAGE_FILENAME
61
62 sys.path.append('%s/testcases' % FUNCTEST_REPO)
63 import functest_utils
64
65 """ logging configuration """
66 logger = logging.getLogger('Promise')
67 logger.setLevel(logging.DEBUG)
68
69 ch = logging.StreamHandler()
70
71 if args.debug:
72     ch.setLevel(logging.DEBUG)
73 else:
74     ch.setLevel(logging.INFO)
75
76 formatter = logging.Formatter('%(asctime)s - %(name)s'
77                               '- %(levelname)s - %(message)s')
78
79 ch.setFormatter(formatter)
80 logger.addHandler(ch)
81
82
83
84 def create_image(glance_client, name):
85
86     return image_id
87
88
89 def main():
90     ks_creds = functest_utils.get_credentials("keystone")
91     nv_creds = functest_utils.get_credentials("nova")
92     nt_creds = functest_utils.get_credentials("neutron")
93
94     keystone = ksclient.Client(**ks_creds)
95
96     user_id = functest_utils.get_user_id(keystone, ks_creds['username'])
97     if user_id == '':
98         logger.error("Error : Failed to get id of %s user" %
99                      ks_creds['username'])
100         exit(-1)
101
102     logger.info("Creating tenant '%s'..." % TENANT_NAME)
103     tenant_id = functest_utils.create_tenant(
104         keystone, TENANT_NAME, TENANT_DESCRIPTION)
105     if tenant_id == '':
106         logger.error("Error : Failed to create %s tenant" % TENANT_NAME)
107         exit(-1)
108     logger.debug("Tenant '%s' created successfully." % TENANT_NAME)
109
110     roles_name = ["admin", "Admin"]
111     role_id = ''
112     for role_name in roles_name:
113         if role_id == '':
114             role_id = functest_utils.get_role_id(keystone, role_name)
115
116     if role_id == '':
117         logger.error("Error : Failed to get id for %s role" % role_name)
118         exit(-1)
119
120     logger.info("Adding role '%s' to tenant '%s'..." % (role_id,TENANT_NAME))
121     if not functest_utils.add_role_user(keystone, user_id, role_id, tenant_id):
122         logger.error("Error : Failed to add %s on tenant %s" %
123                      (ks_creds['username'],TENANT_NAME))
124         exit(-1)
125     logger.debug("Role added successfully.")
126
127     logger.info("Creating user '%s'..." % USER_NAME)
128     user_id = functest_utils.create_user(
129         keystone, USER_NAME, USER_PWD, None, tenant_id)
130
131     if user_id == '':
132         logger.error("Error : Failed to create %s user" % USER_NAME)
133         exit(-1)
134     logger.debug("User '%s' created successfully." % USER_NAME)
135
136     logger.info("Updating OpenStack credentials...")
137     ks_creds.update({
138         "username": TENANT_NAME,
139         "password": TENANT_NAME,
140         "tenant_name": TENANT_NAME,
141     })
142
143     nt_creds.update({
144         "tenant_name": TENANT_NAME,
145     })
146
147     nv_creds.update({
148         "project_id": TENANT_NAME,
149     })
150
151     glance_endpoint = keystone.service_catalog.url_for(service_type='image',
152                                                        endpoint_type='publicURL')
153     glance = glclient.Client(1, glance_endpoint, token=keystone.auth_token)
154     nova = nvclient.Client("2", **nv_creds)
155
156
157     logger.info("Creating image '%s' from '%s'..." % (IMAGE_NAME,
158                                                        GLANCE_IMAGE_PATH))
159     image_id = functest_utils.create_glance_image(glance,
160                                                   IMAGE_NAME,
161                                                   GLANCE_IMAGE_PATH)
162     if not image_id:
163         logger.error("Failed to create the Glance image...")
164         exit(-1)
165     logger.debug("Image '%s' with ID '%s' created successfully." % (IMAGE_NAME,
166                                                                     image_id))
167     flavor_id = functest_utils.get_flavor_id(nova, FLAVOR_NAME)
168     if flavor_id == '':
169         logger.info("Creating flavor '%s'..." % FLAVOR_NAME)
170         flavor_id = functest_utils.create_flavor(nova,
171                                                  FLAVOR_NAME,
172                                                  FLAVOR_RAM,
173                                                  FLAVOR_DISK,
174                                                  FLAVOR_VCPUS)
175         if not flavor_id:
176             logger.error("Failed to create the Flavor...")
177             exit(-1)
178         logger.debug("Flavor '%s' with ID '%s' created successfully." %
179                                             (FLAVOR_NAME, flavor_id))
180     else:
181         logger.debug("Using existing flavor '%s' with ID '%s'..." % (FLAVOR_NAME,
182                                                                     flavor_id))
183
184
185     neutron = ntclient.Client(**nt_creds)
186     private_net=functest_utils.get_private_net(neutron)
187     if private_net == None:
188         logger.error("There is no private network in the deployment. Aborting...")
189         exit(-1)
190     logger.debug("Using private network '%s' (%s)." % (private_net['name'],
191                                                        private_net['id']))
192
193     logger.info("Exporting environment variables...")
194     os.environ["NODE_ENV"] = "functest"
195     os.environ["OS_TENANT_NAME"] = TENANT_NAME
196     os.environ["OS_USERNAME"] = USER_NAME
197     os.environ["OS_PASSWORD"] = USER_PWD
198     os.environ["OS_TEST_IMAGE"] = image_id
199     os.environ["OS_TEST_FLAVOR"] = flavor_id
200     os.environ["OS_TEST_NETWORK"] = private_net['id']
201
202
203     os.chdir(PROMISE_REPO)
204     results_file_name='promise-results.json'
205     results_file=open(results_file_name,'w+')
206     cmd = 'npm run -s test -- --reporter json'
207
208     logger.info("Running command: %s" % cmd)
209     ret = subprocess.call(cmd, shell=True, stdout=results_file, \
210                     stderr=subprocess.STDOUT)
211     results_file.close()
212
213     if ret == 0:
214         logger.info("The test succeeded.")
215         test_status = 'OK'
216     else:
217         logger.info("The command '%s' failed." % cmd)
218         test_status = "Failed"
219
220     # Print output of file
221     with open(results_file_name,'r') as results_file:
222         data = results_file.read()
223         logger.debug("\n%s" % data)
224         json_data = json.loads(data)
225
226         suites = json_data["stats"]["suites"]
227         tests = json_data["stats"]["tests"]
228         passes = json_data["stats"]["passes"]
229         pending = json_data["stats"]["pending"]
230         failures = json_data["stats"]["failures"]
231         start_time = json_data["stats"]["start"]
232         end_time = json_data["stats"]["end"]
233         duration = float(json_data["stats"]["duration"])/float(1000)
234
235     logger.info("\n" \
236     "****************************************\n"\
237     "          Promise test report\n\n"\
238     "****************************************\n"\
239     " Suites:  \t%s\n"\
240     " Tests:   \t%s\n"\
241     " Passes:  \t%s\n"\
242     " Pending: \t%s\n"\
243     " Failures:\t%s\n"\
244     " Start:   \t%s\n"\
245     " End:     \t%s\n"\
246     " Duration:\t%s\n"\
247     "****************************************\n\n"\
248     % (suites, tests, passes, pending, failures, start_time, end_time, duration))
249
250
251     if args.report:
252         pod_name = functest_utils.get_pod_name(logger)
253         installer = functest_utils.get_installer_type(logger)
254         scenario = functest_utils.get_scenario(logger)
255         git_version = functest_utils.get_git_branch(PROMISE_REPO)
256         url = TEST_DB + "/results"
257
258         json_results = {"timestart": start_time, "duration": duration,
259                         "tests": int(tests), "failures": int(failures)}
260         logger.debug("Results json: "+str(json_results))
261
262         params = {"project_name": "promise", "case_name": "promise",
263                   "pod_name": str(pod_name), 'installer': installer,
264                   "version": scenario, 'details': json_results}
265         headers = {'Content-Type': 'application/json'}
266
267         logger.info("Pushing results to DB...")
268         r = requests.post(url, data=json.dumps(params), headers=headers)
269         logger.debug(r)
270
271
272 if __name__ == '__main__':
273     main()