forked from openstack-charmers/zaza-openstack-tests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tests.py
1750 lines (1534 loc) · 67.7 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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018 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.
"""Ceph Testing."""
import unittest
import json
import logging
from os import (
listdir,
path
)
import requests
import tempfile
import boto3
import botocore.exceptions
import urllib3
import tenacity
import zaza.charm_lifecycle.utils as lifecycle_utils
import zaza.openstack.charm_tests.test_utils as test_utils
import zaza.model as zaza_model
import zaza.openstack.utilities.ceph as zaza_ceph
import zaza.openstack.utilities.exceptions as zaza_exceptions
import zaza.openstack.utilities.generic as zaza_utils
import zaza.utilities.juju as juju_utils
import zaza.openstack.utilities.openstack as zaza_openstack
import zaza.openstack.utilities.generic as generic_utils
# Disable warnings for ssl_verify=false
urllib3.disable_warnings(
urllib3.exceptions.InsecureRequestWarning
)
class CephLowLevelTest(test_utils.BaseCharmTest):
"""Ceph Low Level Test Class."""
@classmethod
def setUpClass(cls):
"""Run class setup for running ceph low level tests."""
super(CephLowLevelTest, cls).setUpClass()
def test_processes(self):
"""Verify Ceph processes.
Verify that the expected service processes are running
on each ceph unit.
"""
logging.info('Checking ceph-mon and ceph-osd processes...')
# Process name and quantity of processes to expect on each unit
ceph_mon_processes = {
'ceph-mon': 1,
'ceph-mgr': 1,
}
ceph_osd_processes = {
'ceph-osd': [1, 2, 3]
}
# Units with process names and PID quantities expected
expected_processes = {
'ceph-mon/0': ceph_mon_processes,
'ceph-mon/1': ceph_mon_processes,
'ceph-mon/2': ceph_mon_processes,
'ceph-osd/0': ceph_osd_processes,
'ceph-osd/1': ceph_osd_processes,
'ceph-osd/2': ceph_osd_processes
}
actual_pids = zaza_utils.get_unit_process_ids(expected_processes)
ret = zaza_utils.validate_unit_process_ids(expected_processes,
actual_pids)
self.assertTrue(ret)
def test_services(self):
"""Verify the ceph services.
Verify the expected services are running on the service units.
"""
logging.info('Checking ceph-osd and ceph-mon services...')
services = {}
ceph_services = ['ceph-mon', 'ceph-mgr']
services['ceph-osd/0'] = ['ceph-osd']
services['ceph-mon/0'] = ceph_services
services['ceph-mon/1'] = ceph_services
services['ceph-mon/2'] = ceph_services
for unit_name, unit_services in services.items():
zaza_model.block_until_service_status(
unit_name=unit_name,
services=unit_services,
target_status='running'
)
@test_utils.skipUntilVersion('ceph-mon', 'ceph', '14.2.0')
def test_pg_tuning(self):
"""Verify that auto PG tuning is enabled for Nautilus+."""
unit_name = 'ceph-mon/0'
cmd = "ceph osd pool autoscale-status --format=json"
result = zaza_model.run_on_unit(unit_name, cmd)
self.assertEqual(result['Code'], '0')
for pool in json.loads(result['Stdout']):
self.assertEqual(pool['pg_autoscale_mode'], 'on')
class CephTest(test_utils.BaseCharmTest):
"""Ceph common functional tests."""
@classmethod
def setUpClass(cls):
"""Run the ceph's common class setup."""
super(CephTest, cls).setUpClass()
def osd_out_in(self, services):
"""Run OSD out and OSD in tests.
Remove OSDs and then add them back in on a unit checking that services
are in the required state after each action
:param services: Services expected to be restarted when config_file is
changed.
:type services: list
"""
zaza_model.block_until_service_status(
self.lead_unit,
services,
'running',
model_name=self.model_name)
zaza_model.block_until_unit_wl_status(
self.lead_unit,
'active',
model_name=self.model_name)
zaza_model.run_action(
self.lead_unit,
'osd-out',
model_name=self.model_name)
zaza_model.block_until_unit_wl_status(
self.lead_unit,
'maintenance',
model_name=self.model_name)
zaza_model.block_until_all_units_idle(model_name=self.model_name)
zaza_model.run_action(
self.lead_unit,
'osd-in',
model_name=self.model_name)
zaza_model.block_until_unit_wl_status(
self.lead_unit,
'active',
model_name=self.model_name)
zaza_model.block_until_all_units_idle(model_name=self.model_name)
zaza_model.block_until_service_status(
self.lead_unit,
services,
'running',
model_name=self.model_name)
def test_ceph_check_osd_pools(self):
"""Check OSD pools.
Check osd pools on all ceph units, expect them to be
identical, and expect specific pools to be present.
"""
try:
zaza_model.get_application('cinder-ceph')
except KeyError:
raise unittest.SkipTest("Skipping OpenStack dependent test")
logging.info('Checking pools on ceph units...')
expected_pools = zaza_ceph.get_expected_pools()
results = []
unit_name = 'ceph-mon/0'
# Check for presence of expected pools on each unit
logging.debug('Expected pools: {}'.format(expected_pools))
pools = zaza_ceph.get_ceph_pools(unit_name)
results.append(pools)
for expected_pool in expected_pools:
if expected_pool not in pools:
msg = ('{} does not have pool: '
'{}'.format(unit_name, expected_pool))
raise zaza_exceptions.CephPoolNotFound(msg)
logging.debug('{} has (at least) the expected '
'pools.'.format(unit_name))
# Check that all units returned the same pool name:id data
for i, result in enumerate(results):
for other in results[i+1:]:
logging.debug('result: {}, other: {}'.format(result, other))
self.assertEqual(result, other)
def test_ceph_pool_creation_with_text_file(self):
"""Check the creation of a pool and a text file.
Create a pool, add a text file to it and retrieve its content.
Verify that the content matches the original file.
"""
unit_name = 'ceph-mon/0'
cmd = 'sudo ceph osd pool create test {PG_NUM}; \
echo 123456789 > /tmp/input.txt; \
rados put -p test test_input /tmp/input.txt; \
rados get -p test test_input /dev/stdout'
cmd = cmd.format(PG_NUM=32)
logging.debug('Creating test pool and putting test file in pool...')
result = zaza_model.run_on_unit(unit_name, cmd)
code = result.get('Code')
if code != '0':
raise zaza_model.CommandRunFailed(cmd, result)
output = result.get('Stdout').strip()
logging.debug('Output received: {}'.format(output))
self.assertEqual(output, '123456789')
def test_ceph_encryption(self):
"""Test Ceph encryption.
Verify that the new disk is added with encryption by checking for
Ceph's encryption keys directory.
"""
current_release = zaza_openstack.get_os_release(application='ceph-mon')
trusty_mitaka = zaza_openstack.get_os_release('trusty_mitaka')
if current_release >= trusty_mitaka:
logging.warn("Skipping encryption test for Mitaka and higher")
return
unit_name = 'ceph-osd/0'
set_default = {
'osd-encrypt': 'False',
'osd-devices': '/dev/vdb /srv/ceph',
}
set_alternate = {
'osd-encrypt': 'True',
'osd-devices': '/dev/vdb /srv/ceph /srv/ceph_encrypted',
}
juju_service = 'ceph-osd'
logging.info('Making config change on {}...'.format(juju_service))
mtime = zaza_model.get_unit_time(unit_name)
file_mtime = None
folder_name = '/etc/ceph/dmcrypt-keys/'
with self.config_change(set_default, set_alternate,
application_name=juju_service):
with tempfile.TemporaryDirectory() as tempdir:
# Creating a temp dir to copy keys
temp_folder = '/tmp/dmcrypt-keys'
cmd = 'mkdir {}'.format(temp_folder)
ret = zaza_model.run_on_unit(unit_name, cmd)
logging.debug('Ret for cmd {} is {}'.format(cmd, ret))
# Copy keys from /etc to /tmp
cmd = 'sudo cp {}* {}'.format(folder_name, temp_folder)
ret = zaza_model.run_on_unit(unit_name, cmd)
logging.debug('Ret for cmd {} is {}'.format(cmd, ret))
# Changing permissions to be able to SCP the files
cmd = 'sudo chown -R ubuntu:ubuntu {}'.format(temp_folder)
ret = zaza_model.run_on_unit(unit_name, cmd)
logging.debug('Ret for cmd {} is {}'.format(cmd, ret))
# SCP to retrieve all files in folder
# -p: preserve timestamps
source = '/tmp/dmcrypt-keys/*'
zaza_model.scp_from_unit(unit_name=unit_name,
source=source,
destination=tempdir,
scp_opts='-p')
for elt in listdir(tempdir):
file_path = '/'.join([tempdir, elt])
if path.isfile(file_path):
file_mtime = path.getmtime(file_path)
if file_mtime:
break
if not file_mtime:
logging.warn('Could not determine mtime, assuming '
'folder does not exist')
raise FileNotFoundError('folder does not exist')
if file_mtime >= mtime:
logging.info('Folder mtime is newer than provided mtime '
'(%s >= %s) on %s (OK)' % (file_mtime,
mtime, unit_name))
else:
logging.warn('Folder mtime is older than provided mtime'
'(%s < on %s) on %s' % (file_mtime,
mtime, unit_name))
raise Exception('Folder mtime is older than provided mtime')
def test_blocked_when_non_pristine_disk_appears(self):
"""Test blocked state with non-pristine disk.
Validate that charm goes into blocked state when it is presented with
new block devices that have foreign data on them.
Instances used in UOSCI has a flavour with ephemeral storage in
addition to the bootable instance storage. The ephemeral storage
device is partitioned, formatted and mounted early in the boot process
by cloud-init.
As long as the device is mounted the charm will not attempt to use it.
If we unmount it and trigger the config-changed hook the block device
will appear as a new and previously untouched device for the charm.
One of the first steps of device eligibility checks should be to make
sure we are seeing a pristine and empty device before doing any
further processing.
As the ephemeral device will have data on it we can use it to validate
that these checks work as intended.
"""
current_release = zaza_openstack.get_os_release(application='ceph-mon')
focal_ussuri = zaza_openstack.get_os_release('focal_ussuri')
if current_release >= focal_ussuri:
# NOTE(ajkavanagh) - focal (on ServerStack) is broken for /dev/vdb
# and so this test can't pass: LP#1842751 discusses the issue, but
# basically the snapd daemon along with lxcfs results in /dev/vdb
# being mounted in the lxcfs process namespace. If the charm
# 'tries' to umount it, it can (as root), but the mount is still
# 'held' by lxcfs and thus nothing else can be done with it. This
# is only a problem in serverstack with images with a default
# /dev/vdb ephemeral
logging.warn("Skipping pristine disk test for focal and higher")
return
logging.info('Checking behaviour when non-pristine disks appear...')
logging.info('Configuring ephemeral-unmount...')
alternate_conf = {
'ephemeral-unmount': '/mnt',
'osd-devices': '/dev/vdb'
}
juju_service = 'ceph-osd'
zaza_model.set_application_config(juju_service, alternate_conf)
ceph_osd_states = {
'ceph-osd': {
'workload-status': 'blocked',
'workload-status-message': 'Non-pristine'
}
}
zaza_model.wait_for_application_states(states=ceph_osd_states)
logging.info('Units now in blocked state, running zap-disk action...')
unit_names = ['ceph-osd/0', 'ceph-osd/1', 'ceph-osd/2']
for unit_name in unit_names:
zap_disk_params = {
'devices': '/dev/vdb',
'i-really-mean-it': True,
}
action_obj = zaza_model.run_action(
unit_name=unit_name,
action_name='zap-disk',
action_params=zap_disk_params
)
logging.debug('Result of action: {}'.format(action_obj))
logging.info('Running add-disk action...')
for unit_name in unit_names:
add_disk_params = {
'osd-devices': '/dev/vdb',
}
action_obj = zaza_model.run_action(
unit_name=unit_name,
action_name='add-disk',
action_params=add_disk_params
)
logging.debug('Result of action: {}'.format(action_obj))
logging.info('Wait for idle/ready status...')
zaza_model.wait_for_application_states()
logging.info('OK')
set_default = {
'ephemeral-unmount': '',
'osd-devices': '/dev/vdb',
}
bionic_train = zaza_openstack.get_os_release('bionic_train')
if current_release < bionic_train:
set_default['osd-devices'] = '/dev/vdb /srv/ceph'
logging.info('Restoring to default configuration...')
zaza_model.set_application_config(juju_service, set_default)
zaza_model.wait_for_application_states()
def test_pause_and_resume(self):
"""The services can be paused and resumed."""
logging.info('Checking pause and resume actions...')
self.pause_resume(['ceph-osd'])
def get_device_for_blacklist(self, unit):
"""Return a device to be used by the blacklist tests."""
cmd = "mount | grep 'on / ' | awk '{print $1}'"
obj = zaza_model.run_on_unit(unit, cmd)
return obj.get('Stdout').strip()
def test_blacklist(self):
"""Check the blacklist action.
The blacklist actions execute and behave as expected.
"""
logging.info('Checking blacklist-add-disk and '
'blacklist-remove-disk actions...')
unit_name = 'ceph-osd/0'
zaza_model.block_until_unit_wl_status(
unit_name,
'active'
)
# Attempt to add device with non-absolute path should fail
action_obj = zaza_model.run_action(
unit_name=unit_name,
action_name='blacklist-add-disk',
action_params={'osd-devices': 'vda'}
)
self.assertTrue(action_obj.status != 'completed')
zaza_model.block_until_unit_wl_status(
unit_name,
'active'
)
# Attempt to add device with non-existent path should fail
action_obj = zaza_model.run_action(
unit_name=unit_name,
action_name='blacklist-add-disk',
action_params={'osd-devices': '/non-existent'}
)
self.assertTrue(action_obj.status != 'completed')
zaza_model.block_until_unit_wl_status(
unit_name,
'active'
)
# Attempt to add device with existent path should succeed
device = self.get_device_for_blacklist(unit_name)
if not device:
raise unittest.SkipTest(
"Skipping test because no device was found")
action_obj = zaza_model.run_action(
unit_name=unit_name,
action_name='blacklist-add-disk',
action_params={'osd-devices': device}
)
self.assertEqual('completed', action_obj.status)
zaza_model.block_until_unit_wl_status(
unit_name,
'active'
)
# Attempt to remove listed device should always succeed
action_obj = zaza_model.run_action(
unit_name=unit_name,
action_name='blacklist-remove-disk',
action_params={'osd-devices': device}
)
self.assertEqual('completed', action_obj.status)
zaza_model.block_until_unit_wl_status(
unit_name,
'active'
)
logging.debug('OK')
def test_list_disks(self):
"""Test the list-disks action.
The list-disks action execute.
"""
logging.info('Checking list-disks action...')
unit_name = 'ceph-osd/0'
zaza_model.block_until_unit_wl_status(
unit_name,
'active'
)
action_obj = zaza_model.run_action(
unit_name=unit_name,
action_name='list-disks',
)
self.assertEqual('completed', action_obj.status)
zaza_model.block_until_unit_wl_status(
unit_name,
'active'
)
logging.debug('OK')
def get_local_osd_id(self, unit):
"""Get the OSD id for a unit."""
ret = zaza_model.run_on_unit(unit,
'ceph-volume lvm list --format=json')
local = list(json.loads(ret['Stdout']))[-1]
return local if local.startswith('osd.') else 'osd.' + local
def get_num_osds(self, osd, is_up_only=False):
"""Compute the number of active OSD's."""
result = zaza_model.run_on_unit(osd, 'ceph osd stat --format=json')
result = json.loads(result['Stdout'])
if is_up_only:
return int(result['num_up_osds'])
else:
return int(result['num_osds'])
def get_osd_devices_on_unit(self, unit_name):
"""Get information for osd devices present on a particular unit.
:param unit: Unit name to be queried for osd device info.
:type unit: str
"""
osd_devices = json.loads(
zaza_model.run_on_unit(
unit_name, 'ceph-volume lvm list --format=json'
).get('Stdout', '')
)
return osd_devices
def remove_disk_from_osd_unit(self, unit, osd_id, is_purge=False):
"""Remove osd device with provided osd_id from unit.
:param unit: Unit name where the osd device is to be removed from.
:type unit: str
:param osd_id: osd-id for the osd device to be removed.
:type osd_id: str
:param is_purge: whether to purge the osd device
:type is_purge: bool
"""
action_obj = zaza_model.run_action(
unit_name=unit,
action_name='remove-disk',
action_params={
'osd-ids': osd_id,
'timeout': 10,
'format': 'json',
'purge': is_purge
}
)
zaza_utils.assertActionRanOK(action_obj)
results = json.loads(action_obj.data['results']['message'])
results = results[next(iter(results))]
self.assertEqual(results['osd-ids'], osd_id)
zaza_model.run_on_unit(unit, 'partprobe')
def remove_one_osd(self, unit, block_devs):
"""Remove one device from osd unit.
:param unit: Unit name where the osd device is to be removed from.
:type unit: str
:params block_devs: list of block devices on the scpecified unit
:type block_devs: list[str]
"""
# Should have more than 1 OSDs to take one out and test.
self.assertGreater(len(block_devs), 1)
# Get complete device details for an OSD.
key = list(block_devs)[-1]
device = {
'osd-id': key if key.startswith('osd.') else 'osd.' + key,
'block-device': block_devs[key][0]['devices'][0]
}
self.remove_disk_from_osd_unit(unit, device['osd-id'], is_purge=True)
return device
def test_cache_device(self):
"""Test replacing a disk in use."""
logging.info('Running add-disk action with a caching device')
mon = next(iter(zaza_model.get_units('ceph-mon'))).entity_id
osds = [x.entity_id for x in zaza_model.get_units('ceph-osd')]
osd_info = dict()
# Remove one of the two disks.
logging.info('Removing single disk from each OSD')
for unit in osds:
block_devs = self.get_osd_devices_on_unit(unit)
if len(block_devs) < 2:
continue
device_info = self.remove_one_osd(unit, block_devs)
block_dev = device_info['block-device']
logging.info("Removing device %s from unit %s" % (block_dev, unit))
osd_info[unit] = device_info
if not osd_info:
raise unittest.SkipTest(
'Skipping OSD replacement Test, no spare devices added')
logging.debug('Removed OSD Info: {}'.format(osd_info))
zaza_model.wait_for_application_states()
logging.info('Recycling previously removed disks')
for unit, device_info in osd_info.items():
osd_id = device_info['osd-id']
block_dev = device_info['block-device']
logging.info("Found device %s on unit %s" % (block_dev, unit))
self.assertNotEqual(block_dev, None)
action_obj = zaza_model.run_action(
unit_name=unit,
action_name='add-disk',
action_params={'osd-devices': block_dev,
'osd-ids': osd_id,
'partition-size': 5}
)
zaza_utils.assertActionRanOK(action_obj)
zaza_model.wait_for_application_states()
logging.info('Removing previously added OSDs')
for unit, device_info in osd_info.items():
osd_id = device_info['osd-id']
block_dev = device_info['block-device']
logging.info(
"Removing block device %s from unit %s" %
(block_dev, unit)
)
self.remove_disk_from_osd_unit(unit, osd_id, is_purge=False)
zaza_model.wait_for_application_states()
logging.info('Finally adding back OSDs')
for unit, device_info in osd_info.items():
block_dev = device_info['block-device']
action_obj = zaza_model.run_action(
unit_name=unit,
action_name='add-disk',
action_params={'osd-devices': block_dev,
'partition-size': 5}
)
zaza_utils.assertActionRanOK(action_obj)
zaza_model.wait_for_application_states()
for attempt in tenacity.Retrying(
wait=tenacity.wait_exponential(multiplier=2, max=32),
reraise=True, stop=tenacity.stop_after_attempt(10),
retry=tenacity.retry_if_exception_type(AssertionError)
):
with attempt:
self.assertEqual(
len(osds) * 2, self.get_num_osds(mon, is_up_only=True)
)
class CephRGWTest(test_utils.BaseCharmTest):
"""Ceph RADOS Gateway Daemons Test Class.
This Testset is not idempotent, because we don't support scale down from
multisite to singlesite (yet). Tests can be performed independently.
However, If test_004 has completed migration, retriggering the test-set
would cause a time-out in test_003.
"""
# String Resources
primary_rgw_app = 'ceph-radosgw'
primary_rgw_unit = 'ceph-radosgw/0'
secondary_rgw_app = 'secondary-ceph-radosgw'
secondary_rgw_unit = 'secondary-ceph-radosgw/0'
@classmethod
def setUpClass(cls):
"""Run class setup for running ceph low level tests."""
super(CephRGWTest, cls).setUpClass(application_name='ceph-radosgw')
@property
def expected_apps(self):
"""Determine application names for ceph-radosgw apps."""
_apps = [
self.primary_rgw_app
]
try:
zaza_model.get_application(self.secondary_rgw_app)
_apps.append(self.secondary_rgw_app)
except KeyError:
pass
return _apps
@property
def multisite(self):
"""Determine whether deployment is multi-site."""
try:
zaza_model.get_application(self.secondary_rgw_app)
return True
except KeyError:
return False
def get_rgwadmin_cmd_skeleton(self, unit_name):
"""
Get radosgw-admin cmd skeleton with rgw.hostname populated key.
:param unit_name: Unit on which the complete command would be run.
:type unit_name: str
:returns: hostname filled basic command skeleton
:rtype: str
"""
app_name = unit_name.split('/')[0]
juju_units = zaza_model.get_units(app_name)
unit_hostnames = generic_utils.get_unit_hostnames(juju_units)
hostname = unit_hostnames[unit_name]
return 'radosgw-admin --id=rgw.{} '.format(hostname)
def purge_bucket(self, application, bucket_name):
"""Remove a bucket and all it's objects.
:param application: RGW application name
:type application: str
:param bucket_name: Name for RGW bucket to be deleted
:type bucket_name: str
"""
juju_units = zaza_model.get_units(application)
unit_hostnames = generic_utils.get_unit_hostnames(juju_units)
for unit_name, hostname in unit_hostnames.items():
key_name = "rgw.{}".format(hostname)
cmd = 'radosgw-admin --id={} bucket rm --bucket={}' \
' --purge-objects'.format(key_name, bucket_name)
zaza_model.run_on_unit(unit_name, cmd)
def wait_for_status(self, application,
is_primary=False, sync_expected=True):
"""Wait for required RGW endpoint to finish sync for data and metadata.
:param application: RGW application which has to be waited for
:type application: str
:param is_primary: whether RGW application is primary or secondary
:type is_primary: boolean
:param sync_expected: whether sync details should be expected in status
:type sync_expected: boolean
"""
juju_units = zaza_model.get_units(application)
unit_hostnames = generic_utils.get_unit_hostnames(juju_units)
data_check = 'data is caught up with source'
meta_primary = 'metadata sync no sync (zone is master)'
meta_secondary = 'metadata is caught up with master'
meta_check = meta_primary if is_primary else meta_secondary
for attempt in tenacity.Retrying(
wait=tenacity.wait_exponential(multiplier=10, max=300),
reraise=True, stop=tenacity.stop_after_attempt(12),
retry=tenacity.retry_if_exception_type(AssertionError)
):
with attempt:
for unit_name, hostname in unit_hostnames.items():
key_name = "rgw.{}".format(hostname)
cmd = 'radosgw-admin --id={} sync status'.format(key_name)
stdout = zaza_model.run_on_unit(
unit_name, cmd
).get('Stdout', '')
if sync_expected:
# Both data and meta sync.
self.assertIn(data_check, stdout)
self.assertIn(meta_check, stdout)
else:
# ExpectPrimary's Meta Status and no Data sync status
self.assertIn(meta_primary, stdout)
self.assertNotIn(data_check, stdout)
def fetch_rgw_object(self, target_client, container_name, object_name):
"""Fetch RGW object content.
:param target_client: boto3 client object configured for an endpoint.
:type target_client: str
:param container_name: RGW bucket name for desired object.
:type container_name: str
:param object_name: Object name for desired object.
:type object_name: str
"""
for attempt in tenacity.Retrying(
wait=tenacity.wait_exponential(multiplier=1, max=60),
reraise=True, stop=tenacity.stop_after_attempt(12)
):
with attempt:
return target_client.Object(
container_name, object_name
).get()['Body'].read().decode('UTF-8')
def promote_rgw_to_primary(self, app_name: str):
"""Promote provided app to Primary and update period at new secondary.
:param app_name: Secondary site rgw Application to be promoted.
:type app_name: str
"""
if app_name is self.primary_rgw_app:
new_secondary = self.secondary_rgw_unit
else:
new_secondary = self.primary_rgw_unit
# Promote to Primary
zaza_model.run_action_on_leader(
app_name,
'promote',
action_params={},
)
# Period Update Commit new secondary.
cmd = self.get_rgwadmin_cmd_skeleton(new_secondary)
zaza_model.run_on_unit(
new_secondary, cmd + 'period update --commit'
)
def get_client_keys(self, rgw_app_name=None):
"""Create access_key and secret_key for boto3 client.
:param rgw_app_name: RGW application for which keys are required.
:type rgw_app_name: str
"""
unit_name = self.primary_rgw_unit
if rgw_app_name is not None:
unit_name = rgw_app_name + '/0'
user_name = 'botoclient'
cmd = self.get_rgwadmin_cmd_skeleton(unit_name)
users = json.loads(zaza_model.run_on_unit(
unit_name, cmd + 'user list'
).get('Stdout', ''))
# Fetch boto3 user keys if user exists.
if user_name in users:
output = json.loads(zaza_model.run_on_unit(
unit_name, cmd + 'user info --uid={}'.format(user_name)
).get('Stdout', ''))
keys = output['keys'][0]
return keys['access_key'], keys['secret_key']
# Create boto3 user if it does not exist.
create_cmd = cmd + 'user create --uid={} --display-name={}'.format(
user_name, user_name
)
output = json.loads(
zaza_model.run_on_unit(unit_name, create_cmd).get('Stdout', '')
)
keys = output['keys'][0]
return keys['access_key'], keys['secret_key']
@tenacity.retry(
retry=tenacity.retry_if_result(lambda ret: ret is None),
wait=tenacity.wait_fixed(10),
stop=tenacity.stop_after_attempt(5)
)
def get_rgw_endpoint(self, unit_name: str):
"""Fetch Application endpoint for RGW unit.
:param unit_name: Unit name for which RGW endpoint is required.
:type unit_name: str
"""
unit = zaza_model.get_unit_from_name(unit_name)
unit_address = zaza_model.get_unit_public_address(
unit,
self.model_name
)
logging.debug("Unit: {}, Endpoint: {}".format(unit_name, unit_address))
if unit_address is None:
return None
# Evaluate port
try:
zaza_model.get_application("vault")
return "https://{}:443".format(unit_address)
except KeyError:
return "http://{}:80".format(unit_address)
def configure_rgw_apps_for_multisite(self):
"""Configure Multisite values on primary and secondary apps."""
realm = 'zaza_realm'
zonegroup = 'zaza_zg'
zaza_model.set_application_config(
self.primary_rgw_app,
{
'realm': realm,
'zonegroup': zonegroup,
'zone': 'zaza_primary'
}
)
zaza_model.set_application_config(
self.secondary_rgw_app,
{
'realm': realm,
'zonegroup': zonegroup,
'zone': 'zaza_secondary'
}
)
def clean_rgw_multisite_config(self, app_name):
"""Clear Multisite Juju config values to default.
:param app_name: App for which config values are to be cleared
:type app_name: str
"""
unit_name = app_name + "/0"
zaza_model.set_application_config(
app_name,
{
'realm': "",
'zonegroup': "",
'zone': "default"
}
)
# Commit changes to period.
cmd = self.get_rgwadmin_cmd_skeleton(unit_name)
zaza_model.run_on_unit(
unit_name, cmd + 'period update --commit --rgw-zone=default '
'--rgw-zonegroup=default'
)
def enable_virtual_hosted_bucket(self):
"""Enable virtual hosted bucket on primary rgw app."""
zaza_model.set_application_config(
self.primary_rgw_app,
{
'virtual-hosted-bucket-enabled': "true"
}
)
def set_os_public_hostname(self):
"""Set os-public-hostname on primary rgw app."""
zaza_model.set_application_config(
self.primary_rgw_app,
{
'os-public-hostname': "rgw.example.com",
}
)
def clean_virtual_hosted_bucket(self):
"""Clear virtual hosted bucket on primary app."""
zaza_model.set_application_config(
self.primary_rgw_app,
{
'os-public-hostname': "",
'virtual-hosted-bucket-enabled': "false"
}
)
def test_001_processes(self):
"""Verify Ceph processes.
Verify that the expected service processes are running
on each ceph unit.
"""
logging.info('Checking radosgw processes...')
# Process name and quantity of processes to expect on each unit
ceph_radosgw_processes = {
'radosgw': 1,
}
# Units with process names and PID quantities expected
expected_processes = {}
for app in self.expected_apps:
for unit in zaza_model.get_units(app):
expected_processes[unit.entity_id] = ceph_radosgw_processes
actual_pids = zaza_utils.get_unit_process_ids(expected_processes)
ret = zaza_utils.validate_unit_process_ids(expected_processes,
actual_pids)
self.assertTrue(ret)
def test_002_services(self):
"""Verify the ceph services.
Verify the expected services are running on the service units.
"""
logging.info('Checking radosgw services...')
services = ['radosgw', 'haproxy']
for app in self.expected_apps:
for unit in zaza_model.get_units(app):
zaza_model.block_until_service_status(
unit_name=unit.entity_id,
services=services,
target_status='running'
)
def test_003_object_storage_and_secondary_block(self):
"""Verify Object Storage API and Secondary Migration block."""
container_name = 'zaza-container'
obj_data = 'Test data from Zaza'
obj_name = 'prefile'
logging.info('Checking Object Storage API for Primary Cluster')
# 1. Fetch Primary Endpoint Details
primary_endpoint = self.get_rgw_endpoint(self.primary_rgw_unit)
self.assertNotEqual(primary_endpoint, None)
# 2. Create RGW Client and perform IO
access_key, secret_key = self.get_client_keys()
primary_client = boto3.resource("s3",
verify=False,
endpoint_url=primary_endpoint,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key)
primary_client.Bucket(container_name).create()
primary_object_one = primary_client.Object(
container_name,
obj_name
)
primary_object_one.put(Body=obj_data)
# 3. Fetch Object and Perform Data Integrity check.
content = primary_object_one.get()['Body'].read().decode('UTF-8')
self.assertEqual(content, obj_data)
# Skip multisite tests if not compatible with bundle.
if not self.multisite:
logging.info('Skipping Secondary Object gatewaty verification')