blob: 567f2a04b8e72a37959549a3c32a5d403e4c9028 [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
Steve Baker24641292015-03-13 10:47:50 +130021from oslo_log import log as logging
Jens Rosenboom4f069fb2015-02-18 14:19:07 +010022from oslo_utils import timeutils
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020023import testscenarios
24import testtools
Takashi Kajinamidfb97392022-05-10 00:51:14 +090025import urllib
Steve Baker450aa7f2014-08-25 10:37:27 +120026
rabid2916d02017-09-22 18:19:24 +053027from heat_tempest_plugin.common import exceptions
28from heat_tempest_plugin.common import remote_client
rabid2916d02017-09-22 18:19:24 +053029from heat_tempest_plugin.services import clients
Zane Bitterb4acd962018-01-18 12:08:23 -050030from tempest import config
Steve Baker450aa7f2014-08-25 10:37:27 +120031
32LOG = logging.getLogger(__name__)
Angus Salkeld24043702014-11-21 08:49:26 +100033_LOG_FORMAT = "%(levelname)8s [%(name)s] %(message)s"
rabi82b71282018-03-08 11:08:36 +053034_resource_types = None
Steve Baker450aa7f2014-08-25 10:37:27 +120035
36
Angus Salkeld08514ad2015-02-06 10:08:31 +100037def call_until_true(duration, sleep_for, func, *args, **kwargs):
Peter Razumovskyf0ac9582015-09-24 16:49:03 +030038 """Call the function until it returns True or the duration elapsed.
39
Steve Baker450aa7f2014-08-25 10:37:27 +120040 Call the given function until it returns True (and return True) or
41 until the specified duration (in seconds) elapses (and return
42 False).
43
44 :param func: A zero argument callable that returns True on success.
45 :param duration: The number of seconds for which to attempt a
46 successful call of the function.
47 :param sleep_for: The number of seconds to sleep after an unsuccessful
48 invocation of the function.
49 """
50 now = time.time()
51 timeout = now + duration
52 while now < timeout:
Angus Salkeld08514ad2015-02-06 10:08:31 +100053 if func(*args, **kwargs):
Steve Baker450aa7f2014-08-25 10:37:27 +120054 return True
55 LOG.debug("Sleeping for %d seconds", sleep_for)
56 time.sleep(sleep_for)
57 now = time.time()
58 return False
59
60
rabi32201342017-11-17 22:57:58 +053061def isotime(at):
62 if at is None:
63 return None
64 return at.strftime('%Y-%m-%dT%H:%M:%SZ')
65
66
Steve Baker450aa7f2014-08-25 10:37:27 +120067def rand_name(name=''):
Takashi Kajinamidfb97392022-05-10 00:51:14 +090068 randbits = str(random.randint(1, 0x7fffffff))
Steve Baker450aa7f2014-08-25 10:37:27 +120069 if name:
70 return name + '-' + randbits
71 else:
72 return randbits
73
74
Zane Bitterf407e102017-10-05 14:19:32 -040075def requires_convergence(test_method):
76 '''Decorator for convergence-only tests.
77
78 The decorated test will be skipped when convergence is disabled.
79 '''
rabif89752b2017-11-18 22:14:30 +053080 plugin = config.CONF.heat_plugin
rabi94a520a2017-11-17 22:49:17 +053081 convergence_enabled = plugin.convergence_engine_enabled
Zane Bitterf407e102017-10-05 14:19:32 -040082 skipper = testtools.skipUnless(convergence_enabled,
83 "Convergence-only tests are disabled")
84 return skipper(test_method)
85
86
rabi82b71282018-03-08 11:08:36 +053087def requires_resource_type(resource_type):
88 '''Decorator for tests requiring a resource type.
89
90 The decorated test will be skipped when the resource type is not available.
91 '''
92 def decorator(test_method):
93 conf = getattr(config.CONF, 'heat_plugin', None)
94 if not conf or conf.auth_url is None:
95 return test_method
96
97 global _resource_types
98 if not _resource_types:
99 manager = clients.ClientManager(conf)
100 obj_rtypes = manager.orchestration_client.resource_types.list()
101 _resource_types = list(t.resource_type for t in obj_rtypes)
102 rtype_available = resource_type and resource_type in _resource_types
103 skipper = testtools.skipUnless(
104 rtype_available,
105 "%s resource type not available, skipping test." % resource_type)
106 return skipper(test_method)
107 return decorator
108
109
Takashi Kajinami1e6b3882022-08-21 11:37:20 +0900110def requires_service(service):
111 '''Decorator for tests requiring a specific service being available.
112
113 The decorated test will be skipped when a service is not available. This
114 based on the [service_available] options implemented in tempest
115 '''
116 def decorator(test_method):
117 if not getattr(config.CONF.service_available, service, True):
118 skipper = testtools.skip(
119 "%s service not available, skipping test." % service)
120 return skipper(test_method)
121 else:
122 return test_method
123 return decorator
124
125
Rabi Mishrad6b25352018-10-17 13:11:05 +0530126def requires_service_type(service_type):
127 '''Decorator for tests requiring a specific service being available.
128
129 The decorated test will be skipped when a service is not available.
130 '''
131 def decorator(test_method):
132 conf = getattr(config.CONF, 'heat_plugin', None)
133 if not conf or conf.auth_url is None:
134 return test_method
135
136 manager = clients.ClientManager(conf)
137 try:
138 manager.identity_client.get_endpoint_url(
139 service_type, conf.region, conf.endpoint_type)
140 except kc_exceptions.EndpointNotFound:
141 skipper = testtools.skip(
Takashi Kajinami1e6b3882022-08-21 11:37:20 +0900142 "%s service type not available, skipping test." % service_type)
Rabi Mishrad6b25352018-10-17 13:11:05 +0530143 return skipper(test_method)
144 else:
145 return test_method
146 return decorator
147
148
Rabi Mishra144bdc62019-01-10 17:00:57 +0530149def _check_require(group, feature, test_method):
150 features_group = getattr(config.CONF, group, None)
151 if not features_group:
152 return test_method
153 feature_enabled = features_group.get(feature, True)
154 skipper = testtools.skipUnless(feature_enabled,
155 "%s - Feature not enabled." % feature)
156 return skipper(test_method)
157
158
rabi876449a2018-03-15 21:56:49 +0530159def requires_feature(feature):
160 '''Decorator for tests requring specific feature.
161
162 The decorated test will be skipped when a specific feature is disabled.
163 '''
164 def decorator(test_method):
Rabi Mishra144bdc62019-01-10 17:00:57 +0530165 return _check_require('heat_features_enabled', feature, test_method)
166 return decorator
167
168
169def requires_service_feature(service, feature):
Takashi Kajinami70e516a2024-01-20 18:56:19 +0900170 '''Decorator for tests requring specific service feature
Rabi Mishra144bdc62019-01-10 17:00:57 +0530171
172 The decorated test will be skipped when a specific feature is disabled.
173 '''
174 def decorator(test_method):
175 group = service + '_feature_enabled'
176 return _check_require(group, feature, test_method)
rabi876449a2018-03-15 21:56:49 +0530177 return decorator
178
179
Andrea Frittolid908bef2018-02-22 11:29:53 +0000180class HeatIntegrationTest(testtools.testcase.WithAttributes,
181 testscenarios.WithScenarios,
Angus Salkeld95f65a22014-11-24 12:38:30 +1000182 testtools.TestCase):
Steve Baker450aa7f2014-08-25 10:37:27 +1200183
184 def setUp(self):
185 super(HeatIntegrationTest, self).setUp()
186
Takashi Kajinamic4b871a2022-07-04 11:42:06 +0900187 if not config.CONF.service_available.heat:
188 raise self.skipException("Heat is not available")
189
rabif89752b2017-11-18 22:14:30 +0530190 self.conf = config.CONF.heat_plugin
Steve Baker450aa7f2014-08-25 10:37:27 +1200191
192 self.assertIsNotNone(self.conf.auth_url,
193 'No auth_url configured')
194 self.assertIsNotNone(self.conf.username,
195 'No username configured')
196 self.assertIsNotNone(self.conf.password,
197 'No password configured')
rabifd98a472016-05-24 10:18:33 +0530198 self.setup_clients(self.conf)
199 self.useFixture(fixtures.FakeLogger(format=_LOG_FORMAT))
rabifd98a472016-05-24 10:18:33 +0530200 if self.conf.disable_ssl_certificate_validation:
201 self.verify_cert = False
202 else:
203 self.verify_cert = self.conf.ca_file or True
Steve Baker450aa7f2014-08-25 10:37:27 +1200204
Steve Bakerb752e912016-08-01 22:05:37 +0000205 def setup_clients(self, conf, admin_credentials=False):
206 self.manager = clients.ClientManager(conf, admin_credentials)
Steve Baker450aa7f2014-08-25 10:37:27 +1200207 self.identity_client = self.manager.identity_client
208 self.orchestration_client = self.manager.orchestration_client
209 self.compute_client = self.manager.compute_client
210 self.network_client = self.manager.network_client
211 self.volume_client = self.manager.volume_client
Angus Salkeld4408da32015-02-03 18:53:30 +1000212 self.object_client = self.manager.object_client
rabid69f0312017-10-26 14:52:52 +0530213 self.metric_client = self.manager.metric_client
rabifd98a472016-05-24 10:18:33 +0530214
215 self.client = self.orchestration_client
216
217 def setup_clients_for_admin(self):
Steve Bakerb752e912016-08-01 22:05:37 +0000218 self.setup_clients(self.conf, True)
Steve Baker450aa7f2014-08-25 10:37:27 +1200219
Steve Baker450aa7f2014-08-25 10:37:27 +1200220 def get_remote_client(self, server_or_ip, username, private_key=None):
Takashi Kajinamidfb97392022-05-10 00:51:14 +0900221 if isinstance(server_or_ip, str):
Steve Baker450aa7f2014-08-25 10:37:27 +1200222 ip = server_or_ip
223 else:
224 network_name_for_ssh = self.conf.network_for_ssh
225 ip = server_or_ip.networks[network_name_for_ssh][0]
226 if private_key is None:
227 private_key = self.keypair.private_key
228 linux_client = remote_client.RemoteClient(ip, username,
229 pkey=private_key,
230 conf=self.conf)
231 try:
232 linux_client.validate_authentication()
233 except exceptions.SSHTimeout:
liyi09461f72017-03-21 12:17:51 +0800234 LOG.exception('ssh connection to %s failed', ip)
Steve Baker450aa7f2014-08-25 10:37:27 +1200235 raise
236
237 return linux_client
238
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400239 def check_connectivity(self, check_ip):
240 def try_connect(ip):
241 try:
Sirushti Murugesan4920fda2015-04-22 00:35:26 +0530242 urllib.request.urlopen('http://%s/' % ip)
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400243 return True
244 except IOError:
245 return False
246
247 timeout = self.conf.connectivity_timeout
248 elapsed_time = 0
249 while not try_connect(check_ip):
250 time.sleep(10)
251 elapsed_time += 10
252 if elapsed_time > timeout:
253 raise exceptions.TimeoutException()
254
Steve Baker450aa7f2014-08-25 10:37:27 +1200255 def _log_console_output(self, servers=None):
256 if not servers:
257 servers = self.compute_client.servers.list()
258 for server in servers:
Steve Baker24641292015-03-13 10:47:50 +1300259 LOG.info('Console output for %s', server.id)
260 LOG.info(server.get_console_output())
Steve Baker450aa7f2014-08-25 10:37:27 +1200261
Steve Baker450aa7f2014-08-25 10:37:27 +1200262 def create_keypair(self, client=None, name=None):
263 if client is None:
264 client = self.compute_client
265 if name is None:
266 name = rand_name('heat-keypair')
267 keypair = client.keypairs.create(name)
268 self.assertEqual(keypair.name, name)
269
270 def delete_keypair():
271 keypair.delete()
272
273 self.addCleanup(delete_keypair)
274 return keypair
275
Sergey Krayneva265c132015-02-13 03:51:03 -0500276 def assign_keypair(self):
277 if self.conf.keypair_name:
278 self.keypair = None
279 self.keypair_name = self.conf.keypair_name
280 else:
281 self.keypair = self.create_keypair()
282 self.keypair_name = self.keypair.id
283
Steve Baker450aa7f2014-08-25 10:37:27 +1200284 @classmethod
285 def _stack_rand_name(cls):
286 return rand_name(cls.__name__)
287
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400288 def _get_network(self, net_name=None):
289 if net_name is None:
290 net_name = self.conf.fixed_network_name
Steve Baker450aa7f2014-08-25 10:37:27 +1200291 networks = self.network_client.list_networks()
292 for net in networks['networks']:
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400293 if net['name'] == net_name:
Steve Baker450aa7f2014-08-25 10:37:27 +1200294 return net
295
296 @staticmethod
Angus Salkelda89a0282015-07-24 15:47:38 +1000297 def _stack_output(stack, output_key, validate_errors=True):
Steve Baker450aa7f2014-08-25 10:37:27 +1200298 """Return a stack output value for a given key."""
Angus Salkelda89a0282015-07-24 15:47:38 +1000299 value = None
300 for o in stack.outputs:
301 if validate_errors and 'output_error' in o:
302 # scan for errors in the stack output.
303 raise ValueError(
304 'Unexpected output errors in %s : %s' % (
305 output_key, o['output_error']))
306 if o['output_key'] == output_key:
307 value = o['output_value']
308 return value
Steve Baker450aa7f2014-08-25 10:37:27 +1200309
310 def _ping_ip_address(self, ip_address, should_succeed=True):
311 cmd = ['ping', '-c1', '-w1', ip_address]
312
313 def ping():
314 proc = subprocess.Popen(cmd,
315 stdout=subprocess.PIPE,
316 stderr=subprocess.PIPE)
317 proc.wait()
318 return (proc.returncode == 0) == should_succeed
319
320 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000321 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200322
Angus Salkelda7500d12015-04-10 15:44:07 +1000323 def _wait_for_all_resource_status(self, stack_identifier,
324 status, failure_pattern='^.*_FAILED$',
325 success_on_not_found=False):
326 for res in self.client.resources.list(stack_identifier):
327 self._wait_for_resource_status(
328 stack_identifier, res.resource_name,
329 status, failure_pattern=failure_pattern,
330 success_on_not_found=success_on_not_found)
331
Steve Baker450aa7f2014-08-25 10:37:27 +1200332 def _wait_for_resource_status(self, stack_identifier, resource_name,
333 status, failure_pattern='^.*_FAILED$',
334 success_on_not_found=False):
335 """Waits for a Resource to reach a given status."""
336 fail_regexp = re.compile(failure_pattern)
337 build_timeout = self.conf.build_timeout
338 build_interval = self.conf.build_interval
339
340 start = timeutils.utcnow()
341 while timeutils.delta_seconds(start,
342 timeutils.utcnow()) < build_timeout:
343 try:
344 res = self.client.resources.get(
345 stack_identifier, resource_name)
346 except heat_exceptions.HTTPNotFound:
347 if success_on_not_found:
348 return
349 # ignore this, as the resource may not have
350 # been created yet
351 else:
352 if res.resource_status == status:
353 return
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530354 wait_for_action = status.split('_')[0]
355 resource_action = res.resource_status.split('_')[0]
356 if (resource_action == wait_for_action and
357 fail_regexp.search(res.resource_status)):
Steve Baker450aa7f2014-08-25 10:37:27 +1200358 raise exceptions.StackResourceBuildErrorException(
359 resource_name=res.resource_name,
360 stack_identifier=stack_identifier,
361 resource_status=res.resource_status,
362 resource_status_reason=res.resource_status_reason)
363 time.sleep(build_interval)
364
365 message = ('Resource %s failed to reach %s status within '
366 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400367 (resource_name, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200368 raise exceptions.TimeoutException(message)
369
Rabi Mishra87be9b42016-02-15 14:15:50 +0530370 def verify_resource_status(self, stack_identifier, resource_name,
371 status='CREATE_COMPLETE'):
372 try:
373 res = self.client.resources.get(stack_identifier, resource_name)
374 except heat_exceptions.HTTPNotFound:
375 return False
376 return res.resource_status == status
377
rabi5eaa4962017-08-31 10:55:13 +0530378 def _verify_status(self, stack, stack_identifier, status,
379 fail_regexp, is_action_cancelled=False):
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530380 if stack.stack_status == status:
Zane Bitter8a142e32018-07-31 19:40:54 -0400381 if status == 'DELETE_COMPLETE' and stack.deletion_time is None:
Thomas Herve0e8567e2016-09-22 15:07:37 +0200382 # Wait for deleted_time to be filled, so that we have more
383 # confidence the operation is finished.
384 return False
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530385 else:
386 return True
387
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530388 wait_for_action = status.split('_')[0]
389 if (stack.action == wait_for_action and
390 fail_regexp.search(stack.stack_status)):
Zane Bitter8a142e32018-07-31 19:40:54 -0400391 raise exceptions.StackBuildErrorException(
392 stack_identifier=stack_identifier,
393 stack_status=stack.stack_status,
394 stack_status_reason=stack.stack_status_reason)
395
396 return False
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530397
Steve Baker450aa7f2014-08-25 10:37:27 +1200398 def _wait_for_stack_status(self, stack_identifier, status,
Sergey Kraynev89082a32015-09-04 04:42:33 -0400399 failure_pattern=None,
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530400 success_on_not_found=False,
401 signal_required=False,
rabi5eaa4962017-08-31 10:55:13 +0530402 resources_to_signal=None,
403 is_action_cancelled=False):
Peter Razumovskyf0ac9582015-09-24 16:49:03 +0300404 """Waits for a Stack to reach a given status.
Steve Baker450aa7f2014-08-25 10:37:27 +1200405
406 Note this compares the full $action_$status, e.g
407 CREATE_COMPLETE, not just COMPLETE which is exposed
408 via the status property of Stack in heatclient
409 """
Sergey Kraynev89082a32015-09-04 04:42:33 -0400410 if failure_pattern:
411 fail_regexp = re.compile(failure_pattern)
412 elif 'FAILED' in status:
413 # If we're looking for e.g CREATE_FAILED, COMPLETE is unexpected.
414 fail_regexp = re.compile('^.*_COMPLETE$')
415 else:
416 fail_regexp = re.compile('^.*_FAILED$')
Steve Baker450aa7f2014-08-25 10:37:27 +1200417 build_timeout = self.conf.build_timeout
418 build_interval = self.conf.build_interval
419
420 start = timeutils.utcnow()
421 while timeutils.delta_seconds(start,
422 timeutils.utcnow()) < build_timeout:
423 try:
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500424 stack = self.client.stacks.get(stack_identifier,
425 resolve_outputs=False)
Steve Baker450aa7f2014-08-25 10:37:27 +1200426 except heat_exceptions.HTTPNotFound:
427 if success_on_not_found:
428 return
429 # ignore this, as the resource may not have
430 # been created yet
431 else:
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530432 if self._verify_status(stack, stack_identifier, status,
rabi5eaa4962017-08-31 10:55:13 +0530433 fail_regexp, is_action_cancelled):
Steve Baker450aa7f2014-08-25 10:37:27 +1200434 return
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530435 if signal_required:
436 self.signal_resources(resources_to_signal)
Steve Baker450aa7f2014-08-25 10:37:27 +1200437 time.sleep(build_interval)
438
439 message = ('Stack %s failed to reach %s status within '
440 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400441 (stack_identifier, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200442 raise exceptions.TimeoutException(message)
443
444 def _stack_delete(self, stack_identifier):
445 try:
Thomas Herve3eab2942015-10-22 17:29:21 +0200446 self._handle_in_progress(self.client.stacks.delete,
447 stack_identifier)
Steve Baker450aa7f2014-08-25 10:37:27 +1200448 except heat_exceptions.HTTPNotFound:
449 pass
450 self._wait_for_stack_status(
451 stack_identifier, 'DELETE_COMPLETE',
452 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000453
Thomas Herve3eab2942015-10-22 17:29:21 +0200454 def _handle_in_progress(self, fn, *args, **kwargs):
455 build_timeout = self.conf.build_timeout
456 build_interval = self.conf.build_interval
457 start = timeutils.utcnow()
458 while timeutils.delta_seconds(start,
459 timeutils.utcnow()) < build_timeout:
460 try:
461 fn(*args, **kwargs)
462 except heat_exceptions.HTTPConflict as ex:
463 # FIXME(sirushtim): Wait a little for the stack lock to be
464 # released and hopefully, the stack should be usable again.
465 if ex.error['error']['type'] != 'ActionInProgress':
466 raise ex
467
468 time.sleep(build_interval)
469 else:
470 break
471
Steven Hardy23284b62015-10-01 19:03:42 +0100472 def update_stack(self, stack_identifier, template=None, environment=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000473 files=None, parameters=None, tags=None,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530474 expected_status='UPDATE_COMPLETE',
Steven Hardy23284b62015-10-01 19:03:42 +0100475 disable_rollback=True,
476 existing=False):
Steven Hardyc9efd972014-11-20 11:31:55 +0000477 env = environment or {}
478 env_files = files or {}
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500479 parameters = parameters or {}
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530480
Thomas Herve3eab2942015-10-22 17:29:21 +0200481 self._handle_in_progress(
482 self.client.stacks.update,
483 stack_id=stack_identifier,
Thomas Herve3eab2942015-10-22 17:29:21 +0200484 template=template,
485 files=env_files,
486 disable_rollback=disable_rollback,
487 parameters=parameters,
488 environment=env,
489 tags=tags,
490 existing=existing)
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530491
Rakesh H Sa3325d62015-04-04 19:42:29 +0530492 kwargs = {'stack_identifier': stack_identifier,
493 'status': expected_status}
494 if expected_status in ['ROLLBACK_COMPLETE']:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530495 # To trigger rollback you would intentionally fail the stack
496 # Hence check for rollback failures
497 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
498
499 self._wait_for_stack_status(**kwargs)
Steven Hardyc9efd972014-11-20 11:31:55 +0000500
rabi5eaa4962017-08-31 10:55:13 +0530501 def cancel_update_stack(self, stack_identifier, rollback=True,
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300502 expected_status='ROLLBACK_COMPLETE'):
503
504 stack_name = stack_identifier.split('/')[0]
505
rabi5eaa4962017-08-31 10:55:13 +0530506 if rollback:
507 self.client.actions.cancel_update(stack_name)
508 else:
509 self.client.actions.cancel_without_rollback(stack_name)
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300510
511 kwargs = {'stack_identifier': stack_identifier,
512 'status': expected_status}
rabi5eaa4962017-08-31 10:55:13 +0530513 if expected_status == 'UPDATE_FAILED':
514 kwargs['is_action_cancelled'] = True
515
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300516 if expected_status in ['ROLLBACK_COMPLETE']:
517 # To trigger rollback you would intentionally fail the stack
518 # Hence check for rollback failures
519 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
520
521 self._wait_for_stack_status(**kwargs)
522
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500523 def preview_update_stack(self, stack_identifier, template,
524 environment=None, files=None, parameters=None,
Steven Hardye6de2d62015-12-07 15:59:09 +0000525 tags=None, disable_rollback=True,
526 show_nested=False):
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500527 env = environment or {}
528 env_files = files or {}
529 parameters = parameters or {}
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500530
531 return self.client.stacks.preview_update(
532 stack_id=stack_identifier,
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500533 template=template,
534 files=env_files,
535 disable_rollback=disable_rollback,
536 parameters=parameters,
537 environment=env,
Steven Hardye6de2d62015-12-07 15:59:09 +0000538 tags=tags,
539 show_nested=show_nested
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500540 )
541
Steven Hardy03da0742015-03-19 00:13:17 -0400542 def assert_resource_is_a_stack(self, stack_identifier, res_name,
543 wait=False):
544 build_timeout = self.conf.build_timeout
545 build_interval = self.conf.build_interval
546 start = timeutils.utcnow()
547 while timeutils.delta_seconds(start,
548 timeutils.utcnow()) < build_timeout:
549 time.sleep(build_interval)
550 try:
551 nested_identifier = self._get_nested_identifier(
552 stack_identifier, res_name)
553 except Exception:
554 # We may have to wait, if the create is in-progress
555 if wait:
556 time.sleep(build_interval)
557 else:
558 raise
559 else:
560 return nested_identifier
561
562 def _get_nested_identifier(self, stack_identifier, res_name):
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000563 rsrc = self.client.resources.get(stack_identifier, res_name)
564 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
565 nested_href = nested_link[0]['href']
566 nested_id = nested_href.split('/')[-1]
567 nested_identifier = '/'.join(nested_href.split('/')[-2:])
568 self.assertEqual(rsrc.physical_resource_id, nested_id)
569
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500570 nested_stack = self.client.stacks.get(nested_id, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000571 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
572 nested_stack.id)
573 self.assertEqual(nested_identifier, nested_identifier2)
574 parent_id = stack_identifier.split("/")[-1]
575 self.assertEqual(parent_id, nested_stack.parent)
576 return nested_identifier
577
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530578 def group_nested_identifier(self, stack_identifier,
579 group_name):
580 # Get the nested stack identifier from a group resource
581 rsrc = self.client.resources.get(stack_identifier, group_name)
582 physical_resource_id = rsrc.physical_resource_id
583
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500584 nested_stack = self.client.stacks.get(physical_resource_id,
585 resolve_outputs=False)
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530586 nested_identifier = '%s/%s' % (nested_stack.stack_name,
587 nested_stack.id)
588 parent_id = stack_identifier.split("/")[-1]
589 self.assertEqual(parent_id, nested_stack.parent)
590 return nested_identifier
591
592 def list_group_resources(self, stack_identifier,
593 group_name, minimal=True):
594 nested_identifier = self.group_nested_identifier(stack_identifier,
595 group_name)
596 if minimal:
597 return self.list_resources(nested_identifier)
598 return self.client.resources.list(nested_identifier)
599
Steven Hardyc9efd972014-11-20 11:31:55 +0000600 def list_resources(self, stack_identifier):
601 resources = self.client.resources.list(stack_identifier)
602 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000603
Steven Hardyd448dae2016-06-14 14:57:28 +0100604 def get_resource_stack_id(self, r):
605 stack_link = [l for l in r.links if l.get('rel') == 'stack'][0]
606 return stack_link['href'].split("/")[-1]
607
Botond Zoltáne0b7aa12017-03-28 08:42:16 +0200608 def get_physical_resource_id(self, stack_identifier, resource_name):
609 try:
610 resource = self.client.resources.get(
611 stack_identifier, resource_name)
612 return resource.physical_resource_id
613 except Exception:
614 raise Exception('Resource (%s) not found in stack (%s)!' %
615 (stack_identifier, resource_name))
616
617 def get_stack_output(self, stack_identifier, output_key,
618 validate_errors=True):
619 stack = self.client.stacks.get(stack_identifier)
620 return self._stack_output(stack, output_key, validate_errors)
621
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530622 def check_input_values(self, group_resources, key, value):
623 # Check inputs for deployment and derived config
624 for r in group_resources:
625 d = self.client.software_deployments.get(
626 r.physical_resource_id)
627 self.assertEqual({key: value}, d.input_values)
628 c = self.client.software_configs.get(
629 d.config_id)
630 foo_input_c = [i for i in c.inputs if i.get('name') == key][0]
631 self.assertEqual(value, foo_input_c.get('value'))
632
633 def signal_resources(self, resources):
634 # Signal all IN_PROGRESS resources
635 for r in resources:
636 if 'IN_PROGRESS' in r.resource_status:
637 stack_id = self.get_resource_stack_id(r)
638 self.client.resources.signal(stack_id, r.resource_name)
639
Steven Hardyf2c82c02014-11-20 14:02:17 +0000640 def stack_create(self, stack_name=None, template=None, files=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000641 parameters=None, environment=None, tags=None,
642 expected_status='CREATE_COMPLETE',
Jay Dobies39c4ce42015-11-04 10:49:08 -0500643 disable_rollback=True, enable_cleanup=True,
rabi6ce8d962017-07-10 16:40:12 +0530644 environment_files=None, timeout=None):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000645 name = stack_name or self._stack_rand_name()
646 templ = template or self.template
647 templ_files = files or {}
648 params = parameters or {}
649 env = environment or {}
rabi6ce8d962017-07-10 16:40:12 +0530650 timeout_mins = timeout or self.conf.build_timeout
Steven Hardyf2c82c02014-11-20 14:02:17 +0000651 self.client.stacks.create(
652 stack_name=name,
653 template=templ,
654 files=templ_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530655 disable_rollback=disable_rollback,
Steven Hardyf2c82c02014-11-20 14:02:17 +0000656 parameters=params,
Sabeen Syed277ea692015-02-04 23:30:02 +0000657 environment=env,
Jay Dobies39c4ce42015-11-04 10:49:08 -0500658 tags=tags,
rabi6ce8d962017-07-10 16:40:12 +0530659 environment_files=environment_files,
660 timeout_mins=timeout_mins
Steven Hardyf2c82c02014-11-20 14:02:17 +0000661 )
rabic570e0f2017-10-26 13:07:13 +0530662 if enable_cleanup:
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200663 self.addCleanup(self._stack_delete, name)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000664
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500665 stack = self.client.stacks.get(name, resolve_outputs=False)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000666 stack_identifier = '%s/%s' % (name, stack.id)
Rakesh H Sa3325d62015-04-04 19:42:29 +0530667 kwargs = {'stack_identifier': stack_identifier,
668 'status': expected_status}
Steve Bakerf6c8f122015-02-10 13:54:46 +1300669 if expected_status:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530670 if expected_status in ['ROLLBACK_COMPLETE']:
671 # To trigger rollback you would intentionally fail the stack
672 # Hence check for rollback failures
673 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
674 self._wait_for_stack_status(**kwargs)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000675 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000676
677 def stack_adopt(self, stack_name=None, files=None,
678 parameters=None, environment=None, adopt_data=None,
679 wait_for_status='ADOPT_COMPLETE'):
Rabi Mishra477efc92015-07-31 13:01:45 +0530680 if (self.conf.skip_test_stack_action_list and
681 'ADOPT' in self.conf.skip_test_stack_action_list):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530682 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000683 name = stack_name or self._stack_rand_name()
684 templ_files = files or {}
685 params = parameters or {}
686 env = environment or {}
687 self.client.stacks.create(
688 stack_name=name,
689 files=templ_files,
690 disable_rollback=True,
691 parameters=params,
692 environment=env,
693 adopt_stack_data=adopt_data,
694 )
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200695 self.addCleanup(self._stack_delete, name)
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500696 stack = self.client.stacks.get(name, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000697 stack_identifier = '%s/%s' % (name, stack.id)
698 self._wait_for_stack_status(stack_identifier, wait_for_status)
699 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530700
701 def stack_abandon(self, stack_id):
Rabi Mishra477efc92015-07-31 13:01:45 +0530702 if (self.conf.skip_test_stack_action_list and
703 'ABANDON' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200704 self.addCleanup(self._stack_delete, stack_id)
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530705 self.skipTest('Testing Stack abandon disabled in conf, skipping')
706 info = self.client.stacks.abandon(stack_id=stack_id)
707 return info
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500708
rabi90b3ab42017-05-04 13:02:28 +0530709 def stack_snapshot(self, stack_id,
710 wait_for_status='SNAPSHOT_COMPLETE'):
711 snapshot = self.client.stacks.snapshot(stack_id=stack_id)
712 self._wait_for_stack_status(stack_id, wait_for_status)
713 return snapshot['id']
714
715 def stack_restore(self, stack_id, snapshot_id,
716 wait_for_status='RESTORE_COMPLETE'):
717 self.client.stacks.restore(stack_id, snapshot_id)
718 self._wait_for_stack_status(stack_id, wait_for_status)
719
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500720 def stack_suspend(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530721 if (self.conf.skip_test_stack_action_list and
722 'SUSPEND' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200723 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530724 self.skipTest('Testing Stack suspend disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530725 self._handle_in_progress(self.client.actions.suspend, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000726 # improve debugging by first checking the resource's state.
727 self._wait_for_all_resource_status(stack_identifier,
728 'SUSPEND_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500729 self._wait_for_stack_status(stack_identifier, 'SUSPEND_COMPLETE')
730
731 def stack_resume(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530732 if (self.conf.skip_test_stack_action_list and
733 'RESUME' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200734 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530735 self.skipTest('Testing Stack resume disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530736 self._handle_in_progress(self.client.actions.resume, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000737 # improve debugging by first checking the resource's state.
738 self._wait_for_all_resource_status(stack_identifier,
739 'RESUME_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500740 self._wait_for_stack_status(stack_identifier, 'RESUME_COMPLETE')
Steven Hardy03da0742015-03-19 00:13:17 -0400741
742 def wait_for_event_with_reason(self, stack_identifier, reason,
743 rsrc_name=None, num_expected=1):
744 build_timeout = self.conf.build_timeout
745 build_interval = self.conf.build_interval
746 start = timeutils.utcnow()
747 while timeutils.delta_seconds(start,
748 timeutils.utcnow()) < build_timeout:
749 try:
750 rsrc_events = self.client.events.list(stack_identifier,
751 resource_name=rsrc_name)
752 except heat_exceptions.HTTPNotFound:
liyi09461f72017-03-21 12:17:51 +0800753 LOG.debug("No events yet found for %s", rsrc_name)
Steven Hardy03da0742015-03-19 00:13:17 -0400754 else:
755 matched = [e for e in rsrc_events
756 if e.resource_status_reason == reason]
757 if len(matched) == num_expected:
758 return matched
759 time.sleep(build_interval)
Rakesh H Sc5735a82016-04-28 15:38:09 +0530760
Thomas Hervea6afca82017-04-10 23:44:26 +0200761 def check_autoscale_complete(self, stack_id, expected_num, parent_stack,
rabi55c0f752018-02-07 09:21:28 +0530762 group_name):
Rakesh H Sc5735a82016-04-28 15:38:09 +0530763 res_list = self.client.resources.list(stack_id)
764 all_res_complete = all(res.resource_status in ('UPDATE_COMPLETE',
765 'CREATE_COMPLETE')
766 for res in res_list)
767 all_res = len(res_list) == expected_num
Thomas Hervea6afca82017-04-10 23:44:26 +0200768 if all_res and all_res_complete:
rabi55c0f752018-02-07 09:21:28 +0530769 metadata = self.client.resources.metadata(parent_stack, group_name)
Thomas Hervea6afca82017-04-10 23:44:26 +0200770 return not metadata.get('scaling_in_progress')
771 return False