Add a fundamental rubbos test case with minimum resources
[bottlenecks.git] / testsuites / rubbos / run_rubbos.py
1 #!/usr/bin/env python
2 ##############################################################################
3 # Copyright (c) 2016 Huawei Technologies Co.,Ltd and others.
4 #
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 ##############################################################################
10
11 import os
12 import argparse
13 import time
14 import subprocess
15 import logging
16 import urllib2
17 import shutil
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
22
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="/home/opnfv/bottlenecks/testsuites/rubbos/testcase_cfg/rubbos_basic.yaml")
30 args = parser.parse_args()
31
32 #--------------------------------------------------
33 # logging configuration
34 #--------------------------------------------------
35 logger = logging.getLogger(__name__)
36
37
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
46
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)
51     return heat_client
52
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)
57
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'))
63     return nova_client
64
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
69     try:
70         response = urllib2.urlopen(src_url)
71     except (urllib2.HTTPError, urllib2.URLError):
72         return None
73
74     with open(dest, 'wb') as f:
75         shutil.copyfileobj(response, f)
76     return file_name
77
78
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:
83             # Found target stack
84             print "Found stack, name=" + str(stack.stack_name)
85             return True
86         elif stack.stack_name == name and stack.stack_status==status:
87             print "Found stack, name=" + str(stack.stack_name) + ", status=" + str(stack.stack_status)
88             return True
89     return False
90
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)
94
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()
100
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)
105
106     for keypair in nova.keypairs.list():
107         if keypair.name.find("bottlenecks_rubbos") >= 0:
108             print "Delete keypair, id:" + str(keypair.id) + ", name:" + str(keypair.name)
109             nova.keypairs.delete(keypair.id)
110
111     for flavor in nova.flavors.list():
112         if flavor.name.find("bottlenecks_rubbos") >= 0:
113             print "Delete flavor, id:" + str(flavor.id) + ", name:" + str(flavor.name)
114             nova.flavors.delete(flavor.id)
115
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)
120
121     timeInProgress = 0
122     while rubbos_stack_satisfy(name="bottlenecks_rubbos_stack", status=None) and timeInProgress < 60:
123         time.sleep(5)
124         timeInProgress = timeInProgress + 5
125
126     if rubbos_stack_satisfy(name="bottlenecks_rubbos_stack", status=None) == True:
127         print "Failed to clean the stack"
128         return False
129     else:
130         return True
131
132 def rubbos_create_images(src_url=None, image_name="bottlenecks_rubbos_image"):
133     print "========== Create rubbos image in OS =========="
134     dest_dir = '/tmp'
135     file_name = _download_url(src_url, dest_dir)
136     #file_name = "bottlenecks-trusty-server.img"
137     if file_name == None:
138        return False
139
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)
145
146     timeInQueue = 0
147     img_status = image.status
148     while img_status == "queued" and timeInQueue < 30:
149         print "  image's status: " + img_status
150         time.sleep(1)
151         timeInQueue = timeInQueue + 1
152         img_status = glance.images.get(image.id).status
153
154     print "After %d seconds, the image's status is [%s]" %(timeInQueue, img_status)
155     return True if img_status == "active" else False
156
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())
162
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)
167
168 def rubbos_create_instances(template_file, rubbos_parameters=None, stack_name="bottlenecks_rubbos_stack"):
169     print "========== Create rubbos instances =========="
170     heat = _get_heat_client()
171
172     with open(template_file) as template:
173         stack = heat.stacks.create(stack_name=stack_name, template=template.read(), parameters=rubbos_parameters)
174
175     stack_id = stack['stack']['id']
176     stack_status = heat.stacks.get(stack_id).stack_status
177
178     print "Created stack, id=" + str(stack_id) + ", status=" + str(stack_status)
179
180     timeInProgress= 0
181     while stack_status == "CREATE_IN_PROGRESS" and timeInProgress < 150:
182         print "  stack's status: %s, after %d seconds" %(stack_status, timeInProgress)
183         time.sleep(5)
184         timeInProgress = timeInProgress + 5
185         stack_status = heat.stacks.get(stack_id).stack_status
186
187     print "After %d seconds, the stack's status is [%s]" %(timeInProgress, stack_status)
188     return True if stack_status == "CREATE_COMPLETE" else False
189
190 def get_instances(nova_client):
191     try:
192         instances = nova_client.servers.list(search_opts={'all_tenants': 1})
193         return instances
194     except Exception, e:
195         print "Error [get_instances(nova_client)]:", e
196         return None
197
198 def reboot_instances():
199     print("========== reboot instances ==========")
200     nova = _get_nova_client()
201     print("nova servers list:")
202     print(nova.servers.list())
203     for instance in nova.servers.list():
204         name = getattr(instance, 'name')
205         if name.find("rubbos") >= 0:
206             print("reboot %s" % name)
207             instance.reboot()
208     print("Finish reboot all rubbos servers.")
209
210 def rubbos_run():
211     print "========== run rubbos ==========="
212
213     nova = _get_nova_client()
214     instances = get_instances(nova)
215     if instances == None:
216         print "Found *None* instances, exit rubbos_run()!"
217         return False
218
219     control_public_ip = ""
220     control_server = ""
221     client_servers = ""
222     web_servers = ""
223     app_servers = ""
224     cjdbc_controller = ""
225     database_servers = ""
226     for instance in instances:
227         name = getattr(instance, 'name')
228         private_ip = [ x['addr'] for x in getattr(instance, 'addresses').itervalues().next() if x['OS-EXT-IPS:type'] == 'fixed']
229         public_ip =  [ x['addr'] for x in getattr(instance, 'addresses').itervalues().next() if x['OS-EXT-IPS:type'] == 'floating']
230
231         if name.find("rubbos-control") >= 0:
232             control_public_ip = public_ip[0]
233             control_server = str(name) + ':' + public_ip[0] + ':' + private_ip[0]
234         if name.find("rubbos-client") >= 0:
235             client_servers = client_servers + str(name)+':'+private_ip[0] + ","
236         if name.find("rubbos-httpd") >= 0:
237             web_servers = web_servers + str(name)+':'+private_ip[0] + ","
238         if name.find("rubbos-tomcat") >= 0:
239             app_servers = app_servers + str(name) + ':' + private_ip[0] + ","
240         if name.find("rubbos-cjdbc") >= 0:
241             cjdbc_controller = str(name) + ':' + private_ip[0]
242         if name.find("rubbos-mysql") >= 0:
243             database_servers = database_servers + str(name) + ':' + private_ip[0] + ","
244
245     client_servers = client_servers[0:len(client_servers)-1]
246     web_servers = web_servers[0:len(web_servers)-1]
247     app_servers = app_servers[0:len(app_servers)-1]
248     database_servers = database_servers[0:len(database_servers)-1]
249     print "control_server:    %s" % control_server
250     print "client_servers:    %s" % client_servers
251     print "web_servers:       %s" % web_servers
252     print "app_servers:       %s" % app_servers
253     print "cjdbc_controller:  %s" % cjdbc_controller
254     print "database_servers:  %s" % database_servers
255     with open(Bottlenecks_repo_dir+"/testsuites/rubbos/puppet_manifests/internal/rubbos.conf") as temp_f, open('rubbos.conf', 'w') as new_f:
256         for line in temp_f.readlines():
257             if line.find("REPLACED_CONTROLLER") >= 0 :
258                 new_f.write( line.replace("REPLACED_CONTROLLER", control_server) )
259             elif line.find("REPLACED_CLIENT_SERVERS") >= 0:
260                 new_f.write( line.replace("REPLACED_CLIENT_SERVERS", client_servers) )
261             elif line.find("REPLACED_WEB_SERVERS") >= 0:
262                 new_f.write( line.replace("REPLACED_WEB_SERVERS", web_servers) )
263             elif line.find("REPLACED_APP_SERVERS") >= 0:
264                 new_f.write( line.replace("REPLACED_APP_SERVERS", app_servers) )
265             elif line.find("REPLACED_CJDBC_CONTROLLER") >= 0:
266                 new_f.write( line.replace("REPLACED_CJDBC_CONTROLLER", cjdbc_controller) )
267             elif line.find("REPLACED_DB_SERVERS") >= 0:
268                 new_f.write( line.replace("REPLACED_DB_SERVERS", database_servers) )
269             elif line.find("REPLACED_CLIENTS_PER_NODE") >= 0:
270                 new_f.write( line.replace("REPLACED_CLIENTS_PER_NODE", "200 400 800 1600 3200") )
271             else:
272                 new_f.write(line)
273     if os.path.exists("rubbos.conf") == False:
274         return False
275
276     cmd = "sudo chmod 0600 " + Bottlenecks_repo_dir + "/utils/infra_setup/bottlenecks_key/bottlenecks_key"
277     subprocess.call(cmd, shell=True)
278     ssh_args = "-o StrictHostKeyChecking=no -o BatchMode=yes -i " + Bottlenecks_repo_dir + "/utils/infra_setup/bottlenecks_key/bottlenecks_key "
279
280     print "############### Test #################"
281     cmd = 'ssh-keygen -f "/root/.ssh/known_hosts" -R ' + control_public_ip
282     subprocess.call(cmd, shell=True)
283     print "## Ping test:"
284     cmd = "ping -c 5 " + control_public_ip
285     print cmd
286     subprocess.call(cmd, shell=True)
287     print "## ssh date test:"
288     cmd = "ssh " + ssh_args + " ubuntu@" + control_public_ip + ' "date"'
289     print cmd
290     subprocess.call(cmd, shell=True)
291     print "## neutruon net-list:"
292     subprocess.call("neutron net-list", shell=True)
293     print "## nova list:"
294     subprocess.call("nova list", shell=True)
295     print "############### Test #################"
296
297     cmd = "scp " + ssh_args + "rubbos.conf ubuntu@" + control_public_ip + ":/home/ubuntu/"
298     print "Exec shell: " + cmd
299     subprocess.call(cmd, shell=True)
300
301     cmd = "scp " + ssh_args + Bottlenecks_repo_dir + "/testsuites/rubbos/puppet_manifests/internal/run_rubbos_internal.sh ubuntu@" + control_public_ip + ":/home/ubuntu/"
302     print "Exec shell: " + cmd
303     subprocess.call(cmd, shell=True)
304
305     # call remote run_rubbos_internal.sh
306     cmd = "ssh " + ssh_args + " ubuntu@" + control_public_ip + ' "sudo /home/ubuntu/run_rubbos_internal.sh /home/ubuntu/rubbos.conf /home/ubuntu/btnks-results" '
307     print "Exec shell: " + cmd
308     subprocess.call(cmd, shell=True)
309     cmd = "scp " + ssh_args + " ubuntu@" + control_public_ip + ":/home/ubuntu/btnks-results/rubbos.out ./rubbos.out"
310     print "Exec shell: " + cmd
311     subprocess.call(cmd, shell=True)
312     if os.path.exists("rubbos.out") == False:
313         print "Failed to fetch results from the rubbos_control node!"
314         return False
315
316     with open("rubbos.out") as f:
317         lines = f.readlines()
318         print "Rubbos results:"
319         for line in lines:
320             print line
321     return True
322
323 def main():
324     global Heat_template
325     global Bottlenecks_repo_dir
326     global image_url
327     Bottlenecks_repo_dir = "/home/opnfv/bottlenecks"      # same in Dockerfile, docker directory
328
329     image_url = 'http://artifacts.opnfv.org/bottlenecks/rubbos/trusty-server-cloudimg-amd64-btnks.img'
330     #image_url = 'http://artifacts.opnfv.org/bottlenecks/rubbos/bottlenecks-trusty-server.img'
331
332     if not (args.conf):
333        logger.error("Configuration files are not set for testcase")
334        exit(-1)
335     else:
336        Heat_template = args.conf
337
338     master_user_data=""
339     agent_user_data=""
340     with open(Bottlenecks_repo_dir+"/utils/infra_setup/user_data/p-master-user-data") as f:
341         master_user_data=f.read()
342     master_user_data = master_user_data.replace('REPLACED_PUPPET_MASTER_SERVER','rubbos-control')
343     with open(Bottlenecks_repo_dir+"/utils/infra_setup/user_data/p-agent-user-data") as f:
344         agent_user_data=f.read()
345     agent_user_data = agent_user_data.replace('REPLACED_PUPPET_MASTER_SERVER','rubbos-control')
346
347     parameters={'image': 'bottlenecks_rubbos_image',
348                 'key_name': 'bottlenecks_rubbos_keypair',
349                 'flavor': 'bottlenecks_rubbos_flavor',
350                 'public_net': os.environ.get('EXTERNAL_NET'),
351                 'master_user_data': master_user_data,
352                 'agent_user_data': agent_user_data }
353
354     print "Heat_template_file: " + Heat_template
355     print "parameters:\n" + str(parameters)
356
357     image_created = False
358     stack_created = False
359
360     rubbos_env_prepare(Heat_template)
361     rubbos_env_cleanup()
362
363     image_created = rubbos_create_images(image_url)
364     keyPath = Bottlenecks_repo_dir + "/utils/infra_setup/bottlenecks_key/bottlenecks_key.pub"
365     rubbos_create_keypairs(key_path=keyPath)
366     rubbos_create_flavors()
367
368     if image_created == True:
369         stack_created = rubbos_create_instances(template_file=Heat_template, rubbos_parameters=parameters, stack_name="bottlenecks_rubbos_stack")
370     else:
371         print "Cannot create instances, as Failed to create image(s)."
372         exit (-1)
373
374     print "Wait 150 seconds after stack creation........."
375     time.sleep(150)
376
377     reboot_instances()
378     time.sleep(30)
379
380     rubbos_run()
381     rubbos_env_cleanup()
382
383 if __name__=='__main__':
384     main()