-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcephadm
executable file
·7924 lines (6746 loc) · 282 KB
/
cephadm
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/python3
import asyncio
import asyncio.subprocess
import argparse
import datetime
import fcntl
import ipaddress
import json
import logging
from logging.config import dictConfig
import os
import platform
import pwd
import random
import shlex
import shutil
import socket
import string
import subprocess
import sys
import tempfile
import time
import errno
import struct
from socketserver import ThreadingMixIn
from http.server import BaseHTTPRequestHandler, HTTPServer
import signal
import io
from contextlib import redirect_stdout
import ssl
from enum import Enum
from typing import Dict, List, Tuple, Optional, Union, Any, NoReturn, Callable, IO
import re
import uuid
from configparser import ConfigParser
from functools import wraps
from glob import glob
from io import StringIO
from threading import Thread, RLock
from urllib.error import HTTPError
from urllib.request import urlopen
# Default container images -----------------------------------------------------
DEFAULT_IMAGE = 'quay.ceph.io/ceph-ci/ceph:master'
DEFAULT_IMAGE_IS_MASTER = True
DEFAULT_IMAGE_RELEASE = 'quincy'
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'
# ------------------------------------------------------------------------------
LATEST_STABLE_RELEASE = 'pacific'
DATA_DIR = '/var/lib/ceph'
LOG_DIR = '/var/log/ceph'
LOCK_DIR = '/run/cephadm'
LOGROTATE_DIR = '/etc/logrotate.d'
UNIT_DIR = '/etc/systemd/system'
LOG_DIR_MODE = 0o770
DATA_DIR_MODE = 0o700
CONTAINER_INIT = True
CONTAINER_PREFERENCE = ['podman', 'docker'] # prefer podman to docker
MIN_PODMAN_VERSION = (2, 0, 2)
CUSTOM_PS1 = r'[ceph: \u@\h \W]\$ '
DEFAULT_TIMEOUT = None # in seconds
DEFAULT_RETRY = 15
SHELL_DEFAULT_CONF = '/etc/ceph/ceph.conf'
SHELL_DEFAULT_KEYRING = '/etc/ceph/ceph.client.admin.keyring'
DATEFMT = '%Y-%m-%dT%H:%M:%S.%fZ'
logger: logging.Logger = None # type: ignore
"""
You can invoke cephadm in two ways:
1. The normal way, at the command line.
2. By piping the script to the python3 binary. In this latter case, you should
prepend one or more lines to the beginning of the script.
For arguments,
injected_argv = [...]
e.g.,
injected_argv = ['ls']
For reading stdin from the '--config-json -' argument,
injected_stdin = '...'
"""
cached_stdin = None
##################################
class BaseConfig:
def __init__(self):
self.image: str = ''
self.docker: bool = False
self.data_dir: str = DATA_DIR
self.log_dir: str = LOG_DIR
self.logrotate_dir: str = LOGROTATE_DIR
self.unit_dir: str = UNIT_DIR
self.verbose: bool = False
self.timeout: Optional[int] = DEFAULT_TIMEOUT
self.retry: int = DEFAULT_RETRY
self.env: List[str] = []
self.memory_request: Optional[int] = None
self.memory_limit: Optional[int] = None
self.container_init: bool = CONTAINER_INIT
self.container_path: str = ''
def set_from_args(self, args: argparse.Namespace):
argdict: Dict[str, Any] = vars(args)
for k, v in argdict.items():
if hasattr(self, k):
setattr(self, k, v)
class CephadmContext:
def __init__(self):
self.__dict__['_args'] = None
self.__dict__['_conf'] = BaseConfig()
def set_args(self, args: argparse.Namespace) -> None:
self._conf.set_from_args(args)
self._args = args
def has_function(self) -> bool:
return 'func' in self._args
def __contains__(self, name: str) -> bool:
return hasattr(self, name)
def __getattr__(self, name: str) -> Any:
if '_conf' in self.__dict__ and hasattr(self._conf, name):
return getattr(self._conf, name)
elif '_args' in self.__dict__ and hasattr(self._args, name):
return getattr(self._args, name)
else:
return super().__getattribute__(name)
def __setattr__(self, name: str, value: Any) -> None:
if hasattr(self._conf, name):
setattr(self._conf, name, value)
elif hasattr(self._args, name):
setattr(self._args, name, value)
else:
super().__setattr__(name, value)
# Log and console output config
logging_config = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'cephadm': {
'format': '%(asctime)s %(levelname)s %(message)s'
},
},
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
},
'log_file': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'cephadm',
'filename': '%s/cephadm.log' % LOG_DIR,
'maxBytes': 1024000,
'backupCount': 1,
}
},
'loggers': {
'': {
'level': 'DEBUG',
'handlers': ['console', 'log_file'],
}
}
}
class termcolor:
yellow = '\033[93m'
red = '\033[31m'
end = '\033[0m'
class Error(Exception):
pass
class TimeoutExpired(Error):
pass
##################################
class Ceph(object):
daemons = ('mon', 'mgr', 'mds', 'osd', 'rgw', 'rbd-mirror',
'crash', 'cephfs-mirror')
##################################
class Monitoring(object):
"""Define the configs for the monitoring containers"""
port_map = {
'prometheus': [9095], # Avoid default 9090, due to conflict with cockpit UI
'node-exporter': [9100],
'grafana': [3000],
'alertmanager': [9093, 9094],
}
components = {
'prometheus': {
'image': DEFAULT_PROMETHEUS_IMAGE,
'cpus': '2',
'memory': '4GB',
'args': [
'--config.file=/etc/prometheus/prometheus.yml',
'--storage.tsdb.path=/prometheus',
'--web.listen-address=:{}'.format(port_map['prometheus'][0]),
],
'config-json-files': [
'prometheus.yml',
],
},
'node-exporter': {
'image': DEFAULT_NODE_EXPORTER_IMAGE,
'cpus': '1',
'memory': '1GB',
'args': [
'--no-collector.timex',
],
},
'grafana': {
'image': DEFAULT_GRAFANA_IMAGE,
'cpus': '2',
'memory': '4GB',
'args': [],
'config-json-files': [
'grafana.ini',
'provisioning/datasources/ceph-dashboard.yml',
'certs/cert_file',
'certs/cert_key',
],
},
'alertmanager': {
'image': DEFAULT_ALERT_MANAGER_IMAGE,
'cpus': '2',
'memory': '2GB',
'args': [
'--web.listen-address=:{}'.format(port_map['alertmanager'][0]),
'--cluster.listen-address=:{}'.format(port_map['alertmanager'][1]),
],
'config-json-files': [
'alertmanager.yml',
],
'config-json-args': [
'peers',
],
},
} # type: ignore
@staticmethod
def get_version(ctx, container_id, daemon_type):
# type: (CephadmContext, str, str) -> str
"""
:param: daemon_type Either "prometheus", "alertmanager" or "node-exporter"
"""
assert daemon_type in ('prometheus', 'alertmanager', 'node-exporter')
cmd = daemon_type.replace('-', '_')
code = -1
err = ''
version = ''
if daemon_type == 'alertmanager':
for cmd in ['alertmanager', 'prometheus-alertmanager']:
_, err, code = call(ctx, [
ctx.container_path, 'exec', container_id, cmd,
'--version'
], verbosity=CallVerbosity.DEBUG)
if code == 0:
break
cmd = 'alertmanager' # reset cmd for version extraction
else:
_, err, code = call(ctx, [
ctx.container_path, 'exec', container_id, cmd, '--version'
], verbosity=CallVerbosity.DEBUG)
if code == 0 and \
err.startswith('%s, version ' % cmd):
version = err.split(' ')[2]
return version
##################################
def populate_files(config_dir, config_files, uid, gid):
# type: (str, Dict, int, int) -> None
"""create config files for different services"""
for fname in config_files:
config_file = os.path.join(config_dir, fname)
config_content = dict_get_join(config_files, fname)
logger.info('Write file: %s' % (config_file))
with open(config_file, 'w') as f:
os.fchown(f.fileno(), uid, gid)
os.fchmod(f.fileno(), 0o600)
f.write(config_content)
class NFSGanesha(object):
"""Defines a NFS-Ganesha container"""
daemon_type = 'nfs'
entrypoint = '/usr/bin/ganesha.nfsd'
daemon_args = ['-F', '-L', 'STDERR']
required_files = ['ganesha.conf']
port_map = {
'nfs': 2049,
}
def __init__(self,
ctx,
fsid,
daemon_id,
config_json,
image=DEFAULT_IMAGE):
# type: (CephadmContext, str, Union[int, str], Dict, str) -> None
self.ctx = ctx
self.fsid = fsid
self.daemon_id = daemon_id
self.image = image
# config-json options
self.pool = dict_get(config_json, 'pool', require=True)
self.namespace = dict_get(config_json, 'namespace')
self.userid = dict_get(config_json, 'userid')
self.extra_args = dict_get(config_json, 'extra_args', [])
self.files = dict_get(config_json, 'files', {})
self.rgw = dict_get(config_json, 'rgw', {})
# validate the supplied args
self.validate()
@classmethod
def init(cls, ctx, fsid, daemon_id):
# type: (CephadmContext, str, Union[int, str]) -> NFSGanesha
return cls(ctx, fsid, daemon_id, get_parm(ctx.config_json), ctx.image)
def get_container_mounts(self, data_dir):
# type: (str) -> Dict[str, str]
mounts = dict()
mounts[os.path.join(data_dir, 'config')] = '/etc/ceph/ceph.conf:z'
mounts[os.path.join(data_dir, 'keyring')] = '/etc/ceph/keyring:z'
mounts[os.path.join(data_dir, 'etc/ganesha')] = '/etc/ganesha:z'
if self.rgw:
cluster = self.rgw.get('cluster', 'ceph')
rgw_user = self.rgw.get('user', 'admin')
mounts[os.path.join(data_dir, 'keyring.rgw')] = \
'/var/lib/ceph/radosgw/%s-%s/keyring:z' % (cluster, rgw_user)
return mounts
@staticmethod
def get_container_envs():
# type: () -> List[str]
envs = [
'CEPH_CONF=%s' % ('/etc/ceph/ceph.conf')
]
return envs
@staticmethod
def get_version(ctx, container_id):
# type: (CephadmContext, str) -> Optional[str]
version = None
out, err, code = call(ctx,
[ctx.container_path, 'exec', container_id,
NFSGanesha.entrypoint, '-v'],
verbosity=CallVerbosity.DEBUG)
if code == 0:
match = re.search(r'NFS-Ganesha Release\s*=\s*[V]*([\d.]+)', out)
if match:
version = match.group(1)
return version
def validate(self):
# type: () -> None
if not is_fsid(self.fsid):
raise Error('not an fsid: %s' % self.fsid)
if not self.daemon_id:
raise Error('invalid daemon_id: %s' % self.daemon_id)
if not self.image:
raise Error('invalid image: %s' % self.image)
# check for the required files
if self.required_files:
for fname in self.required_files:
if fname not in self.files:
raise Error('required file missing from config-json: %s' % fname)
# check for an RGW config
if self.rgw:
if not self.rgw.get('keyring'):
raise Error('RGW keyring is missing')
if not self.rgw.get('user'):
raise Error('RGW user is missing')
def get_daemon_name(self):
# type: () -> str
return '%s.%s' % (self.daemon_type, self.daemon_id)
def get_container_name(self, desc=None):
# type: (Optional[str]) -> str
cname = 'ceph-%s-%s' % (self.fsid, self.get_daemon_name())
if desc:
cname = '%s-%s' % (cname, desc)
return cname
def get_daemon_args(self):
# type: () -> List[str]
return self.daemon_args + self.extra_args
def create_daemon_dirs(self, data_dir, uid, gid):
# type: (str, int, int) -> None
"""Create files under the container data dir"""
if not os.path.isdir(data_dir):
raise OSError('data_dir is not a directory: %s' % (data_dir))
logger.info('Creating ganesha config...')
# create the ganesha conf dir
config_dir = os.path.join(data_dir, 'etc/ganesha')
makedirs(config_dir, uid, gid, 0o755)
# populate files from the config-json
populate_files(config_dir, self.files, uid, gid)
# write the RGW keyring
if self.rgw:
keyring_path = os.path.join(data_dir, 'keyring.rgw')
with open(keyring_path, 'w') as f:
os.fchmod(f.fileno(), 0o600)
os.fchown(f.fileno(), uid, gid)
f.write(self.rgw.get('keyring', ''))
def get_rados_grace_container(self, action):
# type: (str) -> CephContainer
"""Container for a ganesha action on the grace db"""
entrypoint = '/usr/bin/ganesha-rados-grace'
assert self.pool
args = ['--pool', self.pool]
if self.namespace:
args += ['--ns', self.namespace]
if self.userid:
args += ['--userid', self.userid]
args += [action, self.get_daemon_name()]
data_dir = get_data_dir(self.fsid, self.ctx.data_dir,
self.daemon_type, self.daemon_id)
volume_mounts = self.get_container_mounts(data_dir)
envs = self.get_container_envs()
logger.info('Creating RADOS grace for action: %s' % action)
c = CephContainer(
self.ctx,
image=self.image,
entrypoint=entrypoint,
args=args,
volume_mounts=volume_mounts,
cname=self.get_container_name(desc='grace-%s' % action),
envs=envs
)
return c
##################################
class CephIscsi(object):
"""Defines a Ceph-Iscsi container"""
daemon_type = 'iscsi'
entrypoint = '/usr/bin/rbd-target-api'
required_files = ['iscsi-gateway.cfg']
def __init__(self,
ctx,
fsid,
daemon_id,
config_json,
image=DEFAULT_IMAGE):
# type: (CephadmContext, str, Union[int, str], Dict, str) -> None
self.ctx = ctx
self.fsid = fsid
self.daemon_id = daemon_id
self.image = image
# config-json options
self.files = dict_get(config_json, 'files', {})
# validate the supplied args
self.validate()
@classmethod
def init(cls, ctx, fsid, daemon_id):
# type: (CephadmContext, str, Union[int, str]) -> CephIscsi
return cls(ctx, fsid, daemon_id,
get_parm(ctx.config_json), ctx.image)
@staticmethod
def get_container_mounts(data_dir, log_dir):
# type: (str, str) -> Dict[str, str]
mounts = dict()
mounts[os.path.join(data_dir, 'config')] = '/etc/ceph/ceph.conf:z'
mounts[os.path.join(data_dir, 'keyring')] = '/etc/ceph/keyring:z'
mounts[os.path.join(data_dir, 'iscsi-gateway.cfg')] = '/etc/ceph/iscsi-gateway.cfg:z'
mounts[os.path.join(data_dir, 'configfs')] = '/sys/kernel/config'
mounts[log_dir] = '/var/log/rbd-target-api:z'
mounts['/dev'] = '/dev'
return mounts
@staticmethod
def get_container_binds():
# type: () -> List[List[str]]
binds = []
lib_modules = ['type=bind',
'source=/lib/modules',
'destination=/lib/modules',
'ro=true']
binds.append(lib_modules)
return binds
@staticmethod
def get_version(ctx, container_id):
# type: (CephadmContext, str) -> Optional[str]
version = None
out, err, code = call(ctx,
[ctx.container_path, 'exec', container_id,
'/usr/bin/python3', '-c', "import pkg_resources; print(pkg_resources.require('ceph_iscsi')[0].version)"],
verbosity=CallVerbosity.DEBUG)
if code == 0:
version = out.strip()
return version
def validate(self):
# type: () -> None
if not is_fsid(self.fsid):
raise Error('not an fsid: %s' % self.fsid)
if not self.daemon_id:
raise Error('invalid daemon_id: %s' % self.daemon_id)
if not self.image:
raise Error('invalid image: %s' % self.image)
# check for the required files
if self.required_files:
for fname in self.required_files:
if fname not in self.files:
raise Error('required file missing from config-json: %s' % fname)
def get_daemon_name(self):
# type: () -> str
return '%s.%s' % (self.daemon_type, self.daemon_id)
def get_container_name(self, desc=None):
# type: (Optional[str]) -> str
cname = 'ceph-%s-%s' % (self.fsid, self.get_daemon_name())
if desc:
cname = '%s-%s' % (cname, desc)
return cname
def create_daemon_dirs(self, data_dir, uid, gid):
# type: (str, int, int) -> None
"""Create files under the container data dir"""
if not os.path.isdir(data_dir):
raise OSError('data_dir is not a directory: %s' % (data_dir))
logger.info('Creating ceph-iscsi config...')
configfs_dir = os.path.join(data_dir, 'configfs')
makedirs(configfs_dir, uid, gid, 0o755)
# populate files from the config-json
populate_files(data_dir, self.files, uid, gid)
@staticmethod
def configfs_mount_umount(data_dir, mount=True):
# type: (str, bool) -> List[str]
mount_path = os.path.join(data_dir, 'configfs')
if mount:
cmd = 'if ! grep -qs {0} /proc/mounts; then ' \
'mount -t configfs none {0}; fi'.format(mount_path)
else:
cmd = 'if grep -qs {0} /proc/mounts; then ' \
'umount {0}; fi'.format(mount_path)
return cmd.split()
def get_tcmu_runner_container(self):
# type: () -> CephContainer
tcmu_container = get_container(self.ctx, self.fsid, self.daemon_type, self.daemon_id)
tcmu_container.entrypoint = '/usr/bin/tcmu-runner'
tcmu_container.cname = self.get_container_name(desc='tcmu')
# remove extra container args for tcmu container.
# extra args could cause issue with forking service type
tcmu_container.container_args = []
return tcmu_container
##################################
class HAproxy(object):
"""Defines an HAproxy container"""
daemon_type = 'haproxy'
required_files = ['haproxy.cfg']
default_image = 'haproxy'
def __init__(self,
ctx: CephadmContext,
fsid: str, daemon_id: Union[int, str],
config_json: Dict, image: str) -> None:
self.ctx = ctx
self.fsid = fsid
self.daemon_id = daemon_id
self.image = image
# config-json options
self.files = dict_get(config_json, 'files', {})
self.validate()
@classmethod
def init(cls, ctx: CephadmContext,
fsid: str, daemon_id: Union[int, str]) -> 'HAproxy':
return cls(ctx, fsid, daemon_id, get_parm(ctx.config_json),
ctx.image)
def create_daemon_dirs(self, data_dir: str, uid: int, gid: int) -> None:
"""Create files under the container data dir"""
if not os.path.isdir(data_dir):
raise OSError('data_dir is not a directory: %s' % (data_dir))
# create additional directories in data dir for HAproxy to use
if not os.path.isdir(os.path.join(data_dir, 'haproxy')):
makedirs(os.path.join(data_dir, 'haproxy'), uid, gid, DATA_DIR_MODE)
data_dir = os.path.join(data_dir, 'haproxy')
populate_files(data_dir, self.files, uid, gid)
def get_daemon_args(self) -> List[str]:
return ['haproxy', '-f', '/var/lib/haproxy/haproxy.cfg']
def validate(self):
# type: () -> None
if not is_fsid(self.fsid):
raise Error('not an fsid: %s' % self.fsid)
if not self.daemon_id:
raise Error('invalid daemon_id: %s' % self.daemon_id)
if not self.image:
raise Error('invalid image: %s' % self.image)
# check for the required files
if self.required_files:
for fname in self.required_files:
if fname not in self.files:
raise Error('required file missing from config-json: %s' % fname)
def get_daemon_name(self):
# type: () -> str
return '%s.%s' % (self.daemon_type, self.daemon_id)
def get_container_name(self, desc=None):
# type: (Optional[str]) -> str
cname = 'ceph-%s-%s' % (self.fsid, self.get_daemon_name())
if desc:
cname = '%s-%s' % (cname, desc)
return cname
def extract_uid_gid_haproxy(self):
# better directory for this?
return extract_uid_gid(self.ctx, file_path='/var/lib')
@staticmethod
def get_container_mounts(data_dir: str) -> Dict[str, str]:
mounts = dict()
mounts[os.path.join(data_dir, 'haproxy')] = '/var/lib/haproxy'
return mounts
##################################
class Keepalived(object):
"""Defines an Keepalived container"""
daemon_type = 'keepalived'
required_files = ['keepalived.conf']
default_image = 'arcts/keepalived'
def __init__(self,
ctx: CephadmContext,
fsid: str, daemon_id: Union[int, str],
config_json: Dict, image: str) -> None:
self.ctx = ctx
self.fsid = fsid
self.daemon_id = daemon_id
self.image = image
# config-json options
self.files = dict_get(config_json, 'files', {})
self.validate()
@classmethod
def init(cls, ctx: CephadmContext, fsid: str,
daemon_id: Union[int, str]) -> 'Keepalived':
return cls(ctx, fsid, daemon_id,
get_parm(ctx.config_json), ctx.image)
def create_daemon_dirs(self, data_dir: str, uid: int, gid: int) -> None:
"""Create files under the container data dir"""
if not os.path.isdir(data_dir):
raise OSError('data_dir is not a directory: %s' % (data_dir))
# create additional directories in data dir for keepalived to use
if not os.path.isdir(os.path.join(data_dir, 'keepalived')):
makedirs(os.path.join(data_dir, 'keepalived'), uid, gid, DATA_DIR_MODE)
# populate files from the config-json
populate_files(data_dir, self.files, uid, gid)
def validate(self):
# type: () -> None
if not is_fsid(self.fsid):
raise Error('not an fsid: %s' % self.fsid)
if not self.daemon_id:
raise Error('invalid daemon_id: %s' % self.daemon_id)
if not self.image:
raise Error('invalid image: %s' % self.image)
# check for the required files
if self.required_files:
for fname in self.required_files:
if fname not in self.files:
raise Error('required file missing from config-json: %s' % fname)
def get_daemon_name(self):
# type: () -> str
return '%s.%s' % (self.daemon_type, self.daemon_id)
def get_container_name(self, desc=None):
# type: (Optional[str]) -> str
cname = 'ceph-%s-%s' % (self.fsid, self.get_daemon_name())
if desc:
cname = '%s-%s' % (cname, desc)
return cname
@staticmethod
def get_container_envs():
# type: () -> List[str]
envs = [
'KEEPALIVED_AUTOCONF=false',
'KEEPALIVED_CONF=/etc/keepalived/keepalived.conf',
'KEEPALIVED_CMD=/usr/sbin/keepalived -n -l -f /etc/keepalived/keepalived.conf',
'KEEPALIVED_DEBUG=false'
]
return envs
def extract_uid_gid_keepalived(self):
# better directory for this?
return extract_uid_gid(self.ctx, file_path='/var/lib')
@staticmethod
def get_container_mounts(data_dir: str) -> Dict[str, str]:
mounts = dict()
mounts[os.path.join(data_dir, 'keepalived.conf')] = '/etc/keepalived/keepalived.conf'
return mounts
##################################
class CustomContainer(object):
"""Defines a custom container"""
daemon_type = 'container'
def __init__(self,
fsid: str, daemon_id: Union[int, str],
config_json: Dict, image: str) -> None:
self.fsid = fsid
self.daemon_id = daemon_id
self.image = image
# config-json options
self.entrypoint = dict_get(config_json, 'entrypoint')
self.uid = dict_get(config_json, 'uid', 65534) # nobody
self.gid = dict_get(config_json, 'gid', 65534) # nobody
self.volume_mounts = dict_get(config_json, 'volume_mounts', {})
self.args = dict_get(config_json, 'args', [])
self.envs = dict_get(config_json, 'envs', [])
self.privileged = dict_get(config_json, 'privileged', False)
self.bind_mounts = dict_get(config_json, 'bind_mounts', [])
self.ports = dict_get(config_json, 'ports', [])
self.dirs = dict_get(config_json, 'dirs', [])
self.files = dict_get(config_json, 'files', {})
@classmethod
def init(cls, ctx: CephadmContext,
fsid: str, daemon_id: Union[int, str]) -> 'CustomContainer':
return cls(fsid, daemon_id,
get_parm(ctx.config_json), ctx.image)
def create_daemon_dirs(self, data_dir: str, uid: int, gid: int) -> None:
"""
Create dirs/files below the container data directory.
"""
logger.info('Creating custom container configuration '
'dirs/files in {} ...'.format(data_dir))
if not os.path.isdir(data_dir):
raise OSError('data_dir is not a directory: %s' % data_dir)
for dir_path in self.dirs:
logger.info('Creating directory: {}'.format(dir_path))
dir_path = os.path.join(data_dir, dir_path.strip('/'))
makedirs(dir_path, uid, gid, 0o755)
for file_path in self.files:
logger.info('Creating file: {}'.format(file_path))
content = dict_get_join(self.files, file_path)
file_path = os.path.join(data_dir, file_path.strip('/'))
with open(file_path, 'w', encoding='utf-8') as f:
os.fchown(f.fileno(), uid, gid)
os.fchmod(f.fileno(), 0o600)
f.write(content)
def get_daemon_args(self) -> List[str]:
return []
def get_container_args(self) -> List[str]:
return self.args
def get_container_envs(self) -> List[str]:
return self.envs
def get_container_mounts(self, data_dir: str) -> Dict[str, str]:
"""
Get the volume mounts. Relative source paths will be located below
`/var/lib/ceph/<cluster-fsid>/<daemon-name>`.
Example:
{
/foo/conf: /conf
foo/conf: /conf
}
becomes
{
/foo/conf: /conf
/var/lib/ceph/<cluster-fsid>/<daemon-name>/foo/conf: /conf
}
"""
mounts = {}
for source, destination in self.volume_mounts.items():
source = os.path.join(data_dir, source)
mounts[source] = destination
return mounts
def get_container_binds(self, data_dir: str) -> List[List[str]]:
"""
Get the bind mounts. Relative `source=...` paths will be located below
`/var/lib/ceph/<cluster-fsid>/<daemon-name>`.
Example:
[
'type=bind',
'source=lib/modules',
'destination=/lib/modules',
'ro=true'
]
becomes
[
...
'source=/var/lib/ceph/<cluster-fsid>/<daemon-name>/lib/modules',
...
]
"""
binds = self.bind_mounts.copy()
for bind in binds:
for index, value in enumerate(bind):
match = re.match(r'^source=(.+)$', value)
if match:
bind[index] = 'source={}'.format(os.path.join(
data_dir, match.group(1)))
return binds
##################################
def dict_get(d: Dict, key: str, default: Any = None, require: bool = False) -> Any:
"""
Helper function to get a key from a dictionary.
:param d: The dictionary to process.
:param key: The name of the key to get.
:param default: The default value in case the key does not
exist. Default is `None`.
:param require: Set to `True` if the key is required. An
exception will be raised if the key does not exist in
the given dictionary.
:return: Returns the value of the given key.
:raises: :exc:`self.Error` if the given key does not exist
and `require` is set to `True`.
"""
if require and key not in d.keys():
raise Error('{} missing from dict'.format(key))
return d.get(key, default) # type: ignore
##################################
def dict_get_join(d: Dict, key: str) -> Any:
"""
Helper function to get the value of a given key from a dictionary.
`List` values will be converted to a string by joining them with a
line break.
:param d: The dictionary to process.
:param key: The name of the key to get.
:return: Returns the value of the given key. If it was a `list`, it
will be joining with a line break.
"""
value = d.get(key)
if isinstance(value, list):
value = '\n'.join(map(str, value))
return value
##################################
def get_supported_daemons():
# type: () -> List[str]
supported_daemons = list(Ceph.daemons)
supported_daemons.extend(Monitoring.components)
supported_daemons.append(NFSGanesha.daemon_type)
supported_daemons.append(CephIscsi.daemon_type)
supported_daemons.append(CustomContainer.daemon_type)
supported_daemons.append(CephadmDaemon.daemon_type)
supported_daemons.append(HAproxy.daemon_type)
supported_daemons.append(Keepalived.daemon_type)
assert len(supported_daemons) == len(set(supported_daemons))
return supported_daemons
##################################
class PortOccupiedError(Error):
pass
def attempt_bind(ctx, s, address, port):
# type: (CephadmContext, socket.socket, str, int) -> None
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((address, port))
except (socket.error, OSError) as e: # py2 and py3
if e.errno == errno.EADDRINUSE:
msg = 'Cannot bind to IP %s port %d: %s' % (address, port, e)
logger.warning(msg)
raise PortOccupiedError(msg)
else:
raise e
finally:
s.close()
def port_in_use(ctx, port_num):
# type: (CephadmContext, int) -> bool
"""Detect whether a port is in use on the local machine - IPv4 and IPv6"""
logger.info('Verifying port %d ...' % port_num)
def _port_in_use(af: socket.AddressFamily, address: str) -> bool:
try:
s = socket.socket(af, socket.SOCK_STREAM)
attempt_bind(ctx, s, address, port_num)
except PortOccupiedError:
return True
except OSError as e:
if e.errno in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL):
# Ignore EAFNOSUPPORT and EADDRNOTAVAIL as two interfaces are
# being tested here and one might be intentionally be disabled.
# In that case no error should be raised.
return False
else:
raise e
return False