-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathredfish.py
More file actions
3349 lines (2911 loc) · 131 KB
/
Copy pathredfish.py
File metadata and controls
3349 lines (2911 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://github.com/Linuxfabrik/lib/blob/main/CONTRIBUTING.md
"""This library parses data returned from the Redfish API."""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026091001'
import atexit
import base64
import json
import os
import re
import sys
import urllib.parse
from . import base, cache, db_sqlite, disk, human, time, txt, url
from .globals import STATE_CRIT, STATE_OK, STATE_WARN
# Shared cache database filename for the Redfish fetch layer. The fetch helpers below cache by URL,
# but only when a caller opts in by passing a non-zero `cache_expire`; with the default
# `cache_expire=0` they fetch straight through and touch no cache. Several consumers read the
# same data from one controller each cycle (its session token, its `$expand` support, the
# Systems or Managers collection and their members), so the first one to miss the cache fetches
# and fills it and every sibling reuses the entry instead of hitting the controller again.
# Kept out of the default cache database so those response bodies do not mingle with other cached
# data. Named here so every consumer and this library agree on the same file and can share
# entries.
CACHE_FILENAME = 'linuxfabrik-monitoring-plugins-redfish.db'
# Upper bound for the Redfish `$expand` `$levels` we ask for, even when a controller advertises a
# higher `MaxLevels`. One level inlines the members of a collection, and the members are all a
# caller reads from it: a deeper resource it needs, it reads as a collection of its own. Every
# further level only inlines what the members link to, and with the `*` operator that includes
# every link. Measured against dmtf/redfish-mockup-server (Redfish 1.15.0): one level inlined
# every member of every collection the Redfish checks read, while three levels made the same
# answers 20 to 800 times larger (Chassis 3 KB against 329 KB, the log entries 1 KB against
# 794 KB) without a single additional member, work a real controller has to do on every request.
MAX_EXPAND_LEVELS = 1
# `$expand` suffix used when the controller does not advertise its expand support (or the service
# root cannot be read): ask for one level of subordinate members. `fetch_collection()` falls back
# to a plain request if the controller rejects it, so this stays safe on controllers without
# `$expand`.
DEFAULT_EXPAND = '?$expand=.($levels=1)'
# Upper bound for the extra attempts a login is given, however high a caller's own retry budget
# is. A login is not a read: a controller creates the session before it answers, so an attempt the
# client abandons on timeout still leaves a session behind on the controller (measured: three
# attempts against a controller answering slower than the timeout left three sessions). Retrying a
# login as often as a GET would therefore exhaust the controller's session pool, which is the very
# condition that makes logins fail. Two extra attempts cover a dropped request without turning a
# slow controller into a flooded one.
MAX_LOGIN_RETRIES = 2
# File the diagnostic trace is written to, inside the same per-user directory as the cache
# database. The trace is a support aid: it records what this library asked the controller for,
# how long each request took and which path the authentication took, so a slow or flapping run
# can be diagnosed from one file instead of from a dozen hand-run curl commands. A consumer
# writes it only when its `--verbose` switch turned the trace on; otherwise the trace costs one
# `if` per request and nothing is opened. See `start_trace()` for why this goes to a file rather
# than to the caller's output.
TRACE_FILENAME = 'linuxfabrik-monitoring-plugins-redfish-trace.log'
# Upper bound for the trace file, in bytes. A caller that runs every minute would otherwise fill
# the temporary directory while an admin leaves `--verbose` on over a weekend. Once the file has
# grown past this, `start_trace()` refuses instead of appending, so an admin is told to move the
# file away rather than losing the temporary directory to it.
TRACE_MAX_BYTES = 10 * 1024 * 1024
# Sentence a consumer appends to its own `--verbose` help, so every Redfish consumer describes
# the switch in the same words and an admin is told where to look before it has run once. Kept
# free of a literal '%', which argparse would try to expand.
VERBOSE_HELP = (
'For this check that also appends every Redfish response it evaluated to its output, '
'ready to be attached to a bug report, and writes a trace of every Redfish request, with '
'timings, to '
+ TRACE_FILENAME
+ " below the temporary directory. Unlike this check's output, the trace survives a check "
'that the monitoring server terminates for exceeding its timeout, which is what makes it '
'useful against a slow management controller. Passwords and session tokens are kept out '
'of both. The output grows with the responses, so keep this switched on in a service '
'definition only while chasing a problem.'
)
CHASSIS_FAN_KEYS = (
'FanName',
'HotPluggable',
'LowerThresholdCritical',
'LowerThresholdFatal',
'LowerThresholdNonCritical',
'Name',
'PhysicalContext',
'Reading',
'ReadingUnits',
'SensorNumber',
'UpperThresholdCritical',
'UpperThresholdFatal',
'UpperThresholdNonCritical',
)
CHASSIS_FAN_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
}
CHASSIS_KEYS = (
'AssetTag',
'ChassisType',
'Id',
'IndicatorLED',
'Manufacturer',
'Model',
'PartNumber',
'PowerState',
'SerialNumber',
'SKU',
)
CHASSIS_NESTED_KEYS = {
'Sensors_@odata.id': ('Sensors', '@odata.id'),
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
CHASSIS_POWER_CONTROL_KEYS = (
'MemberId',
'Name',
'PowerCapacityWatts',
'PowerConsumedWatts',
)
CHASSIS_POWER_CONTROL_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
}
CHASSIS_POWER_KEYS = (
'FirmwareVersion',
'LastPowerOutputWatts',
'LineInputVoltage',
'LineInputVoltageType',
'Manufacturer',
'Model',
'PartNumber',
'PowerCapacityWatts',
'PowerSupplyType',
'SerialNumber',
'SparePartNumber',
)
CHASSIS_POWER_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
}
CHASSIS_SENSOR_KEYS = (
'Id',
'Name',
'PhysicalContext',
'Reading',
'ReadingRangeMax',
'ReadingRangeMin',
'ReadingUnits',
)
CHASSIS_SENSOR_NESTED_KEYS = {
'Thresholds_LowerCaution': ('Thresholds', 'LowerCaution', 'Reading'),
'Thresholds_LowerCautionUser': ('Thresholds', 'LowerCautionUser', 'Reading'),
'Thresholds_LowerCritical': ('Thresholds', 'LowerCritical', 'Reading'),
'Thresholds_LowerCriticalUser': ('Thresholds', 'LowerCriticalUser', 'Reading'),
'Thresholds_UpperCaution': ('Thresholds', 'UpperCaution', 'Reading'),
'Thresholds_UpperCautionUser': ('Thresholds', 'UpperCautionUser', 'Reading'),
'Thresholds_UpperCritical': ('Thresholds', 'UpperCritical', 'Reading'),
'Thresholds_UpperCriticalUser': ('Thresholds', 'UpperCriticalUser', 'Reading'),
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
CHASSIS_THERMAL_REDUNDANCY_KEYS = ('Mode', 'Name')
CHASSIS_THERMAL_REDUNDANCY_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
}
CHASSIS_THERMAL_TEMP_KEYS = (
'LowerThresholdCritical',
'LowerThresholdFatal',
'LowerThresholdNonCritical',
'Name',
'PhysicalContext',
'ReadingCelsius',
'UpperThresholdCritical',
'UpperThresholdFatal',
'UpperThresholdNonCritical',
)
CHASSIS_THERMAL_TEMP_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
}
CHASSIS_VOLTAGE_KEYS = (
'LowerThresholdCritical',
'LowerThresholdFatal',
'LowerThresholdNonCritical',
'Name',
'PhysicalContext',
'ReadingVolts',
'UpperThresholdCritical',
'UpperThresholdFatal',
'UpperThresholdNonCritical',
)
CHASSIS_VOLTAGE_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
}
ETHERNET_KEYS = (
'Description',
'FQDN',
'FullDuplex',
'HostName',
'Id',
'LinkStatus',
'MACAddress',
'Name',
'PermanentMACAddress',
'SpeedMbps',
)
ETHERNET_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
FIRMWARE_KEYS = (
'Id',
'Manufacturer',
'Name',
'ReleaseDate',
'SoftwareId',
'Updateable',
'Version',
)
FIRMWARE_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
MANAGER_KEYS = (
'FirmwareVersion',
'Id',
'ManagerType',
'Model',
'Name',
'PowerState',
'UUID',
)
MANAGER_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
MEMORY_KEYS = (
'BaseModuleType',
'CapacityMiB',
'ErrorCorrection',
'Id',
'Manufacturer',
'MemoryDeviceType',
'MemoryType',
'Name',
'OperatingSpeedMhz',
'PartNumber',
'RankCount',
'SerialNumber',
)
MEMORY_NESTED_KEYS = {
'Location_ServiceLabel': ('Location', 'PartLocation', 'ServiceLabel'),
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
# Some controllers leave the standard Status.State/Health empty on memory
# modules and report the real condition only in an OEM-specific field. These
# tables fold those vendor operational values back onto the standard Redfish
# vocabulary so the generic get_state() can evaluate them. Modules in an absent
# state are skipped by the callers; healthy operational states map to "Enabled",
# everything else is surfaced as a problem.
MEMORY_OEM_ABSENT_STATES = ('Absent', 'EmptyOrNotInstalled', 'NotPresent')
MEMORY_OEM_HEALTHY_HEALTH = ('enabled', 'nominal', 'ok')
MEMORY_OEM_HEALTHY_STATES = ('Enabled', 'GoodInUse', 'Operable', 'Quiesced')
PROCESSOR_KEYS = (
'Id',
'InstructionSet',
'Manufacturer',
'MaxSpeedMHz',
'Model',
'Name',
'ProcessorArchitecture',
'ProcessorType',
'Socket',
'TotalCores',
'TotalThreads',
)
PROCESSOR_NESTED_KEYS = {
'Location_ServiceLabel': ('Location', 'PartLocation', 'ServiceLabel'),
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
SEVERITY_TO_STATE = {
'critical': STATE_CRIT,
'warning': STATE_WARN,
}
SYSTEMS_KEYS = (
'BiosVersion',
'HostName',
'Id',
'IndicatorLED',
'Manufacturer',
'Model',
'PowerState',
'SerialNumber',
'SKU',
)
SYSTEMS_NESTED_KEYS = {
'EthernetInterfaces_@odata.id': ('EthernetInterfaces', '@odata.id'),
'Memory_@odata.id': ('Memory', '@odata.id'),
'Processors_@odata.id': ('Processors', '@odata.id'),
'ProcessorSummary_Count': ('ProcessorSummary', 'Count'),
'ProcessorSummary_LogicalProcessorCount': (
'ProcessorSummary',
'LogicalProcessorCount',
),
'ProcessorSummary_Model': ('ProcessorSummary', 'Model'),
'Storage_@odata.id': ('Storage', '@odata.id'),
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
SYSTEMS_STORAGE_DRIVES_KEYS = (
'BlockSizeBytes',
'CapableSpeedGbs',
'Description',
'EncryptionAbility',
'EncryptionStatus',
'FailurePredicted',
'HotspareType',
'Id',
'Manufacturer',
'MediaType',
'Model',
'Name',
'NegotiatedSpeedGbs',
'PartNumber',
'PowerOnHours',
'PredictedMediaLifeLeftPercent',
'Protocol',
'Revision',
'RotationSpeedRPM',
'SerialNumber',
'WriteCacheEnabled',
)
SYSTEMS_STORAGE_DRIVES_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
SYSTEMS_STORAGE_KEYS = ('Description', 'Drives@odata.count', 'Id', 'Name')
SYSTEMS_STORAGE_NESTED_KEYS = {
'Volumes_@odata.id': ('Volumes', '@odata.id'),
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
VOLUME_KEYS = (
'CapacityBytes',
'Encrypted',
'Id',
'Name',
'RAIDType',
'VolumeType',
)
VOLUME_NESTED_KEYS = {
'Status_State': ('Status', 'State'),
'Status_Health': ('Status', 'Health'),
'Status_HealthRollup': ('Status', 'HealthRollup'),
}
# Diagnostic trace state. `_TRACE['fd']` is the open trace file descriptor and doubles as the
# on/off switch: everything below returns immediately while it is None, which is every run that
# did not call `start_trace()`.
_TRACE = {
'fd': None,
'path': '',
'started': 0.0,
'requests': 0,
'seconds': 0.0,
# per request kind: [count, seconds], so the summary can say where the time actually went
'by_kind': {},
}
# Field names whose value never reaches the recorded responses, whatever a controller sends
# back. The login is not recorded at all, so a session token cannot get in through the front
# door; this closes the back door of a firmware echoing a credential inside a data response.
# Matched case-insensitively.
_REDACTED_FIELDS = frozenset(
{
'authorization',
'community',
'communitystring',
'passphrase',
'password',
'secret',
'token',
'x-auth-token',
}
)
# Responses a replay answers from, keyed by request path (see `replay()`). None while no replay
# runs, which is every run that talks to a controller.
_REPLAY = {'responses': None}
# One recorded response as `format_responses()` renders it: a `### GET <path>` heading line,
# optionally followed by notes, and the response as JSON on the lines below.
_REPLAY_BLOCK = re.compile(r'^### GET (\S+)[^\n]*\n', re.MULTILINE)
# Responses recorded for `--verbose` (see `record_responses()`). `items` holds one
# `(request, payload, cached)` triple per response in the order they arrived. `expand` is the
# `$expand` suffix `get_expand_suffix()` settled on, so the output can say what the collections
# were asked for with. `formatted` turns true once `format_responses()` handed them over, so the
# exit handler does not print them a second time.
_RESPONSES = {
'expand': '',
'formatted': False,
'items': [],
'on': False,
}
def _trace_timestamp():
"""Return the current local time as `YYYY-MM-DD HH:MM:SS.mmm`.
Millisecond resolution, because the point of the trace is to tell a request that took 200 ms
apart from one that took 8 s, and because the gap between two consecutive lines is what
reveals time spent outside the requests.
"""
return time.now(as_type='datetime').strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
def _trace_pid():
"""Return the current process id, padded, for the trace's second column.
A host's Redfish consumers are scheduled together and append to the same file, so their
lines interleave. Without a process id on every line the file cannot be split back into the
runs it came from, and a `+12.000s` from one run reads as if it belonged to another. With it,
`grep` on one id yields one run.
"""
return f'{os.getpid():>7}'
def _trace(event, detail):
"""Append one line to the trace file, if the trace is on.
The line carries an absolute timestamp, the seconds elapsed since `start_trace()`, a
fixed-width event name and a free-form detail, so an admin can both read it top to bottom and
`grep`/`awk` it by column.
Every line is passed through `txt.sanitize_sensitive_data()` before it is written. Callers
are expected to keep credentials out of the detail in the first place (this module never
passes a request header, a request body or a session token in here), but the trace is a file
an admin mails to a bug tracker, so the redaction is applied unconditionally as a second
line of defence.
Failures are swallowed: a diagnostic aid must never turn a working check into an UNKNOWN
because the temporary directory filled up mid-run.
"""
if _TRACE['fd'] is None:
return
elapsed = time.now(as_type='float') - _TRACE['started']
line = f'{_trace_timestamp()} {_trace_pid()} +{elapsed:7.3f}s {event:<9} {detail}\n'
try:
os.write(_TRACE['fd'], txt.sanitize_sensitive_data(line).encode('utf-8'))
except OSError:
pass
def _trace_summary():
"""Write the closing summary and close the trace file. Registered with `atexit`.
Runs on a normal exit and on `sys.exit()`, but not when the process is killed by a signal,
which is exactly the case this trace exists for. That is why every line above is written and
flushed as it happens (unbuffered `os.write()`) instead of being collected and printed at the
end: a run terminated from outside for exceeding a timeout still leaves a complete trace up
to the moment it was killed, just without this summary. A trace whose last line is a request
that never completed is the finding.
"""
if _TRACE['fd'] is None:
return
wall = time.now(as_type='float') - _TRACE['started']
other = wall - _TRACE['seconds']
_trace(
'summary',
f'{_TRACE["requests"]} requests, {_TRACE["seconds"]:.3f}s waiting for the '
f'controller, {other:.3f}s elsewhere, {wall:.3f}s total',
)
# Break the controller time down by what was being read. This is the line that names the
# culprit: 60 member requests worth 55s say the collection was not inlined, while a single
# login worth 55s says the controller is slow to authenticate.
for kind, (count, seconds) in sorted(
_TRACE['by_kind'].items(), key=lambda item: item[1][1], reverse=True
):
share = 100 * seconds / wall if wall > 0 else 0
_trace(
'summary',
f' {seconds:8.3f}s ({share:4.1f}% of the run) in {count} {kind} '
f'request(s), {seconds / count:.3f}s each on average',
)
try:
os.close(_TRACE['fd'])
except OSError:
pass
_TRACE['fd'] = None
def _consumer():
"""Return the name and version of the consumer running this module, as far as it declares them.
Both come from the `__main__` module, its file name and its `__version__`. They identify a
run in the trace and in the recorded responses, which is what a bug report needs to be
matched against the code that produced it.
"""
main_module = sys.modules.get('__main__')
name = os.path.basename(getattr(main_module, '__file__', '') or 'unknown')
version = getattr(main_module, '__version__', '') or 'unknown'
return name, version
def start_trace(path='', filename=TRACE_FILENAME):
"""
Start writing a diagnostic trace of every Redfish request this run makes.
Turn this on from a `--verbose` switch. It records, line by line and with millisecond
timestamps, which URL was requested with which timeout and retry budget, how long the
controller took to answer, whether an answer came from the shared cache, which `$expand`
support the controller advertised, whether its members arrived inlined or had to be fetched
one by one, and which of the three authentication paths (cached token, fresh session, Basic
fallback) the run took. Between them, those lines answer why a run against a slow management
controller takes long, without an admin having to reproduce the walk by hand.
The trace goes to a file rather than to the caller's output on purpose. A run that takes long
enough to be diagnosed is usually one that is terminated from outside with `SIGTERM`, and a
terminated run produces no output at all: whatever it would have printed dies with it. The
file is written as the run progresses, so it survives that termination and still shows where
the time went.
The file lives in the same per-user, `0700` directory as the cache database, and is created
with `0600` and `O_NOFOLLOW`, so a symlink planted at a predictable path under a shared
temporary directory cannot redirect the write (CWE-59/CWE-377, the same reasoning as
`db_sqlite.get_db_dir()`).
Repeated runs append, so a flapping check can be left tracing for several cycles and compared
across them; a header line separates the runs. Once the file has grown past
`TRACE_MAX_BYTES` this refuses instead of appending.
Parameters
----------
path : str, optional
Directory to place the trace file in. Defaults to the system
temporary directory.
filename : str, optional
Name of the trace file (a plain basename).
Defaults to `TRACE_FILENAME`.
Returns
-------
tuple (bool, str)
- `(True, path)` with the absolute path of the trace file on success. Tell the admin where
it is: a trace nobody can find is not a diagnostic.
- `(False, error)` if the file cannot be opened, so a `--verbose` run that silently traces
nowhere is impossible.
Examples
--------
>>> success, trace_path = start_trace()
>>> success
True
"""
if _TRACE['fd'] is not None:
return True, _TRACE['path']
if filename in ('.', '..') or os.path.basename(filename) != filename:
return False, f'Refusing unsafe trace filename: {filename!r}'
if not path:
path = disk.get_tmpdir()
# Reuse the hardened per-user directory the cache database already lives in, so the trace
# inherits its ownership and permission checks instead of repeating them here.
success, trace_dir = db_sqlite.get_db_dir(path)
if not success:
return False, trace_dir
trace_path = os.path.join(trace_dir, filename)
try:
size = os.path.getsize(trace_path)
except OSError:
size = 0
if size > TRACE_MAX_BYTES:
return False, (
f'Trace file {trace_path} has grown past {human.bytes2human(TRACE_MAX_BYTES)}, '
f'refusing to append. Move it away to start a new one.'
)
try:
# O_NOFOLLOW: refuse to open a symlink sitting at the trace path. O_APPEND: several
# Redfish checks on the same host trace into the same file, and append-mode writes of
# this size do not interleave. 0o600: the trace names hosts and URLs.
fd = os.open(
trace_path,
os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW,
0o600,
)
except OSError as e:
return False, f'Cannot open trace file {trace_path}: {e}'
_TRACE['fd'] = fd
_TRACE['path'] = trace_path
_TRACE['started'] = time.now(as_type='float')
_TRACE['requests'] = 0
_TRACE['seconds'] = 0.0
atexit.register(_trace_summary)
# Identify the run: which check, which version of it, which version of this library, and the
# process id, so lines from Redfish checks tracing concurrently into this file can be told
# apart.
check, check_version = _consumer()
_trace(
'start',
f'{check} v{check_version}, lib/redfish.py v{__version__}. Columns: timestamp, pid, '
f'seconds since this run started, event, detail',
)
return True, trace_path
def _replay_key(url_string):
"""Return the key a replay files a response under: the path of `url_string`.
The query is dropped on purpose. It carries the `$expand` suffix, which a replay has no
controller to negotiate with, and a collection has to be found whether it was recorded with
`$expand` or after the plain fallback. A trailing slash is dropped as well, because the
service root is requested as both `/redfish/v1` and `/redfish/v1/`.
"""
return urllib.parse.urlsplit(url_string).path.rstrip('/') or '/'
def _replay_response(url_string):
"""Answer a request from the responses `replay()` loaded, the way a controller would.
A recorded JSON string stands for a request that failed and is handed back as that failure.
A path that was never recorded is answered with a 404, which is what a controller answers
for a resource it does not have, so a consumer's handling of a missing endpoint is exercised
as well.
"""
key = _replay_key(url_string)
if key not in _REPLAY['responses']:
return False, f'HTTP error "404 Not Found" while fetching {key}'
payload = _REPLAY['responses'][key]
if isinstance(payload, str):
return False, payload
return True, payload
def _fetch_json(what, url_string, timeout=8, retries=0, **kwargs):
"""Fetch JSON through `url.fetch_json()`, timing and tracing the call.
Every request this module makes goes through here, so the trace sees all of them and the
timing is measured in exactly one place. With the trace off this adds one `if` to the call.
While a replay runs (see `replay()`), the answer comes from the recorded responses instead
and no request leaves the host.
`url.fetch_json()` retries internally, so the measured duration covers all `retries + 1`
attempts. Both numbers are traced alongside it, which is what makes a long line readable: a
request logged as `timeout=8 retries=10` that took 88 s spent them being retried, while one
that took 88 s at `retries=0` was answered slowly by the controller. Note that `timeout` is
an httpx per-phase timeout, not a deadline for the whole request, so a controller that keeps
dribbling out a large response can exceed it without ever tripping it.
Parameters
----------
what : str
Short label for the trace, naming what is being read (e.g. `collection`).
url_string : str
The URL to fetch.
timeout, retries, **kwargs
Forwarded to `url.fetch_json()`.
Returns
-------
tuple (bool, dict | list | str)
Whatever `url.fetch_json()` returned.
"""
if _REPLAY['responses'] is not None:
return _replay_response(url_string)
if _TRACE['fd'] is None:
result = url.fetch_json(url_string, timeout=timeout, retries=retries, **kwargs)
if _should_renew(what, result) and _renew_auth(kwargs.get('header')):
result = url.fetch_json(
url_string, timeout=timeout, retries=retries, **kwargs
)
return result
method = kwargs.get('method') or ('POST' if kwargs.get('data') else 'GET')
started = time.now(as_type='float')
result = url.fetch_json(url_string, timeout=timeout, retries=retries, **kwargs)
if _should_renew(what, result) and _renew_auth(kwargs.get('header')):
result = url.fetch_json(url_string, timeout=timeout, retries=retries, **kwargs)
elapsed = time.now(as_type='float') - started
_TRACE['requests'] += 1
_TRACE['seconds'] += elapsed
kind = _TRACE['by_kind'].setdefault(what, [0, 0.0])
kind[0] += 1
kind[1] += elapsed
success, payload = result
if success:
# Size of the parsed document re-serialized, not the size on the wire: the wire size is
# not handed back by `fetch_json()` without switching every caller to `extended=True`,
# which would change the code path being measured. It is the right order of magnitude for
# spotting the response that is slow because it is large.
try:
size = human.bytes2human(len(json.dumps(payload)))
except (TypeError, ValueError):
size = 'n/a'
outcome = f'ok {size}'
else:
# `url.fetch_json()` appends ' while fetching <url>' to its errors. The URL is already
# this line's last column, so strip the repetition and keep the line readable.
outcome = f'FAILED {str(payload).split(" while fetching ")[0]}'
_trace(
'request',
f'{elapsed:7.3f}s {method:<4} {what:<10} timeout={timeout} retries={retries} '
f'{outcome} {url_string}',
)
return result
def _cache_read(cache_key, cache_expire, cache_filename):
"""Return the cached JSON value stored under `cache_key`, or `None` on a miss.
Returns `None` when caching is off (`cache_expire` is `0`), while a replay runs, or when the
key is absent, so callers treat all three the same and fetch. A replay must not pick up what
a real run left in the shared cache, or it would no longer replay the recorded responses. A
stored value is deserialized from JSON before it is returned.
"""
if not cache_expire or _REPLAY['responses'] is not None:
return None
cached = cache.get(cache_key, filename=cache_filename)
return json.loads(cached) if cached else None
def _cache_write(data, cache_key, cache_expire, cache_filename):
"""Store `data` as JSON under `cache_key` for `cache_expire` seconds, when caching is on.
A no-op when caching is off (`cache_expire` is `0`), while a replay runs, or when `data` is
not a JSON-serializable container, so a failed fetch never poisons the cache and a replayed
response never reaches a real run.
"""
if cache_expire and _REPLAY['responses'] is None and isinstance(data, (dict, list)):
cache.set(
cache_key,
json.dumps(data),
time.now() + cache_expire,
filename=cache_filename,
)
def _redact(value):
"""Return a copy of a response with the value of every field in `_REDACTED_FIELDS` replaced.
Parameters
----------
value : any
A decoded response, or any part of one.
Returns
-------
The same structure, with each sensitive field's value replaced by ''.
"""
if isinstance(value, dict):
return {
key: ('******' if str(key).lower() in _REDACTED_FIELDS else _redact(inner))
for key, inner in value.items()
}
if isinstance(value, list):
return [_redact(item) for item in value]
return value
def _record(request_url, result, cached=False):
"""Remember what a request returned, for `format_responses()`, if recording is on.
The fetch helpers call this with the URL as they requested it, so a collection keeps its
`$expand` query and the recording shows how it was asked for. Only path and query are kept:
they are all a replay needs, and they keep the controller's address out of an output that
ends up in a bug report. For the same reason the address is cut out of an error message.
A response served from the shared cache is recorded as well, marked as such. The consumer
evaluated it just the same, and a replay needs it.
Parameters
----------
request_url : str
The absolute URL that was requested.
result : tuple
The `(success, payload)` pair the request returned.
cached : bool, optional
Whether the payload came from the shared cache.
"""
if not _RESPONSES['on']:
return
parts = urllib.parse.urlsplit(request_url)
request = parts.path + (f'?{parts.query}' if parts.query else '')
success, payload = result
if not success:
payload = str(payload).replace(f'{parts.scheme}://{parts.netloc}', '')
_RESPONSES['items'].append((request, _redact(payload), cached))
# The "Status" property is common to many Redfish schema, and contains:
#
# Health: This represents the health state of this resource in the absence
# of its dependent resources
# * Critical A critical condition exists that requires immediate attention.
# * OK Normal.
# * Warning A condition exists that requires attention
#
# HealthRollup: This represents the overall health state from the view of this
# resource
# * Critical A critical condition exists that requires immediate attention.
# * OK Normal.
# * Warning A condition exists that requires attention.
#
# State:
# * Absent This function or resource is not present or not detected.
# * Deferring The element will not process any commands but will queue new
# requests.
# * Disabled This function or resource has been disabled.
# * Enabled This function or resource has been enabled.
# * InTest This function or resource is undergoing testing.
# * Quiesced The element is enabled but only processes a restricted set of
# commands.
# * StandbyOffline This function or resource is enabled, but awaiting an external action to
# activate it.
# * StandbySpare This function or resource is part of a redundancy set and is awaiting a
# failover or other external action to activate it.
# * Starting This function or resource is starting.
# * UnavailableOffline This function or resource is present but cannot be used.
# * Updating The element is updating and may be unavailable or degraded.
def build_url(base_url, odata_id):
"""
Build an absolute Redfish URL from the operator-supplied base URL and a server-supplied
`@odata.id` link, always taking scheme and host from the base URL.
Redfish responses reference sub-resources by an `@odata.id` field that is expected to be a
server-relative path such as `/redfish/v1/Systems/1`. Concatenating it onto the base URL
without validation lets a malicious or compromised controller inject a different authority
(for example an `@host` userinfo prefix that turns `https://bmc` + `@evil/x` into
`https://bmc@evil/x`), turning the next authenticated request into a server-side request
forgery that also forwards the Redfish auth header to the attacker-chosen host
(CWE-918/CWE-20). This helper rejects any `@odata.id` that is not a single-slash-rooted
relative path and pins scheme and host to `base_url`, so a response can never redirect the
request to another host.
Parameters
----------
base_url : str
The operator-supplied Redfish base URL, e.g. `https://bmc`.
odata_id : str
The `@odata.id` value taken from the controller's response.
Returns
-------
tuple (bool, str)
- `(True, url)` with the safe absolute URL on success.
- `(False, error)` if `odata_id` is not a server-relative path.
Examples
--------
>>> build_url('https://bmc', '/redfish/v1/Systems/1')
(True, 'https://bmc/redfish/v1/Systems/1')
>>> build_url('https://bmc', '@evil.example.com/x')
(False, "Refusing non-relative Redfish @odata.id link: '@evil.example.com/x'")
"""
if (
not isinstance(odata_id, str)
or not odata_id.startswith('/')
or odata_id.startswith('//')
):
return False, f'Refusing non-relative Redfish @odata.id link: {odata_id!r}'
parts = urllib.parse.urlsplit(base_url)
return True, f'{parts.scheme}://{parts.netloc}{odata_id}'
def fetch_collection(
collection_url,
expand=DEFAULT_EXPAND,
header=None,
insecure=False,
no_proxy=False,
proxy=None,
timeout=8,
retries=0,
cache_expire=0,
cache_filename=CACHE_FILENAME,
):
"""
Fetch a Redfish collection, asking the controller to inline its members in one request.
A Redfish collection (for example `Sensors`, `Memory`, `Drives` or `FirmwareInventory`) lists
its members as bare `@odata.id` references, so reading every member classically costs one
request for the collection plus one request per member. On a controller with dozens of members
that fan-out dominates the runtime and, on a slow management controller, can exceed the
caller's own timeout.
This helper appends the Redfish `$expand` query `expand` (default: one level of subordinate
members), which asks the controller to return the full member objects inline. When the
controller honours it, the whole collection is read in a single request; callers detect the
inlined members with `is_member_expanded()` and skip the per-member requests. When the
controller rejects `$expand` (some implementations answer with an HTTP error), this helper
transparently retries the plain request, so the returned document is the same either way, just
without the inlined members.
Callers pass the `expand` suffix that `get_expand_suffix()` derived from the controller's
advertised support, so the members arrive inlined wherever the controller can inline them.
When `cache_expire` is non-zero the parsed collection is cached under `redfish-<collection_url>`
(keyed by the plain URL, not the `$expand` variant) and reused by any sibling consumer
reading the same collection within the window, so identical reads across a host's Redfish
consumers hit the cache instead of the controller. A failed fetch is never cached.
Parameters
----------
collection_url : str
The absolute URL of the collection resource, as produced by
`build_url()`. Must not already carry a query string.
expand : str, optional
The `$expand` query suffix to append (default `DEFAULT_EXPAND`).
header : dict, optional
Request headers (including the auth header).
insecure, no_proxy, timeout, retries
Forwarded to `url.fetch_json()`.
cache_expire : int, optional
Cache lifetime in seconds; `0` (default) disables caching.
cache_filename : str, optional
Cache database filename (default `CACHE_FILENAME`).
Returns
-------
tuple (bool, dict | str)
- `(True, collection)` with the parsed collection document on success. Its `Members` may or
may not be expanded, depending on controller support.
- `(False, error)` if the collection cannot be read even without `$expand`.
Examples
--------
>>> success, collection = fetch_collection(
... 'https://bmc/redfish/v1/Chassis/1U/Sensors'
... )
>>> members = collection.get('Members', [])