blob: be9cdce1fa3be5ab54f65fcea47453a86c3414e0 [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
13import logging
14import os
15import random
16import re
Steve Baker450aa7f2014-08-25 10:37:27 +120017import subprocess
Steve Baker450aa7f2014-08-25 10:37:27 +120018import time
19
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020020import fixtures
Steve Baker450aa7f2014-08-25 10:37:27 +120021from heatclient import exc as heat_exceptions
Pavlo Shchelokovskyyc6b25622015-01-02 13:22:05 +020022from oslo.utils import timeutils
Pavlo Shchelokovskyy60e0ecd2014-12-14 22:17:21 +020023import six
24import testscenarios
25import testtools
Steve Baker450aa7f2014-08-25 10:37:27 +120026
Steve Baker450aa7f2014-08-25 10:37:27 +120027from heat_integrationtests.common import clients
28from heat_integrationtests.common import config
29from heat_integrationtests.common import exceptions
30from heat_integrationtests.common import remote_client
31
32LOG = logging.getLogger(__name__)
Angus Salkeld24043702014-11-21 08:49:26 +100033_LOG_FORMAT = "%(levelname)8s [%(name)s] %(message)s"
Steve Baker450aa7f2014-08-25 10:37:27 +120034
35
Angus Salkeld08514ad2015-02-06 10:08:31 +100036def call_until_true(duration, sleep_for, func, *args, **kwargs):
Steve Baker450aa7f2014-08-25 10:37:27 +120037 """
38 Call the given function until it returns True (and return True) or
39 until the specified duration (in seconds) elapses (and return
40 False).
41
42 :param func: A zero argument callable that returns True on success.
43 :param duration: The number of seconds for which to attempt a
44 successful call of the function.
45 :param sleep_for: The number of seconds to sleep after an unsuccessful
46 invocation of the function.
47 """
48 now = time.time()
49 timeout = now + duration
50 while now < timeout:
Angus Salkeld08514ad2015-02-06 10:08:31 +100051 if func(*args, **kwargs):
Steve Baker450aa7f2014-08-25 10:37:27 +120052 return True
53 LOG.debug("Sleeping for %d seconds", sleep_for)
54 time.sleep(sleep_for)
55 now = time.time()
56 return False
57
58
59def rand_name(name=''):
60 randbits = str(random.randint(1, 0x7fffffff))
61 if name:
62 return name + '-' + randbits
63 else:
64 return randbits
65
66
Angus Salkeld95f65a22014-11-24 12:38:30 +100067class HeatIntegrationTest(testscenarios.WithScenarios,
68 testtools.TestCase):
Steve Baker450aa7f2014-08-25 10:37:27 +120069
70 def setUp(self):
71 super(HeatIntegrationTest, self).setUp()
72
73 self.conf = config.init_conf()
74
75 self.assertIsNotNone(self.conf.auth_url,
76 'No auth_url configured')
77 self.assertIsNotNone(self.conf.username,
78 'No username configured')
79 self.assertIsNotNone(self.conf.password,
80 'No password configured')
81
82 self.manager = clients.ClientManager(self.conf)
83 self.identity_client = self.manager.identity_client
84 self.orchestration_client = self.manager.orchestration_client
85 self.compute_client = self.manager.compute_client
86 self.network_client = self.manager.network_client
87 self.volume_client = self.manager.volume_client
Angus Salkeld4408da32015-02-03 18:53:30 +100088 self.object_client = self.manager.object_client
Angus Salkeld24043702014-11-21 08:49:26 +100089 self.useFixture(fixtures.FakeLogger(format=_LOG_FORMAT))
Steve Baker450aa7f2014-08-25 10:37:27 +120090
Steve Baker450aa7f2014-08-25 10:37:27 +120091 def get_remote_client(self, server_or_ip, username, private_key=None):
92 if isinstance(server_or_ip, six.string_types):
93 ip = server_or_ip
94 else:
95 network_name_for_ssh = self.conf.network_for_ssh
96 ip = server_or_ip.networks[network_name_for_ssh][0]
97 if private_key is None:
98 private_key = self.keypair.private_key
99 linux_client = remote_client.RemoteClient(ip, username,
100 pkey=private_key,
101 conf=self.conf)
102 try:
103 linux_client.validate_authentication()
104 except exceptions.SSHTimeout:
105 LOG.exception('ssh connection to %s failed' % ip)
106 raise
107
108 return linux_client
109
110 def _log_console_output(self, servers=None):
111 if not servers:
112 servers = self.compute_client.servers.list()
113 for server in servers:
114 LOG.debug('Console output for %s', server.id)
115 LOG.debug(server.get_console_output())
116
Sergey Kraynevd6fa5c02015-02-13 03:03:55 -0500117 def _load_template(self, base_file, file_name, sub_dir=None):
118 sub_dir = sub_dir or ''
Steve Baker450aa7f2014-08-25 10:37:27 +1200119 filepath = os.path.join(os.path.dirname(os.path.realpath(base_file)),
Sergey Kraynevd6fa5c02015-02-13 03:03:55 -0500120 sub_dir, file_name)
Steve Baker450aa7f2014-08-25 10:37:27 +1200121 with open(filepath) as f:
122 return f.read()
123
124 def create_keypair(self, client=None, name=None):
125 if client is None:
126 client = self.compute_client
127 if name is None:
128 name = rand_name('heat-keypair')
129 keypair = client.keypairs.create(name)
130 self.assertEqual(keypair.name, name)
131
132 def delete_keypair():
133 keypair.delete()
134
135 self.addCleanup(delete_keypair)
136 return keypair
137
138 @classmethod
139 def _stack_rand_name(cls):
140 return rand_name(cls.__name__)
141
142 def _get_default_network(self):
143 networks = self.network_client.list_networks()
144 for net in networks['networks']:
145 if net['name'] == self.conf.fixed_network_name:
146 return net
147
148 @staticmethod
149 def _stack_output(stack, output_key):
150 """Return a stack output value for a given key."""
151 return next((o['output_value'] for o in stack.outputs
152 if o['output_key'] == output_key), None)
153
154 def _ping_ip_address(self, ip_address, should_succeed=True):
155 cmd = ['ping', '-c1', '-w1', ip_address]
156
157 def ping():
158 proc = subprocess.Popen(cmd,
159 stdout=subprocess.PIPE,
160 stderr=subprocess.PIPE)
161 proc.wait()
162 return (proc.returncode == 0) == should_succeed
163
164 return call_until_true(
Angus Salkeld08514ad2015-02-06 10:08:31 +1000165 self.conf.build_timeout, 1, ping)
Steve Baker450aa7f2014-08-25 10:37:27 +1200166
167 def _wait_for_resource_status(self, stack_identifier, resource_name,
168 status, failure_pattern='^.*_FAILED$',
169 success_on_not_found=False):
170 """Waits for a Resource to reach a given status."""
171 fail_regexp = re.compile(failure_pattern)
172 build_timeout = self.conf.build_timeout
173 build_interval = self.conf.build_interval
174
175 start = timeutils.utcnow()
176 while timeutils.delta_seconds(start,
177 timeutils.utcnow()) < build_timeout:
178 try:
179 res = self.client.resources.get(
180 stack_identifier, resource_name)
181 except heat_exceptions.HTTPNotFound:
182 if success_on_not_found:
183 return
184 # ignore this, as the resource may not have
185 # been created yet
186 else:
187 if res.resource_status == status:
188 return
189 if fail_regexp.search(res.resource_status):
190 raise exceptions.StackResourceBuildErrorException(
191 resource_name=res.resource_name,
192 stack_identifier=stack_identifier,
193 resource_status=res.resource_status,
194 resource_status_reason=res.resource_status_reason)
195 time.sleep(build_interval)
196
197 message = ('Resource %s failed to reach %s status within '
198 'the required time (%s s).' %
199 (res.resource_name, status, build_timeout))
200 raise exceptions.TimeoutException(message)
201
202 def _wait_for_stack_status(self, stack_identifier, status,
203 failure_pattern='^.*_FAILED$',
204 success_on_not_found=False):
205 """
206 Waits for a Stack to reach a given status.
207
208 Note this compares the full $action_$status, e.g
209 CREATE_COMPLETE, not just COMPLETE which is exposed
210 via the status property of Stack in heatclient
211 """
212 fail_regexp = re.compile(failure_pattern)
213 build_timeout = self.conf.build_timeout
214 build_interval = self.conf.build_interval
215
216 start = timeutils.utcnow()
217 while timeutils.delta_seconds(start,
218 timeutils.utcnow()) < build_timeout:
219 try:
220 stack = self.client.stacks.get(stack_identifier)
221 except heat_exceptions.HTTPNotFound:
222 if success_on_not_found:
223 return
224 # ignore this, as the resource may not have
225 # been created yet
226 else:
227 if stack.stack_status == status:
228 return
229 if fail_regexp.search(stack.stack_status):
230 raise exceptions.StackBuildErrorException(
231 stack_identifier=stack_identifier,
232 stack_status=stack.stack_status,
233 stack_status_reason=stack.stack_status_reason)
234 time.sleep(build_interval)
235
236 message = ('Stack %s failed to reach %s status within '
237 'the required time (%s s).' %
238 (stack.stack_name, status, build_timeout))
239 raise exceptions.TimeoutException(message)
240
241 def _stack_delete(self, stack_identifier):
242 try:
243 self.client.stacks.delete(stack_identifier)
244 except heat_exceptions.HTTPNotFound:
245 pass
246 self._wait_for_stack_status(
247 stack_identifier, 'DELETE_COMPLETE',
248 success_on_not_found=True)
Steven Hardyc9efd972014-11-20 11:31:55 +0000249
250 def update_stack(self, stack_identifier, template, environment=None,
251 files=None):
252 env = environment or {}
253 env_files = files or {}
254 stack_name = stack_identifier.split('/')[0]
255 self.client.stacks.update(
256 stack_id=stack_identifier,
257 stack_name=stack_name,
258 template=template,
259 files=env_files,
260 disable_rollback=True,
261 parameters={},
262 environment=env
263 )
264 self._wait_for_stack_status(stack_identifier, 'UPDATE_COMPLETE')
265
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000266 def assert_resource_is_a_stack(self, stack_identifier, res_name):
267 rsrc = self.client.resources.get(stack_identifier, res_name)
268 nested_link = [l for l in rsrc.links if l['rel'] == 'nested']
269 nested_href = nested_link[0]['href']
270 nested_id = nested_href.split('/')[-1]
271 nested_identifier = '/'.join(nested_href.split('/')[-2:])
272 self.assertEqual(rsrc.physical_resource_id, nested_id)
273
274 nested_stack = self.client.stacks.get(nested_id)
275 nested_identifier2 = '%s/%s' % (nested_stack.stack_name,
276 nested_stack.id)
277 self.assertEqual(nested_identifier, nested_identifier2)
278 parent_id = stack_identifier.split("/")[-1]
279 self.assertEqual(parent_id, nested_stack.parent)
280 return nested_identifier
281
Steven Hardyc9efd972014-11-20 11:31:55 +0000282 def list_resources(self, stack_identifier):
283 resources = self.client.resources.list(stack_identifier)
284 return dict((r.resource_name, r.resource_type) for r in resources)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000285
286 def stack_create(self, stack_name=None, template=None, files=None,
Steven Hardy7c1f2242015-01-12 16:32:56 +0000287 parameters=None, environment=None,
288 expected_status='CREATE_COMPLETE'):
Steven Hardyf2c82c02014-11-20 14:02:17 +0000289 name = stack_name or self._stack_rand_name()
290 templ = template or self.template
291 templ_files = files or {}
292 params = parameters or {}
293 env = environment or {}
294 self.client.stacks.create(
295 stack_name=name,
296 template=templ,
297 files=templ_files,
298 disable_rollback=True,
299 parameters=params,
300 environment=env
301 )
302 self.addCleanup(self.client.stacks.delete, name)
303
304 stack = self.client.stacks.get(name)
305 stack_identifier = '%s/%s' % (name, stack.id)
Steven Hardy7c1f2242015-01-12 16:32:56 +0000306 self._wait_for_stack_status(stack_identifier, expected_status)
Steven Hardyf2c82c02014-11-20 14:02:17 +0000307 return stack_identifier
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000308
309 def stack_adopt(self, stack_name=None, files=None,
310 parameters=None, environment=None, adopt_data=None,
311 wait_for_status='ADOPT_COMPLETE'):
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530312 if self.conf.skip_stack_adopt_tests:
313 self.skipTest('Testing Stack adopt disabled in conf, skipping')
Angus Salkeld2bd63a42015-01-07 11:11:29 +1000314 name = stack_name or self._stack_rand_name()
315 templ_files = files or {}
316 params = parameters or {}
317 env = environment or {}
318 self.client.stacks.create(
319 stack_name=name,
320 files=templ_files,
321 disable_rollback=True,
322 parameters=params,
323 environment=env,
324 adopt_stack_data=adopt_data,
325 )
326 self.addCleanup(self.client.stacks.delete, name)
327
328 stack = self.client.stacks.get(name)
329 stack_identifier = '%s/%s' % (name, stack.id)
330 self._wait_for_stack_status(stack_identifier, wait_for_status)
331 return stack_identifier
Sirushti Murugesan04ee8022015-02-02 23:00:23 +0530332
333 def stack_abandon(self, stack_id):
334 if self.conf.skip_stack_abandon_tests:
335 self.addCleanup(self.client.stacks.delete, stack_id)
336 self.skipTest('Testing Stack abandon disabled in conf, skipping')
337 info = self.client.stacks.abandon(stack_id=stack_id)
338 return info