blob: 66115a779c0095dbacd18d9ef2e9edfe2473068b [file] [log] [blame]
Steve Baker450aa7f2014-08-25 10:37:27 +12001# Licensed under the Apache License, Version 2.0 (the "License"); you may
2# not use this file except in compliance with the License. You may obtain
3# a copy of the License at
4#
5# http://www.apache.org/licenses/LICENSE-2.0
6#
7# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10# License for the specific language governing permissions and limitations
11# under the License.
12
Steve Baker450aa7f2014-08-25 10:37:27 +120013import random
14import re
Steve Baker450aa7f2014-08-25 10:37:27 +120015import subprocess
Steve Baker450aa7f2014-08-25 10:37:27 +120016import time
17
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020018import fixtures
Steve Baker450aa7f2014-08-25 10:37:27 +120019from heatclient import exc as heat_exceptions
Thomas Hervedb36c092017-03-23 11:20:14 +010020from keystoneauth1 import exceptions as kc_exceptions
Mark Vanderwiel6d8e0862015-10-15 12:51:07 -050021from neutronclient.common import exceptions as network_exceptions
Steve Baker24641292015-03-13 10:47:50 +130022from oslo_log import log as logging
Jens Rosenboom4f069fb2015-02-18 14:19:07 +010023from oslo_utils import timeutils
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020024import six
Sirushti Murugesan4920fda2015-04-22 00:35:26 +053025from six.moves import urllib
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020026import testscenarios
27import testtools
Steve Baker450aa7f2014-08-25 10:37:27 +120028
rabid2916d02017-09-22 18:19:24 +053029from heat_tempest_plugin.common import exceptions
30from heat_tempest_plugin.common import remote_client
rabid2916d02017-09-22 18:19:24 +053031from heat_tempest_plugin.services import clients
Zane Bitterb4acd962018-01-18 12:08:23 -050032from tempest import config
Steve Baker450aa7f2014-08-25 10:37:27 +120033
34LOG = logging.getLogger(__name__)
Angus Salkeld24043702014-11-21 08:49:26 +100035_LOG_FORMAT = "%(levelname)8s [%(name)s] %(message)s"
rabi82b71282018-03-08 11:08:36 +053036_resource_types = None
Steve Baker450aa7f2014-08-25 10:37:27 +120037
38
Angus Salkeld08514ad2015-02-06 10:08:31 +100039def call_until_true(duration, sleep_for, func, *args, **kwargs):
Peter Razumovskyf0ac9582015-09-24 16:49:03 +030040 """Call the function until it returns True or the duration elapsed.
41
Steve Baker450aa7f2014-08-25 10:37:27 +120042 Call the given function until it returns True (and return True) or
43 until the specified duration (in seconds) elapses (and return
44 False).
45
46 :param func: A zero argument callable that returns True on success.
47 :param duration: The number of seconds for which to attempt a
48 successful call of the function.
49 :param sleep_for: The number of seconds to sleep after an unsuccessful
50 invocation of the function.
51 """
52 now = time.time()
53 timeout = now + duration
54 while now < timeout:
Angus Salkeld08514ad2015-02-06 10:08:31 +100055 if func(*args, **kwargs):
Steve Baker450aa7f2014-08-25 10:37:27 +120056 return True
57 LOG.debug("Sleeping for %d seconds", sleep_for)
58 time.sleep(sleep_for)
59 now = time.time()
60 return False
61
62
rabi32201342017-11-17 22:57:58 +053063def isotime(at):
64 if at is None:
65 return None
66 return at.strftime('%Y-%m-%dT%H:%M:%SZ')
67
68
Steve Baker450aa7f2014-08-25 10:37:27 +120069def rand_name(name=''):
ricolina4eb53d2017-04-24 23:51:09 +080070 randbits = six.text_type(random.randint(1, 0x7fffffff))
Steve Baker450aa7f2014-08-25 10:37:27 +120071 if name:
72 return name + '-' + randbits
73 else:
74 return randbits
75
76
Zane Bitterf407e102017-10-05 14:19:32 -040077def requires_convergence(test_method):
78 '''Decorator for convergence-only tests.
79
80 The decorated test will be skipped when convergence is disabled.
81 '''
rabif89752b2017-11-18 22:14:30 +053082 plugin = config.CONF.heat_plugin
rabi94a520a2017-11-17 22:49:17 +053083 convergence_enabled = plugin.convergence_engine_enabled
Zane Bitterf407e102017-10-05 14:19:32 -040084 skipper = testtools.skipUnless(convergence_enabled,
85 "Convergence-only tests are disabled")
86 return skipper(test_method)
87
88
rabi82b71282018-03-08 11:08:36 +053089def requires_resource_type(resource_type):
90 '''Decorator for tests requiring a resource type.
91
92 The decorated test will be skipped when the resource type is not available.
93 '''
94 def decorator(test_method):
95 conf = getattr(config.CONF, 'heat_plugin', None)
96 if not conf or conf.auth_url is None:
97 return test_method
98
99 global _resource_types
100 if not _resource_types:
101 manager = clients.ClientManager(conf)
102 obj_rtypes = manager.orchestration_client.resource_types.list()
103 _resource_types = list(t.resource_type for t in obj_rtypes)
104 rtype_available = resource_type and resource_type in _resource_types
105 skipper = testtools.skipUnless(
106 rtype_available,
107 "%s resource type not available, skipping test." % resource_type)
108 return skipper(test_method)
109 return decorator
110
111
Rabi Mishrad6b25352018-10-17 13:11:05 +0530112def requires_service_type(service_type):
113 '''Decorator for tests requiring a specific service being available.
114
115 The decorated test will be skipped when a service is not available.
116 '''
117 def decorator(test_method):
118 conf = getattr(config.CONF, 'heat_plugin', None)
119 if not conf or conf.auth_url is None:
120 return test_method
121
122 manager = clients.ClientManager(conf)
123 try:
124 manager.identity_client.get_endpoint_url(
125 service_type, conf.region, conf.endpoint_type)
126 except kc_exceptions.EndpointNotFound:
127 skipper = testtools.skip(
128 "%s service not available, skipping test." % service_type)
129 return skipper(test_method)
130 else:
131 return test_method
132 return decorator
133
134
Rabi Mishra144bdc62019-01-10 17:00:57 +0530135def _check_require(group, feature, test_method):
136 features_group = getattr(config.CONF, group, None)
137 if not features_group:
138 return test_method
139 feature_enabled = features_group.get(feature, True)
140 skipper = testtools.skipUnless(feature_enabled,
141 "%s - Feature not enabled." % feature)
142 return skipper(test_method)
143
144
rabi876449a2018-03-15 21:56:49 +0530145def requires_feature(feature):
146 '''Decorator for tests requring specific feature.
147
148 The decorated test will be skipped when a specific feature is disabled.
149 '''
150 def decorator(test_method):
Rabi Mishra144bdc62019-01-10 17:00:57 +0530151 return _check_require('heat_features_enabled', feature, test_method)
152 return decorator
153
154
155def requires_service_feature(service, feature):
156 '''Decorator for tests requring specific service feature enabled in tempest.
157
158 The decorated test will be skipped when a specific feature is disabled.
159 '''
160 def decorator(test_method):
161 group = service + '_feature_enabled'
162 return _check_require(group, feature, test_method)
rabi876449a2018-03-15 21:56:49 +0530163 return decorator
164
165
Andrea Frittolid908bef2018-02-22 11:29:53 +0000166class HeatIntegrationTest(testtools.testcase.WithAttributes,
167 testscenarios.WithScenarios,
Angus Salkeld95f65a22014-11-24 12:38:30 +1000168 testtools.TestCase):
Steve Baker450aa7f2014-08-25 10:37:27 +1200169
170 def setUp(self):
171 super(HeatIntegrationTest, self).setUp()
172
Takashi Kajinamic4b871a2022-07-04 11:42:06 +0900173 if not config.CONF.service_available.heat:
174 raise self.skipException("Heat is not available")
175
rabif89752b2017-11-18 22:14:30 +0530176 self.conf = config.CONF.heat_plugin
Steve Baker450aa7f2014-08-25 10:37:27 +1200177
178 self.assertIsNotNone(self.conf.auth_url,
179 'No auth_url configured')
180 self.assertIsNotNone(self.conf.username,
181 'No username configured')
182 self.assertIsNotNone(self.conf.password,
183 'No password configured')
rabifd98a472016-05-24 10:18:33 +0530184 self.setup_clients(self.conf)
185 self.useFixture(fixtures.FakeLogger(format=_LOG_FORMAT))
rabifd98a472016-05-24 10:18:33 +0530186 if self.conf.disable_ssl_certificate_validation:
187 self.verify_cert = False
188 else:
189 self.verify_cert = self.conf.ca_file or True
Steve Baker450aa7f2014-08-25 10:37:27 +1200190
Steve Bakerb752e912016-08-01 22:05:37 +0000191 def setup_clients(self, conf, admin_credentials=False):
192 self.manager = clients.ClientManager(conf, admin_credentials)
Steve Baker450aa7f2014-08-25 10:37:27 +1200193 self.identity_client = self.manager.identity_client
194 self.orchestration_client = self.manager.orchestration_client
195 self.compute_client = self.manager.compute_client
196 self.network_client = self.manager.network_client
197 self.volume_client = self.manager.volume_client
Angus Salkeld4408da32015-02-03 18:53:30 +1000198 self.object_client = self.manager.object_client
rabid69f0312017-10-26 14:52:52 +0530199 self.metric_client = self.manager.metric_client
rabifd98a472016-05-24 10:18:33 +0530200
201 self.client = self.orchestration_client
202
203 def setup_clients_for_admin(self):
Steve Bakerb752e912016-08-01 22:05:37 +0000204 self.setup_clients(self.conf, True)
Steve Baker450aa7f2014-08-25 10:37:27 +1200205
Steve Baker450aa7f2014-08-25 10:37:27 +1200206 def get_remote_client(self, server_or_ip, username, private_key=None):
207 if isinstance(server_or_ip, six.string_types):
208 ip = server_or_ip
209 else:
210 network_name_for_ssh = self.conf.network_for_ssh
211 ip = server_or_ip.networks[network_name_for_ssh][0]
212 if private_key is None:
213 private_key = self.keypair.private_key
214 linux_client = remote_client.RemoteClient(ip, username,
215 pkey=private_key,
216 conf=self.conf)
217 try:
218 linux_client.validate_authentication()
219 except exceptions.SSHTimeout:
liyi09461f72017-03-21 12:17:51 +0800220 LOG.exception('ssh connection to %s failed', ip)
Steve Baker450aa7f2014-08-25 10:37:27 +1200221 raise
222
223 return linux_client
224
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400225 def check_connectivity(self, check_ip):
226 def try_connect(ip):
227 try:
Sirushti Murugesan4920fda2015-04-22 00:35:26 +0530228 urllib.request.urlopen('http://%s/' % ip)
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400229 return True
230 except IOError:
231 return False
232
233 timeout = self.conf.connectivity_timeout
234 elapsed_time = 0
235 while not try_connect(check_ip):
236 time.sleep(10)
237 elapsed_time += 10
238 if elapsed_time > timeout:
239 raise exceptions.TimeoutException()
240
Steve Baker450aa7f2014-08-25 10:37:27 +1200241 def _log_console_output(self, servers=None):
242 if not servers:
243 servers = self.compute_client.servers.list()
244 for server in servers:
Pavlo Shchelokovskyy6f9aafa2021-03-09 14:43:05 +0200245 LOG.info('Server %s', server)
Steve Baker24641292015-03-13 10:47:50 +1300246 LOG.info('Console output for %s', server.id)
247 LOG.info(server.get_console_output())
Steve Baker450aa7f2014-08-25 10:37:27 +1200248
Steve Baker450aa7f2014-08-25 10:37:27 +1200249 def create_keypair(self, client=None, name=None):
250 if client is None:
251 client = self.compute_client
252 if name is None:
253 name = rand_name('heat-keypair')
254 keypair = client.keypairs.create(name)
255 self.assertEqual(keypair.name, name)
256
257 def delete_keypair():
258 keypair.delete()
259
260 self.addCleanup(delete_keypair)
261 return keypair
262
Sergey Krayneva265c132015-02-13 03:51:03 -0500263 def assign_keypair(self):
264 if self.conf.keypair_name:
265 self.keypair = None
266 self.keypair_name = self.conf.keypair_name
267 else:
268 self.keypair = self.create_keypair()
269 self.keypair_name = self.keypair.id
270
Steve Baker450aa7f2014-08-25 10:37:27 +1200271 @classmethod
272 def _stack_rand_name(cls):
273 return rand_name(cls.__name__)
274
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400275 def _get_network(self, net_name=None):
276 if net_name is None:
277 net_name = self.conf.fixed_network_name
Steve Baker450aa7f2014-08-25 10:37:27 +1200278 networks = self.network_client.list_networks()
279 for net in networks['networks']:
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400280 if net['name'] == net_name:
Steve Baker450aa7f2014-08-25 10:37:27 +1200281 return net
282
Mark Vanderwiel6d8e0862015-10-15 12:51:07 -0500283 def is_network_extension_supported(self, extension_alias):
284 try:
285 self.network_client.show_extension(extension_alias)
286 except network_exceptions.NeutronClientException:
287 return False
288 return True
289
Steve Baker450aa7f2014-08-25 10:37:27 +1200290 @staticmethod
Angus Salkelda89a0282015-07-24 15:47:38 +1000291 def _stack_output(stack, output_key, validate_errors=True):
Steve Baker450aa7f2014-08-25 10:37:27 +1200292 """Return a stack output value for a given key."""
Angus Salkelda89a0282015-07-24 15:47:38 +1000293 value = None
294 for o in stack.outputs:
295 if validate_errors and 'output_error' in o:
296 # scan for errors in the stack output.
297 raise ValueError(
298 'Unexpected output errors in %s : %s' % (
299 output_key, o['output_error']))
300 if o['output_key'] == output_key:
301 value = o['output_value']
302 return value
Steve Baker450aa7f2014-08-25 10:37:27 +1200303
304 def _ping_ip_address(self, ip_address, should_succeed=True):
305 cmd = ['ping', '-c1', '-w1', ip_address]
306
307 def ping():
308 proc = subprocess.Popen(cmd,
309 stdout=subprocess.PIPE,
310 stderr=subprocess.PIPE)
311 proc.wait()
312 return (proc.returncode == 0) == should_succeed
313
314 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000315 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200316
Angus Salkelda7500d12015-04-10 15:44:07 +1000317 def _wait_for_all_resource_status(self, stack_identifier,
318 status, failure_pattern='^.*_FAILED$',
319 success_on_not_found=False):
320 for res in self.client.resources.list(stack_identifier):
321 self._wait_for_resource_status(
322 stack_identifier, res.resource_name,
323 status, failure_pattern=failure_pattern,
324 success_on_not_found=success_on_not_found)
325
Steve Baker450aa7f2014-08-25 10:37:27 +1200326 def _wait_for_resource_status(self, stack_identifier, resource_name,
327 status, failure_pattern='^.*_FAILED$',
328 success_on_not_found=False):
329 """Waits for a Resource to reach a given status."""
330 fail_regexp = re.compile(failure_pattern)
331 build_timeout = self.conf.build_timeout
332 build_interval = self.conf.build_interval
333
334 start = timeutils.utcnow()
335 while timeutils.delta_seconds(start,
336 timeutils.utcnow()) < build_timeout:
337 try:
338 res = self.client.resources.get(
339 stack_identifier, resource_name)
340 except heat_exceptions.HTTPNotFound:
341 if success_on_not_found:
342 return
343 # ignore this, as the resource may not have
344 # been created yet
345 else:
346 if res.resource_status == status:
347 return
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530348 wait_for_action = status.split('_')[0]
349 resource_action = res.resource_status.split('_')[0]
350 if (resource_action == wait_for_action and
351 fail_regexp.search(res.resource_status)):
Steve Baker450aa7f2014-08-25 10:37:27 +1200352 raise exceptions.StackResourceBuildErrorException(
353 resource_name=res.resource_name,
354 stack_identifier=stack_identifier,
355 resource_status=res.resource_status,
356 resource_status_reason=res.resource_status_reason)
357 time.sleep(build_interval)
358
359 message = ('Resource %s failed to reach %s status within '
360 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400361 (resource_name, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200362 raise exceptions.TimeoutException(message)
363
Rabi Mishra87be9b42016-02-15 14:15:50 +0530364 def verify_resource_status(self, stack_identifier, resource_name,
365 status='CREATE_COMPLETE'):
366 try:
367 res = self.client.resources.get(stack_identifier, resource_name)
368 except heat_exceptions.HTTPNotFound:
369 return False
370 return res.resource_status == status
371
rabi5eaa4962017-08-31 10:55:13 +0530372 def _verify_status(self, stack, stack_identifier, status,
373 fail_regexp, is_action_cancelled=False):
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530374 if stack.stack_status == status:
Zane Bitter8a142e32018-07-31 19:40:54 -0400375 if status == 'DELETE_COMPLETE' and stack.deletion_time is None:
Thomas Herve0e8567e2016-09-22 15:07:37 +0200376 # Wait for deleted_time to be filled, so that we have more
377 # confidence the operation is finished.
378 return False
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530379 else:
380 return True
381
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530382 wait_for_action = status.split('_')[0]
383 if (stack.action == wait_for_action and
384 fail_regexp.search(stack.stack_status)):
Zane Bitter8a142e32018-07-31 19:40:54 -0400385 raise exceptions.StackBuildErrorException(
386 stack_identifier=stack_identifier,
387 stack_status=stack.stack_status,
388 stack_status_reason=stack.stack_status_reason)
389
390 return False
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530391
Steve Baker450aa7f2014-08-25 10:37:27 +1200392 def _wait_for_stack_status(self, stack_identifier, status,
Sergey Kraynev89082a32015-09-04 04:42:33 -0400393 failure_pattern=None,
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530394 success_on_not_found=False,
395 signal_required=False,
rabi5eaa4962017-08-31 10:55:13 +0530396 resources_to_signal=None,
Pavlo Shchelokovskyy6f9aafa2021-03-09 14:43:05 +0200397 is_action_cancelled=False,
398 log_nova_servers=False):
Peter Razumovskyf0ac9582015-09-24 16:49:03 +0300399 """Waits for a Stack to reach a given status.
Steve Baker450aa7f2014-08-25 10:37:27 +1200400
401 Note this compares the full $action_$status, e.g
402 CREATE_COMPLETE, not just COMPLETE which is exposed
403 via the status property of Stack in heatclient
404 """
Sergey Kraynev89082a32015-09-04 04:42:33 -0400405 if failure_pattern:
406 fail_regexp = re.compile(failure_pattern)
407 elif 'FAILED' in status:
408 # If we're looking for e.g CREATE_FAILED, COMPLETE is unexpected.
409 fail_regexp = re.compile('^.*_COMPLETE$')
410 else:
411 fail_regexp = re.compile('^.*_FAILED$')
Steve Baker450aa7f2014-08-25 10:37:27 +1200412 build_timeout = self.conf.build_timeout
413 build_interval = self.conf.build_interval
414
415 start = timeutils.utcnow()
416 while timeutils.delta_seconds(start,
417 timeutils.utcnow()) < build_timeout:
418 try:
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500419 stack = self.client.stacks.get(stack_identifier,
420 resolve_outputs=False)
Steve Baker450aa7f2014-08-25 10:37:27 +1200421 except heat_exceptions.HTTPNotFound:
422 if success_on_not_found:
423 return
424 # ignore this, as the resource may not have
425 # been created yet
426 else:
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530427 if self._verify_status(stack, stack_identifier, status,
rabi5eaa4962017-08-31 10:55:13 +0530428 fail_regexp, is_action_cancelled):
Steve Baker450aa7f2014-08-25 10:37:27 +1200429 return
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530430 if signal_required:
431 self.signal_resources(resources_to_signal)
Steve Baker450aa7f2014-08-25 10:37:27 +1200432 time.sleep(build_interval)
433
434 message = ('Stack %s failed to reach %s status within '
435 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400436 (stack_identifier, status, build_timeout))
Pavlo Shchelokovskyy6f9aafa2021-03-09 14:43:05 +0200437 if log_nova_servers:
438 self._log_nova_servers(stack_identifier)
Steve Baker450aa7f2014-08-25 10:37:27 +1200439 raise exceptions.TimeoutException(message)
440
Pavlo Shchelokovskyy6f9aafa2021-03-09 14:43:05 +0200441 def _log_nova_servers(self, stack_identifier):
442 server_resources = self.client.resources.list(
443 stack_identifier,
444 type="OS::Nova::Server",
445 nested_depth=999)
446 servers = list(self.compute_client.servers.get(s.physical_resource_id)
447 for s in server_resources)
448 if not servers:
449 LOG.info("No OS::Nova::Server resources found in stack %s",
450 stack_identifier)
451 return
452 self._log_console_output(servers=servers)
453
Steve Baker450aa7f2014-08-25 10:37:27 +1200454 def _stack_delete(self, stack_identifier):
455 try:
Thomas Herve3eab2942015-10-22 17:29:21 +0200456 self._handle_in_progress(self.client.stacks.delete,
457 stack_identifier)
Steve Baker450aa7f2014-08-25 10:37:27 +1200458 except heat_exceptions.HTTPNotFound:
459 pass
460 self._wait_for_stack_status(
461 stack_identifier, 'DELETE_COMPLETE',
462 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000463
Thomas Herve3eab2942015-10-22 17:29:21 +0200464 def _handle_in_progress(self, fn, *args, **kwargs):
465 build_timeout = self.conf.build_timeout
466 build_interval = self.conf.build_interval
467 start = timeutils.utcnow()
468 while timeutils.delta_seconds(start,
469 timeutils.utcnow()) < build_timeout:
470 try:
471 fn(*args, **kwargs)
472 except heat_exceptions.HTTPConflict as ex:
473 # FIXME(sirushtim): Wait a little for the stack lock to be
474 # released and hopefully, the stack should be usable again.
475 if ex.error['error']['type'] != 'ActionInProgress':
476 raise ex
477
478 time.sleep(build_interval)
479 else:
480 break
481
Steven Hardy23284b62015-10-01 19:03:42 +0100482 def update_stack(self, stack_identifier, template=None, environment=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000483 files=None, parameters=None, tags=None,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530484 expected_status='UPDATE_COMPLETE',
Steven Hardy23284b62015-10-01 19:03:42 +0100485 disable_rollback=True,
Pavlo Shchelokovskyy6f9aafa2021-03-09 14:43:05 +0200486 existing=False,
487 log_nova_servers=False):
Steven Hardyc9efd972014-11-20 11:31:55 +0000488 env = environment or {}
489 env_files = files or {}
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500490 parameters = parameters or {}
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530491
Thomas Herve3eab2942015-10-22 17:29:21 +0200492 self._handle_in_progress(
493 self.client.stacks.update,
494 stack_id=stack_identifier,
Thomas Herve3eab2942015-10-22 17:29:21 +0200495 template=template,
496 files=env_files,
497 disable_rollback=disable_rollback,
498 parameters=parameters,
499 environment=env,
500 tags=tags,
501 existing=existing)
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530502
Rakesh H Sa3325d62015-04-04 19:42:29 +0530503 kwargs = {'stack_identifier': stack_identifier,
Pavlo Shchelokovskyy6f9aafa2021-03-09 14:43:05 +0200504 'status': expected_status,
505 'log_nova_servers': log_nova_servers}
Rakesh H Sa3325d62015-04-04 19:42:29 +0530506 if expected_status in ['ROLLBACK_COMPLETE']:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530507 # To trigger rollback you would intentionally fail the stack
508 # Hence check for rollback failures
509 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
510
511 self._wait_for_stack_status(**kwargs)
Steven Hardyc9efd972014-11-20 11:31:55 +0000512
rabi5eaa4962017-08-31 10:55:13 +0530513 def cancel_update_stack(self, stack_identifier, rollback=True,
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300514 expected_status='ROLLBACK_COMPLETE'):
515
516 stack_name = stack_identifier.split('/')[0]
517
rabi5eaa4962017-08-31 10:55:13 +0530518 if rollback:
519 self.client.actions.cancel_update(stack_name)
520 else:
521 self.client.actions.cancel_without_rollback(stack_name)
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300522
523 kwargs = {'stack_identifier': stack_identifier,
524 'status': expected_status}
rabi5eaa4962017-08-31 10:55:13 +0530525 if expected_status == 'UPDATE_FAILED':
526 kwargs['is_action_cancelled'] = True
527
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300528 if expected_status in ['ROLLBACK_COMPLETE']:
529 # To trigger rollback you would intentionally fail the stack
530 # Hence check for rollback failures
531 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
532
533 self._wait_for_stack_status(**kwargs)
534
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500535 def preview_update_stack(self, stack_identifier, template,
536 environment=None, files=None, parameters=None,
Steven Hardye6de2d62015-12-07 15:59:09 +0000537 tags=None, disable_rollback=True,
538 show_nested=False):
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500539 env = environment or {}
540 env_files = files or {}
541 parameters = parameters or {}
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500542
543 return self.client.stacks.preview_update(
544 stack_id=stack_identifier,
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500545 template=template,
546 files=env_files,
547 disable_rollback=disable_rollback,
548 parameters=parameters,
549 environment=env,
Steven Hardye6de2d62015-12-07 15:59:09 +0000550 tags=tags,
551 show_nested=show_nested
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500552 )
553
Steven Hardy03da0742015-03-19 00:13:17 -0400554 def assert_resource_is_a_stack(self, stack_identifier, res_name,
555 wait=False):
556 build_timeout = self.conf.build_timeout
557 build_interval = self.conf.build_interval
558 start = timeutils.utcnow()
559 while timeutils.delta_seconds(start,
560 timeutils.utcnow()) < build_timeout:
561 time.sleep(build_interval)
562 try:
563 nested_identifier = self._get_nested_identifier(
564 stack_identifier, res_name)
565 except Exception:
566 # We may have to wait, if the create is in-progress
567 if wait:
568 time.sleep(build_interval)
569 else:
570 raise
571 else:
572 return nested_identifier
573
574 def _get_nested_identifier(self, stack_identifier, res_name):
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000575 rsrc = self.client.resources.get(stack_identifier, res_name)
576 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
577 nested_href = nested_link[0]['href']
578 nested_id = nested_href.split('/')[-1]
579 nested_identifier = '/'.join(nested_href.split('/')[-2:])
580 self.assertEqual(rsrc.physical_resource_id, nested_id)
581
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500582 nested_stack = self.client.stacks.get(nested_id, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000583 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
584 nested_stack.id)
585 self.assertEqual(nested_identifier, nested_identifier2)
586 parent_id = stack_identifier.split("/")[-1]
587 self.assertEqual(parent_id, nested_stack.parent)
588 return nested_identifier
589
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530590 def group_nested_identifier(self, stack_identifier,
591 group_name):
592 # Get the nested stack identifier from a group resource
593 rsrc = self.client.resources.get(stack_identifier, group_name)
594 physical_resource_id = rsrc.physical_resource_id
595
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500596 nested_stack = self.client.stacks.get(physical_resource_id,
597 resolve_outputs=False)
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530598 nested_identifier = '%s/%s' % (nested_stack.stack_name,
599 nested_stack.id)
600 parent_id = stack_identifier.split("/")[-1]
601 self.assertEqual(parent_id, nested_stack.parent)
602 return nested_identifier
603
604 def list_group_resources(self, stack_identifier,
605 group_name, minimal=True):
606 nested_identifier = self.group_nested_identifier(stack_identifier,
607 group_name)
608 if minimal:
609 return self.list_resources(nested_identifier)
610 return self.client.resources.list(nested_identifier)
611
Steven Hardyc9efd972014-11-20 11:31:55 +0000612 def list_resources(self, stack_identifier):
613 resources = self.client.resources.list(stack_identifier)
614 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000615
Steven Hardyd448dae2016-06-14 14:57:28 +0100616 def get_resource_stack_id(self, r):
617 stack_link = [l for l in r.links if l.get('rel') == 'stack'][0]
618 return stack_link['href'].split("/")[-1]
619
Botond Zoltáne0b7aa12017-03-28 08:42:16 +0200620 def get_physical_resource_id(self, stack_identifier, resource_name):
621 try:
622 resource = self.client.resources.get(
623 stack_identifier, resource_name)
624 return resource.physical_resource_id
625 except Exception:
626 raise Exception('Resource (%s) not found in stack (%s)!' %
627 (stack_identifier, resource_name))
628
629 def get_stack_output(self, stack_identifier, output_key,
630 validate_errors=True):
631 stack = self.client.stacks.get(stack_identifier)
632 return self._stack_output(stack, output_key, validate_errors)
633
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530634 def check_input_values(self, group_resources, key, value):
635 # Check inputs for deployment and derived config
636 for r in group_resources:
637 d = self.client.software_deployments.get(
638 r.physical_resource_id)
639 self.assertEqual({key: value}, d.input_values)
640 c = self.client.software_configs.get(
641 d.config_id)
642 foo_input_c = [i for i in c.inputs if i.get('name') == key][0]
643 self.assertEqual(value, foo_input_c.get('value'))
644
645 def signal_resources(self, resources):
646 # Signal all IN_PROGRESS resources
647 for r in resources:
648 if 'IN_PROGRESS' in r.resource_status:
649 stack_id = self.get_resource_stack_id(r)
650 self.client.resources.signal(stack_id, r.resource_name)
651
Steven Hardyf2c82c02014-11-20 14:02:17 +0000652 def stack_create(self, stack_name=None, template=None, files=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000653 parameters=None, environment=None, tags=None,
654 expected_status='CREATE_COMPLETE',
Jay Dobies39c4ce42015-11-04 10:49:08 -0500655 disable_rollback=True, enable_cleanup=True,
Pavlo Shchelokovskyy6f9aafa2021-03-09 14:43:05 +0200656 environment_files=None, timeout=None,
657 log_nova_servers=False):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000658 name = stack_name or self._stack_rand_name()
659 templ = template or self.template
660 templ_files = files or {}
661 params = parameters or {}
662 env = environment or {}
rabi6ce8d962017-07-10 16:40:12 +0530663 timeout_mins = timeout or self.conf.build_timeout
Steven Hardyf2c82c02014-11-20 14:02:17 +0000664 self.client.stacks.create(
665 stack_name=name,
666 template=templ,
667 files=templ_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530668 disable_rollback=disable_rollback,
Steven Hardyf2c82c02014-11-20 14:02:17 +0000669 parameters=params,
Sabeen Syed277ea692015-02-04 23:30:02 +0000670 environment=env,
Jay Dobies39c4ce42015-11-04 10:49:08 -0500671 tags=tags,
rabi6ce8d962017-07-10 16:40:12 +0530672 environment_files=environment_files,
673 timeout_mins=timeout_mins
Steven Hardyf2c82c02014-11-20 14:02:17 +0000674 )
rabic570e0f2017-10-26 13:07:13 +0530675 if enable_cleanup:
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200676 self.addCleanup(self._stack_delete, name)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000677
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500678 stack = self.client.stacks.get(name, resolve_outputs=False)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000679 stack_identifier = '%s/%s' % (name, stack.id)
Rakesh H Sa3325d62015-04-04 19:42:29 +0530680 kwargs = {'stack_identifier': stack_identifier,
Pavlo Shchelokovskyy6f9aafa2021-03-09 14:43:05 +0200681 'status': expected_status,
682 'log_nova_servers': log_nova_servers}
Steve Bakerf6c8f122015-02-10 13:54:46 +1300683 if expected_status:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530684 if expected_status in ['ROLLBACK_COMPLETE']:
685 # To trigger rollback you would intentionally fail the stack
686 # Hence check for rollback failures
687 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
688 self._wait_for_stack_status(**kwargs)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000689 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000690
691 def stack_adopt(self, stack_name=None, files=None,
692 parameters=None, environment=None, adopt_data=None,
693 wait_for_status='ADOPT_COMPLETE'):
Rabi Mishra477efc92015-07-31 13:01:45 +0530694 if (self.conf.skip_test_stack_action_list and
695 'ADOPT' in self.conf.skip_test_stack_action_list):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530696 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000697 name = stack_name or self._stack_rand_name()
698 templ_files = files or {}
699 params = parameters or {}
700 env = environment or {}
701 self.client.stacks.create(
702 stack_name=name,
703 files=templ_files,
704 disable_rollback=True,
705 parameters=params,
706 environment=env,
707 adopt_stack_data=adopt_data,
708 )
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200709 self.addCleanup(self._stack_delete, name)
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500710 stack = self.client.stacks.get(name, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000711 stack_identifier = '%s/%s' % (name, stack.id)
712 self._wait_for_stack_status(stack_identifier, wait_for_status)
713 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530714
715 def stack_abandon(self, stack_id):
Rabi Mishra477efc92015-07-31 13:01:45 +0530716 if (self.conf.skip_test_stack_action_list and
717 'ABANDON' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200718 self.addCleanup(self._stack_delete, stack_id)
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530719 self.skipTest('Testing Stack abandon disabled in conf, skipping')
720 info = self.client.stacks.abandon(stack_id=stack_id)
721 return info
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500722
rabi90b3ab42017-05-04 13:02:28 +0530723 def stack_snapshot(self, stack_id,
724 wait_for_status='SNAPSHOT_COMPLETE'):
725 snapshot = self.client.stacks.snapshot(stack_id=stack_id)
726 self._wait_for_stack_status(stack_id, wait_for_status)
727 return snapshot['id']
728
729 def stack_restore(self, stack_id, snapshot_id,
730 wait_for_status='RESTORE_COMPLETE'):
731 self.client.stacks.restore(stack_id, snapshot_id)
732 self._wait_for_stack_status(stack_id, wait_for_status)
733
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500734 def stack_suspend(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530735 if (self.conf.skip_test_stack_action_list and
736 'SUSPEND' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200737 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530738 self.skipTest('Testing Stack suspend disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530739 self._handle_in_progress(self.client.actions.suspend, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000740 # improve debugging by first checking the resource's state.
741 self._wait_for_all_resource_status(stack_identifier,
742 'SUSPEND_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500743 self._wait_for_stack_status(stack_identifier, 'SUSPEND_COMPLETE')
744
745 def stack_resume(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530746 if (self.conf.skip_test_stack_action_list and
747 'RESUME' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200748 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530749 self.skipTest('Testing Stack resume disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530750 self._handle_in_progress(self.client.actions.resume, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000751 # improve debugging by first checking the resource's state.
752 self._wait_for_all_resource_status(stack_identifier,
753 'RESUME_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500754 self._wait_for_stack_status(stack_identifier, 'RESUME_COMPLETE')
Steven Hardy03da0742015-03-19 00:13:17 -0400755
756 def wait_for_event_with_reason(self, stack_identifier, reason,
757 rsrc_name=None, num_expected=1):
758 build_timeout = self.conf.build_timeout
759 build_interval = self.conf.build_interval
760 start = timeutils.utcnow()
761 while timeutils.delta_seconds(start,
762 timeutils.utcnow()) < build_timeout:
763 try:
764 rsrc_events = self.client.events.list(stack_identifier,
765 resource_name=rsrc_name)
766 except heat_exceptions.HTTPNotFound:
liyi09461f72017-03-21 12:17:51 +0800767 LOG.debug("No events yet found for %s", rsrc_name)
Steven Hardy03da0742015-03-19 00:13:17 -0400768 else:
769 matched = [e for e in rsrc_events
770 if e.resource_status_reason == reason]
771 if len(matched) == num_expected:
772 return matched
773 time.sleep(build_interval)
Rakesh H Sc5735a82016-04-28 15:38:09 +0530774
Thomas Hervea6afca82017-04-10 23:44:26 +0200775 def check_autoscale_complete(self, stack_id, expected_num, parent_stack,
rabi55c0f752018-02-07 09:21:28 +0530776 group_name):
Rakesh H Sc5735a82016-04-28 15:38:09 +0530777 res_list = self.client.resources.list(stack_id)
778 all_res_complete = all(res.resource_status in ('UPDATE_COMPLETE',
779 'CREATE_COMPLETE')
780 for res in res_list)
781 all_res = len(res_list) == expected_num
Thomas Hervea6afca82017-04-10 23:44:26 +0200782 if all_res and all_res_complete:
rabi55c0f752018-02-07 09:21:28 +0530783 metadata = self.client.resources.metadata(parent_stack, group_name)
Thomas Hervea6afca82017-04-10 23:44:26 +0200784 return not metadata.get('scaling_in_progress')
785 return False