a68b0ff755862381d12ad9a5b7fe16b8d9d634fa
[functest.git] / functest / opnfv_tests / openstack / vping / vping_ssh.py
1 #!/usr/bin/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 import os
11 import re
12 import sys
13 import time
14
15 import argparse
16 import paramiko
17 from scp import SCPClient
18
19 import functest.utils.functest_logger as ft_logger
20 import functest.utils.openstack_utils as os_utils
21 import vping_base
22 import functest.core.testcase as testcase
23
24
25 class VPingSSH(vping_base.VPingBase):
26
27     def __init__(self, case_name='vping_ssh'):
28         super(VPingSSH, self).__init__(case_name)
29         self.logger = ft_logger.Logger(self.case_name).getLogger()
30
31     def do_vping(self, vm, test_ip):
32         floatip = self.add_float_ip(vm)
33         if not floatip:
34             return testcase.TestCase.EX_RUN_ERROR
35         ssh = self.establish_ssh(vm, floatip)
36         if not ssh:
37             return testcase.TestCase.EX_RUN_ERROR
38         if not self.transfer_ping_script(ssh, floatip):
39             return testcase.TestCase.EX_RUN_ERROR
40         return self.do_vping_ssh(ssh, test_ip)
41
42     def add_float_ip(self, vm):
43         self.logger.info("Creating floating IP for VM '%s'..." % self.vm2_name)
44         floatip_dic = os_utils.create_floating_ip(self.neutron_client)
45         floatip = floatip_dic['fip_addr']
46
47         if floatip is None:
48             self.logger.error("Cannot create floating IP.")
49             return None
50         self.logger.info("Floating IP created: '%s'" % floatip)
51
52         self.logger.info("Associating floating ip: '%s' to VM '%s' "
53                          % (floatip, self.vm2_name))
54         if not os_utils.add_floating_ip(self.nova_client, vm.id, floatip):
55             self.logger.error("Cannot associate floating IP to VM.")
56             return None
57
58         return floatip
59
60     def establish_ssh(self, vm, floatip):
61         self.logger.info("Trying to establish SSH connection to %s..."
62                          % floatip)
63         ssh = paramiko.SSHClient()
64         ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
65
66         timeout = 50
67         nolease = False
68         got_ip = False
69         discover_count = 0
70         cidr_first_octet = self.private_subnet_cidr.split('.')[0]
71         while timeout > 0:
72             try:
73                 ssh.connect(floatip, username=self.image_username,
74                             password=self.image_password, timeout=2)
75                 self.logger.debug("SSH connection established to %s."
76                                   % floatip)
77                 break
78             except:
79                 self.logger.debug("Waiting for %s..." % floatip)
80                 time.sleep(6)
81                 timeout -= 1
82
83             console_log = vm.get_console_output()
84
85             # print each "Sending discover" captured on the console log
86             if (len(re.findall("Sending discover", console_log)) >
87                     discover_count and not got_ip):
88                 discover_count += 1
89                 self.logger.debug("Console-log '%s': Sending discover..."
90                                   % self.vm2_name)
91
92             # check if eth0 got an ip,the line looks like this:
93             # "inet addr:192.168."....
94             # if the dhcp agent fails to assing ip, this line will not appear
95             if "inet addr:" + cidr_first_octet in console_log and not got_ip:
96                 got_ip = True
97                 self.logger.debug("The instance '%s' succeeded to get the IP "
98                                   "from the dhcp agent." % self.vm2_name)
99
100             # if dhcp not work,it shows "No lease, failing".The test will fail
101             if ("No lease, failing" in console_log and
102                 not nolease and
103                     not got_ip):
104                 nolease = True
105                 self.logger.debug("Console-log '%s': No lease, failing..."
106                                   % self.vm2_name)
107                 self.logger.info("The instance failed to get an IP from DHCP "
108                                  "agent. The test will probably timeout...")
109
110         if timeout == 0:  # 300 sec timeout (5 min)
111             self.logger.error("Cannot establish connection to IP '%s'. "
112                               "Aborting" % floatip)
113             return None
114         return ssh
115
116     def transfer_ping_script(self, ssh, floatip):
117         self.logger.info("Trying to transfer ping.sh to %s..." % floatip)
118         scp = SCPClient(ssh.get_transport())
119         local_path = self.functest_repo + "/" + self.repo
120         ping_script = os.path.join(local_path, "ping.sh")
121         try:
122             scp.put(ping_script, "~/")
123         except:
124             self.logger.error("Cannot SCP the file '%s' to VM '%s'"
125                               % (ping_script, floatip))
126             return False
127
128         cmd = 'chmod 755 ~/ping.sh'
129         (stdin, stdout, stderr) = ssh.exec_command(cmd)
130         for line in stdout.readlines():
131             print line
132
133         return True
134
135     def do_vping_ssh(self, ssh, test_ip):
136         EXIT_CODE = -1
137         self.logger.info("Waiting for ping...")
138
139         sec = 0
140         cmd = '~/ping.sh ' + test_ip
141         flag = False
142
143         while True:
144             time.sleep(1)
145             (stdin, stdout, stderr) = ssh.exec_command(cmd)
146             output = stdout.readlines()
147
148             for line in output:
149                 if "vPing OK" in line:
150                     self.logger.info("vPing detected!")
151                     EXIT_CODE = 0
152                     flag = True
153                     break
154
155                 elif sec == self.ping_timeout:
156                     self.logger.info("Timeout reached.")
157                     flag = True
158                     break
159             if flag:
160                 break
161             self.logger.debug("Pinging %s. Waiting for response..." % test_ip)
162             sec += 1
163         return EXIT_CODE
164
165
166 if __name__ == '__main__':
167     args_parser = argparse.ArgumentParser()
168     args_parser.add_argument("-r", "--report",
169                              help="Create json result file",
170                              action="store_true")
171     args = vars(args_parser.parse_args())
172     sys.exit(vping_base.VPingMain(VPingSSH).main(**args))