-
Notifications
You must be signed in to change notification settings - Fork 6
/
openbmctool.py
executable file
·5408 lines (4713 loc) · 241 KB
/
openbmctool.py
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
"""
Copyright 2017,2019 IBM Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import argparse
import requests
import getpass
import json
import os
import urllib3
import time, datetime
import binascii
import subprocess
import platform
import zipfile
import tarfile
import tempfile
import hashlib
import re
import uuid
import ssl
import socket
import select
import http.client
from subprocess import check_output
import traceback
MAX_NBD_PACKET_SIZE = 131088
jsonHeader = {'Content-Type' : 'application/json'}
xAuthHeader = {}
baseTimeout = 60
serverTypeMap = {
'ActiveDirectory' : 'active_directory',
'OpenLDAP' : 'openldap'
}
class NBDPipe:
def openHTTPSocket(self,args):
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
pass
else:
# Handle target environment that doesn't support HTTPS verification
ssl._create_default_https_context = _create_unverified_https_context
token = gettoken(args)
self.conn = http.client.HTTPSConnection(args.host,port=443)
uri = "/redfish/v1/Systems/system/LogServices/Dump/attachment/"+args.dumpNum
self.conn.request("GET",uri, headers={"X-Auth-Token":token})
def openTCPSocket(self):
# Create a TCP/IP socket
self.tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 1043)
self.tcp.connect(server_address)
def waitformessage(self):
inputs = [self.conn.sock,self.tcp]
outputs = []
message_queues = {}
while True:
readable, writable, exceptional = select.select(
inputs, outputs, inputs)
for s in readable:
if s is self.conn.sock:
data = self.conn.sock.recv(MAX_NBD_PACKET_SIZE)
print("<<HTTP")
if data:
self.tcp.send(data)
else:
print ("BMC Closed the connection")
self.conn.close()
self.tcp.close()
sys.exit(1)
elif s is self.tcp:
data = self.tcp.recv(MAX_NBD_PACKET_SIZE)
print(">>TCP")
if data:
self.conn.sock.send(data)
else:
print("NBD server closed the connection")
self.conn.sock.close()
self.tcp.close()
sys.exit(1)
for s in exceptional:
inputs.remove(s)
print("Exceptional closing the socket")
s.close()
def getsize(host,args,session):
url = "https://"+host+"/redfish/v1/Systems/system/LogServices/Dump/Entries/"+str(args.dumpNum)
try:
resp = session.get(url, headers=jsonHeader, verify=False, timeout=baseTimeout)
if resp.status_code==200:
size = resp.json()['AdditionalDataSizeBytes']
return size
else:
return "Failed get Size"
except(requests.exceptions.Timeout):
return connectionErrHandler(args.json, "Timeout", None)
except(requests.exceptions.ConnectionError) as err:
return connectionErrHandler(args.json, "ConnectionError", err)
def gettoken(args):
mysess = requests.session()
resp = mysess.post('https://'+args.host+'/login', headers=jsonHeader,json={"data":[args.user,args.PW]},verify=False)
if resp.status_code == 200:
cookie = resp.headers['Set-Cookie']
match = re.search('SESSION=(\w+);', cookie)
return match.group(1)
def get_pid(name):
try:
pid = map(int, check_output(["pidof", "-s",name]))
except Exception:
pid = 0
return pid
def findThisProcess( process_name ):
ps = subprocess.Popen("ps -eaf | grep "+process_name, shell=True, stdout=subprocess.PIPE)
output = ps.stdout.read()
ps.stdout.close()
ps.wait()
pid = get_pid(process_name)
return output
def isThisProcessRunning( process_name ):
pid = get_pid(process_name)
if (pid == 0 ):
return False
else:
return True
def NBDSetup(host,args,session):
user=os.getenv("SUDO_USER")
if user is None:
path = os.getcwd()
nbdServerPath = path + "/nbd-server"
if not os.path.exists(nbdServerPath):
print("Error: this program did not run as sudo!\nplease copy nbd-server to current directory and run script again")
exit()
if isThisProcessRunning('nbd-server') == True:
print("nbd-server already Running! killing the nbd-server")
os.system('killall nbd-server')
if (args.dumpSaveLoc is not None):
if(os.path.exists(args.dumpSaveLoc)):
print("Error: File already exists.")
exit()
fp= open(args.dumpSaveLoc,"w")
sizeInBytes = getsize(host,args,session)
#Round off size to mutiples of 1024
size = int(sizeInBytes)
mod = size % 1024
if mod :
roundoff = 1024 - mod
size = size + roundoff
cmd = 'chmod 777 ' + args.dumpSaveLoc
os.system(cmd)
#Run truncate to create file with given size
cmd = 'truncate -s ' + str(size) + ' '+ args.dumpSaveLoc
os.system(cmd)
if user is None:
cmd = './nbd-server 1043 '+ args.dumpSaveLoc
else:
cmd = 'nbd-server 1043 '+ args.dumpSaveLoc
os.system(cmd)
def hilight(textToColor, color, bold):
"""
Used to add highlights to various text for displaying in a terminal
@param textToColor: string, the text to be colored
@param color: string, used to color the text red or green
@param bold: boolean, used to bold the textToColor
@return: Buffered reader containing the modified string.
"""
if(sys.platform.__contains__("win")):
if(color == "red"):
os.system('color 04')
elif(color == "green"):
os.system('color 02')
else:
os.system('color') #reset to default
return textToColor
else:
attr = []
if(color == "red"):
attr.append('31')
elif(color == "green"):
attr.append('32')
else:
attr.append('0')
if bold:
attr.append('1')
else:
attr.append('0')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr),textToColor)
def connectionErrHandler(jsonFormat, errorStr, err):
"""
Error handler various connection errors to bmcs
@param jsonFormat: boolean, used to output in json format with an error code.
@param errorStr: string, used to color the text red or green
@param err: string, the text from the exception
"""
if errorStr == "Timeout":
if not jsonFormat:
return("FQPSPIN0000M: Connection timed out. Ensure you have network connectivity to the bmc")
else:
conerror = {}
conerror['CommonEventID'] = 'FQPSPIN0000M'
conerror['sensor']="N/A"
conerror['state']="N/A"
conerror['additionalDetails'] = "N/A"
conerror['Message']="Connection timed out. Ensure you have network connectivity to the BMC"
conerror['LengthyDescription'] = "While trying to establish a connection with the specified BMC, the BMC failed to respond in adequate time. Verify the BMC is functioning properly, and the network connectivity to the BMC is stable."
conerror['Serviceable']="Yes"
conerror['CallHomeCandidate']= "No"
conerror['Severity'] = "Critical"
conerror['EventType'] = "Communication Failure/Timeout"
conerror['VMMigrationFlag'] = "Yes"
conerror["AffectedSubsystem"] = "Interconnect (Networking)"
conerror["timestamp"] = str(int(time.time()))
conerror["UserAction"] = "Verify network connectivity between the two systems and the bmc is functional."
eventdict = {}
eventdict['event0'] = conerror
eventdict['numAlerts'] = '1'
errorMessageStr = errorMessageStr = json.dumps(eventdict, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
return(errorMessageStr)
elif errorStr == "ConnectionError":
if not jsonFormat:
return("FQPSPIN0001M: " + str(err))
else:
conerror = {}
conerror['CommonEventID'] = 'FQPSPIN0001M'
conerror['sensor']="N/A"
conerror['state']="N/A"
conerror['additionalDetails'] = str(err)
conerror['Message']="Connection Error. View additional details for more information"
conerror['LengthyDescription'] = "A connection error to the specified BMC occurred and additional details are provided. Review these details to resolve the issue."
conerror['Serviceable']="Yes"
conerror['CallHomeCandidate']= "No"
conerror['Severity'] = "Critical"
conerror['EventType'] = "Communication Failure/Timeout"
conerror['VMMigrationFlag'] = "Yes"
conerror["AffectedSubsystem"] = "Interconnect (Networking)"
conerror["timestamp"] = str(int(time.time()))
conerror["UserAction"] = "Correct the issue highlighted in additional details and try again"
eventdict = {}
eventdict['event0'] = conerror
eventdict['numAlerts'] = '1'
errorMessageStr = json.dumps(eventdict, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
return(errorMessageStr)
else:
return("Unknown Error: "+ str(err))
def setColWidth(keylist, numCols, dictForOutput, colNames):
"""
Sets the output width of the columns to display
@param keylist: list, list of strings representing the keys for the dictForOutput
@param numcols: the total number of columns in the final output
@param dictForOutput: dictionary, contains the information to print to the screen
@param colNames: list, The strings to use for the column headings, in order of the keylist
@return: A list of the column widths for each respective column.
"""
colWidths = []
for x in range(0, numCols):
colWidths.append(0)
for key in dictForOutput:
for x in range(0, numCols):
colWidths[x] = max(colWidths[x], len(str(dictForOutput[key][keylist[x]])))
for x in range(0, numCols):
colWidths[x] = max(colWidths[x], len(colNames[x])) +2
return colWidths
def loadPolicyTable(pathToPolicyTable):
"""
loads a json based policy table into a dictionary
@param value: boolean, the value to convert
@return: A string of "Yes" or "No"
"""
policyTable = {}
if(os.path.exists(pathToPolicyTable)):
with open(pathToPolicyTable, 'r') as stream:
try:
contents =json.load(stream)
policyTable = contents['events']
except Exception as err:
print(err)
return policyTable
def boolToString(value):
"""
converts a boolean value to a human readable string value
@param value: boolean, the value to convert
@return: A string of "Yes" or "No"
"""
if(value):
return "Yes"
else:
return "No"
def stringToInt(text):
"""
returns an integer if the string can be converted, otherwise returns the string
@param text: the string to try to convert to an integer
"""
if text.isdigit():
return int(text)
else:
return text
def naturalSort(text):
"""
provides a way to naturally sort a list
@param text: the key to convert for sorting
@return list containing the broken up string parts by integers and strings
"""
stringPartList = []
for c in re.split('(\d+)', text):
stringPartList.append(stringToInt(c))
return stringPartList
def tableDisplay(keylist, colNames, output):
"""
Logs into the BMC and creates a session
@param keylist: list, keys for the output dictionary, ordered by colNames
@param colNames: Names for the Table of the columns
@param output: The dictionary of data to display
@return: Session object
"""
colWidth = setColWidth(keylist, len(colNames), output, colNames)
row = ""
outputText = ""
for i in range(len(colNames)):
if (i != 0): row = row + "| "
row = row + colNames[i].ljust(colWidth[i])
outputText += row + "\n"
output_keys = list(output.keys())
output_keys.sort(key=naturalSort)
for key in output_keys:
row = ""
for i in range(len(keylist)):
if (i != 0): row = row + "| "
row = row + output[key][keylist[i]].ljust(colWidth[i])
outputText += row + "\n"
return outputText
def checkFWactivation(host, args, session):
"""
Checks the software inventory for an image that is being activated.
@return: True if an image is being activated, false is no activations are happening
"""
url="https://"+host+"/xyz/openbmc_project/software/enumerate"
try:
resp = session.get(url, headers=jsonHeader, verify=False, timeout=baseTimeout)
except(requests.exceptions.Timeout):
print(connectionErrHandler(args.json, "Timeout", None))
return(True)
except(requests.exceptions.ConnectionError) as err:
print( connectionErrHandler(args.json, "ConnectionError", err))
return True
fwInfo = resp.json()['data']
for key in fwInfo:
if 'Activation' in fwInfo[key]:
if 'Activating' in fwInfo[key]['Activation'] or 'Activating' in fwInfo[key]['RequestedActivation']:
return True
return False
def login(host, username, pw,jsonFormat, allowExpiredPassword):
"""
Logs into the BMC and creates a session
@param host: string, the hostname or IP address of the bmc to log into
@param username: The user name for the bmc to log into
@param pw: The password for the BMC to log into
@param jsonFormat: boolean, flag that will only allow relevant data from user command to be display. This function becomes silent when set to true.
@param allowExpiredPassword: true, if the requested operation should
be allowed when the password is expired
@return: Session object
"""
if(jsonFormat==False):
print("Attempting login...")
mysess = requests.session()
try:
r = mysess.post('https://'+host+'/login', headers=jsonHeader, json = {"data": [username, pw]}, verify=False, timeout=baseTimeout)
if r.status_code == 200:
cookie = r.headers['Set-Cookie']
match = re.search('SESSION=(\w+);', cookie)
if match:
xAuthHeader['X-Auth-Token'] = match.group(1)
jsonHeader.update(xAuthHeader)
loginMessage = json.loads(r.text)
if (loginMessage['status'] != "ok"):
print(loginMessage["data"]["description"].encode('utf-8'))
sys.exit(1)
if (('extendedMessage' in r.json()) and
('The password for this account must be changed' in r.json()['extendedMessage'])):
if not allowExpiredPassword:
print("The password for this system has expired and must be changed"+
"\nsee openbmctool.py set_password --help")
logout(host, username, pw, mysess, jsonFormat)
sys.exit(1)
# if(sys.version_info < (3,0)):
# urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# if sys.version_info >= (3,0):
# requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
return mysess
else:
return None
except(requests.exceptions.Timeout):
return (connectionErrHandler(jsonFormat, "Timeout", None))
except(requests.exceptions.ConnectionError) as err:
return (connectionErrHandler(jsonFormat, "ConnectionError", err))
def logout(host, username, pw, session, jsonFormat):
"""
Logs out of the bmc and terminates the session
@param host: string, the hostname or IP address of the bmc to log out of
@param username: The user name for the bmc to log out of
@param pw: The password for the BMC to log out of
@param session: the active session to use
@param jsonFormat: boolean, flag that will only allow relevant data from user command to be display. This function becomes silent when set to true.
"""
try:
r = session.post('https://'+host+'/logout', headers=jsonHeader,json = {"data": [username, pw]}, verify=False, timeout=baseTimeout)
except(requests.exceptions.Timeout):
print(connectionErrHandler(jsonFormat, "Timeout", None))
if(jsonFormat==False):
if r.status_code == 200:
print('User ' +username + ' has been logged out')
def fru(host, args, session):
"""
prints out the system inventory. deprecated see fruPrint and fruList
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the fru sub command
@param session: the active session to use
@param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
"""
#url="https://"+host+"/org/openbmc/inventory/system/chassis/enumerate"
#print(url)
#res = session.get(url, headers=httpHeader, verify=False)
#print(res.text)
#sample = res.text
#inv_list = json.loads(sample)["data"]
url="https://"+host+"/xyz/openbmc_project/inventory/enumerate"
try:
res = session.get(url, headers=jsonHeader, verify=False, timeout=baseTimeout)
except(requests.exceptions.Timeout):
return(connectionErrHandler(args.json, "Timeout", None))
sample = res.text
# inv_list.update(json.loads(sample)["data"])
#
# #determine column width's
# colNames = ["FRU Name", "FRU Type", "Has Fault", "Is FRU", "Present", "Version"]
# colWidths = setColWidth(["FRU Name", "fru_type", "fault", "is_fru", "present", "version"], 6, inv_list, colNames)
#
# print("FRU Name".ljust(colWidths[0])+ "FRU Type".ljust(colWidths[1]) + "Has Fault".ljust(colWidths[2]) + "Is FRU".ljust(colWidths[3])+
# "Present".ljust(colWidths[4]) + "Version".ljust(colWidths[5]))
# format the output
# for key in sorted(inv_list.keys()):
# keyParts = key.split("/")
# isFRU = "True" if (inv_list[key]["is_fru"]==1) else "False"
#
# fruEntry = (keyParts[len(keyParts) - 1].ljust(colWidths[0]) + inv_list[key]["fru_type"].ljust(colWidths[1])+
# inv_list[key]["fault"].ljust(colWidths[2])+isFRU.ljust(colWidths[3])+
# inv_list[key]["present"].ljust(colWidths[4])+ inv_list[key]["version"].ljust(colWidths[5]))
# if(isTTY):
# if(inv_list[key]["is_fru"] == 1):
# color = "green"
# bold = True
# else:
# color='black'
# bold = False
# fruEntry = hilight(fruEntry, color, bold)
# print (fruEntry)
return sample
def fruPrint(host, args, session):
"""
prints out all inventory
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the fru sub command
@param session: the active session to use
@param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
@return returns the total fru list.
"""
url="https://"+host+"/xyz/openbmc_project/inventory/enumerate"
try:
res = session.get(url, headers=jsonHeader, verify=False, timeout=baseTimeout)
except(requests.exceptions.Timeout):
return(connectionErrHandler(args.json, "Timeout", None))
frulist={}
# print(res.text)
if res.status_code==200:
frulist['Hardware'] = res.json()['data']
else:
if not args.json:
return "Error retrieving the system inventory. BMC message: {msg}".format(msg=res.json()['message'])
else:
return res.json()
url="https://"+host+"/xyz/openbmc_project/software/enumerate"
try:
res = session.get(url, headers=jsonHeader, verify=False, timeout=baseTimeout)
except(requests.exceptions.Timeout):
return(connectionErrHandler(args.json, "Timeout", None))
# print(res.text)
if res.status_code==200:
frulist['Software'] = res.json()['data']
else:
if not args.json():
return "Error retrieving the system inventory. BMC message: {msg}".format(msg=res.json()['message'])
else:
return res.json()
return frulist
def fruList(host, args, session):
"""
prints out all inventory or only a specific specified item
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the fru sub command
@param session: the active session to use
@param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
"""
if(args.items==True):
return fruPrint(host, args, session)
else:
return fruPrint(host, args, session)
def fruStatus(host, args, session):
"""
prints out the status of all FRUs
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the fru sub command
@param session: the active session to use
@param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
"""
url="https://"+host+"/xyz/openbmc_project/inventory/enumerate"
try:
res = session.get(url, headers=jsonHeader, verify=False)
except(requests.exceptions.Timeout):
return(connectionErrHandler(args.json, "Timeout", None))
# print(res.text)
frulist = res.json()['data']
frus = {}
for key in frulist:
component = frulist[key]
isFru = False
present = False
func = False
hasSels = False
keyPieces = key.split('/')
fruName = keyPieces[-1]
if 'core' in fruName: #associate cores to cpus
fruName = keyPieces[-2] + '-' + keyPieces[-1]
if 'Functional' in component:
if('Present' in component):
if 'FieldReplaceable' in component:
if component['FieldReplaceable'] == 1:
isFru = True
if "fan" in fruName:
isFru = True;
if component['Present'] == 1:
present = True
if component['Functional'] == 1:
func = True
if ((key + "/fault") in frulist):
hasSels = True;
if args.verbose:
if hasSels:
loglist = []
faults = frulist[key+"/fault"]['endpoints']
for item in faults:
loglist.append(item.split('/')[-1])
frus[fruName] = {"compName": fruName, "Functional": boolToString(func), "Present":boolToString(present), "IsFru": boolToString(isFru), "selList": ', '.join(loglist).strip() }
else:
frus[fruName] = {"compName": fruName, "Functional": boolToString(func), "Present":boolToString(present), "IsFru": boolToString(isFru), "selList": "None" }
else:
frus[fruName] = {"compName": fruName, "Functional": boolToString(func), "Present":boolToString(present), "IsFru": boolToString(isFru), "hasSEL": boolToString(hasSels) }
elif "power_supply" in fruName or "powersupply" in fruName:
if component['Present'] ==1:
present = True
isFru = True
if ((key + "/fault") in frulist):
hasSels = True;
if args.verbose:
if hasSels:
loglist = []
faults = frulist[key+"/fault"]['endpoints']
for item in faults:
loglist.append(item.split('/')[-1])
frus[fruName] = {"compName": fruName, "Functional": "No", "Present":boolToString(present), "IsFru": boolToString(isFru), "selList": ', '.join(loglist).strip() }
else:
frus[fruName] = {"compName": fruName, "Functional": "Yes", "Present":boolToString(present), "IsFru": boolToString(isFru), "selList": "None" }
else:
frus[fruName] = {"compName": fruName, "Functional": boolToString(not hasSels), "Present":boolToString(present), "IsFru": boolToString(isFru), "hasSEL": boolToString(hasSels) }
if not args.json:
if not args.verbose:
colNames = ["Component", "Is a FRU", "Present", "Functional", "Has Logs"]
keylist = ["compName", "IsFru", "Present", "Functional", "hasSEL"]
else:
colNames = ["Component", "Is a FRU", "Present", "Functional", "Assoc. Log Number(s)"]
keylist = ["compName", "IsFru", "Present", "Functional", "selList"]
return tableDisplay(keylist, colNames, frus)
else:
return str(json.dumps(frus, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False))
def sensor(host, args, session):
"""
prints out all sensors
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the sensor sub command
@param session: the active session to use
@param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
"""
url="https://"+host+"/xyz/openbmc_project/sensors/enumerate"
try:
res = session.get(url, headers=jsonHeader, verify=False, timeout=baseTimeout)
except(requests.exceptions.Timeout):
return(connectionErrHandler(args.json, "Timeout", None))
#Get OCC status
url="https://"+host+"/org/open_power/control/enumerate"
try:
occres = session.get(url, headers=jsonHeader, verify=False, timeout=baseTimeout)
except(requests.exceptions.Timeout):
return(connectionErrHandler(args.json, "Timeout", None))
if not args.json:
colNames = ['sensor', 'type', 'units', 'value', 'target']
sensors = res.json()["data"]
output = {}
for key in sensors:
senDict = {}
keyparts = key.split("/")
# Associations like the following also show up here:
# /xyz/openbmc_project/sensors/<type>/<name>/<assoc-name>
# Skip them.
# Note: keyparts[0] = '' which is why there are 7 segments.
if len(keyparts) > 6:
continue
senDict['sensorName'] = keyparts[-1]
senDict['type'] = keyparts[-2]
try:
senDict['units'] = sensors[key]['Unit'].split('.')[-1]
except KeyError:
senDict['units'] = "N/A"
if('Scale' in sensors[key]):
scale = 10 ** sensors[key]['Scale']
else:
scale = 1
try:
senDict['value'] = str(sensors[key]['Value'] * scale)
except KeyError:
if 'value' in sensors[key]:
senDict['value'] = sensors[key]['value']
else:
senDict['value'] = "N/A"
if 'Target' in sensors[key]:
senDict['target'] = str(sensors[key]['Target'])
else:
senDict['target'] = 'N/A'
output[senDict['sensorName']] = senDict
occstatus = occres.json()["data"]
if '/org/open_power/control/occ0' in occstatus:
occ0 = occstatus["/org/open_power/control/occ0"]['OccActive']
if occ0 == 1:
occ0 = 'Active'
else:
occ0 = 'Inactive'
output['OCC0'] = {'sensorName':'OCC0', 'type': 'Discrete', 'units': 'N/A', 'value': occ0, 'target': 'Active'}
occ1 = occstatus["/org/open_power/control/occ1"]['OccActive']
if occ1 == 1:
occ1 = 'Active'
else:
occ1 = 'Inactive'
output['OCC1'] = {'sensorName':'OCC1', 'type': 'Discrete', 'units': 'N/A', 'value': occ0, 'target': 'Active'}
else:
output['OCC0'] = {'sensorName':'OCC0', 'type': 'Discrete', 'units': 'N/A', 'value': 'Inactive', 'target': 'Inactive'}
output['OCC1'] = {'sensorName':'OCC1', 'type': 'Discrete', 'units': 'N/A', 'value': 'Inactive', 'target': 'Inactive'}
keylist = ['sensorName', 'type', 'units', 'value', 'target']
return tableDisplay(keylist, colNames, output)
else:
return res.text + occres.text
def sel(host, args, session):
"""
prints out the bmc alerts
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the sel sub command
@param session: the active session to use
@param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
"""
url="https://"+host+"/xyz/openbmc_project/logging/entry/enumerate"
try:
res = session.get(url, headers=jsonHeader, verify=False, timeout=baseTimeout)
except(requests.exceptions.Timeout):
return(connectionErrHandler(args.json, "Timeout", None))
return res.text
def parseESEL(args, eselRAW):
"""
parses the esel data and gets predetermined search terms
@param eselRAW: string, the raw esel string from the bmc
@return: A dictionary containing the quick snapshot data unless args.fullEsel is listed then a full PEL log is returned
"""
eselParts = {}
esel_bin = binascii.unhexlify(''.join(eselRAW.split()[16:]))
#search terms contains the search term as the key and the return dictionary key as it's value
searchTerms = { 'Signature Description':'signatureDescription', 'devdesc':'devdesc',
'Callout type': 'calloutType', 'Procedure':'procedure', 'Sensor Type': 'sensorType'}
uniqueID = str(uuid.uuid4())
eselBinPath = tempfile.gettempdir() + os.sep + uniqueID + 'esel.bin'
with open(eselBinPath, 'wb') as f:
f.write(esel_bin)
errlPath = ""
#use the right errl file for the machine architecture
arch = platform.machine()
if(arch =='x86_64' or arch =='AMD64'):
if os.path.exists('/opt/ibm/ras/bin/x86_64/errl'):
errlPath = '/opt/ibm/ras/bin/x86_64/errl'
elif os.path.exists('errl/x86_64/errl'):
errlPath = 'errl/x86_64/errl'
else:
errlPath = 'x86_64/errl'
elif (platform.machine()=='ppc64le'):
if os.path.exists('/opt/ibm/ras/bin/ppc64le/errl'):
errlPath = '/opt/ibm/ras/bin/ppc64le/errl'
elif os.path.exists('errl/ppc64le/errl'):
errlPath = 'errl/ppc64le/errl'
else:
errlPath = 'ppc64le/errl'
else:
print("machine architecture not supported for parsing eSELs")
return eselParts
if(os.path.exists(errlPath)):
output= subprocess.check_output([errlPath, '-d', '--file='+eselBinPath]).decode('utf-8')
# output = proc.communicate()[0]
lines = output.split('\n')
if(hasattr(args, 'fullEsel')):
return output
for i in range(0, len(lines)):
lineParts = lines[i].split(':')
if(len(lineParts)>1): #ignore multi lines, output formatting lines, and other information
for term in searchTerms:
if(term in lineParts[0]):
temp = lines[i][lines[i].find(':')+1:].strip()[:-1].strip()
if lines[i+1].find(':') != -1:
if (len(lines[i+1].split(':')[0][1:].strip())==0):
while(len(lines[i][:lines[i].find(':')].strip())>2):
#has multiple lines, process and update line counter
if((i+1) <= len(lines)):
i+=1
else:
i=i-1
break
#Append the content from the next line removing the pretty display characters
#Finds the first colon then starts 2 characters after, then removes all whitespace
temp = temp + lines[i][lines[i].find(':')+2:].strip()[:-1].strip()[:-1].strip()
if(searchTerms[term] in eselParts):
eselParts[searchTerms[term]] = eselParts[searchTerms[term]] + ", " + temp
else:
eselParts[searchTerms[term]] = temp
os.remove(eselBinPath)
else:
print("errl file cannot be found")
return eselParts
def getESELSeverity(esel):
"""
Finds the severity type in an eSEL from the User Header section.
@param esel - the eSEL data
@return severity - e.g. 'Critical'
"""
# everything but 1 and 2 are Critical
# '1': 'recovered',
# '2': 'predictive',
# '4': 'unrecoverable',
# '5': 'critical',
# '6': 'diagnostic',
# '7': 'symptom'
severities = {
'1': 'Informational',
'2': 'Warning'
}
try:
headerPosition = esel.index('55 48') # 'UH'
# The severity is the last byte in the 8 byte section (a byte is ' bb')
severity = esel[headerPosition:headerPosition+32].split(' ')[-1]
type = severity[0]
except ValueError:
print("Could not find severity value in UH section in eSEL")
type = 'x';
return severities.get(type, 'Critical')
def sortSELs(events):
"""
sorts the sels by timestamp, then log entry number
@param events: Dictionary containing events
@return: list containing a list of the ordered log entries, and dictionary of keys
"""
logNumList = []
timestampList = []
eventKeyDict = {}
eventsWithTimestamp = {}
logNum2events = {}
for key in events:
if key == 'numAlerts': continue
if 'callout' in key: continue
timestamp = (events[key]['timestamp'])
if timestamp not in timestampList:
eventsWithTimestamp[timestamp] = [events[key]['logNum']]
else:
eventsWithTimestamp[timestamp].append(events[key]['logNum'])
#map logNumbers to the event dictionary keys
eventKeyDict[str(events[key]['logNum'])] = key
timestampList = list(eventsWithTimestamp.keys())
timestampList.sort()
for ts in timestampList:
if len(eventsWithTimestamp[ts]) > 1:
tmplist = eventsWithTimestamp[ts]
tmplist.sort()
logNumList = logNumList + tmplist
else:
logNumList = logNumList + eventsWithTimestamp[ts]
return [logNumList, eventKeyDict]
def parseAlerts(policyTable, selEntries, args):
"""
parses alerts in the IBM CER format, using an IBM policy Table
@param policyTable: dictionary, the policy table entries
@param selEntries: dictionary, the alerts retrieved from the bmc
@return: A dictionary of the parsed entries, in chronological order
"""
eventDict = {}
eventNum =""
count = 0
esel = ""
eselParts = {}
i2cdevice= ""
eselSeverity = None
'prepare and sort the event entries'
sels = {}
for key in selEntries:
if '/xyz/openbmc_project/logging/entry/' not in key: continue
if 'callout' not in key:
sels[key] = selEntries[key]
sels[key]['logNum'] = key.split('/')[-1]
sels[key]['timestamp'] = selEntries[key]['Timestamp']
sortedEntries = sortSELs(sels)
logNumList = sortedEntries[0]
eventKeyDict = sortedEntries[1]
for logNum in logNumList:
key = eventKeyDict[logNum]
hasEsel=False
i2creadFail = False
if 'callout' in key:
continue
else:
messageID = str(selEntries[key]['Message'])
addDataPiece = selEntries[key]['AdditionalData']
calloutIndex = 0
calloutFound = False
for i in range(len(addDataPiece)):
if("CALLOUT_INVENTORY_PATH" in addDataPiece[i]):
calloutIndex = i
calloutFound = True
fruCallout = str(addDataPiece[calloutIndex]).split('=')[1]
if("CALLOUT_DEVICE_PATH" in addDataPiece[i]):
i2creadFail = True
fruCallout = str(addDataPiece[calloutIndex]).split('=')[1]
# Fall back to "I2C"/"FSI" if dev path isn't in policy table
if (messageID + '||' + fruCallout) not in policyTable:
i2cdevice = str(addDataPiece[i]).strip().split('=')[1]
i2cdevice = '/'.join(i2cdevice.split('/')[-4:])
if 'fsi' in str(addDataPiece[calloutIndex]).split('=')[1]:
fruCallout = 'FSI'
else:
fruCallout = 'I2C'
calloutFound = True
if("CALLOUT_GPIO_NUM" in addDataPiece[i]):
if not calloutFound:
fruCallout = 'GPIO'
calloutFound = True
if("CALLOUT_IIC_BUS" in addDataPiece[i]):
if not calloutFound:
fruCallout = "I2C"
calloutFound = True
if("CALLOUT_IPMI_SENSOR_NUM" in addDataPiece[i]):
if not calloutFound:
fruCallout = "IPMI"
calloutFound = True
if("ESEL" in addDataPiece[i]):
esel = str(addDataPiece[i]).strip().split('=')[1]
eselSeverity = getESELSeverity(esel)
if args.devdebug:
eselParts = parseESEL(args, esel)
hasEsel=True
if("GPU" in addDataPiece[i]):
fruCallout = '/xyz/openbmc_project/inventory/system/chassis/motherboard/gpu' + str(addDataPiece[i]).strip()[-1]
calloutFound = True
if("PROCEDURE" in addDataPiece[i]):
fruCallout = str(hex(int(str(addDataPiece[i]).split('=')[1])))[2:]
calloutFound = True
if("RAIL_NAME" in addDataPiece[i]):
calloutFound=True
fruCallout = str(addDataPiece[i]).split('=')[1].strip()
if("INPUT_NAME" in addDataPiece[i]):