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