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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
|
import datetime
import enum
from copy import copy
import ipaddress
import itertools
import json
import logging
import math
import socket
from typing import TYPE_CHECKING, Dict, List, Iterator, Optional, Any, Tuple, Set, Mapping, cast, \
NamedTuple, Type
import orchestrator
from ceph.deployment import inventory
from ceph.deployment.service_spec import ServiceSpec, PlacementSpec, TunedProfileSpec, IngressSpec
from ceph.utils import str_to_datetime, datetime_to_str, datetime_now
from orchestrator import OrchestratorError, HostSpec, OrchestratorEvent, service_to_daemon_types
from cephadm.services.cephadmservice import CephadmDaemonDeploySpec
from .utils import resolve_ip, SpecialHostLabels
from .migrations import queue_migrate_nfs_spec, queue_migrate_rgw_spec
if TYPE_CHECKING:
from .module import CephadmOrchestrator
logger = logging.getLogger(__name__)
HOST_CACHE_PREFIX = "host."
SPEC_STORE_PREFIX = "spec."
AGENT_CACHE_PREFIX = 'agent.'
class HostCacheStatus(enum.Enum):
stray = 'stray'
host = 'host'
devices = 'devices'
class Inventory:
"""
The inventory stores a HostSpec for all hosts persistently.
"""
def __init__(self, mgr: 'CephadmOrchestrator'):
self.mgr = mgr
adjusted_addrs = False
def is_valid_ip(ip: str) -> bool:
try:
ipaddress.ip_address(ip)
return True
except ValueError:
return False
# load inventory
i = self.mgr.get_store('inventory')
if i:
self._inventory: Dict[str, dict] = json.loads(i)
# handle old clusters missing 'hostname' key from hostspec
for k, v in self._inventory.items():
if 'hostname' not in v:
v['hostname'] = k
# convert legacy non-IP addr?
if is_valid_ip(str(v.get('addr'))):
continue
if len(self._inventory) > 1:
if k == socket.gethostname():
# Never try to resolve our own host! This is
# fraught and can lead to either a loopback
# address (due to podman's futzing with
# /etc/hosts) or a private IP based on the CNI
# configuration. Instead, wait until the mgr
# fails over to another host and let them resolve
# this host.
continue
ip = resolve_ip(cast(str, v.get('addr')))
else:
# we only have 1 node in the cluster, so we can't
# rely on another host doing the lookup. use the
# IP the mgr binds to.
ip = self.mgr.get_mgr_ip()
if is_valid_ip(ip) and not ip.startswith('127.0.'):
self.mgr.log.info(
f"inventory: adjusted host {v['hostname']} addr '{v['addr']}' -> '{ip}'"
)
v['addr'] = ip
adjusted_addrs = True
if adjusted_addrs:
self.save()
else:
self._inventory = dict()
self._all_known_names: Dict[str, List[str]] = {}
logger.debug('Loaded inventory %s' % self._inventory)
def keys(self) -> List[str]:
return list(self._inventory.keys())
def __contains__(self, host: str) -> bool:
return host in self._inventory or host in itertools.chain.from_iterable(self._all_known_names.values())
def _get_stored_name(self, host: str) -> str:
self.assert_host(host)
if host in self._inventory:
return host
for stored_name, all_names in self._all_known_names.items():
if host in all_names:
return stored_name
return host
def update_known_hostnames(self, hostname: str, shortname: str, fqdn: str) -> None:
for hname in [hostname, shortname, fqdn]:
# if we know the host by any of the names, store the full set of names
# in order to be able to check against those names for matching a host
if hname in self._inventory:
self._all_known_names[hname] = [hostname, shortname, fqdn]
return
logger.debug(f'got hostname set from gather-facts for unknown host: {[hostname, shortname, fqdn]}')
def assert_host(self, host: str) -> None:
if host not in self:
raise OrchestratorError('host %s does not exist' % host)
def add_host(self, spec: HostSpec) -> None:
if spec.hostname in self:
# addr
if self.get_addr(spec.hostname) != spec.addr:
self.set_addr(spec.hostname, spec.addr)
# labels
for label in spec.labels:
self.add_label(spec.hostname, label)
else:
self._inventory[spec.hostname] = spec.to_json()
self.save()
def rm_host(self, host: str) -> None:
host = self._get_stored_name(host)
del self._inventory[host]
self._all_known_names.pop(host, [])
self.save()
def set_addr(self, host: str, addr: str) -> None:
host = self._get_stored_name(host)
self._inventory[host]['addr'] = addr
self.save()
def add_label(self, host: str, label: str) -> None:
host = self._get_stored_name(host)
if 'labels' not in self._inventory[host]:
self._inventory[host]['labels'] = list()
if label not in self._inventory[host]['labels']:
self._inventory[host]['labels'].append(label)
self.save()
def rm_label(self, host: str, label: str) -> None:
host = self._get_stored_name(host)
if 'labels' not in self._inventory[host]:
self._inventory[host]['labels'] = list()
if label in self._inventory[host]['labels']:
self._inventory[host]['labels'].remove(label)
self.save()
def has_label(self, host: str, label: str) -> bool:
host = self._get_stored_name(host)
return (
host in self._inventory
and label in self._inventory[host].get('labels', [])
)
def get_addr(self, host: str) -> str:
host = self._get_stored_name(host)
return self._inventory[host].get('addr', host)
def spec_from_dict(self, info: dict) -> HostSpec:
hostname = info['hostname']
hostname = self._get_stored_name(hostname)
return HostSpec(
hostname,
addr=info.get('addr', hostname),
labels=info.get('labels', []),
status='Offline' if hostname in self.mgr.offline_hosts else info.get('status', ''),
)
def all_specs(self) -> List[HostSpec]:
return list(map(self.spec_from_dict, self._inventory.values()))
def get_host_with_state(self, state: str = "") -> List[str]:
"""return a list of host names in a specific state"""
return [h for h in self._inventory if self._inventory[h].get("status", "").lower() == state]
def save(self) -> None:
self.mgr.set_store('inventory', json.dumps(self._inventory))
class SpecDescription(NamedTuple):
spec: ServiceSpec
rank_map: Optional[Dict[int, Dict[int, Optional[str]]]]
created: datetime.datetime
deleted: Optional[datetime.datetime]
class SpecStore():
def __init__(self, mgr):
# type: (CephadmOrchestrator) -> None
self.mgr = mgr
self._specs = {} # type: Dict[str, ServiceSpec]
# service_name -> rank -> gen -> daemon_id
self._rank_maps = {} # type: Dict[str, Dict[int, Dict[int, Optional[str]]]]
self.spec_created = {} # type: Dict[str, datetime.datetime]
self.spec_deleted = {} # type: Dict[str, datetime.datetime]
self.spec_preview = {} # type: Dict[str, ServiceSpec]
self._needs_configuration: Dict[str, bool] = {}
@property
def all_specs(self) -> Mapping[str, ServiceSpec]:
"""
returns active and deleted specs. Returns read-only dict.
"""
return self._specs
def __contains__(self, name: str) -> bool:
return name in self._specs
def __getitem__(self, name: str) -> SpecDescription:
if name not in self._specs:
raise OrchestratorError(f'Service {name} not found.')
return SpecDescription(self._specs[name],
self._rank_maps.get(name),
self.spec_created[name],
self.spec_deleted.get(name, None))
@property
def active_specs(self) -> Mapping[str, ServiceSpec]:
return {k: v for k, v in self._specs.items() if k not in self.spec_deleted}
def load(self):
# type: () -> None
for k, v in self.mgr.get_store_prefix(SPEC_STORE_PREFIX).items():
service_name = k[len(SPEC_STORE_PREFIX):]
try:
j = cast(Dict[str, dict], json.loads(v))
if (
(self.mgr.migration_current or 0) < 3
and j['spec'].get('service_type') == 'nfs'
):
self.mgr.log.debug(f'found legacy nfs spec {j}')
queue_migrate_nfs_spec(self.mgr, j)
if (
(self.mgr.migration_current or 0) < 6
and j['spec'].get('service_type') == 'rgw'
):
queue_migrate_rgw_spec(self.mgr, j)
spec = ServiceSpec.from_json(j['spec'])
created = str_to_datetime(cast(str, j['created']))
self._specs[service_name] = spec
self.spec_created[service_name] = created
if 'deleted' in j:
deleted = str_to_datetime(cast(str, j['deleted']))
self.spec_deleted[service_name] = deleted
if 'needs_configuration' in j:
self._needs_configuration[service_name] = cast(bool, j['needs_configuration'])
if 'rank_map' in j and isinstance(j['rank_map'], dict):
self._rank_maps[service_name] = {}
for rank_str, m in j['rank_map'].items():
try:
rank = int(rank_str)
except ValueError:
logger.exception(f"failed to parse rank in {j['rank_map']}")
continue
if isinstance(m, dict):
self._rank_maps[service_name][rank] = {}
for gen_str, name in m.items():
try:
gen = int(gen_str)
except ValueError:
logger.exception(f"failed to parse gen in {j['rank_map']}")
continue
if isinstance(name, str) or m is None:
self._rank_maps[service_name][rank][gen] = name
self.mgr.log.debug('SpecStore: loaded spec for %s' % (
service_name))
except Exception as e:
self.mgr.log.warning('unable to load spec for %s: %s' % (
service_name, e))
pass
def save(
self,
spec: ServiceSpec,
update_create: bool = True,
) -> None:
name = spec.service_name()
if spec.preview_only:
self.spec_preview[name] = spec
return None
self._specs[name] = spec
self._needs_configuration[name] = True
if update_create:
self.spec_created[name] = datetime_now()
self._save(name)
def save_rank_map(self,
name: str,
rank_map: Dict[int, Dict[int, Optional[str]]]) -> None:
self._rank_maps[name] = rank_map
self._save(name)
def _save(self, name: str) -> None:
data: Dict[str, Any] = {
'spec': self._specs[name].to_json(),
}
if name in self.spec_created:
data['created'] = datetime_to_str(self.spec_created[name])
if name in self._rank_maps:
data['rank_map'] = self._rank_maps[name]
if name in self.spec_deleted:
data['deleted'] = datetime_to_str(self.spec_deleted[name])
if name in self._needs_configuration:
data['needs_configuration'] = self._needs_configuration[name]
self.mgr.set_store(
SPEC_STORE_PREFIX + name,
json.dumps(data, sort_keys=True),
)
self.mgr.events.for_service(self._specs[name],
OrchestratorEvent.INFO,
'service was created')
def rm(self, service_name: str) -> bool:
if service_name not in self._specs:
return False
if self._specs[service_name].preview_only:
self.finally_rm(service_name)
return True
self.spec_deleted[service_name] = datetime_now()
self.save(self._specs[service_name], update_create=False)
return True
def finally_rm(self, service_name):
# type: (str) -> bool
found = service_name in self._specs
if found:
del self._specs[service_name]
if service_name in self._rank_maps:
del self._rank_maps[service_name]
del self.spec_created[service_name]
if service_name in self.spec_deleted:
del self.spec_deleted[service_name]
if service_name in self._needs_configuration:
del self._needs_configuration[service_name]
self.mgr.set_store(SPEC_STORE_PREFIX + service_name, None)
return found
def get_created(self, spec: ServiceSpec) -> Optional[datetime.datetime]:
return self.spec_created.get(spec.service_name())
def set_unmanaged(self, service_name: str, value: bool) -> str:
if service_name not in self._specs:
return f'No service of name {service_name} found. Check "ceph orch ls" for all known services'
if self._specs[service_name].unmanaged == value:
return f'Service {service_name}{" already " if value else " not "}marked unmanaged. No action taken.'
self._specs[service_name].unmanaged = value
self.save(self._specs[service_name])
return f'Set unmanaged to {str(value)} for service {service_name}'
def needs_configuration(self, name: str) -> bool:
return self._needs_configuration.get(name, False)
def mark_needs_configuration(self, name: str) -> None:
if name in self._specs:
self._needs_configuration[name] = True
self._save(name)
else:
self.mgr.log.warning(f'Attempted to mark unknown service "{name}" as needing configuration')
def mark_configured(self, name: str) -> None:
if name in self._specs:
self._needs_configuration[name] = False
self._save(name)
else:
self.mgr.log.warning(f'Attempted to mark unknown service "{name}" as having been configured')
class ClientKeyringSpec(object):
"""
A client keyring file that we should maintain
"""
def __init__(
self,
entity: str,
placement: PlacementSpec,
mode: Optional[int] = None,
uid: Optional[int] = None,
gid: Optional[int] = None,
) -> None:
self.entity = entity
self.placement = placement
self.mode = mode or 0o600
self.uid = uid or 0
self.gid = gid or 0
def validate(self) -> None:
pass
def to_json(self) -> Dict[str, Any]:
return {
'entity': self.entity,
'placement': self.placement.to_json(),
'mode': self.mode,
'uid': self.uid,
'gid': self.gid,
}
@property
def path(self) -> str:
return f'/etc/ceph/ceph.{self.entity}.keyring'
@classmethod
def from_json(cls: Type, data: dict) -> 'ClientKeyringSpec':
c = data.copy()
if 'placement' in c:
c['placement'] = PlacementSpec.from_json(c['placement'])
_cls = cls(**c)
_cls.validate()
return _cls
class ClientKeyringStore():
"""
Track client keyring files that we are supposed to maintain
"""
def __init__(self, mgr):
# type: (CephadmOrchestrator) -> None
self.mgr: CephadmOrchestrator = mgr
self.mgr = mgr
self.keys: Dict[str, ClientKeyringSpec] = {}
def load(self) -> None:
c = self.mgr.get_store('client_keyrings') or b'{}'
j = json.loads(c)
for e, d in j.items():
self.keys[e] = ClientKeyringSpec.from_json(d)
def save(self) -> None:
data = {
k: v.to_json() for k, v in self.keys.items()
}
self.mgr.set_store('client_keyrings', json.dumps(data))
def update(self, ks: ClientKeyringSpec) -> None:
self.keys[ks.entity] = ks
self.save()
def rm(self, entity: str) -> None:
if entity in self.keys:
del self.keys[entity]
self.save()
class TunedProfileStore():
"""
Store for out tuned profile information
"""
def __init__(self, mgr: "CephadmOrchestrator") -> None:
self.mgr: CephadmOrchestrator = mgr
self.mgr = mgr
self.profiles: Dict[str, TunedProfileSpec] = {}
def __contains__(self, profile: str) -> bool:
return profile in self.profiles
def load(self) -> None:
c = self.mgr.get_store('tuned_profiles') or b'{}'
j = json.loads(c)
for k, v in j.items():
self.profiles[k] = TunedProfileSpec.from_json(v)
self.profiles[k]._last_updated = datetime_to_str(datetime_now())
def exists(self, profile_name: str) -> bool:
return profile_name in self.profiles
def save(self) -> None:
profiles_json = {k: v.to_json() for k, v in self.profiles.items()}
self.mgr.set_store('tuned_profiles', json.dumps(profiles_json))
def add_setting(self, profile: str, setting: str, value: str) -> None:
if profile in self.profiles:
self.profiles[profile].settings[setting] = value
self.profiles[profile]._last_updated = datetime_to_str(datetime_now())
self.save()
else:
logger.error(
f'Attempted to set setting "{setting}" for nonexistent os tuning profile "{profile}"')
def rm_setting(self, profile: str, setting: str) -> None:
if profile in self.profiles:
if setting in self.profiles[profile].settings:
self.profiles[profile].settings.pop(setting, '')
self.profiles[profile]._last_updated = datetime_to_str(datetime_now())
self.save()
else:
logger.error(
f'Attemped to remove nonexistent setting "{setting}" from os tuning profile "{profile}"')
else:
logger.error(
f'Attempted to remove setting "{setting}" from nonexistent os tuning profile "{profile}"')
def add_profile(self, spec: TunedProfileSpec) -> None:
spec._last_updated = datetime_to_str(datetime_now())
self.profiles[spec.profile_name] = spec
self.save()
def rm_profile(self, profile: str) -> None:
if profile in self.profiles:
self.profiles.pop(profile, TunedProfileSpec(''))
else:
logger.error(f'Attempted to remove nonexistent os tuning profile "{profile}"')
self.save()
def last_updated(self, profile: str) -> Optional[datetime.datetime]:
if profile not in self.profiles or not self.profiles[profile]._last_updated:
return None
return str_to_datetime(self.profiles[profile]._last_updated)
def set_last_updated(self, profile: str, new_datetime: datetime.datetime) -> None:
if profile in self.profiles:
self.profiles[profile]._last_updated = datetime_to_str(new_datetime)
def list_profiles(self) -> List[TunedProfileSpec]:
return [p for p in self.profiles.values()]
class HostCache():
"""
HostCache stores different things:
1. `daemons`: Deployed daemons O(daemons)
They're part of the configuration nowadays and need to be
persistent. The name "daemon cache" is unfortunately a bit misleading.
Like for example we really need to know where daemons are deployed on
hosts that are offline.
2. `devices`: ceph-volume inventory cache O(hosts)
As soon as this is populated, it becomes more or less read-only.
3. `networks`: network interfaces for each host. O(hosts)
This is needed in order to deploy MONs. As this is mostly read-only.
4. `last_client_files` O(hosts)
Stores the last digest and owner/mode for files we've pushed to /etc/ceph
(ceph.conf or client keyrings).
5. `scheduled_daemon_actions`: O(daemons)
Used to run daemon actions after deploying a daemon. We need to
store it persistently, in order to stay consistent across
MGR failovers.
"""
def __init__(self, mgr):
# type: (CephadmOrchestrator) -> None
self.mgr: CephadmOrchestrator = mgr
self.daemons = {} # type: Dict[str, Dict[str, orchestrator.DaemonDescription]]
self._tmp_daemons = {} # type: Dict[str, Dict[str, orchestrator.DaemonDescription]]
self.last_daemon_update = {} # type: Dict[str, datetime.datetime]
self.devices = {} # type: Dict[str, List[inventory.Device]]
self.facts = {} # type: Dict[str, Dict[str, Any]]
self.last_facts_update = {} # type: Dict[str, datetime.datetime]
self.last_autotune = {} # type: Dict[str, datetime.datetime]
self.osdspec_previews = {} # type: Dict[str, List[Dict[str, Any]]]
self.osdspec_last_applied = {} # type: Dict[str, Dict[str, datetime.datetime]]
self.networks = {} # type: Dict[str, Dict[str, Dict[str, List[str]]]]
self.last_network_update = {} # type: Dict[str, datetime.datetime]
self.last_device_update = {} # type: Dict[str, datetime.datetime]
self.last_device_change = {} # type: Dict[str, datetime.datetime]
self.last_tuned_profile_update = {} # type: Dict[str, datetime.datetime]
self.daemon_refresh_queue = [] # type: List[str]
self.device_refresh_queue = [] # type: List[str]
self.network_refresh_queue = [] # type: List[str]
self.osdspec_previews_refresh_queue = [] # type: List[str]
# host -> daemon name -> dict
self.daemon_config_deps = {} # type: Dict[str, Dict[str, Dict[str,Any]]]
self.last_host_check = {} # type: Dict[str, datetime.datetime]
self.loading_osdspec_preview = set() # type: Set[str]
self.last_client_files: Dict[str, Dict[str, Tuple[str, int, int, int]]] = {}
self.registry_login_queue: Set[str] = set()
self.scheduled_daemon_actions: Dict[str, Dict[str, str]] = {}
self.metadata_up_to_date = {} # type: Dict[str, bool]
def load(self):
# type: () -> None
for k, v in self.mgr.get_store_prefix(HOST_CACHE_PREFIX).items():
host = k[len(HOST_CACHE_PREFIX):]
if self._get_host_cache_entry_status(host) != HostCacheStatus.host:
if self._get_host_cache_entry_status(host) == HostCacheStatus.devices:
continue
self.mgr.log.warning('removing stray HostCache host record %s' % (
host))
self.mgr.set_store(k, None)
try:
j = json.loads(v)
if 'last_device_update' in j:
self.last_device_update[host] = str_to_datetime(j['last_device_update'])
else:
self.device_refresh_queue.append(host)
if 'last_device_change' in j:
self.last_device_change[host] = str_to_datetime(j['last_device_change'])
# for services, we ignore the persisted last_*_update
# and always trigger a new scrape on mgr restart.
self.daemon_refresh_queue.append(host)
self.network_refresh_queue.append(host)
self.daemons[host] = {}
self.osdspec_previews[host] = []
self.osdspec_last_applied[host] = {}
self.networks[host] = {}
self.daemon_config_deps[host] = {}
for name, d in j.get('daemons', {}).items():
self.daemons[host][name] = \
orchestrator.DaemonDescription.from_json(d)
self.devices[host] = []
# still want to check old device location for upgrade scenarios
for d in j.get('devices', []):
self.devices[host].append(inventory.Device.from_json(d))
self.devices[host] += self.load_host_devices(host)
self.networks[host] = j.get('networks_and_interfaces', {})
self.osdspec_previews[host] = j.get('osdspec_previews', {})
self.last_client_files[host] = j.get('last_client_files', {})
for name, ts in j.get('osdspec_last_applied', {}).items():
self.osdspec_last_applied[host][name] = str_to_datetime(ts)
for name, d in j.get('daemon_config_deps', {}).items():
self.daemon_config_deps[host][name] = {
'deps': d.get('deps', []),
'last_config': str_to_datetime(d['last_config']),
}
if 'last_host_check' in j:
self.last_host_check[host] = str_to_datetime(j['last_host_check'])
if 'last_tuned_profile_update' in j:
self.last_tuned_profile_update[host] = str_to_datetime(
j['last_tuned_profile_update'])
self.registry_login_queue.add(host)
self.scheduled_daemon_actions[host] = j.get('scheduled_daemon_actions', {})
self.metadata_up_to_date[host] = j.get('metadata_up_to_date', False)
self.mgr.log.debug(
'HostCache.load: host %s has %d daemons, '
'%d devices, %d networks' % (
host, len(self.daemons[host]), len(self.devices[host]),
len(self.networks[host])))
except Exception as e:
self.mgr.log.warning('unable to load cached state for %s: %s' % (
host, e))
pass
def _get_host_cache_entry_status(self, host: str) -> HostCacheStatus:
# return whether a host cache entry in the config-key
# store is for a host, a set of devices or is stray.
# for a host, the entry name will match a hostname in our
# inventory. For devices, it will be formatted
# <hostname>.devices.<integer> where <hostname> is
# in out inventory. If neither case applies, it is stray
if host in self.mgr.inventory:
return HostCacheStatus.host
try:
# try stripping off the ".devices.<integer>" and see if we get
# a host name that matches our inventory
actual_host = '.'.join(host.split('.')[:-2])
return HostCacheStatus.devices if actual_host in self.mgr.inventory else HostCacheStatus.stray
except Exception:
return HostCacheStatus.stray
def update_host_daemons(self, host, dm):
# type: (str, Dict[str, orchestrator.DaemonDescription]) -> None
self.daemons[host] = dm
self._tmp_daemons.pop(host, {})
self.last_daemon_update[host] = datetime_now()
def append_tmp_daemon(self, host: str, dd: orchestrator.DaemonDescription) -> None:
# for storing empty daemon descriptions representing daemons we have
# just deployed but not yet had the chance to pick up in a daemon refresh
# _tmp_daemons is cleared for a host upon receiving a real update of the
# host's dameons
if host not in self._tmp_daemons:
self._tmp_daemons[host] = {}
self._tmp_daemons[host][dd.name()] = dd
def update_host_facts(self, host, facts):
# type: (str, Dict[str, Dict[str, Any]]) -> None
self.facts[host] = facts
hostnames: List[str] = []
for k in ['hostname', 'shortname', 'fqdn']:
v = facts.get(k, '')
hostnames.append(v if isinstance(v, str) else '')
self.mgr.inventory.update_known_hostnames(hostnames[0], hostnames[1], hostnames[2])
self.last_facts_update[host] = datetime_now()
def update_autotune(self, host: str) -> None:
self.last_autotune[host] = datetime_now()
def invalidate_autotune(self, host: str) -> None:
if host in self.last_autotune:
del self.last_autotune[host]
def devices_changed(self, host: str, b: List[inventory.Device]) -> bool:
old_devs = inventory.Devices(self.devices[host])
new_devs = inventory.Devices(b)
# relying on Devices class __eq__ function here
if old_devs != new_devs:
self.mgr.log.info("Detected new or changed devices on %s" % host)
return True
return False
def update_host_devices(
self,
host: str,
dls: List[inventory.Device],
) -> None:
if (
host not in self.devices
or host not in self.last_device_change
or self.devices_changed(host, dls)
):
self.last_device_change[host] = datetime_now()
self.last_device_update[host] = datetime_now()
self.devices[host] = dls
def update_host_networks(
self,
host: str,
nets: Dict[str, Dict[str, List[str]]]
) -> None:
self.networks[host] = nets
self.last_network_update[host] = datetime_now()
def update_daemon_config_deps(self, host: str, name: str, deps: List[str], stamp: datetime.datetime) -> None:
self.daemon_config_deps[host][name] = {
'deps': deps,
'last_config': stamp,
}
def update_last_host_check(self, host):
# type: (str) -> None
self.last_host_check[host] = datetime_now()
def update_osdspec_last_applied(self, host, service_name, ts):
# type: (str, str, datetime.datetime) -> None
self.osdspec_last_applied[host][service_name] = ts
def update_client_file(self,
host: str,
path: str,
digest: str,
mode: int,
uid: int,
gid: int) -> None:
if host not in self.last_client_files:
self.last_client_files[host] = {}
self.last_client_files[host][path] = (digest, mode, uid, gid)
def removed_client_file(self, host: str, path: str) -> None:
if (
host in self.last_client_files
and path in self.last_client_files[host]
):
del self.last_client_files[host][path]
def prime_empty_host(self, host):
# type: (str) -> None
"""
Install an empty entry for a host
"""
self.daemons[host] = {}
self.devices[host] = []
self.networks[host] = {}
self.osdspec_previews[host] = []
self.osdspec_last_applied[host] = {}
self.daemon_config_deps[host] = {}
self.daemon_refresh_queue.append(host)
self.device_refresh_queue.append(host)
self.network_refresh_queue.append(host)
self.osdspec_previews_refresh_queue.append(host)
self.registry_login_queue.add(host)
self.last_client_files[host] = {}
def refresh_all_host_info(self, host):
# type: (str) -> None
self.last_host_check.pop(host, None)
self.daemon_refresh_queue.append(host)
self.registry_login_queue.add(host)
self.device_refresh_queue.append(host)
self.last_facts_update.pop(host, None)
self.osdspec_previews_refresh_queue.append(host)
self.last_autotune.pop(host, None)
def invalidate_host_daemons(self, host):
# type: (str) -> None
self.daemon_refresh_queue.append(host)
if host in self.last_daemon_update:
del self.last_daemon_update[host]
self.mgr.event.set()
def invalidate_host_devices(self, host):
# type: (str) -> None
self.device_refresh_queue.append(host)
if host in self.last_device_update:
del self.last_device_update[host]
self.mgr.event.set()
def invalidate_host_networks(self, host):
# type: (str) -> None
self.network_refresh_queue.append(host)
if host in self.last_network_update:
del self.last_network_update[host]
self.mgr.event.set()
def distribute_new_registry_login_info(self) -> None:
self.registry_login_queue = set(self.mgr.inventory.keys())
def save_host(self, host: str) -> None:
j: Dict[str, Any] = {
'daemons': {},
'devices': [],
'osdspec_previews': [],
'osdspec_last_applied': {},
'daemon_config_deps': {},
}
if host in self.last_daemon_update:
j['last_daemon_update'] = datetime_to_str(self.last_daemon_update[host])
if host in self.last_device_update:
j['last_device_update'] = datetime_to_str(self.last_device_update[host])
if host in self.last_network_update:
j['last_network_update'] = datetime_to_str(self.last_network_update[host])
if host in self.last_device_change:
j['last_device_change'] = datetime_to_str(self.last_device_change[host])
if host in self.last_tuned_profile_update:
j['last_tuned_profile_update'] = datetime_to_str(self.last_tuned_profile_update[host])
if host in self.daemons:
for name, dd in self.daemons[host].items():
j['daemons'][name] = dd.to_json()
if host in self.networks:
j['networks_and_interfaces'] = self.networks[host]
if host in self.daemon_config_deps:
for name, depi in self.daemon_config_deps[host].items():
j['daemon_config_deps'][name] = {
'deps': depi.get('deps', []),
'last_config': datetime_to_str(depi['last_config']),
}
if host in self.osdspec_previews and self.osdspec_previews[host]:
j['osdspec_previews'] = self.osdspec_previews[host]
if host in self.osdspec_last_applied:
for name, ts in self.osdspec_last_applied[host].items():
j['osdspec_last_applied'][name] = datetime_to_str(ts)
if host in self.last_host_check:
j['last_host_check'] = datetime_to_str(self.last_host_check[host])
if host in self.last_client_files:
j['last_client_files'] = self.last_client_files[host]
if host in self.scheduled_daemon_actions:
j['scheduled_daemon_actions'] = self.scheduled_daemon_actions[host]
if host in self.metadata_up_to_date:
j['metadata_up_to_date'] = self.metadata_up_to_date[host]
if host in self.devices:
self.save_host_devices(host)
self.mgr.set_store(HOST_CACHE_PREFIX + host, json.dumps(j))
def save_host_devices(self, host: str) -> None:
if host not in self.devices or not self.devices[host]:
logger.debug(f'Host {host} has no devices to save')
return
devs: List[Dict[str, Any]] = []
for d in self.devices[host]:
devs.append(d.to_json())
def byte_len(s: str) -> int:
return len(s.encode('utf-8'))
dev_cache_counter: int = 0
cache_size: int = self.mgr.get_foreign_ceph_option('mon', 'mon_config_key_max_entry_size')
if cache_size is not None and cache_size != 0 and byte_len(json.dumps(devs)) > cache_size - 1024:
# no guarantee all device entries take up the same amount of space
# splitting it up so there's one more entry than we need should be fairly
# safe and save a lot of extra logic checking sizes
cache_entries_needed = math.ceil(byte_len(json.dumps(devs)) / cache_size) + 1
dev_sublist_size = math.ceil(len(devs) / cache_entries_needed)
dev_lists: List[List[Dict[str, Any]]] = [devs[i:i + dev_sublist_size]
for i in range(0, len(devs), dev_sublist_size)]
for dev_list in dev_lists:
dev_dict: Dict[str, Any] = {'devices': dev_list}
if dev_cache_counter == 0:
dev_dict.update({'entries': len(dev_lists)})
self.mgr.set_store(HOST_CACHE_PREFIX + host + '.devices.'
+ str(dev_cache_counter), json.dumps(dev_dict))
dev_cache_counter += 1
else:
self.mgr.set_store(HOST_CACHE_PREFIX + host + '.devices.'
+ str(dev_cache_counter), json.dumps({'devices': devs, 'entries': 1}))
def load_host_devices(self, host: str) -> List[inventory.Device]:
dev_cache_counter: int = 0
devs: List[Dict[str, Any]] = []
dev_entries: int = 0
try:
# number of entries for the host's devices should be in
# the "entries" field of the first entry
dev_entries = json.loads(self.mgr.get_store(
HOST_CACHE_PREFIX + host + '.devices.0')).get('entries')
except Exception:
logger.debug(f'No device entries found for host {host}')
for i in range(dev_entries):
try:
new_devs = json.loads(self.mgr.get_store(
HOST_CACHE_PREFIX + host + '.devices.' + str(i))).get('devices', [])
if len(new_devs) > 0:
# verify list contains actual device objects by trying to load one from json
inventory.Device.from_json(new_devs[0])
# if we didn't throw an Exception on above line, we can add the devices
devs = devs + new_devs
dev_cache_counter += 1
except Exception as e:
logger.error(('Hit exception trying to load devices from '
+ f'{HOST_CACHE_PREFIX + host + ".devices." + str(dev_cache_counter)} in key store: {e}'))
return []
return [inventory.Device.from_json(d) for d in devs]
def rm_host(self, host):
# type: (str) -> None
if host in self.daemons:
del self.daemons[host]
if host in self.devices:
del self.devices[host]
if host in self.facts:
del self.facts[host]
if host in self.last_facts_update:
del self.last_facts_update[host]
if host in self.last_autotune:
del self.last_autotune[host]
if host in self.osdspec_previews:
del self.osdspec_previews[host]
if host in self.osdspec_last_applied:
del self.osdspec_last_applied[host]
if host in self.loading_osdspec_preview:
self.loading_osdspec_preview.remove(host)
if host in self.networks:
del self.networks[host]
if host in self.last_daemon_update:
del self.last_daemon_update[host]
if host in self.last_device_update:
del self.last_device_update[host]
if host in self.last_network_update:
del self.last_network_update[host]
if host in self.last_device_change:
del self.last_device_change[host]
if host in self.last_tuned_profile_update:
del self.last_tuned_profile_update[host]
if host in self.daemon_config_deps:
del self.daemon_config_deps[host]
if host in self.scheduled_daemon_actions:
del self.scheduled_daemon_actions[host]
if host in self.last_client_files:
del self.last_client_files[host]
self.mgr.set_store(HOST_CACHE_PREFIX + host, None)
def get_hosts(self):
# type: () -> List[str]
return list(self.daemons)
def get_schedulable_hosts(self) -> List[HostSpec]:
"""
Returns all usable hosts that went through _refresh_host_daemons().
This mitigates a potential race, where new host was added *after*
``_refresh_host_daemons()`` was called, but *before*
``_apply_all_specs()`` was called. thus we end up with a hosts
where daemons might be running, but we have not yet detected them.
"""
return [
h for h in self.mgr.inventory.all_specs()
if (
self.host_had_daemon_refresh(h.hostname)
and SpecialHostLabels.DRAIN_DAEMONS not in h.labels
)
]
def get_conf_keyring_available_hosts(self) -> List[HostSpec]:
"""
Returns all hosts without the drain conf and keyrings
label (SpecialHostLabels.DRAIN_CONF_KEYRING) that have
had a refresh. That is equivalent to all hosts we
consider eligible for deployment of conf and keyring files
Any host without that label is considered fair game for
a client keyring spec to match. However, we want to still
wait for refresh here so that we know what keyrings we've
already deployed here
"""
return [
h for h in self.mgr.inventory.all_specs()
if (
self.host_had_daemon_refresh(h.hostname)
and SpecialHostLabels.DRAIN_CONF_KEYRING not in h.labels
)
]
def get_non_draining_hosts(self) -> List[HostSpec]:
"""
Returns all hosts that do not have drain daemon label
(SpecialHostLabels.DRAIN_DAEMONS).
Useful for the agent who needs this specific list rather than the
schedulable_hosts since the agent needs to be deployed on hosts with
no daemon refresh
"""
return [
h for h in self.mgr.inventory.all_specs() if SpecialHostLabels.DRAIN_DAEMONS not in h.labels
]
def get_draining_hosts(self) -> List[HostSpec]:
"""
Returns all hosts that have the drain daemons label (SpecialHostLabels.DRAIN_DAEMONS)
and therefore should have no daemons placed on them, but are potentially still reachable
"""
return [
h for h in self.mgr.inventory.all_specs() if SpecialHostLabels.DRAIN_DAEMONS in h.labels
]
def get_conf_keyring_draining_hosts(self) -> List[HostSpec]:
"""
Returns all hosts that have drain conf and keyrings label (SpecialHostLabels.DRAIN_CONF_KEYRING)
and therefore should have no config files or client keyring placed on them, but are
potentially still reachable
"""
return [
h for h in self.mgr.inventory.all_specs() if SpecialHostLabels.DRAIN_CONF_KEYRING in h.labels
]
def get_unreachable_hosts(self) -> List[HostSpec]:
"""
Return all hosts that are offline or in maintenance mode.
The idea is we should not touch the daemons on these hosts (since
in theory the hosts are inaccessible so we CAN'T touch them) but
we still want to count daemons that exist on these hosts toward the
placement so daemons on these hosts aren't just moved elsewhere
"""
return [
h for h in self.mgr.inventory.all_specs()
if (
h.status.lower() in ['maintenance', 'offline']
or h.hostname in self.mgr.offline_hosts
)
]
def is_host_unreachable(self, hostname: str) -> bool:
# take hostname and return if it matches the hostname of an unreachable host
return hostname in [h.hostname for h in self.get_unreachable_hosts()]
def is_host_schedulable(self, hostname: str) -> bool:
# take hostname and return if it matches the hostname of a schedulable host
return hostname in [h.hostname for h in self.get_schedulable_hosts()]
def is_host_draining(self, hostname: str) -> bool:
# take hostname and return if it matches the hostname of a draining host
return hostname in [h.hostname for h in self.get_draining_hosts()]
def get_facts(self, host: str) -> Dict[str, Any]:
return self.facts.get(host, {})
def _get_daemons(self) -> Iterator[orchestrator.DaemonDescription]:
for dm in self.daemons.copy().values():
yield from dm.values()
def _get_tmp_daemons(self) -> Iterator[orchestrator.DaemonDescription]:
for dm in self._tmp_daemons.copy().values():
yield from dm.values()
def get_daemons(self):
# type: () -> List[orchestrator.DaemonDescription]
return list(self._get_daemons())
def get_error_daemons(self) -> List[orchestrator.DaemonDescription]:
r = []
for dd in self._get_daemons():
if dd.status is not None and dd.status == orchestrator.DaemonDescriptionStatus.error:
r.append(dd)
return r
def get_daemons_by_host(self, host: str) -> List[orchestrator.DaemonDescription]:
return list(self.daemons.get(host, {}).values())
def get_daemon(self, daemon_name: str, host: Optional[str] = None) -> orchestrator.DaemonDescription:
assert not daemon_name.startswith('ha-rgw.')
dds = self.get_daemons_by_host(host) if host else self._get_daemons()
for dd in dds:
if dd.name() == daemon_name:
return dd
raise orchestrator.OrchestratorError(f'Unable to find {daemon_name} daemon(s)')
def has_daemon(self, daemon_name: str, host: Optional[str] = None) -> bool:
try:
self.get_daemon(daemon_name, host)
except orchestrator.OrchestratorError:
return False
return True
def get_daemons_with_volatile_status(self) -> Iterator[Tuple[str, Dict[str, orchestrator.DaemonDescription]]]:
def alter(host: str, dd_orig: orchestrator.DaemonDescription) -> orchestrator.DaemonDescription:
dd = copy(dd_orig)
if host in self.mgr.offline_hosts:
dd.status = orchestrator.DaemonDescriptionStatus.error
dd.status_desc = 'host is offline'
elif self.mgr.inventory._inventory[host].get("status", "").lower() == "maintenance":
# We do not refresh daemons on hosts in maintenance mode, so stored daemon statuses
# could be wrong. We must assume maintenance is working and daemons are stopped
dd.status = orchestrator.DaemonDescriptionStatus.stopped
dd.events = self.mgr.events.get_for_daemon(dd.name())
return dd
for host, dm in self.daemons.copy().items():
yield host, {name: alter(host, d) for name, d in dm.items()}
def get_daemons_by_service(self, service_name):
# type: (str) -> List[orchestrator.DaemonDescription]
assert not service_name.startswith('keepalived.')
assert not service_name.startswith('haproxy.')
return list(dd for dd in self._get_daemons() if dd.service_name() == service_name)
def get_related_service_daemons(self, service_spec: ServiceSpec) -> Optional[List[orchestrator.DaemonDescription]]:
if service_spec.service_type == 'ingress':
dds = list(dd for dd in self._get_daemons() if dd.service_name() == cast(IngressSpec, service_spec).backend_service)
dds += list(dd for dd in self._get_tmp_daemons() if dd.service_name() == cast(IngressSpec, service_spec).backend_service)
logger.debug(f'Found related daemons {dds} for service {service_spec.service_name()}')
return dds
else:
for ingress_spec in [cast(IngressSpec, s) for s in self.mgr.spec_store.active_specs.values() if s.service_type == 'ingress']:
if ingress_spec.backend_service == service_spec.service_name():
dds = list(dd for dd in self._get_daemons() if dd.service_name() == ingress_spec.service_name())
dds += list(dd for dd in self._get_tmp_daemons() if dd.service_name() == ingress_spec.service_name())
logger.debug(f'Found related daemons {dds} for service {service_spec.service_name()}')
return dds
return None
def get_daemons_by_type(self, service_type: str, host: str = '') -> List[orchestrator.DaemonDescription]:
assert service_type not in ['keepalived', 'haproxy']
daemons = self.daemons[host].values() if host else self._get_daemons()
return [d for d in daemons if d.daemon_type in service_to_daemon_types(service_type)]
def get_daemon_types(self, hostname: str) -> Set[str]:
"""Provide a list of the types of daemons on the host"""
return cast(Set[str], {d.daemon_type for d in self.daemons[hostname].values()})
def get_daemon_names(self):
# type: () -> List[str]
return [d.name() for d in self._get_daemons()]
def get_daemon_last_config_deps(self, host: str, name: str) -> Tuple[Optional[List[str]], Optional[datetime.datetime]]:
if host in self.daemon_config_deps:
if name in self.daemon_config_deps[host]:
return self.daemon_config_deps[host][name].get('deps', []), \
self.daemon_config_deps[host][name].get('last_config', None)
return None, None
def get_host_client_files(self, host: str) -> Dict[str, Tuple[str, int, int, int]]:
return self.last_client_files.get(host, {})
def host_needs_daemon_refresh(self, host):
# type: (str) -> bool
if host in self.mgr.offline_hosts:
logger.debug(f'Host "{host}" marked as offline. Skipping daemon refresh')
return False
if host in self.daemon_refresh_queue:
self.daemon_refresh_queue.remove(host)
return True
cutoff = datetime_now() - datetime.timedelta(
seconds=self.mgr.daemon_cache_timeout)
if host not in self.last_daemon_update or self.last_daemon_update[host] < cutoff:
return True
if not self.mgr.cache.host_metadata_up_to_date(host):
return True
return False
def host_needs_facts_refresh(self, host):
# type: (str) -> bool
if host in self.mgr.offline_hosts:
logger.debug(f'Host "{host}" marked as offline. Skipping gather facts refresh')
return False
cutoff = datetime_now() - datetime.timedelta(
seconds=self.mgr.facts_cache_timeout)
if host not in self.last_facts_update or self.last_facts_update[host] < cutoff:
return True
if not self.mgr.cache.host_metadata_up_to_date(host):
return True
return False
def host_needs_autotune_memory(self, host):
# type: (str) -> bool
if host in self.mgr.offline_hosts:
logger.debug(f'Host "{host}" marked as offline. Skipping autotune')
return False
cutoff = datetime_now() - datetime.timedelta(
seconds=self.mgr.autotune_interval)
if host not in self.last_autotune or self.last_autotune[host] < cutoff:
return True
return False
def host_needs_tuned_profile_update(self, host: str, profile: str) -> bool:
if host in self.mgr.offline_hosts:
logger.debug(f'Host "{host}" marked as offline. Cannot apply tuned profile')
return False
if profile not in self.mgr.tuned_profiles:
logger.debug(
f'Cannot apply tuned profile {profile} on host {host}. Profile does not exist')
return False
if host not in self.last_tuned_profile_update:
return True
last_profile_update = self.mgr.tuned_profiles.last_updated(profile)
if last_profile_update is None:
self.mgr.tuned_profiles.set_last_updated(profile, datetime_now())
return True
if self.last_tuned_profile_update[host] < last_profile_update:
return True
return False
def host_had_daemon_refresh(self, host: str) -> bool:
"""
... at least once.
"""
if host in self.last_daemon_update:
return True
if host not in self.daemons:
return False
return bool(self.daemons[host])
def host_needs_device_refresh(self, host):
# type: (str) -> bool
if host in self.mgr.offline_hosts:
logger.debug(f'Host "{host}" marked as offline. Skipping device refresh')
return False
if host in self.device_refresh_queue:
self.device_refresh_queue.remove(host)
return True
cutoff = datetime_now() - datetime.timedelta(
seconds=self.mgr.device_cache_timeout)
if host not in self.last_device_update or self.last_device_update[host] < cutoff:
return True
if not self.mgr.cache.host_metadata_up_to_date(host):
return True
return False
def host_needs_network_refresh(self, host):
# type: (str) -> bool
if host in self.mgr.offline_hosts:
logger.debug(f'Host "{host}" marked as offline. Skipping network refresh')
return False
if host in self.network_refresh_queue:
self.network_refresh_queue.remove(host)
return True
cutoff = datetime_now() - datetime.timedelta(
seconds=self.mgr.device_cache_timeout)
if host not in self.last_network_update or self.last_network_update[host] < cutoff:
return True
if not self.mgr.cache.host_metadata_up_to_date(host):
return True
return False
def host_needs_osdspec_preview_refresh(self, host: str) -> bool:
if host in self.mgr.offline_hosts:
logger.debug(f'Host "{host}" marked as offline. Skipping osdspec preview refresh')
return False
if host in self.osdspec_previews_refresh_queue:
self.osdspec_previews_refresh_queue.remove(host)
return True
# Since this is dependent on other factors (device and spec) this does not need
# to be updated periodically.
return False
def host_needs_check(self, host):
# type: (str) -> bool
cutoff = datetime_now() - datetime.timedelta(
seconds=self.mgr.host_check_interval)
return host not in self.last_host_check or self.last_host_check[host] < cutoff
def osdspec_needs_apply(self, host: str, spec: ServiceSpec) -> bool:
if (
host not in self.devices
or host not in self.last_device_change
or host not in self.last_device_update
or host not in self.osdspec_last_applied
or spec.service_name() not in self.osdspec_last_applied[host]
):
return True
created = self.mgr.spec_store.get_created(spec)
if not created or created > self.last_device_change[host]:
return True
return self.osdspec_last_applied[host][spec.service_name()] < self.last_device_change[host]
def host_needs_registry_login(self, host: str) -> bool:
if host in self.mgr.offline_hosts:
return False
if host in self.registry_login_queue:
self.registry_login_queue.remove(host)
return True
return False
def host_metadata_up_to_date(self, host: str) -> bool:
if host not in self.metadata_up_to_date or not self.metadata_up_to_date[host]:
return False
return True
def all_host_metadata_up_to_date(self) -> bool:
if [h for h in self.get_hosts() if (not self.host_metadata_up_to_date(h) and not self.is_host_unreachable(h))]:
# this function is primarily for telling if it's safe to try and apply a service
# spec. Since offline/maintenance hosts aren't considered in that process anyway
# we don't want to return False if the host without up-to-date metadata is in one
# of those two categories.
return False
return True
def add_daemon(self, host, dd):
# type: (str, orchestrator.DaemonDescription) -> None
assert host in self.daemons
self.daemons[host][dd.name()] = dd
def rm_daemon(self, host: str, name: str) -> None:
assert not name.startswith('ha-rgw.')
if host in self.daemons:
if name in self.daemons[host]:
del self.daemons[host][name]
def daemon_cache_filled(self) -> bool:
"""
i.e. we have checked the daemons for each hosts at least once.
excluding offline hosts.
We're not checking for `host_needs_daemon_refresh`, as this might never be
False for all hosts.
"""
return all((self.host_had_daemon_refresh(h) or h in self.mgr.offline_hosts)
for h in self.get_hosts())
def schedule_daemon_action(self, host: str, daemon_name: str, action: str) -> None:
assert not daemon_name.startswith('ha-rgw.')
priorities = {
'start': 1,
'restart': 2,
'reconfig': 3,
'redeploy': 4,
'stop': 5,
'rotate-key': 6,
}
existing_action = self.scheduled_daemon_actions.get(host, {}).get(daemon_name, None)
if existing_action and priorities[existing_action] > priorities[action]:
logger.debug(
f'skipping {action}ing {daemon_name}, cause {existing_action} already scheduled.')
return
if host not in self.scheduled_daemon_actions:
self.scheduled_daemon_actions[host] = {}
self.scheduled_daemon_actions[host][daemon_name] = action
def rm_scheduled_daemon_action(self, host: str, daemon_name: str) -> bool:
found = False
if host in self.scheduled_daemon_actions:
if daemon_name in self.scheduled_daemon_actions[host]:
del self.scheduled_daemon_actions[host][daemon_name]
found = True
if not self.scheduled_daemon_actions[host]:
del self.scheduled_daemon_actions[host]
return found
def get_scheduled_daemon_action(self, host: str, daemon: str) -> Optional[str]:
assert not daemon.startswith('ha-rgw.')
return self.scheduled_daemon_actions.get(host, {}).get(daemon)
class AgentCache():
"""
AgentCache is used for storing metadata about agent daemons that must be kept
through MGR failovers
"""
def __init__(self, mgr):
# type: (CephadmOrchestrator) -> None
self.mgr: CephadmOrchestrator = mgr
self.agent_config_deps = {} # type: Dict[str, Dict[str,Any]]
self.agent_counter = {} # type: Dict[str, int]
self.agent_timestamp = {} # type: Dict[str, datetime.datetime]
self.agent_keys = {} # type: Dict[str, str]
self.agent_ports = {} # type: Dict[str, int]
self.sending_agent_message = {} # type: Dict[str, bool]
def load(self):
# type: () -> None
for k, v in self.mgr.get_store_prefix(AGENT_CACHE_PREFIX).items():
host = k[len(AGENT_CACHE_PREFIX):]
if host not in self.mgr.inventory:
self.mgr.log.warning('removing stray AgentCache record for agent on %s' % (
host))
self.mgr.set_store(k, None)
try:
j = json.loads(v)
self.agent_config_deps[host] = {}
conf_deps = j.get('agent_config_deps', {})
if conf_deps:
conf_deps['last_config'] = str_to_datetime(conf_deps['last_config'])
self.agent_config_deps[host] = conf_deps
self.agent_counter[host] = int(j.get('agent_counter', 1))
self.agent_timestamp[host] = str_to_datetime(
j.get('agent_timestamp', datetime_to_str(datetime_now())))
self.agent_keys[host] = str(j.get('agent_keys', ''))
agent_port = int(j.get('agent_ports', 0))
if agent_port:
self.agent_ports[host] = agent_port
except Exception as e:
self.mgr.log.warning('unable to load cached state for agent on host %s: %s' % (
host, e))
pass
def save_agent(self, host: str) -> None:
j: Dict[str, Any] = {}
if host in self.agent_config_deps:
j['agent_config_deps'] = {
'deps': self.agent_config_deps[host].get('deps', []),
'last_config': datetime_to_str(self.agent_config_deps[host]['last_config']),
}
if host in self.agent_counter:
j['agent_counter'] = self.agent_counter[host]
if host in self.agent_keys:
j['agent_keys'] = self.agent_keys[host]
if host in self.agent_ports:
j['agent_ports'] = self.agent_ports[host]
if host in self.agent_timestamp:
j['agent_timestamp'] = datetime_to_str(self.agent_timestamp[host])
self.mgr.set_store(AGENT_CACHE_PREFIX + host, json.dumps(j))
def update_agent_config_deps(self, host: str, deps: List[str], stamp: datetime.datetime) -> None:
self.agent_config_deps[host] = {
'deps': deps,
'last_config': stamp,
}
def get_agent_last_config_deps(self, host: str) -> Tuple[Optional[List[str]], Optional[datetime.datetime]]:
if host in self.agent_config_deps:
return self.agent_config_deps[host].get('deps', []), \
self.agent_config_deps[host].get('last_config', None)
return None, None
def messaging_agent(self, host: str) -> bool:
if host not in self.sending_agent_message or not self.sending_agent_message[host]:
return False
return True
def agent_config_successfully_delivered(self, daemon_spec: CephadmDaemonDeploySpec) -> None:
# agent successfully received new config. Update config/deps
assert daemon_spec.service_name == 'agent'
self.update_agent_config_deps(
daemon_spec.host, daemon_spec.deps, datetime_now())
self.agent_timestamp[daemon_spec.host] = datetime_now()
self.agent_counter[daemon_spec.host] = 1
self.save_agent(daemon_spec.host)
class EventStore():
def __init__(self, mgr):
# type: (CephadmOrchestrator) -> None
self.mgr: CephadmOrchestrator = mgr
self.events = {} # type: Dict[str, List[OrchestratorEvent]]
def add(self, event: OrchestratorEvent) -> None:
if event.kind_subject() not in self.events:
self.events[event.kind_subject()] = [event]
for e in self.events[event.kind_subject()]:
if e.message == event.message:
return
self.events[event.kind_subject()].append(event)
# limit to five events for now.
self.events[event.kind_subject()] = self.events[event.kind_subject()][-5:]
def for_service(self, spec: ServiceSpec, level: str, message: str) -> None:
e = OrchestratorEvent(datetime_now(), 'service',
spec.service_name(), level, message)
self.add(e)
def from_orch_error(self, e: OrchestratorError) -> None:
if e.event_subject is not None:
self.add(OrchestratorEvent(
datetime_now(),
e.event_subject[0],
e.event_subject[1],
"ERROR",
str(e)
))
def for_daemon(self, daemon_name: str, level: str, message: str) -> None:
e = OrchestratorEvent(datetime_now(), 'daemon', daemon_name, level, message)
self.add(e)
def for_daemon_from_exception(self, daemon_name: str, e: Exception) -> None:
self.for_daemon(
daemon_name,
"ERROR",
str(e)
)
def cleanup(self) -> None:
# Needs to be properly done, in case events are persistently stored.
unknowns: List[str] = []
daemons = self.mgr.cache.get_daemon_names()
specs = self.mgr.spec_store.all_specs.keys()
for k_s, v in self.events.items():
kind, subject = k_s.split(':')
if kind == 'service':
if subject not in specs:
unknowns.append(k_s)
elif kind == 'daemon':
if subject not in daemons:
unknowns.append(k_s)
for k_s in unknowns:
del self.events[k_s]
def get_for_service(self, name: str) -> List[OrchestratorEvent]:
return self.events.get('service:' + name, [])
def get_for_daemon(self, name: str) -> List[OrchestratorEvent]:
return self.events.get('daemon:' + name, [])
|