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 ##############################################################################
18 from heatclient.client import Client as HeatClient
19 from keystoneclient.v2_0.client import Client as KeystoneClient
20 from glanceclient.v2.client import Client as GlanceClient
21 from novaclient.client import Client as NovaClient
23 #------------------------------------------------------
24 # parser for configuration files in each test case
25 # ------------------------------------------------------
26 parser = argparse.ArgumentParser()
27 parser.add_argument("-c", "--conf",
28 help="configuration files for the testcase, in yaml format",
29 default="/tmp/rubbos_1-1-1.yaml")
30 args = parser.parse_args()
32 #--------------------------------------------------
33 # logging configuration
34 #--------------------------------------------------
35 logger = logging.getLogger(__name__)
38 def _get_keystone_client():
39 keystone_client = KeystoneClient(
40 auth_url=os.environ.get('OS_AUTH_URL'),
41 username=os.environ.get('OS_USERNAME'),
42 password=os.environ.get('OS_PASSWORD'),
43 tenant_name=os.environ.get('OS_TENANT_NAME'),
44 cacert=os.environ.get('OS_CACERT'))
45 return keystone_client
47 def _get_heat_client():
48 keystone = _get_keystone_client()
49 heat_endpoint = keystone.service_catalog.url_for(service_type='orchestration')
50 heat_client = HeatClient('1', endpoint=heat_endpoint, token=keystone.auth_token)
53 def _get_glance_client():
54 keystone = _get_keystone_client()
55 glance_endpoint = keystone.service_catalog.url_for(service_type='image', endpoint_type='publicURL')
56 return GlanceClient(glance_endpoint, token=keystone.auth_token)
58 def _get_nova_client():
59 nova_client = NovaClient("2", os.environ.get('OS_USERNAME'),
60 os.environ.get('OS_PASSWORD'),
61 os.environ.get('OS_TENANT_NAME'),
62 os.environ.get('OS_AUTH_URL'))
65 def _download_url(src_url, dest_dir):
66 ''' Download a file to a destination path given a URL'''
67 file_name = src_url.rsplit('/')[-1]
68 dest = dest_dir + "/" + file_name
70 response = urllib2.urlopen(src_url)
71 except (urllib2.HTTPError, urllib2.URLError):
74 with open(dest, 'wb') as f:
75 shutil.copyfileobj(response, f)
79 def rubbos_stack_satisfy(name="bottlenecks_rubbos_stack", status="CREATE_COMPLETE"):
80 heat = _get_heat_client()
81 for stack in heat.stacks.list():
82 if status == None and stack.stack_name == name:
84 print "Found stack, name=" + stack.stack_name
86 elif stack.stack_name == name and stack.stack_status==status:
87 print "Found stack, name=" + stack.stack_name + ", status=" + stack.stack_status
91 def rubbos_env_prepare(template=None):
92 print "========== Prepare rubbos environment =========="
93 logger.info("Generate heat template for the testcase based on template '%s'." % template)
95 def rubbos_env_cleanup():
96 print "========== Cleanup rubbos environment =========="
97 glance = _get_glance_client()
98 heat = _get_heat_client()
99 nova = _get_nova_client()
101 for image in glance.images.list():
102 if image.name.find("bottlenecks_rubbos") >= 0:
103 print "Delete image, id:" + str(image.id) + ", name:" + str(image.name)
104 glance.images.delete(image.id)
106 for keypair in nova.keypairs.list():
107 if keypair.name.find("bottlenecks_rubbos") >= 0:
108 print "Delete keypair, id:" + keypair.id + ", name:" + keypair.name
109 nova.keypairs.delete(keypair.id)
111 for flavor in nova.flavors.list():
112 if flavor.name.find("bottlenecks_rubbos") >= 0:
113 print "Delete flavor, id:" + str(flavor.id) + ", name:" + flavor.name
114 nova.flavors.delete(flavor.id)
116 for stack in heat.stacks.list():
117 if stack.stack_name.find("bottlenecks_rubbos") >= 0:
118 print "Delete stack, id: " + str(stack.id) + ", name:" + str(stack.stack_name
119 heat.stacks.delete(stack.id)
122 while rubbos_stack_satisfy(name="bottlenecks_rubbos_stack", status=None) and timeInProgress < 60:
124 timeInProgress = timeInProgress + 5
126 if rubbos_stack_satisfy(name="bottlenecks_rubbos_stack", status=None) == True:
127 print "Failed to clean the stack"
132 def rubbos_create_images(src_url=None, image_name="bottlenecks_rubbos_image"):
133 print "========== Create rubbos image in OS =========="
135 file_name = _download_url(src_url, dest_dir)
136 #file_name = "bottlenecks-trusty-server.img"
137 if file_name == None:
140 glance = _get_glance_client()
141 imagefile = dest_dir + "/" + file_name
142 image = glance.images.create(name=image_name, disk_format="qcow2", container_format="bare")
143 with open(imagefile) as fimage:
144 glance.images.upload(image.id, fimage)
147 img_status = image.status
148 while img_status == "queued" and timeInQueue < 30:
149 print " image's status: " + img_status
151 timeInQueue = timeInQueue + 1
152 img_status = glance.images.get(image.id).status
154 print "After %d seconds, the image's status is [%s]" %(timeInQueue, img_status)
155 return True if img_status == "active" else False
157 def rubbos_create_keypairs(key_path, name="bottlenecks_rubbos_keypair"):
158 print "========== Add rubbos keypairs in OS =========="
159 nova = _get_nova_client()
160 with open(key_path) as pkey:
161 nova.keypairs.create(name=name, public_key=pkey.read())
163 def rubbos_create_flavors(name="bottlenecks_rubbos_flavor", ram=4096, vcpus=2, disk=10):
164 print "========== Create rubbos flavors in OS =========="
165 nova = _get_nova_client()
166 nova.flavors.create(name=name, ram=ram, vcpus=vcpus, disk=disk)
168 def rubbos_create_instance(template_file, rubbos_parameters=None, stack_name="bottlenecks_rubbos_stack"):
169 print "========== Create rubbos instances =========="
170 heat = _get_heat_client()
172 with open(template_file) as template:
173 stack = heat.stacks.create(stack_name=stack_name, template=template.read(), parameters=rubbos_parameters)
175 stack_id = stack['stack']['id']
176 stack_status = heat.stacks.get(stack_id).stack_status
178 print "Created stack, id=" + stack_id + ", status=" + stack_status
181 while stack_status == "CREATE_IN_PROGRESS" and timeInProgress < 150:
182 print " stack's status: %s, after %d seconds" %(stack_status, timeInProgress)
184 timeInProgress = timeInProgress + 5
185 stack_status = heat.stacks.get(stack_id).stack_status
187 print "After %d seconds, the stack's status is [%s]" %(timeInProgress, stack_status)
188 return True if stack_status == "CREATE_COMPLETE" else False
195 global Bottlenecks_repo_dir
197 Bottlenecks_repo_dir = "/tmp/opnfvrepo/bottlenecks"
198 #Bottlenecks_repo_dir = "/root/wyg/bottlenecks" # Test dir in local env
200 image_url = 'http://artifacts.opnfv.org/bottlenecks/rubbos/bottlenecks-trusty-server.img'
203 logger.error("Configuration files are not set for testcase")
206 Heat_template = args.conf
208 parameters={'image': 'bottlenecks_rubbos_image',
209 'key_name': 'bottlenecks_rubbos_keypair',
210 'flavor': 'm1.small',
211 'public_net': 'ext-net'}
213 print "Heat_template_file: " + Heat_template
214 print "parameters:\n" + str(parameters)
216 image_created = False
217 stack_created = False
219 rubbos_env_prepare(Heat_template)
222 image_created = rubbos_create_images(image_url)
223 keyPath = Bottlenecks_repo_dir + "/utils/infra_setup/bottlenecks_key/bottlenecks_key.pub"
224 rubbos_create_keypairs(key_path=keyPath)
225 rubbos_create_flavors()
227 if image_created == True:
228 stack_created = rubbos_create_instances(template_file=Heat_template, rubbos_parameters=parameters, stack_name="bottlenecks_rubbos_stack")
230 print "Cannot create instances, as Failed to create image(s)."
236 if __name__=='__main__':