/
_interface.py
1768 lines (1424 loc) · 59.2 KB
/
_interface.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
"""
ceph-mgr orchestrator interface
Please see the ceph-mgr module developer's guide for more information.
"""
import copy
import functools
import logging
import pickle
import sys
import time
from collections import namedtuple
from functools import wraps, partial
import uuid
import string
import random
import datetime
import copy
import re
import six
import errno
from ceph.deployment import inventory
from mgr_module import MgrModule, PersistentStoreDict, CLICommand, HandleCommandResult
from mgr_util import format_bytes
try:
from ceph.deployment.drive_group import DriveGroupSpec
from typing import TypeVar, Generic, List, Optional, Union, Tuple, Iterator, Callable, Any, \
Type, Sequence, Dict
except ImportError:
pass
logger = logging.getLogger(__name__)
class HostPlacementSpec(namedtuple('HostPlacementSpec', ['hostname', 'network', 'name'])):
def __str__(self):
res = ''
res += self.hostname
if self.network:
res += ':' + self.network
if self.name:
res += '=' + self.name
return res
@classmethod
def parse(cls, host, require_network=True):
# type: (str, bool) -> HostPlacementSpec
"""
Split host into host, network, and (optional) daemon name parts. The network
part can be an IP, CIDR, or ceph addrvec like '[v2:1.2.3.4:3300,v1:1.2.3.4:6789]'.
e.g.,
"myhost"
"myhost=name"
"myhost:1.2.3.4"
"myhost:1.2.3.4=name"
"myhost:1.2.3.0/24"
"myhost:1.2.3.0/24=name"
"myhost:[v2:1.2.3.4:3000]=name"
"myhost:[v2:1.2.3.4:3000,v1:1.2.3.4:6789]=name"
"""
# Matches from start to : or = or until end of string
host_re = r'^(.*?)(:|=|$)'
# Matches from : to = or until end of string
ip_re = r':(.*?)(=|$)'
# Matches from = to end of string
name_re = r'=(.*?)$'
# assign defaults
host_spec = cls('', '', '')
match_host = re.search(host_re, host)
if match_host:
host_spec = host_spec._replace(hostname=match_host.group(1))
name_match = re.search(name_re, host)
if name_match:
host_spec = host_spec._replace(name=name_match.group(1))
ip_match = re.search(ip_re, host)
if ip_match:
host_spec = host_spec._replace(network=ip_match.group(1))
if not require_network:
return host_spec
from ipaddress import ip_network, ip_address
networks = list() # type: List[str]
network = host_spec.network
# in case we have [v2:1.2.3.4:3000,v1:1.2.3.4:6478]
if ',' in network:
networks = [x for x in network.split(',')]
else:
networks.append(network)
for network in networks:
# only if we have versioned network configs
if network.startswith('v') or network.startswith('[v'):
network = network.split(':')[1]
try:
# if subnets are defined, also verify the validity
if '/' in network:
ip_network(six.text_type(network))
else:
ip_address(six.text_type(network))
except ValueError as e:
# logging?
raise e
return host_spec
class OrchestratorError(Exception):
"""
General orchestrator specific error.
Used for deployment, configuration or user errors.
It's not intended for programming errors or orchestrator internal errors.
"""
class NoOrchestrator(OrchestratorError):
"""
No orchestrator in configured.
"""
def __init__(self, msg="No orchestrator configured (try `ceph orch set backend`)"):
super(NoOrchestrator, self).__init__(msg)
class OrchestratorValidationError(OrchestratorError):
"""
Raised when an orchestrator doesn't support a specific feature.
"""
def handle_exception(prefix, cmd_args, desc, perm, func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except (OrchestratorError, ImportError) as e:
# Do not print Traceback for expected errors.
return HandleCommandResult(-errno.ENOENT, stderr=str(e))
except NotImplementedError:
msg = 'This Orchestrator does not support `{}`'.format(prefix)
return HandleCommandResult(-errno.ENOENT, stderr=msg)
# misuse partial to copy `wrapper`
wrapper_copy = partial(wrapper)
wrapper_copy._prefix = prefix # type: ignore
wrapper_copy._cli_command = CLICommand(prefix, cmd_args, desc, perm) # type: ignore
wrapper_copy._cli_command.func = wrapper_copy # type: ignore
return wrapper_copy
def _cli_command(perm):
def inner_cli_command(prefix, cmd_args="", desc=""):
return lambda func: handle_exception(prefix, cmd_args, desc, perm, func)
return inner_cli_command
_cli_read_command = _cli_command('r')
_cli_write_command = _cli_command('rw')
class CLICommandMeta(type):
"""
This is a workaround for the use of a global variable CLICommand.COMMANDS which
prevents modules from importing any other module.
We make use of CLICommand, except for the use of the global variable.
"""
def __init__(cls, name, bases, dct):
super(CLICommandMeta, cls).__init__(name, bases, dct)
dispatch = {} # type: Dict[str, CLICommand]
for v in dct.values():
try:
dispatch[v._prefix] = v._cli_command
except AttributeError:
pass
def handle_command(self, inbuf, cmd):
if cmd['prefix'] not in dispatch:
return self.handle_command(inbuf, cmd)
return dispatch[cmd['prefix']].call(self, cmd, inbuf)
cls.COMMANDS = [cmd.dump_cmd() for cmd in dispatch.values()]
cls.handle_command = handle_command
def _no_result():
return object()
class _Promise(object):
"""
A completion may need multiple promises to be fulfilled. `_Promise` is one
step.
Typically ``Orchestrator`` implementations inherit from this class to
build their own way of finishing a step to fulfil a future.
They are not exposed in the orchestrator interface and can be seen as a
helper to build orchestrator modules.
"""
INITIALIZED = 1 # We have a parent completion and a next completion
RUNNING = 2
FINISHED = 3 # we have a final result
NO_RESULT = _no_result() # type: None
ASYNC_RESULT = object()
def __init__(self,
_first_promise=None, # type: Optional["_Promise"]
value=NO_RESULT, # type: Optional[Any]
on_complete=None, # type: Optional[Callable]
name=None, # type: Optional[str]
):
self._on_complete_ = on_complete
self._name = name
self._next_promise = None # type: Optional[_Promise]
self._state = self.INITIALIZED
self._exception = None # type: Optional[Exception]
# Value of this _Promise. may be an intermediate result.
self._value = value
# _Promise is not a continuation monad, as `_result` is of type
# T instead of (T -> r) -> r. Therefore we need to store the first promise here.
self._first_promise = _first_promise or self # type: '_Promise'
@property
def _exception(self):
# type: () -> Optional[Exception]
return getattr(self, '_exception_', None)
@_exception.setter
def _exception(self, e):
self._exception_ = e
self._serialized_exception_ = pickle.dumps(e) if e is not None else None
@property
def _serialized_exception(self):
# type: () -> Optional[bytes]
return getattr(self, '_serialized_exception_', None)
@property
def _on_complete(self):
# type: () -> Optional[Callable]
# https://github.com/python/mypy/issues/4125
return self._on_complete_
@_on_complete.setter
def _on_complete(self, val):
# type: (Optional[Callable]) -> None
self._on_complete_ = val
def __repr__(self):
name = self._name or getattr(self._on_complete, '__name__', '??') if self._on_complete else 'None'
val = repr(self._value) if self._value is not self.NO_RESULT else 'NA'
return '{}(_s={}, val={}, _on_c={}, id={}, name={}, pr={}, _next={})'.format(
self.__class__, self._state, val, self._on_complete, id(self), name, getattr(next, '_progress_reference', 'NA'), repr(self._next_promise)
)
def pretty_print_1(self):
if self._name:
name = self._name
elif self._on_complete is None:
name = 'lambda x: x'
elif hasattr(self._on_complete, '__name__'):
name = getattr(self._on_complete, '__name__')
else:
name = self._on_complete.__class__.__name__
val = repr(self._value) if self._value not in (self.NO_RESULT, self.ASYNC_RESULT) else '...'
prefix = {
self.INITIALIZED: ' ',
self.RUNNING: ' >>>',
self.FINISHED: '(done)'
}[self._state]
return '{} {}({}),'.format(prefix, name, val)
def then(self, on_complete):
# type: (Any, Callable) -> Any
"""
Call ``on_complete`` as soon as this promise is finalized.
"""
assert self._state in (self.INITIALIZED, self.RUNNING)
if self._on_complete is not None:
assert self._next_promise is None
self._set_next_promise(self.__class__(
_first_promise=self._first_promise,
on_complete=on_complete
))
return self._next_promise
else:
self._on_complete = on_complete
self._set_next_promise(self.__class__(_first_promise=self._first_promise))
return self._next_promise
def _set_next_promise(self, next):
# type: (_Promise) -> None
assert self is not next
assert self._state in (self.INITIALIZED, self.RUNNING)
self._next_promise = next
assert self._next_promise is not None
for p in iter(self._next_promise):
p._first_promise = self._first_promise
def _finalize(self, value=NO_RESULT):
"""
Sets this promise to complete.
Orchestrators may choose to use this helper function.
:param value: new value.
"""
if self._state not in (self.INITIALIZED, self.RUNNING):
raise ValueError('finalize: {} already finished. {}'.format(repr(self), value))
self._state = self.RUNNING
if value is not self.NO_RESULT:
self._value = value
assert self._value is not self.NO_RESULT, repr(self)
if self._on_complete:
try:
next_result = self._on_complete(self._value)
except Exception as e:
self.fail(e)
return
else:
next_result = self._value
if isinstance(next_result, _Promise):
# hack: _Promise is not a continuation monad.
next_result = next_result._first_promise # type: ignore
assert next_result not in self, repr(self._first_promise) + repr(next_result)
assert self not in next_result
next_result._append_promise(self._next_promise)
self._set_next_promise(next_result)
assert self._next_promise
if self._next_promise._value is self.NO_RESULT:
self._next_promise._value = self._value
self.propagate_to_next()
elif next_result is not self.ASYNC_RESULT:
# simple map. simply forward
if self._next_promise:
self._next_promise._value = next_result
else:
# Hack: next_result is of type U, _value is of type T
self._value = next_result # type: ignore
self.propagate_to_next()
else:
# asynchronous promise
pass
def propagate_to_next(self):
self._state = self.FINISHED
logger.debug('finalized {}'.format(repr(self)))
if self._next_promise:
self._next_promise._finalize()
def fail(self, e):
# type: (Exception) -> None
"""
Sets the whole completion to be faild with this exception and end the
evaluation.
"""
if self._state == self.FINISHED:
raise ValueError(
'Invalid State: called fail, but Completion is already finished: {}'.format(str(e)))
assert self._state in (self.INITIALIZED, self.RUNNING)
logger.exception('_Promise failed')
self._exception = e
self._value = 'exception'
if self._next_promise:
self._next_promise.fail(e)
self._state = self.FINISHED
def __contains__(self, item):
return any(item is p for p in iter(self._first_promise))
def __iter__(self):
yield self
elem = self._next_promise
while elem is not None:
yield elem
elem = elem._next_promise
def _append_promise(self, other):
if other is not None:
assert self not in other
assert other not in self
self._last_promise()._set_next_promise(other)
def _last_promise(self):
# type: () -> _Promise
return list(iter(self))[-1]
class ProgressReference(object):
def __init__(self,
message, # type: str
mgr,
completion=None # type: Optional[Callable[[], Completion]]
):
"""
ProgressReference can be used within Completions::
+---------------+ +---------------------------------+
| | then | |
| My Completion | +--> | on_complete=ProgressReference() |
| | | |
+---------------+ +---------------------------------+
See :func:`Completion.with_progress` for an easy way to create
a progress reference
"""
super(ProgressReference, self).__init__()
self.progress_id = str(uuid.uuid4())
self.message = message
self.mgr = mgr
#: The completion can already have a result, before the write
#: operation is effective. progress == 1 means, the services are
#: created / removed.
self.completion = completion # type: Optional[Callable[[], Completion]]
#: if a orchestrator module can provide a more detailed
#: progress information, it needs to also call ``progress.update()``.
self.progress = 0.0
self._completion_has_result = False
self.mgr.all_progress_references.append(self)
def __str__(self):
"""
``__str__()`` is used for determining the message for progress events.
"""
return self.message or super(ProgressReference, self).__str__()
def __call__(self, arg):
self._completion_has_result = True
self.progress = 1.0
return arg
@property
def progress(self):
return self._progress
@progress.setter
def progress(self, progress):
assert progress <= 1.0
self._progress = progress
try:
if self.effective:
self.mgr.remote("progress", "complete", self.progress_id)
self.mgr.all_progress_references = [p for p in self.mgr.all_progress_references if p is not self]
else:
self.mgr.remote("progress", "update", self.progress_id, self.message,
progress,
[("origin", "orchestrator")])
except ImportError:
# If the progress module is disabled that's fine,
# they just won't see the output.
pass
@property
def effective(self):
return self.progress == 1 and self._completion_has_result
def update(self):
def progress_run(progress):
self.progress = progress
if self.completion:
c = self.completion().then(progress_run)
self.mgr.process([c._first_promise])
else:
self.progress = 1
def fail(self):
self._completion_has_result = True
self.progress = 1
class Completion(_Promise):
"""
Combines multiple promises into one overall operation.
Completions are composable by being able to
call one completion from another completion. I.e. making them re-usable
using Promises E.g.::
>>> return Orchestrator().get_hosts().then(self._create_osd)
where ``get_hosts`` returns a Completion of list of hosts and
``_create_osd`` takes a list of hosts.
The concept behind this is to store the computation steps
explicit and then explicitly evaluate the chain:
>>> p = Completion(on_complete=lambda x: x*2).then(on_complete=lambda x: str(x))
... p.finalize(2)
... assert p.result = "4"
or graphically::
+---------------+ +-----------------+
| | then | |
| lambda x: x*x | +--> | lambda x: str(x)|
| | | |
+---------------+ +-----------------+
"""
def __init__(self,
_first_promise=None, # type: Optional["Completion"]
value=_Promise.NO_RESULT, # type: Any
on_complete=None, # type: Optional[Callable]
name=None, # type: Optional[str]
):
super(Completion, self).__init__(_first_promise, value, on_complete, name)
@property
def _progress_reference(self):
# type: () -> Optional[ProgressReference]
if hasattr(self._on_complete, 'progress_id'):
return self._on_complete # type: ignore
return None
@property
def progress_reference(self):
# type: () -> Optional[ProgressReference]
"""
ProgressReference. Marks this completion
as a write completeion.
"""
references = [c._progress_reference for c in iter(self) if c._progress_reference is not None]
if references:
assert len(references) == 1
return references[0]
return None
@classmethod
def with_progress(cls, # type: Any
message, # type: str
mgr,
_first_promise=None, # type: Optional["Completion"]
value=_Promise.NO_RESULT, # type: Any
on_complete=None, # type: Optional[Callable]
calc_percent=None # type: Optional[Callable[[], Any]]
):
# type: (...) -> Any
c = cls(
_first_promise=_first_promise,
value=value,
on_complete=on_complete
).add_progress(message, mgr, calc_percent)
return c._first_promise
def add_progress(self,
message, # type: str
mgr,
calc_percent=None # type: Optional[Callable[[], Any]]
):
return self.then(
on_complete=ProgressReference(
message=message,
mgr=mgr,
completion=calc_percent
)
)
def fail(self, e):
super(Completion, self).fail(e)
if self._progress_reference:
self._progress_reference.fail()
def finalize(self, result=_Promise.NO_RESULT):
if self._first_promise._state == self.INITIALIZED:
self._first_promise._finalize(result)
@property
def result(self):
"""
The result of the operation that we were waited
for. Only valid after calling Orchestrator.process() on this
completion.
"""
last = self._last_promise()
assert last._state == _Promise.FINISHED
return last._value
def result_str(self):
"""Force a string."""
if self.result is None:
return ''
if isinstance(self.result, list):
return '\n'.join(str(x) for x in self.result)
return str(self.result)
@property
def exception(self):
# type: () -> Optional[Exception]
return self._last_promise()._exception
@property
def serialized_exception(self):
# type: () -> Optional[bytes]
return self._last_promise()._serialized_exception
@property
def has_result(self):
# type: () -> bool
"""
Has the operation already a result?
For Write operations, it can already have a
result, if the orchestrator's configuration is
persistently written. Typically this would
indicate that an update had been written to
a manifest, but that the update had not
necessarily been pushed out to the cluster.
:return:
"""
return self._last_promise()._state == _Promise.FINISHED
@property
def is_errored(self):
# type: () -> bool
"""
Has the completion failed. Default implementation looks for
self.exception. Can be overwritten.
"""
return self.exception is not None
@property
def needs_result(self):
# type: () -> bool
"""
Could the external operation be deemed as complete,
or should we wait?
We must wait for a read operation only if it is not complete.
"""
return not self.is_errored and not self.has_result
@property
def is_finished(self):
# type: () -> bool
"""
Could the external operation be deemed as complete,
or should we wait?
We must wait for a read operation only if it is not complete.
"""
return self.is_errored or (self.has_result)
def pretty_print(self):
reprs = '\n'.join(p.pretty_print_1() for p in iter(self._first_promise))
return """<{}>[\n{}\n]""".format(self.__class__.__name__, reprs)
def pretty_print(completions):
# type: (Sequence[Completion]) -> str
return ', '.join(c.pretty_print() for c in completions)
def raise_if_exception(c):
# type: (Completion) -> None
"""
:raises OrchestratorError: Some user error or a config error.
:raises Exception: Some internal error
"""
if c.serialized_exception is not None:
try:
e = pickle.loads(c.serialized_exception)
except (KeyError, AttributeError):
raise Exception('{}: {}'.format(type(c.exception), c.exception))
raise e
class TrivialReadCompletion(Completion):
"""
This is the trivial completion simply wrapping a result.
"""
def __init__(self, result):
super(TrivialReadCompletion, self).__init__()
if result:
self.finalize(result)
def _hide_in_features(f):
f._hide_in_features = True
return f
class Orchestrator(object):
"""
Calls in this class may do long running remote operations, with time
periods ranging from network latencies to package install latencies and large
internet downloads. For that reason, all are asynchronous, and return
``Completion`` objects.
Methods should only return the completion and not directly execute
anything, like network calls. Otherwise the purpose of
those completions is defeated.
Implementations are not required to start work on an operation until
the caller waits on the relevant Completion objects. Callers making
multiple updates should not wait on Completions until they're done
sending operations: this enables implementations to batch up a series
of updates when wait() is called on a set of Completion objects.
Implementations are encouraged to keep reasonably fresh caches of
the status of the system: it is better to serve a stale-but-recent
result read of e.g. device inventory than it is to keep the caller waiting
while you scan hosts every time.
"""
@_hide_in_features
def is_orchestrator_module(self):
"""
Enable other modules to interrogate this module to discover
whether it's usable as an orchestrator module.
Subclasses do not need to override this.
"""
return True
@_hide_in_features
def available(self):
# type: () -> Tuple[bool, str]
"""
Report whether we can talk to the orchestrator. This is the
place to give the user a meaningful message if the orchestrator
isn't running or can't be contacted.
This method may be called frequently (e.g. every page load
to conditionally display a warning banner), so make sure it's
not too expensive. It's okay to give a slightly stale status
(e.g. based on a periodic background ping of the orchestrator)
if that's necessary to make this method fast.
.. note::
`True` doesn't mean that the desired functionality
is actually available in the orchestrator. I.e. this
won't work as expected::
>>> if OrchestratorClientMixin().available()[0]: # wrong.
... OrchestratorClientMixin().get_hosts()
:return: two-tuple of boolean, string
"""
raise NotImplementedError()
@_hide_in_features
def process(self, completions):
# type: (List[Completion]) -> None
"""
Given a list of Completion instances, process any which are
incomplete.
Callers should inspect the detail of each completion to identify
partial completion/progress information, and present that information
to the user.
This method should not block, as this would make it slow to query
a status, while other long running operations are in progress.
"""
raise NotImplementedError()
@_hide_in_features
def get_feature_set(self):
"""Describes which methods this orchestrator implements
.. note::
`True` doesn't mean that the desired functionality
is actually possible in the orchestrator. I.e. this
won't work as expected::
>>> api = OrchestratorClientMixin()
... if api.get_feature_set()['get_hosts']['available']: # wrong.
... api.get_hosts()
It's better to ask for forgiveness instead::
>>> try:
... OrchestratorClientMixin().get_hosts()
... except (OrchestratorError, NotImplementedError):
... ...
:returns: Dict of API method names to ``{'available': True or False}``
"""
module = self.__class__
features = {a: {'available': getattr(Orchestrator, a, None) != getattr(module, a)}
for a in Orchestrator.__dict__
if not a.startswith('_') and not getattr(getattr(Orchestrator, a), '_hide_in_features', False)
}
return features
@_hide_in_features
def cancel_completions(self):
# type: () -> None
"""
Cancels ongoing completions. Unstuck the mgr.
"""
raise NotImplementedError()
def add_host(self, HostSpec):
# type: (HostSpec) -> Completion
"""
Add a host to the orchestrator inventory.
:param host: hostname
"""
raise NotImplementedError()
def remove_host(self, host):
# type: (str) -> Completion
"""
Remove a host from the orchestrator inventory.
:param host: hostname
"""
raise NotImplementedError()
def update_host_addr(self, host, addr):
# type: (str, str) -> Completion
"""
Update a host's address
:param host: hostname
:param addr: address (dns name or IP)
"""
raise NotImplementedError()
def get_hosts(self):
# type: () -> Completion
"""
Report the hosts in the cluster.
The default implementation is extra slow.
:return: list of InventoryNodes
"""
return self.get_inventory()
def add_host_label(self, host, label):
# type: (str, str) -> Completion
"""
Add a host label
"""
raise NotImplementedError()
def remove_host_label(self, host, label):
# type: (str, str) -> Completion
"""
Remove a host label
"""
raise NotImplementedError()
def get_inventory(self, node_filter=None, refresh=False):
# type: (Optional[InventoryFilter], bool) -> Completion
"""
Returns something that was created by `ceph-volume inventory`.
:return: list of InventoryNode
"""
raise NotImplementedError()
def describe_service(self, service_type=None, service_id=None, node_name=None, refresh=False):
# type: (Optional[str], Optional[str], Optional[str], bool) -> Completion
"""
Describe a service (of any kind) that is already configured in
the orchestrator. For example, when viewing an OSD in the dashboard
we might like to also display information about the orchestrator's
view of the service (like the kubernetes pod ID).
When viewing a CephFS filesystem in the dashboard, we would use this
to display the pods being currently run for MDS daemons.
:return: list of ServiceDescription objects.
"""
raise NotImplementedError()
def list_daemons(self, daemon_type=None, daemon_id=None, host=None, refresh=False):
# type: (Optional[str], Optional[str], Optional[str], bool) -> Completion
"""
Describe a daemon (of any kind) that is already configured in
the orchestrator.
:return: list of DaemonDescription objects.
"""
raise NotImplementedError()
def remove_daemons(self, names, force):
# type: (List[str], bool) -> Completion
"""
Remove specific daemon(s).
:return: None
"""
raise NotImplementedError()
def remove_service(self, service_type, service_name=None):
# type: (str, Optional[str]) -> Completion
"""
Remove a service (a collection of daemons).
:return: None
"""
raise NotImplementedError()
def service_action(self, action, service_type, service_name):
# type: (str, str, str) -> Completion
"""
Perform an action (start/stop/reload) on a service (i.e., all daemons
providing the logical service).
:param action: one of "start", "stop", "restart", "redeploy", "reconfig"
:param service_type: e.g. "mds", "rgw", ...
:param service_name: name of logical service ("cephfs", "us-east", ...)
:rtype: Completion
"""
#assert action in ["start", "stop", "reload, "restart", "redeploy"]
raise NotImplementedError()
def daemon_action(self, action, daemon_type, daemon_id):
# type: (str, str, str) -> Completion
"""
Perform an action (start/stop/reload) on a daemon.
:param action: one of "start", "stop", "restart", "redeploy", "reconfig"
:param name: name of daemon
:rtype: Completion
"""
#assert action in ["start", "stop", "reload, "restart", "redeploy"]
raise NotImplementedError()
def create_osds(self, drive_groups):
# type: (List[DriveGroupSpec]) -> Completion
"""
Create one or more OSDs within a single Drive Group.
The principal argument here is the drive_group member
of OsdSpec: other fields are advisory/extensible for any
finer-grained OSD feature enablement (choice of backing store,
compression/encryption, etc).
:param drive_groups: a list of DriveGroupSpec
:param all_hosts: TODO, this is required because the orchestrator methods are not composable
Probably this parameter can be easily removed because each orchestrator can use
the "get_inventory" method and the "drive_group.host_pattern" attribute
to obtain the list of hosts where to apply the operation
"""
raise NotImplementedError()
def blink_device_light(self, ident_fault, on, locations):
# type: (str, bool, List[DeviceLightLoc]) -> Completion
"""
Instructs the orchestrator to enable or disable either the ident or the fault LED.
:param ident_fault: either ``"ident"`` or ``"fault"``
:param on: ``True`` = on.
:param locations: See :class:`orchestrator.DeviceLightLoc`
"""
raise NotImplementedError()
def add_mon(self, spec):
# type: (ServiceSpec) -> Completion
"""Create mon daemon(s)"""
raise NotImplementedError()
def apply_mon(self, spec):
# type: (ServiceSpec) -> Completion
"""Update mon cluster"""
raise NotImplementedError()
def add_mgr(self, spec):
# type: (ServiceSpec) -> Completion
"""Create mgr daemon(s)"""
raise NotImplementedError()