Debian Codegraph @

mistral_tempest_tests/tests/scenario/engine/actions/v2/test_ssh_actions.py

raw
1 # Copyright 2015 - Mirantis, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import os
16 from os import path
17 import testtools
18 import time
19
20 from oslo_log import log as logging
21 from oslo_serialization import jsonutils
22 from paramiko import ssh_exception
23 from tempest import config
24 from tempest.lib import decorators
25 from tempest.lib import exceptions
26
27 from mistral_tempest_tests.tests import base
28 from mistral_tempest_tests.tests import ssh_utils
29 from mistral_tempest_tests.tests import utils
30
31
32 LOG = logging.getLogger(__name__)
33 CONF = config.CONF
34 SSH_KEYS_DIRECTORY = path.expanduser("~/.ssh/")
35
36
37 class SSHActionsTestsV2(base.TestCaseAdvanced):
38
39 _service = 'workflowv2'
40
41 def _create_security_group_rule_ssh(self):
42 sec_groups = (
43 self.mgr.compute_security_groups_client.
44 list_security_groups()
45 )
46 sec_groups = sec_groups['security_groups']
47
48 default_group = next(
49 g for g in sec_groups if g['name'] == 'default'
50 )
51
52 rule = (
53 self.mgr.compute_security_group_rules_client
54 .create_security_group_rule(
55 parent_group_id=default_group['id'],
56 ip_protocol="tcp",
57 from_port=22,
58 to_port=22,
59 cidr="0.0.0.0/0"
60 )
61 )
62
63 self.ssh_rule_id = rule['security_group_rule']['id']
64
65 def _create_server(self, server_name, **kwargs):
66 return self.mgr.servers_client.create_server(
67 name=server_name,
68 imageRef=CONF.compute.image_ref,
69 flavorRef=CONF.compute.flavor_ref,
70 **kwargs
71 ).get('server')
72
73 def _associate_floating_ip_to_server(self, server_id):
74 fl_ip_client = self.mgr.compute_floating_ips_client
75
76 all_ips = fl_ip_client.list_floating_ips().get(
77 'floating_ips'
78 )
79 free_ips = list(
80 [fl_ip for fl_ip in all_ips if fl_ip['instance_id'] is None]
81 )
82
83 if free_ips:
84 ip = free_ips[0]['ip']
85 else:
86 # Allocate new floating ip.
87 ip = fl_ip_client.create_floating_ip()['floating_ip']['ip']
88
89 # Associate IP.
90 fl_ip_client.associate_floating_ip_to_server(
91 floating_ip=ip,
92 server_id=server_id
93 )
94
95 return ip
96
97 @staticmethod
98 def _wait_until_server_up(server_ip, timeout=120, delay=2):
99 seconds_remain = timeout
100
101 LOG.info("Waiting server SSH [IP=%s]...", server_ip)
102
103 while seconds_remain > 0:
104 try:
105 ssh_utils.execute_command('cd', server_ip, None)
106 except ssh_exception.SSHException:
107 LOG.info("Server %s: SSH service is ready.")
108 return
109 except Exception as e:
110 LOG.info(str(e))
111 seconds_remain -= delay
112 time.sleep(delay)
113 else:
114 return
115
116 raise Exception(
117 "Failed waiting until server's '%s' SSH is up." % server_ip
118 )
119
120 def _wait_until_server_active(self, server_id, timeout=60, delay=2):
121 seconds_remain = timeout
122
123 LOG.info("Waiting server [id=%s]...", server_id)
124
125 while seconds_remain > 0:
126 server_info = self.mgr.servers_client.show_server(server_id)
127 if server_info['server']['status'] == 'ACTIVE':
128 return
129
130 seconds_remain -= delay
131 time.sleep(delay)
132
133 raise Exception(
134 "Failed waiting until server %s is active." % server_id
135 )
136
137 def _wait_until_server_delete(self, server_id, timeout=60, delay=2):
138 seconds_remain = timeout
139
140 LOG.info("Deleting server [id=%s]...", server_id)
141
142 while seconds_remain > 0:
143 try:
144 self.mgr.servers_client.show_server(server_id)
145 seconds_remain -= delay
146 time.sleep(delay)
147 except exceptions.NotFound:
148 return
149
150 raise RuntimeError("Server delete timeout!")
151
152 def setUp(self):
153 super(SSHActionsTestsV2, self).setUp()
154
155 # Modify security group for accessing VM via SSH.
156 self._create_security_group_rule_ssh()
157
158 # Create keypair (public and private keys).
159 self.private_key, self.public_key = utils.generate_key_pair()
160 self.key_name = 'mistral-functional-tests-key'
161
162 self.key_dir = SSH_KEYS_DIRECTORY
163
164 self.key_path = self.key_dir + self.key_name
165
166 utils.save_text_to(
167 self.private_key,
168 self.key_path,
169 overwrite=True
170 )
171
172 LOG.info("Private key saved to %s", self.key_path)
173
174 # Create keypair in nova.
175 self.mgr.keypairs_client.create_keypair(
176 name=self.key_name,
177 public_key=self.public_key
178 )
179
180 # Start servers and provide key_name.
181 # Note: start public vm only after starting the guest one,
182 # so we can track public vm launching using ssh, but can't
183 # do the same with guest VM.
184 self.guest_vm = self._create_server(
185 'mistral-guest-vm',
186 key_name=self.key_name
187 )
188 self.public_vm = self._create_server(
189 'mistral-public-vm',
190 key_name=self.key_name
191 )
192
193 self._wait_until_server_active(self.public_vm['id'])
194
195 self.public_vm_ip = self._associate_floating_ip_to_server(
196 self.public_vm['id']
197 )
198
199 # Wait until server is up.
200 self._wait_until_server_up(self.public_vm_ip)
201
202 # Update servers info.
203 self.public_vm = self.mgr.servers_client.show_server(
204 self.public_vm['id']
205 ).get('server')
206
207 self.guest_vm = self.mgr.servers_client.show_server(
208 self.guest_vm['id']
209 ).get('server')
210
211 def tearDown(self):
212 mgr = self.mgr
213
214 fl_ip_client = mgr.compute_floating_ips_client
215 fl_ip_client.disassociate_floating_ip_from_server(
216 self.public_vm_ip,
217 self.public_vm['id']
218 )
219
220 mgr.servers_client.delete_server(self.public_vm['id'])
221 mgr.servers_client.delete_server(self.guest_vm['id'])
222
223 self._wait_until_server_delete(self.public_vm['id'])
224 self._wait_until_server_delete(self.guest_vm['id'])
225
226 mgr.keypairs_client.delete_keypair(self.key_name)
227
228 mgr.compute_security_group_rules_client.delete_security_group_rule(
229 self.ssh_rule_id
230 )
231 os.remove(self.key_path)
232
233 super(SSHActionsTestsV2, self).tearDown()
234
235 @decorators.attr(type='sanity')
236 @testtools.skip('https://bugs.launchpad.net/mistral/+bug/1822969')
237 @decorators.idempotent_id('3e12a2ad-5b10-46b0-ae1f-ed34d3cc6ae2')
238 def test_run_ssh_action(self):
239 input_data = {
240 'cmd': 'hostname',
241 'host': self.public_vm_ip,
242 'username': CONF.validation.image_ssh_user,
243 'private_key_filename': self.key_path
244 }
245
246 resp, body = self.client.create_action_execution(
247 {
248 'name': 'std.ssh',
249 'input': jsonutils.dump_as_bytes(input_data)
250 }
251 )
252
253 self.assertEqual(201, resp.status)
254
255 output = jsonutils.loads(body['output'])
256
257 self.assertIn(self.public_vm['name'], output['result'])
258
259 @decorators.attr(type='sanity')
260 @testtools.skip('https://bugs.launchpad.net/mistral/+bug/1822969')
261 @decorators.idempotent_id('6c09fb04-70b4-43a6-b5f8-a53ca92e66e0')
262 def test_run_ssh_proxied_action(self):
263 guest_vm_ip = self.guest_vm['addresses'].popitem()[1][0]['addr']
264
265 input_data = {
266 'cmd': 'hostname',
267 'host': guest_vm_ip,
268 'username': CONF.validation.image_ssh_user,
269 'private_key_filename': self.key_path,
270 'gateway_host': self.public_vm_ip,
271 'gateway_username': CONF.validation.image_ssh_user
272 }
273
274 resp, body = self.client.create_action_execution(
275 {
276 'name': 'std.ssh_proxied',
277 'input': jsonutils.dump_as_bytes(input_data)
278 }
279 )
280
281 self.assertEqual(201, resp.status)
282
283 output = jsonutils.loads(body['output'])
284
285 self.assertIn(self.guest_vm['name'], output['result'])