blob: f772c84aee4090b2f8cfb913a7acd4f59b42b66d [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
Steve Baker24641292015-03-13 10:47:50 +130021from oslo_log import log as logging
Jens Rosenboom4f069fb2015-02-18 14:19:07 +010022from oslo_utils import timeutils
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020023import six
Sirushti Murugesan4920fda2015-04-22 00:35:26 +053024from six.moves import urllib
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020025import 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:
Sirushti Murugesan4920fda2015-04-22 00:35:26 +0530114 urllib.request.urlopen('http://%s/' % ip)
Anastasia Kuznetsova3e0ab4d2015-03-06 18:10:13 +0400115 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
Sergey Kraynev83ef84d2015-04-29 05:31:54 -0400175 def _get_subnet_by_version(self, network, ip_version=4):
176 for subnet_id in self.net['subnets']:
177 subnet_info = self.network_client.show_subnet(subnet_id)
178 if subnet_info['subnet']['ip_version'] == ip_version:
179 return subnet_id
180
Rabi Mishra95ac9aa2015-04-30 10:40:43 +0530181 def _get_server_ip_by_version(self, addresses, ip_version=4):
182 for address in addresses:
183 if address['version'] == ip_version:
184 return address['addr']
185
Steve Baker450aa7f2014-08-25 10:37:27 +1200186 @staticmethod
187 def _stack_output(stack, output_key):
188 """Return a stack output value for a given key."""
189 return next((o['output_value'] for o in stack.outputs
190 if o['output_key'] == output_key), None)
191
192 def _ping_ip_address(self, ip_address, should_succeed=True):
193 cmd = ['ping', '-c1', '-w1', ip_address]
194
195 def ping():
196 proc = subprocess.Popen(cmd,
197 stdout=subprocess.PIPE,
198 stderr=subprocess.PIPE)
199 proc.wait()
200 return (proc.returncode == 0) == should_succeed
201
202 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000203 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200204
Angus Salkelda7500d12015-04-10 15:44:07 +1000205 def _wait_for_all_resource_status(self, stack_identifier,
206 status, failure_pattern='^.*_FAILED$',
207 success_on_not_found=False):
208 for res in self.client.resources.list(stack_identifier):
209 self._wait_for_resource_status(
210 stack_identifier, res.resource_name,
211 status, failure_pattern=failure_pattern,
212 success_on_not_found=success_on_not_found)
213
Steve Baker450aa7f2014-08-25 10:37:27 +1200214 def _wait_for_resource_status(self, stack_identifier, resource_name,
215 status, failure_pattern='^.*_FAILED$',
216 success_on_not_found=False):
217 """Waits for a Resource to reach a given status."""
218 fail_regexp = re.compile(failure_pattern)
219 build_timeout = self.conf.build_timeout
220 build_interval = self.conf.build_interval
221
222 start = timeutils.utcnow()
223 while timeutils.delta_seconds(start,
224 timeutils.utcnow()) < build_timeout:
225 try:
226 res = self.client.resources.get(
227 stack_identifier, resource_name)
228 except heat_exceptions.HTTPNotFound:
229 if success_on_not_found:
230 return
231 # ignore this, as the resource may not have
232 # been created yet
233 else:
234 if res.resource_status == status:
235 return
236 if fail_regexp.search(res.resource_status):
237 raise exceptions.StackResourceBuildErrorException(
238 resource_name=res.resource_name,
239 stack_identifier=stack_identifier,
240 resource_status=res.resource_status,
241 resource_status_reason=res.resource_status_reason)
242 time.sleep(build_interval)
243
244 message = ('Resource %s failed to reach %s status within '
245 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400246 (resource_name, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200247 raise exceptions.TimeoutException(message)
248
249 def _wait_for_stack_status(self, stack_identifier, status,
250 failure_pattern='^.*_FAILED$',
251 success_on_not_found=False):
252 """
253 Waits for a Stack to reach a given status.
254
255 Note this compares the full $action_$status, e.g
256 CREATE_COMPLETE, not just COMPLETE which is exposed
257 via the status property of Stack in heatclient
258 """
259 fail_regexp = re.compile(failure_pattern)
260 build_timeout = self.conf.build_timeout
261 build_interval = self.conf.build_interval
262
263 start = timeutils.utcnow()
264 while timeutils.delta_seconds(start,
265 timeutils.utcnow()) < build_timeout:
266 try:
267 stack = self.client.stacks.get(stack_identifier)
268 except heat_exceptions.HTTPNotFound:
269 if success_on_not_found:
270 return
271 # ignore this, as the resource may not have
272 # been created yet
273 else:
274 if stack.stack_status == status:
275 return
276 if fail_regexp.search(stack.stack_status):
277 raise exceptions.StackBuildErrorException(
278 stack_identifier=stack_identifier,
279 stack_status=stack.stack_status,
280 stack_status_reason=stack.stack_status_reason)
281 time.sleep(build_interval)
282
283 message = ('Stack %s failed to reach %s status within '
284 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400285 (stack_identifier, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200286 raise exceptions.TimeoutException(message)
287
288 def _stack_delete(self, stack_identifier):
289 try:
290 self.client.stacks.delete(stack_identifier)
291 except heat_exceptions.HTTPNotFound:
292 pass
293 self._wait_for_stack_status(
294 stack_identifier, 'DELETE_COMPLETE',
295 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000296
297 def update_stack(self, stack_identifier, template, environment=None,
Steven Hardy03da0742015-03-19 00:13:17 -0400298 files=None, parameters=None,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530299 expected_status='UPDATE_COMPLETE',
300 disable_rollback=True):
Steven Hardyc9efd972014-11-20 11:31:55 +0000301 env = environment or {}
302 env_files = files or {}
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500303 parameters = parameters or {}
Steven Hardyc9efd972014-11-20 11:31:55 +0000304 stack_name = stack_identifier.split('/')[0]
305 self.client.stacks.update(
306 stack_id=stack_identifier,
307 stack_name=stack_name,
308 template=template,
309 files=env_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530310 disable_rollback=disable_rollback,
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500311 parameters=parameters,
Steven Hardyc9efd972014-11-20 11:31:55 +0000312 environment=env
313 )
Rakesh H Sa3325d62015-04-04 19:42:29 +0530314 kwargs = {'stack_identifier': stack_identifier,
315 'status': expected_status}
316 if expected_status in ['ROLLBACK_COMPLETE']:
317 self.addCleanup(self.client.stacks.delete, stack_name)
318 # To trigger rollback you would intentionally fail the stack
319 # Hence check for rollback failures
320 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
321
322 self._wait_for_stack_status(**kwargs)
Steven Hardyc9efd972014-11-20 11:31:55 +0000323
Steven Hardy03da0742015-03-19 00:13:17 -0400324 def assert_resource_is_a_stack(self, stack_identifier, res_name,
325 wait=False):
326 build_timeout = self.conf.build_timeout
327 build_interval = self.conf.build_interval
328 start = timeutils.utcnow()
329 while timeutils.delta_seconds(start,
330 timeutils.utcnow()) < build_timeout:
331 time.sleep(build_interval)
332 try:
333 nested_identifier = self._get_nested_identifier(
334 stack_identifier, res_name)
335 except Exception:
336 # We may have to wait, if the create is in-progress
337 if wait:
338 time.sleep(build_interval)
339 else:
340 raise
341 else:
342 return nested_identifier
343
344 def _get_nested_identifier(self, stack_identifier, res_name):
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000345 rsrc = self.client.resources.get(stack_identifier, res_name)
346 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
347 nested_href = nested_link[0]['href']
348 nested_id = nested_href.split('/')[-1]
349 nested_identifier = '/'.join(nested_href.split('/')[-2:])
350 self.assertEqual(rsrc.physical_resource_id, nested_id)
351
352 nested_stack = self.client.stacks.get(nested_id)
353 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
354 nested_stack.id)
355 self.assertEqual(nested_identifier, nested_identifier2)
356 parent_id = stack_identifier.split("/")[-1]
357 self.assertEqual(parent_id, nested_stack.parent)
358 return nested_identifier
359
Steven Hardyc9efd972014-11-20 11:31:55 +0000360 def list_resources(self, stack_identifier):
361 resources = self.client.resources.list(stack_identifier)
362 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000363
364 def stack_create(self, stack_name=None, template=None, files=None,
Steven Hardy7c1f2242015-01-12 16:32:56 +0000365 parameters=None, environment=None,
Sergey Kraynevbf67ce32015-04-17 10:54:20 -0400366 expected_status='CREATE_COMPLETE', disable_rollback=True,
367 enable_cleanup=True):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000368 name = stack_name or self._stack_rand_name()
369 templ = template or self.template
370 templ_files = files or {}
371 params = parameters or {}
372 env = environment or {}
373 self.client.stacks.create(
374 stack_name=name,
375 template=templ,
376 files=templ_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530377 disable_rollback=disable_rollback,
Steven Hardyf2c82c02014-11-20 14:02:17 +0000378 parameters=params,
379 environment=env
380 )
Sergey Kraynevbf67ce32015-04-17 10:54:20 -0400381 if expected_status not in ['ROLLBACK_COMPLETE'] and enable_cleanup:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530382 self.addCleanup(self.client.stacks.delete, name)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000383
384 stack = self.client.stacks.get(name)
385 stack_identifier = '%s/%s' % (name, stack.id)
Rakesh H Sa3325d62015-04-04 19:42:29 +0530386 kwargs = {'stack_identifier': stack_identifier,
387 'status': expected_status}
Steve Bakerf6c8f122015-02-10 13:54:46 +1300388 if expected_status:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530389 if expected_status in ['ROLLBACK_COMPLETE']:
390 # To trigger rollback you would intentionally fail the stack
391 # Hence check for rollback failures
392 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
393 self._wait_for_stack_status(**kwargs)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000394 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000395
396 def stack_adopt(self, stack_name=None, files=None,
397 parameters=None, environment=None, adopt_data=None,
398 wait_for_status='ADOPT_COMPLETE'):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530399 if self.conf.skip_stack_adopt_tests:
400 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000401 name = stack_name or self._stack_rand_name()
402 templ_files = files or {}
403 params = parameters or {}
404 env = environment or {}
405 self.client.stacks.create(
406 stack_name=name,
407 files=templ_files,
408 disable_rollback=True,
409 parameters=params,
410 environment=env,
411 adopt_stack_data=adopt_data,
412 )
413 self.addCleanup(self.client.stacks.delete, name)
414
415 stack = self.client.stacks.get(name)
416 stack_identifier = '%s/%s' % (name, stack.id)
417 self._wait_for_stack_status(stack_identifier, wait_for_status)
418 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530419
420 def stack_abandon(self, stack_id):
421 if self.conf.skip_stack_abandon_tests:
422 self.addCleanup(self.client.stacks.delete, stack_id)
423 self.skipTest('Testing Stack abandon disabled in conf, skipping')
424 info = self.client.stacks.abandon(stack_id=stack_id)
425 return info
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500426
427 def stack_suspend(self, stack_identifier):
428 stack_name = stack_identifier.split('/')[0]
429 self.client.actions.suspend(stack_name)
Angus Salkelda7500d12015-04-10 15:44:07 +1000430
431 # improve debugging by first checking the resource's state.
432 self._wait_for_all_resource_status(stack_identifier,
433 'SUSPEND_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500434 self._wait_for_stack_status(stack_identifier, 'SUSPEND_COMPLETE')
435
436 def stack_resume(self, stack_identifier):
437 stack_name = stack_identifier.split('/')[0]
438 self.client.actions.resume(stack_name)
Angus Salkelda7500d12015-04-10 15:44:07 +1000439
440 # improve debugging by first checking the resource's state.
441 self._wait_for_all_resource_status(stack_identifier,
442 'RESUME_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500443 self._wait_for_stack_status(stack_identifier, 'RESUME_COMPLETE')
Steven Hardy03da0742015-03-19 00:13:17 -0400444
445 def wait_for_event_with_reason(self, stack_identifier, reason,
446 rsrc_name=None, num_expected=1):
447 build_timeout = self.conf.build_timeout
448 build_interval = self.conf.build_interval
449 start = timeutils.utcnow()
450 while timeutils.delta_seconds(start,
451 timeutils.utcnow()) < build_timeout:
452 try:
453 rsrc_events = self.client.events.list(stack_identifier,
454 resource_name=rsrc_name)
455 except heat_exceptions.HTTPNotFound:
456 LOG.debug("No events yet found for %s" % rsrc_name)
457 else:
458 matched = [e for e in rsrc_events
459 if e.resource_status_reason == reason]
460 if len(matched) == num_expected:
461 return matched
462 time.sleep(build_interval)