-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathredfish.py
More file actions
1722 lines (1475 loc) · 65.8 KB
/
redfish.py
File metadata and controls
1722 lines (1475 loc) · 65.8 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__ = '2026060704'
import base64
from . import base, cache, human, time, txt, url
from .globals import STATE_CRIT, STATE_OK, STATE_WARN
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'),
}
# 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 get_auth_header(args):
"""
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, caches the returned token via `cache`, and
reuses it across requests and subsequent runs until the cache entry expires.
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.
A cached token is reused until `CACHE_EXPIRE` minutes pass, independent of the controller's own
session timeout. Keep `CACHE_EXPIRE` below that timeout so the cached token does not go stale
before it is dropped.
### Parameters
- **args** (object): must provide `URL`, `USERNAME`, `PASSWORD`, `INSECURE`, `NO_PROXY`,
`TIMEOUT` and `CACHE_EXPIRE` (cache lifetime in minutes).
### 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))
"""
if not (args.USERNAME and args.PASSWORD):
return {}
token_key = f'redfish-{args.URL}-{args.USERNAME}-token'
token = cache.get(token_key)
if token:
return {'X-Auth-Token': 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:
cache.set(token_key, token, time.now() + args.CACHE_EXPIRE * 60)
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, ...}
"""
data = {key: redfish.get(key, '') for key in CHASSIS_SENSOR_KEYS}
for out_key, path in CHASSIS_SENSOR_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_thermal_fans(redfish):
"""
Extract thermal fan information from a Redfish API response.
This function retrieves specific thermal fan details from a Redfish response and returns
them as a dictionary.
### Parameters
- **redfish** (`dict`): A dictionary containing Redfish thermal fan data.
### Returns
- **dict**: A dictionary containing the following thermal fan details:
- **FanName** (`str`): The name of the fan.
- **HotPluggable** (`str`): Indicates if the fan is hot pluggable.
- **LowerThresholdCritical** (`str`): The critical lower threshold for the fan's reading.
- **LowerThresholdFatal** (`str`): The fatal lower threshold for the fan's reading.
- **LowerThresholdNonCritical** (`str`): The non-critical lower threshold for the fan's
reading.
- **Name** (`str`): The name of the sensor.
- **PhysicalContext** (`str`): The physical context of the sensor.
- **Reading** (`str`): The current reading of the fan.
- **ReadingUnits** (`str`): The units of the fan's reading.
- **SensorNumber** (`str`): The number of the fan's sensor.
- **UpperThresholdCritical** (`str`): The critical upper threshold for the fan's reading.
- **UpperThresholdFatal** (`str`): The fatal upper threshold for the fan's reading.
- **UpperThresholdNonCritical** (`str`): The non-critical upper threshold for the fan's
reading.
- **Status_State** (`str`): The state of the fan (e.g., "Enabled").
- **Status_Health** (`str`): The health status of the fan (e.g., "OK").
### Example
>>> redfish_data = {'FanName': 'Fan1', 'Reading': 80, 'UpperThresholdCritical': 100}
>>> get_chassis_thermal_fans(redfish_data)
{'FanName': 'Fan1', 'Reading': 80, 'UpperThresholdCritical': 100, ...}
"""
data = {key: redfish.get(key, '') for key in CHASSIS_FAN_KEYS}
for out_key, path in CHASSIS_FAN_NESTED_KEYS.items():
ref = redfish
for step in path:
ref = ref.get(step, {})
data[out_key] = ref if isinstance(ref, (str, int, float)) else ''
# vendor quirk: Dell, Fujitsu and Huawei report fan speed in RPM under
# "ReadingRPM"; HP and Lenovo report a percentage. Normalize both onto
# Reading / ReadingUnits so get_perfdata() and the table see one shape.
if redfish.get('ReadingRPM') is not None or redfish.get('ReadingUnits') == 'RPM':
reading = redfish.get('ReadingRPM')
data['Reading'] = redfish.get('Reading', '') if reading is None else reading
data['ReadingUnits'] = 'RPM'
elif redfish.get('ReadingUnits') == 'Percent':
data['ReadingUnits'] = '%'
return data
def get_chassis_thermal_redundancy(redfish):
"""
Extract thermal redundancy information from a Redfish API response.
This function retrieves specific thermal redundancy details from a Redfish response and returns
them as a dictionary.
### Parameters
- **redfish** (`dict`): A dictionary containing Redfish thermal redundancy data.
### Returns
- **dict**: A dictionary containing the following thermal redundancy details:
- **Mode** (`str`): The mode of the thermal redundancy.
- **Name** (`str`): The name of the thermal redundancy.
- **Status_State** (`str`): The state of the thermal redundancy (e.g., "Enabled").
- **Status_Health** (`str`): The health status of the thermal redundancy (e.g., "OK").
### Example
>>> redfish_data = {
... 'Mode': 'Active',
... 'Name': 'Thermal Redundancy',
... 'Status': {'State': 'Enabled', 'Health': 'OK'},
... }
>>> get_chassis_thermal_redundancy(redfish_data)
{'Mode': 'Active', 'Name': 'Thermal Redundancy', 'Status_State': 'Enabled', 'Status_Health': 'OK'}
"""
data = {key: redfish.get(key, '') for key in CHASSIS_THERMAL_REDUNDANCY_KEYS}
for out_key, path in CHASSIS_THERMAL_REDUNDANCY_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_thermal_temperatures(redfish):
"""
Extract thermal temperature information from a Redfish API response.
This function retrieves specific thermal temperature details from a Redfish response and returns
them as a dictionary.
### Parameters
- **redfish** (`dict`): A dictionary containing Redfish thermal temperature data.
### Returns
- **dict**: A dictionary containing the following thermal temperature details:
- **LowerThresholdCritical** (`str`): The critical lower threshold temperature.
- **LowerThresholdFatal** (`str`): The fatal lower threshold temperature.
- **LowerThresholdNonCritical** (`str`): The non-critical lower threshold temperature.
- **Name** (`str`): The name of the thermal temperature sensor.
- **PhysicalContext** (`str`): The physical context of the sensor.
- **ReadingCelsius** (`str`): The current temperature reading in Celsius.
- **UpperThresholdCritical** (`str`): The critical upper threshold temperature.
- **UpperThresholdFatal** (`str`): The fatal upper threshold temperature.
- **UpperThresholdNonCritical** (`str`): The non-critical upper threshold temperature.
- **Status_State** (`str`): The state of the thermal sensor (e.g., "Enabled").
- **Status_Health** (`str`): The health status of the thermal sensor (e.g., "OK").
### Example
>>> redfish_data = {
... 'LowerThresholdCritical': '10',
... 'LowerThresholdFatal': '5',
... 'LowerThresholdNonCritical': '15',
... 'Name': 'Thermal Sensor',
... 'ReadingCelsius': '22',
... 'Status': {'State': 'Enabled', 'Health': 'OK'},
... }
>>> get_chassis_thermal_temperatures(redfish_data)
{'LowerThresholdCritical': '10', 'LowerThresholdFatal': '5', 'LowerThresholdNonCritical': '15', 'Name': 'Thermal Sensor', 'ReadingCelsius': '22', 'Status_State': 'Enabled', 'Status_Health': 'OK'}
"""
data = {key: redfish.get(key, '') for key in CHASSIS_THERMAL_TEMP_KEYS}
for out_key, path in CHASSIS_THERMAL_TEMP_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_manager(redfish):
"""
Retrieves manager (BMC) details from a Redfish API response.
This function processes a Redfish manager resource (e.g., a BMC, iLO, or iDRAC) and extracts
the attributes relevant for health monitoring and identification.
### Parameters
- **redfish** (`dict`): A dictionary containing Redfish manager data, typically a single member
of the `Managers` collection.
### Returns
- **dict**: A dictionary containing the following manager details:
- `FirmwareVersion`: The firmware version of the manager.
- `Id`: The unique identifier of the manager.
- `ManagerType`: The type of the manager (e.g., "BMC").
- `Model`: The model of the manager.
- `Name`: The name of the manager.
- `PowerState`: The power state of the manager (e.g., "On").
- `UUID`: The UUID of the manager.
- `Status_State`: The state of the manager (e.g., "Enabled").
- `Status_Health`: The health status of the manager (e.g., "OK").
- `Status_HealthRollup`: The rollup health status of the manager (e.g., "OK").
### Example
>>> redfish_data = {
... 'FirmwareVersion': '1.45',
... 'ManagerType': 'BMC',
... 'Status': {'State': 'Enabled', 'Health': 'OK'},
... }
>>> get_manager(redfish_data)
{'FirmwareVersion': '1.45', 'ManagerType': 'BMC', ..., 'Status_State': 'Enabled', ...}
"""
data = {key: redfish.get(key, '') for key in MANAGER_KEYS}
for out_key, path in MANAGER_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_manager_logservices_sel_entries(
redfish, match=None, ignore=None, cutoff_epoch=0
):
"""
Fetch and format SEL (System Event Log) entries from the Redfish API.
Processes each entry by severity and formats the non-OK ones into a message string, returning
the worst state across them. Entries can be filtered and aged out before they contribute:
- **ignore**: drop entries whose `Message` matches any of these compiled regular expressions.
- **match**: when given, keep only entries whose `Message` matches at least one of these
compiled regular expressions.
- **cutoff_epoch**: when non-zero, drop (and count) entries whose `Created` timestamp is older
than this Unix epoch, so a long-since resolved event no longer keeps the state non-OK.
### Parameters
- **redfish** (`dict`): A dictionary containing the Redfish log entries under the 'Members' key.
- **match** (`list`, optional): Compiled regular expressions; keep only matching messages.
- **ignore** (`list`, optional): Compiled regular expressions; drop matching messages.
- **cutoff_epoch** (`int` or `float`, optional): Drop entries created before this epoch.
`0` (default) disables aging.
### Returns
- **tuple**:
- **msg** (`str`): A formatted string of the reported entries (created time, message, state).
- **state** (`int`): The worst state across the reported entries:
- `STATE_OK` (0): nothing to report.
- `STATE_WARN` (1): some entries are warnings.
- `STATE_CRIT` (2): some entries are critical.
- **aged_out** (`int`): How many non-OK entries were suppressed because they were older than
`cutoff_epoch`.
### Example
>>> redfish_data = {
... 'Members': [
... {
... 'Created': '2021-08-01',
... 'Message': 'Temperature is high',
... 'Severity': 'Critical',
... },
... {
... 'Created': '2021-08-02',
... 'Message': 'Fan speed normal',
... 'Severity': 'OK',
... },
... ]
... }
>>> get_manager_logservices_sel_entries(redfish_data)
('* 2021-08-01: Temperature is high [CRITICAL]\n', 2, 0)
"""
lines = []
state = STATE_OK
aged_out = 0
utc = time.get_timezone('UTC')
for entry in redfish.get('Members', []):
severity = entry.get('Severity', '').lower()
if severity == 'ok':
continue
message = entry.get('Message', '')
# --ignore: drop entries whose message matches any ignore pattern
if ignore and any(p.search(message) for p in ignore):
continue
# --match: keep only entries whose message matches a match pattern
if match and not any(p.search(message) for p in match):
continue
created = entry.get('Created', '')
# aging: drop (and count) entries older than the cutoff. A naive
# timestamp is read as UTC, which is what controllers commonly report.
if cutoff_epoch and created:
try:
entry_epoch = time.timestr2epoch(created, pattern='iso8601', tzinfo=utc)
except ValueError:
# undateable entry: keep it rather than silently suppress it
entry_epoch = None
if entry_epoch is not None and entry_epoch < cutoff_epoch:
aged_out += 1
continue
msg_state = SEVERITY_TO_STATE.get(severity, STATE_OK)
lines.append(
'* {}: {}{}'.format(created, message, base.state2str(msg_state, prefix=' '))
)
state = base.get_worst(state, msg_state)
return '\n'.join(lines) + ('\n' if lines else ''), state, aged_out
def get_perfdata(data, key='Reading'):
"""
Retrieve the performance data for a specific key from the provided data.
This function extracts performance-related values such as the reading value, thresholds, and
range from the provided dictionary. It formats this data and returns a performance data string,
suitable for monitoring.
### Parameters
- **data** (`dict`): A dictionary containing performance data and related information.
- **key** (`str`, optional): The key in the dictionary whose value should be extracted.
Defaults to `'Reading'`.
### Returns
- **str**: A formatted string containing performance data in the format:
`'label=value[unit];[warn];[crit];[min];[max]'`, or an empty string if the required data is invalid or missing.
### Example
>>> data = {
... 'Name': 'Temperature Sensor 1',
... 'PhysicalContext': 'Chassis',
... 'Reading': 75.0,
... 'ReadingUnits': '%',
... 'Thresholds_UpperCaution': 80,
... 'Thresholds_UpperCritical': 90,
... 'ReadingRangeMin': 0,
... 'ReadingRangeMax': 100,
... }
>>> get_perfdata(data)
'Chassis_Temperature_Sensor_1=75.0%;80;90;0;100'
"""
value = data.get(key)
if not isinstance(value, (int, float)):
return ''
name = data.get('Name', '')
physical_context = data.get('PhysicalContext', '')
uom = '%' if data.get('ReadingUnits') == '%' else None
warn = data.get('Thresholds_UpperCaution') or None
crit = data.get('Thresholds_UpperCritical') or None
_min = data.get('ReadingRangeMin') or None
_max = data.get('ReadingRangeMax') or None
label = f'{physical_context}_{name}'.replace(' ', '_')
return base.get_perfdata(label, value, uom, warn, crit, _min, _max)
def get_sensor_state(data, key='Reading'):
"""
Determine the state of a Redfish sensor according to status, health, thresholds, and range.
This function evaluates the sensor reading in the following order:
1. **Status_State**
If `data['Status_State']` is not `'Enabled'` or `'Quiesced'`, the sensor is considered OK.
2. **Status_HealthRollup / Status_Health**
- Returns STATE_CRIT if either is `'Critical'`.
- Returns STATE_WARN if either is `'Warning'`.
3. **Thresholds** (with user-defined overrides)
Checks in this sequence for any defined thresholds:
- **User-defined critical** (`Thresholds_LowerCriticalUser`, `Thresholds_UpperCriticalUser`) → STATE_CRIT
- **Default critical** (`Thresholds_LowerCritical`, `Thresholds_UpperCritical`) → STATE_CRIT
- **User-defined caution** (`Thresholds_LowerCautionUser`, `Thresholds_UpperCautionUser`) → STATE_WARN
- **Default caution** (`Thresholds_LowerCaution`, `Thresholds_UpperCaution`) → STATE_WARN
Otherwise, if any thresholds were present but none breached, returns STATE_OK.
4. **ReadingRange** (last-resort sanity check)
If both `ReadingRangeMin` and `ReadingRangeMax` are defined and differ, returns STATE_WARN