-
Notifications
You must be signed in to change notification settings - Fork 1
/
module.py
1865 lines (1624 loc) · 75.5 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 enum
import errno
import json
from typing import List, Set, Optional, Iterator, cast, Dict, Any, Union, Sequence, Mapping, Tuple
import re
import datetime
import math
import yaml
from prettytable import PrettyTable
try:
from natsort import natsorted
except ImportError:
# fallback to normal sort
natsorted = sorted # type: ignore
from ceph.deployment.inventory import Device # noqa: F401; pylint: disable=unused-variable
from ceph.deployment.drive_group import DriveGroupSpec, DeviceSelection, OSDMethod
from ceph.deployment.service_spec import PlacementSpec, ServiceSpec, service_spec_allow_invalid_from_json, TracingSpec
from ceph.deployment.hostspec import SpecValidationError
from ceph.utils import datetime_now
from mgr_util import to_pretty_timedelta, format_bytes
from mgr_module import MgrModule, HandleCommandResult, Option
from object_format import Format
from ._interface import OrchestratorClientMixin, DeviceLightLoc, _cli_read_command, \
raise_if_exception, _cli_write_command, OrchestratorError, \
NoOrchestrator, OrchestratorValidationError, NFSServiceSpec, \
RGWSpec, InventoryFilter, InventoryHost, HostSpec, CLICommandMeta, \
ServiceDescription, DaemonDescription, IscsiServiceSpec, json_to_generic_spec, \
GenericSpec, DaemonDescriptionStatus, SNMPGatewaySpec, MDSSpec, TunedProfileSpec, \
NvmeofServiceSpec
def nice_delta(now: datetime.datetime, t: Optional[datetime.datetime], suffix: str = '') -> str:
if t:
return to_pretty_timedelta(now - t) + suffix
else:
return '-'
def nice_bytes(v: Optional[int]) -> str:
if not v:
return '-'
return format_bytes(v, 5)
class ArgumentError(Exception):
pass
class HostDetails:
def __init__(self,
host: Optional[HostSpec] = None,
facts: Optional[Dict[str, Any]] = None,
object_dump: Optional[Dict[str, Any]] = None):
self._hostspec = host
self._facts = facts
self.hdd_summary = 'N/A'
self.ram = 'N/A'
self.cpu_summary = 'N/A'
self.server = 'N/A'
self.os = 'N/A'
self.ssd_summary = 'N/A'
self.nic_count = 'N/A'
assert host or object_dump
if object_dump:
self._load(object_dump)
else:
self._build()
def _load(self, object_dump: Dict[str, Any]) -> None:
"""Build the object from predefined dictionary"""
self.addr = object_dump.get('addr')
self.hostname = object_dump.get('hostname')
self.labels = object_dump.get('labels')
self.status = object_dump.get('status')
self.location = object_dump.get('location')
self.server = object_dump.get('server', 'N/A')
self.hdd_summary = object_dump.get('hdd_summary', 'N/A')
self.ssd_summary = object_dump.get('ssd_summary', 'N/A')
self.os = object_dump.get('os', 'N/A')
self.cpu_summary = object_dump.get('cpu_summary', 'N/A')
self.ram = object_dump.get('ram', 'N/A')
self.nic_count = object_dump.get('nic_count', 'N/A')
def _build(self) -> None:
"""build host details from the HostSpec and facts"""
for a in self._hostspec.__dict__:
setattr(self, a, getattr(self._hostspec, a))
if self._facts:
self.server = f"{self._facts.get('vendor', '').strip()} {self._facts.get('model', '').strip()}"
_cores = self._facts.get('cpu_cores', 0) * self._facts.get('cpu_count', 0)
_threads = self._facts.get('cpu_threads', 0) * _cores
self.os = self._facts.get('operating_system', 'N/A')
self.cpu_summary = f"{_cores}C/{_threads}T" if _cores > 0 else 'N/A'
_total_bytes = self._facts.get('memory_total_kb', 0) * 1024
divisor, suffix = (1073741824, 'GiB') if _total_bytes > 1073741824 else (1048576, 'MiB')
self.ram = f'{math.ceil(_total_bytes / divisor)} {suffix}'
_hdd_capacity = self._facts.get('hdd_capacity', '')
_ssd_capacity = self._facts.get('flash_capacity', '')
if _hdd_capacity:
if self._facts.get('hdd_count', 0) == 0:
self.hdd_summary = '-'
else:
self.hdd_summary = f"{self._facts.get('hdd_count', 0)}/{self._facts.get('hdd_capacity', 0)}"
if _ssd_capacity:
if self._facts.get('flash_count', 0) == 0:
self.ssd_summary = '-'
else:
self.ssd_summary = f"{self._facts.get('flash_count', 0)}/{self._facts.get('flash_capacity', 0)}"
self.nic_count = self._facts.get('nic_count', '')
def to_json(self) -> Dict[str, Any]:
return {k: v for k, v in self.__dict__.items() if not k.startswith('_')}
@classmethod
def from_json(cls, host_details: dict) -> 'HostDetails':
_cls = cls(object_dump=host_details)
return _cls
@staticmethod
def yaml_representer(dumper: 'yaml.SafeDumper', data: 'HostDetails') -> Any:
return dumper.represent_dict(cast(Mapping, data.to_json().items()))
yaml.add_representer(HostDetails, HostDetails.yaml_representer)
class ServiceType(enum.Enum):
mon = 'mon'
mgr = 'mgr'
rbd_mirror = 'rbd-mirror'
cephfs_mirror = 'cephfs-mirror'
crash = 'crash'
alertmanager = 'alertmanager'
grafana = 'grafana'
node_exporter = 'node-exporter'
ceph_exporter = 'ceph-exporter'
prometheus = 'prometheus'
loki = 'loki'
promtail = 'promtail'
mds = 'mds'
rgw = 'rgw'
nfs = 'nfs'
iscsi = 'iscsi'
nvmeof = 'nvmeof'
snmp_gateway = 'snmp-gateway'
elasticsearch = 'elasticsearch'
jaeger_agent = 'jaeger-agent'
jaeger_collector = 'jaeger-collector'
jaeger_query = 'jaeger-query'
class ServiceAction(enum.Enum):
start = 'start'
stop = 'stop'
restart = 'restart'
redeploy = 'redeploy'
reconfig = 'reconfig'
rotate_key = 'rotate-key'
class DaemonAction(enum.Enum):
start = 'start'
stop = 'stop'
restart = 'restart'
reconfig = 'reconfig'
rotate_key = 'rotate-key'
class IngressType(enum.Enum):
default = 'default'
keepalive_only = 'keepalive-only'
haproxy_standard = 'haproxy-standard'
haproxy_protocol = 'haproxy-protocol'
def canonicalize(self) -> "IngressType":
if self == self.default:
return IngressType(self.haproxy_standard)
return IngressType(self)
def to_format(what: Any, format: Format, many: bool, cls: Any) -> Any:
def to_json_1(obj: Any) -> Any:
if hasattr(obj, 'to_json'):
return obj.to_json()
return obj
def to_json_n(objs: List) -> List:
return [to_json_1(o) for o in objs]
to_json = to_json_n if many else to_json_1
if format == Format.json:
return json.dumps(to_json(what), sort_keys=True)
elif format == Format.json_pretty:
return json.dumps(to_json(what), indent=2, sort_keys=True)
elif format == Format.yaml:
# fun with subinterpreters again. pyyaml depends on object identity.
# as what originates from a different subinterpreter we have to copy things here.
if cls:
flat = to_json(what)
copy = [cls.from_json(o) for o in flat] if many else cls.from_json(flat)
else:
copy = what
def to_yaml_1(obj: Any) -> Any:
if hasattr(obj, 'yaml_representer'):
return obj
return to_json_1(obj)
def to_yaml_n(objs: list) -> list:
return [to_yaml_1(o) for o in objs]
to_yaml = to_yaml_n if many else to_yaml_1
if many:
return yaml.dump_all(to_yaml(copy), default_flow_style=False)
return yaml.dump(to_yaml(copy), default_flow_style=False)
elif format == Format.xml or format == Format.xml_pretty:
raise OrchestratorError(f"format '{format.name}' is not implemented.")
else:
raise OrchestratorError(f'unsupported format type: {format}')
def generate_preview_tables(data: Any, osd_only: bool = False) -> str:
error = [x.get('error') for x in data if x.get('error')]
if error:
return json.dumps(error)
warning = [x.get('warning') for x in data if x.get('warning')]
osd_table = preview_table_osd(data)
service_table = preview_table_services(data)
if osd_only:
tables = f"""
{''.join(warning)}
################
OSDSPEC PREVIEWS
################
{osd_table}
"""
return tables
else:
tables = f"""
{''.join(warning)}
####################
SERVICESPEC PREVIEWS
####################
{service_table}
################
OSDSPEC PREVIEWS
################
{osd_table}
"""
return tables
def preview_table_osd(data: List) -> str:
table = PrettyTable(header_style='upper', title='OSDSPEC PREVIEWS', border=True)
table.field_names = "service name host data db wal".split()
table.align = 'l'
table.left_padding_width = 0
table.right_padding_width = 2
notes = ''
for osd_data in data:
if osd_data.get('service_type') != 'osd':
continue
for host, specs in osd_data.get('data').items():
for spec in specs:
if spec.get('error'):
return spec.get('message')
dg_name = spec.get('osdspec')
if spec.get('notes', []):
notes += '\n'.join(spec.get('notes')) + '\n'
for osd in spec.get('data', []):
db_path = osd.get('block_db', '-')
wal_path = osd.get('block_wal', '-')
block_data = osd.get('data', '')
if not block_data:
continue
table.add_row(('osd', dg_name, host, block_data, db_path, wal_path))
return notes + table.get_string()
def preview_table_services(data: List) -> str:
table = PrettyTable(header_style='upper', title="SERVICESPEC PREVIEW", border=True)
table.field_names = 'SERVICE NAME ADD_TO REMOVE_FROM'.split()
table.align = 'l'
table.left_padding_width = 0
table.right_padding_width = 2
for item in data:
if item.get('warning'):
continue
if item.get('service_type') != 'osd':
table.add_row((item.get('service_type'), item.get('service_name'),
" ".join(item.get('add')), " ".join(item.get('remove'))))
return table.get_string()
class OrchestratorCli(OrchestratorClientMixin, MgrModule,
metaclass=CLICommandMeta):
MODULE_OPTIONS = [
Option(
'orchestrator',
type='str',
default=None,
desc='Orchestrator backend',
enum_allowed=['cephadm', 'rook', 'test_orchestrator'],
runtime=True,
),
Option(
'fail_fs',
type='bool',
default=False,
desc='Fail filesystem for rapid multi-rank mds upgrade'
),
]
NATIVE_OPTIONS = [] # type: List[dict]
def __init__(self, *args: Any, **kwargs: Any) -> None:
super(OrchestratorCli, self).__init__(*args, **kwargs)
self.ident: Set[str] = set()
self.fault: Set[str] = set()
self._load()
self._refresh_health()
def _load(self) -> None:
active = self.get_store('active_devices')
if active:
decoded = json.loads(active)
self.ident = set(decoded.get('ident', []))
self.fault = set(decoded.get('fault', []))
self.log.debug('ident {}, fault {}'.format(self.ident, self.fault))
def _save(self) -> None:
encoded = json.dumps({
'ident': list(self.ident),
'fault': list(self.fault),
})
self.set_store('active_devices', encoded)
def _refresh_health(self) -> None:
h = {}
if self.ident:
h['DEVICE_IDENT_ON'] = {
'severity': 'warning',
'summary': '%d devices have ident light turned on' % len(
self.ident),
'detail': ['{} ident light enabled'.format(d) for d in self.ident]
}
if self.fault:
h['DEVICE_FAULT_ON'] = {
'severity': 'warning',
'summary': '%d devices have fault light turned on' % len(
self.fault),
'detail': ['{} fault light enabled'.format(d) for d in self.ident]
}
self.set_health_checks(h)
def _get_device_locations(self, dev_id):
# type: (str) -> List[DeviceLightLoc]
locs = [d['location'] for d in self.get('devices')['devices'] if d['devid'] == dev_id]
return [DeviceLightLoc(**loc) for loc in sum(locs, [])]
@_cli_read_command(prefix='device ls-lights')
def _device_ls(self) -> HandleCommandResult:
"""List currently active device indicator lights"""
return HandleCommandResult(
stdout=json.dumps({
'ident': list(self.ident),
'fault': list(self.fault)
}, indent=4, sort_keys=True))
def light_on(self, fault_ident, devid):
# type: (str, str) -> HandleCommandResult
assert fault_ident in ("fault", "ident")
locs = self._get_device_locations(devid)
if locs is None:
return HandleCommandResult(stderr='device {} not found'.format(devid),
retval=-errno.ENOENT)
getattr(self, fault_ident).add(devid)
self._save()
self._refresh_health()
completion = self.blink_device_light(fault_ident, True, locs)
return HandleCommandResult(stdout=str(completion.result))
def light_off(self, fault_ident, devid, force):
# type: (str, str, bool) -> HandleCommandResult
assert fault_ident in ("fault", "ident")
locs = self._get_device_locations(devid)
if locs is None:
return HandleCommandResult(stderr='device {} not found'.format(devid),
retval=-errno.ENOENT)
try:
completion = self.blink_device_light(fault_ident, False, locs)
if devid in getattr(self, fault_ident):
getattr(self, fault_ident).remove(devid)
self._save()
self._refresh_health()
return HandleCommandResult(stdout=str(completion.result))
except Exception:
# There are several reasons the try: block might fail:
# 1. the device no longer exist
# 2. the device is no longer known to Ceph
# 3. the host is not reachable
if force and devid in getattr(self, fault_ident):
getattr(self, fault_ident).remove(devid)
self._save()
self._refresh_health()
raise
class DeviceLightEnable(enum.Enum):
on = 'on'
off = 'off'
class DeviceLightType(enum.Enum):
ident = 'ident'
fault = 'fault'
@_cli_write_command(prefix='device light')
def _device_light(self,
enable: DeviceLightEnable,
devid: str,
light_type: DeviceLightType = DeviceLightType.ident,
force: bool = False) -> HandleCommandResult:
"""
Enable or disable the device light. Default type is `ident`
'Usage: device light (on|off) <devid> [ident|fault] [--force]'
"""""
if enable == self.DeviceLightEnable.on:
return self.light_on(light_type.value, devid)
else:
return self.light_off(light_type.value, devid, force)
def _select_orchestrator(self) -> str:
return cast(str, self.get_module_option("orchestrator"))
def _get_fail_fs_value(self) -> bool:
return bool(self.get_module_option("fail_fs"))
@_cli_write_command('orch host add')
def _add_host(self,
hostname: str,
addr: Optional[str] = None,
labels: Optional[List[str]] = None,
maintenance: Optional[bool] = False) -> HandleCommandResult:
"""Add a host"""
_status = 'maintenance' if maintenance else ''
# split multiple labels passed in with --labels=label1,label2
if labels and len(labels) == 1:
labels = labels[0].split(',')
s = HostSpec(hostname=hostname, addr=addr, labels=labels, status=_status)
return self._apply_misc([s], False, Format.plain)
@_cli_write_command('orch host rm')
def _remove_host(self, hostname: str, force: bool = False, offline: bool = False) -> HandleCommandResult:
"""Remove a host"""
completion = self.remove_host(hostname, force, offline)
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_write_command('orch host drain')
def _drain_host(self, hostname: str, force: bool = False) -> HandleCommandResult:
"""drain all daemons from a host"""
completion = self.drain_host(hostname, force)
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_write_command('orch host set-addr')
def _update_set_addr(self, hostname: str, addr: str) -> HandleCommandResult:
"""Update a host address"""
completion = self.update_host_addr(hostname, addr)
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_read_command('orch host ls')
def _get_hosts(self,
format: Format = Format.plain,
host_pattern: str = '',
label: str = '',
host_status: str = '',
detail: bool = False) -> HandleCommandResult:
"""List high level host information"""
completion = self.get_hosts()
hosts = raise_if_exception(completion)
cephadm_active = True if self._select_orchestrator() == "cephadm" else False
show_detail = cephadm_active and detail
filter_spec = PlacementSpec(
host_pattern=host_pattern,
label=label
)
filtered_hosts: List[str] = filter_spec.filter_matching_hostspecs(hosts)
hosts = [h for h in hosts if h.hostname in filtered_hosts]
if host_status:
hosts = [h for h in hosts if h.status.lower() == host_status]
if show_detail:
# switch to a HostDetails based representation
_hosts = []
for h in hosts:
facts_completion = self.get_facts(h.hostname)
host_facts = raise_if_exception(facts_completion)
_hosts.append(HostDetails(host=h, facts=host_facts[0]))
hosts: List[HostDetails] = _hosts # type: ignore [no-redef]
if format != Format.plain:
if show_detail:
output = to_format(hosts, format, many=True, cls=HostDetails)
else:
output = to_format(hosts, format, many=True, cls=HostSpec)
else:
if show_detail:
table_headings = ['HOST', 'ADDR', 'LABELS', 'STATUS',
'VENDOR/MODEL', 'CPU', 'RAM', 'HDD', 'SSD', 'NIC']
else:
table_headings = ['HOST', 'ADDR', 'LABELS', 'STATUS']
table = PrettyTable(
table_headings,
border=False)
table.align = 'l'
table.left_padding_width = 0
table.right_padding_width = 2
for host in natsorted(hosts, key=lambda h: h.hostname):
row = (host.hostname, host.addr, ','.join(
host.labels), host.status.capitalize())
if show_detail and isinstance(host, HostDetails):
row += (host.server, host.cpu_summary, host.ram,
host.hdd_summary, host.ssd_summary, host.nic_count)
table.add_row(row)
output = table.get_string()
if format == Format.plain:
output += f'\n{len(hosts)} hosts in cluster'
if label:
output += f' who had label {label}'
if host_pattern:
output += f' whose hostname matched {host_pattern}'
if host_status:
output += f' with status {host_status}'
return HandleCommandResult(stdout=output)
@_cli_write_command('orch host label add')
def _host_label_add(self, hostname: str, label: str) -> HandleCommandResult:
"""Add a host label"""
completion = self.add_host_label(hostname, label)
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_write_command('orch host label rm')
def _host_label_rm(self, hostname: str, label: str, force: bool = False) -> HandleCommandResult:
"""Remove a host label"""
completion = self.remove_host_label(hostname, label, force)
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_write_command('orch host ok-to-stop')
def _host_ok_to_stop(self, hostname: str) -> HandleCommandResult:
"""Check if the specified host can be safely stopped without reducing availability"""""
completion = self.host_ok_to_stop(hostname)
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_write_command('orch host maintenance enter')
def _host_maintenance_enter(self, hostname: str, force: bool = False, yes_i_really_mean_it: bool = False) -> HandleCommandResult:
"""
Prepare a host for maintenance by shutting down and disabling all Ceph daemons (cephadm only)
"""
completion = self.enter_host_maintenance(hostname, force=force, yes_i_really_mean_it=yes_i_really_mean_it)
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_write_command('orch host maintenance exit')
def _host_maintenance_exit(self, hostname: str) -> HandleCommandResult:
"""
Return a host from maintenance, restarting all Ceph daemons (cephadm only)
"""
completion = self.exit_host_maintenance(hostname)
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_write_command('orch host rescan')
def _host_rescan(self, hostname: str, with_summary: bool = False) -> HandleCommandResult:
"""Perform a disk rescan on a host"""
completion = self.rescan_host(hostname)
raise_if_exception(completion)
if with_summary:
return HandleCommandResult(stdout=completion.result_str())
return HandleCommandResult(stdout=completion.result_str().split('.')[0])
@_cli_read_command('orch device ls')
def _list_devices(self,
hostname: Optional[List[str]] = None,
format: Format = Format.plain,
refresh: bool = False,
wide: bool = False) -> HandleCommandResult:
"""
List devices on a host
"""
# Provide information about storage devices present in cluster hosts
#
# Note: this does not have to be completely synchronous. Slightly out of
# date hardware inventory is fine as long as hardware ultimately appears
# in the output of this command.
nf = InventoryFilter(hosts=hostname) if hostname else None
completion = self.get_inventory(host_filter=nf, refresh=refresh)
inv_hosts = raise_if_exception(completion)
if format != Format.plain:
return HandleCommandResult(stdout=to_format(inv_hosts,
format,
many=True,
cls=InventoryHost))
else:
display_map = {
"Unsupported": "N/A",
"N/A": "N/A",
"On": "On",
"Off": "Off",
True: "Yes",
False: "No",
}
out = []
if wide:
table = PrettyTable(
['HOST', 'PATH', 'TYPE', 'TRANSPORT', 'RPM', 'DEVICE ID', 'SIZE',
'HEALTH', 'IDENT', 'FAULT',
'AVAILABLE', 'REFRESHED', 'REJECT REASONS'],
border=False)
else:
table = PrettyTable(
['HOST', 'PATH', 'TYPE', 'DEVICE ID', 'SIZE',
'AVAILABLE', 'REFRESHED', 'REJECT REASONS'],
border=False)
table.align = 'l'
table._align['SIZE'] = 'r'
table.left_padding_width = 0
table.right_padding_width = 2
now = datetime_now()
for host_ in natsorted(inv_hosts, key=lambda h: h.name): # type: InventoryHost
for d in sorted(host_.devices.devices, key=lambda d: d.path): # type: Device
led_ident = 'N/A'
led_fail = 'N/A'
if d.lsm_data.get('ledSupport', None):
led_ident = d.lsm_data['ledSupport']['IDENTstatus']
led_fail = d.lsm_data['ledSupport']['FAILstatus']
if wide:
table.add_row(
(
host_.name,
d.path,
d.human_readable_type,
d.lsm_data.get('transport', ''),
d.lsm_data.get('rpm', ''),
d.device_id,
format_bytes(d.sys_api.get('size', 0), 5),
d.lsm_data.get('health', ''),
display_map[led_ident],
display_map[led_fail],
display_map[d.available],
nice_delta(now, d.created, ' ago'),
', '.join(d.rejected_reasons)
)
)
else:
table.add_row(
(
host_.name,
d.path,
d.human_readable_type,
d.device_id,
format_bytes(d.sys_api.get('size', 0), 5),
display_map[d.available],
nice_delta(now, d.created, ' ago'),
', '.join(d.rejected_reasons)
)
)
out.append(table.get_string())
return HandleCommandResult(stdout='\n'.join(out))
@_cli_write_command('orch device zap')
def _zap_device(self, hostname: str, path: str, force: bool = False) -> HandleCommandResult:
"""
Zap (erase!) a device so it can be re-used
"""
if not force:
raise OrchestratorError('must pass --force to PERMANENTLY ERASE DEVICE DATA')
completion = self.zap_device(hostname, path)
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_write_command('orch sd dump cert')
def _service_discovery_dump_cert(self) -> HandleCommandResult:
"""
Returns service discovery server root certificate
"""
completion = self.service_discovery_dump_cert()
raise_if_exception(completion)
return HandleCommandResult(stdout=completion.result_str())
@_cli_read_command('orch ls')
def _list_services(self,
service_type: Optional[str] = None,
service_name: Optional[str] = None,
export: bool = False,
format: Format = Format.plain,
refresh: bool = False) -> HandleCommandResult:
"""
List services known to orchestrator
"""
if export and format == Format.plain:
format = Format.yaml
completion = self.describe_service(service_type,
service_name,
refresh=refresh)
services = raise_if_exception(completion)
def ukn(s: Optional[str]) -> str:
return '<unknown>' if s is None else s
# Sort the list for display
services.sort(key=lambda s: (ukn(s.spec.service_name())))
if len(services) == 0:
return HandleCommandResult(stdout="No services reported")
elif format != Format.plain:
with service_spec_allow_invalid_from_json():
if export:
data = [s.spec for s in services if s.deleted is None]
return HandleCommandResult(stdout=to_format(data, format, many=True, cls=ServiceSpec))
else:
return HandleCommandResult(stdout=to_format(services, format, many=True, cls=ServiceDescription))
else:
now = datetime_now()
table = PrettyTable(
[
'NAME', 'PORTS',
'RUNNING', 'REFRESHED', 'AGE',
'PLACEMENT',
],
border=False)
table.align['NAME'] = 'l'
table.align['PORTS'] = 'l'
table.align['RUNNING'] = 'r'
table.align['REFRESHED'] = 'l'
table.align['AGE'] = 'l'
table.align['PLACEMENT'] = 'l'
table.left_padding_width = 0
table.right_padding_width = 2
for s in services:
if not s.spec:
pl = '<no spec>'
elif s.spec.unmanaged:
pl = '<unmanaged>'
else:
pl = s.spec.placement.pretty_str()
if s.deleted:
refreshed = '<deleting>'
else:
refreshed = nice_delta(now, s.last_refresh, ' ago')
if s.spec.service_type == 'osd':
running = str(s.running)
else:
running = '{}/{}'.format(s.running, s.size)
table.add_row((
s.spec.service_name(),
s.get_port_summary(),
running,
refreshed,
nice_delta(now, s.created),
pl,
))
return HandleCommandResult(stdout=table.get_string())
@_cli_read_command('orch ps')
def _list_daemons(self,
hostname: Optional[str] = None,
_end_positional_: int = 0,
service_name: Optional[str] = None,
daemon_type: Optional[str] = None,
daemon_id: Optional[str] = None,
format: Format = Format.plain,
refresh: bool = False) -> HandleCommandResult:
"""
List daemons known to orchestrator
"""
completion = self.list_daemons(service_name,
daemon_type,
daemon_id=daemon_id,
host=hostname,
refresh=refresh)
daemons = raise_if_exception(completion)
def ukn(s: Optional[str]) -> str:
return '<unknown>' if s is None else s
# Sort the list for display
daemons.sort(key=lambda s: (ukn(s.daemon_type), ukn(s.hostname), ukn(s.daemon_id)))
if format != Format.plain:
return HandleCommandResult(stdout=to_format(daemons, format, many=True, cls=DaemonDescription))
else:
if len(daemons) == 0:
return HandleCommandResult(stdout="No daemons reported")
now = datetime_now()
table = PrettyTable(
['NAME', 'HOST', 'PORTS',
'STATUS', 'REFRESHED', 'AGE',
'MEM USE', 'MEM LIM',
'VERSION', 'IMAGE ID', 'CONTAINER ID'],
border=False)
table.align = 'l'
table._align['REFRESHED'] = 'r'
table._align['AGE'] = 'r'
table._align['MEM USE'] = 'r'
table._align['MEM LIM'] = 'r'
table.left_padding_width = 0
table.right_padding_width = 2
for s in natsorted(daemons, key=lambda d: d.name()):
if s.status_desc:
status = s.status_desc
else:
status = DaemonDescriptionStatus.to_str(s.status)
if s.status == DaemonDescriptionStatus.running and s.started: # See DDS.starting
status += ' (%s)' % to_pretty_timedelta(now - s.started)
table.add_row((
s.name(),
ukn(s.hostname),
s.get_port_summary(),
status,
nice_delta(now, s.last_refresh, ' ago'),
nice_delta(now, s.created),
nice_bytes(s.memory_usage),
nice_bytes(s.memory_request),
ukn(s.version),
ukn(s.container_image_id)[0:12],
ukn(s.container_id)))
remove_column = 'CONTAINER ID'
if table.get_string(fields=[remove_column], border=False,
header=False).count('<unknown>') == len(daemons):
try:
table.del_column(remove_column)
except AttributeError as e:
# del_column method was introduced in prettytable 2.0
if str(e) != "del_column":
raise
table.field_names.remove(remove_column)
table._rows = [row[:-1] for row in table._rows]
return HandleCommandResult(stdout=table.get_string())
def _get_credentials(self, username: Optional[str] = None, password: Optional[str] = None, inbuf: Optional[str] = None) -> Tuple[str, str]:
_username = username
_password = password
if inbuf:
try:
credentials = json.loads(inbuf)
_username = credentials['username'].strip()
_password = credentials['password'].strip()
except (KeyError, json.JSONDecodeError):
raise ArgumentError("""
json provided for credentials did not include all necessary fields. Please setup json file as:
{
"username": "USERNAME",
"password": "PASSWORD"
}
""")
if not _username or not _password:
raise ArgumentError("Invalid arguments. Please provide arguments <username> <password> or -i <credentials_json_file>")
return _username, _password
@_cli_write_command('orch prometheus set-credentials')
def _set_prometheus_access_info(self, username: Optional[str] = None, password: Optional[str] = None, inbuf: Optional[str] = None) -> HandleCommandResult:
try:
username, password = self._get_credentials(username, password, inbuf)
completion = self.set_prometheus_access_info(username, password)
result = raise_if_exception(completion)
return HandleCommandResult(stdout=json.dumps(result))
except ArgumentError as e:
return HandleCommandResult(-errno.EINVAL, "", (str(e)))
@_cli_write_command('orch alertmanager set-credentials')
def _set_alertmanager_access_info(self, username: Optional[str] = None, password: Optional[str] = None, inbuf: Optional[str] = None) -> HandleCommandResult:
try:
username, password = self._get_credentials(username, password, inbuf)
completion = self.set_alertmanager_access_info(username, password)
result = raise_if_exception(completion)
return HandleCommandResult(stdout=json.dumps(result))
except ArgumentError as e:
return HandleCommandResult(-errno.EINVAL, "", (str(e)))
@_cli_write_command('orch prometheus get-credentials')
def _get_prometheus_access_info(self) -> HandleCommandResult:
completion = self.get_prometheus_access_info()
access_info = raise_if_exception(completion)
return HandleCommandResult(stdout=json.dumps(access_info))
@_cli_write_command('orch alertmanager get-credentials')
def _get_alertmanager_access_info(self) -> HandleCommandResult:
completion = self.get_alertmanager_access_info()
access_info = raise_if_exception(completion)
return HandleCommandResult(stdout=json.dumps(access_info))
@_cli_write_command('orch apply osd')
def _apply_osd(self,
all_available_devices: bool = False,
format: Format = Format.plain,
unmanaged: Optional[bool] = None,
dry_run: bool = False,
no_overwrite: bool = False,
method: Optional[OSDMethod] = None,
inbuf: Optional[str] = None # deprecated. Was deprecated before Quincy
) -> HandleCommandResult:
"""
Create OSD daemon(s) on all available devices
"""
if inbuf and all_available_devices:
return HandleCommandResult(-errno.EINVAL, '-i infile and --all-available-devices are mutually exclusive')
if not inbuf and not all_available_devices:
# one parameter must be present
return HandleCommandResult(-errno.EINVAL, '--all-available-devices is required')
if inbuf:
if unmanaged is not None:
return HandleCommandResult(-errno.EINVAL, stderr='-i infile and --unmanaged are mutually exclusive')
try:
drivegroups = [_dg for _dg in yaml.safe_load_all(inbuf)]
except yaml.scanner.ScannerError as e:
msg = f"Invalid YAML received : {str(e)}"
self.log.exception(e)
return HandleCommandResult(-errno.EINVAL, stderr=msg)
dg_specs = []
for dg in drivegroups:
spec = DriveGroupSpec.from_json(dg)
if dry_run:
spec.preview_only = True
dg_specs.append(spec)
return self._apply_misc(dg_specs, dry_run, format, no_overwrite)
if all_available_devices:
if unmanaged is None:
unmanaged = False
dg_specs = [
DriveGroupSpec(
service_id='all-available-devices',
placement=PlacementSpec(host_pattern='*'),
data_devices=DeviceSelection(all=True),
unmanaged=unmanaged,
preview_only=dry_run,
method=method
)
]
return self._apply_misc(dg_specs, dry_run, format, no_overwrite)