Control vping cleanup step via --noclean
[functest.git] / functest / opnfv_tests / openstack / vping / vping_ssh.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 """vPingSSH testcase."""
11
12 import time
13
14 from scp import SCPClient
15 import pkg_resources
16
17 from snaps.config.keypair import KeypairConfig
18 from snaps.config.network import PortConfig
19 from snaps.config.security_group import (
20     Direction, Protocol, SecurityGroupConfig, SecurityGroupRuleConfig)
21 from snaps.config.vm_inst import FloatingIpConfig, VmInstanceConfig
22 from snaps.openstack.utils import deploy_utils
23
24 from xtesting.core import testcase
25 from xtesting.energy import energy
26
27 from functest.opnfv_tests.openstack.vping import vping_base
28 from functest.utils import config
29
30
31 class VPingSSH(vping_base.VPingBase):
32     """
33     VPingSSH testcase implementation.
34
35     Class to execute the vPing test using a Floating IP to connect to one VM
36     to issue the ping command to the second
37     """
38
39     def __init__(self, **kwargs):
40         """Initialize testcase."""
41         if "case_name" not in kwargs:
42             kwargs["case_name"] = "vping_ssh"
43         super(VPingSSH, self).__init__(**kwargs)
44
45         self.kp_name = getattr(config.CONF, 'vping_keypair_name') + self.guid
46         self.kp_priv_file = getattr(config.CONF, 'vping_keypair_priv_file')
47         self.kp_pub_file = getattr(config.CONF, 'vping_keypair_pub_file')
48         self.sg_name = getattr(config.CONF, 'vping_sg_name') + self.guid
49         self.sg_desc = getattr(config.CONF, 'vping_sg_desc')
50
51     @energy.enable_recording
52     def run(self, **kwargs):
53         """
54         Excecute VPingSSH testcase.
55
56         Sets up the OpenStack keypair, router, security group, and VM instance
57         objects then validates the ping.
58         :return: the exit code from the super.execute() method
59         """
60         try:
61             super(VPingSSH, self).run()
62
63             log = "Creating keypair with name: '%s'" % self.kp_name
64             self.logger.info(log)
65             kp_creator = deploy_utils.create_keypair(
66                 self.os_creds,
67                 KeypairConfig(
68                     name=self.kp_name, private_filepath=self.kp_priv_file,
69                     public_filepath=self.kp_pub_file))
70             self.creators.append(kp_creator)
71
72             # Creating Instance 1
73             port1_settings = PortConfig(
74                 name=self.vm1_name + '-vPingPort',
75                 network_name=self.network_creator.network_settings.name)
76             instance1_settings = VmInstanceConfig(
77                 name=self.vm1_name, flavor=self.flavor_name,
78                 vm_boot_timeout=self.vm_boot_timeout,
79                 vm_delete_timeout=self.vm_delete_timeout,
80                 ssh_connect_timeout=self.vm_ssh_connect_timeout,
81                 port_settings=[port1_settings])
82
83             log = ("Creating VM 1 instance with name: '%s'"
84                    % instance1_settings.name)
85             self.logger.info(log)
86             self.vm1_creator = deploy_utils.create_vm_instance(
87                 self.os_creds,
88                 instance1_settings,
89                 self.image_creator.image_settings,
90                 keypair_creator=kp_creator)
91             self.creators.append(self.vm1_creator)
92
93             # Creating Instance 2
94             sg_creator = self.__create_security_group()
95             self.creators.append(sg_creator)
96
97             port2_settings = PortConfig(
98                 name=self.vm2_name + '-vPingPort',
99                 network_name=self.network_creator.network_settings.name)
100             instance2_settings = VmInstanceConfig(
101                 name=self.vm2_name, flavor=self.flavor_name,
102                 vm_boot_timeout=self.vm_boot_timeout,
103                 vm_delete_timeout=self.vm_delete_timeout,
104                 ssh_connect_timeout=self.vm_ssh_connect_timeout,
105                 port_settings=[port2_settings],
106                 security_group_names=[sg_creator.sec_grp_settings.name],
107                 floating_ip_settings=[FloatingIpConfig(
108                     name=self.vm2_name + '-FIPName',
109                     port_name=port2_settings.name,
110                     router_name=self.router_creator.router_settings.name)])
111
112             log = ("Creating VM 2 instance with name: '%s'"
113                    % instance2_settings.name)
114             self.logger.info(log)
115             self.vm2_creator = deploy_utils.create_vm_instance(
116                 self.os_creds,
117                 instance2_settings,
118                 self.image_creator.image_settings,
119                 keypair_creator=kp_creator)
120             self.creators.append(self.vm2_creator)
121
122             return self._execute()
123         except Exception as exc:  # pylint: disable=broad-except
124             self.logger.error('Unexpected error running test - ' + exc.message)
125             return testcase.TestCase.EX_RUN_ERROR
126
127     def _do_vping(self, vm_creator, test_ip):
128         """
129         Execute ping command.
130
131         Override from super
132         """
133         if vm_creator.vm_ssh_active(block=True):
134             ssh = vm_creator.ssh_client()
135             if not self._transfer_ping_script(ssh):
136                 return testcase.TestCase.EX_RUN_ERROR
137             return self._do_vping_ssh(ssh, test_ip)
138         else:
139             return testcase.TestCase.EX_RUN_ERROR
140
141     def _transfer_ping_script(self, ssh):
142         """
143         Transfert vping script to VM.
144
145         Uses SCP to copy the ping script via the SSH client
146         :param ssh: the SSH client
147         :return:
148         """
149         self.logger.info("Trying to transfer ping.sh")
150         scp = SCPClient(ssh.get_transport())
151         ping_script = pkg_resources.resource_filename(
152             'functest.opnfv_tests.openstack.vping', 'ping.sh')
153         try:
154             scp.put(ping_script, "~/")
155         except Exception:  # pylint: disable=broad-except
156             self.logger.error("Cannot SCP the file '%s'", ping_script)
157             return False
158
159         cmd = 'chmod 755 ~/ping.sh'
160         # pylint: disable=unused-variable
161         (stdin, stdout, stderr) = ssh.exec_command(cmd)
162         for line in stdout.readlines():
163             print line
164
165         return True
166
167     def _do_vping_ssh(self, ssh, test_ip):
168         """
169         Execute ping command via SSH.
170
171         Pings the test_ip via the SSH client
172         :param ssh: the SSH client used to issue the ping command
173         :param test_ip: the IP for the ping command to use
174         :return: exit_code (int)
175         """
176         exit_code = testcase.TestCase.EX_TESTCASE_FAILED
177         self.logger.info("Waiting for ping...")
178
179         sec = 0
180         cmd = '~/ping.sh ' + test_ip
181         flag = False
182
183         while True:
184             time.sleep(1)
185             (_, stdout, _) = ssh.exec_command(cmd)
186             output = stdout.readlines()
187
188             for line in output:
189                 if "vPing OK" in line:
190                     self.logger.info("vPing detected!")
191                     exit_code = testcase.TestCase.EX_OK
192                     flag = True
193                     break
194
195                 elif sec == self.ping_timeout:
196                     self.logger.info("Timeout reached.")
197                     flag = True
198                     break
199             if flag:
200                 break
201             log = "Pinging %s. Waiting for response..." % test_ip
202             self.logger.debug(log)
203             sec += 1
204         return exit_code
205
206     def __create_security_group(self):
207         """
208         Configure OpenStack security groups.
209
210         Configures and deploys an OpenStack security group object
211         :return: the creator object
212         """
213         sg_rules = list()
214         sg_rules.append(
215             SecurityGroupRuleConfig(
216                 sec_grp_name=self.sg_name, direction=Direction.ingress,
217                 protocol=Protocol.icmp))
218         sg_rules.append(
219             SecurityGroupRuleConfig(
220                 sec_grp_name=self.sg_name, direction=Direction.ingress,
221                 protocol=Protocol.tcp, port_range_min=22, port_range_max=22))
222         sg_rules.append(
223             SecurityGroupRuleConfig(
224                 sec_grp_name=self.sg_name, direction=Direction.egress,
225                 protocol=Protocol.tcp, port_range_min=22, port_range_max=22))
226
227         log = "Security group with name: '%s'" % self.sg_name
228         self.logger.info(log)
229         return deploy_utils.create_security_group(self.os_creds,
230                                                   SecurityGroupConfig(
231                                                       name=self.sg_name,
232                                                       description=self.sg_desc,
233                                                       rule_settings=sg_rules))