forked from openstack-charmers/zaza-openstack-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
557 lines (469 loc) · 22.9 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
# Copyright 2019 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Encapsulate policyd testing.
The Policyd Tests test the following:
- Two general tests in the PolicydTest class that check that a policy zip can
drop policy files in the correct service policy.d directory. One test tests
that a valid yaml file is dropped; the 2nd that an invalid one is not dropped
and the workload info status line shows that it is broken.
- A custom policyd test that is per charm and tests that a policy zip file
attached does actually disable something in the associated service (i.e.
verify that the charm has implemented policy overrides and ensured that the
service actually picks them up).
If a charm doesn't require a specific test, then the GenericPolicydTest class
can be used that just includes the two generic tests. The config in the
tests.yaml would stil be required. See the PolicydTest class docstring for
further details.
"""
import logging
import os
import shutil
import tempfile
import unittest
import zipfile
import keystoneauth1
import glanceclient.common.exceptions
import cinderclient.exceptions
import zaza.model as zaza_model
import zaza.openstack.charm_tests.test_utils as test_utils
import zaza.openstack.utilities.openstack as openstack_utils
import zaza.openstack.charm_tests.keystone as ch_keystone
import zaza.openstack.utilities.exceptions as zaza_exceptions
class PolicydTest(object):
"""Charm operation tests.
The policyd test needs some config from the tests.yaml in order to work
properly. A top level key of "tests_options". Under that key is
'policyd', and then the k:v of 'service': <name>. e.g. for keystone
tests_options:
policyd:
service: keystone
"""
@classmethod
def setUpClass(cls, application_name=None):
"""Run class setup for running Policyd charm operation tests."""
super(PolicydTest, cls).setUpClass(application_name)
cls._tmp_dir = tempfile.mkdtemp()
cls._service_name = \
cls.test_config['tests_options']['policyd']['service']
@classmethod
def tearDownClass(cls):
"""Run class tearDown for running Policyd charm operation tests."""
super(PolicydTest, cls).tearDownClass()
try:
shutil.rmtree(cls._tmp_dir, ignore_errors=True)
except Exception as e:
logging.error("Removing the policyd tempdir/files failed: {}"
.format(str(e)))
def _set_config(self, state):
s = "True" if state else "False"
config = {"use-policyd-override": s}
logging.info("Setting config to {}".format(config))
zaza_model.set_application_config(self.application_name, config)
def _make_zip_file_from(self, name, files):
"""Make a zip file from a dictionary of filename: string.
:param name: the name of the zip file
:type name: PathLike
:param files: a dict of name: string to construct the files from.
:type files: Dict[str, str]
:returns: temp file that is the zip file.
:rtype: PathLike
"""
path = os.path.join(self._tmp_dir, name)
with zipfile.ZipFile(path, "w") as zfp:
for name, contents in files.items():
zfp.writestr(name, contents)
return path
def _set_policy_with(self, rules):
rules_zip_path = self._make_zip_file_from('rules.zip', rules)
zaza_model.attach_resource(self.application_name,
'policyd-override',
rules_zip_path)
self._set_config(True)
zaza_model.block_until_wl_status_info_starts_with(
self.application_name, "PO:", negate_match=False)
def test_001_policyd_good_yaml(self):
"""Test that the policyd with a good zipped yaml file."""
good = {
'file1.yaml': "{'rule1': '!'}"
}
good_zip_path = self._make_zip_file_from('good.zip', good)
logging.info("Attaching good zip file as a resource.")
zaza_model.attach_resource(self.application_name,
'policyd-override',
good_zip_path)
zaza_model.block_until_all_units_idle()
logging.debug("Now setting config to true")
self._set_config(True)
# check that the file gets to the right location
path = os.path.join(
"/etc", self._service_name, "policy.d", 'file1.yaml')
logging.info("Now checking for file contents: {}".format(path))
zaza_model.block_until_file_has_contents(self.application_name,
path,
"rule1: '!'")
# ensure that the workload status info line starts with PO:
logging.info("Checking for workload status line starts with PO:")
zaza_model.block_until_wl_status_info_starts_with(
self.application_name, "PO:")
logging.debug("App status is valid")
# disable the policy override
logging.info("Disabling policy override by setting config to false")
self._set_config(False)
# check that the status no longer has "PO:" on it.
# we have to do it twice due to async races and that some info lines
# erase the PO: bit prior to actuall getting back to idle. The double
# check verifies that the charms have started, the idle waits until it
# is finished, and then the final check really makes sure they got
# switched off.
zaza_model.block_until_wl_status_info_starts_with(
self.application_name, "PO:", negate_match=True)
zaza_model.block_until_all_units_idle()
zaza_model.block_until_wl_status_info_starts_with(
self.application_name, "PO:", negate_match=True)
# verify that the file no longer exists
logging.info("Checking that {} has been removed".format(path))
zaza_model.block_until_file_missing(self.application_name, path)
logging.info("OK")
def test_002_policyd_bad_yaml(self):
"""Test bad yaml file in the zip file is handled."""
bad = {
"file2.yaml": "{'rule': '!}"
}
bad_zip_path = self._make_zip_file_from('bad.zip', bad)
logging.info("Attaching bad zip file as a resource")
zaza_model.attach_resource(self.application_name,
'policyd-override',
bad_zip_path)
zaza_model.block_until_all_units_idle()
logging.debug("Now setting config to true")
self._set_config(True)
# ensure that the workload status info line starts with PO (broken):
# to show that it didn't work
logging.info(
"Checking for workload status line starts with PO (broken):")
zaza_model.block_until_wl_status_info_starts_with(
self.application_name, "PO (broken):")
logging.debug("App status is valid for broken yaml file")
zaza_model.block_until_all_units_idle()
# now verify that no file got landed on the machine
path = os.path.join(
"/etc", self._service_name, "policy.d", 'file2.yaml')
logging.info("Now checking that file {} is not present.".format(path))
zaza_model.block_until_file_missing(self.application_name, path)
self._set_config(False)
zaza_model.block_until_all_units_idle()
logging.info("OK")
class GenericPolicydTest(PolicydTest, test_utils.OpenStackBaseTest):
"""Generic policyd test for any charm without a specific test."""
@classmethod
def setUpClass(cls, application_name=None):
"""Run class setup for running KeystonePolicydTest tests."""
super(GenericPolicydTest, cls).setUpClass(application_name)
if (openstack_utils.get_os_release() <
openstack_utils.get_os_release('xenial_queens')):
raise unittest.SkipTest(
"zaza.openstack.charm_tests.policyd.tests.GenericPolicydTest "
"not valid before xenial_queens")
class PolicydOperationFailedException(Exception):
"""This is raised by the get_client_and_attempt_operation() method.
This is used to signal that the operation in the
get_client_and_attempt_operation() method in the BaseSpecialization class
has failed.
"""
pass
class BasePolicydSpecialization(PolicydTest,
ch_keystone.BaseKeystoneTest,
test_utils.OpenStackBaseTest):
"""Base test for specialising Policyd override tests.
This class is for specialization of the test to verify that a yaml file
placed in the policy.d director is observed. This is done by first calling
the get_client_and_attempt_operation() method and ensuring that it works.
This method should attempt an operation on the service that can be blocked
by the policy override in the `_rule` class variable. The method should
pass cleanly without the override in place.
The test_003_test_overide_is_observed will then apply the override and then
call get_client_and_attempt_operation() again, and this time it should
detect the failure and raise the PolicydOperationFailedException()
exception. This will be detected as the override working and thus the test
will pass.
The test will fail if the first call fails for any reason, or if the 2nd
call doesn't raise PolicydOperationFailedException or raises any other
exception.
To use this class, follow the keystone example:
class KeystonePolicydTest(BasePolicydSpecialization):
_rule = "{'identity:list_services': '!'}"
def get_client_and_attempt_operation(self, keystone_session):
... etc.
"""
# this needs to be defined as the rule that gets placed into a yaml policy
# override. It is a string of the form: 'some-rule: "!"'
# i.e. disable some policy and then try and test it.
_rule = None
# Optional: the name to log at the beginning of the test
_test_name = None
@classmethod
def setUpClass(cls, application_name=None):
"""Run class setup for running KeystonePolicydTest tests."""
super(BasePolicydSpecialization, cls).setUpClass(application_name)
if (openstack_utils.get_os_release() <
openstack_utils.get_os_release('xenial_queens')):
raise unittest.SkipTest(
"zaza.openstack.charm_tests.policyd.tests.* "
"not valid before xenial_queens")
if cls._rule is None:
raise unittest.SkipTest(
"zaza.openstack.charm_tests.policyd.tests.* "
"not valid if {}.rule is not configured"
.format(cls.__name__))
def get_client_and_attempt_operation(self, keystone_session):
"""Override this method to perform the operation.
This operation should pass normally for the demo_user, and fail when
the rule has been overriden (see the `rule` class variable.
:param keystone_session: the keystone session to use to obtain the
client necessary for the test.
:type keystone_session: keystoneauth1.session.Session
:raises: PolicydOperationFailedException if operation fails.
"""
raise NotImplementedError("This method must be overridden")
def _get_keystone_session(self, ip, openrc, scope='DOMAIN'):
"""Return the keystone session for the IP address passed.
:param ip: the IP address to get the session against.
:type ip: str
:param openrc: the params to authenticate with.
:type openrc: Dict[str, str]
:param scope: the scope of the token
:type scope: str
:returns: a keystone session to the IP address
:rtype: keystoneauth1.session.Session
"""
logging.info('Authentication for {} on keystone IP {}'
.format(openrc['OS_USERNAME'], ip))
if self.tls_rid:
openrc['OS_CACERT'] = \
openstack_utils.KEYSTONE_LOCAL_CACERT
openrc['OS_AUTH_URL'] = (
openrc['OS_AUTH_URL'].replace('http', 'https'))
logging.info('keystone IP {}'.format(ip))
keystone_session = openstack_utils.get_keystone_session(
openrc, scope=scope)
return keystone_session
def get_keystone_session_demo_user(self, ip, scope='PROJECT'):
"""Return the keystone session for demo user.
:param ip: the IP address to get the session against.
:type ip: str
:param scope: the scope of the token
:type scope: str
:returns: a keystone session to the IP address
:rtype: keystoneauth1.session.Session
"""
return self._get_keystone_session(ip, {
'API_VERSION': 3,
'OS_USERNAME': ch_keystone.DEMO_USER,
'OS_PASSWORD': ch_keystone.DEMO_PASSWORD,
'OS_AUTH_URL': 'http://{}:5000/v3'.format(ip),
'OS_USER_DOMAIN_NAME': ch_keystone.DEMO_DOMAIN,
'OS_PROJECT_DOMAIN_NAME': ch_keystone.DEMO_DOMAIN,
'OS_PROJECT_NAME': ch_keystone.DEMO_PROJECT,
'OS_DOMAIN_NAME': ch_keystone.DEMO_DOMAIN,
}, scope)
def get_keystone_session_demo_admin_user(self, ip, scope='PROJECT'):
"""Return the keystone session demo_admin user.
:param ip: the IP address to get the session against.
:type ip: str
:param scope: the scope of the token
:type scope: str
:returns: a keystone session to the IP address
:rtype: keystoneauth1.session.Session
"""
return self._get_keystone_session(ip, {
'API_VERSION': 3,
'OS_USERNAME': ch_keystone.DEMO_ADMIN_USER,
'OS_PASSWORD': ch_keystone.DEMO_ADMIN_USER_PASSWORD,
'OS_AUTH_URL': 'http://{}:5000/v3'.format(ip),
'OS_USER_DOMAIN_NAME': ch_keystone.DEMO_DOMAIN,
'OS_PROJECT_DOMAIN_NAME': ch_keystone.DEMO_DOMAIN,
'OS_PROJECT_NAME': ch_keystone.DEMO_PROJECT,
'OS_DOMAIN_NAME': ch_keystone.DEMO_DOMAIN,
}, scope)
def get_keystone_session_admin_user(self, ip):
"""Return the keystone session admin user.
:param ip: the IP address to get the session against.
:type ip: str
:returns: a keystone session to the IP address
:rtype: keystoneauth1.session.Session
"""
return openstack_utils.get_keystone_session(
openstack_utils.get_overcloud_auth(address=ip))
def test_003_test_overide_is_observed(self):
"""Test that the override is observed by the underlying service."""
if self._test_name is None:
logging.info("Doing policyd override for {}"
.format(self._service_name))
else:
logging.info(self._test_name)
# note policyd override only works with Xenial-queens and so keystone
# is already v3
# verify that the operation works before performing the policyd
# override.
zaza_model.block_until_wl_status_info_starts_with(
self.application_name, "PO:", negate_match=True)
zaza_model.block_until_all_units_idle()
logging.info("First verify that operation works prior to override")
try:
self.get_client_and_attempt_operation(self.keystone_ips[0])
except Exception as e:
raise zaza_exceptions.PolicydError(
'Service action failed and should have passed. "{}"'
.format(str(e)))
# now do the policyd override.
logging.info("Doing policyd override with: {}".format(self._rule))
self._set_policy_with({'rule.yaml': self._rule})
zaza_model.block_until_all_units_idle()
# now make sure the operation fails
logging.info("Now verify that operation doesn't work with override")
try:
self.get_client_and_attempt_operation(self.keystone_ips[0])
raise zaza_exceptions.PolicydError(
"Service action passed and should have failed.")
except PolicydOperationFailedException:
pass
except zaza_exceptions.PolicydError as e:
logging.info("{}".format(str(e)))
raise
except Exception as e:
logging.info("exception was: {}".format(e.__class__.__name__))
import traceback
logging.info(traceback.format_exc())
raise zaza_exceptions.PolicydError(
'Service action failed in an unexpected way: {}'
.format(str(e)))
# clean out the policy and wait
self._set_config(False)
# check that the status no longer has "PO:" on it.
# we have to do it twice due to async races and that some info lines
# erase the PO: bit prior to actuall getting back to idle. The double
# check verifies that the charms have started, the idle waits until it
# is finished, and then the final check really makes sure they got
# switched off.
zaza_model.block_until_wl_status_info_starts_with(
self.application_name, "PO:", negate_match=True)
zaza_model.block_until_all_units_idle()
zaza_model.block_until_wl_status_info_starts_with(
self.application_name, "PO:", negate_match=True)
# Finally make sure it works again!
logging.info("Finally verify that operation works after removing the "
"override.")
try:
self.get_client_and_attempt_operation(self.keystone_ips[0])
except Exception as e:
raise zaza_exceptions.PolicydError(
'Service action failed and should have passed after removing '
'policy override: "{}"'
.format(str(e)))
logging.info('OK')
class KeystoneTests(BasePolicydSpecialization):
"""Test the policyd override using the keystone client."""
_rule = "{'identity:list_services': '!'}"
@classmethod
def setUpClass(cls, application_name=None):
"""Run class setup for running NeutronApiTest charm operation tests."""
super(KeystoneTests, cls).setUpClass(
application_name="keystone")
def get_client_and_attempt_operation(self, ip):
"""Attempt to list services. If it fails, raise an exception.
This operation should pass normally for the demo_user, and fail when
the rule has been overriden (see the `rule` class variable.
:param ip: the IP address to get the session against.
:type ip: str
:raises: PolicydOperationFailedException if operation fails.
"""
keystone_client = openstack_utils.get_keystone_session_client(
self.get_keystone_session_demo_admin_user(ip))
try:
keystone_client.services.list()
except keystoneauth1.exceptions.http.Forbidden:
raise PolicydOperationFailedException()
class NeutronApiTests(BasePolicydSpecialization):
"""Test the policyd override using the neutron client."""
_rule = "{'get_network': '!'}"
@classmethod
def setUpClass(cls, application_name=None):
"""Run class setup for running NeutronApiTest charm operation tests."""
super(NeutronApiTests, cls).setUpClass(application_name="neutron-api")
cls.application_name = "neutron-api"
def get_client_and_attempt_operation(self, ip):
"""Attempt to list the networks as a policyd override.
This operation should pass normally for the demo_user, and fail when
the rule has been overriden (see the `rule` class variable.
:param ip: the IP address to get the session against.
:type ip: str
:raises: PolicydOperationFailedException if operation fails.
"""
neutron_client = openstack_utils.get_neutron_session_client(
self.get_keystone_session_demo_user(ip))
try:
# If we are allowed to list networks, this will return something.
# if the policyd override is present, then no error is generated,
# but no networks are returned.
networks = neutron_client.list_networks()
logging.debug("networks: {}".format(networks))
if len(networks['networks']) == 0:
raise PolicydOperationFailedException()
except Exception:
raise PolicydOperationFailedException()
class GlanceTests(BasePolicydSpecialization):
"""Test the policyd override using the glance client."""
_rule = "{'get_images': '!'}"
@classmethod
def setUpClass(cls, application_name=None):
"""Run class setup for running GlanceTests charm operation tests."""
super(GlanceTests, cls).setUpClass(application_name="glance")
cls.application_name = "glance"
def get_client_and_attempt_operation(self, ip):
"""Attempt to list the images as a policyd override.
This operation should pass normally for the demo_user, and fail when
the rule has been overriden (see the `rule` class variable.
:param ip: the IP address to get the session against.
:type ip: str
:raises: PolicydOperationFailedException if operation fails.
"""
glance_client = openstack_utils.get_glance_session_client(
self.get_keystone_session_demo_user(ip))
try:
images = list(glance_client.images.list())
logging.debug("images is: {}".format(images))
except glanceclient.common.exceptions.HTTPForbidden:
raise PolicydOperationFailedException()
class CinderTests(BasePolicydSpecialization):
"""Test the policyd override using the cinder client."""
_rule = "{'volume:get_all': '!'}"
@classmethod
def setUpClass(cls, application_name=None):
"""Run class setup for running CinderTests charm operation tests."""
super(CinderTests, cls).setUpClass(application_name="cinder")
cls.application_name = "cinder"
def get_client_and_attempt_operation(self, ip):
"""Attempt to list the images as a policyd override.
This operation should pass normally for the demo_user, and fail when
the rule has been overriden (see the `rule` class variable.
:param ip: the IP address to get the session against.
:type ip: str
:raises: PolicydOperationFailedException if operation fails.
"""
cinder_client = openstack_utils.get_cinder_session_client(
self.get_keystone_session_admin_user(ip))
try:
cinder_client.volumes.list()
except cinderclient.exceptions.Forbidden:
raise PolicydOperationFailedException()