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