blob: c864d3b7ad3de37b9bf55027f727e22fa10bf58a [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 os
14import random
15import re
Steve Baker450aa7f2014-08-25 10:37:27 +120016import subprocess
Steve Baker450aa7f2014-08-25 10:37:27 +120017import time
18
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020019import fixtures
Steve Baker450aa7f2014-08-25 10:37:27 +120020from heatclient import exc as heat_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
Steve Baker450aa7f2014-08-25 10:37:27 +120029from heat_integrationtests.common import clients
30from heat_integrationtests.common import config
31from heat_integrationtests.common import exceptions
32from heat_integrationtests.common import remote_client
33
34LOG = logging.getLogger(__name__)
Angus Salkeld24043702014-11-21 08:49:26 +100035_LOG_FORMAT = "%(levelname)8s [%(name)s] %(message)s"
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
62def rand_name(name=''):
63 randbits = str(random.randint(1, 0x7fffffff))
64 if name:
65 return name + '-' + randbits
66 else:
67 return randbits
68
69
Angus Salkeld95f65a22014-11-24 12:38:30 +100070class HeatIntegrationTest(testscenarios.WithScenarios,
71 testtools.TestCase):
Steve Baker450aa7f2014-08-25 10:37:27 +120072
73 def setUp(self):
74 super(HeatIntegrationTest, self).setUp()
75
76 self.conf = config.init_conf()
77
78 self.assertIsNotNone(self.conf.auth_url,
79 'No auth_url configured')
80 self.assertIsNotNone(self.conf.username,
81 'No username configured')
82 self.assertIsNotNone(self.conf.password,
83 'No password configured')
rabifd98a472016-05-24 10:18:33 +053084 self.setup_clients(self.conf)
85 self.useFixture(fixtures.FakeLogger(format=_LOG_FORMAT))
86 self.updated_time = {}
87 if self.conf.disable_ssl_certificate_validation:
88 self.verify_cert = False
89 else:
90 self.verify_cert = self.conf.ca_file or True
Steve Baker450aa7f2014-08-25 10:37:27 +120091
rabifd98a472016-05-24 10:18:33 +053092 def setup_clients(self, conf):
93 self.manager = clients.ClientManager(conf)
Steve Baker450aa7f2014-08-25 10:37:27 +120094 self.identity_client = self.manager.identity_client
95 self.orchestration_client = self.manager.orchestration_client
96 self.compute_client = self.manager.compute_client
97 self.network_client = self.manager.network_client
98 self.volume_client = self.manager.volume_client
Angus Salkeld4408da32015-02-03 18:53:30 +100099 self.object_client = self.manager.object_client
Angus Salkeld406bbd52015-05-13 14:24:04 +1000100 self.metering_client = self.manager.metering_client
rabifd98a472016-05-24 10:18:33 +0530101
102 self.client = self.orchestration_client
103
104 def setup_clients_for_admin(self):
105 self.assertIsNotNone(self.conf.admin_username,
106 'No admin username configured')
107 self.assertIsNotNone(self.conf.admin_password,
108 'No admin password configured')
109 conf = config.init_conf()
110 conf.username = self.conf.admin_username
111 conf.password = self.conf.admin_password
112 conf.tenant_name = self.conf.admin_tenant_name
113 self.setup_clients(conf)
Steve Baker450aa7f2014-08-25 10:37:27 +1200114
Steve Baker450aa7f2014-08-25 10:37:27 +1200115 def get_remote_client(self, server_or_ip, username, private_key=None):
116 if isinstance(server_or_ip, six.string_types):
117 ip = server_or_ip
118 else:
119 network_name_for_ssh = self.conf.network_for_ssh
120 ip = server_or_ip.networks[network_name_for_ssh][0]
121 if private_key is None:
122 private_key = self.keypair.private_key
123 linux_client = remote_client.RemoteClient(ip, username,
124 pkey=private_key,
125 conf=self.conf)
126 try:
127 linux_client.validate_authentication()
128 except exceptions.SSHTimeout:
129 LOG.exception('ssh connection to %s failed' % ip)
130 raise
131
132 return linux_client
133
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400134 def check_connectivity(self, check_ip):
135 def try_connect(ip):
136 try:
Sirushti Murugesan4920fda2015-04-22 00:35:26 +0530137 urllib.request.urlopen('http://%s/' % ip)
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400138 return True
139 except IOError:
140 return False
141
142 timeout = self.conf.connectivity_timeout
143 elapsed_time = 0
144 while not try_connect(check_ip):
145 time.sleep(10)
146 elapsed_time += 10
147 if elapsed_time > timeout:
148 raise exceptions.TimeoutException()
149
Steve Baker450aa7f2014-08-25 10:37:27 +1200150 def _log_console_output(self, servers=None):
151 if not servers:
152 servers = self.compute_client.servers.list()
153 for server in servers:
Steve Baker24641292015-03-13 10:47:50 +1300154 LOG.info('Console output for %s', server.id)
155 LOG.info(server.get_console_output())
Steve Baker450aa7f2014-08-25 10:37:27 +1200156
Sergey Kraynevd6fa5c02015-02-13 03:03:55 -0500157 def _load_template(self, base_file, file_name, sub_dir=None):
158 sub_dir = sub_dir or ''
Steve Baker450aa7f2014-08-25 10:37:27 +1200159 filepath = os.path.join(os.path.dirname(os.path.realpath(base_file)),
Sergey Kraynevd6fa5c02015-02-13 03:03:55 -0500160 sub_dir, file_name)
Steve Baker450aa7f2014-08-25 10:37:27 +1200161 with open(filepath) as f:
162 return f.read()
163
164 def create_keypair(self, client=None, name=None):
165 if client is None:
166 client = self.compute_client
167 if name is None:
168 name = rand_name('heat-keypair')
169 keypair = client.keypairs.create(name)
170 self.assertEqual(keypair.name, name)
171
172 def delete_keypair():
173 keypair.delete()
174
175 self.addCleanup(delete_keypair)
176 return keypair
177
Sergey Krayneva265c132015-02-13 03:51:03 -0500178 def assign_keypair(self):
179 if self.conf.keypair_name:
180 self.keypair = None
181 self.keypair_name = self.conf.keypair_name
182 else:
183 self.keypair = self.create_keypair()
184 self.keypair_name = self.keypair.id
185
Steve Baker450aa7f2014-08-25 10:37:27 +1200186 @classmethod
187 def _stack_rand_name(cls):
188 return rand_name(cls.__name__)
189
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400190 def _get_network(self, net_name=None):
191 if net_name is None:
192 net_name = self.conf.fixed_network_name
Steve Baker450aa7f2014-08-25 10:37:27 +1200193 networks = self.network_client.list_networks()
194 for net in networks['networks']:
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400195 if net['name'] == net_name:
Steve Baker450aa7f2014-08-25 10:37:27 +1200196 return net
197
Mark Vanderwiel6d8e0862015-10-15 12:51:07 -0500198 def is_network_extension_supported(self, extension_alias):
199 try:
200 self.network_client.show_extension(extension_alias)
201 except network_exceptions.NeutronClientException:
202 return False
203 return True
204
Steve Baker450aa7f2014-08-25 10:37:27 +1200205 @staticmethod
Angus Salkelda89a0282015-07-24 15:47:38 +1000206 def _stack_output(stack, output_key, validate_errors=True):
Steve Baker450aa7f2014-08-25 10:37:27 +1200207 """Return a stack output value for a given key."""
Angus Salkelda89a0282015-07-24 15:47:38 +1000208 value = None
209 for o in stack.outputs:
210 if validate_errors and 'output_error' in o:
211 # scan for errors in the stack output.
212 raise ValueError(
213 'Unexpected output errors in %s : %s' % (
214 output_key, o['output_error']))
215 if o['output_key'] == output_key:
216 value = o['output_value']
217 return value
Steve Baker450aa7f2014-08-25 10:37:27 +1200218
219 def _ping_ip_address(self, ip_address, should_succeed=True):
220 cmd = ['ping', '-c1', '-w1', ip_address]
221
222 def ping():
223 proc = subprocess.Popen(cmd,
224 stdout=subprocess.PIPE,
225 stderr=subprocess.PIPE)
226 proc.wait()
227 return (proc.returncode == 0) == should_succeed
228
229 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000230 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200231
Angus Salkelda7500d12015-04-10 15:44:07 +1000232 def _wait_for_all_resource_status(self, stack_identifier,
233 status, failure_pattern='^.*_FAILED$',
234 success_on_not_found=False):
235 for res in self.client.resources.list(stack_identifier):
236 self._wait_for_resource_status(
237 stack_identifier, res.resource_name,
238 status, failure_pattern=failure_pattern,
239 success_on_not_found=success_on_not_found)
240
Steve Baker450aa7f2014-08-25 10:37:27 +1200241 def _wait_for_resource_status(self, stack_identifier, resource_name,
242 status, failure_pattern='^.*_FAILED$',
243 success_on_not_found=False):
244 """Waits for a Resource to reach a given status."""
245 fail_regexp = re.compile(failure_pattern)
246 build_timeout = self.conf.build_timeout
247 build_interval = self.conf.build_interval
248
249 start = timeutils.utcnow()
250 while timeutils.delta_seconds(start,
251 timeutils.utcnow()) < build_timeout:
252 try:
253 res = self.client.resources.get(
254 stack_identifier, resource_name)
255 except heat_exceptions.HTTPNotFound:
256 if success_on_not_found:
257 return
258 # ignore this, as the resource may not have
259 # been created yet
260 else:
261 if res.resource_status == status:
262 return
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530263 wait_for_action = status.split('_')[0]
264 resource_action = res.resource_status.split('_')[0]
265 if (resource_action == wait_for_action and
266 fail_regexp.search(res.resource_status)):
Steve Baker450aa7f2014-08-25 10:37:27 +1200267 raise exceptions.StackResourceBuildErrorException(
268 resource_name=res.resource_name,
269 stack_identifier=stack_identifier,
270 resource_status=res.resource_status,
271 resource_status_reason=res.resource_status_reason)
272 time.sleep(build_interval)
273
274 message = ('Resource %s failed to reach %s status within '
275 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400276 (resource_name, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200277 raise exceptions.TimeoutException(message)
278
Rabi Mishra87be9b42016-02-15 14:15:50 +0530279 def verify_resource_status(self, stack_identifier, resource_name,
280 status='CREATE_COMPLETE'):
281 try:
282 res = self.client.resources.get(stack_identifier, resource_name)
283 except heat_exceptions.HTTPNotFound:
284 return False
285 return res.resource_status == status
286
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530287 def _verify_status(self, stack, stack_identifier, status, fail_regexp):
288 if stack.stack_status == status:
Sergey Kraynev89082a32015-09-04 04:42:33 -0400289 # Handle UPDATE_COMPLETE/FAILED case: Make sure we don't
290 # wait for a stale UPDATE_COMPLETE/FAILED status.
291 if status in ('UPDATE_FAILED', 'UPDATE_COMPLETE'):
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530292 if self.updated_time.get(
293 stack_identifier) != stack.updated_time:
294 self.updated_time[stack_identifier] = stack.updated_time
295 return True
296 else:
297 return True
298
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530299 wait_for_action = status.split('_')[0]
300 if (stack.action == wait_for_action and
301 fail_regexp.search(stack.stack_status)):
Sergey Kraynev89082a32015-09-04 04:42:33 -0400302 # Handle UPDATE_COMPLETE/UPDATE_FAILED case.
303 if status in ('UPDATE_FAILED', 'UPDATE_COMPLETE'):
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530304 if self.updated_time.get(
305 stack_identifier) != stack.updated_time:
306 self.updated_time[stack_identifier] = stack.updated_time
307 raise exceptions.StackBuildErrorException(
308 stack_identifier=stack_identifier,
309 stack_status=stack.stack_status,
310 stack_status_reason=stack.stack_status_reason)
311 else:
312 raise exceptions.StackBuildErrorException(
313 stack_identifier=stack_identifier,
314 stack_status=stack.stack_status,
315 stack_status_reason=stack.stack_status_reason)
316
Steve Baker450aa7f2014-08-25 10:37:27 +1200317 def _wait_for_stack_status(self, stack_identifier, status,
Sergey Kraynev89082a32015-09-04 04:42:33 -0400318 failure_pattern=None,
Steve Baker450aa7f2014-08-25 10:37:27 +1200319 success_on_not_found=False):
Peter Razumovskyf0ac9582015-09-24 16:49:03 +0300320 """Waits for a Stack to reach a given status.
Steve Baker450aa7f2014-08-25 10:37:27 +1200321
322 Note this compares the full $action_$status, e.g
323 CREATE_COMPLETE, not just COMPLETE which is exposed
324 via the status property of Stack in heatclient
325 """
Sergey Kraynev89082a32015-09-04 04:42:33 -0400326 if failure_pattern:
327 fail_regexp = re.compile(failure_pattern)
328 elif 'FAILED' in status:
329 # If we're looking for e.g CREATE_FAILED, COMPLETE is unexpected.
330 fail_regexp = re.compile('^.*_COMPLETE$')
331 else:
332 fail_regexp = re.compile('^.*_FAILED$')
Steve Baker450aa7f2014-08-25 10:37:27 +1200333 build_timeout = self.conf.build_timeout
334 build_interval = self.conf.build_interval
335
336 start = timeutils.utcnow()
337 while timeutils.delta_seconds(start,
338 timeutils.utcnow()) < build_timeout:
339 try:
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500340 stack = self.client.stacks.get(stack_identifier,
341 resolve_outputs=False)
Steve Baker450aa7f2014-08-25 10:37:27 +1200342 except heat_exceptions.HTTPNotFound:
343 if success_on_not_found:
344 return
345 # ignore this, as the resource may not have
346 # been created yet
347 else:
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530348 if self._verify_status(stack, stack_identifier, status,
349 fail_regexp):
Steve Baker450aa7f2014-08-25 10:37:27 +1200350 return
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530351
Steve Baker450aa7f2014-08-25 10:37:27 +1200352 time.sleep(build_interval)
353
354 message = ('Stack %s failed to reach %s status within '
355 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400356 (stack_identifier, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200357 raise exceptions.TimeoutException(message)
358
359 def _stack_delete(self, stack_identifier):
360 try:
Thomas Herve3eab2942015-10-22 17:29:21 +0200361 self._handle_in_progress(self.client.stacks.delete,
362 stack_identifier)
Steve Baker450aa7f2014-08-25 10:37:27 +1200363 except heat_exceptions.HTTPNotFound:
364 pass
365 self._wait_for_stack_status(
366 stack_identifier, 'DELETE_COMPLETE',
367 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000368
Thomas Herve3eab2942015-10-22 17:29:21 +0200369 def _handle_in_progress(self, fn, *args, **kwargs):
370 build_timeout = self.conf.build_timeout
371 build_interval = self.conf.build_interval
372 start = timeutils.utcnow()
373 while timeutils.delta_seconds(start,
374 timeutils.utcnow()) < build_timeout:
375 try:
376 fn(*args, **kwargs)
377 except heat_exceptions.HTTPConflict as ex:
378 # FIXME(sirushtim): Wait a little for the stack lock to be
379 # released and hopefully, the stack should be usable again.
380 if ex.error['error']['type'] != 'ActionInProgress':
381 raise ex
382
383 time.sleep(build_interval)
384 else:
385 break
386
Steven Hardy23284b62015-10-01 19:03:42 +0100387 def update_stack(self, stack_identifier, template=None, environment=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000388 files=None, parameters=None, tags=None,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530389 expected_status='UPDATE_COMPLETE',
Steven Hardy23284b62015-10-01 19:03:42 +0100390 disable_rollback=True,
391 existing=False):
Steven Hardyc9efd972014-11-20 11:31:55 +0000392 env = environment or {}
393 env_files = files or {}
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500394 parameters = parameters or {}
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530395
Sergey Kraynev89082a32015-09-04 04:42:33 -0400396 self.updated_time[stack_identifier] = self.client.stacks.get(
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500397 stack_identifier, resolve_outputs=False).updated_time
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530398
Thomas Herve3eab2942015-10-22 17:29:21 +0200399 self._handle_in_progress(
400 self.client.stacks.update,
401 stack_id=stack_identifier,
Thomas Herve3eab2942015-10-22 17:29:21 +0200402 template=template,
403 files=env_files,
404 disable_rollback=disable_rollback,
405 parameters=parameters,
406 environment=env,
407 tags=tags,
408 existing=existing)
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530409
Rakesh H Sa3325d62015-04-04 19:42:29 +0530410 kwargs = {'stack_identifier': stack_identifier,
411 'status': expected_status}
412 if expected_status in ['ROLLBACK_COMPLETE']:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530413 # To trigger rollback you would intentionally fail the stack
414 # Hence check for rollback failures
415 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
416
417 self._wait_for_stack_status(**kwargs)
Steven Hardyc9efd972014-11-20 11:31:55 +0000418
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500419 def preview_update_stack(self, stack_identifier, template,
420 environment=None, files=None, parameters=None,
Steven Hardye6de2d62015-12-07 15:59:09 +0000421 tags=None, disable_rollback=True,
422 show_nested=False):
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500423 env = environment or {}
424 env_files = files or {}
425 parameters = parameters or {}
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500426
427 return self.client.stacks.preview_update(
428 stack_id=stack_identifier,
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500429 template=template,
430 files=env_files,
431 disable_rollback=disable_rollback,
432 parameters=parameters,
433 environment=env,
Steven Hardye6de2d62015-12-07 15:59:09 +0000434 tags=tags,
435 show_nested=show_nested
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500436 )
437
Steven Hardy03da0742015-03-19 00:13:17 -0400438 def assert_resource_is_a_stack(self, stack_identifier, res_name,
439 wait=False):
440 build_timeout = self.conf.build_timeout
441 build_interval = self.conf.build_interval
442 start = timeutils.utcnow()
443 while timeutils.delta_seconds(start,
444 timeutils.utcnow()) < build_timeout:
445 time.sleep(build_interval)
446 try:
447 nested_identifier = self._get_nested_identifier(
448 stack_identifier, res_name)
449 except Exception:
450 # We may have to wait, if the create is in-progress
451 if wait:
452 time.sleep(build_interval)
453 else:
454 raise
455 else:
456 return nested_identifier
457
458 def _get_nested_identifier(self, stack_identifier, res_name):
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000459 rsrc = self.client.resources.get(stack_identifier, res_name)
460 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
461 nested_href = nested_link[0]['href']
462 nested_id = nested_href.split('/')[-1]
463 nested_identifier = '/'.join(nested_href.split('/')[-2:])
464 self.assertEqual(rsrc.physical_resource_id, nested_id)
465
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500466 nested_stack = self.client.stacks.get(nested_id, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000467 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
468 nested_stack.id)
469 self.assertEqual(nested_identifier, nested_identifier2)
470 parent_id = stack_identifier.split("/")[-1]
471 self.assertEqual(parent_id, nested_stack.parent)
472 return nested_identifier
473
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530474 def group_nested_identifier(self, stack_identifier,
475 group_name):
476 # Get the nested stack identifier from a group resource
477 rsrc = self.client.resources.get(stack_identifier, group_name)
478 physical_resource_id = rsrc.physical_resource_id
479
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500480 nested_stack = self.client.stacks.get(physical_resource_id,
481 resolve_outputs=False)
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530482 nested_identifier = '%s/%s' % (nested_stack.stack_name,
483 nested_stack.id)
484 parent_id = stack_identifier.split("/")[-1]
485 self.assertEqual(parent_id, nested_stack.parent)
486 return nested_identifier
487
488 def list_group_resources(self, stack_identifier,
489 group_name, minimal=True):
490 nested_identifier = self.group_nested_identifier(stack_identifier,
491 group_name)
492 if minimal:
493 return self.list_resources(nested_identifier)
494 return self.client.resources.list(nested_identifier)
495
Steven Hardyc9efd972014-11-20 11:31:55 +0000496 def list_resources(self, stack_identifier):
497 resources = self.client.resources.list(stack_identifier)
498 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000499
500 def stack_create(self, stack_name=None, template=None, files=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000501 parameters=None, environment=None, tags=None,
502 expected_status='CREATE_COMPLETE',
Jay Dobies39c4ce42015-11-04 10:49:08 -0500503 disable_rollback=True, enable_cleanup=True,
504 environment_files=None):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000505 name = stack_name or self._stack_rand_name()
506 templ = template or self.template
507 templ_files = files or {}
508 params = parameters or {}
509 env = environment or {}
510 self.client.stacks.create(
511 stack_name=name,
512 template=templ,
513 files=templ_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530514 disable_rollback=disable_rollback,
Steven Hardyf2c82c02014-11-20 14:02:17 +0000515 parameters=params,
Sabeen Syed277ea692015-02-04 23:30:02 +0000516 environment=env,
Jay Dobies39c4ce42015-11-04 10:49:08 -0500517 tags=tags,
518 environment_files=environment_files
Steven Hardyf2c82c02014-11-20 14:02:17 +0000519 )
Sergey Kraynevbf67ce32015-04-17 10:54:20 -0400520 if expected_status not in ['ROLLBACK_COMPLETE'] and enable_cleanup:
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200521 self.addCleanup(self._stack_delete, name)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000522
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500523 stack = self.client.stacks.get(name, resolve_outputs=False)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000524 stack_identifier = '%s/%s' % (name, stack.id)
Rakesh H Sa3325d62015-04-04 19:42:29 +0530525 kwargs = {'stack_identifier': stack_identifier,
526 'status': expected_status}
Steve Bakerf6c8f122015-02-10 13:54:46 +1300527 if expected_status:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530528 if expected_status in ['ROLLBACK_COMPLETE']:
529 # To trigger rollback you would intentionally fail the stack
530 # Hence check for rollback failures
531 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
532 self._wait_for_stack_status(**kwargs)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000533 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000534
535 def stack_adopt(self, stack_name=None, files=None,
536 parameters=None, environment=None, adopt_data=None,
537 wait_for_status='ADOPT_COMPLETE'):
Rabi Mishra477efc92015-07-31 13:01:45 +0530538 if (self.conf.skip_test_stack_action_list and
539 'ADOPT' in self.conf.skip_test_stack_action_list):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530540 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000541 name = stack_name or self._stack_rand_name()
542 templ_files = files or {}
543 params = parameters or {}
544 env = environment or {}
545 self.client.stacks.create(
546 stack_name=name,
547 files=templ_files,
548 disable_rollback=True,
549 parameters=params,
550 environment=env,
551 adopt_stack_data=adopt_data,
552 )
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200553 self.addCleanup(self._stack_delete, name)
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500554 stack = self.client.stacks.get(name, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000555 stack_identifier = '%s/%s' % (name, stack.id)
556 self._wait_for_stack_status(stack_identifier, wait_for_status)
557 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530558
559 def stack_abandon(self, stack_id):
Rabi Mishra477efc92015-07-31 13:01:45 +0530560 if (self.conf.skip_test_stack_action_list and
561 'ABANDON' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200562 self.addCleanup(self._stack_delete, stack_id)
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530563 self.skipTest('Testing Stack abandon disabled in conf, skipping')
564 info = self.client.stacks.abandon(stack_id=stack_id)
565 return info
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500566
567 def stack_suspend(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530568 if (self.conf.skip_test_stack_action_list and
569 'SUSPEND' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200570 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530571 self.skipTest('Testing Stack suspend disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530572 self._handle_in_progress(self.client.actions.suspend, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000573 # improve debugging by first checking the resource's state.
574 self._wait_for_all_resource_status(stack_identifier,
575 'SUSPEND_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500576 self._wait_for_stack_status(stack_identifier, 'SUSPEND_COMPLETE')
577
578 def stack_resume(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530579 if (self.conf.skip_test_stack_action_list and
580 'RESUME' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200581 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530582 self.skipTest('Testing Stack resume disabled in conf, skipping')
rabif7d67082016-05-17 18:51:22 +0530583 self._handle_in_progress(self.client.actions.resume, stack_identifier)
Angus Salkelda7500d12015-04-10 15:44:07 +1000584 # improve debugging by first checking the resource's state.
585 self._wait_for_all_resource_status(stack_identifier,
586 'RESUME_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500587 self._wait_for_stack_status(stack_identifier, 'RESUME_COMPLETE')
Steven Hardy03da0742015-03-19 00:13:17 -0400588
589 def wait_for_event_with_reason(self, stack_identifier, reason,
590 rsrc_name=None, num_expected=1):
591 build_timeout = self.conf.build_timeout
592 build_interval = self.conf.build_interval
593 start = timeutils.utcnow()
594 while timeutils.delta_seconds(start,
595 timeutils.utcnow()) < build_timeout:
596 try:
597 rsrc_events = self.client.events.list(stack_identifier,
598 resource_name=rsrc_name)
599 except heat_exceptions.HTTPNotFound:
600 LOG.debug("No events yet found for %s" % rsrc_name)
601 else:
602 matched = [e for e in rsrc_events
603 if e.resource_status_reason == reason]
604 if len(matched) == num_expected:
605 return matched
606 time.sleep(build_interval)
Rakesh H Sc5735a82016-04-28 15:38:09 +0530607
608 def check_autoscale_complete(self, stack_id, expected_num):
609 res_list = self.client.resources.list(stack_id)
610 all_res_complete = all(res.resource_status in ('UPDATE_COMPLETE',
611 'CREATE_COMPLETE')
612 for res in res_list)
613 all_res = len(res_list) == expected_num
614 return all_res and all_res_complete