forked from quadsproject/badfish
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·3083 lines (2680 loc) · 126 KB
/
main.py
File metadata and controls
executable file
·3083 lines (2680 loc) · 126 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
import asyncio
import base64
import functools
import json
import os
import re
import sys
import time
import warnings
import yaml
import tempfile
from urllib.parse import urlparse
from rich.console import Console
from badfish.helpers import get_now
from badfish.helpers.parser import parse_arguments
from badfish.helpers.logger import BadfishLogger
from badfish.helpers.http_client import HTTPClient
from badfish.helpers.exceptions import BadfishException
from badfish.helpers.progress import polling_progress
from logging import (
DEBUG,
INFO,
getLogger,
)
warnings.filterwarnings("ignore")
RETRIES = 15
async def badfish_factory(
_host,
_username,
_password,
_logger=None,
_retries=RETRIES,
_loop=None,
_insecure=False,
_console=None,
_progress_disabled=False,
):
if not _logger:
bfl = BadfishLogger()
_logger = bfl.logger
badfish = Badfish(
_host,
_username,
_password,
_logger,
_retries,
_loop,
_insecure,
_console,
_progress_disabled,
)
await badfish.init()
return badfish
class Badfish:
def __init__(
self,
_host,
_username,
_password,
_logger,
_retries,
_loop=None,
_insecure=False,
_console=None,
_progress_disabled=False,
):
self.host = _host
self.username = _username
self.password = _password
self.retries = _retries
self.host_uri = "https://%s" % _host
self.redfish_uri = "/redfish/v1"
self.root_uri = "%s%s" % (self.host_uri, self.redfish_uri)
self.logger = _logger
self.semaphore = asyncio.Semaphore(50)
self.loop = _loop
if not self.loop:
self.loop = asyncio.get_event_loop()
self.http_client = HTTPClient(_host, _username, _password, _logger, _retries, _insecure)
self.system_resource = None
self.manager_resource = None
self.bios_uri = None
self.boot_devices = None
self.session_uri = None
self.session_id = None
self.token = None
self.vendor = None
self.console = _console if _console is not None else Console()
self._progress_disabled = _progress_disabled
async def __aenter__(self):
await self.init()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.delete_session()
if exc_type is not None:
self.logger.debug(f"Exiting context with exception: {exc_type.__name__}: {exc_val}")
return False
async def init(self):
self.session_uri = await self.find_session_uri()
self.token = await self.validate_credentials()
try:
self.system_resource = await self.find_systems_resource()
self.bios_uri = "%s/Bios/Settings" % self.system_resource[len(self.redfish_uri) :]
except BadfishException as e:
self.logger.warning(f"Could not find system resource: {e}. Some operations may not be available.")
self.system_resource = None
self.bios_uri = None
self.manager_resource = await self.find_managers_resource()
async def error_handler(self, _response, message=None):
try:
raw = await _response.text("utf-8", "ignore")
data = json.loads(raw.strip())
except ValueError:
raise BadfishException("Error reading response from host.")
detail_message = data
if "error" in data:
try:
detail_message = str(data["error"]["@Message.ExtendedInfo"][0]["Message"])
resolution = str(data["error"]["@Message.ExtendedInfo"][0]["Resolution"])
self.logger.debug(resolution)
except (KeyError, IndexError) as ex:
self.logger.debug(ex)
if message:
self.logger.debug(detail_message)
raise BadfishException(message)
else:
raise BadfishException(detail_message)
async def get_interfaces_by_type(self, host_type, _interfaces_path):
definitions = await self.read_yaml(_interfaces_path)
host_name_split = self.host.split(".")[0].split("-")
host_model = None
rack = None
uloc = None
host_blade = None
prefix = [host_type]
if len(host_name_split) > 1:
host_model = host_name_split[-1]
rack = host_name_split[1]
uloc = host_name_split[2]
prefix.extend([rack, uloc])
if len(host_name_split) > 4:
host_blade = host_name_split[3]
prefix.append(host_blade)
if host_blade:
key = f"{host_type}_{host_blade}_{host_model}"
interfaces_string = definitions.get(key)
if interfaces_string:
return interfaces_string.split(",")
len_prefix = len(prefix)
key = "None"
for _ in range(len_prefix):
prefix_string = "_".join(prefix)
key = prefix_string
if host_model:
key = "_".join([prefix_string, host_model])
interfaces_string = definitions.get(key)
if interfaces_string:
return interfaces_string.split(",")
else:
prefix.pop()
raise BadfishException(f"Couldn't find a valid key defined on the interfaces yaml: {key}")
async def get_boot_seq(self):
bios_boot_mode = await self.get_bios_boot_mode()
if bios_boot_mode == "Uefi":
return "UefiBootSeq"
else:
return "BootSeq"
async def get_bios_boot_mode(self):
self.logger.debug("Getting bios boot mode.")
attribute = "BootMode"
bios_boot_mode = await self.get_bios_attribute(attribute)
if not bios_boot_mode:
self.logger.warning("Assuming boot mode is Bios.")
bios_boot_mode = "Bios"
self.logger.debug("Current boot mode: %s" % bios_boot_mode)
return bios_boot_mode
async def get_sriov_mode(self):
self.logger.debug("Getting global SRIOV mode.")
attribute = "SriovGlobalEnable"
sriov_mode = await self.get_bios_attribute(attribute)
return sriov_mode
async def get_bios_attributes_registry(self):
self.logger.debug("Getting BIOS attribute registry.")
_uri = "%s%s/Bios/BiosRegistry" % (self.host_uri, self.system_resource)
data = await self.http_client.get_json(_uri)
if not data:
self.logger.error("Operation not supported by vendor.")
return False
return data
async def get_bios_attribute_registry(self, attribute):
data = await self.get_bios_attributes_registry()
attribute_value = await self.get_bios_attribute(attribute)
for entry in data["RegistryEntries"]["Attributes"]:
entries = [low_entry.lower() for low_entry in entry.values() if isinstance(low_entry, str)]
if attribute.lower() in entries:
for values in entry.items():
if values[0] == "CurrentValue":
self.logger.info(f"{values[0]}: {attribute_value}")
else:
self.logger.info(f"{values[0]}: {values[1]}")
return True
raise BadfishException(f"Unable to locate the Bios attribute: {attribute}")
async def get_bios_attributes(self):
self.logger.debug("Getting BIOS attributes.")
_uri = "%s%s/Bios" % (self.host_uri, self.system_resource)
data = await self.http_client.get_json(_uri)
if not data:
self.logger.error("Operation not supported by vendor.")
return False
return data
async def get_bios_attribute(self, attribute):
data = await self.get_bios_attributes()
try:
bios_attribute = data["Attributes"][attribute]
return bios_attribute
except (KeyError, TypeError):
self.logger.warning("Could not retrieve Bios Attributes.")
return None
async def set_bios_attribute(self, attributes):
data = await self.get_bios_attributes_registry()
accepted = False
for entry in data["RegistryEntries"]["Attributes"]:
entries = [low_entry.lower() for low_entry in entry.values() if isinstance(low_entry, str)]
_warnings = []
_not_found = []
_remove = []
for attribute, value in attributes.items():
if attribute.lower() in entries:
for values in entry.items():
if values[0] == "Value":
accepted_values = [value["ValueName"] for value in values[1]]
for accepted_value in accepted_values:
if value.lower() == accepted_value.lower():
value = accepted_value
accepted = True
if not accepted:
_warnings.append(f"List of accepted values for '{attribute}': {accepted_values}")
attribute_value = await self.get_bios_attribute(attribute)
if attribute_value:
if value.lower() == attribute_value.lower():
self.logger.warning(f"Attribute value for {attribute} is already in that state. IGNORING.")
_remove.append(attribute)
else:
_not_found.append(f"{attribute} not found. Please check attribute name.")
if _warnings:
for warning in _warnings:
self.logger.warning(warning)
raise BadfishException("Value not accepted")
if _not_found:
for warning in _not_found:
self.logger.error(warning)
raise BadfishException("Attribute not found")
if _remove:
for attribute in _remove:
attributes.pop(attribute)
_payload = {"Attributes": attributes}
await self.patch_bios(_payload, insist=False)
await self.reboot_server()
async def get_boot_devices(self):
if not self.boot_devices:
_boot_seq = await self.get_boot_seq()
_uri = "%s%s/BootSources" % (self.host_uri, self.system_resource)
_response = await self.get_request(_uri)
if _response and _response.status == 404:
self.logger.debug(await _response.text())
raise BadfishException("Boot order modification is not supported by this host.")
if not _response:
raise BadfishException("Boot order modification is not supported by this host.")
raw = await _response.text("utf-8", "ignore")
data = json.loads(raw.strip())
if "Attributes" in data:
try:
self.boot_devices = data["Attributes"][_boot_seq]
except KeyError:
for key in data["Attributes"].keys():
if "bootseq" in key.lower():
self.logger.debug("Boot sequence found: %s" % key)
raise BadfishException(
"The boot mode does not match the boot sequence. Try again in a few minutes."
)
else:
self.logger.debug(data)
raise BadfishException("Boot order modification is not supported by this host.")
async def get_job_queue(self):
self.logger.debug("Getting job queue.")
_url = "%s%s/Jobs" % (self.host_uri, self.manager_resource)
_response = await self.get_request(_url)
data = await _response.text("utf-8", "ignore")
job_queue = re.findall(r"[JR]ID_.+?\d+", data)
jobs = [job.strip("}").strip('"').strip("'") for job in job_queue]
return jobs
async def get_reset_types(self, manager=False, bmc=False):
if manager:
resource = self.manager_resource
endpoint = "#Manager.Reset"
else:
resource = self.system_resource
endpoint = "#ComputerSystem.Reset"
self.logger.debug("Getting allowable reset types.")
_url = "%s%s" % (self.host_uri, resource)
_response = await self.get_request(_url)
reset_types = []
if _response:
raw = await _response.text("utf-8", "ignore")
data = json.loads(raw.strip())
if "Actions" not in data:
self.logger.warning("Actions resource not found")
else:
reset = data["Actions"].get(endpoint)
if reset:
reset_types = reset.get("ResetType@Redfish.AllowableValues", [])
if not reset_types:
if bmc:
reset_types = ["GracefulRestart", "ForceRestart"]
else:
self.logger.warning("Could not get allowable reset types")
return reset_types
async def read_yaml(self, _yaml_file):
with open(_yaml_file, "r") as f:
try:
definitions = yaml.safe_load(f)
except yaml.YAMLError as ex:
self.logger.debug(ex)
raise BadfishException("Couldn't read file: %s" % _yaml_file)
return definitions
async def get_host_types_from_yaml(self, _interfaces_path):
definitions = await self.read_yaml(_interfaces_path)
host_types = set()
for line in definitions:
_split = line.split("_")
host_types.add(_split[0])
ordered_types = sorted(list(host_types))
return ordered_types
async def get_host_type(self, _interfaces_path):
await self.get_boot_devices()
if _interfaces_path:
host_types = await self.get_host_types_from_yaml(_interfaces_path)
for host_type in host_types:
match = True
try:
interfaces = await self.get_interfaces_by_type(host_type, _interfaces_path)
except BadfishException as ex:
self.logger.debug(str(ex))
continue
for device in sorted(self.boot_devices[: len(interfaces)], key=lambda x: x["Index"]):
if device["Name"] == interfaces[device["Index"]]:
continue
else:
match = False
break
if match:
return host_type
return None
async def find_session_uri(self):
response = await self.http_client.get_request(self.root_uri, _get_token=True)
if not response:
raise BadfishException(f"Failed to communicate with {self.host}")
if response.status == 401:
raise BadfishException(f"Failed to authenticate. Verify your credentials for {self.host}")
raw = await response.text("utf-8", "ignore")
data = json.loads(raw.strip())
try:
redfish_version = int(data["RedfishVersion"].replace(".", ""))
except KeyError:
raise BadfishException("Was unable to get Redfish Version. Please verify credentials/host.")
session_uri = None
if redfish_version >= 160:
session_uri = "/redfish/v1/SessionService/Sessions"
elif redfish_version < 160:
session_uri = "/redfish/v1/Sessions"
_uri = "%s%s" % (self.host_uri, session_uri)
check_response = await self.http_client.get_request(_uri, _continue=True, _get_token=True)
if check_response is None or check_response.status != 200:
session_uri = "/redfish/v1/SessionService/Sessions"
return session_uri
async def validate_credentials(self):
payload = {"UserName": self.username, "Password": self.password}
headers = {"content-type": "application/json"}
_uri = "%s%s" % (self.host_uri, self.session_uri)
_response = await self.http_client.post_request(_uri, payload, headers, _get_token=True)
await _response.text("utf-8", "ignore")
status = _response.status
if status == 401:
raise BadfishException(f"Failed to authenticate. Verify your credentials for {self.host}")
if status not in [200, 201]:
raise BadfishException(f"Failed to communicate with {self.host}")
# Extract token from response headers
token = _response.headers.get("X-Auth-Token")
if token:
self.token = token
self.http_client.token = token
# Store session info for cleanup
self.session_id = _response.headers.get("Location")
return token
async def get_interfaces_endpoints(self):
_uri = "%s%s/EthernetInterfaces" % (self.host_uri, self.system_resource)
data = await self.http_client.get_json(_uri)
if not data:
raise BadfishException("EthernetInterfaces entry point not supported by this host.")
endpoints = []
if data.get("Members"):
for member in data["Members"]:
endpoints.append(member["@odata.id"])
else:
raise BadfishException("EthernetInterfaces's Members array is either empty or missing")
return endpoints
async def get_interface(self, endpoint):
_uri = "%s%s" % (self.host_uri, endpoint)
data = await self.http_client.get_json(_uri)
if not data:
raise BadfishException("EthernetInterface entry point not supported by this host.")
return data
async def find_systems_resource(self):
response = await self.http_client.get_request(self.root_uri)
if not response:
raise BadfishException("Failed to communicate with server.")
raw = await response.text("utf-8", "ignore")
data = json.loads(raw.strip())
if "Systems" not in data:
raise BadfishException("Systems resource not found")
systems = data["Systems"]["@odata.id"]
systems_response = await self.http_client.get_request(self.host_uri + systems)
if not systems_response:
raise BadfishException("Authorization Error: verify credentials.")
raw = await systems_response.text("utf-8", "ignore")
systems_data = json.loads(raw.strip())
if systems_data.get("Members"):
for member in systems_data["Members"]:
systems_service = member["@odata.id"]
self.logger.debug("Systems service: %s." % systems_service)
return systems_service
else:
raise BadfishException("ComputerSystem's Members array is either empty or missing")
async def find_managers_resource(self):
response = await self.http_client.get_request(self.root_uri)
if not response:
raise BadfishException("Failed to communicate with server.")
raw = await response.text("utf-8", "ignore")
data = json.loads(raw.strip())
self.vendor = "Dell" if data.get("Oem") and "Dell" in data["Oem"] else "Supermicro"
if "Managers" not in data:
raise BadfishException("Managers resource not found")
managers = data["Managers"]["@odata.id"]
managers_response = await self.http_client.get_request(self.host_uri + managers)
managers_data = None
if managers_response:
raw = await managers_response.text("utf-8", "ignore")
managers_data = json.loads(raw.strip())
if managers_data and managers_data.get("Members"):
for member in managers_data["Members"]:
managers_service = member["@odata.id"]
self.logger.debug("Managers service: %s." % managers_service)
return managers_service
else:
raise BadfishException("Manager's Members array is either empty or missing")
# HTTP client wrapper methods
async def get_request(self, uri, _continue=False, _get_token=False):
return await self.http_client.get_request(uri, _continue, _get_token)
async def post_request(self, uri, payload, headers, _get_token=False):
return await self.http_client.post_request(uri, payload, headers, _get_token)
async def patch_request(self, uri, payload, headers, _continue=False):
return await self.http_client.patch_request(uri, payload, headers, _continue)
async def delete_request(self, uri, headers):
return await self.http_client.delete_request(uri, headers)
async def get_power_state(self):
_uri = "%s%s" % (self.host_uri, self.system_resource)
self.logger.debug("url: %s" % _uri)
data = await self.http_client.get_json(_uri, _continue=True)
if not data:
self.logger.debug("Couldn't get power state. Retrying.")
return "Down"
if not data.get("PowerState"):
raise BadfishException("Power state not found. Try to racreset.")
else:
self.logger.debug("Current server power state is: %s." % data["PowerState"])
return data["PowerState"]
async def set_power_state(self, state):
if state.lower() not in ["on", "off"]:
raise BadfishException("Power state not valid. 'on' or 'off' only accepted.")
_uri = "%s%s" % (self.host_uri, self.system_resource)
self.logger.debug("url: %s" % _uri)
_response = await self.get_request(_uri, _continue=True)
if not _response and state.lower() == "off":
self.logger.warning("Power state appears to be already set to 'off'.")
return
status = _response.status
if status == 200:
raw = await _response.text("utf-8", "ignore")
data = json.loads(raw.strip())
else:
raise BadfishException("Couldn't get power state.")
if not data.get("PowerState"):
raise BadfishException("Power state not found. Try to racreset.")
else:
self.logger.debug("Current server power state is: %s." % data["PowerState"])
if state.lower() == "off":
await self.send_reset("ForceOff")
elif state.lower() == "on":
await self.send_reset("On")
return data["PowerState"]
async def get_power_consumed_watts(self):
_uri = "%s%s/Chassis/%s/Power" % (self.host_uri, self.redfish_uri, self.system_resource.split("/")[-1])
_response = await self.get_request(_uri)
if _response.status == 404:
self.logger.error("Operation not supported by vendor.")
return False
try:
raw = await _response.text("utf-8", "ignore")
data = json.loads(raw.strip())
except ValueError:
raise BadfishException("Power value outside operating range.")
try:
cwc = data["PowerControl"][0]["PowerConsumedWatts"]
except IndexError:
cwc = "N/A. Try to `--racreset`."
self.logger.info(f"Current watts consumed: {cwc}")
return
async def change_boot(self, host_type, interfaces_path, pxe=False):
if interfaces_path:
if not os.path.exists(interfaces_path):
raise BadfishException("No such file or directory: '%s'." % interfaces_path)
host_types = await self.get_host_types_from_yaml(interfaces_path)
if host_type.lower() not in host_types:
raise BadfishException(f"Expected values for -t argument are: {host_types}")
else:
raise BadfishException("You must provide a path to the interfaces yaml via `-i` optional argument.")
_type = None
if host_type.lower() != "uefi":
_type = await self.get_host_type(interfaces_path)
if (_type and _type.lower() != host_type.lower()) or not _type:
await self.clear_job_queue()
if host_type.lower() == "uefi":
payload = dict()
boot_mode = await self.get_bios_boot_mode()
if boot_mode.lower() != "uefi":
payload["BootMode"] = "Uefi"
interfaces = await self.get_interfaces_by_type(host_type, interfaces_path)
for i, interface in enumerate(interfaces, 1):
payload[f"PxeDev{i}Interface"] = interface
payload[f"PxeDev{i}EnDis"] = "Enabled"
await self.set_bios_attribute(payload)
else:
boot_mode = await self.get_bios_boot_mode()
if boot_mode.lower() == "uefi":
self.logger.warning(
"Changes being requested will be valid for Bios BootMode. " "Current boot mode is set to Uefi."
)
await self.change_boot_order(host_type, interfaces_path)
if pxe:
await self.set_next_boot_pxe()
await self.create_bios_config_job(self.bios_uri)
await self.reboot_server(graceful=False)
else:
self.logger.warning("No changes were made since the boot order already matches the requested.")
return True
async def change_boot_order(self, _host_type, _interfaces_path):
interfaces = await self.get_interfaces_by_type(_host_type, _interfaces_path)
await self.get_boot_devices()
devices = [device["Name"] for device in self.boot_devices]
valid_devices = [device for device in interfaces if device in devices]
if len(valid_devices) < len(interfaces):
diff = [device for device in interfaces if device not in valid_devices]
self.logger.warning("Some interfaces are not valid boot devices. Ignoring: %s" % ", ".join(diff))
change = False
ordered_devices = self.boot_devices.copy()
for i, interface in enumerate(valid_devices):
for device in ordered_devices:
if interface == device["Name"]:
if device["Index"] != i:
device["Index"] = i
change = True
break
if change:
await self.patch_boot_seq(ordered_devices)
else:
self.logger.warning("No changes were made since the boot order already matches the requested.")
async def patch_boot_seq(self, ordered_devices):
_boot_seq = await self.get_boot_seq()
boot_sources_uri = "%s/BootSources/Settings" % self.system_resource
url = "%s%s" % (self.host_uri, boot_sources_uri)
payload = {"Attributes": {_boot_seq: ordered_devices}}
headers = {"content-type": "application/json"}
response = None
_status_code = 400
for _ in range(self.retries):
if _status_code != 200:
response = await self.patch_request(url, payload, headers, True)
if response:
raw = await response.text("utf-8", "ignore")
self.logger.debug(raw)
_status_code = response.status
else:
break
if _status_code == 200:
self.logger.debug("PATCH command passed to update boot order.")
else:
self.logger.error("There was something wrong with your request.")
if response:
await self.error_handler(response)
async def set_next_boot_pxe(self):
_url = "%s%s" % (self.host_uri, self.system_resource)
_payload = {
"Boot": {
"BootSourceOverrideTarget": "Pxe",
"BootSourceOverrideEnabled": "Once",
}
}
_headers = {"content-type": "application/json"}
_response = await self.patch_request(_url, _payload, _headers)
await asyncio.sleep(5)
if _response.status == 200:
self.logger.info('PATCH command passed to set next boot onetime boot device to: "%s".' % "Pxe")
else:
self.logger.error("Command failed, error code is %s." % _response.status)
await self.error_handler(_response)
async def check_supported_idrac_version(self):
_url = "%s/Dell/Managers/iDRAC.Embedded.1/DellJobService/" % self.root_uri
_response = await self.get_request(_url)
if _response.status != 200:
self.logger.warning("iDRAC version installed does not support DellJobService")
return False
return True
async def check_supported_network_interfaces(self, endpoint):
_url = "%s%s/%s" % (self.host_uri, self.system_resource, endpoint)
_response = await self.get_request(_url)
if _response.status != 200:
return False
return True
async def delete_job_queue_dell(self, force):
_url = "%s/Dell/Managers/iDRAC.Embedded.1/DellJobService/Actions/DellJobService.DeleteJobQueue" % self.root_uri
job_id = "JID_CLEARALL"
if force:
job_id = f"{job_id}_FORCE"
_payload = {"JobID": job_id}
_headers = {"content-type": "application/json"}
response = await self.post_request(_url, _payload, _headers)
if response.status == 200:
self.logger.info("Job queue for iDRAC %s successfully cleared." % self.host)
else:
await self.error_handler(
response,
message="Job queue not cleared, there was something wrong with your request.",
)
async def delete_job_queue_force(self):
_url = "%s%s/Jobs" % (self.host_uri, self.manager_resource)
_headers = {"content-type": "application/json"}
url = "%s/JID_CLEARALL_FORCE" % _url
try:
_response = await self.delete_request(url, _headers)
if _response.status in [200, 204]:
self.logger.info("Job queue for iDRAC %s successfully cleared." % self.host)
except BadfishException as ex:
self.logger.debug(ex)
raise BadfishException("There was something wrong clearing the job queue.")
return _response
async def clear_job_list(self, _job_queue):
_url = "%s%s/Jobs" % (self.host_uri, self.manager_resource)
_headers = {"content-type": "application/json"}
self.logger.warning("Clearing job queue for job IDs: %s." % _job_queue)
for _job in _job_queue:
job = _job.strip("'")
url = "/".join([_url, job])
response = await self.delete_request(url, _headers)
if response.status != 200:
raise BadfishException("Job queue not cleared, there was something wrong with your request.")
self.logger.info("Job queue for iDRAC %s successfully cleared." % self.host)
return True
async def clear_job_queue(self, force=False):
_job_queue = await self.get_job_queue()
if _job_queue or force:
supported = await self.check_supported_idrac_version()
if supported:
await self.delete_job_queue_dell(force)
else:
try:
_response = await self.delete_job_queue_force()
if _response.status == 400:
await self.clear_job_list(_job_queue)
except BadfishException:
self.logger.info("Attempting to clear job list instead.")
await self.clear_job_list(_job_queue)
else:
self.logger.warning("Job queue already cleared for iDRAC %s, DELETE command will not execute." % self.host)
async def list_job_queue(self):
_job_queue = await self.get_job_queue()
if _job_queue:
self.logger.info("Found active jobs:")
for job in _job_queue:
self.logger.info(" JobID: " + job)
else:
self.logger.info("Found active jobs: None")
async def create_job(self, _url, _payload, _headers, expected=None):
if not expected:
expected = [200, 204]
_response = await self.post_request(_url, _payload, _headers)
status_code = _response.status
if status_code in expected:
self.logger.debug("POST command passed to create target config job.")
else: # pragma: no cover
# Defensive error handling: POST failures typically raise exceptions in http_client
# before returning, making this path difficult to test in isolation
self.logger.error("POST command failed to create BIOS config job, status_code is %s." % status_code)
await self.error_handler(_response)
job_id = self._extract_job_id_from_response(_response, warn_on_missing=False)
if job_id:
self.logger.debug("%s job ID successfully created" % job_id)
return job_id
async def create_bios_config_job(self, uri):
_url = "%s%s/Jobs" % (self.host_uri, self.manager_resource)
_payload = {"TargetSettingsURI": "%s%s" % (self.redfish_uri, uri)}
_headers = {"content-type": "application/json"}
return await self.create_job(_url, _payload, _headers)
async def check_schedule_job_status(self, job_id):
_url = f"{self.host_uri}{self.manager_resource}/Jobs/{job_id}"
_response = await self.get_request(_url)
if _response:
status_code = _response.status
raw = await _response.text("utf-8", "ignore")
data = json.loads(raw.strip())
if status_code == 200:
await asyncio.sleep(10)
# Only try to access job data if we got a successful response
if isinstance(data, dict) and "Id" in data:
self.logger.info(f"JobID: {data[u'Id']}")
self.logger.info(f"Name: {data[u'Name']}")
self.logger.info(f"Message: {data[u'Message']}")
self.logger.info(f"PercentComplete: {str(data[u'PercentComplete'])}")
else:
self.logger.error(f"Command failed to check job status, return code is {status_code}")
self.logger.debug(f"Extended Info Message: {data}")
return False
else:
self.logger.error("Command failed to check job status")
return False
async def check_job_status(self, job_id):
with polling_progress(
self.console, self.retries, "Status", disable=self._progress_disabled
) as (progress, task_id):
for count in range(self.retries):
_url = f"{self.host_uri}{self.manager_resource}/Jobs/{job_id}"
self.http_client.get_request.cache_clear()
_response = await self.get_request(_url)
status_code = _response.status
raw = await _response.text("utf-8", "ignore")
data = json.loads(raw.strip())
if status_code != 200:
self.logger.error(f"Command failed to check job status, return code is {status_code}")
self.logger.debug(f"Extended Info Message: {data}")
return False
if "Message" not in data:
self.logger.warning("Job status response missing Message field")
return False
if "Fail" in data["Message"] or "fail" in data["Message"]:
self.logger.debug(f"\n{job_id} job failed.")
return False
elif data["Message"] == "Job completed successfully.":
self.logger.info(f"JobID: {data[u'Id']}")
self.logger.info(f"Name: {data[u'Name']}")
self.logger.info(f"Message: {data[u'Message']}")
self.logger.info(f"PercentComplete: {str(data[u'PercentComplete'])}")
break
else:
progress.update(task_id, completed=count + 1, state=data["Message"])
await asyncio.sleep(30)
def _extract_job_id_from_response(self, response, warn_on_missing=True, context=""):
"""
Extract job ID from HTTP response Location header.
Args:
response: HTTP response object with headers
warn_on_missing: If True, log warning when job ID not found. If False, log error.
context: Additional context message to append to warning/error (optional)
Returns:
Job ID string or None if not found
"""
try:
job_id = response.headers.get("Location", "").split("/")[-1]
if job_id:
return job_id
else:
if warn_on_missing:
msg = "No job ID returned in Location header."
if context:
msg += f" {context}"
self.logger.warning(msg)
else:
self.logger.error("Failed to find a job ID in headers of the response.")
return None
except (AttributeError, ValueError, KeyError) as e: # pragma: no cover
# Defensive: headers.get() raising exceptions is extremely rare in practice
if warn_on_missing:
msg = f"Could not extract job ID from response headers: {e}"
if context:
msg += f" {context}"
self.logger.warning(msg)
else:
self.logger.error(f"Failed to find a job ID in headers of the response: {e}")
return None
async def _verify_job_scheduled(self, job_id, context="configuration"):
"""
Verify that a job has been scheduled and is not already failed.
This is typically called before rebooting to ensure the job is in a good state.
Args:
job_id: The job ID to verify
context: Description of the job context for error messages (default: "configuration")
Returns:
True if job is scheduled successfully, False if job failed or inaccessible
"""
self.logger.info(f"Waiting for {context} job to be scheduled...")
# Give job a moment to register in job queue
await asyncio.sleep(2)
# Check job status to ensure it's scheduled properly
job_url = f"{self.host_uri}{self.manager_resource}/Jobs/{job_id}"
try:
job_response = await self.get_request(job_url)
if job_response.status == 200:
job_raw = await job_response.text("utf-8", "ignore")
job_data = json.loads(job_raw.strip())
job_state = job_data.get("JobState", "Unknown")
job_message = job_data.get("Message", "No message")
self.logger.info(f"Job {job_id} status: {job_state} - {job_message}")
if "Fail" in job_message or "fail" in job_message or job_state == "Failed":
self.logger.error(f"{context.capitalize()} job failed before reboot: {job_message}")
return False
return True
else: # pragma: no cover
# Defensive: non-200 responses during job verification are rare
self.logger.warning(
f"Could not verify job status (HTTP {job_response.status}). Proceeding with reboot."
)
return True # Don't block on verification failure
except Exception as e: # pragma: no cover
# Defensive: exceptions during job status check are rare in practice
self.logger.warning(f"Could not check job status before reboot: {e}. Proceeding anyway.")
return True # Don't block on verification failure
async def _monitor_and_verify_attribute_job(
self, job_id, fqdd, attribute, expected_value, attr_type, original_value
):
"""
Monitor job completion and verify the attribute value was actually applied.
This handles the full post-reboot workflow:
1. Wait for job to complete
2. If job fails, still verify the actual value (detect false negatives)
3. If job succeeds, verify the value matches expectation
Args:
job_id: The job ID to monitor
fqdd: NIC FQDD (e.g., "NIC.Embedded.1-1-1")
attribute: Attribute name (e.g., "WakeOnLan")
expected_value: Expected value after change
attr_type: Attribute type ("Integer", "String", "Enumeration")
original_value: Original value before change (for logging)