Merge "Fix pylint errors of vping"
[functest.git] / functest / opnfv_tests / openstack / vping / vping_base.py
1 # Copyright (c) 2017 Cable Television Laboratories, Inc. and others.
2 #
3 # This program and the accompanying materials
4 # are made available under the terms of the Apache License, Version 2.0
5 # which accompanies this distribution, and is available at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8
9 """Define the parent class of vping_ssh and vping_userdata testcases."""
10
11 from datetime import datetime
12 import logging
13 import time
14 import uuid
15
16 from functest.core import testcase
17 from functest.opnfv_tests.openstack.snaps import snaps_utils
18 from functest.utils.constants import CONST
19
20 from snaps.config.flavor import FlavorConfig
21 from snaps.config.network import NetworkConfig, SubnetConfig
22 from snaps.config.router import RouterConfig
23 from snaps.openstack import create_flavor
24 from snaps.openstack.create_flavor import OpenStackFlavor
25 from snaps.openstack.tests import openstack_tests
26 from snaps.openstack.utils import deploy_utils
27
28
29 class VPingBase(testcase.TestCase):
30
31     """
32     Base class for vPing tests that check connectivity between two VMs shared
33     internal network.
34     This class is responsible for creating the image, internal network.
35     """
36     # pylint: disable=too-many-instance-attributes
37
38     def __init__(self, **kwargs):
39         super(VPingBase, self).__init__(**kwargs)
40
41         self.logger = logging.getLogger(__name__)
42
43         if 'os_creds' in kwargs:
44             self.os_creds = kwargs['os_creds']
45         else:
46             creds_override = None
47             if hasattr(CONST, 'snaps_os_creds_override'):
48                 creds_override = CONST.__getattribute__(
49                     'snaps_os_creds_override')
50
51             self.os_creds = openstack_tests.get_credentials(
52                 os_env_file=CONST.__getattribute__('openstack_creds'),
53                 overrides=creds_override)
54
55         self.creators = list()
56         self.image_creator = None
57         self.network_creator = None
58         self.vm1_creator = None
59         self.vm2_creator = None
60         self.router_creator = None
61
62         # Shared metadata
63         self.guid = ''
64         if CONST.__getattribute__('vping_unique_names'):
65             self.guid = '-' + str(uuid.uuid4())
66
67         self.router_name = CONST.__getattribute__(
68             'vping_router_name') + self.guid
69         self.vm1_name = CONST.__getattribute__('vping_vm_name_1') + self.guid
70         self.vm2_name = CONST.__getattribute__('vping_vm_name_2') + self.guid
71
72         self.vm_boot_timeout = CONST.__getattribute__('vping_vm_boot_timeout')
73         self.vm_delete_timeout = CONST.__getattribute__(
74             'vping_vm_delete_timeout')
75         self.vm_ssh_connect_timeout = CONST.__getattribute__(
76             'vping_vm_ssh_connect_timeout')
77         self.ping_timeout = CONST.__getattribute__('vping_ping_timeout')
78         self.flavor_name = 'vping-flavor' + self.guid
79
80         # Move this configuration option up for all tests to leverage
81         if hasattr(CONST, 'snaps_images_cirros'):
82             self.cirros_image_config = CONST.__getattribute__(
83                 'snaps_images_cirros')
84         else:
85             self.cirros_image_config = None
86
87     def run(self):
88         """
89         Begins the test execution which should originate from the subclass
90         """
91         self.logger.info('Begin virtual environment setup')
92
93         self.start_time = time.time()
94         self.logger.info(
95             "vPing Start Time:'%s'",
96             datetime.fromtimestamp(self.start_time).strftime(
97                 '%Y-%m-%d %H:%M:%S'))
98
99         image_base_name = '{}-{}'.format(
100             CONST.__getattribute__('vping_image_name'),
101             str(self.guid))
102         os_image_settings = openstack_tests.cirros_image_settings(
103             image_base_name, image_metadata=self.cirros_image_config)
104         self.logger.info("Creating image with name: '%s'", image_base_name)
105
106         self.image_creator = deploy_utils.create_image(
107             self.os_creds, os_image_settings)
108         self.creators.append(self.image_creator)
109
110         private_net_name = CONST.__getattribute__(
111             'vping_private_net_name') + self.guid
112         private_subnet_name = CONST.__getattribute__(
113             'vping_private_subnet_name') + self.guid
114         private_subnet_cidr = CONST.__getattribute__(
115             'vping_private_subnet_cidr')
116
117         vping_network_type = None
118         vping_physical_network = None
119         vping_segmentation_id = None
120
121         if hasattr(CONST, 'vping_network_type'):
122             vping_network_type = CONST.__getattribute__(
123                 'vping_network_type')
124         if hasattr(CONST, 'vping_physical_network'):
125             vping_physical_network = CONST.__getattribute__(
126                 'vping_physical_network')
127         if hasattr(CONST, 'vping_segmentation_id'):
128             vping_segmentation_id = CONST.__getattribute__(
129                 'vping_segmentation_id')
130
131         self.logger.info(
132             "Creating network with name: '%s'", private_net_name)
133         self.network_creator = deploy_utils.create_network(
134             self.os_creds,
135             NetworkConfig(
136                 name=private_net_name,
137                 network_type=vping_network_type,
138                 physical_network=vping_physical_network,
139                 segmentation_id=vping_segmentation_id,
140                 subnet_settings=[SubnetConfig(
141                     name=private_subnet_name,
142                     cidr=private_subnet_cidr)]))
143         self.creators.append(self.network_creator)
144
145         # Creating router to external network
146         log = "Creating router with name: '%s'" % self.router_name
147         self.logger.info(log)
148         ext_net_name = snaps_utils.get_ext_net_name(self.os_creds)
149         self.router_creator = deploy_utils.create_router(
150             self.os_creds,
151             RouterConfig(
152                 name=self.router_name,
153                 external_gateway=ext_net_name,
154                 internal_subnets=[private_subnet_name]))
155         self.creators.append(self.router_creator)
156
157         self.logger.info(
158             "Creating flavor with name: '%s'", self.flavor_name)
159         scenario = CONST.__getattribute__('DEPLOY_SCENARIO')
160         flavor_metadata = None
161         if 'ovs' in scenario or 'fdio' in scenario:
162             flavor_metadata = create_flavor.MEM_PAGE_SIZE_LARGE
163         flavor_creator = OpenStackFlavor(
164             self.os_creds,
165             FlavorConfig(name=self.flavor_name, ram=512, disk=1, vcpus=1,
166                          metadata=flavor_metadata))
167         flavor_creator.create()
168         self.creators.append(flavor_creator)
169
170     def _execute(self):
171         """
172         Method called by subclasses after environment has been setup
173         :return: the exit code
174         """
175         self.logger.info('Begin test execution')
176
177         test_ip = self.vm1_creator.get_port_ip(
178             self.vm1_creator.instance_settings.port_settings[0].name)
179
180         if self.vm1_creator.vm_active(
181                 block=True) and self.vm2_creator.vm_active(block=True):
182             result = self._do_vping(self.vm2_creator, test_ip)
183         else:
184             raise Exception('VMs never became active')
185
186         self.stop_time = time.time()
187
188         if result != testcase.TestCase.EX_OK:
189             self.result = 0
190             return testcase.TestCase.EX_RUN_ERROR
191
192         self.result = 100
193         return testcase.TestCase.EX_OK
194
195     def _cleanup(self):
196         """
197         Cleanup all OpenStack objects. Should be called on completion
198         :return:
199         """
200         if CONST.__getattribute__('vping_cleanup_objects'):
201             for creator in reversed(self.creators):
202                 try:
203                     creator.clean()
204                 except Exception as error:  # pylint: disable=broad-except
205                     self.logger.error('Unexpected error cleaning - %s', error)
206
207     def _do_vping(self, vm_creator, test_ip):
208         """
209         Method to be implemented by subclasses
210         Begins the real test after the OpenStack environment has been setup
211         :param vm_creator: the SNAPS VM instance creator object
212         :param test_ip: the IP to which the VM needs to issue the ping
213         :return: T/F
214         """
215         raise NotImplementedError('vping execution is not implemented')