blob: 0f8442b533cf7e358f44f439a642391b7ab46dd3 [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
Steve Baker450aa7f2014-08-25 10:37:27 +1200181 @staticmethod
182 def _stack_output(stack, output_key):
183 """Return a stack output value for a given key."""
184 return next((o['output_value'] for o in stack.outputs
185 if o['output_key'] == output_key), None)
186
187 def _ping_ip_address(self, ip_address, should_succeed=True):
188 cmd = ['ping', '-c1', '-w1', ip_address]
189
190 def ping():
191 proc = subprocess.Popen(cmd,
192 stdout=subprocess.PIPE,
193 stderr=subprocess.PIPE)
194 proc.wait()
195 return (proc.returncode == 0) == should_succeed
196
197 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000198 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200199
Angus Salkelda7500d12015-04-10 15:44:07 +1000200 def _wait_for_all_resource_status(self, stack_identifier,
201 status, failure_pattern='^.*_FAILED$',
202 success_on_not_found=False):
203 for res in self.client.resources.list(stack_identifier):
204 self._wait_for_resource_status(
205 stack_identifier, res.resource_name,
206 status, failure_pattern=failure_pattern,
207 success_on_not_found=success_on_not_found)
208
Steve Baker450aa7f2014-08-25 10:37:27 +1200209 def _wait_for_resource_status(self, stack_identifier, resource_name,
210 status, failure_pattern='^.*_FAILED$',
211 success_on_not_found=False):
212 """Waits for a Resource to reach a given status."""
213 fail_regexp = re.compile(failure_pattern)
214 build_timeout = self.conf.build_timeout
215 build_interval = self.conf.build_interval
216
217 start = timeutils.utcnow()
218 while timeutils.delta_seconds(start,
219 timeutils.utcnow()) < build_timeout:
220 try:
221 res = self.client.resources.get(
222 stack_identifier, resource_name)
223 except heat_exceptions.HTTPNotFound:
224 if success_on_not_found:
225 return
226 # ignore this, as the resource may not have
227 # been created yet
228 else:
229 if res.resource_status == status:
230 return
231 if fail_regexp.search(res.resource_status):
232 raise exceptions.StackResourceBuildErrorException(
233 resource_name=res.resource_name,
234 stack_identifier=stack_identifier,
235 resource_status=res.resource_status,
236 resource_status_reason=res.resource_status_reason)
237 time.sleep(build_interval)
238
239 message = ('Resource %s failed to reach %s status within '
240 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400241 (resource_name, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200242 raise exceptions.TimeoutException(message)
243
244 def _wait_for_stack_status(self, stack_identifier, status,
245 failure_pattern='^.*_FAILED$',
246 success_on_not_found=False):
247 """
248 Waits for a Stack to reach a given status.
249
250 Note this compares the full $action_$status, e.g
251 CREATE_COMPLETE, not just COMPLETE which is exposed
252 via the status property of Stack in heatclient
253 """
254 fail_regexp = re.compile(failure_pattern)
255 build_timeout = self.conf.build_timeout
256 build_interval = self.conf.build_interval
257
258 start = timeutils.utcnow()
259 while timeutils.delta_seconds(start,
260 timeutils.utcnow()) < build_timeout:
261 try:
262 stack = self.client.stacks.get(stack_identifier)
263 except heat_exceptions.HTTPNotFound:
264 if success_on_not_found:
265 return
266 # ignore this, as the resource may not have
267 # been created yet
268 else:
269 if stack.stack_status == status:
270 return
271 if fail_regexp.search(stack.stack_status):
272 raise exceptions.StackBuildErrorException(
273 stack_identifier=stack_identifier,
274 stack_status=stack.stack_status,
275 stack_status_reason=stack.stack_status_reason)
276 time.sleep(build_interval)
277
278 message = ('Stack %s failed to reach %s status within '
279 'the required time (%s s).' %
Anastasia Kuznetsova9a745572015-03-04 13:19:15 +0400280 (stack_identifier, status, build_timeout))
Steve Baker450aa7f2014-08-25 10:37:27 +1200281 raise exceptions.TimeoutException(message)
282
283 def _stack_delete(self, stack_identifier):
284 try:
285 self.client.stacks.delete(stack_identifier)
286 except heat_exceptions.HTTPNotFound:
287 pass
288 self._wait_for_stack_status(
289 stack_identifier, 'DELETE_COMPLETE',
290 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000291
292 def update_stack(self, stack_identifier, template, environment=None,
Steven Hardy03da0742015-03-19 00:13:17 -0400293 files=None, parameters=None,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530294 expected_status='UPDATE_COMPLETE',
295 disable_rollback=True):
Steven Hardyc9efd972014-11-20 11:31:55 +0000296 env = environment or {}
297 env_files = files or {}
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500298 parameters = parameters or {}
Steven Hardyc9efd972014-11-20 11:31:55 +0000299 stack_name = stack_identifier.split('/')[0]
300 self.client.stacks.update(
301 stack_id=stack_identifier,
302 stack_name=stack_name,
303 template=template,
304 files=env_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530305 disable_rollback=disable_rollback,
Sergey Kraynevbcc78df2015-02-27 04:34:32 -0500306 parameters=parameters,
Steven Hardyc9efd972014-11-20 11:31:55 +0000307 environment=env
308 )
Rakesh H Sa3325d62015-04-04 19:42:29 +0530309 kwargs = {'stack_identifier': stack_identifier,
310 'status': expected_status}
311 if expected_status in ['ROLLBACK_COMPLETE']:
312 self.addCleanup(self.client.stacks.delete, stack_name)
313 # To trigger rollback you would intentionally fail the stack
314 # Hence check for rollback failures
315 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
316
317 self._wait_for_stack_status(**kwargs)
Steven Hardyc9efd972014-11-20 11:31:55 +0000318
Steven Hardy03da0742015-03-19 00:13:17 -0400319 def assert_resource_is_a_stack(self, stack_identifier, res_name,
320 wait=False):
321 build_timeout = self.conf.build_timeout
322 build_interval = self.conf.build_interval
323 start = timeutils.utcnow()
324 while timeutils.delta_seconds(start,
325 timeutils.utcnow()) < build_timeout:
326 time.sleep(build_interval)
327 try:
328 nested_identifier = self._get_nested_identifier(
329 stack_identifier, res_name)
330 except Exception:
331 # We may have to wait, if the create is in-progress
332 if wait:
333 time.sleep(build_interval)
334 else:
335 raise
336 else:
337 return nested_identifier
338
339 def _get_nested_identifier(self, stack_identifier, res_name):
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000340 rsrc = self.client.resources.get(stack_identifier, res_name)
341 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
342 nested_href = nested_link[0]['href']
343 nested_id = nested_href.split('/')[-1]
344 nested_identifier = '/'.join(nested_href.split('/')[-2:])
345 self.assertEqual(rsrc.physical_resource_id, nested_id)
346
347 nested_stack = self.client.stacks.get(nested_id)
348 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
349 nested_stack.id)
350 self.assertEqual(nested_identifier, nested_identifier2)
351 parent_id = stack_identifier.split("/")[-1]
352 self.assertEqual(parent_id, nested_stack.parent)
353 return nested_identifier
354
Steven Hardyc9efd972014-11-20 11:31:55 +0000355 def list_resources(self, stack_identifier):
356 resources = self.client.resources.list(stack_identifier)
357 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000358
359 def stack_create(self, stack_name=None, template=None, files=None,
Steven Hardy7c1f2242015-01-12 16:32:56 +0000360 parameters=None, environment=None,
Sergey Kraynevbf67ce32015-04-17 10:54:20 -0400361 expected_status='CREATE_COMPLETE', disable_rollback=True,
362 enable_cleanup=True):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000363 name = stack_name or self._stack_rand_name()
364 templ = template or self.template
365 templ_files = files or {}
366 params = parameters or {}
367 env = environment or {}
368 self.client.stacks.create(
369 stack_name=name,
370 template=templ,
371 files=templ_files,
Rakesh H Sa3325d62015-04-04 19:42:29 +0530372 disable_rollback=disable_rollback,
Steven Hardyf2c82c02014-11-20 14:02:17 +0000373 parameters=params,
374 environment=env
375 )
Sergey Kraynevbf67ce32015-04-17 10:54:20 -0400376 if expected_status not in ['ROLLBACK_COMPLETE'] and enable_cleanup:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530377 self.addCleanup(self.client.stacks.delete, name)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000378
379 stack = self.client.stacks.get(name)
380 stack_identifier = '%s/%s' % (name, stack.id)
Rakesh H Sa3325d62015-04-04 19:42:29 +0530381 kwargs = {'stack_identifier': stack_identifier,
382 'status': expected_status}
Steve Bakerf6c8f122015-02-10 13:54:46 +1300383 if expected_status:
Rakesh H Sa3325d62015-04-04 19:42:29 +0530384 if expected_status in ['ROLLBACK_COMPLETE']:
385 # To trigger rollback you would intentionally fail the stack
386 # Hence check for rollback failures
387 kwargs['failure_pattern'] = '^ROLLBACK_FAILED$'
388 self._wait_for_stack_status(**kwargs)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000389 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000390
391 def stack_adopt(self, stack_name=None, files=None,
392 parameters=None, environment=None, adopt_data=None,
393 wait_for_status='ADOPT_COMPLETE'):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530394 if self.conf.skip_stack_adopt_tests:
395 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000396 name = stack_name or self._stack_rand_name()
397 templ_files = files or {}
398 params = parameters or {}
399 env = environment or {}
400 self.client.stacks.create(
401 stack_name=name,
402 files=templ_files,
403 disable_rollback=True,
404 parameters=params,
405 environment=env,
406 adopt_stack_data=adopt_data,
407 )
408 self.addCleanup(self.client.stacks.delete, name)
409
410 stack = self.client.stacks.get(name)
411 stack_identifier = '%s/%s' % (name, stack.id)
412 self._wait_for_stack_status(stack_identifier, wait_for_status)
413 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530414
415 def stack_abandon(self, stack_id):
416 if self.conf.skip_stack_abandon_tests:
417 self.addCleanup(self.client.stacks.delete, stack_id)
418 self.skipTest('Testing Stack abandon disabled in conf, skipping')
419 info = self.client.stacks.abandon(stack_id=stack_id)
420 return info
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500421
422 def stack_suspend(self, stack_identifier):
423 stack_name = stack_identifier.split('/')[0]
424 self.client.actions.suspend(stack_name)
Angus Salkelda7500d12015-04-10 15:44:07 +1000425
426 # improve debugging by first checking the resource's state.
427 self._wait_for_all_resource_status(stack_identifier,
428 'SUSPEND_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500429 self._wait_for_stack_status(stack_identifier, 'SUSPEND_COMPLETE')
430
431 def stack_resume(self, stack_identifier):
432 stack_name = stack_identifier.split('/')[0]
433 self.client.actions.resume(stack_name)
Angus Salkelda7500d12015-04-10 15:44:07 +1000434
435 # improve debugging by first checking the resource's state.
436 self._wait_for_all_resource_status(stack_identifier,
437 'RESUME_COMPLETE')
Oleksii Chuprykovd9cd9dc2015-02-03 10:34:55 -0500438 self._wait_for_stack_status(stack_identifier, 'RESUME_COMPLETE')
Steven Hardy03da0742015-03-19 00:13:17 -0400439
440 def wait_for_event_with_reason(self, stack_identifier, reason,
441 rsrc_name=None, num_expected=1):
442 build_timeout = self.conf.build_timeout
443 build_interval = self.conf.build_interval
444 start = timeutils.utcnow()
445 while timeutils.delta_seconds(start,
446 timeutils.utcnow()) < build_timeout:
447 try:
448 rsrc_events = self.client.events.list(stack_identifier,
449 resource_name=rsrc_name)
450 except heat_exceptions.HTTPNotFound:
451 LOG.debug("No events yet found for %s" % rsrc_name)
452 else:
453 matched = [e for e in rsrc_events
454 if e.resource_status_reason == reason]
455 if len(matched) == num_expected:
456 return matched
457 time.sleep(build_interval)