Fix userdata issue for vping and orchestra
[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 from datetime import datetime
10 import logging
11 import os
12 import time
13 import uuid
14
15 from functest.core import testcase
16 from functest.utils.constants import CONST
17
18 from snaps.openstack import create_flavor
19 from snaps.openstack.create_flavor import FlavorSettings, OpenStackFlavor
20 from snaps.openstack.create_network import NetworkSettings, SubnetSettings
21 from snaps.openstack.tests import openstack_tests
22 from snaps.openstack.utils import deploy_utils
23
24
25 class VPingBase(testcase.TestCase):
26
27     """
28     Base class for vPing tests that check connectivity between two VMs shared
29     internal network.
30     This class is responsible for creating the image, internal network.
31     """
32
33     def __init__(self, **kwargs):
34         super(VPingBase, self).__init__(**kwargs)
35
36         # This line is here simply for pep8 as the 'os' package import appears
37         # to be required for mock and the unit tests will fail without it
38         os.environ
39
40         self.logger = logging.getLogger(__name__)
41
42         if 'os_creds' in kwargs:
43             self.os_creds = kwargs['os_creds']
44         else:
45             creds_override = None
46             if hasattr(CONST, 'snaps_os_creds_override'):
47                 creds_override = CONST.__getattribute__(
48                     'snaps_os_creds_override')
49
50             self.os_creds = openstack_tests.get_credentials(
51                 os_env_file=CONST.__getattribute__('openstack_creds'),
52                 overrides=creds_override)
53
54         self.creators = list()
55         self.image_creator = None
56         self.network_creator = None
57         self.vm1_creator = None
58         self.vm2_creator = None
59
60         # Shared metadata
61         self.guid = ''
62         if CONST.__getattribute__('vping_unique_names'):
63             self.guid = '-' + str(uuid.uuid4())
64
65         self.vm1_name = CONST.__getattribute__('vping_vm_name_1') + self.guid
66         self.vm2_name = CONST.__getattribute__('vping_vm_name_2') + self.guid
67
68         self.vm_boot_timeout = CONST.__getattribute__('vping_vm_boot_timeout')
69         self.vm_delete_timeout = CONST.__getattribute__(
70             'vping_vm_delete_timeout')
71         self.vm_ssh_connect_timeout = CONST.vping_vm_ssh_connect_timeout
72         self.ping_timeout = CONST.__getattribute__('vping_ping_timeout')
73         self.flavor_name = 'vping-flavor' + self.guid
74
75         # Move this configuration option up for all tests to leverage
76         if hasattr(CONST, 'snaps_images_cirros'):
77             self.cirros_image_config = CONST.__getattribute__(
78                 'snaps_images_cirros')
79         else:
80             self.cirros_image_config = None
81
82     def run(self):
83         """
84         Begins the test execution which should originate from the subclass
85         """
86         self.logger.info('Begin virtual environment setup')
87
88         self.start_time = time.time()
89         self.logger.info("vPing Start Time:'%s'" % (
90             datetime.fromtimestamp(self.start_time).strftime(
91                 '%Y-%m-%d %H:%M:%S')))
92
93         image_base_name = '{}-{}'.format(
94             CONST.__getattribute__('vping_image_name'),
95             str(self.guid))
96         os_image_settings = openstack_tests.cirros_image_settings(
97             image_base_name, image_metadata=self.cirros_image_config)
98         self.logger.info("Creating image with name: '%s'" % image_base_name)
99
100         self.image_creator = deploy_utils.create_image(
101             self.os_creds, os_image_settings)
102         self.creators.append(self.image_creator)
103
104         private_net_name = CONST.__getattribute__(
105             'vping_private_net_name') + self.guid
106         private_subnet_name = CONST.__getattribute__(
107             'vping_private_subnet_name') + self.guid
108         private_subnet_cidr = CONST.__getattribute__(
109             'vping_private_subnet_cidr')
110
111         vping_network_type = None
112         vping_physical_network = None
113         vping_segmentation_id = None
114
115         if (hasattr(CONST, 'vping_network_type')):
116             vping_network_type = CONST.__getattribute__(
117                 'vping_network_type')
118         if (hasattr(CONST, 'vping_physical_network')):
119             vping_physical_network = CONST.__getattribute__(
120                 'vping_physical_network')
121         if (hasattr(CONST, 'vping_segmentation_id')):
122             vping_segmentation_id = CONST.__getattribute__(
123                 'vping_segmentation_id')
124
125         self.logger.info(
126             "Creating network with name: '%s'" % private_net_name)
127         self.network_creator = deploy_utils.create_network(
128             self.os_creds,
129             NetworkSettings(
130                 name=private_net_name,
131                 network_type=vping_network_type,
132                 physical_network=vping_physical_network,
133                 segmentation_id=vping_segmentation_id,
134                 subnet_settings=[SubnetSettings(
135                     name=private_subnet_name,
136                     cidr=private_subnet_cidr)]))
137         self.creators.append(self.network_creator)
138
139         self.logger.info(
140             "Creating flavor with name: '%s'" % self.flavor_name)
141         scenario = CONST.__getattribute__('DEPLOY_SCENARIO')
142         flavor_metadata = None
143         if 'ovs' in scenario or 'fdio' in scenario:
144             flavor_metadata = create_flavor.MEM_PAGE_SIZE_LARGE
145         flavor_creator = OpenStackFlavor(
146             self.os_creds,
147             FlavorSettings(name=self.flavor_name, ram=512, disk=1, vcpus=1,
148                            metadata=flavor_metadata))
149         flavor_creator.create()
150         self.creators.append(flavor_creator)
151
152     def _execute(self):
153         """
154         Method called by subclasses after environment has been setup
155         :return: the exit code
156         """
157         self.logger.info('Begin test execution')
158
159         test_ip = self.vm1_creator.get_port_ip(
160             self.vm1_creator.instance_settings.port_settings[0].name)
161
162         if self.vm1_creator.vm_active(
163                 block=True) and self.vm2_creator.vm_active(block=True):
164             result = self._do_vping(self.vm2_creator, test_ip)
165         else:
166             raise Exception('VMs never became active')
167
168         if result == testcase.TestCase.EX_RUN_ERROR:
169             return testcase.TestCase.EX_RUN_ERROR
170
171         self.stop_time = time.time()
172         self.result = 100
173         return testcase.TestCase.EX_OK
174
175     def _cleanup(self):
176         """
177         Cleanup all OpenStack objects. Should be called on completion
178         :return:
179         """
180         if CONST.__getattribute__('vping_cleanup_objects'):
181             for creator in reversed(self.creators):
182                 try:
183                     creator.clean()
184                 except Exception as e:
185                     self.logger.error('Unexpected error cleaning - %s', e)
186
187     def _do_vping(self, vm_creator, test_ip):
188         """
189         Method to be implemented by subclasses
190         Begins the real test after the OpenStack environment has been setup
191         :param vm_creator: the SNAPS VM instance creator object
192         :param test_ip: the IP to which the VM needs to issue the ping
193         :return: T/F
194         """
195         raise NotImplementedError('vping execution is not implemented')