/
module.py
3523 lines (3136 loc) · 133 KB
/
module.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
import json
import errno
import logging
import time
import yaml
from threading import Event
from functools import wraps
from mgr_util import create_self_signed_cert, verify_tls, ServerConfigException
import string
try:
from typing import List, Dict, Optional, Callable, Tuple, TypeVar, Type, \
Any, NamedTuple, Iterator, Set, Sequence
from typing import TYPE_CHECKING, cast
except ImportError:
TYPE_CHECKING = False # just for type checking
import datetime
import six
import os
import random
import tempfile
import multiprocessing.pool
import re
import shutil
import subprocess
import uuid
from ceph.deployment import inventory, translate
from ceph.deployment.drive_group import DriveGroupSpec
from ceph.deployment.drive_selection import selector
from ceph.deployment.service_spec import \
HostPlacementSpec, NFSServiceSpec, ServiceSpec, PlacementSpec, assert_valid_host
from mgr_module import MgrModule, HandleCommandResult
import orchestrator
from orchestrator import OrchestratorError, OrchestratorValidationError, HostSpec, \
CLICommandMeta
from . import remotes
from . import utils
from .nfs import NFSGanesha
from .osd import RemoveUtil, OSDRemoval
try:
import remoto
import remoto.process
import execnet.gateway_bootstrap
except ImportError as e:
remoto = None
remoto_import_error = str(e)
try:
from typing import List
except ImportError:
pass
logger = logging.getLogger(__name__)
DEFAULT_SSH_CONFIG = ('Host *\n'
'User root\n'
'StrictHostKeyChecking no\n'
'UserKnownHostsFile /dev/null\n')
DATEFMT = '%Y-%m-%dT%H:%M:%S.%f'
CEPH_DATEFMT = '%Y-%m-%dT%H:%M:%S.%fZ'
HOST_CACHE_PREFIX = "host."
SPEC_STORE_PREFIX = "spec."
# ceph daemon types that use the ceph container image.
# NOTE: listed in upgrade order!
CEPH_UPGRADE_ORDER = ['mgr', 'mon', 'crash', 'osd', 'mds', 'rgw', 'rbd-mirror']
CEPH_TYPES = set(CEPH_UPGRADE_ORDER)
# for py2 compat
try:
from tempfile import TemporaryDirectory # py3
except ImportError:
# define a minimal (but sufficient) equivalent for <= py 3.2
class TemporaryDirectory(object): # type: ignore
def __init__(self):
self.name = tempfile.mkdtemp()
def __enter__(self):
if not self.name:
self.name = tempfile.mkdtemp()
return self.name
def cleanup(self):
shutil.rmtree(self.name)
def __exit__(self, exc_type, exc_value, traceback):
self.cleanup()
class SpecStore():
def __init__(self, mgr):
# type: (CephadmOrchestrator) -> None
self.mgr = mgr
self.specs = {} # type: Dict[str, ServiceSpec]
self.spec_created = {} # type: Dict[str, datetime.datetime]
def load(self):
# type: () -> None
for k, v in six.iteritems(self.mgr.get_store_prefix(SPEC_STORE_PREFIX)):
service_name = k[len(SPEC_STORE_PREFIX):]
try:
v = json.loads(v)
spec = ServiceSpec.from_json(v['spec'])
created = datetime.datetime.strptime(v['created'], DATEFMT)
self.specs[service_name] = spec
self.spec_created[service_name] = created
self.mgr.log.debug('SpecStore: loaded spec for %s' % (
service_name))
except Exception as e:
self.mgr.log.warning('unable to load spec for %s: %s' % (
service_name, e))
pass
def save(self, spec):
# type: (ServiceSpec) -> None
self.specs[spec.service_name()] = spec
self.spec_created[spec.service_name()] = datetime.datetime.utcnow()
self.mgr.set_store(
SPEC_STORE_PREFIX + spec.service_name(),
json.dumps({
'spec': spec.to_json(),
'created': self.spec_created[spec.service_name()].strftime(DATEFMT),
}, sort_keys=True),
)
def rm(self, service_name):
# type: (str) -> None
if service_name in self.specs:
del self.specs[service_name]
del self.spec_created[service_name]
self.mgr.set_store(SPEC_STORE_PREFIX + service_name, None)
def find(self, service_name=None):
# type: (Optional[str]) -> List[ServiceSpec]
specs = []
for sn, spec in self.specs.items():
if not service_name or \
sn == service_name or \
sn.startswith(service_name + '.'):
specs.append(spec)
self.mgr.log.debug('SpecStore: find spec for %s returned: %s' % (
service_name, specs))
return specs
class HostCache():
def __init__(self, mgr):
# type: (CephadmOrchestrator) -> None
self.mgr = mgr
self.daemons = {} # type: Dict[str, Dict[str, orchestrator.DaemonDescription]]
self.last_daemon_update = {} # type: Dict[str, datetime.datetime]
self.devices = {} # type: Dict[str, List[inventory.Device]]
self.networks = {} # type: Dict[str, Dict[str, List[str]]]
self.last_device_update = {} # type: Dict[str, datetime.datetime]
self.daemon_refresh_queue = [] # type: List[str]
self.device_refresh_queue = [] # type: List[str]
self.daemon_config_deps = {} # type: Dict[str, Dict[str, Dict[str,Any]]]
self.last_host_check = {} # type: Dict[str, datetime.datetime]
def load(self):
# type: () -> None
for k, v in six.iteritems(self.mgr.get_store_prefix(HOST_CACHE_PREFIX)):
host = k[len(HOST_CACHE_PREFIX):]
if host not in self.mgr.inventory:
self.mgr.log.warning('removing stray HostCache host record %s' % (
host))
self.mgr.set_store(k, None)
try:
j = json.loads(v)
if 'last_device_update' in j:
self.last_device_update[host] = datetime.datetime.strptime(
j['last_device_update'], DATEFMT)
else:
self.device_refresh_queue.append(host)
# for services, we ignore the persisted last_*_update
# and always trigger a new scrape on mgr restart.
self.daemon_refresh_queue.append(host)
self.daemons[host] = {}
self.devices[host] = []
self.networks[host] = {}
self.daemon_config_deps[host] = {}
for name, d in j.get('daemons', {}).items():
self.daemons[host][name] = \
orchestrator.DaemonDescription.from_json(d)
for d in j.get('devices', []):
self.devices[host].append(inventory.Device.from_json(d))
self.networks[host] = j.get('networks', {})
for name, d in j.get('daemon_config_deps', {}).items():
self.daemon_config_deps[host][name] = {
'deps': d.get('deps', []),
'last_config': datetime.datetime.strptime(
d['last_config'], DATEFMT),
}
if 'last_host_check' in j:
self.last_host_check[host] = datetime.datetime.strptime(
j['last_host_check'], DATEFMT)
self.mgr.log.debug(
'HostCache.load: host %s has %d daemons, '
'%d devices, %d networks' % (
host, len(self.daemons[host]), len(self.devices[host]),
len(self.networks[host])))
except Exception as e:
self.mgr.log.warning('unable to load cached state for %s: %s' % (
host, e))
pass
def update_host_daemons(self, host, dm):
# type: (str, Dict[str, orchestrator.DaemonDescription]) -> None
self.daemons[host] = dm
self.last_daemon_update[host] = datetime.datetime.utcnow()
def update_host_devices_networks(self, host, dls, nets):
# type: (str, List[inventory.Device], Dict[str,List[str]]) -> None
self.devices[host] = dls
self.networks[host] = nets
self.last_device_update[host] = datetime.datetime.utcnow()
def update_daemon_config_deps(self, host, name, deps, stamp):
self.daemon_config_deps[host][name] = {
'deps': deps,
'last_config': stamp,
}
def update_last_host_check(self, host):
# type: (str) -> None
self.last_host_check[host] = datetime.datetime.utcnow()
def prime_empty_host(self, host):
# type: (str) -> None
"""
Install an empty entry for a host
"""
self.daemons[host] = {}
self.devices[host] = []
self.networks[host] = {}
self.daemon_config_deps[host] = {}
self.daemon_refresh_queue.append(host)
self.device_refresh_queue.append(host)
def invalidate_host_daemons(self, host):
# type: (str) -> None
self.daemon_refresh_queue.append(host)
if host in self.last_daemon_update:
del self.last_daemon_update[host]
self.mgr.event.set()
def invalidate_host_devices(self, host):
# type: (str) -> None
self.device_refresh_queue.append(host)
if host in self.last_device_update:
del self.last_device_update[host]
self.mgr.event.set()
def save_host(self, host):
# type: (str) -> None
j = { # type: ignore
'daemons': {},
'devices': [],
'daemon_config_deps': {},
}
if host in self.last_daemon_update:
j['last_daemon_update'] = self.last_daemon_update[host].strftime(DATEFMT) # type: ignore
if host in self.last_device_update:
j['last_device_update'] = self.last_device_update[host].strftime(DATEFMT) # type: ignore
for name, dd in self.daemons[host].items():
j['daemons'][name] = dd.to_json() # type: ignore
for d in self.devices[host]:
j['devices'].append(d.to_json()) # type: ignore
j['networks'] = self.networks[host]
for name, depi in self.daemon_config_deps[host].items():
j['daemon_config_deps'][name] = { # type: ignore
'deps': depi.get('deps', []),
'last_config': depi['last_config'].strftime(DATEFMT),
}
if host in self.last_host_check:
j['last_host_check']= self.last_host_check[host].strftime(DATEFMT)
self.mgr.set_store(HOST_CACHE_PREFIX + host, json.dumps(j))
def rm_host(self, host):
# type: (str) -> None
if host in self.daemons:
del self.daemons[host]
if host in self.devices:
del self.devices[host]
if host in self.networks:
del self.networks[host]
if host in self.last_daemon_update:
del self.last_daemon_update[host]
if host in self.last_device_update:
del self.last_device_update[host]
if host in self.daemon_config_deps:
del self.daemon_config_deps[host]
self.mgr.set_store(HOST_CACHE_PREFIX + host, None)
def get_hosts(self):
# type: () -> List[str]
r = []
for host, di in self.daemons.items():
r.append(host)
return r
def get_daemons(self):
# type: () -> List[orchestrator.DaemonDescription]
r = []
for host, dm in self.daemons.items():
for name, dd in dm.items():
r.append(dd)
return r
def get_daemons_by_service(self, service_name):
# type: (str) -> List[orchestrator.DaemonDescription]
result = [] # type: List[orchestrator.DaemonDescription]
for host, dm in self.daemons.items():
for name, d in dm.items():
if name.startswith(service_name + '.'):
result.append(d)
return result
def get_daemon_names(self):
# type: () -> List[str]
r = []
for host, dm in self.daemons.items():
for name, dd in dm.items():
r.append(name)
return r
def get_daemon_last_config_deps(self, host, name):
if host in self.daemon_config_deps:
if name in self.daemon_config_deps[host]:
return self.daemon_config_deps[host][name].get('deps', []), \
self.daemon_config_deps[host][name].get('last_config', None)
return None, None
def host_needs_daemon_refresh(self, host):
# type: (str) -> bool
if host in self.daemon_refresh_queue:
self.daemon_refresh_queue.remove(host)
return True
cutoff = datetime.datetime.utcnow() - datetime.timedelta(
seconds=self.mgr.daemon_cache_timeout)
if host not in self.last_daemon_update or self.last_daemon_update[host] < cutoff:
return True
return False
def host_needs_device_refresh(self, host):
# type: (str) -> bool
if host in self.device_refresh_queue:
self.device_refresh_queue.remove(host)
return True
cutoff = datetime.datetime.utcnow() - datetime.timedelta(
seconds=self.mgr.device_cache_timeout)
if host not in self.last_device_update or self.last_device_update[host] < cutoff:
return True
return False
def host_needs_check(self, host):
# type: (str) -> bool
cutoff = datetime.datetime.utcnow() - datetime.timedelta(
seconds=self.mgr.host_check_interval)
return host not in self.last_host_check or self.last_host_check[host] < cutoff
def add_daemon(self, host, dd):
# type: (str, orchestrator.DaemonDescription) -> None
assert host in self.daemons
self.daemons[host][dd.name()] = dd
def rm_daemon(self, host, name):
if host in self.daemons:
if name in self.daemons[host]:
del self.daemons[host][name]
class AsyncCompletion(orchestrator.Completion):
def __init__(self,
_first_promise=None, # type: Optional[orchestrator.Completion]
value=orchestrator._Promise.NO_RESULT, # type: Any
on_complete=None, # type: Optional[Callable]
name=None, # type: Optional[str]
many=False, # type: bool
update_progress=False, # type: bool
):
assert CephadmOrchestrator.instance is not None
self.many = many
self.update_progress = update_progress
if name is None and on_complete is not None:
name = getattr(on_complete, '__name__', None)
super(AsyncCompletion, self).__init__(_first_promise, value, on_complete, name)
@property
def _progress_reference(self):
# type: () -> Optional[orchestrator.ProgressReference]
if hasattr(self._on_complete_, 'progress_id'): # type: ignore
return self._on_complete_ # type: ignore
return None
@property
def _on_complete(self):
# type: () -> Optional[Callable]
if self._on_complete_ is None:
return None
def callback(result):
try:
if self.update_progress:
assert self.progress_reference
self.progress_reference.progress = 1.0
self._on_complete_ = None
self._finalize(result)
except Exception as e:
try:
self.fail(e)
except Exception:
logger.exception(f'failed to fail AsyncCompletion: >{repr(self)}<')
if 'UNITTEST' in os.environ:
assert False
def error_callback(e):
pass
def run(value):
def do_work(*args, **kwargs):
assert self._on_complete_ is not None
try:
res = self._on_complete_(*args, **kwargs)
if self.update_progress and self.many:
assert self.progress_reference
self.progress_reference.progress += 1.0 / len(value)
return res
except Exception as e:
self.fail(e)
raise
assert CephadmOrchestrator.instance
if self.many:
if not value:
logger.info('calling map_async without values')
callback([])
if six.PY3:
CephadmOrchestrator.instance._worker_pool.map_async(do_work, value,
callback=callback,
error_callback=error_callback)
else:
CephadmOrchestrator.instance._worker_pool.map_async(do_work, value,
callback=callback)
else:
if six.PY3:
CephadmOrchestrator.instance._worker_pool.apply_async(do_work, (value,),
callback=callback, error_callback=error_callback)
else:
CephadmOrchestrator.instance._worker_pool.apply_async(do_work, (value,),
callback=callback)
return self.ASYNC_RESULT
return run
@_on_complete.setter
def _on_complete(self, inner):
# type: (Callable) -> None
self._on_complete_ = inner
def ssh_completion(cls=AsyncCompletion, **c_kwargs):
# type: (Type[orchestrator.Completion], Any) -> Callable
"""
See ./HACKING.rst for a how-to
"""
def decorator(f):
@wraps(f)
def wrapper(*args):
name = f.__name__
many = c_kwargs.get('many', False)
# Some weired logic to make calling functions with multiple arguments work.
if len(args) == 1:
[value] = args
if many and value and isinstance(value[0], tuple):
return cls(on_complete=lambda x: f(*x), value=value, name=name, **c_kwargs)
else:
return cls(on_complete=f, value=value, name=name, **c_kwargs)
else:
if many:
self, value = args
def call_self(inner_args):
if not isinstance(inner_args, tuple):
inner_args = (inner_args, )
return f(self, *inner_args)
return cls(on_complete=call_self, value=value, name=name, **c_kwargs)
else:
return cls(on_complete=lambda x: f(*x), value=args, name=name, **c_kwargs)
return wrapper
return decorator
def async_completion(f):
# type: (Callable) -> Callable[..., AsyncCompletion]
"""
See ./HACKING.rst for a how-to
:param f: wrapped function
"""
return ssh_completion()(f)
def async_map_completion(f):
# type: (Callable) -> Callable[..., AsyncCompletion]
"""
See ./HACKING.rst for a how-to
:param f: wrapped function
kind of similar to
>>> def sync_map(f):
... return lambda x: map(f, x)
"""
return ssh_completion(many=True)(f)
def trivial_completion(f):
# type: (Callable) -> Callable[..., orchestrator.Completion]
@wraps(f)
def wrapper(*args, **kwargs):
return AsyncCompletion(value=f(*args, **kwargs), name=f.__name__)
return wrapper
@six.add_metaclass(CLICommandMeta)
class CephadmOrchestrator(orchestrator.Orchestrator, MgrModule):
_STORE_HOST_PREFIX = "host"
instance = None
NATIVE_OPTIONS = [] # type: List[Any]
MODULE_OPTIONS = [
{
'name': 'ssh_config_file',
'type': 'str',
'default': None,
'desc': 'customized SSH config file to connect to managed hosts',
},
{
'name': 'device_cache_timeout',
'type': 'secs',
'default': 30 * 60,
'desc': 'seconds to cache device inventory',
},
{
'name': 'daemon_cache_timeout',
'type': 'secs',
'default': 10 * 60,
'desc': 'seconds to cache service (daemon) inventory',
},
{
'name': 'host_check_interval',
'type': 'secs',
'default': 10 * 60,
'desc': 'how frequently to perform a host check',
},
{
'name': 'mode',
'type': 'str',
'enum_allowed': ['root', 'cephadm-package'],
'default': 'root',
'desc': 'mode for remote execution of cephadm',
},
{
'name': 'container_image_base',
'default': 'docker.io/ceph/ceph',
'desc': 'Container image name, without the tag',
'runtime': True,
},
{
'name': 'warn_on_stray_hosts',
'type': 'bool',
'default': True,
'desc': 'raise a health warning if daemons are detected on a host '
'that is not managed by cephadm',
},
{
'name': 'warn_on_stray_daemons',
'type': 'bool',
'default': True,
'desc': 'raise a health warning if daemons are detected '
'that are not managed by cephadm',
},
{
'name': 'warn_on_failed_host_check',
'type': 'bool',
'default': True,
'desc': 'raise a health warning if the host check fails',
},
{
'name': 'log_to_cluster',
'type': 'bool',
'default': True,
'desc': 'log to the "cephadm" cluster log channel"',
},
{
'name': 'allow_ptrace',
'type': 'bool',
'default': False,
'desc': 'allow SYS_PTRACE capability on ceph containers',
'long_desc': 'The SYS_PTRACE capability is needed to attach to a '
'process with gdb or strace. Enabling this options '
'can allow debugging daemons that encounter problems '
'at runtime.',
},
{
'name': 'prometheus_alerts_path',
'type': 'str',
'default': '/etc/prometheus/ceph/ceph_default_alerts.yml',
'desc': 'location of alerts to include in prometheus deployments',
},
]
def __init__(self, *args, **kwargs):
super(CephadmOrchestrator, self).__init__(*args, **kwargs)
self._cluster_fsid = self.get('mon_map')['fsid']
# for serve()
self.run = True
self.event = Event()
if self.get_store('pause'):
self.paused = True
else:
self.paused = False
# for mypy which does not run the code
if TYPE_CHECKING:
self.ssh_config_file = None # type: Optional[str]
self.device_cache_timeout = 0
self.daemon_cache_timeout = 0
self.host_check_interval = 0
self.mode = ''
self.container_image_base = ''
self.warn_on_stray_hosts = True
self.warn_on_stray_daemons = True
self.warn_on_failed_host_check = True
self.allow_ptrace = False
self.prometheus_alerts_path = ''
self._cons = {} # type: Dict[str, Tuple[remoto.backends.BaseConnection,remoto.backends.LegacyModuleExecute]]
self.config_notify()
path = self.get_ceph_option('cephadm_path')
try:
with open(path, 'r') as f:
self._cephadm = f.read()
except (IOError, TypeError) as e:
raise RuntimeError("unable to read cephadm at '%s': %s" % (
path, str(e)))
self._worker_pool = multiprocessing.pool.ThreadPool(10)
self._reconfig_ssh()
CephadmOrchestrator.instance = self
t = self.get_store('upgrade_state')
if t:
self.upgrade_state = json.loads(t)
else:
self.upgrade_state = None
self.health_checks = {}
self.all_progress_references = list() # type: List[orchestrator.ProgressReference]
# load inventory
i = self.get_store('inventory')
if i:
self.inventory: Dict[str, dict] = json.loads(i)
else:
self.inventory = dict()
self.log.debug('Loaded inventory %s' % self.inventory)
self.cache = HostCache(self)
self.cache.load()
self.rm_util = RemoveUtil(self)
self.spec_store = SpecStore(self)
self.spec_store.load()
# ensure the host lists are in sync
for h in self.inventory.keys():
if h not in self.cache.daemons:
self.cache.prime_empty_host(h)
for h in self.cache.get_hosts():
if h not in self.inventory:
self.cache.rm_host(h)
def shutdown(self):
self.log.debug('shutdown')
self._worker_pool.close()
self._worker_pool.join()
self.run = False
self.event.set()
def _kick_serve_loop(self):
self.log.debug('_kick_serve_loop')
self.event.set()
def _check_safe_to_destroy_mon(self, mon_id):
# type: (str) -> None
ret, out, err = self.mon_command({
'prefix': 'quorum_status',
})
if ret:
raise OrchestratorError('failed to check mon quorum status')
try:
j = json.loads(out)
except Exception as e:
raise OrchestratorError('failed to parse quorum status')
mons = [m['name'] for m in j['monmap']['mons']]
if mon_id not in mons:
self.log.info('Safe to remove mon.%s: not in monmap (%s)' % (
mon_id, mons))
return
new_mons = [m for m in mons if m != mon_id]
new_quorum = [m for m in j['quorum_names'] if m != mon_id]
if len(new_quorum) > len(new_mons) / 2:
self.log.info('Safe to remove mon.%s: new quorum should be %s (from %s)' % (mon_id, new_quorum, new_mons))
return
raise OrchestratorError('Removing %s would break mon quorum (new quorum %s, new mons %s)' % (mon_id, new_quorum, new_mons))
def _wait_for_ok_to_stop(self, s):
# only wait a little bit; the service might go away for something
tries = 4
while tries > 0:
if s.daemon_type not in ['mon', 'osd', 'mds']:
self.log.info('Upgrade: It is presumed safe to stop %s.%s' %
(s.daemon_type, s.daemon_id))
return True
ret, out, err = self.mon_command({
'prefix': '%s ok-to-stop' % s.daemon_type,
'ids': [s.daemon_id],
})
if not self.upgrade_state or self.upgrade_state.get('paused'):
return False
if ret:
self.log.info('Upgrade: It is NOT safe to stop %s.%s' %
(s.daemon_type, s.daemon_id))
time.sleep(15)
tries -= 1
else:
self.log.info('Upgrade: It is safe to stop %s.%s' %
(s.daemon_type, s.daemon_id))
return True
return False
def _clear_upgrade_health_checks(self):
for k in ['UPGRADE_NO_STANDBY_MGR',
'UPGRADE_FAILED_PULL']:
if k in self.health_checks:
del self.health_checks[k]
self.set_health_checks(self.health_checks)
def _fail_upgrade(self, alert_id, alert):
self.log.error('Upgrade: Paused due to %s: %s' % (alert_id,
alert['summary']))
self.upgrade_state['error'] = alert_id + ': ' + alert['summary']
self.upgrade_state['paused'] = True
self._save_upgrade_state()
self.health_checks[alert_id] = alert
self.set_health_checks(self.health_checks)
def _update_upgrade_progress(self, progress):
if 'progress_id' not in self.upgrade_state:
self.upgrade_state['progress_id'] = str(uuid.uuid4())
self._save_upgrade_state()
self.remote('progress', 'update', self.upgrade_state['progress_id'],
ev_msg='Upgrade to %s' % self.upgrade_state['target_name'],
ev_progress=progress)
def _do_upgrade(self):
# type: () -> None
if not self.upgrade_state:
self.log.debug('_do_upgrade no state, exiting')
return
target_name = self.upgrade_state.get('target_name')
target_id = self.upgrade_state.get('target_id', None)
if not target_id:
# need to learn the container hash
self.log.info('Upgrade: First pull of %s' % target_name)
try:
target_id, target_version = self._get_container_image_id(target_name)
except OrchestratorError as e:
self._fail_upgrade('UPGRADE_FAILED_PULL', {
'severity': 'warning',
'summary': 'Upgrade: failed to pull target image',
'count': 1,
'detail': [str(e)],
})
return
self.upgrade_state['target_id'] = target_id
self.upgrade_state['target_version'] = target_version
self._save_upgrade_state()
target_version = self.upgrade_state.get('target_version')
self.log.info('Upgrade: Target is %s with id %s' % (target_name,
target_id))
# get all distinct container_image settings
image_settings = {}
ret, out, err = self.mon_command({
'prefix': 'config dump',
'format': 'json',
})
config = json.loads(out)
for opt in config:
if opt['name'] == 'container_image':
image_settings[opt['section']] = opt['value']
daemons = self.cache.get_daemons()
done = 0
for daemon_type in CEPH_UPGRADE_ORDER:
self.log.info('Upgrade: Checking %s daemons...' % daemon_type)
need_upgrade_self = False
for d in daemons:
if d.daemon_type != daemon_type:
continue
if d.container_image_id == target_id:
self.log.debug('daemon %s.%s version correct' % (
daemon_type, d.daemon_id))
done += 1
continue
self.log.debug('daemon %s.%s not correct (%s, %s, %s)' % (
daemon_type, d.daemon_id,
d.container_image_name, d.container_image_id, d.version))
if daemon_type == 'mgr' and \
d.daemon_id == self.get_mgr_id():
self.log.info('Upgrade: Need to upgrade myself (mgr.%s)' %
self.get_mgr_id())
need_upgrade_self = True
continue
# make sure host has latest container image
out, err, code = self._run_cephadm(
d.hostname, None, 'inspect-image', [],
image=target_name, no_fsid=True, error_ok=True)
if code or json.loads(''.join(out)).get('image_id') != target_id:
self.log.info('Upgrade: Pulling %s on %s' % (target_name,
d.hostname))
out, err, code = self._run_cephadm(
d.hostname, None, 'pull', [],
image=target_name, no_fsid=True, error_ok=True)
if code:
self._fail_upgrade('UPGRADE_FAILED_PULL', {
'severity': 'warning',
'summary': 'Upgrade: failed to pull target image',
'count': 1,
'detail': [
'failed to pull %s on host %s' % (target_name,
d.hostname)],
})
return
r = json.loads(''.join(out))
if r.get('image_id') != target_id:
self.log.info('Upgrade: image %s pull on %s got new image %s (not %s), restarting' % (target_name, d.hostname, r['image_id'], target_id))
self.upgrade_state['target_id'] = r['image_id']
self._save_upgrade_state()
return
self._update_upgrade_progress(done / len(daemons))
if not d.container_image_id:
if d.container_image_name == target_name:
self.log.debug('daemon %s has unknown container_image_id but has correct image name' % (d.name()))
continue
if not self._wait_for_ok_to_stop(d):
return
self.log.info('Upgrade: Redeploying %s.%s' %
(d.daemon_type, d.daemon_id))
ret, out, err = self.mon_command({
'prefix': 'config set',
'name': 'container_image',
'value': target_name,
'who': utils.name_to_config_section(daemon_type + '.' + d.daemon_id),
})
self._daemon_action(
d.daemon_type,
d.daemon_id,
d.hostname,
'redeploy'
)
return
if need_upgrade_self:
mgr_map = self.get('mgr_map')
num = len(mgr_map.get('standbys'))
if not num:
self._fail_upgrade('UPGRADE_NO_STANDBY_MGR', {
'severity': 'warning',
'summary': 'Upgrade: Need standby mgr daemon',
'count': 1,
'detail': [
'The upgrade process needs to upgrade the mgr, '
'but it needs at least one standby to proceed.',
],
})
return
self.log.info('Upgrade: there are %d other already-upgraded '
'standby mgrs, failing over' % num)
self._update_upgrade_progress(done / len(daemons))
# fail over
ret, out, err = self.mon_command({
'prefix': 'mgr fail',
'who': self.get_mgr_id(),
})
return
elif daemon_type == 'mgr':
if 'UPGRADE_NO_STANDBY_MGR' in self.health_checks:
del self.health_checks['UPGRADE_NO_STANDBY_MGR']
self.set_health_checks(self.health_checks)
# make sure 'ceph versions' agrees
ret, out, err = self.mon_command({
'prefix': 'versions',
})
j = json.loads(out)
for version, count in j.get(daemon_type, {}).items():
if version != target_version:
self.log.warning(
'Upgrade: %d %s daemon(s) are %s != target %s' %
(count, daemon_type, version, target_version))
# push down configs
if image_settings.get(daemon_type) != target_name:
self.log.info('Upgrade: Setting container_image for all %s...' %
daemon_type)
ret, out, err = self.mon_command({
'prefix': 'config set',
'name': 'container_image',
'value': target_name,
'who': daemon_type,
})
to_clean = []
for section in image_settings.keys():
if section.startswith(utils.name_to_config_section(daemon_type) + '.'):
to_clean.append(section)
if to_clean:
self.log.debug('Upgrade: Cleaning up container_image for %s...' %
to_clean)
for section in to_clean:
ret, image, err = self.mon_command({
'prefix': 'config rm',
'name': 'container_image',
'who': section,
})
self.log.info('Upgrade: All %s daemons are up to date.' %
daemon_type)
# clean up
self.log.info('Upgrade: Finalizing container_image settings')
ret, out, err = self.mon_command({
'prefix': 'config set',
'name': 'container_image',
'value': target_name,
'who': 'global',
})
for daemon_type in CEPH_UPGRADE_ORDER:
ret, image, err = self.mon_command({
'prefix': 'config rm',
'name': 'container_image',
'who': utils.name_to_config_section(daemon_type),
})
self.log.info('Upgrade: Complete!')
if 'progress_id' in self.upgrade_state:
self.remote('progress', 'complete',
self.upgrade_state['progress_id'])
self.upgrade_state = None
self._save_upgrade_state()
return
def _check_hosts(self):