blob: cbf4abbd06b7c19a5d802e0f3c0fc1d726977ad1 [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
rabi876449a2018-03-15 21:56:49 +0530112def requires_feature(feature):
113 '''Decorator for tests requring specific feature.
114
115 The decorated test will be skipped when a specific feature is disabled.
116 '''
117 def decorator(test_method):
118 features_group = getattr(config.CONF, 'heat_features_enabled', None)
119 if not features_group:
120 return test_method
121 feature_enabled = config.CONF.heat_features_enabled.get(feature, False)
122 skipper = testtools.skipUnless(feature_enabled,
123 "%s - Feature not enabled." % feature)
124 return skipper(test_method)
125 return decorator
126
127
Andrea Frittolid908bef2018-02-22 11:29:53 +0000128class HeatIntegrationTest(testtools.testcase.WithAttributes,
129 testscenarios.WithScenarios,
Angus Salkeld95f65a22014-11-24 12:38:30 +1000130 testtools.TestCase):
Steve Baker450aa7f2014-08-25 10:37:27 +1200131
132 def setUp(self):
133 super(HeatIntegrationTest, self).setUp()
134
rabif89752b2017-11-18 22:14:30 +0530135 self.conf = config.CONF.heat_plugin
Steve Baker450aa7f2014-08-25 10:37:27 +1200136
137 self.assertIsNotNone(self.conf.auth_url,
138 'No auth_url configured')
139 self.assertIsNotNone(self.conf.username,
140 'No username configured')
141 self.assertIsNotNone(self.conf.password,
142 'No password configured')
rabifd98a472016-05-24 10:18:33 +0530143 self.setup_clients(self.conf)
144 self.useFixture(fixtures.FakeLogger(format=_LOG_FORMAT))
145 self.updated_time = {}
146 if self.conf.disable_ssl_certificate_validation:
147 self.verify_cert = False
148 else:
149 self.verify_cert = self.conf.ca_file or True
Steve Baker450aa7f2014-08-25 10:37:27 +1200150
Steve Bakerb752e912016-08-01 22:05:37 +0000151 def setup_clients(self, conf, admin_credentials=False):
152 self.manager = clients.ClientManager(conf, admin_credentials)
Steve Baker450aa7f2014-08-25 10:37:27 +1200153 self.identity_client = self.manager.identity_client
154 self.orchestration_client = self.manager.orchestration_client
155 self.compute_client = self.manager.compute_client
156 self.network_client = self.manager.network_client
157 self.volume_client = self.manager.volume_client
Angus Salkeld4408da32015-02-03 18:53:30 +1000158 self.object_client = self.manager.object_client
rabid69f0312017-10-26 14:52:52 +0530159 self.metric_client = self.manager.metric_client
rabifd98a472016-05-24 10:18:33 +0530160
161 self.client = self.orchestration_client
162
163 def setup_clients_for_admin(self):
Steve Bakerb752e912016-08-01 22:05:37 +0000164 self.setup_clients(self.conf, True)
Steve Baker450aa7f2014-08-25 10:37:27 +1200165
Steve Baker450aa7f2014-08-25 10:37:27 +1200166 def get_remote_client(self, server_or_ip, username, private_key=None):
167 if isinstance(server_or_ip, six.string_types):
168 ip = server_or_ip
169 else:
170 network_name_for_ssh = self.conf.network_for_ssh
171 ip = server_or_ip.networks[network_name_for_ssh][0]
172 if private_key is None:
173 private_key = self.keypair.private_key
174 linux_client = remote_client.RemoteClient(ip, username,
175 pkey=private_key,
176 conf=self.conf)
177 try:
178 linux_client.validate_authentication()
179 except exceptions.SSHTimeout:
liyi09461f72017-03-21 12:17:51 +0800180 LOG.exception('ssh connection to %s failed', ip)
Steve Baker450aa7f2014-08-25 10:37:27 +1200181 raise
182
183 return linux_client
184
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400185 def check_connectivity(self, check_ip):
186 def try_connect(ip):
187 try:
Sirushti Murugesan4920fda2015-04-22 00:35:26 +0530188 urllib.request.urlopen('http://%s/' % ip)
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400189 return True
190 except IOError:
191 return False
192
193 timeout = self.conf.connectivity_timeout
194 elapsed_time = 0
195 while not try_connect(check_ip):
196 time.sleep(10)
197 elapsed_time += 10
198 if elapsed_time > timeout:
199 raise exceptions.TimeoutException()
200
Steve Baker450aa7f2014-08-25 10:37:27 +1200201 def _log_console_output(self, servers=None):
202 if not servers:
203 servers = self.compute_client.servers.list()
204 for server in servers:
Steve Baker24641292015-03-13 10:47:50 +1300205 LOG.info('Console output for %s', server.id)
206 LOG.info(server.get_console_output())
Steve Baker450aa7f2014-08-25 10:37:27 +1200207
Steve Baker450aa7f2014-08-25 10:37:27 +1200208 def create_keypair(self, client=None, name=None):
209 if client is None:
210 client = self.compute_client
211 if name is None:
212 name = rand_name('heat-keypair')
213 keypair = client.keypairs.create(name)
214 self.assertEqual(keypair.name, name)
215
216 def delete_keypair():
217 keypair.delete()
218
219 self.addCleanup(delete_keypair)
220 return keypair
221
Sergey Krayneva265c132015-02-13 03:51:03 -0500222 def assign_keypair(self):
223 if self.conf.keypair_name:
224 self.keypair = None
225 self.keypair_name = self.conf.keypair_name
226 else:
227 self.keypair = self.create_keypair()
228 self.keypair_name = self.keypair.id
229
Steve Baker450aa7f2014-08-25 10:37:27 +1200230 @classmethod
231 def _stack_rand_name(cls):
232 return rand_name(cls.__name__)
233
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400234 def _get_network(self, net_name=None):
235 if net_name is None:
236 net_name = self.conf.fixed_network_name
Steve Baker450aa7f2014-08-25 10:37:27 +1200237 networks = self.network_client.list_networks()
238 for net in networks['networks']:
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400239 if net['name'] == net_name:
Steve Baker450aa7f2014-08-25 10:37:27 +1200240 return net
241
Mark Vanderwiel6d8e0862015-10-15 12:51:07 -0500242 def is_network_extension_supported(self, extension_alias):
243 try:
244 self.network_client.show_extension(extension_alias)
245 except network_exceptions.NeutronClientException:
246 return False
247 return True
248
Thomas Hervedb36c092017-03-23 11:20:14 +0100249 def is_service_available(self, service_type):
250 try:
251 self.identity_client.get_endpoint_url(
Matthias Bastian092d8bd2018-07-12 12:16:30 +0200252 service_type, self.conf.region, self.conf.endpoint_type)
Thomas Hervedb36c092017-03-23 11:20:14 +0100253 except kc_exceptions.EndpointNotFound:
254 return False
255 else:
256 return True
257
Steve Baker450aa7f2014-08-25 10:37:27 +1200258 @staticmethod
Angus Salkelda89a0282015-07-24 15:47:38 +1000259 def _stack_output(stack, output_key, validate_errors=True):
Steve Baker450aa7f2014-08-25 10:37:27 +1200260 """Return a stack output value for a given key."""
Angus Salkelda89a0282015-07-24 15:47:38 +1000261 value = None
262 for o in stack.outputs:
263 if validate_errors and 'output_error' in o:
264 # scan for errors in the stack output.
265 raise ValueError(
266 'Unexpected output errors in %s : %s' % (
267 output_key, o['output_error']))
268 if o['output_key'] == output_key:
269 value = o['output_value']
270 return value
Steve Baker450aa7f2014-08-25 10:37:27 +1200271
272 def _ping_ip_address(self, ip_address, should_succeed=True):
273 cmd = ['ping', '-c1', '-w1', ip_address]
274
275 def ping():
276 proc = subprocess.Popen(cmd,
277 stdout=subprocess.PIPE,
278 stderr=subprocess.PIPE)
279 proc.wait()
280 return (proc.returncode == 0) == should_succeed
281
282 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000283 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200284
Angus Salkelda7500d12015-04-10 15:44:07 +1000285 def _wait_for_all_resource_status(self, stack_identifier,
286 status, failure_pattern='^.*_FAILED$',
287 success_on_not_found=False):
288 for res in self.client.resources.list(stack_identifier):
289 self._wait_for_resource_status(
290 stack_identifier, res.resource_name,
291 status, failure_pattern=failure_pattern,
292 success_on_not_found=success_on_not_found)
293
Steve Baker450aa7f2014-08-25 10:37:27 +1200294 def _wait_for_resource_status(self, stack_identifier, resource_name,
295 status, failure_pattern='^.*_FAILED$',
296 success_on_not_found=False):
297 """Waits for a Resource to reach a given status."""
298 fail_regexp = re.compile(failure_pattern)
299 build_timeout = self.conf.build_timeout
300 build_interval = self.conf.build_interval
301
302 start = timeutils.utcnow()
303 while timeutils.delta_seconds(start,
304 timeutils.utcnow()) < build_timeout:
305 try:
306 res = self.client.resources.get(
307 stack_identifier, resource_name)
308 except heat_exceptions.HTTPNotFound:
309 if success_on_not_found:
310 return
311 # ignore this, as the resource may not have
312 # been created yet
313 else:
314 if res.resource_status == status:
315 return
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530316 wait_for_action = status.split('_')[0]
317 resource_action = res.resource_status.split('_')[0]
318 if (resource_action == wait_for_action and
319 fail_regexp.search(res.resource_status)):
Steve Baker450aa7f2014-08-25 10:37:27 +1200320 raise exceptions.StackResourceBuildErrorException(
321 resource_name=res.resource_name,
322 stack_identifier=stack_identifier,
323 resource_status=res.resource_status,
324 resource_status_reason=res.resource_status_reason)
325 time.sleep(build_interval)
326
327 message = ('Resource %s failed to reach %s status within '
328 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400329 (resource_name, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200330 raise exceptions.TimeoutException(message)
331
Rabi Mishra87be9b42016-02-15 14:15:50 +0530332 def verify_resource_status(self, stack_identifier, resource_name,
333 status='CREATE_COMPLETE'):
334 try:
335 res = self.client.resources.get(stack_identifier, resource_name)
336 except heat_exceptions.HTTPNotFound:
337 return False
338 return res.resource_status == status
339
rabi5eaa4962017-08-31 10:55:13 +0530340 def _verify_status(self, stack, stack_identifier, status,
341 fail_regexp, is_action_cancelled=False):
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530342 if stack.stack_status == status:
Sergey Kraynev89082a32015-09-04 04:42:33 -0400343 # Handle UPDATE_COMPLETE/FAILED case: Make sure we don't
344 # wait for a stale UPDATE_COMPLETE/FAILED status.
345 if status in ('UPDATE_FAILED', 'UPDATE_COMPLETE'):
rabi5eaa4962017-08-31 10:55:13 +0530346 if is_action_cancelled:
347 return True
348
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530349 if self.updated_time.get(
350 stack_identifier) != stack.updated_time:
351 self.updated_time[stack_identifier] = stack.updated_time
352 return True
Thomas Herve0e8567e2016-09-22 15:07:37 +0200353 elif status == 'DELETE_COMPLETE' and stack.deletion_time is None:
354 # Wait for deleted_time to be filled, so that we have more
355 # confidence the operation is finished.
356 return False
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530357 else:
358 return True
359
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530360 wait_for_action = status.split('_')[0]
361 if (stack.action == wait_for_action and
362 fail_regexp.search(stack.stack_status)):
Sergey Kraynev89082a32015-09-04 04:42:33 -0400363 # Handle UPDATE_COMPLETE/UPDATE_FAILED case.
364 if status in ('UPDATE_FAILED', 'UPDATE_COMPLETE'):
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530365 if self.updated_time.get(
366 stack_identifier) != stack.updated_time:
367 self.updated_time[stack_identifier] = stack.updated_time
368 raise exceptions.StackBuildErrorException(
369 stack_identifier=stack_identifier,
370 stack_status=stack.stack_status,
371 stack_status_reason=stack.stack_status_reason)
372 else:
373 raise exceptions.StackBuildErrorException(
374 stack_identifier=stack_identifier,
375 stack_status=stack.stack_status,
376 stack_status_reason=stack.stack_status_reason)
377
Steve Baker450aa7f2014-08-25 10:37:27 +1200378 def _wait_for_stack_status(self, stack_identifier, status,
Sergey Kraynev89082a32015-09-04 04:42:33 -0400379 failure_pattern=None,
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530380 success_on_not_found=False,
381 signal_required=False,
rabi5eaa4962017-08-31 10:55:13 +0530382 resources_to_signal=None,
383 is_action_cancelled=False):
Peter Razumovskyf0ac9582015-09-24 16:49:03 +0300384 """Waits for a Stack to reach a given status.
Steve Baker450aa7f2014-08-25 10:37:27 +1200385
386 Note this compares the full $action_$status, e.g
387 CREATE_COMPLETE, not just COMPLETE which is exposed
388 via the status property of Stack in heatclient
389 """
Sergey Kraynev89082a32015-09-04 04:42:33 -0400390 if failure_pattern:
391 fail_regexp = re.compile(failure_pattern)
392 elif 'FAILED' in status:
393 # If we're looking for e.g CREATE_FAILED, COMPLETE is unexpected.
394 fail_regexp = re.compile('^.*_COMPLETE$')
395 else:
396 fail_regexp = re.compile('^.*_FAILED$')
Steve Baker450aa7f2014-08-25 10:37:27 +1200397 build_timeout = self.conf.build_timeout
398 build_interval = self.conf.build_interval
399
400 start = timeutils.utcnow()
401 while timeutils.delta_seconds(start,
402 timeutils.utcnow()) < build_timeout:
403 try:
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500404 stack = self.client.stacks.get(stack_identifier,
405 resolve_outputs=False)
Steve Baker450aa7f2014-08-25 10:37:27 +1200406 except heat_exceptions.HTTPNotFound:
407 if success_on_not_found:
408 return
409 # ignore this, as the resource may not have
410 # been created yet
411 else:
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530412 if self._verify_status(stack, stack_identifier, status,
rabi5eaa4962017-08-31 10:55:13 +0530413 fail_regexp, is_action_cancelled):
Steve Baker450aa7f2014-08-25 10:37:27 +1200414 return
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530415 if signal_required:
416 self.signal_resources(resources_to_signal)
Steve Baker450aa7f2014-08-25 10:37:27 +1200417 time.sleep(build_interval)
418
419 message = ('Stack %s failed to reach %s status within '
420 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400421 (stack_identifier, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200422 raise exceptions.TimeoutException(message)
423
424 def _stack_delete(self, stack_identifier):
425 try:
Thomas Herve3eab2942015-10-22 17:29:21 +0200426 self._handle_in_progress(self.client.stacks.delete,
427 stack_identifier)
Steve Baker450aa7f2014-08-25 10:37:27 +1200428 except heat_exceptions.HTTPNotFound:
429 pass
430 self._wait_for_stack_status(
431 stack_identifier, 'DELETE_COMPLETE',
432 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000433
Thomas Herve3eab2942015-10-22 17:29:21 +0200434 def _handle_in_progress(self, fn, *args, **kwargs):
435 build_timeout = self.conf.build_timeout
436 build_interval = self.conf.build_interval
437 start = timeutils.utcnow()
438 while timeutils.delta_seconds(start,
439 timeutils.utcnow()) < build_timeout:
440 try:
441 fn(*args, **kwargs)
442 except heat_exceptions.HTTPConflict as ex:
443 # FIXME(sirushtim): Wait a little for the stack lock to be
444 # released and hopefully, the stack should be usable again.
445 if ex.error['error']['type'] != 'ActionInProgress':
446 raise ex
447
448 time.sleep(build_interval)
449 else:
450 break
451
Steven Hardy23284b62015-10-01 19:03:42 +0100452 def update_stack(self, stack_identifier, template=None, environment=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000453 files=None, parameters=None, tags=None,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530454 expected_status='UPDATE_COMPLETE',
Steven Hardy23284b62015-10-01 19:03:42 +0100455 disable_rollback=True,
456 existing=False):
Steven Hardyc9efd972014-11-20 11:31:55 +0000457 env = environment or {}
458 env_files = files or {}
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500459 parameters = parameters or {}
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530460
Sergey Kraynev89082a32015-09-04 04:42:33 -0400461 self.updated_time[stack_identifier] = self.client.stacks.get(
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500462 stack_identifier, resolve_outputs=False).updated_time
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530463
Thomas Herve3eab2942015-10-22 17:29:21 +0200464 self._handle_in_progress(
465 self.client.stacks.update,
466 stack_id=stack_identifier,
Thomas Herve3eab2942015-10-22 17:29:21 +0200467 template=template,
468 files=env_files,
469 disable_rollback=disable_rollback,
470 parameters=parameters,
471 environment=env,
472 tags=tags,
473 existing=existing)
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530474
Rakesh H Sa3325d62015-04-04 19:42:29 +0530475 kwargs = {'stack_identifier': stack_identifier,
476 'status': expected_status}
477 if expected_status in ['ROLLBACK_COMPLETE']:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530478 # To trigger rollback you would intentionally fail the stack
479 # Hence check for rollback failures
480 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
481
482 self._wait_for_stack_status(**kwargs)
Steven Hardyc9efd972014-11-20 11:31:55 +0000483
rabi5eaa4962017-08-31 10:55:13 +0530484 def cancel_update_stack(self, stack_identifier, rollback=True,
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300485 expected_status='ROLLBACK_COMPLETE'):
486
487 stack_name = stack_identifier.split('/')[0]
488
489 self.updated_time[stack_identifier] = self.client.stacks.get(
490 stack_identifier, resolve_outputs=False).updated_time
491
rabi5eaa4962017-08-31 10:55:13 +0530492 if rollback:
493 self.client.actions.cancel_update(stack_name)
494 else:
495 self.client.actions.cancel_without_rollback(stack_name)
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300496
497 kwargs = {'stack_identifier': stack_identifier,
498 'status': expected_status}
rabi5eaa4962017-08-31 10:55:13 +0530499 if expected_status == 'UPDATE_FAILED':
500 kwargs['is_action_cancelled'] = True
501
Oleksii Chuprykovfc2c58f2016-04-29 17:03:17 +0300502 if expected_status in ['ROLLBACK_COMPLETE']:
503 # To trigger rollback you would intentionally fail the stack
504 # Hence check for rollback failures
505 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
506
507 self._wait_for_stack_status(**kwargs)
508
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500509 def preview_update_stack(self, stack_identifier, template,
510 environment=None, files=None, parameters=None,
Steven Hardye6de2d62015-12-07 15:59:09 +0000511 tags=None, disable_rollback=True,
512 show_nested=False):
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500513 env = environment or {}
514 env_files = files or {}
515 parameters = parameters or {}
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500516
517 return self.client.stacks.preview_update(
518 stack_id=stack_identifier,
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500519 template=template,
520 files=env_files,
521 disable_rollback=disable_rollback,
522 parameters=parameters,
523 environment=env,
Steven Hardye6de2d62015-12-07 15:59:09 +0000524 tags=tags,
525 show_nested=show_nested
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500526 )
527
Steven Hardy03da0742015-03-19 00:13:17 -0400528 def assert_resource_is_a_stack(self, stack_identifier, res_name,
529 wait=False):
530 build_timeout = self.conf.build_timeout
531 build_interval = self.conf.build_interval
532 start = timeutils.utcnow()
533 while timeutils.delta_seconds(start,
534 timeutils.utcnow()) < build_timeout:
535 time.sleep(build_interval)
536 try:
537 nested_identifier = self._get_nested_identifier(
538 stack_identifier, res_name)
539 except Exception:
540 # We may have to wait, if the create is in-progress
541 if wait:
542 time.sleep(build_interval)
543 else:
544 raise
545 else:
546 return nested_identifier
547
548 def _get_nested_identifier(self, stack_identifier, res_name):
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000549 rsrc = self.client.resources.get(stack_identifier, res_name)
550 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
551 nested_href = nested_link[0]['href']
552 nested_id = nested_href.split('/')[-1]
553 nested_identifier = '/'.join(nested_href.split('/')[-2:])
554 self.assertEqual(rsrc.physical_resource_id, nested_id)
555
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500556 nested_stack = self.client.stacks.get(nested_id, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000557 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
558 nested_stack.id)
559 self.assertEqual(nested_identifier, nested_identifier2)
560 parent_id = stack_identifier.split("/")[-1]
561 self.assertEqual(parent_id, nested_stack.parent)
562 return nested_identifier
563
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530564 def group_nested_identifier(self, stack_identifier,
565 group_name):
566 # Get the nested stack identifier from a group resource
567 rsrc = self.client.resources.get(stack_identifier, group_name)
568 physical_resource_id = rsrc.physical_resource_id
569
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500570 nested_stack = self.client.stacks.get(physical_resource_id,
571 resolve_outputs=False)
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530572 nested_identifier = '%s/%s' % (nested_stack.stack_name,
573 nested_stack.id)
574 parent_id = stack_identifier.split("/")[-1]
575 self.assertEqual(parent_id, nested_stack.parent)
576 return nested_identifier
577
578 def list_group_resources(self, stack_identifier,
579 group_name, minimal=True):
580 nested_identifier = self.group_nested_identifier(stack_identifier,
581 group_name)
582 if minimal:
583 return self.list_resources(nested_identifier)
584 return self.client.resources.list(nested_identifier)
585
Steven Hardyc9efd972014-11-20 11:31:55 +0000586 def list_resources(self, stack_identifier):
587 resources = self.client.resources.list(stack_identifier)
588 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000589
Steven Hardyd448dae2016-06-14 14:57:28 +0100590 def get_resource_stack_id(self, r):
591 stack_link = [l for l in r.links if l.get('rel') == 'stack'][0]
592 return stack_link['href'].split("/")[-1]
593
Botond Zoltáne0b7aa12017-03-28 08:42:16 +0200594 def get_physical_resource_id(self, stack_identifier, resource_name):
595 try:
596 resource = self.client.resources.get(
597 stack_identifier, resource_name)
598 return resource.physical_resource_id
599 except Exception:
600 raise Exception('Resource (%s) not found in stack (%s)!' %
601 (stack_identifier, resource_name))
602
603 def get_stack_output(self, stack_identifier, output_key,
604 validate_errors=True):
605 stack = self.client.stacks.get(stack_identifier)
606 return self._stack_output(stack, output_key, validate_errors)
607
Rabi Mishra81ca6bc2016-06-16 15:09:20 +0530608 def check_input_values(self, group_resources, key, value):
609 # Check inputs for deployment and derived config
610 for r in group_resources:
611 d = self.client.software_deployments.get(
612 r.physical_resource_id)
613 self.assertEqual({key: value}, d.input_values)
614 c = self.client.software_configs.get(
615 d.config_id)
616 foo_input_c = [i for i in c.inputs if i.get('name') == key][0]
617 self.assertEqual(value, foo_input_c.get('value'))
618
619 def signal_resources(self, resources):
620 # Signal all IN_PROGRESS resources
621 for r in resources:
622 if 'IN_PROGRESS' in r.resource_status:
623 stack_id = self.get_resource_stack_id(r)
624 self.client.resources.signal(stack_id, r.resource_name)
625
Steven Hardyf2c82c02014-11-20 14:02:17 +0000626 def stack_create(self, stack_name=None, template=None, files=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000627 parameters=None, environment=None, tags=None,
628 expected_status='CREATE_COMPLETE',
Jay Dobies39c4ce42015-11-04 10:49:08 -0500629 disable_rollback=True, enable_cleanup=True,
rabi6ce8d962017-07-10 16:40:12 +0530630 environment_files=None, timeout=None):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000631 name = stack_name or self._stack_rand_name()
632 templ = template or self.template
633 templ_files = files or {}
634 params = parameters or {}
635 env = environment or {}
rabi6ce8d962017-07-10 16:40:12 +0530636 timeout_mins = timeout or self.conf.build_timeout
Steven Hardyf2c82c02014-11-20 14:02:17 +0000637 self.client.stacks.create(
638 stack_name=name,
639 template=templ,
640 files=templ_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530641 disable_rollback=disable_rollback,
Steven Hardyf2c82c02014-11-20 14:02:17 +0000642 parameters=params,
Sabeen Syed277ea692015-02-04 23:30:02 +0000643 environment=env,
Jay Dobies39c4ce42015-11-04 10:49:08 -0500644 tags=tags,
rabi6ce8d962017-07-10 16:40:12 +0530645 environment_files=environment_files,
646 timeout_mins=timeout_mins
Steven Hardyf2c82c02014-11-20 14:02:17 +0000647 )
rabic570e0f2017-10-26 13:07:13 +0530648 if enable_cleanup:
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200649 self.addCleanup(self._stack_delete, name)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000650
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500651 stack = self.client.stacks.get(name, resolve_outputs=False)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000652 stack_identifier = '%s/%s' % (name, stack.id)
Rakesh H Sa3325d62015-04-04 19:42:29 +0530653 kwargs = {'stack_identifier': stack_identifier,
654 'status': expected_status}
Steve Bakerf6c8f122015-02-10 13:54:46 +1300655 if expected_status:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530656 if expected_status in ['ROLLBACK_COMPLETE']:
657 # To trigger rollback you would intentionally fail the stack
658 # Hence check for rollback failures
659 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
660 self._wait_for_stack_status(**kwargs)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000661 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000662
663 def stack_adopt(self, stack_name=None, files=None,
664 parameters=None, environment=None, adopt_data=None,
665 wait_for_status='ADOPT_COMPLETE'):
Rabi Mishra477efc92015-07-31 13:01:45 +0530666 if (self.conf.skip_test_stack_action_list and
667 'ADOPT' in self.conf.skip_test_stack_action_list):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530668 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000669 name = stack_name or self._stack_rand_name()
670 templ_files = files or {}
671 params = parameters or {}
672 env = environment or {}
673 self.client.stacks.create(
674 stack_name=name,
675 files=templ_files,
676 disable_rollback=True,
677 parameters=params,
678 environment=env,
679 adopt_stack_data=adopt_data,
680 )
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200681 self.addCleanup(self._stack_delete, name)
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500682 stack = self.client.stacks.get(name, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000683 stack_identifier = '%s/%s' % (name, stack.id)
684 self._wait_for_stack_status(stack_identifier, wait_for_status)
685 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530686
687 def stack_abandon(self, stack_id):
Rabi Mishra477efc92015-07-31 13:01:45 +0530688 if (self.conf.skip_test_stack_action_list and
689 'ABANDON' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200690 self.addCleanup(self._stack_delete, stack_id)
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530691 self.skipTest('Testing Stack abandon disabled in conf, skipping')
692 info = self.client.stacks.abandon(stack_id=stack_id)
693 return info
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500694
rabi90b3ab42017-05-04 13:02:28 +0530695 def stack_snapshot(self, stack_id,
696 wait_for_status='SNAPSHOT_COMPLETE'):
697 snapshot = self.client.stacks.snapshot(stack_id=stack_id)
698 self._wait_for_stack_status(stack_id, wait_for_status)
699 return snapshot['id']
700
701 def stack_restore(self, stack_id, snapshot_id,
702 wait_for_status='RESTORE_COMPLETE'):
703 self.client.stacks.restore(stack_id, snapshot_id)
704 self._wait_for_stack_status(stack_id, wait_for_status)
705
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500706 def stack_suspend(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530707 if (self.conf.skip_test_stack_action_list and
708 'SUSPEND' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200709 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530710 self.skipTest('Testing Stack suspend disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530711 self._handle_in_progress(self.client.actions.suspend, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000712 # improve debugging by first checking the resource's state.
713 self._wait_for_all_resource_status(stack_identifier,
714 'SUSPEND_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500715 self._wait_for_stack_status(stack_identifier, 'SUSPEND_COMPLETE')
716
717 def stack_resume(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530718 if (self.conf.skip_test_stack_action_list and
719 'RESUME' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200720 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530721 self.skipTest('Testing Stack resume disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530722 self._handle_in_progress(self.client.actions.resume, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000723 # improve debugging by first checking the resource's state.
724 self._wait_for_all_resource_status(stack_identifier,
725 'RESUME_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500726 self._wait_for_stack_status(stack_identifier, 'RESUME_COMPLETE')
Steven Hardy03da0742015-03-19 00:13:17 -0400727
728 def wait_for_event_with_reason(self, stack_identifier, reason,
729 rsrc_name=None, num_expected=1):
730 build_timeout = self.conf.build_timeout
731 build_interval = self.conf.build_interval
732 start = timeutils.utcnow()
733 while timeutils.delta_seconds(start,
734 timeutils.utcnow()) < build_timeout:
735 try:
736 rsrc_events = self.client.events.list(stack_identifier,
737 resource_name=rsrc_name)
738 except heat_exceptions.HTTPNotFound:
liyi09461f72017-03-21 12:17:51 +0800739 LOG.debug("No events yet found for %s", rsrc_name)
Steven Hardy03da0742015-03-19 00:13:17 -0400740 else:
741 matched = [e for e in rsrc_events
742 if e.resource_status_reason == reason]
743 if len(matched) == num_expected:
744 return matched
745 time.sleep(build_interval)
Rakesh H Sc5735a82016-04-28 15:38:09 +0530746
Thomas Hervea6afca82017-04-10 23:44:26 +0200747 def check_autoscale_complete(self, stack_id, expected_num, parent_stack,
rabi55c0f752018-02-07 09:21:28 +0530748 group_name):
Rakesh H Sc5735a82016-04-28 15:38:09 +0530749 res_list = self.client.resources.list(stack_id)
750 all_res_complete = all(res.resource_status in ('UPDATE_COMPLETE',
751 'CREATE_COMPLETE')
752 for res in res_list)
753 all_res = len(res_list) == expected_num
Thomas Hervea6afca82017-04-10 23:44:26 +0200754 if all_res and all_res_complete:
rabi55c0f752018-02-07 09:21:28 +0530755 metadata = self.client.resources.metadata(parent_stack, group_name)
Thomas Hervea6afca82017-04-10 23:44:26 +0200756 return not metadata.get('scaling_in_progress')
757 return False