-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
module.py
2507 lines (2199 loc) · 99.8 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 re
import shlex
from collections import defaultdict
from configparser import ConfigParser
from functools import wraps
from tempfile import TemporaryDirectory
from threading import Event
import string
from typing import List, Dict, Optional, Callable, Tuple, TypeVar, \
Any, Set, TYPE_CHECKING, cast, NamedTuple, Sequence, Type
import datetime
import os
import random
import tempfile
import multiprocessing.pool
import subprocess
from prettytable import PrettyTable
from ceph.deployment import inventory
from ceph.deployment.drive_group import DriveGroupSpec
from ceph.deployment.service_spec import \
NFSServiceSpec, ServiceSpec, PlacementSpec, assert_valid_host, \
HostPlacementSpec, IngressSpec
from ceph.utils import str_to_datetime, datetime_to_str, datetime_now
from cephadm.serve import CephadmServe
from cephadm.services.cephadmservice import CephadmDaemonDeploySpec
from mgr_module import MgrModule, HandleCommandResult, Option
from mgr_util import create_self_signed_cert
import secrets
import orchestrator
from orchestrator.module import to_format, Format
from orchestrator import OrchestratorError, OrchestratorValidationError, HostSpec, \
CLICommandMeta, DaemonDescription, DaemonDescriptionStatus, handle_orch_error, \
service_to_daemon_types
from orchestrator._interface import GenericSpec
from orchestrator._interface import daemon_type_to_service
from . import remotes
from . import utils
from .migrations import Migrations
from .services.cephadmservice import MonService, MgrService, MdsService, RgwService, \
RbdMirrorService, CrashService, CephadmService, CephfsMirrorService
from .services.ingress import IngressService
from .services.container import CustomContainerService
from .services.iscsi import IscsiService
from .services.nfs import NFSService
from .services.osd import OSDRemovalQueue, OSDService, OSD, NotFoundError
from .services.monitoring import GrafanaService, AlertmanagerService, PrometheusService, \
NodeExporterService
from .services.exporter import CephadmExporter, CephadmExporterConfig
from .schedule import HostAssignment
from .inventory import Inventory, SpecStore, HostCache, EventStore, ClientKeyringStore, ClientKeyringSpec
from .upgrade import CephadmUpgrade
from .template import TemplateMgr
from .utils import CEPH_TYPES, GATEWAY_TYPES, forall_hosts, cephadmNoImage
from .configchecks import CephadmConfigChecks
try:
import remoto
# NOTE(mattoliverau) Patch remoto until remoto PR
# (https://github.com/alfredodeza/remoto/pull/56) lands
from distutils.version import StrictVersion
if StrictVersion(remoto.__version__) <= StrictVersion('1.2'):
def remoto_has_connection(self: Any) -> bool:
return self.gateway.hasreceiver()
from remoto.backends import BaseConnection
BaseConnection.has_connection = remoto_has_connection
import remoto.process
except ImportError as e:
remoto = None
remoto_import_error = str(e)
logger = logging.getLogger(__name__)
T = TypeVar('T')
DEFAULT_SSH_CONFIG = """
Host *
User root
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
ConnectTimeout=30
"""
# Default container images -----------------------------------------------------
DEFAULT_IMAGE = 'docker.io/ceph/ceph'
DEFAULT_PROMETHEUS_IMAGE = 'docker.io/prom/prometheus:v2.18.1'
DEFAULT_NODE_EXPORTER_IMAGE = 'docker.io/prom/node-exporter:v0.18.1'
DEFAULT_GRAFANA_IMAGE = 'docker.io/ceph/ceph-grafana:6.7.4'
DEFAULT_ALERT_MANAGER_IMAGE = 'docker.io/prom/alertmanager:v0.20.0'
# ------------------------------------------------------------------------------
def service_inactive(spec_name: str) -> Callable:
def inner(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
obj = args[0]
if obj.get_store(f"spec.{spec_name}") is not None:
return 1, "", f"Unable to change configuration of an active service {spec_name}"
return func(*args, **kwargs)
return wrapper
return inner
def host_exists(hostname_position: int = 1) -> Callable:
"""Check that a hostname exists in the inventory"""
def inner(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
this = args[0] # self object
hostname = args[hostname_position]
if hostname not in this.cache.get_hosts():
candidates = ','.join([h for h in this.cache.get_hosts() if h.startswith(hostname)])
help_msg = f"Did you mean {candidates}?" if candidates else ""
raise OrchestratorError(
f"Cannot find host '{hostname}' in the inventory. {help_msg}")
return func(*args, **kwargs)
return wrapper
return inner
class CephadmOrchestrator(orchestrator.Orchestrator, MgrModule,
metaclass=CLICommandMeta):
_STORE_HOST_PREFIX = "host"
instance = None
NATIVE_OPTIONS = [] # type: List[Any]
MODULE_OPTIONS = [
Option(
'ssh_config_file',
type='str',
default=None,
desc='customized SSH config file to connect to managed hosts',
),
Option(
'device_cache_timeout',
type='secs',
default=30 * 60,
desc='seconds to cache device inventory',
),
Option(
'device_enhanced_scan',
type='bool',
default=False,
desc='Use libstoragemgmt during device scans',
),
Option(
'daemon_cache_timeout',
type='secs',
default=10 * 60,
desc='seconds to cache service (daemon) inventory',
),
Option(
'facts_cache_timeout',
type='secs',
default=1 * 60,
desc='seconds to cache host facts data',
),
Option(
'host_check_interval',
type='secs',
default=10 * 60,
desc='how frequently to perform a host check',
),
Option(
'mode',
type='str',
enum_allowed=['root', 'cephadm-package'],
default='root',
desc='mode for remote execution of cephadm',
),
Option(
'container_image_base',
default=DEFAULT_IMAGE,
desc='Container image name, without the tag',
runtime=True,
),
Option(
'container_image_prometheus',
default=DEFAULT_PROMETHEUS_IMAGE,
desc='Prometheus container image',
),
Option(
'container_image_grafana',
default=DEFAULT_GRAFANA_IMAGE,
desc='Prometheus container image',
),
Option(
'container_image_alertmanager',
default=DEFAULT_ALERT_MANAGER_IMAGE,
desc='Prometheus container image',
),
Option(
'container_image_node_exporter',
default=DEFAULT_NODE_EXPORTER_IMAGE,
desc='Prometheus container image',
),
Option(
'container_image_haproxy',
default='haproxy',
desc='HAproxy container image',
),
Option(
'container_image_keepalived',
default='arcts/keepalived',
desc='Keepalived container image',
),
Option(
'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',
),
Option(
'warn_on_stray_daemons',
type='bool',
default=True,
desc='raise a health warning if daemons are detected '
'that are not managed by cephadm',
),
Option(
'warn_on_failed_host_check',
type='bool',
default=True,
desc='raise a health warning if the host check fails',
),
Option(
'log_to_cluster',
type='bool',
default=True,
desc='log to the "cephadm" cluster log channel"',
),
Option(
'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.',
),
Option(
'container_init',
type='bool',
default=True,
desc='Run podman/docker with `--init`'
),
Option(
'prometheus_alerts_path',
type='str',
default='/etc/prometheus/ceph/ceph_default_alerts.yml',
desc='location of alerts to include in prometheus deployments',
),
Option(
'migration_current',
type='int',
default=None,
desc='internal - do not modify',
# used to track track spec and other data migrations.
),
Option(
'config_dashboard',
type='bool',
default=True,
desc='manage configs like API endpoints in Dashboard.'
),
Option(
'manage_etc_ceph_ceph_conf',
type='bool',
default=False,
desc='Manage and own /etc/ceph/ceph.conf on the hosts.',
),
Option(
'manage_etc_ceph_ceph_conf_hosts',
type='str',
default='*',
desc='PlacementSpec describing on which hosts to manage /etc/ceph/ceph.conf',
),
Option(
'registry_url',
type='str',
default=None,
desc='Custom repository url'
),
Option(
'registry_username',
type='str',
default=None,
desc='Custom repository username'
),
Option(
'registry_password',
type='str',
default=None,
desc='Custom repository password'
),
Option(
'use_repo_digest',
type='bool',
default=True,
desc='Automatically convert image tags to image digest. Make sure all daemons use the same image',
),
Option(
'config_checks_enabled',
type='bool',
default=False,
desc='Enable or disable the cephadm configuration analysis',
),
Option(
'default_registry',
type='str',
default='docker.io',
desc='Registry to which we should normalize unqualified image names',
),
Option(
'max_count_per_host',
type='int',
default=10,
desc='max number of daemons per service per host',
),
]
def __init__(self, *args: Any, **kwargs: Any):
super(CephadmOrchestrator, self).__init__(*args, **kwargs)
self._cluster_fsid: str = self.get('mon_map')['fsid']
self.last_monmap: Optional[datetime.datetime] = None
# 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.facts_cache_timeout = 0
self.host_check_interval = 0
self.max_count_per_host = 0
self.mode = ''
self.container_image_base = ''
self.container_image_prometheus = ''
self.container_image_grafana = ''
self.container_image_alertmanager = ''
self.container_image_node_exporter = ''
self.container_image_haproxy = ''
self.container_image_keepalived = ''
self.warn_on_stray_hosts = True
self.warn_on_stray_daemons = True
self.warn_on_failed_host_check = True
self.allow_ptrace = False
self.container_init = True
self.prometheus_alerts_path = ''
self.migration_current: Optional[int] = None
self.config_dashboard = True
self.manage_etc_ceph_ceph_conf = True
self.manage_etc_ceph_ceph_conf_hosts = '*'
self.registry_url: Optional[str] = None
self.registry_username: Optional[str] = None
self.registry_password: Optional[str] = None
self.use_repo_digest = True
self.default_registry = ''
self._cons: Dict[str, Tuple[remoto.backends.BaseConnection,
remoto.backends.LegacyModuleExecute]] = {}
self.notify('mon_map', None)
self.config_notify()
path = self.get_ceph_option('cephadm_path')
try:
assert isinstance(path, str)
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.cephadm_binary_path = self._get_cephadm_binary_path()
self._worker_pool = multiprocessing.pool.ThreadPool(10)
self._reconfig_ssh()
CephadmOrchestrator.instance = self
self.upgrade = CephadmUpgrade(self)
self.health_checks: Dict[str, dict] = {}
self.inventory = Inventory(self)
self.cache = HostCache(self)
self.cache.load()
self.to_remove_osds = OSDRemovalQueue(self)
self.to_remove_osds.load_from_store()
self.spec_store = SpecStore(self)
self.spec_store.load()
self.keys = ClientKeyringStore(self)
self.keys.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)
# in-memory only.
self.events = EventStore(self)
self.offline_hosts: Set[str] = set()
self.migration = Migrations(self)
_service_clses: Sequence[Type[CephadmService]] = [
OSDService, NFSService, MonService, MgrService, MdsService,
RgwService, RbdMirrorService, GrafanaService, AlertmanagerService,
PrometheusService, NodeExporterService, CrashService, IscsiService,
IngressService, CustomContainerService, CephadmExporter, CephfsMirrorService
]
# https://github.com/python/mypy/issues/8993
self.cephadm_services: Dict[str, CephadmService] = {
cls.TYPE: cls(self) for cls in _service_clses} # type: ignore
self.mgr_service: MgrService = cast(MgrService, self.cephadm_services['mgr'])
self.osd_service: OSDService = cast(OSDService, self.cephadm_services['osd'])
self.template = TemplateMgr(self)
self.requires_post_actions: Set[str] = set()
self.config_checker = CephadmConfigChecks(self)
def shutdown(self) -> None:
self.log.debug('shutdown')
self._worker_pool.close()
self._worker_pool.join()
self.run = False
self.event.set()
def _get_cephadm_service(self, service_type: str) -> CephadmService:
assert service_type in ServiceSpec.KNOWN_SERVICE_TYPES
return self.cephadm_services[service_type]
def _get_cephadm_binary_path(self) -> str:
import hashlib
m = hashlib.sha256()
m.update(self._cephadm.encode())
return f'/var/lib/ceph/{self._cluster_fsid}/cephadm.{m.hexdigest()}'
def _kick_serve_loop(self) -> None:
self.log.debug('_kick_serve_loop')
self.event.set()
def serve(self) -> None:
"""
The main loop of cephadm.
A command handler will typically change the declarative state
of cephadm. This loop will then attempt to apply this new state.
"""
serve = CephadmServe(self)
serve.serve()
def set_container_image(self, entity: str, image: str) -> None:
self.check_mon_command({
'prefix': 'config set',
'name': 'container_image',
'value': image,
'who': entity,
})
def config_notify(self) -> None:
"""
This method is called whenever one of our config options is changed.
TODO: this method should be moved into mgr_module.py
"""
for opt in self.MODULE_OPTIONS:
setattr(self,
opt['name'], # type: ignore
self.get_module_option(opt['name'])) # type: ignore
self.log.debug(' mgr option %s = %s',
opt['name'], getattr(self, opt['name'])) # type: ignore
for opt in self.NATIVE_OPTIONS:
setattr(self,
opt, # type: ignore
self.get_ceph_option(opt))
self.log.debug(' native option %s = %s', opt, getattr(self, opt)) # type: ignore
self.event.set()
def notify(self, notify_type: str, notify_id: Optional[str]) -> None:
if notify_type == "mon_map":
# get monmap mtime so we can refresh configs when mons change
monmap = self.get('mon_map')
self.last_monmap = str_to_datetime(monmap['modified'])
if self.last_monmap and self.last_monmap > datetime_now():
self.last_monmap = None # just in case clocks are skewed
if getattr(self, 'manage_etc_ceph_ceph_conf', False):
# getattr, due to notify() being called before config_notify()
self._kick_serve_loop()
if notify_type == "pg_summary":
self._trigger_osd_removal()
def _trigger_osd_removal(self) -> None:
data = self.get("osd_stats")
for osd in data.get('osd_stats', []):
if osd.get('num_pgs') == 0:
# if _ANY_ osd that is currently in the queue appears to be empty,
# start the removal process
if int(osd.get('osd')) in self.to_remove_osds.as_osd_ids():
self.log.debug('Found empty osd. Starting removal process')
# if the osd that is now empty is also part of the removal queue
# start the process
self._kick_serve_loop()
def pause(self) -> None:
if not self.paused:
self.log.info('Paused')
self.set_store('pause', 'true')
self.paused = True
# wake loop so we update the health status
self._kick_serve_loop()
def resume(self) -> None:
if self.paused:
self.log.info('Resumed')
self.paused = False
self.set_store('pause', None)
# unconditionally wake loop so that 'orch resume' can be used to kick
# cephadm
self._kick_serve_loop()
def get_unique_name(self, daemon_type, host, existing, prefix=None,
forcename=None):
# type: (str, str, List[orchestrator.DaemonDescription], Optional[str], Optional[str]) -> str
"""
Generate a unique random service name
"""
suffix = daemon_type not in [
'mon', 'crash', 'nfs',
'prometheus', 'node-exporter', 'grafana', 'alertmanager',
'container', 'cephadm-exporter',
]
if forcename:
if len([d for d in existing if d.daemon_id == forcename]):
raise orchestrator.OrchestratorValidationError(
f'name {daemon_type}.{forcename} already in use')
return forcename
if '.' in host:
host = host.split('.')[0]
while True:
if prefix:
name = prefix + '.'
else:
name = ''
name += host
if suffix:
name += '.' + ''.join(random.choice(string.ascii_lowercase)
for _ in range(6))
if len([d for d in existing if d.daemon_id == name]):
if not suffix:
raise orchestrator.OrchestratorValidationError(
f'name {daemon_type}.{name} already in use')
self.log.debug('name %s exists, trying again', name)
continue
return name
def _reconfig_ssh(self) -> None:
temp_files = [] # type: list
ssh_options = [] # type: List[str]
# ssh_config
ssh_config_fname = self.ssh_config_file
ssh_config = self.get_store("ssh_config")
if ssh_config is not None or ssh_config_fname is None:
if not ssh_config:
ssh_config = DEFAULT_SSH_CONFIG
f = tempfile.NamedTemporaryFile(prefix='cephadm-conf-')
os.fchmod(f.fileno(), 0o600)
f.write(ssh_config.encode('utf-8'))
f.flush() # make visible to other processes
temp_files += [f]
ssh_config_fname = f.name
if ssh_config_fname:
self.validate_ssh_config_fname(ssh_config_fname)
ssh_options += ['-F', ssh_config_fname]
self.ssh_config = ssh_config
# identity
ssh_key = self.get_store("ssh_identity_key")
ssh_pub = self.get_store("ssh_identity_pub")
self.ssh_pub = ssh_pub
self.ssh_key = ssh_key
if ssh_key and ssh_pub:
tkey = tempfile.NamedTemporaryFile(prefix='cephadm-identity-')
tkey.write(ssh_key.encode('utf-8'))
os.fchmod(tkey.fileno(), 0o600)
tkey.flush() # make visible to other processes
tpub = open(tkey.name + '.pub', 'w')
os.fchmod(tpub.fileno(), 0o600)
tpub.write(ssh_pub)
tpub.flush() # make visible to other processes
temp_files += [tkey, tpub]
ssh_options += ['-i', tkey.name]
self._temp_files = temp_files
if ssh_options:
self._ssh_options = ' '.join(ssh_options) # type: Optional[str]
else:
self._ssh_options = None
if self.mode == 'root':
self.ssh_user = self.get_store('ssh_user', default='root')
elif self.mode == 'cephadm-package':
self.ssh_user = 'cephadm'
self._reset_cons()
def validate_ssh_config_content(self, ssh_config: Optional[str]) -> None:
if ssh_config is None or len(ssh_config.strip()) == 0:
raise OrchestratorValidationError('ssh_config cannot be empty')
# StrictHostKeyChecking is [yes|no] ?
res = re.findall(r'StrictHostKeyChecking\s+.*', ssh_config)
if not res:
raise OrchestratorValidationError('ssh_config requires StrictHostKeyChecking')
for s in res:
if 'ask' in s.lower():
raise OrchestratorValidationError(f'ssh_config cannot contain: \'{s}\'')
def validate_ssh_config_fname(self, ssh_config_fname: str) -> None:
if not os.path.isfile(ssh_config_fname):
raise OrchestratorValidationError("ssh_config \"{}\" does not exist".format(
ssh_config_fname))
def _reset_con(self, host: str) -> None:
conn, r = self._cons.get(host, (None, None))
if conn:
self.log.debug('_reset_con close %s' % host)
conn.exit()
del self._cons[host]
def _reset_cons(self) -> None:
for host, conn_and_r in self._cons.items():
self.log.debug('_reset_cons close %s' % host)
conn, r = conn_and_r
conn.exit()
self._cons = {}
def offline_hosts_remove(self, host: str) -> None:
if host in self.offline_hosts:
self.offline_hosts.remove(host)
@staticmethod
def can_run() -> Tuple[bool, str]:
if remoto is not None:
return True, ""
else:
return False, "loading remoto library:{}".format(
remoto_import_error)
def available(self) -> Tuple[bool, str, Dict[str, Any]]:
"""
The cephadm orchestrator is always available.
"""
ok, err = self.can_run()
if not ok:
return ok, err, {}
if not self.ssh_key or not self.ssh_pub:
return False, 'SSH keys not set. Use `ceph cephadm set-priv-key` and `ceph cephadm set-pub-key` or `ceph cephadm generate-key`', {}
# mypy is unable to determine type for _processes since it's private
worker_count: int = self._worker_pool._processes # type: ignore
ret = {
"workers": worker_count,
"paused": self.paused,
}
return True, err, ret
@orchestrator._cli_write_command(
prefix='cephadm set-ssh-config')
def _set_ssh_config(self, inbuf: Optional[str] = None) -> Tuple[int, str, str]:
"""
Set the ssh_config file (use -i <ssh_config>)
"""
# Set an ssh_config file provided from stdin
if inbuf == self.ssh_config:
return 0, "value unchanged", ""
self.validate_ssh_config_content(inbuf)
self.set_store("ssh_config", inbuf)
self.log.info('Set ssh_config')
self._reconfig_ssh()
return 0, "", ""
@orchestrator._cli_write_command('cephadm clear-ssh-config')
def _clear_ssh_config(self) -> Tuple[int, str, str]:
"""
Clear the ssh_config file
"""
# Clear the ssh_config file provided from stdin
self.set_store("ssh_config", None)
self.ssh_config_tmp = None
self.log.info('Cleared ssh_config')
self._reconfig_ssh()
return 0, "", ""
@orchestrator._cli_read_command('cephadm get-ssh-config')
def _get_ssh_config(self) -> HandleCommandResult:
"""
Returns the ssh config as used by cephadm
"""
if self.ssh_config_file:
self.validate_ssh_config_fname(self.ssh_config_file)
with open(self.ssh_config_file) as f:
return HandleCommandResult(stdout=f.read())
ssh_config = self.get_store("ssh_config")
if ssh_config:
return HandleCommandResult(stdout=ssh_config)
return HandleCommandResult(stdout=DEFAULT_SSH_CONFIG)
@orchestrator._cli_write_command('cephadm generate-key')
def _generate_key(self) -> Tuple[int, str, str]:
"""
Generate a cluster SSH key (if not present)
"""
if not self.ssh_pub or not self.ssh_key:
self.log.info('Generating ssh key...')
tmp_dir = TemporaryDirectory()
path = tmp_dir.name + '/key'
try:
subprocess.check_call([
'/usr/bin/ssh-keygen',
'-C', 'ceph-%s' % self._cluster_fsid,
'-N', '',
'-f', path
])
with open(path, 'r') as f:
secret = f.read()
with open(path + '.pub', 'r') as f:
pub = f.read()
finally:
os.unlink(path)
os.unlink(path + '.pub')
tmp_dir.cleanup()
self.set_store('ssh_identity_key', secret)
self.set_store('ssh_identity_pub', pub)
self._reconfig_ssh()
return 0, '', ''
@orchestrator._cli_write_command(
'cephadm set-priv-key')
def _set_priv_key(self, inbuf: Optional[str] = None) -> Tuple[int, str, str]:
"""Set cluster SSH private key (use -i <private_key>)"""
if inbuf is None or len(inbuf) == 0:
return -errno.EINVAL, "", "empty private ssh key provided"
if inbuf == self.ssh_key:
return 0, "value unchanged", ""
self.set_store("ssh_identity_key", inbuf)
self.log.info('Set ssh private key')
self._reconfig_ssh()
return 0, "", ""
@orchestrator._cli_write_command(
'cephadm set-pub-key')
def _set_pub_key(self, inbuf: Optional[str] = None) -> Tuple[int, str, str]:
"""Set cluster SSH public key (use -i <public_key>)"""
if inbuf is None or len(inbuf) == 0:
return -errno.EINVAL, "", "empty public ssh key provided"
if inbuf == self.ssh_pub:
return 0, "value unchanged", ""
self.set_store("ssh_identity_pub", inbuf)
self.log.info('Set ssh public key')
self._reconfig_ssh()
return 0, "", ""
@orchestrator._cli_write_command(
'cephadm clear-key')
def _clear_key(self) -> Tuple[int, str, str]:
"""Clear cluster SSH key"""
self.set_store('ssh_identity_key', None)
self.set_store('ssh_identity_pub', None)
self._reconfig_ssh()
self.log.info('Cleared cluster SSH key')
return 0, '', ''
@orchestrator._cli_read_command(
'cephadm get-pub-key')
def _get_pub_key(self) -> Tuple[int, str, str]:
"""Show SSH public key for connecting to cluster hosts"""
if self.ssh_pub:
return 0, self.ssh_pub, ''
else:
return -errno.ENOENT, '', 'No cluster SSH key defined'
@orchestrator._cli_read_command(
'cephadm get-user')
def _get_user(self) -> Tuple[int, str, str]:
"""
Show user for SSHing to cluster hosts
"""
if self.ssh_user is None:
return -errno.ENOENT, '', 'No cluster SSH user configured'
else:
return 0, self.ssh_user, ''
@orchestrator._cli_read_command(
'cephadm set-user')
def set_ssh_user(self, user: str) -> Tuple[int, str, str]:
"""
Set user for SSHing to cluster hosts, passwordless sudo will be needed for non-root users
"""
current_user = self.ssh_user
if user == current_user:
return 0, "value unchanged", ""
self.set_store('ssh_user', user)
self._reconfig_ssh()
host = self.cache.get_hosts()[0]
r = CephadmServe(self)._check_host(host)
if r is not None:
# connection failed reset user
self.set_store('ssh_user', current_user)
self._reconfig_ssh()
return -errno.EINVAL, '', 'ssh connection %s@%s failed' % (user, host)
msg = 'ssh user set to %s' % user
if user != 'root':
msg += ' sudo will be used'
self.log.info(msg)
return 0, msg, ''
@orchestrator._cli_read_command(
'cephadm registry-login')
def registry_login(self, url: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, inbuf: Optional[str] = None) -> Tuple[int, str, str]:
"""
Set custom registry login info by providing url, username and password or json file with login info (-i <file>)
"""
# if password not given in command line, get it through file input
if not (url and username and password) and (inbuf is None or len(inbuf) == 0):
return -errno.EINVAL, "", ("Invalid arguments. Please provide arguments <url> <username> <password> "
"or -i <login credentials json file>")
elif not (url and username and password):
assert isinstance(inbuf, str)
login_info = json.loads(inbuf)
if "url" in login_info and "username" in login_info and "password" in login_info:
url = login_info["url"]
username = login_info["username"]
password = login_info["password"]
else:
return -errno.EINVAL, "", ("json provided for custom registry login did not include all necessary fields. "
"Please setup json file as\n"
"{\n"
" \"url\": \"REGISTRY_URL\",\n"
" \"username\": \"REGISTRY_USERNAME\",\n"
" \"password\": \"REGISTRY_PASSWORD\"\n"
"}\n")
# verify login info works by attempting login on random host
host = None
for host_name in self.inventory.keys():
host = host_name
break
if not host:
raise OrchestratorError('no hosts defined')
r = CephadmServe(self)._registry_login(host, url, username, password)
if r is not None:
return 1, '', r
# if logins succeeded, store info
self.log.debug("Host logins successful. Storing login info.")
self.set_module_option('registry_url', url)
self.set_module_option('registry_username', username)
self.set_module_option('registry_password', password)
# distribute new login info to all hosts
self.cache.distribute_new_registry_login_info()
return 0, "registry login scheduled", ''
@orchestrator._cli_read_command('cephadm check-host')
def check_host(self, host: str, addr: Optional[str] = None) -> Tuple[int, str, str]:
"""Check whether we can access and manage a remote host"""
try:
out, err, code = CephadmServe(self)._run_cephadm(host, cephadmNoImage, 'check-host',
['--expect-hostname', host],
addr=addr,
error_ok=True, no_fsid=True)
if code:
return 1, '', ('check-host failed:\n' + '\n'.join(err))
except OrchestratorError:
self.log.exception(f"check-host failed for '{host}'")
return 1, '', ('check-host failed:\n'
+ f"Host '{host}' not found. Use 'ceph orch host ls' to see all managed hosts.")
# if we have an outstanding health alert for this host, give the
# serve thread a kick
if 'CEPHADM_HOST_CHECK_FAILED' in self.health_checks:
for item in self.health_checks['CEPHADM_HOST_CHECK_FAILED']['detail']:
if item.startswith('host %s ' % host):
self.event.set()
return 0, '%s (%s) ok' % (host, addr), '\n'.join(err)
@orchestrator._cli_read_command(
'cephadm prepare-host')
def _prepare_host(self, host: str, addr: Optional[str] = None) -> Tuple[int, str, str]:
"""Prepare a remote host for use with cephadm"""
out, err, code = CephadmServe(self)._run_cephadm(host, cephadmNoImage, 'prepare-host',
['--expect-hostname', host],
addr=addr,
error_ok=True, no_fsid=True)
if code:
return 1, '', ('prepare-host failed:\n' + '\n'.join(err))
# if we have an outstanding health alert for this host, give the
# serve thread a kick
if 'CEPHADM_HOST_CHECK_FAILED' in self.health_checks:
for item in self.health_checks['CEPHADM_HOST_CHECK_FAILED']['detail']:
if item.startswith('host %s ' % host):
self.event.set()
return 0, '%s (%s) ok' % (host, addr), '\n'.join(err)
@orchestrator._cli_write_command(
prefix='cephadm set-extra-ceph-conf')
def _set_extra_ceph_conf(self, inbuf: Optional[str] = None) -> HandleCommandResult:
"""
Text that is appended to all daemon's ceph.conf.
Mainly a workaround, till `config generate-minimal-conf` generates
a complete ceph.conf.
Warning: this is a dangerous operation.
"""
if inbuf:
# sanity check.
cp = ConfigParser()
cp.read_string(inbuf, source='<infile>')
self.set_store("extra_ceph_conf", json.dumps({
'conf': inbuf,
'last_modified': datetime_to_str(datetime_now())
}))
self.log.info('Set extra_ceph_conf')
self._kick_serve_loop()
return HandleCommandResult()
@orchestrator._cli_read_command(
'cephadm get-extra-ceph-conf')
def _get_extra_ceph_conf(self) -> HandleCommandResult:
"""
Get extra ceph conf that is appended
"""
return HandleCommandResult(stdout=self.extra_ceph_conf().conf)
def _set_exporter_config(self, config: Dict[str, str]) -> None:
self.set_store('exporter_config', json.dumps(config))
def _get_exporter_config(self) -> Dict[str, str]:
cfg_str = self.get_store('exporter_config')
return json.loads(cfg_str) if cfg_str else {}
def _set_exporter_option(self, option: str, value: Optional[str] = None) -> None:
kv_option = f'exporter_{option}'
self.set_store(kv_option, value)
def _get_exporter_option(self, option: str) -> Optional[str]:
kv_option = f'exporter_{option}'
return self.get_store(kv_option)
@orchestrator._cli_write_command(
prefix='cephadm generate-exporter-config')
@service_inactive('cephadm-exporter')
def _generate_exporter_config(self) -> Tuple[int, str, str]:
"""
Generate default SSL crt/key and token for cephadm exporter daemons
"""
self._set_exporter_defaults()
self.log.info('Default settings created for cephadm exporter(s)')
return 0, "", ""