-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathredfish.py
More file actions
2167 lines (1870 loc) · 86.7 KB
/
Copy pathredfish.py
File metadata and controls
2167 lines (1870 loc) · 86.7 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/monitoring-plugins/blob/main/CONTRIBUTING.rst
"""This library parses data returned from the Redfish API."""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026071404'
import base64
import json
import urllib.parse
from . import base, cache, 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` (the plugins pass one); with
# the default `cache_expire=0` they fetch straight through and touch no cache. Several checks 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 check to miss the cache fetches
# and fills it and every sibling check 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 plugin 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`. A single deeply expanded document already inlines every member a check reads;
# going deeper only inflates the response (and the controller's work) without a caller that needs
# it. Three levels reach the deepest tree we walk (Systems -> Storage -> Drives/Volumes).
MAX_EXPAND_LEVELS = 3
# `$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)'
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'),
}
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`) or the key is absent, so callers
treat both the same and fetch. A stored value is deserialized from JSON before it is returned.
"""
if not cache_expire:
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`) or `data` is not a JSON-serializable
container, so a failed fetch never poisons the cache.
"""
if cache_expire and isinstance(data, (dict, list)):
cache.set(
cache_key,
json.dumps(data),
time.now() + cache_expire,
filename=cache_filename,
)
# 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.
### Example
>>> 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,
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 check runtime and, on a slow management controller, can exceed the
monitoring server's check 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 a single request inlines as much of the subtree as the controller can.
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 check reading the
same collection within the window, so identical reads across a host's Redfish checks 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`.
### Example
>>> success, collection = fetch_collection('https://bmc/redfish/v1/Chassis/1U/Sensors')
>>> members = collection.get('Members', [])
"""
cache_key = f'redfish-{collection_url}'
cached = _cache_read(cache_key, cache_expire, cache_filename)
if cached is not None:
return True, cached
# `expand` is the `$expand` query suffix (default: one level of subordinate members). It is
# derived from the controller's advertised expand support by `get_expand_suffix()`, so it is
# our own literal and cannot smuggle in a different authority the way an `@odata.id` could.
success, collection = url.fetch_json(
f'{collection_url}{expand}',
header=header,
insecure=insecure,
no_proxy=no_proxy,
timeout=timeout,
retries=retries,
)
if not (success and isinstance(collection, dict)):
# controller rejected or could not answer the $expand query: read it plainly
success, collection = url.fetch_json(
collection_url,
header=header,
insecure=insecure,
no_proxy=no_proxy,
timeout=timeout,
retries=retries,
)
if success and isinstance(collection, dict):
_cache_write(collection, cache_key, cache_expire, cache_filename)
return True, collection
return success, collection
def fetch_members(
members,
base_url,
header=None,
insecure=False,
no_proxy=False,
timeout=8,
retries=0,
cache_expire=0,
cache_filename=CACHE_FILENAME,
):
"""
Return every member reference of a Redfish collection as a fully populated dict.
A collection lists its members as reference stubs (`{"@odata.id": "..."}`). With the Redfish
`$expand` query (see `fetch_collection()`) the controller inlines the full member objects
instead. This helper accepts either form and normalizes it: members that already arrived
expanded are returned untouched, and members that are still bare references are fetched
individually. It also accepts inline reference arrays that are not part of a collection's
`Members` list, such as a storage member's `Drives` array.
Each follow-up request goes through `build_url()`, so a malicious or compromised controller
cannot redirect it to another host (see `build_url()` for the SSRF rationale).
When `cache_expire` is non-zero each fetched member is cached under `redfish-<member_url>` and
reused by any sibling check that reads the same member within the window. On a controller without
`$expand` support several checks otherwise re-fetch the same members every cycle, so this is what
keeps a fleet of Redfish checks from hammering the controller. Already-inlined members are not
re-cached (they came from an already-cached collection), and a failed fetch is never cached.
### Parameters
- **members** (`list`): The member references, e.g. `collection.get('Members', [])` or a
storage member's `Drives` list. Each item is a dict, expanded or a bare `@odata.id` stub.
- **base_url** (`str`): The operator-supplied Redfish base URL, used to pin the host of every
follow-up request.
- **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`, `list` | `str`):
- `(True, [member_dict, ...])` on success (the list is empty when `members` is empty).
- `(False, error)` if a bare reference is malformed or cannot be fetched.
### Example
>>> success, collection = fetch_collection('https://bmc/redfish/v1/Chassis/1U/Sensors')
>>> success, sensors = fetch_members(collection.get('Members', []), 'https://bmc')
"""
result = []
for member in members:
if not isinstance(member, dict):
continue
if is_member_expanded(member):
# the controller already inlined this member via $expand
result.append(member)
continue
# bare reference: fetch the member individually, pinning the host
success, member_url = build_url(base_url, member.get('@odata.id'))
if not success:
return False, member_url
cache_key = f'redfish-{member_url}'
member_data = _cache_read(cache_key, cache_expire, cache_filename)
if member_data is None:
success, member_data = url.fetch_json(
member_url,
header=header,
insecure=insecure,
no_proxy=no_proxy,
timeout=timeout,
retries=retries,
)
if not success or not isinstance(member_data, dict):
return False, member_data
_cache_write(member_data, cache_key, cache_expire, cache_filename)
result.append(member_data)
return True, result
def fetch_resource(
resource_url,
header=None,
insecure=False,
no_proxy=False,
timeout=8,
retries=0,
cache_expire=0,
cache_filename=CACHE_FILENAME,
):
"""
Fetch a single Redfish resource by URL, optionally serving and filling a shared cache.
Unlike `fetch_collection()` this adds no `$expand` query; it is for reading an individual
resource such as the service root a caller inspects to detect the controller vendor. When
`cache_expire` is non-zero the parsed document is cached under `redfish-<resource_url>` and
reused by any sibling check that reads the same URL within the window, so identical reads across
a host's Redfish checks hit the cache instead of the controller. A failed fetch is never cached.
### Parameters
- **resource_url** (`str`): The absolute URL of the resource.
- **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, resource)` with the parsed resource document on success.
- `(False, error)` if the resource cannot be read.
### Example
>>> success, root = fetch_resource('https://bmc/redfish/v1/')
"""
cache_key = f'redfish-{resource_url}'
cached = _cache_read(cache_key, cache_expire, cache_filename)
if cached is not None:
return True, cached
success, resource = url.fetch_json(
resource_url,
header=header,
insecure=insecure,
no_proxy=no_proxy,
timeout=timeout,
retries=retries,
)
if success and isinstance(resource, dict):
_cache_write(resource, cache_key, cache_expire, cache_filename)
return success, resource
def get_auth_header(args, cache_expire=0, cache_filename=CACHE_FILENAME):
"""
Build the authentication header for Redfish API requests, reusing a cached session token.
Redfish supports two authentication schemes: HTTP Basic auth (credentials are sent on every
request) and session-based auth (a token is obtained once from the SessionService and then
presented as `X-Auth-Token`). Some management controllers create and log a new internal
session for every Basic-auth request, which floods their session table or audit log. To avoid
that, this function establishes a session once and, when `cache_expire` is non-zero, caches the
token under `redfish-<URL>-<USERNAME>-token` so this run's later requests and the sibling
Redfish checks on the host present the same token instead of each creating a new session.
It degrades gracefully: when a session cannot be created (e.g. the implementation does not
offer the SessionService) it falls back to HTTP Basic auth, and when no credentials are given
(e.g. against an anonymous mockup) it returns an empty header. Only the session token is cached;
the Basic and empty headers carry no token.
The cached token's lifetime is bounded by the controller's own `SessionTimeout` (an inactivity
timeout in seconds, read back from the SessionService) minus a `TIMEOUT`-sized safety margin, so
a token is never reused after the controller would already have dropped the session, which
otherwise surfaces as a "401 Unauthorized". `cache_expire` caps that lifetime from above; the
effective lifetime is the smaller of the two. When caching is off (`cache_expire` is `0`) the
SessionService is not even probed, since there is no lifetime to bound.
### Parameters
- **args** (object): must provide `URL`, `USERNAME`, `PASSWORD`, `INSECURE`, `NO_PROXY` and
`TIMEOUT`.
- **cache_expire** (`int`, optional): Token cache lifetime cap in seconds; `0` (default) fetches
a fresh session and does not cache the token.
- **cache_filename** (`str`, optional): Cache database filename (default `CACHE_FILENAME`).
### Returns
- **dict**: a header fragment to merge into the request headers, one of
`{'X-Auth-Token': '...'}`, `{'Authorization': 'Basic ...'}` or `{}`.
### Example
>>> header = {'Accept': 'application/json'}
>>> header.update(get_auth_header(args, cache_expire=300))
"""
if not (args.USERNAME and args.PASSWORD):
return {}
token_key = f'redfish-{args.URL}-{args.USERNAME}-token'
if cache_expire:
cached_token = cache.get(token_key, filename=cache_filename)
if cached_token:
return {'X-Auth-Token': cached_token}
# no cached token: create a new session via the SessionService
success, result = url.fetch_json(
f'{args.URL}/redfish/v1/SessionService/Sessions',
data={'UserName': args.USERNAME, 'Password': args.PASSWORD},
encoding='serialized-json',
extended=True,
header={'Accept': 'application/json', 'Content-Type': 'application/json'},
insecure=args.INSECURE,
no_proxy=args.NO_PROXY,
timeout=args.TIMEOUT,
method='POST',
)
# lib.url lower-cases all response header names (RFC 9110, section 5.1).
token = ''
if success and isinstance(result, dict):
token = result.get('response_header', {}).get('x-auth-token', '')
if token:
if cache_expire:
# Bound the cached token's lifetime by the controller's own inactivity
# timeout (SessionTimeout, in seconds) so a sibling check never reuses
# the token after the controller would already have dropped the
# session. cache_expire caps it from above.
token_ttl = cache_expire
success, result = url.fetch_json(
f'{args.URL}/redfish/v1/SessionService',
encoding='serialized-json',
header={
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Auth-Token': token,
},
insecure=args.INSECURE,
no_proxy=args.NO_PROXY,
timeout=args.TIMEOUT,
)
session_timeout = 0
if success and isinstance(result, dict):
try:
session_timeout = int(result.get('SessionTimeout') or 0)
except (TypeError, ValueError):
session_timeout = 0
if session_timeout > 0:
# Subtract a TIMEOUT-sized margin so a token cached at the very edge
# of the window still reaches the controller before it drops the
# session. Never drop below one second.
token_ttl = min(token_ttl, max(session_timeout - args.TIMEOUT, 1))
cache.set(
token_key, token, time.now() + token_ttl, filename=cache_filename
)
return {'X-Auth-Token': token}
# session creation failed: fall back to HTTP Basic auth
encoded = txt.to_text(
base64.b64encode(txt.to_bytes(f'{args.USERNAME}:{args.PASSWORD}'))
)
return {'Authorization': f'Basic {encoded}'}
def get_chassis(redfish):
"""
Extract chassis information from a Redfish API response.
This function retrieves specific chassis details from a Redfish response and returns
them as a dictionary.
### Parameters
- **redfish** (`dict`): A dictionary containing Redfish chassis data.
### Returns
- **dict**: A dictionary containing the following chassis details:
- **AssetTag** (`str`): The asset tag of the chassis.
- **ChassisType** (`str`): The type of the chassis.
- **Id** (`str`): The ID of the chassis.
- **IndicatorLED** (`str`): The status of the indicator LED.
- **Manufacturer** (`str`): The manufacturer of the chassis.
- **Model** (`str`): The model of the chassis.
- **PartNumber** (`str`): The part number of the chassis.
- **PowerState** (`str`): The power state of the chassis (e.g., "On").
- **SerialNumber** (`str`): The serial number of the chassis.
- **SKU** (`str`): The SKU of the chassis.
- **Sensors_@odata.id** (`str`): The sensors' OData ID.
- **Status_State** (`str`): The state of the chassis (e.g., "Enabled").
- **Status_Health** (`str`): The health status of the chassis (e.g., "OK").
- **Status_HealthRollup** (`str`): The health rollup status of the chassis (e.g., "OK").
### Example
>>> redfish_data = {
... 'AssetTag': '12345',
... 'ChassisType': 'Rackmount',
... 'Id': '1',
... 'PowerState': 'On',
... }
>>> get_chassis(redfish_data)
{'AssetTag': '12345', 'ChassisType': 'Rackmount', 'Id': '1', 'PowerState': 'On', ...}
"""
data = {key: redfish.get(key, '') for key in CHASSIS_KEYS}
for output_key, (parent_key, child_key) in CHASSIS_NESTED_KEYS.items():
data[output_key] = redfish.get(parent_key, {}).get(child_key, '')
return data
def get_chassis_power_powercontrol(redfish):
"""
Extract power control (overall power consumption) information from a Redfish API response.
The legacy Power resource exposes one or more `PowerControl` entries that report the aggregate
power consumption of the chassis. This function projects a single such entry into a flat
dictionary.
### Parameters
- **redfish** (`dict`): A dictionary containing a single Redfish `PowerControl` entry.
### Returns
- **dict**: A dictionary containing the following power control details:
- **MemberId** (`str`): The identifier of the power control entry.
- **Name** (`str`): The name of the power control entry.
- **PowerCapacityWatts** (`str`): The total power capacity in watts.
- **PowerConsumedWatts** (`str`): The currently consumed power in watts.
- **Status_State** (`str`): The state of the power control entry (e.g., "Enabled").
- **Status_Health** (`str`): The health status of the power control entry (e.g., "OK").
### Example
>>> redfish_data = {
... 'Name': 'System Power Control',
... 'PowerConsumedWatts': 344,
... 'Status': {'State': 'Enabled', 'Health': 'OK'},
... }
>>> get_chassis_power_powercontrol(redfish_data)
{'Name': 'System Power Control', 'PowerConsumedWatts': 344, ..., 'Status_State': 'Enabled', ...}
"""
data = {key: redfish.get(key, '') for key in CHASSIS_POWER_CONTROL_KEYS}
for out_key, path in CHASSIS_POWER_CONTROL_NESTED_KEYS.items():
ref = redfish
for step in path:
ref = ref.get(step, {})
data[out_key] = ref if isinstance(ref, (str, int, float)) else ''
return data
def get_chassis_power_powersupplies(redfish):
"""
Extract power supply information from a Redfish API response.
This function retrieves specific power supply details from a Redfish response and returns
them as a dictionary.
### Parameters
- **redfish** (`dict`): A dictionary containing Redfish power supply data.
### Returns
- **dict**: A dictionary containing the following power supply details:
- **FirmwareVersion** (`str`): The firmware version of the power supply.
- **LastPowerOutputWatts** (`str`): The last reported power output in watts.
- **LineInputVoltage** (`str`): The input voltage of the power supply.
- **LineInputVoltageType** (`str`): The type of input voltage.
- **Manufacturer** (`str`): The manufacturer of the power supply.
- **Model** (`str`): The model of the power supply.
- **PartNumber** (`str`): The part number of the power supply.
- **PowerCapacityWatts** (`str`): The power capacity of the power supply in watts.
- **PowerSupplyType** (`str`): The type of power supply.
- **SerialNumber** (`str`): The serial number of the power supply.
- **SparePartNumber** (`str`): The spare part number of the power supply.
- **Status_State** (`str`): The state of the power supply (e.g., "Enabled").
- **Status_Health** (`str`): The health status of the power supply (e.g., "OK").
### Example
>>> redfish_data = {
... 'FirmwareVersion': '1.0',
... 'LastPowerOutputWatts': 200,
... 'PowerCapacityWatts': 500,
... }
>>> get_chassis_power_powersupplies(redfish_data)
{'FirmwareVersion': '1.0', 'LastPowerOutputWatts': 200, 'PowerCapacityWatts': 500, ...}
"""
data = {key: redfish.get(key, '') for key in CHASSIS_POWER_KEYS}
if data['LastPowerOutputWatts'] in ('', None):
data['LastPowerOutputWatts'] = redfish.get('PowerOutputWatts', '')
for output_key, (parent_key, child_key) in CHASSIS_POWER_NESTED_KEYS.items():
data[output_key] = redfish.get(parent_key, {}).get(child_key, '')
return data
def get_chassis_power_voltages(redfish):
"""
Extract power voltage information from a Redfish API response.
This function retrieves specific power voltage details from a Redfish response and returns
them as a dictionary.
### Parameters
- **redfish** (`dict`): A dictionary containing Redfish power voltage data.
### Returns
- **dict**: A dictionary containing the following power voltage details:
- **LowerThresholdCritical** (`str`): The critical lower threshold voltage.
- **LowerThresholdFatal** (`str`): The fatal lower threshold voltage.
- **LowerThresholdNonCritical** (`str`): The non-critical lower threshold voltage.
- **Name** (`str`): The name of the voltage.
- **PhysicalContext** (`str`): The physical context of the voltage.
- **ReadingVolts** (`str`): The current voltage reading.
- **UpperThresholdCritical** (`str`): The critical upper threshold voltage.
- **UpperThresholdFatal** (`str`): The fatal upper threshold voltage.
- **UpperThresholdNonCritical** (`str`): The non-critical upper threshold voltage.
- **Status_State** (`str`): The state of the voltage (e.g., "Enabled").
- **Status_Health** (`str`): The health status of the voltage (e.g., "OK").
### Example
>>> redfish_data = {
... 'LowerThresholdCritical': 10,
... 'ReadingVolts': 12,
... 'UpperThresholdCritical': 15,
... }
>>> get_chassis_power_voltages(redfish_data)
{'LowerThresholdCritical': 10, 'ReadingVolts': 12, 'UpperThresholdCritical': 15, ...}
"""
data = {key: redfish.get(key, '') for key in CHASSIS_VOLTAGE_KEYS}
for output_key, (parent_key, child_key) in CHASSIS_VOLTAGE_NESTED_KEYS.items():
data[output_key] = redfish.get(parent_key, {}).get(child_key, '')
return data
def get_chassis_sensors(redfish):
"""
Extract sensor information from a Redfish API response.
This function retrieves specific sensor details from a Redfish response and returns
them as a dictionary.
### Parameters
- **redfish** (`dict`): A dictionary containing Redfish sensor data.
### Returns
- **dict**: A dictionary containing the following sensor details:
- **Id** (`str`): The ID of the sensor.
- **Name** (`str`): The name of the sensor.
- **PhysicalContext** (`str`): The physical context of the sensor.
- **Reading** (`str`): The current reading of the sensor.
- **ReadingRangeMax** (`str`): The maximum reading range of the sensor.
- **ReadingRangeMin** (`str`): The minimum reading range of the sensor.
- **ReadingUnits** (`str`): The units of the sensor reading.
- **Thresholds_LowerCaution** (`str`): The lower caution threshold for the sensor.
- **Thresholds_LowerCritical** (`str`): The lower critical threshold for the sensor.
- **Thresholds_UpperCaution** (`str`): The upper caution threshold for the sensor.
- **Thresholds_UpperCritical** (`str`): The upper critical threshold for the sensor.
- **Status_State** (`str`): The state of the sensor (e.g., "Enabled").
- **Status_Health** (`str`): The health status of the sensor (e.g., "OK").
- **Status_HealthRollup** (`str`): The health rollup status of the sensor (e.g., "OK").
### Example
>>> redfish_data = {
... 'Id': 'sensor1',
... 'Reading': 75,
... 'ReadingRangeMax': 100,
... 'Thresholds_LowerCaution': 30,
... }
>>> get_chassis_sensors(redfish_data)
{'Id': 'sensor1', 'Reading': 75, 'ReadingRangeMax': 100, 'Thresholds_LowerCaution': 30, ...}
"""