blob: 976ae8b26ecb6d284618fe7dd448c608f2582313 [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')
84
85 self.manager = clients.ClientManager(self.conf)
86 self.identity_client = self.manager.identity_client
87 self.orchestration_client = self.manager.orchestration_client
88 self.compute_client = self.manager.compute_client
89 self.network_client = self.manager.network_client
90 self.volume_client = self.manager.volume_client
Angus Salkeld4408da32015-02-03 18:53:30 +100091 self.object_client = self.manager.object_client
Angus Salkeld406bbd52015-05-13 14:24:04 +100092 self.metering_client = self.manager.metering_client
Angus Salkeld24043702014-11-21 08:49:26 +100093 self.useFixture(fixtures.FakeLogger(format=_LOG_FORMAT))
Sirushti Murugesan13a8a172015-04-14 00:30:05 +053094 self.updated_time = {}
tyagi39aa11a2016-03-07 04:47:00 -080095 if self.conf.disable_ssl_certificate_validation:
96 self.verify_cert = False
97 else:
98 self.verify_cert = self.conf.ca_file or True
Steve Baker450aa7f2014-08-25 10:37:27 +120099
Steve Baker450aa7f2014-08-25 10:37:27 +1200100 def get_remote_client(self, server_or_ip, username, private_key=None):
101 if isinstance(server_or_ip, six.string_types):
102 ip = server_or_ip
103 else:
104 network_name_for_ssh = self.conf.network_for_ssh
105 ip = server_or_ip.networks[network_name_for_ssh][0]
106 if private_key is None:
107 private_key = self.keypair.private_key
108 linux_client = remote_client.RemoteClient(ip, username,
109 pkey=private_key,
110 conf=self.conf)
111 try:
112 linux_client.validate_authentication()
113 except exceptions.SSHTimeout:
114 LOG.exception('ssh connection to %s failed' % ip)
115 raise
116
117 return linux_client
118
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400119 def check_connectivity(self, check_ip):
120 def try_connect(ip):
121 try:
Sirushti Murugesan4920fda2015-04-22 00:35:26 +0530122 urllib.request.urlopen('http://%s/' % ip)
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400123 return True
124 except IOError:
125 return False
126
127 timeout = self.conf.connectivity_timeout
128 elapsed_time = 0
129 while not try_connect(check_ip):
130 time.sleep(10)
131 elapsed_time += 10
132 if elapsed_time > timeout:
133 raise exceptions.TimeoutException()
134
Steve Baker450aa7f2014-08-25 10:37:27 +1200135 def _log_console_output(self, servers=None):
136 if not servers:
137 servers = self.compute_client.servers.list()
138 for server in servers:
Steve Baker24641292015-03-13 10:47:50 +1300139 LOG.info('Console output for %s', server.id)
140 LOG.info(server.get_console_output())
Steve Baker450aa7f2014-08-25 10:37:27 +1200141
Sergey Kraynevd6fa5c02015-02-13 03:03:55 -0500142 def _load_template(self, base_file, file_name, sub_dir=None):
143 sub_dir = sub_dir or ''
Steve Baker450aa7f2014-08-25 10:37:27 +1200144 filepath = os.path.join(os.path.dirname(os.path.realpath(base_file)),
Sergey Kraynevd6fa5c02015-02-13 03:03:55 -0500145 sub_dir, file_name)
Steve Baker450aa7f2014-08-25 10:37:27 +1200146 with open(filepath) as f:
147 return f.read()
148
149 def create_keypair(self, client=None, name=None):
150 if client is None:
151 client = self.compute_client
152 if name is None:
153 name = rand_name('heat-keypair')
154 keypair = client.keypairs.create(name)
155 self.assertEqual(keypair.name, name)
156
157 def delete_keypair():
158 keypair.delete()
159
160 self.addCleanup(delete_keypair)
161 return keypair
162
Sergey Krayneva265c132015-02-13 03:51:03 -0500163 def assign_keypair(self):
164 if self.conf.keypair_name:
165 self.keypair = None
166 self.keypair_name = self.conf.keypair_name
167 else:
168 self.keypair = self.create_keypair()
169 self.keypair_name = self.keypair.id
170
Steve Baker450aa7f2014-08-25 10:37:27 +1200171 @classmethod
172 def _stack_rand_name(cls):
173 return rand_name(cls.__name__)
174
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400175 def _get_network(self, net_name=None):
176 if net_name is None:
177 net_name = self.conf.fixed_network_name
Steve Baker450aa7f2014-08-25 10:37:27 +1200178 networks = self.network_client.list_networks()
179 for net in networks['networks']:
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400180 if net['name'] == net_name:
Steve Baker450aa7f2014-08-25 10:37:27 +1200181 return net
182
Mark Vanderwiel6d8e0862015-10-15 12:51:07 -0500183 def is_network_extension_supported(self, extension_alias):
184 try:
185 self.network_client.show_extension(extension_alias)
186 except network_exceptions.NeutronClientException:
187 return False
188 return True
189
Steve Baker450aa7f2014-08-25 10:37:27 +1200190 @staticmethod
Angus Salkelda89a0282015-07-24 15:47:38 +1000191 def _stack_output(stack, output_key, validate_errors=True):
Steve Baker450aa7f2014-08-25 10:37:27 +1200192 """Return a stack output value for a given key."""
Angus Salkelda89a0282015-07-24 15:47:38 +1000193 value = None
194 for o in stack.outputs:
195 if validate_errors and 'output_error' in o:
196 # scan for errors in the stack output.
197 raise ValueError(
198 'Unexpected output errors in %s : %s' % (
199 output_key, o['output_error']))
200 if o['output_key'] == output_key:
201 value = o['output_value']
202 return value
Steve Baker450aa7f2014-08-25 10:37:27 +1200203
204 def _ping_ip_address(self, ip_address, should_succeed=True):
205 cmd = ['ping', '-c1', '-w1', ip_address]
206
207 def ping():
208 proc = subprocess.Popen(cmd,
209 stdout=subprocess.PIPE,
210 stderr=subprocess.PIPE)
211 proc.wait()
212 return (proc.returncode == 0) == should_succeed
213
214 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000215 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200216
Angus Salkelda7500d12015-04-10 15:44:07 +1000217 def _wait_for_all_resource_status(self, stack_identifier,
218 status, failure_pattern='^.*_FAILED$',
219 success_on_not_found=False):
220 for res in self.client.resources.list(stack_identifier):
221 self._wait_for_resource_status(
222 stack_identifier, res.resource_name,
223 status, failure_pattern=failure_pattern,
224 success_on_not_found=success_on_not_found)
225
Steve Baker450aa7f2014-08-25 10:37:27 +1200226 def _wait_for_resource_status(self, stack_identifier, resource_name,
227 status, failure_pattern='^.*_FAILED$',
228 success_on_not_found=False):
229 """Waits for a Resource to reach a given status."""
230 fail_regexp = re.compile(failure_pattern)
231 build_timeout = self.conf.build_timeout
232 build_interval = self.conf.build_interval
233
234 start = timeutils.utcnow()
235 while timeutils.delta_seconds(start,
236 timeutils.utcnow()) < build_timeout:
237 try:
238 res = self.client.resources.get(
239 stack_identifier, resource_name)
240 except heat_exceptions.HTTPNotFound:
241 if success_on_not_found:
242 return
243 # ignore this, as the resource may not have
244 # been created yet
245 else:
246 if res.resource_status == status:
247 return
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530248 wait_for_action = status.split('_')[0]
249 resource_action = res.resource_status.split('_')[0]
250 if (resource_action == wait_for_action and
251 fail_regexp.search(res.resource_status)):
Steve Baker450aa7f2014-08-25 10:37:27 +1200252 raise exceptions.StackResourceBuildErrorException(
253 resource_name=res.resource_name,
254 stack_identifier=stack_identifier,
255 resource_status=res.resource_status,
256 resource_status_reason=res.resource_status_reason)
257 time.sleep(build_interval)
258
259 message = ('Resource %s failed to reach %s status within '
260 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400261 (resource_name, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200262 raise exceptions.TimeoutException(message)
263
Rabi Mishra87be9b42016-02-15 14:15:50 +0530264 def verify_resource_status(self, stack_identifier, resource_name,
265 status='CREATE_COMPLETE'):
266 try:
267 res = self.client.resources.get(stack_identifier, resource_name)
268 except heat_exceptions.HTTPNotFound:
269 return False
270 return res.resource_status == status
271
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530272 def _verify_status(self, stack, stack_identifier, status, fail_regexp):
273 if stack.stack_status == status:
Sergey Kraynev89082a32015-09-04 04:42:33 -0400274 # Handle UPDATE_COMPLETE/FAILED case: Make sure we don't
275 # wait for a stale UPDATE_COMPLETE/FAILED status.
276 if status in ('UPDATE_FAILED', 'UPDATE_COMPLETE'):
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530277 if self.updated_time.get(
278 stack_identifier) != stack.updated_time:
279 self.updated_time[stack_identifier] = stack.updated_time
280 return True
281 else:
282 return True
283
Sirushti Murugesane5ad25b2015-04-18 23:30:59 +0530284 wait_for_action = status.split('_')[0]
285 if (stack.action == wait_for_action and
286 fail_regexp.search(stack.stack_status)):
Sergey Kraynev89082a32015-09-04 04:42:33 -0400287 # Handle UPDATE_COMPLETE/UPDATE_FAILED case.
288 if status in ('UPDATE_FAILED', 'UPDATE_COMPLETE'):
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530289 if self.updated_time.get(
290 stack_identifier) != stack.updated_time:
291 self.updated_time[stack_identifier] = stack.updated_time
292 raise exceptions.StackBuildErrorException(
293 stack_identifier=stack_identifier,
294 stack_status=stack.stack_status,
295 stack_status_reason=stack.stack_status_reason)
296 else:
297 raise exceptions.StackBuildErrorException(
298 stack_identifier=stack_identifier,
299 stack_status=stack.stack_status,
300 stack_status_reason=stack.stack_status_reason)
301
Steve Baker450aa7f2014-08-25 10:37:27 +1200302 def _wait_for_stack_status(self, stack_identifier, status,
Sergey Kraynev89082a32015-09-04 04:42:33 -0400303 failure_pattern=None,
Steve Baker450aa7f2014-08-25 10:37:27 +1200304 success_on_not_found=False):
Peter Razumovskyf0ac9582015-09-24 16:49:03 +0300305 """Waits for a Stack to reach a given status.
Steve Baker450aa7f2014-08-25 10:37:27 +1200306
307 Note this compares the full $action_$status, e.g
308 CREATE_COMPLETE, not just COMPLETE which is exposed
309 via the status property of Stack in heatclient
310 """
Sergey Kraynev89082a32015-09-04 04:42:33 -0400311 if failure_pattern:
312 fail_regexp = re.compile(failure_pattern)
313 elif 'FAILED' in status:
314 # If we're looking for e.g CREATE_FAILED, COMPLETE is unexpected.
315 fail_regexp = re.compile('^.*_COMPLETE$')
316 else:
317 fail_regexp = re.compile('^.*_FAILED$')
Steve Baker450aa7f2014-08-25 10:37:27 +1200318 build_timeout = self.conf.build_timeout
319 build_interval = self.conf.build_interval
320
321 start = timeutils.utcnow()
322 while timeutils.delta_seconds(start,
323 timeutils.utcnow()) < build_timeout:
324 try:
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500325 stack = self.client.stacks.get(stack_identifier,
326 resolve_outputs=False)
Steve Baker450aa7f2014-08-25 10:37:27 +1200327 except heat_exceptions.HTTPNotFound:
328 if success_on_not_found:
329 return
330 # ignore this, as the resource may not have
331 # been created yet
332 else:
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530333 if self._verify_status(stack, stack_identifier, status,
334 fail_regexp):
Steve Baker450aa7f2014-08-25 10:37:27 +1200335 return
Sirushti Murugesan13a8a172015-04-14 00:30:05 +0530336
Steve Baker450aa7f2014-08-25 10:37:27 +1200337 time.sleep(build_interval)
338
339 message = ('Stack %s failed to reach %s status within '
340 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400341 (stack_identifier, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200342 raise exceptions.TimeoutException(message)
343
344 def _stack_delete(self, stack_identifier):
345 try:
Thomas Herve3eab2942015-10-22 17:29:21 +0200346 self._handle_in_progress(self.client.stacks.delete,
347 stack_identifier)
Steve Baker450aa7f2014-08-25 10:37:27 +1200348 except heat_exceptions.HTTPNotFound:
349 pass
350 self._wait_for_stack_status(
351 stack_identifier, 'DELETE_COMPLETE',
352 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000353
Thomas Herve3eab2942015-10-22 17:29:21 +0200354 def _handle_in_progress(self, fn, *args, **kwargs):
355 build_timeout = self.conf.build_timeout
356 build_interval = self.conf.build_interval
357 start = timeutils.utcnow()
358 while timeutils.delta_seconds(start,
359 timeutils.utcnow()) < build_timeout:
360 try:
361 fn(*args, **kwargs)
362 except heat_exceptions.HTTPConflict as ex:
363 # FIXME(sirushtim): Wait a little for the stack lock to be
364 # released and hopefully, the stack should be usable again.
365 if ex.error['error']['type'] != 'ActionInProgress':
366 raise ex
367
368 time.sleep(build_interval)
369 else:
370 break
371
Steven Hardy23284b62015-10-01 19:03:42 +0100372 def update_stack(self, stack_identifier, template=None, environment=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000373 files=None, parameters=None, tags=None,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530374 expected_status='UPDATE_COMPLETE',
Steven Hardy23284b62015-10-01 19:03:42 +0100375 disable_rollback=True,
376 existing=False):
Steven Hardyc9efd972014-11-20 11:31:55 +0000377 env = environment or {}
378 env_files = files or {}
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500379 parameters = parameters or {}
Steven Hardyc9efd972014-11-20 11:31:55 +0000380 stack_name = stack_identifier.split('/')[0]
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530381
Sergey Kraynev89082a32015-09-04 04:42:33 -0400382 self.updated_time[stack_identifier] = self.client.stacks.get(
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500383 stack_identifier, resolve_outputs=False).updated_time
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530384
Thomas Herve3eab2942015-10-22 17:29:21 +0200385 self._handle_in_progress(
386 self.client.stacks.update,
387 stack_id=stack_identifier,
388 stack_name=stack_name,
389 template=template,
390 files=env_files,
391 disable_rollback=disable_rollback,
392 parameters=parameters,
393 environment=env,
394 tags=tags,
395 existing=existing)
Sirushti Murugesan3a195a52015-05-01 09:47:09 +0530396
Rakesh H Sa3325d62015-04-04 19:42:29 +0530397 kwargs = {'stack_identifier': stack_identifier,
398 'status': expected_status}
399 if expected_status in ['ROLLBACK_COMPLETE']:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530400 # To trigger rollback you would intentionally fail the stack
401 # Hence check for rollback failures
402 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
403
404 self._wait_for_stack_status(**kwargs)
Steven Hardyc9efd972014-11-20 11:31:55 +0000405
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500406 def preview_update_stack(self, stack_identifier, template,
407 environment=None, files=None, parameters=None,
Steven Hardye6de2d62015-12-07 15:59:09 +0000408 tags=None, disable_rollback=True,
409 show_nested=False):
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500410 env = environment or {}
411 env_files = files or {}
412 parameters = parameters or {}
413 stack_name = stack_identifier.split('/')[0]
414
415 return self.client.stacks.preview_update(
416 stack_id=stack_identifier,
417 stack_name=stack_name,
418 template=template,
419 files=env_files,
420 disable_rollback=disable_rollback,
421 parameters=parameters,
422 environment=env,
Steven Hardye6de2d62015-12-07 15:59:09 +0000423 tags=tags,
424 show_nested=show_nested
Jason Dunsmoreb5aa9022015-09-09 16:57:04 -0500425 )
426
Steven Hardy03da0742015-03-19 00:13:17 -0400427 def assert_resource_is_a_stack(self, stack_identifier, res_name,
428 wait=False):
429 build_timeout = self.conf.build_timeout
430 build_interval = self.conf.build_interval
431 start = timeutils.utcnow()
432 while timeutils.delta_seconds(start,
433 timeutils.utcnow()) < build_timeout:
434 time.sleep(build_interval)
435 try:
436 nested_identifier = self._get_nested_identifier(
437 stack_identifier, res_name)
438 except Exception:
439 # We may have to wait, if the create is in-progress
440 if wait:
441 time.sleep(build_interval)
442 else:
443 raise
444 else:
445 return nested_identifier
446
447 def _get_nested_identifier(self, stack_identifier, res_name):
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000448 rsrc = self.client.resources.get(stack_identifier, res_name)
449 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
450 nested_href = nested_link[0]['href']
451 nested_id = nested_href.split('/')[-1]
452 nested_identifier = '/'.join(nested_href.split('/')[-2:])
453 self.assertEqual(rsrc.physical_resource_id, nested_id)
454
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500455 nested_stack = self.client.stacks.get(nested_id, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000456 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
457 nested_stack.id)
458 self.assertEqual(nested_identifier, nested_identifier2)
459 parent_id = stack_identifier.split("/")[-1]
460 self.assertEqual(parent_id, nested_stack.parent)
461 return nested_identifier
462
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530463 def group_nested_identifier(self, stack_identifier,
464 group_name):
465 # Get the nested stack identifier from a group resource
466 rsrc = self.client.resources.get(stack_identifier, group_name)
467 physical_resource_id = rsrc.physical_resource_id
468
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500469 nested_stack = self.client.stacks.get(physical_resource_id,
470 resolve_outputs=False)
Rabi Mishra8bcff8a2015-09-21 18:15:04 +0530471 nested_identifier = '%s/%s' % (nested_stack.stack_name,
472 nested_stack.id)
473 parent_id = stack_identifier.split("/")[-1]
474 self.assertEqual(parent_id, nested_stack.parent)
475 return nested_identifier
476
477 def list_group_resources(self, stack_identifier,
478 group_name, minimal=True):
479 nested_identifier = self.group_nested_identifier(stack_identifier,
480 group_name)
481 if minimal:
482 return self.list_resources(nested_identifier)
483 return self.client.resources.list(nested_identifier)
484
Steven Hardyc9efd972014-11-20 11:31:55 +0000485 def list_resources(self, stack_identifier):
486 resources = self.client.resources.list(stack_identifier)
487 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000488
489 def stack_create(self, stack_name=None, template=None, files=None,
Sabeen Syed277ea692015-02-04 23:30:02 +0000490 parameters=None, environment=None, tags=None,
491 expected_status='CREATE_COMPLETE',
Jay Dobies39c4ce42015-11-04 10:49:08 -0500492 disable_rollback=True, enable_cleanup=True,
493 environment_files=None):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000494 name = stack_name or self._stack_rand_name()
495 templ = template or self.template
496 templ_files = files or {}
497 params = parameters or {}
498 env = environment or {}
499 self.client.stacks.create(
500 stack_name=name,
501 template=templ,
502 files=templ_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530503 disable_rollback=disable_rollback,
Steven Hardyf2c82c02014-11-20 14:02:17 +0000504 parameters=params,
Sabeen Syed277ea692015-02-04 23:30:02 +0000505 environment=env,
Jay Dobies39c4ce42015-11-04 10:49:08 -0500506 tags=tags,
507 environment_files=environment_files
Steven Hardyf2c82c02014-11-20 14:02:17 +0000508 )
Sergey Kraynevbf67ce32015-04-17 10:54:20 -0400509 if expected_status not in ['ROLLBACK_COMPLETE'] and enable_cleanup:
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200510 self.addCleanup(self._stack_delete, name)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000511
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500512 stack = self.client.stacks.get(name, resolve_outputs=False)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000513 stack_identifier = '%s/%s' % (name, stack.id)
Rakesh H Sa3325d62015-04-04 19:42:29 +0530514 kwargs = {'stack_identifier': stack_identifier,
515 'status': expected_status}
Steve Bakerf6c8f122015-02-10 13:54:46 +1300516 if expected_status:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530517 if expected_status in ['ROLLBACK_COMPLETE']:
518 # To trigger rollback you would intentionally fail the stack
519 # Hence check for rollback failures
520 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
521 self._wait_for_stack_status(**kwargs)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000522 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000523
524 def stack_adopt(self, stack_name=None, files=None,
525 parameters=None, environment=None, adopt_data=None,
526 wait_for_status='ADOPT_COMPLETE'):
Rabi Mishra477efc92015-07-31 13:01:45 +0530527 if (self.conf.skip_test_stack_action_list and
528 'ADOPT' in self.conf.skip_test_stack_action_list):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530529 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000530 name = stack_name or self._stack_rand_name()
531 templ_files = files or {}
532 params = parameters or {}
533 env = environment or {}
534 self.client.stacks.create(
535 stack_name=name,
536 files=templ_files,
537 disable_rollback=True,
538 parameters=params,
539 environment=env,
540 adopt_stack_data=adopt_data,
541 )
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200542 self.addCleanup(self._stack_delete, name)
Sergey Kraynevf07f4712016-02-15 05:24:17 -0500543 stack = self.client.stacks.get(name, resolve_outputs=False)
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000544 stack_identifier = '%s/%s' % (name, stack.id)
545 self._wait_for_stack_status(stack_identifier, wait_for_status)
546 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530547
548 def stack_abandon(self, stack_id):
Rabi Mishra477efc92015-07-31 13:01:45 +0530549 if (self.conf.skip_test_stack_action_list and
550 'ABANDON' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200551 self.addCleanup(self._stack_delete, stack_id)
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530552 self.skipTest('Testing Stack abandon disabled in conf, skipping')
553 info = self.client.stacks.abandon(stack_id=stack_id)
554 return info
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500555
556 def stack_suspend(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530557 if (self.conf.skip_test_stack_action_list and
558 'SUSPEND' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200559 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530560 self.skipTest('Testing Stack suspend disabled in conf, skipping')
Rabi Mishra287ffff2015-08-10 09:52:35 +0530561 stack_name = stack_identifier.split('/')[0]
Thomas Herve3eab2942015-10-22 17:29:21 +0200562 self._handle_in_progress(self.client.actions.suspend, stack_name)
Angus Salkelda7500d12015-04-10 15:44:07 +1000563 # improve debugging by first checking the resource's state.
564 self._wait_for_all_resource_status(stack_identifier,
565 'SUSPEND_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500566 self._wait_for_stack_status(stack_identifier, 'SUSPEND_COMPLETE')
567
568 def stack_resume(self, stack_identifier):
Rabi Mishra477efc92015-07-31 13:01:45 +0530569 if (self.conf.skip_test_stack_action_list and
570 'RESUME' in self.conf.skip_test_stack_action_list):
Steve Bakerdbea6ab2015-08-19 13:37:08 +1200571 self.addCleanup(self._stack_delete, stack_identifier)
Rabi Mishra477efc92015-07-31 13:01:45 +0530572 self.skipTest('Testing Stack resume disabled in conf, skipping')
Rabi Mishra287ffff2015-08-10 09:52:35 +0530573 stack_name = stack_identifier.split('/')[0]
Thomas Herve3eab2942015-10-22 17:29:21 +0200574 self._handle_in_progress(self.client.actions.resume, stack_name)
Angus Salkelda7500d12015-04-10 15:44:07 +1000575 # improve debugging by first checking the resource's state.
576 self._wait_for_all_resource_status(stack_identifier,
577 'RESUME_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500578 self._wait_for_stack_status(stack_identifier, 'RESUME_COMPLETE')
Steven Hardy03da0742015-03-19 00:13:17 -0400579
580 def wait_for_event_with_reason(self, stack_identifier, reason,
581 rsrc_name=None, num_expected=1):
582 build_timeout = self.conf.build_timeout
583 build_interval = self.conf.build_interval
584 start = timeutils.utcnow()
585 while timeutils.delta_seconds(start,
586 timeutils.utcnow()) < build_timeout:
587 try:
588 rsrc_events = self.client.events.list(stack_identifier,
589 resource_name=rsrc_name)
590 except heat_exceptions.HTTPNotFound:
591 LOG.debug("No events yet found for %s" % rsrc_name)
592 else:
593 matched = [e for e in rsrc_events
594 if e.resource_status_reason == reason]
595 if len(matched) == num_expected:
596 return matched
597 time.sleep(build_interval)
Rakesh H Sc5735a82016-04-28 15:38:09 +0530598
599 def check_autoscale_complete(self, stack_id, expected_num):
600 res_list = self.client.resources.list(stack_id)
601 all_res_complete = all(res.resource_status in ('UPDATE_COMPLETE',
602 'CREATE_COMPLETE')
603 for res in res_list)
604 all_res = len(res_list) == expected_num
605 return all_res and all_res_complete