blob: ec3310f89f57ed673a04cd7b9158fae82dcd1cb5 [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 testscenarios
25import testtools
Takashi Kajinamidfb97392022-05-10 00:51:14 +090026import urllib
Steve Baker450aa7f2014-08-25 10:37:27 +120027
rabid2916d02017-09-22 18:19:24 +053028from heat_tempest_plugin.common import exceptions
29from heat_tempest_plugin.common import remote_client
rabid2916d02017-09-22 18:19:24 +053030from heat_tempest_plugin.services import clients
Zane Bitterb4acd962018-01-18 12:08:23 -050031from tempest import config
Steve Baker450aa7f2014-08-25 10:37:27 +120032
33LOG = logging.getLogger(__name__)
Angus Salkeld24043702014-11-21 08:49:26 +100034_LOG_FORMAT = "%(levelname)8s [%(name)s] %(message)s"
rabi82b71282018-03-08 11:08:36 +053035_resource_types = None
Steve Baker450aa7f2014-08-25 10:37:27 +120036
37
Angus Salkeld08514ad2015-02-06 10:08:31 +100038def call_until_true(duration, sleep_for, func, *args, **kwargs):
Peter Razumovskyf0ac9582015-09-24 16:49:03 +030039 """Call the function until it returns True or the duration elapsed.
40
Steve Baker450aa7f2014-08-25 10:37:27 +120041 Call the given function until it returns True (and return True) or
42 until the specified duration (in seconds) elapses (and return
43 False).
44
45 :param func: A zero argument callable that returns True on success.
46 :param duration: The number of seconds for which to attempt a
47 successful call of the function.
48 :param sleep_for: The number of seconds to sleep after an unsuccessful
49 invocation of the function.
50 """
51 now = time.time()
52 timeout = now + duration
53 while now < timeout:
Angus Salkeld08514ad2015-02-06 10:08:31 +100054 if func(*args, **kwargs):
Steve Baker450aa7f2014-08-25 10:37:27 +120055 return True
56 LOG.debug("Sleeping for %d seconds", sleep_for)
57 time.sleep(sleep_for)
58 now = time.time()
59 return False
60
61
rabi32201342017-11-17 22:57:58 +053062def isotime(at):
63 if at is None:
64 return None
65 return at.strftime('%Y-%m-%dT%H:%M:%SZ')
66
67
Steve Baker450aa7f2014-08-25 10:37:27 +120068def rand_name(name=''):
Takashi Kajinamidfb97392022-05-10 00:51:14 +090069 randbits = str(random.randint(1, 0x7fffffff))
Steve Baker450aa7f2014-08-25 10:37:27 +120070 if name:
71 return name + '-' + randbits
72 else:
73 return randbits
74
75
Zane Bitterf407e102017-10-05 14:19:32 -040076def requires_convergence(test_method):
77 '''Decorator for convergence-only tests.
78
79 The decorated test will be skipped when convergence is disabled.
80 '''
rabif89752b2017-11-18 22:14:30 +053081 plugin = config.CONF.heat_plugin
rabi94a520a2017-11-17 22:49:17 +053082 convergence_enabled = plugin.convergence_engine_enabled
Zane Bitterf407e102017-10-05 14:19:32 -040083 skipper = testtools.skipUnless(convergence_enabled,
84 "Convergence-only tests are disabled")
85 return skipper(test_method)
86
87
rabi82b71282018-03-08 11:08:36 +053088def requires_resource_type(resource_type):
89 '''Decorator for tests requiring a resource type.
90
91 The decorated test will be skipped when the resource type is not available.
92 '''
93 def decorator(test_method):
94 conf = getattr(config.CONF, 'heat_plugin', None)
95 if not conf or conf.auth_url is None:
96 return test_method
97
98 global _resource_types
99 if not _resource_types:
100 manager = clients.ClientManager(conf)
101 obj_rtypes = manager.orchestration_client.resource_types.list()
102 _resource_types = list(t.resource_type for t in obj_rtypes)
103 rtype_available = resource_type and resource_type in _resource_types
104 skipper = testtools.skipUnless(
105 rtype_available,
106 "%s resource type not available, skipping test." % resource_type)
107 return skipper(test_method)
108 return decorator
109
110
Rabi Mishrad6b25352018-10-17 13:11:05 +0530111def requires_service_type(service_type):
112 '''Decorator for tests requiring a specific service being available.
113
114 The decorated test will be skipped when a service is not available.
115 '''
116 def decorator(test_method):
117 conf = getattr(config.CONF, 'heat_plugin', None)
118 if not conf or conf.auth_url is None:
119 return test_method
120
121 manager = clients.ClientManager(conf)
122 try:
123 manager.identity_client.get_endpoint_url(
124 service_type, conf.region, conf.endpoint_type)
125 except kc_exceptions.EndpointNotFound:
126 skipper = testtools.skip(
127 "%s service not available, skipping test." % service_type)
128 return skipper(test_method)
129 else:
130 return test_method
131 return decorator
132
133
Rabi Mishra144bdc62019-01-10 17:00:57 +0530134def _check_require(group, feature, test_method):
135 features_group = getattr(config.CONF, group, None)
136 if not features_group:
137 return test_method
138 feature_enabled = features_group.get(feature, True)
139 skipper = testtools.skipUnless(feature_enabled,
140 "%s - Feature not enabled." % feature)
141 return skipper(test_method)
142
143
rabi876449a2018-03-15 21:56:49 +0530144def requires_feature(feature):
145 '''Decorator for tests requring specific feature.
146
147 The decorated test will be skipped when a specific feature is disabled.
148 '''
149 def decorator(test_method):
Rabi Mishra144bdc62019-01-10 17:00:57 +0530150 return _check_require('heat_features_enabled', feature, test_method)
151 return decorator
152
153
154def requires_service_feature(service, feature):
155 '''Decorator for tests requring specific service feature enabled in tempest.
156
157 The decorated test will be skipped when a specific feature is disabled.
158 '''
159 def decorator(test_method):
160 group = service + '_feature_enabled'
161 return _check_require(group, feature, test_method)
rabi876449a2018-03-15 21:56:49 +0530162 return decorator
163
164
Andrea Frittolid908bef2018-02-22 11:29:53 +0000165class HeatIntegrationTest(testtools.testcase.WithAttributes,
166 testscenarios.WithScenarios,
Angus Salkeld95f65a22014-11-24 12:38:30 +1000167 testtools.TestCase):
Steve Baker450aa7f2014-08-25 10:37:27 +1200168
169 def setUp(self):
170 super(HeatIntegrationTest, self).setUp()
171
Takashi Kajinamic4b871a2022-07-04 11:42:06 +0900172 if not config.CONF.service_available.heat:
173 raise self.skipException("Heat is not available")
174
rabif89752b2017-11-18 22:14:30 +0530175 self.conf = config.CONF.heat_plugin
Steve Baker450aa7f2014-08-25 10:37:27 +1200176
177 self.assertIsNotNone(self.conf.auth_url,
178 'No auth_url configured')
179 self.assertIsNotNone(self.conf.username,
180 'No username configured')
181 self.assertIsNotNone(self.conf.password,
182 'No password configured')
rabifd98a472016-05-24 10:18:33 +0530183 self.setup_clients(self.conf)
184 self.useFixture(fixtures.FakeLogger(format=_LOG_FORMAT))
rabifd98a472016-05-24 10:18:33 +0530185 if self.conf.disable_ssl_certificate_validation:
186 self.verify_cert = False
187 else:
188 self.verify_cert = self.conf.ca_file or True
Steve Baker450aa7f2014-08-25 10:37:27 +1200189
Steve Bakerb752e912016-08-01 22:05:37 +0000190 def setup_clients(self, conf, admin_credentials=False):
191 self.manager = clients.ClientManager(conf, admin_credentials)
Steve Baker450aa7f2014-08-25 10:37:27 +1200192 self.identity_client = self.manager.identity_client
193 self.orchestration_client = self.manager.orchestration_client
194 self.compute_client = self.manager.compute_client
195 self.network_client = self.manager.network_client
196 self.volume_client = self.manager.volume_client
Angus Salkeld4408da32015-02-03 18:53:30 +1000197 self.object_client = self.manager.object_client
rabid69f0312017-10-26 14:52:52 +0530198 self.metric_client = self.manager.metric_client
rabifd98a472016-05-24 10:18:33 +0530199
200 self.client = self.orchestration_client
201
202 def setup_clients_for_admin(self):
Steve Bakerb752e912016-08-01 22:05:37 +0000203 self.setup_clients(self.conf, True)
Steve Baker450aa7f2014-08-25 10:37:27 +1200204
Steve Baker450aa7f2014-08-25 10:37:27 +1200205 def get_remote_client(self, server_or_ip, username, private_key=None):
Takashi Kajinamidfb97392022-05-10 00:51:14 +0900206 if isinstance(server_or_ip, str):
Steve Baker450aa7f2014-08-25 10:37:27 +1200207 ip = server_or_ip
208 else:
209 network_name_for_ssh = self.conf.network_for_ssh
210 ip = server_or_ip.networks[network_name_for_ssh][0]
211 if private_key is None:
212 private_key = self.keypair.private_key
213 linux_client = remote_client.RemoteClient(ip, username,
214 pkey=private_key,
215 conf=self.conf)
216 try:
217 linux_client.validate_authentication()
218 except exceptions.SSHTimeout:
liyi09461f72017-03-21 12:17:51 +0800219 LOG.exception('ssh connection to %s failed', ip)
Steve Baker450aa7f2014-08-25 10:37:27 +1200220 raise
221
222 return linux_client
223
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400224 def check_connectivity(self, check_ip):
225 def try_connect(ip):
226 try:
Sirushti Murugesan4920fda2015-04-22 00:35:26 +0530227 urllib.request.urlopen('http://%s/' % ip)
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400228 return True
229 except IOError:
230 return False
231
232 timeout = self.conf.connectivity_timeout
233 elapsed_time = 0
234 while not try_connect(check_ip):
235 time.sleep(10)
236 elapsed_time += 10
237 if elapsed_time > timeout:
238 raise exceptions.TimeoutException()
239
Steve Baker450aa7f2014-08-25 10:37:27 +1200240 def _log_console_output(self, servers=None):
241 if not servers:
242 servers = self.compute_client.servers.list()
243 for server in servers:
Steve Baker24641292015-03-13 10:47:50 +1300244 LOG.info('Console output for %s', server.id)
245 LOG.info(server.get_console_output())
Steve Baker450aa7f2014-08-25 10:37:27 +1200246
Steve Baker450aa7f2014-08-25 10:37:27 +1200247 def create_keypair(self, client=None, name=None):
248 if client is None:
249 client = self.compute_client
250 if name is None:
251 name = rand_name('heat-keypair')
252 keypair = client.keypairs.create(name)
253 self.assertEqual(keypair.name, name)
254
255 def delete_keypair():
256 keypair.delete()
257
258 self.addCleanup(delete_keypair)
259 return keypair
260
Sergey Krayneva265c132015-02-13 03:51:03 -0500261 def assign_keypair(self):
262 if self.conf.keypair_name:
263 self.keypair = None
264 self.keypair_name = self.conf.keypair_name
265 else:
266 self.keypair = self.create_keypair()
267 self.keypair_name = self.keypair.id
268
Steve Baker450aa7f2014-08-25 10:37:27 +1200269 @classmethod
270 def _stack_rand_name(cls):
271 return rand_name(cls.__name__)
272
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400273 def _get_network(self, net_name=None):
274 if net_name is None:
275 net_name = self.conf.fixed_network_name
Steve Baker450aa7f2014-08-25 10:37:27 +1200276 networks = self.network_client.list_networks()
277 for net in networks['networks']:
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400278 if net['name'] == net_name:
Steve Baker450aa7f2014-08-25 10:37:27 +1200279 return net
280
Mark Vanderwiel6d8e0862015-10-15 12:51:07 -0500281 def is_network_extension_supported(self, extension_alias):
282 try:
283 self.network_client.show_extension(extension_alias)
284 except network_exceptions.NeutronClientException:
285 return False
286 return True
287
Steve Baker450aa7f2014-08-25 10:37:27 +1200288 @staticmethod
Angus Salkelda89a0282015-07-24 15:47:38 +1000289 def _stack_output(stack, output_key, validate_errors=True):
Steve Baker450aa7f2014-08-25 10:37:27 +1200290 """Return a stack output value for a given key."""
Angus Salkelda89a0282015-07-24 15:47:38 +1000291 value = None
292 for o in stack.outputs:
293 if validate_errors and 'output_error' in o:
294 # scan for errors in the stack output.
295 raise ValueError(
296 'Unexpected output errors in %s : %s' % (
297 output_key, o['output_error']))
298 if o['output_key'] == output_key:
299 value = o['output_value']
300 return value
Steve Baker450aa7f2014-08-25 10:37:27 +1200301
302 def _ping_ip_address(self, ip_address, should_succeed=True):
303 cmd = ['ping', '-c1', '-w1', ip_address]
304
305 def ping():
306 proc = subprocess.Popen(cmd,
307 stdout=subprocess.PIPE,
308 stderr=subprocess.PIPE)
309 proc.wait()
310 return (proc.returncode == 0) == should_succeed
311
312 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000313 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200314
Angus Salkelda7500d12015-04-10 15:44:07 +1000315 def _wait_for_all_resource_status(self, stack_identifier,
316 status, failure_pattern='^.*_FAILED$',
317 success_on_not_found=False):
318 for res in self.client.resources.list(stack_identifier):
319 self._wait_for_resource_status(
320 stack_identifier, res.resource_name,
321 status, failure_pattern=failure_pattern,
322 success_on_not_found=success_on_not_found)
323
Steve Baker450aa7f2014-08-25 10:37:27 +1200324 def _wait_for_resource_status(self, stack_identifier, resource_name,
325 status, failure_pattern='^.*_FAILED$',
326 success_on_not_found=False):
327 """Waits for a Resource to reach a given status."""
328 fail_regexp = re.compile(failure_pattern)
329 build_timeout = self.conf.build_timeout
330 build_interval = self.conf.build_interval
331
332 start = timeutils.utcnow()
333 while timeutils.delta_seconds(start,
334 timeutils.utcnow()) < build_timeout:
335 try:
336 res = self.client.resources.get(
337 stack_identifier, resource_name)
338 except heat_exceptions.HTTPNotFound:
339 if success_on_not_found:
340 return
341 # ignore this, as the resource may not have
342 # been created yet
343 else:
344 if res.resource_status == status:
345 return
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530346 wait_for_action = status.split('_')[0]
347 resource_action = res.resource_status.split('_')[0]
348 if (resource_action == wait_for_action and
349 fail_regexp.search(res.resource_status)):
Steve Baker450aa7f2014-08-25 10:37:27 +1200350 raise exceptions.StackResourceBuildErrorException(
351 resource_name=res.resource_name,
352 stack_identifier=stack_identifier,
353 resource_status=res.resource_status,
354 resource_status_reason=res.resource_status_reason)
355 time.sleep(build_interval)
356
357 message = ('Resource %s failed to reach %s status within '
358 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400359 (resource_name, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200360 raise exceptions.TimeoutException(message)
361
Rabi Mishra87be9b42016-02-15 14:15:50 +0530362 def verify_resource_status(self, stack_identifier, resource_name,
363 status='CREATE_COMPLETE'):
364 try:
365 res = self.client.resources.get(stack_identifier, resource_name)
366 except heat_exceptions.HTTPNotFound:
367 return False
368 return res.resource_status == status
369
rabi5eaa4962017-08-31 10:55:13 +0530370 def _verify_status(self, stack, stack_identifier, status,
371 fail_regexp, is_action_cancelled=False):
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530372 if stack.stack_status == status:
Zane Bitter8a142e32018-07-31 19:40:54 -0400373 if status == 'DELETE_COMPLETE' and stack.deletion_time is None:
Thomas Herve0e8567e2016-09-22 15:07:37 +0200374 # Wait for deleted_time to be filled, so that we have more
375 # confidence the operation is finished.
376 return False
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530377 else:
378 return True
379
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530380 wait_for_action = status.split('_')[0]
381 if (stack.action == wait_for_action and
382 fail_regexp.search(stack.stack_status)):
Zane Bitter8a142e32018-07-31 19:40:54 -0400383 raise exceptions.StackBuildErrorException(
384 stack_identifier=stack_identifier,
385 stack_status=stack.stack_status,
386 stack_status_reason=stack.stack_status_reason)
387
388 return False
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530389
Steve Baker450aa7f2014-08-25 10:37:27 +1200390 def _wait_for_stack_status(self, stack_identifier, status,
Sergey Kraynev89082a32015-09-04 04:42:33 -0400391 failure_pattern=None,
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530392 success_on_not_found=False,
393 signal_required=False,
rabi5eaa4962017-08-31 10:55:13 +0530394 resources_to_signal=None,
395 is_action_cancelled=False):
Peter Razumovskyf0ac9582015-09-24 16:49:03 +0300396 """Waits for a Stack to reach a given status.
Steve Baker450aa7f2014-08-25 10:37:27 +1200397
398 Note this compares the full $action_$status, e.g
399 CREATE_COMPLETE, not just COMPLETE which is exposed
400 via the status property of Stack in heatclient
401 """
Sergey Kraynev89082a32015-09-04 04:42:33 -0400402 if failure_pattern:
403 fail_regexp = re.compile(failure_pattern)
404 elif 'FAILED' in status:
405 # If we're looking for e.g CREATE_FAILED, COMPLETE is unexpected.
406 fail_regexp = re.compile('^.*_COMPLETE$')
407 else:
408 fail_regexp = re.compile('^.*_FAILED$')
Steve Baker450aa7f2014-08-25 10:37:27 +1200409 build_timeout = self.conf.build_timeout
410 build_interval = self.conf.build_interval
411
412 start = timeutils.utcnow()
413 while timeutils.delta_seconds(start,
414 timeutils.utcnow()) < build_timeout:
415 try:
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500416 stack = self.client.stacks.get(stack_identifier,
417 resolve_outputs=False)
Steve Baker450aa7f2014-08-25 10:37:27 +1200418 except heat_exceptions.HTTPNotFound:
419 if success_on_not_found:
420 return
421 # ignore this, as the resource may not have
422 # been created yet
423 else:
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530424 if self._verify_status(stack, stack_identifier, status,
rabi5eaa4962017-08-31 10:55:13 +0530425 fail_regexp, is_action_cancelled):
Steve Baker450aa7f2014-08-25 10:37:27 +1200426 return
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530427 if signal_required:
428 self.signal_resources(resources_to_signal)
Steve Baker450aa7f2014-08-25 10:37:27 +1200429 time.sleep(build_interval)
430
431 message = ('Stack %s failed to reach %s status within '
432 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400433 (stack_identifier, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200434 raise exceptions.TimeoutException(message)
435
436 def _stack_delete(self, stack_identifier):
437 try:
Thomas Herve3eab2942015-10-22 17:29:21 +0200438 self._handle_in_progress(self.client.stacks.delete,
439 stack_identifier)
Steve Baker450aa7f2014-08-25 10:37:27 +1200440 except heat_exceptions.HTTPNotFound:
441 pass
442 self._wait_for_stack_status(
443 stack_identifier, 'DELETE_COMPLETE',
444 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000445
Thomas Herve3eab2942015-10-22 17:29:21 +0200446 def _handle_in_progress(self, fn, *args, **kwargs):
447 build_timeout = self.conf.build_timeout
448 build_interval = self.conf.build_interval
449 start = timeutils.utcnow()
450 while timeutils.delta_seconds(start,
451 timeutils.utcnow()) < build_timeout:
452 try:
453 fn(*args, **kwargs)
454 except heat_exceptions.HTTPConflict as ex:
455 # FIXME(sirushtim): Wait a little for the stack lock to be
456 # released and hopefully, the stack should be usable again.
457 if ex.error['error']['type'] != 'ActionInProgress':
458 raise ex
459
460 time.sleep(build_interval)
461 else:
462 break
463
Steven Hardy23284b62015-10-01 19:03:42 +0100464 def update_stack(self, stack_identifier, template=None, environment=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000465 files=None, parameters=None, tags=None,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530466 expected_status='UPDATE_COMPLETE',
Steven Hardy23284b62015-10-01 19:03:42 +0100467 disable_rollback=True,
468 existing=False):
Steven Hardyc9efd972014-11-20 11:31:55 +0000469 env = environment or {}
470 env_files = files or {}
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500471 parameters = parameters or {}
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530472
Thomas Herve3eab2942015-10-22 17:29:21 +0200473 self._handle_in_progress(
474 self.client.stacks.update,
475 stack_id=stack_identifier,
Thomas Herve3eab2942015-10-22 17:29:21 +0200476 template=template,
477 files=env_files,
478 disable_rollback=disable_rollback,
479 parameters=parameters,
480 environment=env,
481 tags=tags,
482 existing=existing)
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530483
Rakesh H Sa3325d62015-04-04 19:42:29 +0530484 kwargs = {'stack_identifier': stack_identifier,
485 'status': expected_status}
486 if expected_status in ['ROLLBACK_COMPLETE']:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530487 # To trigger rollback you would intentionally fail the stack
488 # Hence check for rollback failures
489 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
490
491 self._wait_for_stack_status(**kwargs)
Steven Hardyc9efd972014-11-20 11:31:55 +0000492
rabi5eaa4962017-08-31 10:55:13 +0530493 def cancel_update_stack(self, stack_identifier, rollback=True,
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300494 expected_status='ROLLBACK_COMPLETE'):
495
496 stack_name = stack_identifier.split('/')[0]
497
rabi5eaa4962017-08-31 10:55:13 +0530498 if rollback:
499 self.client.actions.cancel_update(stack_name)
500 else:
501 self.client.actions.cancel_without_rollback(stack_name)
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300502
503 kwargs = {'stack_identifier': stack_identifier,
504 'status': expected_status}
rabi5eaa4962017-08-31 10:55:13 +0530505 if expected_status == 'UPDATE_FAILED':
506 kwargs['is_action_cancelled'] = True
507
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300508 if expected_status in ['ROLLBACK_COMPLETE']:
509 # To trigger rollback you would intentionally fail the stack
510 # Hence check for rollback failures
511 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
512
513 self._wait_for_stack_status(**kwargs)
514
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500515 def preview_update_stack(self, stack_identifier, template,
516 environment=None, files=None, parameters=None,
Steven Hardye6de2d62015-12-07 15:59:09 +0000517 tags=None, disable_rollback=True,
518 show_nested=False):
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500519 env = environment or {}
520 env_files = files or {}
521 parameters = parameters or {}
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500522
523 return self.client.stacks.preview_update(
524 stack_id=stack_identifier,
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500525 template=template,
526 files=env_files,
527 disable_rollback=disable_rollback,
528 parameters=parameters,
529 environment=env,
Steven Hardye6de2d62015-12-07 15:59:09 +0000530 tags=tags,
531 show_nested=show_nested
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500532 )
533
Steven Hardy03da0742015-03-19 00:13:17 -0400534 def assert_resource_is_a_stack(self, stack_identifier, res_name,
535 wait=False):
536 build_timeout = self.conf.build_timeout
537 build_interval = self.conf.build_interval
538 start = timeutils.utcnow()
539 while timeutils.delta_seconds(start,
540 timeutils.utcnow()) < build_timeout:
541 time.sleep(build_interval)
542 try:
543 nested_identifier = self._get_nested_identifier(
544 stack_identifier, res_name)
545 except Exception:
546 # We may have to wait, if the create is in-progress
547 if wait:
548 time.sleep(build_interval)
549 else:
550 raise
551 else:
552 return nested_identifier
553
554 def _get_nested_identifier(self, stack_identifier, res_name):
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000555 rsrc = self.client.resources.get(stack_identifier, res_name)
556 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
557 nested_href = nested_link[0]['href']
558 nested_id = nested_href.split('/')[-1]
559 nested_identifier = '/'.join(nested_href.split('/')[-2:])
560 self.assertEqual(rsrc.physical_resource_id, nested_id)
561
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500562 nested_stack = self.client.stacks.get(nested_id, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000563 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
564 nested_stack.id)
565 self.assertEqual(nested_identifier, nested_identifier2)
566 parent_id = stack_identifier.split("/")[-1]
567 self.assertEqual(parent_id, nested_stack.parent)
568 return nested_identifier
569
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530570 def group_nested_identifier(self, stack_identifier,
571 group_name):
572 # Get the nested stack identifier from a group resource
573 rsrc = self.client.resources.get(stack_identifier, group_name)
574 physical_resource_id = rsrc.physical_resource_id
575
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500576 nested_stack = self.client.stacks.get(physical_resource_id,
577 resolve_outputs=False)
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530578 nested_identifier = '%s/%s' % (nested_stack.stack_name,
579 nested_stack.id)
580 parent_id = stack_identifier.split("/")[-1]
581 self.assertEqual(parent_id, nested_stack.parent)
582 return nested_identifier
583
584 def list_group_resources(self, stack_identifier,
585 group_name, minimal=True):
586 nested_identifier = self.group_nested_identifier(stack_identifier,
587 group_name)
588 if minimal:
589 return self.list_resources(nested_identifier)
590 return self.client.resources.list(nested_identifier)
591
Steven Hardyc9efd972014-11-20 11:31:55 +0000592 def list_resources(self, stack_identifier):
593 resources = self.client.resources.list(stack_identifier)
594 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000595
Steven Hardyd448dae2016-06-14 14:57:28 +0100596 def get_resource_stack_id(self, r):
597 stack_link = [l for l in r.links if l.get('rel') == 'stack'][0]
598 return stack_link['href'].split("/")[-1]
599
Botond Zoltáne0b7aa12017-03-28 08:42:16 +0200600 def get_physical_resource_id(self, stack_identifier, resource_name):
601 try:
602 resource = self.client.resources.get(
603 stack_identifier, resource_name)
604 return resource.physical_resource_id
605 except Exception:
606 raise Exception('Resource (%s) not found in stack (%s)!' %
607 (stack_identifier, resource_name))
608
609 def get_stack_output(self, stack_identifier, output_key,
610 validate_errors=True):
611 stack = self.client.stacks.get(stack_identifier)
612 return self._stack_output(stack, output_key, validate_errors)
613
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530614 def check_input_values(self, group_resources, key, value):
615 # Check inputs for deployment and derived config
616 for r in group_resources:
617 d = self.client.software_deployments.get(
618 r.physical_resource_id)
619 self.assertEqual({key: value}, d.input_values)
620 c = self.client.software_configs.get(
621 d.config_id)
622 foo_input_c = [i for i in c.inputs if i.get('name') == key][0]
623 self.assertEqual(value, foo_input_c.get('value'))
624
625 def signal_resources(self, resources):
626 # Signal all IN_PROGRESS resources
627 for r in resources:
628 if 'IN_PROGRESS' in r.resource_status:
629 stack_id = self.get_resource_stack_id(r)
630 self.client.resources.signal(stack_id, r.resource_name)
631
Steven Hardyf2c82c02014-11-20 14:02:17 +0000632 def stack_create(self, stack_name=None, template=None, files=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000633 parameters=None, environment=None, tags=None,
634 expected_status='CREATE_COMPLETE',
Jay Dobies39c4ce42015-11-04 10:49:08 -0500635 disable_rollback=True, enable_cleanup=True,
rabi6ce8d962017-07-10 16:40:12 +0530636 environment_files=None, timeout=None):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000637 name = stack_name or self._stack_rand_name()
638 templ = template or self.template
639 templ_files = files or {}
640 params = parameters or {}
641 env = environment or {}
rabi6ce8d962017-07-10 16:40:12 +0530642 timeout_mins = timeout or self.conf.build_timeout
Steven Hardyf2c82c02014-11-20 14:02:17 +0000643 self.client.stacks.create(
644 stack_name=name,
645 template=templ,
646 files=templ_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530647 disable_rollback=disable_rollback,
Steven Hardyf2c82c02014-11-20 14:02:17 +0000648 parameters=params,
Sabeen Syed277ea692015-02-04 23:30:02 +0000649 environment=env,
Jay Dobies39c4ce42015-11-04 10:49:08 -0500650 tags=tags,
rabi6ce8d962017-07-10 16:40:12 +0530651 environment_files=environment_files,
652 timeout_mins=timeout_mins
Steven Hardyf2c82c02014-11-20 14:02:17 +0000653 )
rabic570e0f2017-10-26 13:07:13 +0530654 if enable_cleanup:
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200655 self.addCleanup(self._stack_delete, name)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000656
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500657 stack = self.client.stacks.get(name, resolve_outputs=False)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000658 stack_identifier = '%s/%s' % (name, stack.id)
Rakesh H Sa3325d62015-04-04 19:42:29 +0530659 kwargs = {'stack_identifier': stack_identifier,
660 'status': expected_status}
Steve Bakerf6c8f122015-02-10 13:54:46 +1300661 if expected_status:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530662 if expected_status in ['ROLLBACK_COMPLETE']:
663 # To trigger rollback you would intentionally fail the stack
664 # Hence check for rollback failures
665 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
666 self._wait_for_stack_status(**kwargs)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000667 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000668
669 def stack_adopt(self, stack_name=None, files=None,
670 parameters=None, environment=None, adopt_data=None,
671 wait_for_status='ADOPT_COMPLETE'):
Rabi Mishra477efc92015-07-31 13:01:45 +0530672 if (self.conf.skip_test_stack_action_list and
673 'ADOPT' in self.conf.skip_test_stack_action_list):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530674 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000675 name = stack_name or self._stack_rand_name()
676 templ_files = files or {}
677 params = parameters or {}
678 env = environment or {}
679 self.client.stacks.create(
680 stack_name=name,
681 files=templ_files,
682 disable_rollback=True,
683 parameters=params,
684 environment=env,
685 adopt_stack_data=adopt_data,
686 )
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200687 self.addCleanup(self._stack_delete, name)
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500688 stack = self.client.stacks.get(name, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000689 stack_identifier = '%s/%s' % (name, stack.id)
690 self._wait_for_stack_status(stack_identifier, wait_for_status)
691 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530692
693 def stack_abandon(self, stack_id):
Rabi Mishra477efc92015-07-31 13:01:45 +0530694 if (self.conf.skip_test_stack_action_list and
695 'ABANDON' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200696 self.addCleanup(self._stack_delete, stack_id)
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530697 self.skipTest('Testing Stack abandon disabled in conf, skipping')
698 info = self.client.stacks.abandon(stack_id=stack_id)
699 return info
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500700
rabi90b3ab42017-05-04 13:02:28 +0530701 def stack_snapshot(self, stack_id,
702 wait_for_status='SNAPSHOT_COMPLETE'):
703 snapshot = self.client.stacks.snapshot(stack_id=stack_id)
704 self._wait_for_stack_status(stack_id, wait_for_status)
705 return snapshot['id']
706
707 def stack_restore(self, stack_id, snapshot_id,
708 wait_for_status='RESTORE_COMPLETE'):
709 self.client.stacks.restore(stack_id, snapshot_id)
710 self._wait_for_stack_status(stack_id, wait_for_status)
711
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500712 def stack_suspend(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530713 if (self.conf.skip_test_stack_action_list and
714 'SUSPEND' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200715 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530716 self.skipTest('Testing Stack suspend disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530717 self._handle_in_progress(self.client.actions.suspend, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000718 # improve debugging by first checking the resource's state.
719 self._wait_for_all_resource_status(stack_identifier,
720 'SUSPEND_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500721 self._wait_for_stack_status(stack_identifier, 'SUSPEND_COMPLETE')
722
723 def stack_resume(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530724 if (self.conf.skip_test_stack_action_list and
725 'RESUME' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200726 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530727 self.skipTest('Testing Stack resume disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530728 self._handle_in_progress(self.client.actions.resume, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000729 # improve debugging by first checking the resource's state.
730 self._wait_for_all_resource_status(stack_identifier,
731 'RESUME_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500732 self._wait_for_stack_status(stack_identifier, 'RESUME_COMPLETE')
Steven Hardy03da0742015-03-19 00:13:17 -0400733
734 def wait_for_event_with_reason(self, stack_identifier, reason,
735 rsrc_name=None, num_expected=1):
736 build_timeout = self.conf.build_timeout
737 build_interval = self.conf.build_interval
738 start = timeutils.utcnow()
739 while timeutils.delta_seconds(start,
740 timeutils.utcnow()) < build_timeout:
741 try:
742 rsrc_events = self.client.events.list(stack_identifier,
743 resource_name=rsrc_name)
744 except heat_exceptions.HTTPNotFound:
liyi09461f72017-03-21 12:17:51 +0800745 LOG.debug("No events yet found for %s", rsrc_name)
Steven Hardy03da0742015-03-19 00:13:17 -0400746 else:
747 matched = [e for e in rsrc_events
748 if e.resource_status_reason == reason]
749 if len(matched) == num_expected:
750 return matched
751 time.sleep(build_interval)
Rakesh H Sc5735a82016-04-28 15:38:09 +0530752
Thomas Hervea6afca82017-04-10 23:44:26 +0200753 def check_autoscale_complete(self, stack_id, expected_num, parent_stack,
rabi55c0f752018-02-07 09:21:28 +0530754 group_name):
Rakesh H Sc5735a82016-04-28 15:38:09 +0530755 res_list = self.client.resources.list(stack_id)
756 all_res_complete = all(res.resource_status in ('UPDATE_COMPLETE',
757 'CREATE_COMPLETE')
758 for res in res_list)
759 all_res = len(res_list) == expected_num
Thomas Hervea6afca82017-04-10 23:44:26 +0200760 if all_res and all_res_complete:
rabi55c0f752018-02-07 09:21:28 +0530761 metadata = self.client.resources.metadata(parent_stack, group_name)
Thomas Hervea6afca82017-04-10 23:44:26 +0200762 return not metadata.get('scaling_in_progress')
763 return False