Mend create_image() function
[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         image_exists = True
170
171     return image_exists, image_id
172
173
174 def get_flavor():
175     EXIT_CODE = -1
176
177     # Check if the given flavor exists
178     try:
179         flavor = nova_client.flavors.find(name=FLAVOR)
180         logger.info("Using existing Flavor '%s'..." % FLAVOR)
181         return flavor
182     except:
183         logger.error("Flavor '%s' not found." % FLAVOR)
184         logger.info("Available flavors are: ")
185         pMsg(nova_client.flavor.list())
186         exit(EXIT_CODE)
187
188
189 def create_network_full():
190     EXIT_CODE = -1
191
192     network_dic = os_utils.create_network_full(neutron_client,
193                                                PRIVATE_NET_NAME,
194                                                PRIVATE_SUBNET_NAME,
195                                                ROUTER_NAME,
196                                                PRIVATE_SUBNET_CIDR)
197
198     if not network_dic:
199         logger.error(
200             "There has been a problem when creating the neutron network")
201         exit(EXIT_CODE)
202     network_id = network_dic["net_id"]
203     return network_id
204
205
206 def delete_exist_vms():
207     servers = nova_client.servers.list()
208     for server in servers:
209         if server.name == NAME_VM_1 or server.name == NAME_VM_2:
210             logger.info("Instance %s found. Deleting..." % server.name)
211             server.delete()
212
213
214 def is_userdata(case):
215     return case == 'vping_userdata'
216
217
218 def is_ssh(case):
219     return case == 'vping_ssh'
220
221
222 def boot_vm(case, name, image_id, flavor, network_id, test_ip, sg_id):
223     EXIT_CODE = -1
224
225     config = dict()
226     config['name'] = name
227     config['flavor'] = flavor
228     config['image'] = image_id
229     config['nics'] = [{"net-id": network_id}]
230     if is_userdata(case):
231         config['config_drive'] = True
232         if name == NAME_VM_2:
233             u = ("#!/bin/sh\n\n"
234                  "while true; do\n"
235                  " ping -c 1 %s 2>&1 >/dev/null\n"
236                  " RES=$?\n"
237                  " if [ \"Z$RES\" = \"Z0\" ] ; then\n"
238                  "  echo 'vPing OK'\n"
239                  "  break\n"
240                  " else\n"
241                  "  echo 'vPing KO'\n"
242                  " fi\n"
243                  " sleep 1\n"
244                  "done\n" % test_ip)
245             config['userdata'] = u
246
247     logger.info("Creating instance '%s'..." % name)
248     logger.debug("Configuration: %s" % config)
249     vm = nova_client.servers.create(**config)
250
251     # wait until VM status is active
252     if not waitVmActive(nova_client, vm):
253
254         logger.error("Instance '%s' cannot be booted. Status is '%s'" % (
255             name, os_utils.get_instance_status(nova_client, vm)))
256         exit(EXIT_CODE)
257     else:
258         logger.info("Instance '%s' is ACTIVE." % name)
259
260     add_secgroup(name, vm.id, sg_id)
261
262     return vm
263
264
265 def get_test_ip(vm):
266     test_ip = vm.networks.get(PRIVATE_NET_NAME)[0]
267     logger.debug("Instance '%s' got %s" % (vm.name, test_ip))
268     return test_ip
269
270
271 def add_secgroup(vmname, vm_id, sg_id):
272     logger.info("Adding '%s' to security group '%s'..." %
273                 (vmname, SECGROUP_NAME))
274     os_utils.add_secgroup_to_instance(nova_client, vm_id, sg_id)
275
276
277 def add_float_ip(vm):
278     EXIT_CODE = -1
279
280     logger.info("Creating floating IP for VM '%s'..." % NAME_VM_2)
281     floatip_dic = os_utils.create_floating_ip(neutron_client)
282     floatip = floatip_dic['fip_addr']
283
284     if floatip is None:
285         logger.error("Cannot create floating IP.")
286         exit(EXIT_CODE)
287     logger.info("Floating IP created: '%s'" % floatip)
288
289     logger.info("Associating floating ip: '%s' to VM '%s' "
290                 % (floatip, NAME_VM_2))
291     if not os_utils.add_floating_ip(nova_client, vm.id, floatip):
292         logger.error("Cannot associate floating IP to VM.")
293         exit(EXIT_CODE)
294
295     return floatip
296
297
298 def establish_ssh(vm, floatip):
299     EXIT_CODE = -1
300
301     logger.info("Trying to establish SSH connection to %s..." % floatip)
302     username = 'cirros'
303     password = 'cubswin:)'
304     ssh = paramiko.SSHClient()
305     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
306
307     timeout = 50
308     nolease = False
309     got_ip = False
310     discover_count = 0
311     cidr_first_octet = PRIVATE_SUBNET_CIDR.split('.')[0]
312     while timeout > 0:
313         try:
314             ssh.connect(floatip, username=username,
315                         password=password, timeout=2)
316             logger.debug("SSH connection established to %s." % floatip)
317             break
318         except:
319             logger.debug("Waiting for %s..." % floatip)
320             time.sleep(6)
321             timeout -= 1
322
323         console_log = vm.get_console_output()
324
325         # print each "Sending discover" captured on the console log
326         if (len(re.findall("Sending discover", console_log)) >
327                 discover_count and not got_ip):
328             discover_count += 1
329             logger.debug("Console-log '%s': Sending discover..."
330                          % NAME_VM_2)
331
332         # check if eth0 got an ip,the line looks like this:
333         # "inet addr:192.168."....
334         # if the dhcp agent fails to assing ip, this line will not appear
335         if "inet addr:" + cidr_first_octet in console_log and not got_ip:
336             got_ip = True
337             logger.debug("The instance '%s' succeeded to get the IP "
338                          "from the dhcp agent." % NAME_VM_2)
339
340         # if dhcp doesnt work,it shows "No lease, failing".The test will fail
341         if "No lease, failing" in console_log and not nolease and not got_ip:
342             nolease = True
343             logger.debug("Console-log '%s': No lease, failing..."
344                          % NAME_VM_2)
345             logger.info("The instance failed to get an IP from the "
346                         "DHCP agent. The test will probably timeout...")
347
348     if timeout == 0:  # 300 sec timeout (5 min)
349         logger.error("Cannot establish connection to IP '%s'. Aborting"
350                      % floatip)
351         exit(EXIT_CODE)
352     return ssh
353
354
355 def transfer_ping_script(ssh, floatip):
356     EXIT_CODE = -1
357
358     logger.info("Trying to transfer ping.sh to %s..." % floatip)
359     scp = SCPClient(ssh.get_transport())
360
361     ping_script = REPO_PATH + "testcases/OpenStack/vPing/ping.sh"
362     try:
363         scp.put(ping_script, "~/")
364     except:
365         logger.error("Cannot SCP the file '%s' to VM '%s'"
366                      % (ping_script, floatip))
367         exit(EXIT_CODE)
368
369     cmd = 'chmod 755 ~/ping.sh'
370     (stdin, stdout, stderr) = ssh.exec_command(cmd)
371     for line in stdout.readlines():
372         print line
373
374
375 def do_vping_ssh(ssh, test_ip):
376     logger.info("Waiting for ping...")
377
378     sec = 0
379     cmd = '~/ping.sh ' + test_ip
380     flag = False
381
382     while True:
383         time.sleep(1)
384         (stdin, stdout, stderr) = ssh.exec_command(cmd)
385         output = stdout.readlines()
386
387         for line in output:
388             if "vPing OK" in line:
389                 logger.info("vPing detected!")
390                 EXIT_CODE = 0
391                 flag = True
392                 break
393
394             elif sec == PING_TIMEOUT:
395                 logger.info("Timeout reached.")
396                 flag = True
397                 break
398         if flag:
399             break
400         logger.debug("Pinging %s. Waiting for response..." % test_ip)
401         sec += 1
402     return EXIT_CODE, time.time()
403
404
405 def do_vping_userdata(vm, test_ip):
406     logger.info("Waiting for ping...")
407     EXIT_CODE = -1
408     sec = 0
409     metadata_tries = 0
410
411     while True:
412         time.sleep(1)
413         console_log = vm.get_console_output()
414         if "vPing OK" in console_log:
415             logger.info("vPing detected!")
416             EXIT_CODE = 0
417             break
418         elif ("failed to read iid from metadata" in console_log or
419               metadata_tries > 5):
420             EXIT_CODE = -2
421             break
422         elif sec == PING_TIMEOUT:
423             logger.info("Timeout reached.")
424             break
425         elif sec % 10 == 0:
426             if "request failed" in console_log:
427                 logger.debug("It seems userdata is not supported in "
428                              "nova boot. Waiting a bit...")
429                 metadata_tries += 1
430             else:
431                 logger.debug("Pinging %s. Waiting for response..." % test_ip)
432         sec += 1
433
434     return EXIT_CODE, time.time()
435
436
437 def do_vping(case, vm, test_ip):
438     if is_userdata(case):
439         return do_vping_userdata(vm, test_ip)
440     else:
441         floatip = add_float_ip(vm)
442         ssh = establish_ssh(vm, floatip)
443         transfer_ping_script(ssh, floatip)
444         return do_vping_ssh(ssh, test_ip)
445
446
447 def check_result(code, start_time, stop_time):
448     test_status = "FAIL"
449     if code == 0:
450         logger.info("vPing OK")
451         duration = round(stop_time - start_time, 1)
452         logger.info("vPing duration:'%s'" % duration)
453         test_status = "PASS"
454     elif code == -2:
455         duration = 0
456         logger.info("Userdata is not supported in nova boot. Aborting test...")
457     else:
458         duration = 0
459         logger.error("vPing FAILED")
460
461     details = {'timestart': start_time,
462                'duration': duration,
463                'status': test_status}
464
465     return details
466
467
468 def push_result(report, case, start_time, stop_time, details):
469     if report:
470         try:
471             logger.debug("Pushing vPing %s results into DB..." % case)
472             ft_utils.push_results_to_db('functest',
473                                         case,
474                                         logger,
475                                         start_time,
476                                         stop_time,
477                                         details['status'],
478                                         details=details)
479         except:
480             logger.error("Error pushing results into Database '%s'"
481                          % sys.exc_info()[0])