/
ceph_hooks.py
executable file
·1343 lines (1167 loc) · 47.9 KB
/
ceph_hooks.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
#!/usr/bin/env python3
#
# Copyright 2016 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.
import ast
import json
import os
import subprocess
import sys
import uuid
sys.path.append('lib')
import charms_ceph.utils as ceph
from charms_ceph.broker import (
process_requests
)
from charmhelpers.core import hookenv
from charmhelpers.core.hookenv import (
log,
DEBUG,
ERROR,
INFO,
WARNING,
config,
relation_ids,
related_units,
is_relation_made,
relation_get,
relation_set,
leader_set, leader_get,
is_leader,
remote_unit,
Hooks, UnregisteredHookError,
service_name,
relations_of_type,
relations,
status_set,
local_unit,
application_version_set)
from charmhelpers.core.host import (
service_pause,
mkdir,
write_file,
rsync,
cmp_pkgrevno)
from charmhelpers.fetch import (
apt_install,
apt_update,
apt_purge,
filter_installed_packages,
add_source,
get_upstream_version,
)
from charmhelpers.payload.execd import execd_preinstall
from charmhelpers.contrib.openstack.alternatives import install_alternative
from charmhelpers.contrib.openstack.utils import (
clear_unit_paused,
clear_unit_upgrading,
get_os_codename_install_source,
is_unit_upgrading_set,
set_unit_paused,
set_unit_upgrading,
)
from charmhelpers.contrib.network.ip import (
get_ipv6_addr,
format_ipv6_addr,
get_relation_ip,
)
from charmhelpers.core.sysctl import create as create_sysctl
from charmhelpers.core.templating import render
from charmhelpers.contrib.storage.linux.ceph import (
CephBrokerRq,
CephConfContext,
OSD_SETTING_EXCEPTIONS,
enable_pg_autoscale,
get_osd_settings,
send_osd_settings,
)
from utils import (
add_rbd_mirror_features,
assert_charm_supports_ipv6,
get_cluster_addr,
get_networks,
get_public_addr,
get_rbd_features,
has_rbd_mirrors,
get_ceph_osd_releases,
execute_post_osd_upgrade_steps,
mgr_disable_module,
mgr_enable_module,
is_mgr_module_enabled,
)
from charmhelpers.contrib.charmsupport import nrpe
from charmhelpers.contrib.hardening.harden import harden
hooks = Hooks()
NAGIOS_PLUGINS = '/usr/local/lib/nagios/plugins'
SCRIPTS_DIR = '/usr/local/bin'
STATUS_FILE = '/var/lib/nagios/cat-ceph-status.txt'
STATUS_CRONFILE = '/etc/cron.d/cat-ceph-health'
def check_for_upgrade():
if not ceph.is_bootstrapped():
log("Ceph is not bootstrapped, skipping upgrade checks.")
return
c = hookenv.config()
old_version = ceph.resolve_ceph_version(c.previous('source') or
'distro')
log('old_version: {}'.format(old_version))
# Strip all whitespace
new_version = ceph.resolve_ceph_version(hookenv.config('source'))
old_version_os = get_os_codename_install_source(c.previous('source') or
'distro')
new_version_os = get_os_codename_install_source(hookenv.config('source'))
log('new_version: {}'.format(new_version))
if (old_version in ceph.UPGRADE_PATHS and
new_version == ceph.UPGRADE_PATHS[old_version]):
log("{} to {} is a valid upgrade path. Proceeding.".format(
old_version, new_version))
ceph.roll_monitor_cluster(new_version=new_version,
upgrade_key='admin')
elif (old_version == new_version and
old_version_os < new_version_os):
# See LP: #1778823
add_source(hookenv.config('source'), hookenv.config('key'))
log(("The installation source has changed yet there is no new major "
"version of Ceph in this new source. As a result no package "
"upgrade will take effect. Please upgrade manually if you need "
"to."), level=INFO)
else:
# Log a helpful error message
log("Invalid upgrade path from {} to {}. "
"Valid paths are: {}".format(old_version,
new_version,
ceph.pretty_print_upgrade_paths()),
level=ERROR)
@hooks.hook('install.real')
@harden()
def install():
execd_preinstall()
add_source(config('source'), config('key'))
apt_update(fatal=True)
apt_install(packages=ceph.determine_packages(), fatal=True)
rm_packages = ceph.determine_packages_to_remove()
if rm_packages:
apt_purge(packages=rm_packages, fatal=True)
try:
# we defer and explicitly run `ceph-create-keys` from
# add_keyring_to_ceph() as part of bootstrap process
# LP: #1719436.
service_pause('ceph-create-keys')
except ValueError:
pass
def get_ceph_context():
networks = get_networks('ceph-public-network')
public_network = ', '.join(networks)
networks = get_networks('ceph-cluster-network')
cluster_network = ', '.join(networks)
cephcontext = {
'auth_supported': config('auth-supported'),
'mon_hosts': config('monitor-hosts') or ' '.join(get_mon_hosts()),
'fsid': leader_get('fsid'),
'old_auth': cmp_pkgrevno('ceph', "0.51") < 0,
'use_syslog': str(config('use-syslog')).lower(),
'ceph_public_network': public_network,
'ceph_cluster_network': cluster_network,
'loglevel': config('loglevel'),
'dio': str(config('use-direct-io')).lower(),
'mon_data_avail_warn': int(config('monitor-data-available-warning')),
'mon_data_avail_crit': int(config('monitor-data-available-critical')),
}
if config('prefer-ipv6'):
dynamic_ipv6_address = get_ipv6_addr()[0]
if not public_network:
cephcontext['public_addr'] = dynamic_ipv6_address
if not cluster_network:
cephcontext['cluster_addr'] = dynamic_ipv6_address
else:
cephcontext['public_addr'] = get_public_addr()
cephcontext['cluster_addr'] = get_cluster_addr()
rbd_features = get_rbd_features()
if rbd_features:
cephcontext['rbd_features'] = rbd_features
if config('disable-pg-max-object-skew'):
cephcontext['disable_object_skew'] = config(
'disable-pg-max-object-skew')
# NOTE(dosaboy): these sections must correspond to what is supported in the
# config template.
sections = ['global', 'mds', 'mon']
cephcontext.update(CephConfContext(permitted_sections=sections)())
return cephcontext
def emit_cephconf():
# Install ceph.conf as an alternative to support
# co-existence with other charms that write this file
charm_ceph_conf = "/var/lib/charm/{}/ceph.conf".format(service_name())
mkdir(os.path.dirname(charm_ceph_conf), owner=ceph.ceph_user(),
group=ceph.ceph_user())
render('ceph.conf', charm_ceph_conf, get_ceph_context(), perms=0o644)
install_alternative('ceph.conf', '/etc/ceph/ceph.conf',
charm_ceph_conf, 100)
JOURNAL_ZAPPED = '/var/lib/ceph/journal_zapped'
@hooks.hook('config-changed')
@harden()
def config_changed():
# Get the cfg object so we can see if the no-bootstrap value has changed
# and triggered this hook invocation
cfg = config()
if config('prefer-ipv6'):
assert_charm_supports_ipv6()
check_for_upgrade()
log('Monitor hosts are ' + repr(get_mon_hosts()))
sysctl_dict = config('sysctl')
if sysctl_dict:
create_sysctl(sysctl_dict, '/etc/sysctl.d/50-ceph-charm.conf')
if relations_of_type('nrpe-external-master'):
update_nrpe_config()
if is_leader():
if not config('no-bootstrap'):
if not leader_get('fsid') or not leader_get('monitor-secret'):
if config('fsid'):
fsid = config('fsid')
else:
fsid = "{}".format(uuid.uuid1())
if config('monitor-secret'):
mon_secret = config('monitor-secret')
else:
mon_secret = "{}".format(ceph.generate_monitor_secret())
opts = {
'fsid': fsid,
'monitor-secret': mon_secret,
}
try:
leader_set(opts)
status_set('maintenance',
'Created FSID and Monitor Secret')
log("Settings for the cluster are: {}".format(opts))
except Exception as e:
# we're probably not the leader an exception occured
# let's log it anyway.
log("leader_set failed: {}".format(str(e)))
elif (cfg.changed('no-bootstrap') and
is_relation_made('bootstrap-source')):
# User changed the no-bootstrap config option, we're the leader,
# and the bootstrap-source relation has been made. The charm should
# be in a blocked state indicating that the no-bootstrap option
# must be set. This block is invoked when the user is trying to
# get out of that scenario by enabling no-bootstrap.
bootstrap_source_relation_changed()
# This will only ensure that we are enabled if the 'pg-autotune' option
# is explicitly set to 'true', and not if it is 'auto' or 'false'
if (config('pg-autotune') == 'true' and
cmp_pkgrevno('ceph', '14.2.0') >= 0):
# The return value of the enable_module call will tell us if the
# module was already enabled, in which case, we don't need to
# re-configure the already configured pools
if mgr_enable_module('pg_autoscaler'):
ceph.monitor_key_set('admin', 'autotune', 'true')
for pool in ceph.list_pools():
enable_pg_autoscale('admin', pool)
# unconditionally verify that the fsid and monitor-secret are set now
# otherwise we exit until a leader does this.
if leader_get('fsid') is None or leader_get('monitor-secret') is None:
log('still waiting for leader to setup keys')
status_set('waiting', 'Waiting for leader to setup keys')
return
emit_cephconf()
# Support use of single node ceph
if (not ceph.is_bootstrapped() and int(config('monitor-count')) == 1 and
is_leader()):
status_set('maintenance', 'Bootstrapping single Ceph MON')
# the following call raises an exception if it can't add the keyring
try:
ceph.bootstrap_monitor_cluster(leader_get('monitor-secret'))
except FileNotFoundError as e: # NOQA -- PEP8 is still PY2
log("Couldn't bootstrap the monitor yet: {}".format(str(e)))
return
ceph.wait_for_bootstrap()
ceph.wait_for_quorum()
ceph.create_keyrings()
if cmp_pkgrevno('ceph', '12.0.0') >= 0:
status_set('maintenance', 'Bootstrapping single Ceph MGR')
ceph.bootstrap_manager()
for relid in relation_ids('dashboard'):
dashboard_relation(relid)
# Update client relations
notify_client()
def get_mon_hosts():
hosts = []
addr = get_public_addr()
hosts.append(format_ipv6_addr(addr) or addr)
rel_ids = relation_ids('mon')
if config('no-bootstrap'):
rel_ids += relation_ids('bootstrap-source')
for relid in rel_ids:
for unit in related_units(relid):
addr = relation_get('ceph-public-address', unit, relid)
if addr is not None:
hosts.append(format_ipv6_addr(addr) or addr)
return sorted(hosts)
def get_peer_units():
"""
Returns a dictionary of unit names from the mon peer relation with
a flag indicating whether the unit has presented its address
"""
units = {}
units[local_unit()] = True
for relid in relation_ids('mon'):
for unit in related_units(relid):
addr = relation_get('ceph-public-address', unit, relid)
units[unit] = addr is not None
return units
@hooks.hook('mon-relation-joined')
def mon_relation_joined():
public_addr = get_public_addr()
for relid in relation_ids('mon'):
relation_set(relation_id=relid,
relation_settings={'ceph-public-address': public_addr})
@hooks.hook('bootstrap-source-relation-changed')
def bootstrap_source_relation_changed():
"""Handles relation data changes on the bootstrap-source relation.
The bootstrap-source relation to share remote bootstrap information with
the ceph-mon charm. This relation is used to exchange the remote
ceph-public-addresses which are used for the mon's, the fsid, and the
monitor-secret.
"""
if not config('no-bootstrap'):
status_set('blocked', 'Cannot join the bootstrap-source relation when '
'no-bootstrap is False')
return
if not is_leader():
log('Deferring leader-setting updates to the leader unit')
return
curr_fsid = leader_get('fsid')
curr_secret = leader_get('monitor-secret')
for relid in relation_ids('bootstrap-source'):
for unit in related_units(relid=relid):
mon_secret = relation_get('monitor-secret', unit, relid)
fsid = relation_get('fsid', unit, relid)
if not (mon_secret and fsid):
log('Relation data is not ready as the fsid or the '
'monitor-secret are missing from the relation: '
'mon_secret = {} and fsid = {} '.format(mon_secret, fsid))
continue
if not (curr_fsid or curr_secret):
curr_fsid = fsid
curr_secret = mon_secret
else:
# The fsids and secrets need to match or the local monitors
# will fail to join the mon cluster. If they don't,
# bail because something needs to be investigated.
assert curr_fsid == fsid, \
"bootstrap fsid '{}' != current fsid '{}'".format(
fsid, curr_fsid)
assert curr_secret == mon_secret, \
"bootstrap secret '{}' != current secret '{}'".format(
mon_secret, curr_secret)
opts = {
'fsid': fsid,
'monitor-secret': mon_secret,
}
try:
leader_set(opts)
log('Updating leader settings for fsid and monitor-secret '
'from remote relation data: {}'.format(opts))
except Exception as e:
# we're probably not the leader an exception occured
# let's log it anyway.
log("leader_set failed: {}".format(str(e)))
# The leader unit needs to bootstrap itself as it won't receive the
# leader-settings-changed hook elsewhere.
if curr_fsid:
mon_relation()
@hooks.hook('prometheus-relation-joined',
'prometheus-relation-changed')
def prometheus_relation(relid=None, unit=None, prometheus_permitted=None,
module_enabled=None):
if not ceph.is_bootstrapped():
return
if prometheus_permitted is None:
prometheus_permitted = cmp_pkgrevno('ceph', '12.2.0') >= 0
if module_enabled is None:
module_enabled = (is_mgr_module_enabled('prometheus') or
mgr_enable_module('prometheus'))
log("checking if prometheus module is enabled")
if prometheus_permitted and module_enabled:
log("Updating prometheus")
data = {
'hostname': get_relation_ip('prometheus'),
'port': 9283,
}
relation_set(relation_id=relid,
relation_settings=data)
else:
log("Couldn't enable prometheus, but are related. "
"Prometheus is available in Ceph version: {} ; "
"Prometheus Module is enabled: {}".format(
prometheus_permitted, module_enabled), level=WARNING)
@hooks.hook('prometheus-relation-departed')
def prometheus_left():
mgr_disable_module('prometheus')
@hooks.hook('mon-relation-departed',
'mon-relation-changed',
'leader-settings-changed',
'bootstrap-source-relation-departed')
def mon_relation():
if leader_get('monitor-secret') is None:
log('still waiting for leader to setup keys')
status_set('waiting', 'Waiting for leader to setup keys')
return
emit_cephconf()
moncount = int(config('monitor-count'))
if len(get_mon_hosts()) >= moncount:
if ceph.is_bootstrapped():
# The ceph-mon unit chosen for handling broker requests is based on
# internal Ceph MON leadership and not Juju leadership. To update
# the rbd-mirror relation on all ceph-mon units after pool creation
# the unit handling the broker request will update a nonce on the
# mon relation.
notify_rbd_mirrors()
else:
status_set('maintenance', 'Bootstrapping MON cluster')
# the following call raises an exception
# if it can't add the keyring
try:
ceph.bootstrap_monitor_cluster(leader_get('monitor-secret'))
except FileNotFoundError as e: # NOQA -- PEP8 is still PY2
log("Couldn't bootstrap the monitor yet: {}".format(str(e)))
exit(0)
ceph.wait_for_bootstrap()
ceph.wait_for_quorum()
ceph.create_keyrings()
if cmp_pkgrevno('ceph', '12.0.0') >= 0:
status_set('maintenance', 'Bootstrapping Ceph MGR')
ceph.bootstrap_manager()
if ceph.monitor_key_exists('admin', 'autotune'):
autotune = ceph.monitor_key_get('admin', 'autotune')
else:
ceph.wait_for_manager()
autotune = config('pg-autotune')
if (cmp_pkgrevno('ceph', '14.2.0') >= 0 and
(autotune == 'true' or
autotune == 'auto')):
ceph.monitor_key_set('admin', 'autotune', 'true')
else:
ceph.monitor_key_set('admin', 'autotune', 'false')
if ceph.monitor_key_get('admin', 'autotune') == 'true':
try:
mgr_enable_module('pg_autoscaler')
except subprocess.CalledProcessError:
log("Failed to initialize autoscaler, it must be "
"initialized on the last monitor", level='info')
# If we can and want to
if is_leader() and config('customize-failure-domain'):
# But only if the environment supports it
if os.environ.get('JUJU_AVAILABILITY_ZONE'):
cmds = [
"ceph osd getcrushmap -o /tmp/crush.map",
"crushtool -d /tmp/crush.map| "
"sed 's/step chooseleaf firstn 0 type host/step "
"chooseleaf firstn 0 type rack/' > "
"/tmp/crush.decompiled",
"crushtool -c /tmp/crush.decompiled -o /tmp/crush.map",
"crushtool -i /tmp/crush.map --test",
"ceph osd setcrushmap -i /tmp/crush.map"
]
for cmd in cmds:
try:
subprocess.check_call(cmd, shell=True)
except subprocess.CalledProcessError as e:
log("Failed to modify crush map:", level='error')
log("Cmd: {}".format(cmd), level='error')
log("Error: {}".format(e.output), level='error')
break
else:
log(
"Your Juju environment doesn't"
"have support for Availability Zones"
)
notify_osds()
notify_radosgws()
notify_client()
notify_rbd_mirrors()
notify_prometheus()
else:
log('Not enough mons ({}), punting.'
.format(len(get_mon_hosts())))
def notify_prometheus():
if relation_ids('prometheus') and ceph.is_bootstrapped():
prometheus_permitted = cmp_pkgrevno('ceph', '12.2.0') >= 0
module_enabled = (is_mgr_module_enabled('prometheus') or
mgr_enable_module('prometheus'))
for relid in relation_ids('prometheus'):
for unit in related_units(relid):
prometheus_relation(relid=relid, unit=unit,
prometheus_permitted=prometheus_permitted,
module_enabled=module_enabled)
def notify_osds():
for relid in relation_ids('osd'):
for unit in related_units(relid):
osd_relation(relid=relid, unit=unit)
def notify_radosgws():
for relid in relation_ids('radosgw'):
for unit in related_units(relid):
radosgw_relation(relid=relid, unit=unit)
def notify_rbd_mirrors():
for relid in relation_ids('rbd-mirror'):
for unit in related_units(relid):
rbd_mirror_relation(relid=relid, unit=unit, recurse=False)
def _get_ceph_info_from_configs():
"""Create dictionary of ceph information required to set client relation.
:returns: Dictionary of ceph configurations needed for client relation
:rtpe: dict
"""
public_addr = get_public_addr()
rbd_features = get_rbd_features()
data = {
'auth': config('auth-supported'),
'ceph-public-address': public_addr
}
if rbd_features:
data['rbd-features'] = rbd_features
return data
def _handle_client_relation(relid, unit, data=None):
"""Handle broker request and set the relation data
:param relid: Relation ID
:type relid: str
:param unit: Unit name
:type unit: str
:param data: Initial relation data
:type data: dict
"""
if data is None:
data = {}
if is_unsupported_cmr(unit):
return
data.update(
handle_broker_request(relid, unit, add_legacy_response=True))
relation_set(relation_id=relid, relation_settings=data)
def notify_client():
send_osd_settings()
if not ready_for_service():
log("mon cluster is not in quorum, skipping notify_client",
level=WARNING)
return
for relid in relation_ids('client'):
data = _get_ceph_info_from_configs()
service_name = None
# Loop through all related units until client application name is found
# This is done in seperate loop to avoid calling ceph to retreive named
# key for every unit
for unit in related_units(relid):
service_name = get_client_application_name(relid, unit)
if service_name:
data.update({'key': ceph.get_named_key(service_name)})
break
if not service_name:
log('Unable to determine remote service name, deferring processing'
' of broker requests for relation {} '.format(relid))
# continue with next relid
continue
for unit in related_units(relid):
_handle_client_relation(relid, unit, data)
for relid in relation_ids('admin'):
admin_relation_joined(relid)
for relid in relation_ids('mds'):
for unit in related_units(relid):
mds_relation_joined(relid=relid, unit=unit)
def req_already_treated(request_id, relid, req_unit):
"""Check if broker request already handled.
The local relation data holds all the broker request/responses that
are handled as a dictionary. There will be a single entry for each
unit that makes broker request in the form of broker-rsp-<unit name>:
{reqeust-id: <id>, ..}. Verify if request_id exists in the relation
data broker response for the requested unit.
:param request_id: Request ID
:type request_id: str
:param relid: Relation ID
:type relid: str
:param req_unit: Requested unit name
:type req_unit: str
:returns: Whether request is already handled
:rtype: bool
"""
status = relation_get(rid=relid, unit=local_unit())
response_key = 'broker-rsp-' + req_unit.replace('/', '-')
if not status.get(response_key):
return False
data = None
# relation_get returns the value of response key as a dict or json
# encoded string
if isinstance(status[response_key], str):
try:
data = json.loads(status[response_key])
except (TypeError, json.decoder.JSONDecodeError):
log('Not able to decode broker response for relid {} requested'
'unit {}'.format(relid, req_unit), level=WARNING)
return False
else:
data = status[response_key]
if data.get('request-id') == request_id:
return True
return False
def notify_mons():
"""Update a nonce on the ``mon`` relation.
This is useful for flagging that our peer mon units should update some of
their client relations.
Normally we would have handled this with leader storage, but for the Ceph
case, the unit handling the broker requests is the Ceph MON leader and not
necessarilly the Juju leader.
A non-leader unit has no way of changing data in leader-storage.
"""
nonce = uuid.uuid4()
for relid in relation_ids('mon'):
for unit in related_units(relid):
relation_set(relation_id=relid,
relation_settings={'nonce': nonce})
def get_client_application_name(relid, unit):
"""Retrieve client application name from relation data.
:param relid: Realtion ID
:type relid: str
:param unit: Remote unit name
:type unit: str
"""
if not unit:
unit = remote_unit()
app_name = relation_get(rid=relid, unit=unit).get(
'application-name',
hookenv.remote_service_name(relid=relid))
return app_name
def retrieve_client_broker_requests():
"""Retrieve broker requests from client-type relations.
:returns: Map of broker requests by request-id.
:rtype: List[CephBrokerRq]
"""
def _get_request(relation_data):
if 'broker_req' in relation_data:
rq = CephBrokerRq(raw_request_data=relation_data['broker_req'])
yield rq.request_id, rq
# Note that empty return from generator produces empty generator and
# not None, ref PEP 479
return
# we use a dictionary with request_id as key to deduplicate the list.
# we cannot use the list(set([])) trick here as CephBrokerRq is an
# unhashable type. We also cannot just pass on the raw request either
# as we need to intelligently compare them to avoid false negatives
# due to reordering of keys
return {
request_id: request
# NOTE(fnordahl): the ``rbd-mirror`` endpoint is omitted here as it is
# typically a consumer of the ouptut of this function
for endpoint in ('client', 'mds', 'radosgw')
for relid in relation_ids(endpoint)
for unit in related_units(relid)
for request_id, request in _get_request(
relation_get(rid=relid, unit=unit))
}.values()
def handle_broker_request(relid, unit, add_legacy_response=False,
recurse=True):
"""Retrieve broker request from relation, process, return response data.
:param relid: Realtion ID
:type relid: str
:param unit: Remote unit name
:type unit: str
:param add_legacy_response: (Optional) Adds the legacy ``broker_rsp`` key
to the response in addition to the new way.
:type add_legacy_response: bool
:param recurse: Whether we should call out to update relation functions or
not. Mainly used to handle recursion when called from
notify_rbd_mirrors()
:type recurse: bool
:returns: Dictionary of response data ready for use with relation_set.
:rtype: dict
"""
def _get_broker_req_id(request):
if isinstance(request, str):
try:
req_key = json.loads(request)['request-id']
except (TypeError, json.decoder.JSONDecodeError):
log('Not able to decode request id for broker request {}'.
format(request),
level=WARNING)
req_key = None
else:
req_key = request['request-id']
return req_key
response = {}
if not unit:
unit = remote_unit()
settings = relation_get(rid=relid, unit=unit)
if 'broker_req' in settings:
broker_req_id = _get_broker_req_id(settings['broker_req'])
if broker_req_id is None:
return {}
if not ceph.is_leader():
log("Not leader - ignoring broker request {}".format(
broker_req_id),
level=DEBUG)
return {}
if req_already_treated(broker_req_id, relid, unit):
log("Ignoring already executed broker request {}".format(
broker_req_id),
level=DEBUG)
return {}
rsp = process_requests(settings['broker_req'])
unit_id = settings.get('unit-name', unit).replace('/', '-')
unit_response_key = 'broker-rsp-' + unit_id
response.update({unit_response_key: rsp})
if add_legacy_response:
response.update({'broker_rsp': rsp})
if relation_ids('rbd-mirror'):
# NOTE(fnordahl): juju relation level data candidate
# notify mons to flag that the other mon units should update
# their ``rbd-mirror`` relations with information about new
# pools.
log('Notifying peers after processing broker request {}.'.format(
broker_req_id),
level=DEBUG)
notify_mons()
if recurse:
# update ``rbd-mirror`` relations for this unit with
# information about new pools.
log('Notifying this units rbd-mirror relations after '
'processing broker request {}.'.format(broker_req_id),
level=DEBUG)
notify_rbd_mirrors()
return response
@hooks.hook('osd-relation-joined')
@hooks.hook('osd-relation-changed')
def osd_relation(relid=None, unit=None):
if ceph.is_quorum():
log('mon cluster in quorum - providing fsid & keys')
public_addr = get_public_addr()
data = {
'fsid': leader_get('fsid'),
'osd_bootstrap_key': ceph.get_osd_bootstrap_key(),
'auth': config('auth-supported'),
'ceph-public-address': public_addr,
'osd_upgrade_key': ceph.get_named_key('osd-upgrade',
caps=ceph.osd_upgrade_caps),
}
data.update(handle_broker_request(relid, unit))
relation_set(relation_id=relid,
relation_settings=data)
if is_leader():
ceph_osd_releases = get_ceph_osd_releases()
if len(ceph_osd_releases) == 1:
execute_post_osd_upgrade_steps(ceph_osd_releases[0])
# NOTE: radosgw key provision is gated on presence of OSD
# units so ensure that any deferred hooks are processed
notify_radosgws()
notify_client()
notify_rbd_mirrors()
send_osd_settings()
for relid in relation_ids('dashboard'):
dashboard_relation(relid)
else:
log('mon cluster not in quorum - deferring fsid provision')
def related_osds(num_units=3):
'''
Determine whether there are OSD units currently related
@param num_units: The minimum number of units required
@return: boolean indicating whether the required number of
units where detected.
'''
units = 0
for r_id in relation_ids('osd'):
units += len(related_units(r_id))
if units >= num_units:
return True
return False
def sufficient_osds(minimum_osds=3):
'''
Determine if the minimum number of OSD's have been
bootstrapped into the cluster.
@param expected_osds: The minimum number of OSD's required
@return: boolean indicating whether the required number of
OSD's where detected.
'''
bootstrapped_osds = 0
for r_id in relation_ids('osd'):
for unit in related_units(r_id):
unit_osds = relation_get(
attribute='bootstrapped-osds',
unit=unit, rid=r_id
)
if unit_osds is not None:
bootstrapped_osds += int(unit_osds)
if bootstrapped_osds >= minimum_osds:
return True
return False
def ready_for_service():
'''
Determine whether the Ceph cluster is ready to service
storage traffic from clients
@return: boolean indicating whether the Ceph cluster is
ready for pool creation/client usage.
'''
if not ceph.is_quorum():
log('mon cluster is not in quorum', level=DEBUG)
return False
if is_leader():
if leader_get('bootstrapped-osds') is None and \
not sufficient_osds(config('expected-osd-count') or 3):
log('insufficient osds bootstrapped', level=DEBUG)
return False
leader_set({'bootstrapped-osds': True})
else:
if leader_get('bootstrapped-osds') is None:
return False
return True
@hooks.hook('dashboard-relation-joined')
def dashboard_relation(relid=None):
"""Inform dashboard that mons are ready"""
if not ready_for_service():
log("mon cluster is not in quorum, dashboard notification skipped",
level=WARNING)
return
relation_set(relation_id=relid, relation_settings={'mon-ready': True})
@hooks.hook('radosgw-relation-changed')
@hooks.hook('radosgw-relation-joined')
def radosgw_relation(relid=None, unit=None):
# Install radosgw for admin tools
apt_install(packages=filter_installed_packages(['radosgw']))
if not unit:
unit = remote_unit()
if is_unsupported_cmr(unit):
return
# NOTE: radosgw needs some usage OSD storage, so defer key
# provision until OSD units are detected.
if ready_for_service():
log('mon cluster in quorum and osds bootstrapped '
'- providing radosgw with keys')
public_addr = get_public_addr()
data = {
'fsid': leader_get('fsid'),
'auth': config('auth-supported'),
'ceph-public-address': public_addr,
}
key_name = relation_get('key_name', unit=unit, rid=relid)
if key_name:
# New style, per unit keys
data['{}_key'.format(key_name)] = (
ceph.get_radosgw_key(name=key_name)
)
else:
# Old style global radosgw key
data['radosgw_key'] = ceph.get_radosgw_key()
data.update(handle_broker_request(relid, unit))
relation_set(relation_id=relid, relation_settings=data)
@hooks.hook('rbd-mirror-relation-joined')
@hooks.hook('rbd-mirror-relation-changed')
def rbd_mirror_relation(relid=None, unit=None, recurse=True):
if ready_for_service():
log('mon cluster in quorum and osds bootstrapped '
'- providing rbd-mirror client with keys')
if not unit:
unit = remote_unit()