-
Notifications
You must be signed in to change notification settings - Fork 7
/
cephadm
executable file
·2717 lines (2405 loc) · 92.5 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
DEFAULT_IMAGE='ceph/daemon-base:latest-master-devel' # FIXME when octopus is ready!!!
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_PREFERENCE = ['podman', 'docker'] # prefer podman to docker
CUSTOM_PS1=r'[ceph: \u@\h \W]\$ '
"""
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-and-json -' argument,
injected_stdin = '...'
"""
import argparse
import fcntl
import json
import logging
import os
import random
import re
import select
import shutil
import socket
import string
import subprocess
import sys
import tempfile
import time
import errno
try:
from typing import Dict, List, Tuple, Optional, Union
except ImportError:
pass
import uuid
from distutils.spawn import find_executable
from functools import wraps
from glob import glob
if sys.version_info >= (3, 0):
from io import StringIO
else:
from StringIO import StringIO
if sys.version_info >= (3, 2):
from configparser import ConfigParser
else:
from ConfigParser import SafeConfigParser
container_path = None
class Error(Exception):
pass
##################################
class Ceph(object):
daemons = ('mon', 'mgr', 'mds', 'osd', 'rgw', 'rbd-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,
}
components = {
"prometheus": {
"image": {
"image": "prom/prometheus:latest",
"cpus": '2',
"memory": '4GB',
"args": [
"--config.file=/etc/prometheus/prometheus.yml",
"--storage.tsdb.path=/prometheus",
"--web.listen-address=:{}".format(port_map['prometheus']),
]
},
"config-json": [
"prometheus.yml",
],
},
"node-exporter": {
"image": {
"image": "prom/node-exporter",
"cpus": "1",
"memory": "1GB",
"args": [
"--no-collector.timex",
],
}
},
"grafana": {
"image": {
"image": "pcuzner/ceph-grafana-el8:latest",
"cpus": "2",
"memory": "4GB",
"args": [],
},
"config-json": [
"grafana.ini",
"provisioning/datasources/ceph-dashboard.yml",
"certs/cert_file",
"certs/cert_key",
],
}
}
def attempt_bind(s, address, port):
# type (str) -> None
try:
s.bind((address, port))
except (socket.error, OSError) as e: # py2 and py3
if e.errno == errno.EADDRINUSE:
raise OSError
elif e.errno == errno.EADDRNOTAVAIL:
return
finally:
s.close()
def port_in_use(port_num):
# type (int) -> bool
"""Detect whether a port is in use on the local machine - IPv4 and IPv6"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
attempt_bind(s, '0.0.0.0', port_num)
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
attempt_bind(s, '::', port_num)
except OSError:
return True
else:
return False
def check_ip_port(ip, port):
if not args.skip_ping_check:
logger.info('Verifying IP %s port %d is not in use...' % (ip, port))
if ip.startswith('[') or '::' in ip:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
attempt_bind(s, ip, port)
except OSError as e:
raise Error('Unable to bind to IP %s port %d: %s' % (ip, port,
str(e)))
##################################
# this is an abbreviated version of
# https://github.com/benediktschmitt/py-filelock/blob/master/filelock.py
# that drops all of the compatibility (this is Unix/Linux only).
try:
TimeoutError
except NameError:
TimeoutError = OSError
class Timeout(TimeoutError):
"""
Raised when the lock could not be acquired in *timeout*
seconds.
"""
def __init__(self, lock_file):
"""
"""
#: The path of the file lock.
self.lock_file = lock_file
return None
def __str__(self):
temp = "The file lock '{}' could not be acquired."\
.format(self.lock_file)
return temp
class _Acquire_ReturnProxy(object):
def __init__(self, lock):
self.lock = lock
return None
def __enter__(self):
return self.lock
def __exit__(self, exc_type, exc_value, traceback):
self.lock.release()
return None
class FileLock(object):
def __init__(self, name, timeout = -1):
if not os.path.exists(LOCK_DIR):
os.mkdir(LOCK_DIR, 0o700)
self._lock_file = os.path.join(LOCK_DIR, name + '.lock')
# The file descriptor for the *_lock_file* as it is returned by the
# os.open() function.
# This file lock is only NOT None, if the object currently holds the
# lock.
self._lock_file_fd = None
self.timeout = timeout
# The lock counter is used for implementing the nested locking
# mechanism. Whenever the lock is acquired, the counter is increased and
# the lock is only released, when this value is 0 again.
self._lock_counter = 0
return None
@property
def is_locked(self):
return self._lock_file_fd is not None
def acquire(self, timeout=None, poll_intervall=0.05):
"""
Acquires the file lock or fails with a :exc:`Timeout` error.
.. code-block:: python
# You can use this method in the context manager (recommended)
with lock.acquire():
pass
# Or use an equivalent try-finally construct:
lock.acquire()
try:
pass
finally:
lock.release()
:arg float timeout:
The maximum time waited for the file lock.
If ``timeout < 0``, there is no timeout and this method will
block until the lock could be acquired.
If ``timeout`` is None, the default :attr:`~timeout` is used.
:arg float poll_intervall:
We check once in *poll_intervall* seconds if we can acquire the
file lock.
:raises Timeout:
if the lock could not be acquired in *timeout* seconds.
.. versionchanged:: 2.0.0
This method returns now a *proxy* object instead of *self*,
so that it can be used in a with statement without side effects.
"""
# Use the default timeout, if no timeout is provided.
if timeout is None:
timeout = self.timeout
# Increment the number right at the beginning.
# We can still undo it, if something fails.
self._lock_counter += 1
lock_id = id(self)
lock_filename = self._lock_file
start_time = time.time()
try:
while True:
if not self.is_locked:
logger.debug('Acquiring lock %s on %s', lock_id,
lock_filename)
self._acquire()
if self.is_locked:
logger.debug('Lock %s acquired on %s', lock_id,
lock_filename)
break
elif timeout >= 0 and time.time() - start_time > timeout:
logger.warning('Timeout acquiring lock %s on %s', lock_id,
lock_filename)
raise Timeout(self._lock_file)
else:
logger.debug(
'Lock %s not acquired on %s, waiting %s seconds ...',
lock_id, lock_filename, poll_intervall
)
time.sleep(poll_intervall)
except:
# Something did go wrong, so decrement the counter.
self._lock_counter = max(0, self._lock_counter - 1)
raise
return _Acquire_ReturnProxy(lock = self)
def release(self, force = False):
"""
Releases the file lock.
Please note, that the lock is only completly released, if the lock
counter is 0.
Also note, that the lock file itself is not automatically deleted.
:arg bool force:
If true, the lock counter is ignored and the lock is released in
every case.
"""
if self.is_locked:
self._lock_counter -= 1
if self._lock_counter == 0 or force:
lock_id = id(self)
lock_filename = self._lock_file
logger.debug('Releasing lock %s on %s', lock_id, lock_filename)
self._release()
self._lock_counter = 0
logger.debug('Lock %s released on %s', lock_id, lock_filename)
return None
def __enter__(self):
self.acquire()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.release()
return None
def __del__(self):
self.release(force = True)
return None
def _acquire(self):
open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC
fd = os.open(self._lock_file, open_mode)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (IOError, OSError):
os.close(fd)
else:
self._lock_file_fd = fd
return None
def _release(self):
# Do not remove the lockfile:
#
# https://github.com/benediktschmitt/py-filelock/issues/31
# https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
fd = self._lock_file_fd
self._lock_file_fd = None
fcntl.flock(fd, fcntl.LOCK_UN)
os.close(fd)
return None
##################################
# Popen wrappers, lifted from ceph-volume
def call(command, desc=None, verbose=False, **kwargs):
"""
Wrap subprocess.Popen to
- log stdout/stderr to a logger,
- decode utf-8
- cleanly return out, err, returncode
If verbose=True, log at info (instead of debug) level.
:param verbose_on_failure: On a non-zero exit status, it will forcefully set
logging ON for the terminal
"""
if not desc:
desc = command[0]
verbose_on_failure = kwargs.pop('verbose_on_failure', True)
logger.debug("Running command: %s" % ' '.join(command))
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
**kwargs
)
# get current p.stdout flags, add O_NONBLOCK
stdout_flags = fcntl.fcntl(process.stdout, fcntl.F_GETFL)
stderr_flags = fcntl.fcntl(process.stderr, fcntl.F_GETFL)
fcntl.fcntl(process.stdout, fcntl.F_SETFL, stdout_flags | os.O_NONBLOCK)
fcntl.fcntl(process.stderr, fcntl.F_SETFL, stderr_flags | os.O_NONBLOCK)
out = ''
err = ''
reads = None
stop = False
out_buffer = '' # partial line (no newline yet)
err_buffer = '' # partial line (no newline yet)
while not stop:
if reads and process.poll() is not None:
# we want to stop, but first read off anything remaining
# on stdout/stderr
stop = True
else:
reads, _, _ = select.select(
[process.stdout.fileno(), process.stderr.fileno()],
[], []
)
for fd in reads:
try:
message = os.read(fd, 1024)
if not isinstance(message, str):
message = message.decode('utf-8')
if fd == process.stdout.fileno():
out += message
message = out_buffer + message
lines = message.split('\n')
out_buffer = lines.pop()
for line in lines:
if verbose:
logger.info(desc + ':stdout ' + line)
else:
logger.debug(desc + ':stdout ' + line)
elif fd == process.stderr.fileno():
err += message
message = err_buffer + message
lines = message.split('\n')
err_buffer = lines.pop()
for line in lines:
if verbose:
logger.info(desc + ':stderr ' + line)
else:
logger.debug(desc + ':stderr ' + line)
else:
assert False
except (IOError, OSError):
pass
returncode = process.wait()
if out_buffer != '':
if verbose:
logger.info(desc + ':stdout ' + out_buffer)
else:
logger.debug(desc + ':stdout ' + out_buffer)
if err_buffer != '':
if verbose:
logger.info(desc + ':stderr ' + err_buffer)
else:
logger.debug(desc + ':stderr ' + err_buffer)
if returncode != 0 and verbose_on_failure and not verbose:
# dump stdout + stderr
logger.info('Non-zero exit code %d from %s' % (returncode, ' '.join(command)))
for line in out.splitlines():
logger.info(desc + ':stdout ' + line)
for line in err.splitlines():
logger.info(desc + ':stderr ' + line)
return out, err, returncode
def call_throws(command, **kwargs):
out, err, ret = call(command, **kwargs)
if ret:
raise RuntimeError('Failed command: %s' % ' '.join(command))
return out, err, ret
##################################
def read_config(fn):
# type: (Optional[str]) -> ConfigParser
# bend over backwards here because py2's ConfigParser doesn't like
# whitespace before config option names (e.g., '\n foo = bar\n').
# Yeesh!
if sys.version_info >= (3, 2):
cp = ConfigParser()
else:
cp = SafeConfigParser()
if fn:
with open(fn, 'r') as f:
raw_conf = f.read()
nice_conf = re.sub(r'\n(\s)+', r'\n', raw_conf)
s_io = StringIO(nice_conf)
if sys.version_info >= (3, 2):
cp.read_file(s_io)
else:
cp.readfp(s_io)
return cp
def pathify(p):
# type: (str) -> str
if not p.startswith('/'):
return os.path.join(os.getcwd(), p)
return p
def get_hostname():
# type: () -> str
return socket.gethostname()
def get_fqdn():
# type: () -> str
return socket.getfqdn() or socket.gethostname()
def generate_service_id():
# type: () -> str
return ''.join(random.choice(string.ascii_lowercase)
for _ in range(6))
def generate_password():
# type: () -> str
return ''.join(random.choice(string.ascii_lowercase + string.digits)
for i in range(10))
def make_fsid():
# type: () -> str
return str(uuid.uuid1())
def is_fsid(s):
# type: (str) -> bool
try:
uuid.UUID(s)
except ValueError:
return False
return True
def infer_fsid(func):
"""
If we only find a single fsid in /var/lib/ceph/*, use that
"""
@wraps(func)
def _infer_fsid():
if args.fsid:
logger.debug('Using specified fsid: %s' % args.fsid)
return func()
fsid_list = []
if os.path.exists(args.data_dir):
for i in os.listdir(args.data_dir):
if is_fsid(i):
fsid_list.append(i)
logger.debug('Found fsids %s' % str(fsid_list))
if not fsid_list:
# TODO: raise?
return func()
if len(fsid_list) > 1:
raise Error('cannot infer fsid, must specify --fsid')
logger.info('Inferring fsid %s' % fsid_list[0])
args.fsid = fsid_list[0]
return func()
return _infer_fsid
def write_tmp(s, uid, gid):
tmp_f = tempfile.NamedTemporaryFile(mode='w',
prefix='ceph-tmp')
os.fchown(tmp_f.fileno(), uid, gid)
tmp_f.write(s)
tmp_f.flush()
return tmp_f
def makedirs(dir, uid, gid, mode):
# type: (str, int, int, int) -> None
if not os.path.exists(dir):
os.makedirs(dir, mode=mode)
else:
os.chmod(dir, mode)
os.chown(dir, uid, gid)
os.chmod(dir, mode) # the above is masked by umask...
def get_data_dir(fsid, t, n):
# type: (str, str, Union[int, str]) -> str
return os.path.join(args.data_dir, fsid, '%s.%s' % (t, n))
def get_log_dir(fsid):
# type: (str) -> str
return os.path.join(args.log_dir, fsid)
def make_data_dir_base(fsid, uid, gid):
# type: (str, int, int) -> str
data_dir_base = os.path.join(args.data_dir, fsid)
makedirs(data_dir_base, uid, gid, DATA_DIR_MODE)
makedirs(os.path.join(data_dir_base, 'crash'), uid, gid, DATA_DIR_MODE)
makedirs(os.path.join(data_dir_base, 'crash', 'posted'), uid, gid,
DATA_DIR_MODE)
return data_dir_base
def make_data_dir(fsid, daemon_type, daemon_id, uid=None, gid=None):
# type: (str, str, Union[int, str], int, int) -> str
if not uid or not gid:
(uid, gid) = extract_uid_gid()
make_data_dir_base(fsid, uid, gid)
data_dir = get_data_dir(fsid, daemon_type, daemon_id)
makedirs(data_dir, uid, gid, DATA_DIR_MODE)
return data_dir
def make_log_dir(fsid, uid=None, gid=None):
# type: (str, int, int) -> str
if not uid or not gid:
(uid, gid) = extract_uid_gid()
log_dir = get_log_dir(fsid)
makedirs(log_dir, uid, gid, LOG_DIR_MODE)
return log_dir
def make_var_run(fsid, uid, gid):
# type: (str, int, int) -> None
call_throws(['install', '-d', '-m0770', '-o', str(uid), '-g', str(gid),
'/var/run/ceph/%s' % fsid])
def copy_files(src, dst, uid=None, gid=None):
# type: (List[str], str, int, int) -> None
"""
Copy a files from src to dst
"""
if not uid or not gid:
(uid, gid) = extract_uid_gid()
for src_file in src:
dst_file = dst
if os.path.isdir(dst):
dst_file = os.path.join(dst, os.path.basename(src_file))
logger.debug('copy file \'%s\' -> \'%s\'' % (src_file, dst_file))
shutil.copyfile(src_file, dst_file)
logger.debug('chown %s:%s \'%s\'' % (uid, gid, dst_file))
os.chown(dst_file, uid, gid)
def move_files(src, dst, uid=None, gid=None):
# type: (List[str], str, int, int) -> None
"""
Move files from src to dst
"""
if not uid or not gid:
(uid, gid) = extract_uid_gid()
for src_file in src:
dst_file = dst
if os.path.isdir(dst):
dst_file = os.path.join(dst, os.path.basename(src_file))
if os.path.islink(src_file):
# shutil.move() in py2 does not handle symlinks correctly
src_rl = os.readlink(src_file)
logger.debug("symlink '%s' -> '%s'" % (dst_file, src_rl))
os.symlink(src_rl, dst_file)
os.unlink(src_file)
else:
logger.debug("move file '%s' -> '%s'" % (src_file, dst_file))
shutil.move(src_file, dst_file)
logger.debug('chown %s:%s \'%s\'' % (uid, gid, dst_file))
os.chown(dst_file, uid, gid)
def find_program(filename):
# type: (str) -> str
name = find_executable(filename)
if name is None:
raise ValueError('%s not found' % filename)
return name
def get_unit_name(fsid, daemon_type, daemon_id=None):
# type (str, str, Optional[Union[int, str]]) -> str
# accept either name or type + id
if daemon_id is not None:
return 'ceph-%s@%s.%s' % (fsid, daemon_type, daemon_id)
else:
return 'ceph-%s@%s' % (fsid, daemon_type)
def check_unit(unit_name):
# type: (str) -> Tuple[bool, str]
# NOTE: we ignore the exit code here because systemctl outputs
# various exit codes based on the state of the service, but the
# string result is more explicit (and sufficient).
enabled = False
try:
out, err, code = call(['systemctl', 'is-enabled', unit_name],
verbose_on_failure=False)
if code == 0:
enabled = True
except Exception as e:
logger.warning('unable to run systemctl: %s' % e)
enabled = False
state = 'unknown'
try:
out, err, code = call(['systemctl', 'is-active', unit_name],
verbose_on_failure=False)
out = out.strip()
if out in ['active']:
state = 'running'
elif out in ['inactive']:
state = 'stopped'
elif out in ['failed', 'auto-restart']:
state = 'error'
else:
state = 'unknown'
except Exception as e:
logger.warning('unable to run systemctl: %s' % e)
state = 'unknown'
return (enabled, state)
def get_legacy_config_fsid(cluster, legacy_dir=None):
# type: (str, str) -> Optional[str]
config_file = '/etc/ceph/%s.conf' % cluster
if legacy_dir is not None:
config_file = os.path.abspath(legacy_dir + config_file)
if os.path.exists(config_file):
config = read_config(config_file)
if config.has_section('global') and config.has_option('global', 'fsid'):
return config.get('global', 'fsid')
return None
def get_legacy_daemon_fsid(cluster, daemon_type, daemon_id, legacy_dir=None):
# type: (str, str, Union[int, str], str) -> Optional[str]
fsid = None
if daemon_type == 'osd':
try:
fsid_file = os.path.join(args.data_dir,
daemon_type,
'ceph-%s' % daemon_id,
'ceph_fsid')
if legacy_dir is not None:
fsid_file = os.path.abspath(legacy_dir + fsid_file)
with open(fsid_file, 'r') as f:
fsid = f.read().strip()
except IOError:
pass
if not fsid:
fsid = get_legacy_config_fsid(cluster, legacy_dir=legacy_dir)
return fsid
def get_daemon_args(fsid, daemon_type, daemon_id):
# type: (str, str, Union[int, str]) -> List[str]
r = list() # type: List[str]
if daemon_type in Ceph.daemons:
r += [
'--setuser', 'ceph',
'--setgroup', 'ceph',
'--default-log-to-file=false',
'--default-log-to-stderr=true',
'--default-log-stderr-prefix=debug\ ',
]
if daemon_type == 'mon':
r += [
'--default-mon-cluster-log-to-file=false',
'--default-mon-cluster-log-to-stderr=true',
]
elif daemon_type in Monitoring.components:
component = Monitoring.components[daemon_type] # type: ignore
metadata = component.get('image', list()) # type: ignore
r += metadata.get('args', list()) # type: ignore
return r
def create_daemon_dirs(fsid, daemon_type, daemon_id, uid, gid,
config=None, keyring=None,
reconfig=False):
# type: (str, str, Union[int, str], int, int, Optional[str], Optional[str], Optional[bool]) -> None
data_dir = make_data_dir(fsid, daemon_type, daemon_id, uid=uid, gid=gid)
make_log_dir(fsid, uid=uid, gid=gid)
if config:
with open(data_dir + '/config', 'w') as f:
os.fchown(f.fileno(), uid, gid)
os.fchmod(f.fileno(), 0o600)
f.write(config)
if keyring:
with open(data_dir + '/keyring', 'w') as f:
os.fchmod(f.fileno(), 0o600)
os.fchown(f.fileno(), uid, gid)
f.write(keyring)
if daemon_type in Monitoring.components.keys():
received_config = get_parm(args.config_json)
required_config = Monitoring.components[daemon_type].get('config-json', list()) # type: ignore
if required_config:
if not received_config or not all(c in received_config.keys() for c in required_config):
raise Error("{} deployment requires config-json which must "
"contain settings for {}".format(daemon_type.capitalize(), ', '.join(required_config)))
# Set up directories specific to the monitoring component
config_dir = ''
if daemon_type == 'prometheus':
data_dir_root = get_data_dir(fsid, daemon_type, daemon_id)
config_dir = 'etc/prometheus'
makedirs(os.path.join(data_dir_root, config_dir), uid, gid, 0o755)
makedirs(os.path.join(data_dir_root, config_dir, 'alerting'), uid, gid, 0o755)
makedirs(os.path.join(data_dir_root, 'data'), uid, gid, 0o755)
elif daemon_type == 'grafana':
data_dir_root = get_data_dir(fsid, daemon_type, daemon_id)
config_dir = 'etc/grafana'
makedirs(os.path.join(data_dir_root, config_dir), uid, gid, 0o755)
makedirs(os.path.join(data_dir_root, config_dir, 'certs'), uid, gid, 0o755)
makedirs(os.path.join(data_dir_root, config_dir, 'provisioning/datasources'), uid, gid, 0o755)
makedirs(os.path.join(data_dir_root, 'data'), uid, gid, 0o755)
# populate the config directory for the component from the config-json
for fname in required_config:
if isinstance(received_config[fname], list):
content = '\n'.join(received_config[fname])
else:
content = received_config[fname]
with open(os.path.join(data_dir_root, config_dir, fname), 'w') as f:
os.fchown(f.fileno(), uid, gid)
os.fchmod(f.fileno(), 0o600)
f.write(content)
def get_parm(option):
# type: (str) -> Dict[str, str]
if not option:
return dict()
if option == '-':
try:
j = injected_stdin # type: ignore
except NameError:
j = sys.stdin.read()
else:
# inline json string
if option[0] == '{' and option[-1] == '}':
j = option
# json file
elif os.path.exists(option):
with open(option, 'r') as f:
j = f.read()
else:
raise Error("Config file {} not found".format(option))
try:
js = json.loads(j)
except ValueError:
raise Error("Invalid JSON in {}".format(option))
else:
return js
def get_config_and_keyring():
# type: () -> Tuple[str, str]
if args.config_and_keyring:
if args.config_and_keyring == '-':
try:
j = injected_stdin # type: ignore
except NameError:
j = sys.stdin.read()
else:
with open(args.config_and_keyring, 'r') as f:
j = f.read()
d = json.loads(j)
config = d.get('config')
keyring = d.get('keyring')
else:
if args.key:
keyring = '[%s]\n\tkey = %s\n' % (args.name, args.key)
elif args.keyring:
with open(args.keyring, 'r') as f:
keyring = f.read()
else:
raise Error('no keyring provided')
with open(args.config, 'r') as f:
config = f.read()
return (config, keyring)
def get_config_and_both_keyrings():
# type: () -> Tuple[str, str, Optional[str]]
if args.config_and_keyrings:
if args.config_and_keyrings == '-':
try:
j = injected_stdin # type: ignore
except NameError:
j = sys.stdin.read()
else:
with open(args.config_and_keyrings, 'r') as f:
j = f.read()
d = json.loads(j)
return (d.get('config'), d.get('keyring'), d.get('crash_keyring'))
else:
if args.key:
keyring = '[%s]\n\tkey = %s\n' % (args.name, args.key)
elif args.keyring:
with open(args.keyring, 'r') as f:
keyring = f.read()
else:
raise Error('no keyring provided')
crash_keyring = None
if args.crash_keyring:
with open(args.crash_keyring, 'r') as f:
crash_keyring = f.read()
with open(args.config, 'r') as f:
config = f.read()
return (config, keyring, crash_keyring)
def get_container_mounts(fsid, daemon_type, daemon_id,
no_config=False):
# type: (str, str, Union[int, str, None], Optional[bool]) -> Dict[str, str]
mounts = dict()
if daemon_type in Ceph.daemons:
if fsid:
run_path = os.path.join('/var/run/ceph', fsid);
if os.path.exists(run_path):
mounts[run_path] = '/var/run/ceph:z'
log_dir = get_log_dir(fsid)
mounts[log_dir] = '/var/log/ceph:z'
crash_dir = '/var/lib/ceph/%s/crash' % fsid
if os.path.exists(crash_dir):
mounts[crash_dir] = '/var/lib/ceph/crash:z'
if daemon_type in Ceph.daemons and daemon_id:
data_dir = get_data_dir(fsid, daemon_type, daemon_id)
if daemon_type == 'rgw':
cdata_dir = '/var/lib/ceph/radosgw/ceph-rgw.%s' % (daemon_id)
else:
cdata_dir = '/var/lib/ceph/%s/ceph-%s' % (daemon_type, daemon_id)
mounts[data_dir] = cdata_dir + ':z'
if not no_config:
mounts[data_dir + '/config'] = '/etc/ceph/ceph.conf:z'
if daemon_type == 'rbd-mirror':
# rbd-mirror does not search for its keyring in a data directory
mounts[data_dir + '/keyring'] = '/etc/ceph/ceph.client.rbd-mirror.%s.keyring' % daemon_id
if daemon_type in ['mon', 'osd']:
mounts['/dev'] = '/dev' # FIXME: narrow this down?
mounts['/run/udev'] = '/run/udev'
if daemon_type == 'osd':
mounts['/sys'] = '/sys' # for numa.cc, pick_address, cgroups, ...
mounts['/run/lvm'] = '/run/lvm'
mounts['/run/lock/lvm'] = '/run/lock/lvm'
if daemon_type in Monitoring.components and daemon_id:
data_dir = get_data_dir(fsid, daemon_type, daemon_id)
if daemon_type == 'prometheus':
mounts[os.path.join(data_dir, 'etc/prometheus')] = '/etc/prometheus:Z'
mounts[os.path.join(data_dir, 'data')] = '/prometheus:Z'
elif daemon_type == 'node-exporter':
mounts['/proc'] = '/host/proc:ro'
mounts['/sys'] = '/host/sys:ro'
mounts['/'] = '/rootfs:ro'
elif daemon_type == "grafana":
mounts[os.path.join(data_dir, 'etc/grafana/grafana.ini')] = '/etc/grafana/grafana.ini:Z'
mounts[os.path.join(data_dir, 'etc/grafana/provisioning/datasources')] = '/etc/grafana/provisioning/datasources:Z'
mounts[os.path.join(data_dir, 'etc/grafana/certs')] = '/etc/grafana/certs:Z'
return mounts
def get_container(fsid, daemon_type, daemon_id, privileged=False,
container_args=[]):
# type: (str, str, Union[int, str], bool, List[str]) -> CephContainer
if daemon_type in ['mon', 'osd'] or privileged:
# mon and osd need privileged in order for libudev to query devices
container_args += ['--privileged']
if daemon_type == 'rgw':
entrypoint = '/usr/bin/radosgw'
name = 'client.rgw.%s' % daemon_id
elif daemon_type == 'rbd-mirror':
entrypoint = '/usr/bin/rbd-mirror'
name = 'client.rbd-mirror.%s' % daemon_id
elif daemon_type in ['mon', 'mgr', 'mds', 'osd']:
entrypoint = '/usr/bin/ceph-' + daemon_type
name = '%s.%s' % (daemon_type, daemon_id)
elif daemon_type in Monitoring.components:
entrypoint = ''
name = ''
ceph_args = ['-n', name, '-f']
if daemon_type in Monitoring.components:
ceph_args = []
return CephContainer(
image=args.image,
entrypoint=entrypoint,
args=ceph_args + get_daemon_args(fsid, daemon_type, daemon_id),
container_args=container_args,
volume_mounts=get_container_mounts(fsid, daemon_type, daemon_id),
cname='ceph-%s-%s.%s' % (fsid, daemon_type, daemon_id),
)
def extract_uid_gid(img='', file_path='/var/lib/ceph'):
# type: (str, str) -> Tuple[int, int]
if not img:
img = args.image
out = CephContainer(
image=img,