2 ##############################################################################
3 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
17 from heatclient.client import Client as HeatClient
18 from keystoneclient.v2_0.client import Client as KeystoneClient
19 from glanceclient.v2.client import Client as GlanceClient
20 from novaclient.client import Client as NovaClient
22 #------------------------------------------------------
23 # parser for configuration files in each test case
24 # ------------------------------------------------------
25 parser = argparse.ArgumentParser()
26 parser.add_argument("-c", "--conf",
27 help="configuration files for the testcase, in yaml format",
28 default="/home/opnfv/bottlenecks/testsuites/vstf/testcase_cfg/vstf_Tu1.yaml")
29 args = parser.parse_args()
31 #--------------------------------------------------
32 # logging configuration
33 #--------------------------------------------------
34 logger = logging.getLogger(__name__)
37 def _get_keystone_client():
38 keystone_client = KeystoneClient(
39 auth_url=os.environ.get('OS_AUTH_URL'),
40 username=os.environ.get('OS_USERNAME'),
41 password=os.environ.get('OS_PASSWORD'),
42 tenant_name=os.environ.get('OS_TENANT_NAME'),
43 cacert=os.environ.get('OS_CACERT'))
44 return keystone_client
46 def _get_heat_client():
47 keystone = _get_keystone_client()
48 heat_endpoint = keystone.service_catalog.url_for(service_type='orchestration')
49 heat_client = HeatClient('1', endpoint=heat_endpoint, token=keystone.auth_token)
52 def _get_glance_client():
53 keystone = _get_keystone_client()
54 glance_endpoint = keystone.service_catalog.url_for(service_type='image', endpoint_type='publicURL')
55 return GlanceClient(glance_endpoint, token=keystone.auth_token)
57 def _get_nova_client():
58 nova_client = NovaClient("2", os.environ.get('OS_USERNAME'),
59 os.environ.get('OS_PASSWORD'),
60 os.environ.get('OS_TENANT_NAME'),
61 os.environ.get('OS_AUTH_URL'))
64 def _download_url(src_url, dest_dir):
65 ''' Download a file to a destination path given a URL'''
66 file_name = src_url.rsplit('/')[-1]
67 dest = dest_dir + "/" + file_name
69 response = urllib2.urlopen(src_url)
70 except (urllib2.HTTPError, urllib2.URLError):
73 with open(dest, 'wb') as f:
74 shutil.copyfileobj(response, f)
77 def vstf_stack_satisfy(name="bottlenecks_vstf_stack", status="CREATE_COMPLETE"):
78 heat = _get_heat_client()
79 for stack in heat.stacks.list():
80 if status == None and stack.stack_name == name:
82 print "Found stack, name=" + str(stack.stack_name)
84 elif stack.stack_name == name and stack.stack_status==status:
85 print "Found stack, name=" + str(stack.stack_name) + ", status=" + str(stack.stack_status)
89 def vstf_env_prepare(template=None):
90 print "========== Prepare vstf environment =========="
91 logger.info("env preparation for testcase.")
93 def vstf_env_cleanup():
94 print "========== Cleanup vstf environment =========="
95 glance = _get_glance_client()
96 heat = _get_heat_client()
97 nova = _get_nova_client()
99 for image in glance.images.list():
100 if image.name.find("bottlenecks_vstf") >= 0:
101 print "Delete image, id:" + str(image.id) + ", name:" + str(image.name)
102 glance.images.delete(image.id)
104 for keypair in nova.keypairs.list():
105 if keypair.name.find("bottlenecks_vstf") >= 0:
106 print "Delete keypair, id:" + str(keypair.id) + ", name:" + str(keypair.name)
107 nova.keypairs.delete(keypair.id)
109 for flavor in nova.flavors.list():
110 if flavor.name.find("bottlenecks_vstf") >= 0:
111 print "Delete flavor, id:" + str(flavor.id) + ", name:" + str(flavor.name)
112 nova.flavors.delete(flavor.id)
114 for stack in heat.stacks.list():
115 if stack.stack_name.find("bottlenecks_vstf") >= 0:
116 print "Delete stack, id: " + str(stack.id) + ", name:" + str(stack.stack_name)
117 heat.stacks.delete(stack.id)
120 while vstf_stack_satisfy(name="bottlenecks_vstf_stack", status=None) and timeInProgress < 60:
122 timeInProgress = timeInProgress + 5
124 if vstf_stack_satisfy(name="bottlenecks_vstf_stack", status=None) == True:
125 print "Failed to clean the stack"
130 def vstf_create_images(imagefile=None, image_name="bottlenecks_vstf_image"):
131 print "========== Create vstf image in OS =========="
133 if imagefile == None:
134 print "imagefile not set/found"
137 glance = _get_glance_client()
138 image = glance.images.create(name=image_name, disk_format="qcow2", container_format="bare")
139 with open(imagefile) as fimage:
140 glance.images.upload(image.id, fimage)
143 img_status = image.status
144 while img_status == "queued" and timeInQueue < 30:
145 print " image's status: " + img_status
147 timeInQueue = timeInQueue + 1
148 img_status = glance.images.get(image.id).status
150 print "After %d seconds, the image's status is [%s]" %(timeInQueue, img_status)
151 return True if img_status == "active" else False
153 def vstf_create_keypairs(key_path, name="bottlenecks_vstf_keypair"):
154 print "========== Add vstf keypairs in OS =========="
155 nova = _get_nova_client()
156 with open(key_path) as pkey:
157 nova.keypairs.create(name=name, public_key=pkey.read())
159 def vstf_create_flavors(name="bottlenecks_vstf_flavor", ram=4096, vcpus=2, disk=10):
160 print "========== Create vstf flavors in OS =========="
161 nova = _get_nova_client()
162 nova.flavors.create(name=name, ram=ram, vcpus=vcpus, disk=disk)
164 def vstf_create_instances(template_file, vstf_parameters=None, stack_name="bottlenecks_vstf_stack"):
165 print "========== Create vstf instances =========="
166 heat = _get_heat_client()
168 with open(template_file) as template:
169 stack = heat.stacks.create(stack_name=stack_name, template=template.read(), parameters=vstf_parameters)
171 stack_id = stack['stack']['id']
172 stack_status = heat.stacks.get(stack_id).stack_status
174 print "Created stack, id=" + str(stack_id) + ", status=" + str(stack_status)
177 while stack_status == "CREATE_IN_PROGRESS" and timeInProgress < 150:
178 print " stack's status: %s, after %d seconds" %(stack_status, timeInProgress)
180 timeInProgress = timeInProgress + 5
181 stack_status = heat.stacks.get(stack_id).stack_status
183 print "After %d seconds, the stack's status is [%s]" %(timeInProgress, stack_status)
184 return True if stack_status == "CREATE_COMPLETE" else False
186 def get_instances(nova_client):
188 instances = nova_client.servers.list(search_opts={'all_tenants': 1})
191 print "Error [get_instances(nova_client)]:", e
195 print "================run vstf==============="
197 nova = _get_nova_client()
198 print(nova.servers.list())
199 instances = get_instances(nova)
200 if instances == None:
201 print "Found *None* instances, exit vstf_run()!"
206 Bottlenecks_repo_dir = "/home/opnfv/bottlenecks" # same in Dockerfile, docker directory
207 Heat_template = Bottlenecks_repo_dir + "/testsuites/vstf/testcase_cfg/vstf_heat_template.yaml"
208 manager_image_url = 'http://artifacts.opnfv.org/bottlenecks/vstf-manager-new.img'
209 agent_image_url = 'http://artifacts.opnfv.org/bottlenecks/vstf-agent-new.img'
211 #vstf_env_prepare(testcase_cfg)
215 manager_file = _download_url(manager_image_url, dest_dir)
216 if manager_file == None:
217 print "error with downloading image(s)"
219 agent_file = _download_url(agent_image_url, dest_dir)
220 if agent_file == None:
221 print "error with downloading image(s)"
224 #TO DO:the parameters are all used defaults here, it should be changed depends on what it is really named
225 parameters={'key_name': 'bottlenecks_vstf_keypair',
226 'flavor': 'bottlenecks_vstf_flavor',
227 'public_net': os.environ.get('EXTERNAL_NET')}
229 print "Heat_template_file: " + Heat_template
230 print "parameters:\n" + str(parameters)
233 logger.error("Configuration files are not set for testcase")
236 testcase_cfg = args.conf
238 manager_image_created = False
239 tester_image_created = False
240 target_image_created = False
241 stack_created = False
243 manager_image_created = vstf_create_images(imagefile=manager_file, image_name="vstf-manager")
244 tester_image_created = vstf_create_images(imagefile=agent_file, image_name="vstf-tester")
245 target_image_created = vstf_create_images(imagefile=agent_file, image_name="vstf-target")
246 keyPath = Bottlenecks_repo_dir + "/utils/infra_setup/bottlenecks_key/bottlenecks_key.pub"
247 vstf_create_keypairs(key_path=keyPath)
248 vstf_create_flavors()
250 if manager_image_created == True and tester_image_created == True and target_image_created == True:
251 stack_created = vstf_create_instances(template_file=Heat_template, vstf_parameters=parameters, stack_name="bottlenecks_vstf_stack")
253 print "Cannot create instances, as Failed to create image(s)."
256 print "Wait 100 seconds after stack creation..."
263 if __name__=='__main__':