Fix the wrong image path
[promise.git] / promise / test / functest / run_promise_tests.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 import argparse
11 import json
12 import logging
13 import logging.config
14 import os
15 import re
16 import subprocess
17 import sys
18 import time
19
20 import functest.utils.openstack_utils as os_utils
21 from functest.utils.constants import CONST
22
23 parser = argparse.ArgumentParser()
24
25 parser.add_argument("-d", "--debug", help="Debug mode", action="store_true")
26 parser.add_argument("-r", "--report",
27                     help="Create json result file",
28                     action="store_true")
29 args = parser.parse_args()
30
31
32 PROMISE_REPO_DIR = CONST.dir_repo_promise
33 RESULTS_DIR = CONST.dir_results
34
35 PROMISE_TENANT_NAME = CONST.promise_tenant_name
36 TENANT_DESCRIPTION = CONST.promise_tenant_description
37 PROMISE_USER_NAME = CONST.promise_user_name
38 PROMISE_USER_PWD = CONST.promise_user_pwd
39 PROMISE_IMAGE_NAME = CONST.promise_image_name
40 PROMISE_FLAVOR_NAME = CONST.promise_flavor_name
41 PROMISE_FLAVOR_VCPUS = CONST.promise_flavor_vcpus
42 PROMISE_FLAVOR_RAM = CONST.promise_flavor_ram
43 PROMISE_FLAVOR_DISK = CONST.promise_flavor_disk
44
45
46 GLANCE_IMAGE_FILENAME = CONST.openstack_image_file_name
47 GLANCE_IMAGE_FORMAT = CONST.openstack_image_disk_format
48 GLANCE_IMAGE_NAME = CONST.openstack_image_file_name
49 GLANCE_IMAGE_PATH = os.path.join(CONST.dir_functest_images,
50                                  GLANCE_IMAGE_FILENAME)
51
52 PROMISE_NET_NAME = CONST.promise_network_name
53 PROMISE_SUBNET_NAME = CONST.promise_subnet_name
54 PROMISE_SUBNET_CIDR = CONST.promise_subnet_cidr
55 PROMISE_ROUTER_NAME = CONST.promise_router_name
56
57
58 """ logging configuration """
59 logger = logging.getLogger('promise')
60
61
62 def main():
63     return_code = -1
64     change_keystone_version = False
65     os_auth = os.environ["OS_AUTH_URL"]
66
67     # check keystone version
68     # if keystone v3, for keystone v2
69     if os_utils.is_keystone_v3():
70         os.environ["OS_IDENTITY_API_VERSION"] = "2"
71         # the OS_AUTH_URL may have different format according to the installer
72         # apex: OS_AUTH_URL=http://192.168.37.17:5000/v2.0
73         # fuel: OS_AUTH_URL='http://192.168.0.2:5000/'
74         #       OS_AUTH_URL='http://192.168.10.2:5000/v3
75         match = re.findall(r'[0-9]+(?:\.[0-9]+){3}:[0-9]+',
76                            os.environ["OS_AUTH_URL"])
77         new_url = "http://" + match[0] + "/v2.0"
78
79         os.environ["OS_AUTH_URL"] = new_url
80         change_keystone_version = True
81         logger.info("Force Keystone v2")
82
83     creds = os_utils.get_credentials()
84
85     try:
86         logger.info("Env variables")
87         logger.info("OS_AUTH_URL: %s" % os.environ["OS_AUTH_URL"])
88         logger.info("OS_IDENTITY_API_VERSION: %s " %
89                     os.environ["OS_IDENTITY_API_VERSION"])
90     except KeyError:
91         logger.error("Please set the OS environment variables")
92
93     keystone_client = os_utils.get_keystone_client()
94
95     user_id = os_utils.get_user_id(keystone_client, creds['username'])
96     if user_id == '':
97         logger.error("Error : Failed to get id of %s user" %
98                      creds['username'])
99         return return_code
100
101     logger.info("Creating tenant '%s'..." % PROMISE_TENANT_NAME)
102     tenant_id = os_utils.create_tenant(
103         keystone_client, PROMISE_TENANT_NAME, TENANT_DESCRIPTION)
104     if not tenant_id:
105         logger.error("Error : Failed to create %s tenant"
106                      % PROMISE_TENANT_NAME)
107         return return_code
108     logger.debug("Tenant '%s' created successfully." % PROMISE_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 = os_utils.get_role_id(keystone_client, role_name)
115
116     if role_id == '':
117         logger.error("Error : Failed to get id for %s role" % role_name)
118         return return_code
119
120     logger.info("Adding role '%s' to tenant '%s'..."
121                 % (role_id, PROMISE_TENANT_NAME))
122     if not os_utils.add_role_user(keystone_client, user_id,
123                                   role_id, tenant_id):
124         logger.error("Error : Failed to add %s on tenant %s" %
125                      (creds['username'], PROMISE_TENANT_NAME))
126         return return_code
127     logger.debug("Role added successfully.")
128
129     logger.info("Creating user '%s'..." % PROMISE_USER_NAME)
130     user_id = os_utils.create_user(
131         keystone_client, PROMISE_USER_NAME, PROMISE_USER_PWD, None, tenant_id)
132
133     if not user_id:
134         logger.error("Error : Failed to create %s user" % PROMISE_USER_NAME)
135         return return_code
136     logger.debug("User '%s' created successfully." % PROMISE_USER_NAME)
137
138     nova_client = os_utils.get_nova_client()
139     glance_client = os_utils.get_glance_client()
140
141     logger.info("Creating image '%s' from '%s'..." % (PROMISE_IMAGE_NAME,
142                                                       GLANCE_IMAGE_PATH))
143
144     logger.info("Upload some OS images if it doesn't exist")
145
146     image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
147
148     if image_id == '':
149         logger.info("%s image doesn't exist on glance repo" % GLANCE_IMAGE_NAME)
150         logger.info("Try downloading this image and upload on glance !")
151         image_id = os_utils.create_glance_image(
152             glance_client, GLANCE_IMAGE_NAME, GLANCE_IMAGE_PATH)
153
154     if image_id == '':
155         logger.error("Failed to create the Glance image...")
156         return return_code
157
158     logger.debug("Image '%s' with ID '%s' created successfully."
159                  % (PROMISE_IMAGE_NAME, image_id))
160     flavor_id = os_utils.get_flavor_id(nova_client, PROMISE_FLAVOR_NAME)
161     if flavor_id == '':
162         logger.info("Creating flavor '%s'..." % PROMISE_FLAVOR_NAME)
163         flavor_id = os_utils.create_flavor(nova_client,
164                                            PROMISE_FLAVOR_NAME,
165                                            PROMISE_FLAVOR_RAM,
166                                            PROMISE_FLAVOR_DISK,
167                                            PROMISE_FLAVOR_VCPUS)
168         if not flavor_id:
169             logger.error("Failed to create the Flavor...")
170             return return_code
171         logger.debug("Flavor '%s' with ID '%s' created successfully." %
172                      (PROMISE_FLAVOR_NAME, flavor_id))
173     else:
174         logger.debug("Using existing flavor '%s' with ID '%s'..."
175                      % (PROMISE_FLAVOR_NAME, flavor_id))
176
177     network_dic = os_utils.create_shared_network_full(PROMISE_NET_NAME,
178                                                       PROMISE_SUBNET_NAME,
179                                                       PROMISE_ROUTER_NAME,
180                                                       PROMISE_SUBNET_CIDR)
181     if not network_dic:
182         logger.error("Failed to create the private network...")
183         return return_code
184
185     logger.info("Exporting environment variables...")
186     os.environ["NODE_ENV"] = "functest"
187     os.environ["OS_PASSWORD"] = PROMISE_USER_PWD
188     os.environ["OS_TEST_IMAGE"] = image_id
189     os.environ["OS_TEST_FLAVOR"] = flavor_id
190     os.environ["OS_TEST_NETWORK"] = network_dic["net_id"]
191     os.environ["OS_TENANT_NAME"] = PROMISE_TENANT_NAME
192     os.environ["OS_USERNAME"] = PROMISE_USER_NAME
193
194     os.chdir(PROMISE_REPO_DIR + '/source/')
195     results_file_name = os.path.join(RESULTS_DIR, 'promise-results.json')
196     results_file = open(results_file_name, 'w+')
197     cmd = 'npm run -s test -- --reporter json'
198
199     logger.info("Running command: %s" % cmd)
200     ret = subprocess.call(cmd, shell=True, stdout=results_file,
201                           stderr=subprocess.STDOUT)
202     results_file.close()
203
204     if ret == 0:
205         logger.info("The test succeeded.")
206         return_code = 0
207     else:
208         logger.info("The command '%s' failed." % cmd)
209
210     # Print output of file
211     with open(results_file_name, 'r') as results_file:
212         data = results_file.read()
213         logger.debug("\n%s" % data)
214         json_data = json.loads(data)
215
216         suites = json_data["stats"]["suites"]
217         tests = json_data["stats"]["tests"]
218         passes = json_data["stats"]["passes"]
219         pending = json_data["stats"]["pending"]
220         failures = json_data["stats"]["failures"]
221         start_time_json = json_data["stats"]["start"]
222         end_time = json_data["stats"]["end"]
223         duration = float(json_data["stats"]["duration"]) / float(1000)
224
225     logger.info("\n"
226                 "****************************************\n"
227                 "          Promise test report\n\n"
228                 "****************************************\n"
229                 " Suites:  \t%s\n"
230                 " Tests:   \t%s\n"
231                 " Passes:  \t%s\n"
232                 " Pending: \t%s\n"
233                 " Failures:\t%s\n"
234                 " Start:   \t%s\n"
235                 " End:     \t%s\n"
236                 " Duration:\t%s\n"
237                 "****************************************\n\n"
238                 % (suites, tests, passes, pending, failures,
239                    start_time_json, end_time, duration))
240     end_time = time.time()
241
242     # re set default keysone version to 3 if it has been changed for promise
243     if change_keystone_version:
244         os.environ["OS_IDENTITY_API_VERSION"] = "3"
245         os.environ["OS_AUTH_URL"] = os_auth
246         logger.info("Revert to Keystone v3")
247
248     return return_code
249
250
251 if __name__ == '__main__':
252     logging.config.fileConfig(
253         CONST.__getattribute__('dir_functest_logging_cfg'))
254     sys.exit(main())