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