Merge "Add reporting to DB in OpenDaylightTesting"
[functest.git] / testcases / OpenStack / vPing / vping_util.py
1 import os
2 import re
3 import pprint
4 import sys
5 import time
6
7 import functest.utils.functest_utils as ft_utils
8 import functest.utils.openstack_utils as os_utils
9 import paramiko
10 from scp import SCPClient
11 import yaml
12
13 REPO_PATH = os.environ['repos_dir'] + '/functest/'
14
15 with open(os.environ["CONFIG_FUNCTEST_YAML"]) as f:
16     functest_yaml = yaml.safe_load(f)
17 f.close()
18
19 NAME_VM_1 = functest_yaml.get("vping").get("vm_name_1")
20 NAME_VM_2 = functest_yaml.get("vping").get("vm_name_2")
21
22 VM_BOOT_TIMEOUT = 180
23 VM_DELETE_TIMEOUT = 100
24 PING_TIMEOUT = functest_yaml.get("vping").get("ping_timeout")
25
26 GLANCE_IMAGE_NAME = functest_yaml.get("vping").get("image_name")
27 GLANCE_IMAGE_FILENAME = functest_yaml.get("general").get(
28     "openstack").get("image_file_name")
29 GLANCE_IMAGE_FORMAT = functest_yaml.get("general").get(
30     "openstack").get("image_disk_format")
31 GLANCE_IMAGE_PATH = functest_yaml.get("general").get("directories").get(
32     "dir_functest_data") + "/" + GLANCE_IMAGE_FILENAME
33
34 FLAVOR = functest_yaml.get("vping").get("vm_flavor")
35
36 # NEUTRON Private Network parameters
37 PRIVATE_NET_NAME = functest_yaml.get("vping").get(
38     "vping_private_net_name")
39 PRIVATE_SUBNET_NAME = functest_yaml.get("vping").get(
40     "vping_private_subnet_name")
41 PRIVATE_SUBNET_CIDR = functest_yaml.get("vping").get(
42     "vping_private_subnet_cidr")
43 ROUTER_NAME = functest_yaml.get("vping").get(
44     "vping_router_name")
45
46 SECGROUP_NAME = functest_yaml.get("vping").get("vping_sg_name")
47 SECGROUP_DESCR = functest_yaml.get("vping").get("vping_sg_descr")
48
49
50 neutron_client = None
51 glance_client = None
52 nova_client = None
53 logger = None
54
55 pp = pprint.PrettyPrinter(indent=4)
56
57
58 def pMsg(value):
59     """pretty printing"""
60     pp.pprint(value)
61
62
63 def check_repo_exist():
64     if not os.path.exists(REPO_PATH):
65         logger.error("Functest repository not found '%s'" % REPO_PATH)
66         exit(-1)
67
68
69 def get_vmname_1():
70     return NAME_VM_1
71
72
73 def get_vmname_2():
74     return NAME_VM_2
75
76
77 def init(vping_logger):
78     global nova_client
79     nova_client = os_utils.get_nova_client()
80     global neutron_client
81     neutron_client = os_utils.get_neutron_client()
82     global glance_client
83     glance_client = os_utils.get_glance_client()
84     global logger
85     logger = vping_logger
86
87
88 def waitVmActive(nova, vm):
89
90     # sleep and wait for VM status change
91     sleep_time = 3
92     count = VM_BOOT_TIMEOUT / sleep_time
93     while True:
94         status = os_utils.get_instance_status(nova, vm)
95         logger.debug("Status: %s" % status)
96         if status == "ACTIVE":
97             return True
98         if status == "ERROR" or status == "error":
99             return False
100         if count == 0:
101             logger.debug("Booting a VM timed out...")
102             return False
103         count -= 1
104         time.sleep(sleep_time)
105     return False
106
107
108 def create_security_group():
109     sg_id = os_utils.get_security_group_id(neutron_client,
110                                            SECGROUP_NAME)
111     if sg_id != '':
112         logger.info("Using existing security group '%s'..." % SECGROUP_NAME)
113     else:
114         logger.info("Creating security group  '%s'..." % SECGROUP_NAME)
115         SECGROUP = os_utils.create_security_group(neutron_client,
116                                                   SECGROUP_NAME,
117                                                   SECGROUP_DESCR)
118         if not SECGROUP:
119             logger.error("Failed to create the security group...")
120             return False
121
122         sg_id = SECGROUP['id']
123
124         logger.debug("Security group '%s' with ID=%s created successfully."
125                      % (SECGROUP['name'], sg_id))
126
127         logger.debug("Adding ICMP rules in security group '%s'..."
128                      % SECGROUP_NAME)
129         if not os_utils.create_secgroup_rule(neutron_client, sg_id,
130                                              'ingress', 'icmp'):
131             logger.error("Failed to create the security group rule...")
132             return False
133
134         logger.debug("Adding SSH rules in security group '%s'..."
135                      % SECGROUP_NAME)
136         if not os_utils.create_secgroup_rule(neutron_client, sg_id,
137                                              'ingress', 'tcp',
138                                              '22', '22'):
139             logger.error("Failed to create the security group rule...")
140             return False
141
142         if not os_utils.create_secgroup_rule(
143                 neutron_client, sg_id, 'egress', 'tcp', '22', '22'):
144             logger.error("Failed to create the security group rule...")
145             return False
146     return sg_id
147
148
149 def create_image():
150     EXIT_CODE = -1
151
152     # Check if the given image exists
153     image_id = os_utils.get_image_id(glance_client, GLANCE_IMAGE_NAME)
154     if image_id != '':
155         logger.info("Using existing image '%s'..." % GLANCE_IMAGE_NAME)
156         image_exists = True
157     else:
158         logger.info("Creating image '%s' from '%s'..." % (GLANCE_IMAGE_NAME,
159                                                           GLANCE_IMAGE_PATH))
160         image_id = os_utils.create_glance_image(glance_client,
161                                                 GLANCE_IMAGE_NAME,
162                                                 GLANCE_IMAGE_PATH,
163                                                 GLANCE_IMAGE_FORMAT)
164         if not image_id:
165             logger.error("Failed to create a Glance image...")
166             exit(EXIT_CODE)
167         logger.debug("Image '%s' with ID=%s created successfully."
168                      % (GLANCE_IMAGE_NAME, image_id))
169     return image_exists, image_id
170
171
172 def get_flavor():
173     EXIT_CODE = -1
174
175     # Check if the given flavor exists
176     try:
177         flavor = nova_client.flavors.find(name=FLAVOR)
178         logger.info("Using existing Flavor '%s'..." % FLAVOR)
179         return flavor
180     except:
181         logger.error("Flavor '%s' not found." % FLAVOR)
182         logger.info("Available flavors are: ")
183         pMsg(nova_client.flavor.list())
184         exit(EXIT_CODE)
185
186
187 def create_network_full():
188     EXIT_CODE = -1
189
190     network_dic = os_utils.create_network_full(neutron_client,
191                                                PRIVATE_NET_NAME,
192                                                PRIVATE_SUBNET_NAME,
193                                                ROUTER_NAME,
194                                                PRIVATE_SUBNET_CIDR)
195
196     if not network_dic:
197         logger.error(
198             "There has been a problem when creating the neutron network")
199         exit(EXIT_CODE)
200     network_id = network_dic["net_id"]
201     return network_id
202
203
204 def delete_exist_vms():
205     servers = nova_client.servers.list()
206     for server in servers:
207         if server.name == NAME_VM_1 or server.name == NAME_VM_2:
208             logger.info("Instance %s found. Deleting..." % server.name)
209             server.delete()
210
211
212 def is_userdata(case):
213     return case == 'vping_userdata'
214
215
216 def is_ssh(case):
217     return case == 'vping_ssh'
218
219
220 def boot_vm(case, name, image_id, flavor, network_id, test_ip, sg_id):
221     EXIT_CODE = -1
222
223     config = dict()
224     config['name'] = name
225     config['flavor'] = flavor
226     config['image'] = image_id
227     config['nics'] = [{"net-id": network_id}]
228     if is_userdata(case):
229         config['config_drive'] = True
230         if name == NAME_VM_2:
231             u = ("#!/bin/sh\n\n"
232                  "while true; do\n"
233                  " ping -c 1 %s 2>&1 >/dev/null\n"
234                  " RES=$?\n"
235                  " if [ \"Z$RES\" = \"Z0\" ] ; then\n"
236                  "  echo 'vPing OK'\n"
237                  "  break\n"
238                  " else\n"
239                  "  echo 'vPing KO'\n"
240                  " fi\n"
241                  " sleep 1\n"
242                  "done\n" % test_ip)
243             config['userdata'] = u
244
245     logger.info("Creating instance '%s'..." % name)
246     logger.debug("Configuration: %s" % config)
247     vm = nova_client.servers.create(**config)
248
249     # wait until VM status is active
250     if not waitVmActive(nova_client, vm):
251
252         logger.error("Instance '%s' cannot be booted. Status is '%s'" % (
253             name, os_utils.get_instance_status(nova_client, vm)))
254         exit(EXIT_CODE)
255     else:
256         logger.info("Instance '%s' is ACTIVE." % name)
257
258     add_secgroup(name, vm.id, sg_id)
259
260     return vm
261
262
263 def get_test_ip(vm):
264     test_ip = vm.networks.get(PRIVATE_NET_NAME)[0]
265     logger.debug("Instance '%s' got %s" % (vm.name, test_ip))
266     return test_ip
267
268
269 def add_secgroup(vmname, vm_id, sg_id):
270     logger.info("Adding '%s' to security group '%s'..." %
271                 (vmname, SECGROUP_NAME))
272     os_utils.add_secgroup_to_instance(nova_client, vm_id, sg_id)
273
274
275 def add_float_ip(vm):
276     EXIT_CODE = -1
277
278     logger.info("Creating floating IP for VM '%s'..." % NAME_VM_2)
279     floatip_dic = os_utils.create_floating_ip(neutron_client)
280     floatip = floatip_dic['fip_addr']
281
282     if floatip is None:
283         logger.error("Cannot create floating IP.")
284         exit(EXIT_CODE)
285     logger.info("Floating IP created: '%s'" % floatip)
286
287     logger.info("Associating floating ip: '%s' to VM '%s' "
288                 % (floatip, NAME_VM_2))
289     if not os_utils.add_floating_ip(nova_client, vm.id, floatip):
290         logger.error("Cannot associate floating IP to VM.")
291         exit(EXIT_CODE)
292
293     return floatip
294
295
296 def establish_ssh(vm, floatip):
297     EXIT_CODE = -1
298
299     logger.info("Trying to establish SSH connection to %s..." % floatip)
300     username = 'cirros'
301     password = 'cubswin:)'
302     ssh = paramiko.SSHClient()
303     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
304
305     timeout = 50
306     nolease = False
307     got_ip = False
308     discover_count = 0
309     cidr_first_octet = PRIVATE_SUBNET_CIDR.split('.')[0]
310     while timeout > 0:
311         try:
312             ssh.connect(floatip, username=username,
313                         password=password, timeout=2)
314             logger.debug("SSH connection established to %s." % floatip)
315             break
316         except:
317             logger.debug("Waiting for %s..." % floatip)
318             time.sleep(6)
319             timeout -= 1
320
321         console_log = vm.get_console_output()
322
323         # print each "Sending discover" captured on the console log
324         if (len(re.findall("Sending discover", console_log)) >
325                 discover_count and not got_ip):
326             discover_count += 1
327             logger.debug("Console-log '%s': Sending discover..."
328                          % NAME_VM_2)
329
330         # check if eth0 got an ip,the line looks like this:
331         # "inet addr:192.168."....
332         # if the dhcp agent fails to assing ip, this line will not appear
333         if "inet addr:" + cidr_first_octet in console_log and not got_ip:
334             got_ip = True
335             logger.debug("The instance '%s' succeeded to get the IP "
336                          "from the dhcp agent." % NAME_VM_2)
337
338         # if dhcp doesnt work,it shows "No lease, failing".The test will fail
339         if "No lease, failing" in console_log and not nolease and not got_ip:
340             nolease = True
341             logger.debug("Console-log '%s': No lease, failing..."
342                          % NAME_VM_2)
343             logger.info("The instance failed to get an IP from the "
344                         "DHCP agent. The test will probably timeout...")
345
346     if timeout == 0:  # 300 sec timeout (5 min)
347         logger.error("Cannot establish connection to IP '%s'. Aborting"
348                      % floatip)
349         exit(EXIT_CODE)
350     return ssh
351
352
353 def transfer_ping_script(ssh, floatip):
354     EXIT_CODE = -1
355
356     logger.info("Trying to transfer ping.sh to %s..." % floatip)
357     scp = SCPClient(ssh.get_transport())
358
359     ping_script = REPO_PATH + "testcases/OpenStack/vPing/ping.sh"
360     try:
361         scp.put(ping_script, "~/")
362     except:
363         logger.error("Cannot SCP the file '%s' to VM '%s'"
364                      % (ping_script, floatip))
365         exit(EXIT_CODE)
366
367     cmd = 'chmod 755 ~/ping.sh'
368     (stdin, stdout, stderr) = ssh.exec_command(cmd)
369     for line in stdout.readlines():
370         print line
371
372
373 def do_vping_ssh(ssh, test_ip):
374     logger.info("Waiting for ping...")
375
376     sec = 0
377     cmd = '~/ping.sh ' + test_ip
378     flag = False
379
380     while True:
381         time.sleep(1)
382         (stdin, stdout, stderr) = ssh.exec_command(cmd)
383         output = stdout.readlines()
384
385         for line in output:
386             if "vPing OK" in line:
387                 logger.info("vPing detected!")
388                 EXIT_CODE = 0
389                 flag = True
390                 break
391
392             elif sec == PING_TIMEOUT:
393                 logger.info("Timeout reached.")
394                 flag = True
395                 break
396         if flag:
397             break
398         logger.debug("Pinging %s. Waiting for response..." % test_ip)
399         sec += 1
400     return EXIT_CODE, time.time()
401
402
403 def do_vping_userdata(vm, test_ip):
404     logger.info("Waiting for ping...")
405     EXIT_CODE = -1
406     sec = 0
407     metadata_tries = 0
408
409     while True:
410         time.sleep(1)
411         console_log = vm.get_console_output()
412         if "vPing OK" in console_log:
413             logger.info("vPing detected!")
414             EXIT_CODE = 0
415             break
416         elif ("failed to read iid from metadata" in console_log or
417               metadata_tries > 5):
418             EXIT_CODE = -2
419             break
420         elif sec == PING_TIMEOUT:
421             logger.info("Timeout reached.")
422             break
423         elif sec % 10 == 0:
424             if "request failed" in console_log:
425                 logger.debug("It seems userdata is not supported in "
426                              "nova boot. Waiting a bit...")
427                 metadata_tries += 1
428             else:
429                 logger.debug("Pinging %s. Waiting for response..." % test_ip)
430         sec += 1
431
432     return EXIT_CODE, time.time()
433
434
435 def do_vping(case, vm, test_ip):
436     if is_userdata(case):
437         return do_vping_userdata(vm, test_ip)
438     else:
439         floatip = add_float_ip(vm)
440         ssh = establish_ssh(vm, floatip)
441         transfer_ping_script(ssh, floatip)
442         return do_vping_ssh(ssh, test_ip)
443
444
445 def check_result(code, start_time, stop_time):
446     test_status = "FAIL"
447     if code == 0:
448         logger.info("vPing OK")
449         duration = round(stop_time - start_time, 1)
450         logger.info("vPing duration:'%s'" % duration)
451         test_status = "PASS"
452     elif code == -2:
453         duration = 0
454         logger.info("Userdata is not supported in nova boot. Aborting test...")
455     else:
456         duration = 0
457         logger.error("vPing FAILED")
458
459     details = {'timestart': start_time,
460                'duration': duration,
461                'status': test_status}
462
463     return details
464
465
466 def push_result(report, case, start_time, stop_time, details):
467     if report:
468         try:
469             logger.debug("Pushing vPing %s results into DB..." % case)
470             ft_utils.push_results_to_db('functest',
471                                         case,
472                                         logger,
473                                         start_time,
474                                         stop_time,
475                                         details['status'],
476                                         details=details)
477         except:
478             logger.error("Error pushing results into Database '%s'"
479                          % sys.exc_info()[0])