Merge "Add cinder_test testcase"
[functest.git] / functest / opnfv_tests / openstack / vping / vping_userdata.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2015 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 """vping_userdata testcase."""
11
12 import logging
13 import time
14
15 from xtesting.core import testcase
16
17 from functest.opnfv_tests.openstack.vping import vping_base
18 from functest.utils import config
19
20
21 class VPingUserdata(vping_base.VPingBase):
22     """
23     Class to execute the vPing test using userdata and the VM's console
24     """
25
26     def __init__(self, **kwargs):
27         if "case_name" not in kwargs:
28             kwargs["case_name"] = "vping_userdata"
29         super(VPingUserdata, self).__init__(**kwargs)
30         self.logger = logging.getLogger(__name__)
31         self.vm2 = None
32
33     def run(self, **kwargs):
34         """
35         Sets up the OpenStack VM instance objects then executes the ping and
36         validates.
37         :return: the exit code from the super.execute() method
38         """
39         try:
40             assert self.cloud
41             super(VPingUserdata, self).run()
42
43             vm2_name = "{}-{}-{}".format(
44                 getattr(config.CONF, 'vping_vm_name_2'), "userdata", self.guid)
45             self.logger.info(
46                 "Creating VM 2 instance with name: '%s'", vm2_name)
47             self.vm2 = self.cloud.create_server(
48                 vm2_name, image=self.image.id, flavor=self.flavor.id,
49                 auto_ip=False, wait=True,
50                 timeout=getattr(config.CONF, 'vping_vm_boot_timeout'),
51                 network=self.network.id,
52                 userdata=self._get_userdata())
53             self.logger.debug("vm2: %s", self.vm2)
54             self.vm2 = self.cloud.wait_for_server(self.vm2, auto_ip=False)
55             p_console = self.cloud.get_server_console(self.vm1.id)
56             self.logger.debug("vm2 console: \n%s", p_console)
57
58             return self._execute()
59         except Exception:  # pylint: disable=broad-except
60             self.logger.exception('Unexpected error running vping_userdata')
61             return testcase.TestCase.EX_RUN_ERROR
62
63     def _do_vping(self):
64         """
65         Override from super
66         """
67         self.logger.info("Waiting for ping...")
68         exit_code = testcase.TestCase.EX_TESTCASE_FAILED
69         sec = 0
70         tries = 0
71
72         while True:
73             time.sleep(1)
74             p_console = self.cloud.get_server_console(self.vm2.id)
75             self.logger.debug("console: \n%s", p_console)
76             if "vPing OK" in p_console:
77                 self.logger.info("vPing detected!")
78                 exit_code = testcase.TestCase.EX_OK
79                 break
80             elif "failed to read iid from metadata" in p_console or tries > 5:
81                 self.logger.info("Failed to read iid from metadata")
82                 break
83             elif sec == getattr(config.CONF, 'vping_ping_timeout'):
84                 self.logger.info("Timeout reached.")
85                 break
86             elif sec % 10 == 0:
87                 if "request failed" in p_console:
88                     self.logger.debug(
89                         "It seems userdata is not supported in nova boot. " +
90                         "Waiting a bit...")
91                     tries += 1
92                 else:
93                     self.logger.debug(
94                         "Pinging %s. Waiting for response...",
95                         self.vm1.private_v4)
96             sec += 1
97
98         return exit_code
99
100     def _get_userdata(self):
101         """
102         Returns the post VM creation script to be added into the VM's userdata
103         :param test_ip: the IP value to substitute into the script
104         :return: the bash script contents
105         """
106         if self.vm1.private_v4:
107             return ("#!/bin/sh\n\n"
108                     "while true; do\n"
109                     " ping -c 1 %s 2>&1 >/dev/null\n"
110                     " RES=$?\n"
111                     " if [ \"Z$RES\" = \"Z0\" ] ; then\n"
112                     "  echo 'vPing OK'\n"
113                     "  break\n"
114                     " else\n"
115                     "  echo 'vPing KO'\n"
116                     " fi\n"
117                     " sleep 1\n"
118                     "done\n" % str(self.vm1.private_v4))
119         return None
120
121     def clean(self):
122         assert self.cloud
123         self.cloud.delete_server(
124             self.vm2, wait=True,
125             timeout=getattr(config.CONF, 'vping_vm_delete_timeout'))
126         self.cloud.delete_server(self.vm2, wait=True)
127         super(VPingUserdata, self).clean()