Add cinder_test testcase
[functest.git] / functest / opnfv_tests / openstack / cinder / cinder_test.py
1 #!/usr/bin/env python
2
3
4 # Copyright (c) 2018 Enea AB and others
5
6 # This program and the accompanying materials
7 # are made available under the terms of the Apache License, Version 2.0
8 # which accompanies this distribution, and is available at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11
12 """CinderCheck testcase."""
13
14 import logging
15 import os
16 import tempfile
17 import time
18 import pkg_resources
19 from scp import SCPClient
20
21 import paramiko
22 from xtesting.core import testcase
23 from xtesting.energy import energy
24
25 from functest.opnfv_tests.openstack.cinder import cinder_base
26 from functest.utils import config
27
28
29 class CinderCheck(cinder_base.CinderBase):
30     """
31     CinderCheck testcase implementation.
32
33     Class to execute the CinderCheck test using 2 Floating IPs
34     to connect to the VMs and one data volume
35     """
36     # pylint: disable=too-many-instance-attributes
37
38     def __init__(self, **kwargs):
39         """Initialize testcase."""
40         if "case_name" not in kwargs:
41             kwargs["case_name"] = "cinder_test"
42         super(CinderCheck, self).__init__(**kwargs)
43         self.logger = logging.getLogger(__name__)
44         self.vm1 = None
45         self.vm2 = None
46         self.sec = None
47         self.fip1 = None
48         self.fip2 = None
49         self.keypair1 = None
50         self.keypair2 = None
51         (_, self.key1_filename) = tempfile.mkstemp()
52         self.ssh = paramiko.SSHClient()
53         (_, self.key2_filename) = tempfile.mkstemp()
54
55     @energy.enable_recording
56     def run(self, **kwargs):
57         """
58         Excecute CinderCheck testcase.
59
60         Sets up the OpenStack keypair, router, security group, and VM instance
61         objects then validates the ping.
62         :return: the exit code from the super.execute() method
63         """
64         try:
65             assert self.cloud
66             super(CinderCheck, self).run()
67
68             # Creating key pair 1
69             kp_name1 = getattr(
70                 config.CONF, 'cinder_keypair_name') + '_1' + self.guid
71             self.logger.info("Creating keypair with name: '%s'", kp_name1)
72             self.keypair1 = self.cloud.create_keypair(kp_name1)
73             self.logger.debug("keypair: %s", self.keypair1)
74             self.logger.debug("private_key: %s", self.keypair1.private_key)
75             with open(self.key1_filename, 'w') as private_key1_file:
76                 private_key1_file.write(self.keypair1.private_key)
77             # Creating key pair 2
78             kp_name2 = getattr(
79                 config.CONF, 'cinder_keypair_name') + '_2' + self.guid
80             self.logger.info("Creating keypair with name: '%s'", kp_name2)
81             self.keypair2 = self.cloud.create_keypair(kp_name2)
82             self.logger.debug("keypair: %s", self.keypair2)
83             self.logger.debug("private_key: %s", self.keypair2.private_key)
84             with open(self.key2_filename, 'w') as private_key2_file:
85                 private_key2_file.write(self.keypair2.private_key)
86
87             # Creating security group
88             self.sec = self.cloud.create_security_group(
89                 getattr(config.CONF, 'cinder_sg_name') + self.guid,
90                 getattr(config.CONF, 'cinder_sg_desc'))
91             self.cloud.create_security_group_rule(
92                 self.sec.id, port_range_min='22', port_range_max='22',
93                 protocol='tcp', direction='ingress')
94             self.cloud.create_security_group_rule(
95                 self.sec.id, port_range_min='22', port_range_max='22',
96                 protocol='tcp', direction='egress')
97             self.cloud.create_security_group_rule(
98                 self.sec.id, protocol='icmp', direction='ingress')
99
100             # Creating VM 1
101             vm1_name = "{}-{}-{}".format(
102                 getattr(config.CONF, 'cinder_vm_name_1'), "ssh", self.guid)
103             self.logger.info(
104                 "Creating VM 1 instance with name: '%s'", vm1_name)
105             self.vm1 = self.cloud.create_server(
106                 vm1_name, image=self.image.id, flavor=self.flavor.id,
107                 key_name=self.keypair1.id,
108                 auto_ip=False, wait=True,
109                 timeout=getattr(config.CONF, 'cinder_vm_boot_timeout'),
110                 network=self.network.id,
111                 security_groups=[self.sec.id])
112             self.logger.debug("vm1: %s", self.vm2)
113             self.fip1 = self.cloud.create_floating_ip(
114                 network=self.ext_net.id, server=self.vm1)
115             self.logger.debug("floating_ip1: %s", self.fip1)
116             self.vm1 = self.cloud.wait_for_server(self.vm1, auto_ip=False)
117             self.cloud.attach_volume(self.vm1, self.volume)
118
119             # Creating VM 2
120             vm2_name = "{}-{}-{}".format(
121                 getattr(config.CONF, 'cinder_vm_name_2'), "ssh", self.guid)
122             self.logger.info(
123                 "Creating VM 2 instance with name: '%s'", vm2_name)
124             self.vm2 = self.cloud.create_server(
125                 vm2_name, image=self.image.id, flavor=self.flavor.id,
126                 key_name=self.keypair2.id,
127                 auto_ip=False, wait=True,
128                 timeout=getattr(config.CONF, 'cinder_vm_boot_timeout'),
129                 network=self.network.id,
130                 security_groups=[self.sec.id])
131             self.logger.debug("vm2: %s", self.vm2)
132             self.fip2 = self.cloud.create_floating_ip(
133                 network=self.ext_net.id, server=self.vm2)
134             self.logger.debug("floating_ip2: %s", self.fip2)
135             self.vm2 = self.cloud.wait_for_server(self.vm2, auto_ip=False)
136
137             return self.execute()
138         except Exception:  # pylint: disable=broad-except
139             self.logger.exception('Unexpected error running cinder_ssh')
140             return testcase.TestCase.EX_RUN_ERROR
141
142     def write_data(self):
143         time.sleep(10)
144         write_data_script = pkg_resources.resource_filename(
145             'functest.opnfv_tests.openstack.cinder', 'write_data.sh')
146         cmd = '. ~/write_data.sh '
147         username = getattr(config.CONF, 'openstack_image_user')
148         destination_path = '/home/' + username
149         self.ssh.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
150         self.ssh.connect(
151             self.vm1.public_v4,
152             username=username,
153             key_filename=self.key1_filename,
154             timeout=getattr(config.CONF, 'cinder_vm_ssh_connect_timeout'))
155         try:
156             scp = SCPClient(self.ssh.get_transport())
157             scp.put(write_data_script, remote_path=destination_path)
158         except Exception:  # pylint: disable=broad-except
159             self.logger.error("File not transfered!")
160             return testcase.TestCase.EX_RUN_ERROR
161
162         self.logger.debug("ssh: %s", self.ssh)
163         self.ssh.exec_command('chmod +x ~/write_data.sh')
164         (_, stdout, _) = self.ssh.exec_command(cmd)
165         self.logger.debug("volume_write output: %s", stdout.read())
166
167         return stdout.channel.recv_exit_status()
168
169     def read_data(self):
170         assert self.cloud
171         # Detach volume from VM 1
172         self.logger.info("Detach volume from VM 1")
173         self.cloud.detach_volume(self.vm1, self.volume)
174         # Attach volume to VM 2
175         self.logger.info("Attach volume to VM 2")
176         self.cloud.attach_volume(self.vm2, self.volume)
177         # Check volume data
178         time.sleep(10)
179         read_data_script = pkg_resources.resource_filename(
180             'functest.opnfv_tests.openstack.cinder', 'read_data.sh')
181         cmd = '. ~/read_data.sh '
182         username = getattr(config.CONF, 'openstack_image_user')
183         destination_path = '/home/' + username
184         self.ssh.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
185         self.ssh.connect(
186             self.vm2.public_v4,
187             username=username,
188             key_filename=self.key2_filename,
189             timeout=getattr(config.CONF, 'cinder_vm_ssh_connect_timeout'))
190         try:
191             scp = SCPClient(self.ssh.get_transport())
192             scp.put(read_data_script, remote_path=destination_path)
193         except Exception:  # pylint: disable=broad-except
194             self.logger.error("File not transfered!")
195             return testcase.TestCase.EX_RUN_ERROR
196         self.logger.debug("ssh: %s", self.ssh)
197         self.ssh.exec_command('chmod +x ~/read_data.sh')
198         (_, stdout, _) = self.ssh.exec_command(cmd)
199         self.logger.debug("read volume output: %s", stdout.read())
200
201         return stdout.channel.recv_exit_status()
202
203     def clean(self):
204         assert self.cloud
205         os.remove(self.key1_filename)
206         os.remove(self.key2_filename)
207         self.cloud.delete_server(
208             self.vm1, wait=True,
209             timeout=getattr(config.CONF, 'cinder_vm_delete_timeout'))
210         self.cloud.delete_server(
211             self.vm2, wait=True,
212             timeout=getattr(config.CONF, 'cinder_vm_delete_timeout'))
213         self.cloud.delete_security_group(self.sec.id)
214         self.cloud.delete_keypair(self.keypair1.id)
215         self.cloud.delete_keypair(self.keypair2.id)
216         self.cloud.delete_floating_ip(self.fip1.id)
217         self.cloud.delete_floating_ip(self.fip2.id)
218         super(CinderCheck, self).clean()