584ded386b1673601be195098ec7ba37fe83550a
[functest.git] / functest / opnfv_tests / openstack / vping / vping_base.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 pprint
12 import time
13 from datetime import datetime
14
15 import functest.core.testcase as testcase
16 import functest.utils.openstack_utils as os_utils
17 from functest.utils.constants import CONST
18
19
20 class VPingBase(testcase.TestCase):
21     def __init__(self):
22         super(VPingBase, self).__init__()
23         self.logger = None
24         self.functest_repo = CONST.dir_repo_functest
25         self.repo = CONST.dir_vping
26         self.vm1_name = CONST.vping_vm_name_1
27         self.vm2_name = CONST.vping_vm_name_2
28         self.vm_boot_timeout = 180
29         self.vm_delete_timeout = 100
30         self.ping_timeout = CONST.vping_ping_timeout
31
32         self.image_name = CONST.vping_image_name
33         self.image_filename = CONST.openstack_image_file_name
34         self.image_format = CONST.openstack_image_disk_format
35         self.image_username = CONST.openstack_image_username
36         self.image_password = CONST.openstack_image_password
37         self.image_path = os.path.join(CONST.dir_functest_data,
38                                        self.image_filename)
39
40         self.flavor_name = CONST.vping_vm_flavor
41
42         # NEUTRON Private Network parameters
43         self.private_net_name = CONST.vping_private_net_name
44         self.private_subnet_name = CONST.vping_private_subnet_name
45         self.private_subnet_cidr = CONST.vping_private_subnet_cidr
46         self.router_name = CONST.vping_router_name
47         self.sg_name = CONST.vping_sg_name
48         self.sg_desc = CONST.vping_sg_desc
49         self.neutron_client = os_utils.get_neutron_client()
50         self.glance_client = os_utils.get_glance_client()
51         self.nova_client = os_utils.get_nova_client()
52
53     def run(self, **kwargs):
54         if not self.check_repo_exist():
55             return testcase.TestCase.EX_RUN_ERROR
56
57         image_id = self.create_image()
58         if not image_id:
59             return testcase.TestCase.EX_RUN_ERROR
60
61         flavor = self.get_flavor()
62         if not flavor:
63             return testcase.TestCase.EX_RUN_ERROR
64
65         network_id = self.create_network_full()
66         if not network_id:
67             return testcase.TestCase.EX_RUN_ERROR
68
69         sg_id = self.create_security_group()
70         if not sg_id:
71             return testcase.TestCase.EX_RUN_ERROR
72
73         self.delete_exist_vms()
74
75         self.start_time = time.time()
76         self.logger.info("vPing Start Time:'%s'" % (
77             datetime.fromtimestamp(self.start_time).strftime(
78                 '%Y-%m-%d %H:%M:%S')))
79
80         vm1 = self.boot_vm(self.vm1_name,
81                            image_id,
82                            flavor,
83                            network_id,
84                            None,
85                            sg_id)
86         if not vm1:
87             return testcase.TestCase.EX_RUN_ERROR
88
89         test_ip = self.get_test_ip(vm1)
90         vm2 = self.boot_vm(self.vm2_name,
91                            image_id,
92                            flavor,
93                            network_id,
94                            test_ip,
95                            sg_id)
96         if not vm2:
97             return testcase.TestCase.EX_RUN_ERROR
98
99         EXIT_CODE = self.do_vping(vm2, test_ip)
100         if EXIT_CODE == testcase.TestCase.EX_RUN_ERROR:
101             return EXIT_CODE
102
103         self.stop_time = time.time()
104         self.parse_result(EXIT_CODE,
105                           self.start_time,
106                           self.stop_time)
107         return testcase.TestCase.EX_OK
108
109     def boot_vm_preparation(self, config, vmname, test_ip):
110         pass
111
112     def do_vping(self, vm, test_ip):
113         raise NotImplementedError('vping execution is not implemented')
114
115     def check_repo_exist(self):
116         if not os.path.exists(self.functest_repo):
117             self.logger.error("Functest repository not found '%s'"
118                               % self.functest_repo)
119             return False
120         return True
121
122     def create_image(self):
123         _, image_id = os_utils.get_or_create_image(self.image_name,
124                                                    self.image_path,
125                                                    self.image_format)
126         if not image_id:
127             return None
128
129         return image_id
130
131     def get_flavor(self):
132         try:
133             flavor = self.nova_client.flavors.find(name=self.flavor_name)
134             self.logger.info("Using existing Flavor '%s'..."
135                              % self.flavor_name)
136             return flavor
137         except:
138             self.logger.error("Flavor '%s' not found." % self.flavor_name)
139             self.logger.info("Available flavors are: ")
140             self.pMsg(self.nova_client.flavor.list())
141             return None
142
143     def create_network_full(self):
144         network_dic = os_utils.create_network_full(self.neutron_client,
145                                                    self.private_net_name,
146                                                    self.private_subnet_name,
147                                                    self.router_name,
148                                                    self.private_subnet_cidr)
149
150         if not network_dic:
151             self.logger.error(
152                 "There has been a problem when creating the neutron network")
153             return None
154         network_id = network_dic["net_id"]
155         return network_id
156
157     def create_security_group(self):
158         sg_id = os_utils.get_security_group_id(self.neutron_client,
159                                                self.sg_name)
160         if sg_id != '':
161             self.logger.info("Using existing security group '%s'..."
162                              % self.sg_name)
163         else:
164             self.logger.info("Creating security group  '%s'..."
165                              % self.sg_name)
166             SECGROUP = os_utils.create_security_group(self.neutron_client,
167                                                       self.sg_name,
168                                                       self.sg_desc)
169             if not SECGROUP:
170                 self.logger.error("Failed to create the security group...")
171                 return None
172
173             sg_id = SECGROUP['id']
174
175             self.logger.debug("Security group '%s' with ID=%s created "
176                               "successfully." % (SECGROUP['name'], sg_id))
177
178             self.logger.debug("Adding ICMP rules in security group '%s'..."
179                               % self.sg_name)
180             if not os_utils.create_secgroup_rule(self.neutron_client, sg_id,
181                                                  'ingress', 'icmp'):
182                 self.logger.error("Failed to create security group rule...")
183                 return None
184
185             self.logger.debug("Adding SSH rules in security group '%s'..."
186                               % self.sg_name)
187             if not os_utils.create_secgroup_rule(self.neutron_client, sg_id,
188                                                  'ingress', 'tcp',
189                                                  '22', '22'):
190                 self.logger.error("Failed to create security group rule...")
191                 return None
192
193             if not os_utils.create_secgroup_rule(
194                     self.neutron_client, sg_id, 'egress', 'tcp', '22', '22'):
195                 self.logger.error("Failed to create security group rule...")
196                 return None
197         return sg_id
198
199     def delete_exist_vms(self):
200         servers = self.nova_client.servers.list()
201         for server in servers:
202             if server.name == self.vm1_name or server.name == self.vm2_name:
203                 self.logger.info("Deleting instance %s..." % server.name)
204                 server.delete()
205
206     def boot_vm(self, vmname, image_id, flavor, network_id, test_ip, sg_id):
207         config = dict()
208         config['name'] = vmname
209         config['flavor'] = flavor
210         config['image'] = image_id
211         config['nics'] = [{"net-id": network_id}]
212         self.boot_vm_preparation(config, vmname, test_ip)
213         self.logger.info("Creating instance '%s'..." % vmname)
214         self.logger.debug("Configuration: %s" % config)
215         vm = self.nova_client.servers.create(**config)
216
217         # wait until VM status is active
218         if not self.waitVmActive(self.nova_client, vm):
219             vm_status = os_utils.get_instance_status(self.nova_client, vm)
220             self.logger.error("Instance '%s' cannot be booted. Status is '%s'"
221                               % (vmname, vm_status))
222             return None
223         else:
224             self.logger.info("Instance '%s' is ACTIVE." % vmname)
225
226         self.add_secgroup(vmname, vm.id, sg_id)
227
228         return vm
229
230     def waitVmActive(self, nova, vm):
231         # sleep and wait for VM status change
232         sleep_time = 3
233         count = self.vm_boot_timeout / sleep_time
234         while True:
235             status = os_utils.get_instance_status(nova, vm)
236             self.logger.debug("Status: %s" % status)
237             if status == "ACTIVE":
238                 return True
239             if status == "ERROR" or status == "error":
240                 return False
241             if count == 0:
242                 self.logger.debug("Booting a VM timed out...")
243                 return False
244             count -= 1
245             time.sleep(sleep_time)
246         return False
247
248     def add_secgroup(self, vmname, vm_id, sg_id):
249         self.logger.info("Adding '%s' to security group '%s'..." %
250                          (vmname, self.sg_name))
251         os_utils.add_secgroup_to_instance(self.nova_client, vm_id, sg_id)
252
253     def get_test_ip(self, vm):
254         test_ip = vm.networks.get(self.private_net_name)[0]
255         self.logger.debug("Instance '%s' got %s" % (vm.name, test_ip))
256         return test_ip
257
258     def parse_result(self, code, start_time, stop_time):
259         test_status = "FAIL"
260         if code == 0:
261             self.logger.info("vPing OK")
262             duration = round(stop_time - start_time, 1)
263             self.logger.info("vPing duration:'%s'" % duration)
264             test_status = "PASS"
265         elif code == -2:
266             duration = 0
267             self.logger.info("Userdata is not supported in nova boot. "
268                              "Aborting test...")
269         else:
270             duration = 0
271             self.logger.error("vPing FAILED")
272
273         self.details = {'timestart': start_time,
274                         'duration': duration,
275                         'status': test_status}
276         self.criteria = test_status
277
278     @staticmethod
279     def pMsg(msg):
280         """pretty printing"""
281         pprint.PrettyPrinter(indent=4).pprint(msg)
282
283
284 class VPingMain(object):
285     def __init__(self, vping_cls):
286         self.vping = vping_cls()
287
288     def main(self, **kwargs):
289         try:
290             result = self.vping.run(**kwargs)
291             if result != VPingBase.EX_OK:
292                 return result
293             if kwargs['report']:
294                 return self.vping.push_to_db()
295         except Exception:
296             return VPingBase.EX_RUN_ERROR