blob: a7aa0395437975e3dbe28ea5f9604e8f9b59d989 [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
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +040018import urllib
Steve Baker450aa7f2014-08-25 10:37:27 +120019
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020020import fixtures
Steve Baker450aa7f2014-08-25 10:37:27 +120021from heatclient import exc as heat_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
25import testscenarios
26import testtools
Steve Baker450aa7f2014-08-25 10:37:27 +120027
Steve Baker450aa7f2014-08-25 10:37:27 +120028from heat_integrationtests.common import clients
29from heat_integrationtests.common import config
30from heat_integrationtests.common import exceptions
31from heat_integrationtests.common import remote_client
32
33LOG = logging.getLogger(__name__)
Angus Salkeld24043702014-11-21 08:49:26 +100034_LOG_FORMAT = "%(levelname)8s [%(name)s] %(message)s"
Steve Baker450aa7f2014-08-25 10:37:27 +120035
36
Angus Salkeld08514ad2015-02-06 10:08:31 +100037def call_until_true(duration, sleep_for, func, *args, **kwargs):
Steve Baker450aa7f2014-08-25 10:37:27 +120038 """
39 Call the given function until it returns True (and return True) or
40 until the specified duration (in seconds) elapses (and return
41 False).
42
43 :param func: A zero argument callable that returns True on success.
44 :param duration: The number of seconds for which to attempt a
45 successful call of the function.
46 :param sleep_for: The number of seconds to sleep after an unsuccessful
47 invocation of the function.
48 """
49 now = time.time()
50 timeout = now + duration
51 while now < timeout:
Angus Salkeld08514ad2015-02-06 10:08:31 +100052 if func(*args, **kwargs):
Steve Baker450aa7f2014-08-25 10:37:27 +120053 return True
54 LOG.debug("Sleeping for %d seconds", sleep_for)
55 time.sleep(sleep_for)
56 now = time.time()
57 return False
58
59
60def rand_name(name=''):
61 randbits = str(random.randint(1, 0x7fffffff))
62 if name:
63 return name + '-' + randbits
64 else:
65 return randbits
66
67
Angus Salkeld95f65a22014-11-24 12:38:30 +100068class HeatIntegrationTest(testscenarios.WithScenarios,
69 testtools.TestCase):
Steve Baker450aa7f2014-08-25 10:37:27 +120070
71 def setUp(self):
72 super(HeatIntegrationTest, self).setUp()
73
74 self.conf = config.init_conf()
75
76 self.assertIsNotNone(self.conf.auth_url,
77 'No auth_url configured')
78 self.assertIsNotNone(self.conf.username,
79 'No username configured')
80 self.assertIsNotNone(self.conf.password,
81 'No password configured')
82
83 self.manager = clients.ClientManager(self.conf)
84 self.identity_client = self.manager.identity_client
85 self.orchestration_client = self.manager.orchestration_client
86 self.compute_client = self.manager.compute_client
87 self.network_client = self.manager.network_client
88 self.volume_client = self.manager.volume_client
Angus Salkeld4408da32015-02-03 18:53:30 +100089 self.object_client = self.manager.object_client
Angus Salkeld24043702014-11-21 08:49:26 +100090 self.useFixture(fixtures.FakeLogger(format=_LOG_FORMAT))
Steve Baker450aa7f2014-08-25 10:37:27 +120091
Steve Baker450aa7f2014-08-25 10:37:27 +120092 def get_remote_client(self, server_or_ip, username, private_key=None):
93 if isinstance(server_or_ip, six.string_types):
94 ip = server_or_ip
95 else:
96 network_name_for_ssh = self.conf.network_for_ssh
97 ip = server_or_ip.networks[network_name_for_ssh][0]
98 if private_key is None:
99 private_key = self.keypair.private_key
100 linux_client = remote_client.RemoteClient(ip, username,
101 pkey=private_key,
102 conf=self.conf)
103 try:
104 linux_client.validate_authentication()
105 except exceptions.SSHTimeout:
106 LOG.exception('ssh connection to %s failed' % ip)
107 raise
108
109 return linux_client
110
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400111 def check_connectivity(self, check_ip):
112 def try_connect(ip):
113 try:
114 urllib.urlopen('http://%s/' % ip)
115 return True
116 except IOError:
117 return False
118
119 timeout = self.conf.connectivity_timeout
120 elapsed_time = 0
121 while not try_connect(check_ip):
122 time.sleep(10)
123 elapsed_time += 10
124 if elapsed_time > timeout:
125 raise exceptions.TimeoutException()
126
Steve Baker450aa7f2014-08-25 10:37:27 +1200127 def _log_console_output(self, servers=None):
128 if not servers:
129 servers = self.compute_client.servers.list()
130 for server in servers:
Steve Baker24641292015-03-13 10:47:50 +1300131 LOG.info('Console output for %s', server.id)
132 LOG.info(server.get_console_output())
Steve Baker450aa7f2014-08-25 10:37:27 +1200133
Sergey Kraynevd6fa5c02015-02-13 03:03:55 -0500134 def _load_template(self, base_file, file_name, sub_dir=None):
135 sub_dir = sub_dir or ''
Steve Baker450aa7f2014-08-25 10:37:27 +1200136 filepath = os.path.join(os.path.dirname(os.path.realpath(base_file)),
Sergey Kraynevd6fa5c02015-02-13 03:03:55 -0500137 sub_dir, file_name)
Steve Baker450aa7f2014-08-25 10:37:27 +1200138 with open(filepath) as f:
139 return f.read()
140
141 def create_keypair(self, client=None, name=None):
142 if client is None:
143 client = self.compute_client
144 if name is None:
145 name = rand_name('heat-keypair')
146 keypair = client.keypairs.create(name)
147 self.assertEqual(keypair.name, name)
148
149 def delete_keypair():
150 keypair.delete()
151
152 self.addCleanup(delete_keypair)
153 return keypair
154
Sergey Krayneva265c132015-02-13 03:51:03 -0500155 def assign_keypair(self):
156 if self.conf.keypair_name:
157 self.keypair = None
158 self.keypair_name = self.conf.keypair_name
159 else:
160 self.keypair = self.create_keypair()
161 self.keypair_name = self.keypair.id
162
Steve Baker450aa7f2014-08-25 10:37:27 +1200163 @classmethod
164 def _stack_rand_name(cls):
165 return rand_name(cls.__name__)
166
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400167 def _get_network(self, net_name=None):
168 if net_name is None:
169 net_name = self.conf.fixed_network_name
Steve Baker450aa7f2014-08-25 10:37:27 +1200170 networks = self.network_client.list_networks()
171 for net in networks['networks']:
Anastasia Kuznetsova673fc432015-03-12 16:41:36 +0400172 if net['name'] == net_name:
Steve Baker450aa7f2014-08-25 10:37:27 +1200173 return net
174
175 @staticmethod
176 def _stack_output(stack, output_key):
177 """Return a stack output value for a given key."""
178 return next((o['output_value'] for o in stack.outputs
179 if o['output_key'] == output_key), None)
180
181 def _ping_ip_address(self, ip_address, should_succeed=True):
182 cmd = ['ping', '-c1', '-w1', ip_address]
183
184 def ping():
185 proc = subprocess.Popen(cmd,
186 stdout=subprocess.PIPE,
187 stderr=subprocess.PIPE)
188 proc.wait()
189 return (proc.returncode == 0) == should_succeed
190
191 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000192 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200193
Angus Salkelda7500d12015-04-10 15:44:07 +1000194 def _wait_for_all_resource_status(self, stack_identifier,
195 status, failure_pattern='^.*_FAILED$',
196 success_on_not_found=False):
197 for res in self.client.resources.list(stack_identifier):
198 self._wait_for_resource_status(
199 stack_identifier, res.resource_name,
200 status, failure_pattern=failure_pattern,
201 success_on_not_found=success_on_not_found)
202
Steve Baker450aa7f2014-08-25 10:37:27 +1200203 def _wait_for_resource_status(self, stack_identifier, resource_name,
204 status, failure_pattern='^.*_FAILED$',
205 success_on_not_found=False):
206 """Waits for a Resource to reach a given status."""
207 fail_regexp = re.compile(failure_pattern)
208 build_timeout = self.conf.build_timeout
209 build_interval = self.conf.build_interval
210
211 start = timeutils.utcnow()
212 while timeutils.delta_seconds(start,
213 timeutils.utcnow()) < build_timeout:
214 try:
215 res = self.client.resources.get(
216 stack_identifier, resource_name)
217 except heat_exceptions.HTTPNotFound:
218 if success_on_not_found:
219 return
220 # ignore this, as the resource may not have
221 # been created yet
222 else:
223 if res.resource_status == status:
224 return
225 if fail_regexp.search(res.resource_status):
226 raise exceptions.StackResourceBuildErrorException(
227 resource_name=res.resource_name,
228 stack_identifier=stack_identifier,
229 resource_status=res.resource_status,
230 resource_status_reason=res.resource_status_reason)
231 time.sleep(build_interval)
232
233 message = ('Resource %s failed to reach %s status within '
234 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400235 (resource_name, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200236 raise exceptions.TimeoutException(message)
237
238 def _wait_for_stack_status(self, stack_identifier, status,
239 failure_pattern='^.*_FAILED$',
240 success_on_not_found=False):
241 """
242 Waits for a Stack to reach a given status.
243
244 Note this compares the full $action_$status, e.g
245 CREATE_COMPLETE, not just COMPLETE which is exposed
246 via the status property of Stack in heatclient
247 """
248 fail_regexp = re.compile(failure_pattern)
249 build_timeout = self.conf.build_timeout
250 build_interval = self.conf.build_interval
251
252 start = timeutils.utcnow()
253 while timeutils.delta_seconds(start,
254 timeutils.utcnow()) < build_timeout:
255 try:
256 stack = self.client.stacks.get(stack_identifier)
257 except heat_exceptions.HTTPNotFound:
258 if success_on_not_found:
259 return
260 # ignore this, as the resource may not have
261 # been created yet
262 else:
263 if stack.stack_status == status:
264 return
265 if fail_regexp.search(stack.stack_status):
266 raise exceptions.StackBuildErrorException(
267 stack_identifier=stack_identifier,
268 stack_status=stack.stack_status,
269 stack_status_reason=stack.stack_status_reason)
270 time.sleep(build_interval)
271
272 message = ('Stack %s failed to reach %s status within '
273 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400274 (stack_identifier, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200275 raise exceptions.TimeoutException(message)
276
277 def _stack_delete(self, stack_identifier):
278 try:
279 self.client.stacks.delete(stack_identifier)
280 except heat_exceptions.HTTPNotFound:
281 pass
282 self._wait_for_stack_status(
283 stack_identifier, 'DELETE_COMPLETE',
284 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000285
286 def update_stack(self, stack_identifier, template, environment=None,
Steven Hardy03da0742015-03-19 00:13:17 -0400287 files=None, parameters=None,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530288 expected_status='UPDATE_COMPLETE',
289 disable_rollback=True):
Steven Hardyc9efd972014-11-20 11:31:55 +0000290 env = environment or {}
291 env_files = files or {}
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500292 parameters = parameters or {}
Steven Hardyc9efd972014-11-20 11:31:55 +0000293 stack_name = stack_identifier.split('/')[0]
294 self.client.stacks.update(
295 stack_id=stack_identifier,
296 stack_name=stack_name,
297 template=template,
298 files=env_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530299 disable_rollback=disable_rollback,
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500300 parameters=parameters,
Steven Hardyc9efd972014-11-20 11:31:55 +0000301 environment=env
302 )
Rakesh H Sa3325d62015-04-04 19:42:29 +0530303 kwargs = {'stack_identifier': stack_identifier,
304 'status': expected_status}
305 if expected_status in ['ROLLBACK_COMPLETE']:
306 self.addCleanup(self.client.stacks.delete, stack_name)
307 # To trigger rollback you would intentionally fail the stack
308 # Hence check for rollback failures
309 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
310
311 self._wait_for_stack_status(**kwargs)
Steven Hardyc9efd972014-11-20 11:31:55 +0000312
Steven Hardy03da0742015-03-19 00:13:17 -0400313 def assert_resource_is_a_stack(self, stack_identifier, res_name,
314 wait=False):
315 build_timeout = self.conf.build_timeout
316 build_interval = self.conf.build_interval
317 start = timeutils.utcnow()
318 while timeutils.delta_seconds(start,
319 timeutils.utcnow()) < build_timeout:
320 time.sleep(build_interval)
321 try:
322 nested_identifier = self._get_nested_identifier(
323 stack_identifier, res_name)
324 except Exception:
325 # We may have to wait, if the create is in-progress
326 if wait:
327 time.sleep(build_interval)
328 else:
329 raise
330 else:
331 return nested_identifier
332
333 def _get_nested_identifier(self, stack_identifier, res_name):
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000334 rsrc = self.client.resources.get(stack_identifier, res_name)
335 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
336 nested_href = nested_link[0]['href']
337 nested_id = nested_href.split('/')[-1]
338 nested_identifier = '/'.join(nested_href.split('/')[-2:])
339 self.assertEqual(rsrc.physical_resource_id, nested_id)
340
341 nested_stack = self.client.stacks.get(nested_id)
342 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
343 nested_stack.id)
344 self.assertEqual(nested_identifier, nested_identifier2)
345 parent_id = stack_identifier.split("/")[-1]
346 self.assertEqual(parent_id, nested_stack.parent)
347 return nested_identifier
348
Steven Hardyc9efd972014-11-20 11:31:55 +0000349 def list_resources(self, stack_identifier):
350 resources = self.client.resources.list(stack_identifier)
351 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000352
353 def stack_create(self, stack_name=None, template=None, files=None,
Steven Hardy7c1f2242015-01-12 16:32:56 +0000354 parameters=None, environment=None,
Sergey Kraynevbf67ce32015-04-17 10:54:20 -0400355 expected_status='CREATE_COMPLETE', disable_rollback=True,
356 enable_cleanup=True):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000357 name = stack_name or self._stack_rand_name()
358 templ = template or self.template
359 templ_files = files or {}
360 params = parameters or {}
361 env = environment or {}
362 self.client.stacks.create(
363 stack_name=name,
364 template=templ,
365 files=templ_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530366 disable_rollback=disable_rollback,
Steven Hardyf2c82c02014-11-20 14:02:17 +0000367 parameters=params,
368 environment=env
369 )
Sergey Kraynevbf67ce32015-04-17 10:54:20 -0400370 if expected_status not in ['ROLLBACK_COMPLETE'] and enable_cleanup:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530371 self.addCleanup(self.client.stacks.delete, name)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000372
373 stack = self.client.stacks.get(name)
374 stack_identifier = '%s/%s' % (name, stack.id)
Rakesh H Sa3325d62015-04-04 19:42:29 +0530375 kwargs = {'stack_identifier': stack_identifier,
376 'status': expected_status}
Steve Bakerf6c8f122015-02-10 13:54:46 +1300377 if expected_status:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530378 if expected_status in ['ROLLBACK_COMPLETE']:
379 # To trigger rollback you would intentionally fail the stack
380 # Hence check for rollback failures
381 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
382 self._wait_for_stack_status(**kwargs)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000383 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000384
385 def stack_adopt(self, stack_name=None, files=None,
386 parameters=None, environment=None, adopt_data=None,
387 wait_for_status='ADOPT_COMPLETE'):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530388 if self.conf.skip_stack_adopt_tests:
389 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000390 name = stack_name or self._stack_rand_name()
391 templ_files = files or {}
392 params = parameters or {}
393 env = environment or {}
394 self.client.stacks.create(
395 stack_name=name,
396 files=templ_files,
397 disable_rollback=True,
398 parameters=params,
399 environment=env,
400 adopt_stack_data=adopt_data,
401 )
402 self.addCleanup(self.client.stacks.delete, name)
403
404 stack = self.client.stacks.get(name)
405 stack_identifier = '%s/%s' % (name, stack.id)
406 self._wait_for_stack_status(stack_identifier, wait_for_status)
407 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530408
409 def stack_abandon(self, stack_id):
410 if self.conf.skip_stack_abandon_tests:
411 self.addCleanup(self.client.stacks.delete, stack_id)
412 self.skipTest('Testing Stack abandon disabled in conf, skipping')
413 info = self.client.stacks.abandon(stack_id=stack_id)
414 return info
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500415
416 def stack_suspend(self, stack_identifier):
417 stack_name = stack_identifier.split('/')[0]
418 self.client.actions.suspend(stack_name)
Angus Salkelda7500d12015-04-10 15:44:07 +1000419
420 # improve debugging by first checking the resource's state.
421 self._wait_for_all_resource_status(stack_identifier,
422 'SUSPEND_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500423 self._wait_for_stack_status(stack_identifier, 'SUSPEND_COMPLETE')
424
425 def stack_resume(self, stack_identifier):
426 stack_name = stack_identifier.split('/')[0]
427 self.client.actions.resume(stack_name)
Angus Salkelda7500d12015-04-10 15:44:07 +1000428
429 # improve debugging by first checking the resource's state.
430 self._wait_for_all_resource_status(stack_identifier,
431 'RESUME_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500432 self._wait_for_stack_status(stack_identifier, 'RESUME_COMPLETE')
Steven Hardy03da0742015-03-19 00:13:17 -0400433
434 def wait_for_event_with_reason(self, stack_identifier, reason,
435 rsrc_name=None, num_expected=1):
436 build_timeout = self.conf.build_timeout
437 build_interval = self.conf.build_interval
438 start = timeutils.utcnow()
439 while timeutils.delta_seconds(start,
440 timeutils.utcnow()) < build_timeout:
441 try:
442 rsrc_events = self.client.events.list(stack_identifier,
443 resource_name=rsrc_name)
444 except heat_exceptions.HTTPNotFound:
445 LOG.debug("No events yet found for %s" % rsrc_name)
446 else:
447 matched = [e for e in rsrc_events
448 if e.resource_status_reason == reason]
449 if len(matched) == num_expected:
450 return matched
451 time.sleep(build_interval)