blob: babf6c6bd5ec1210efa71b6eea848389632a5eec [file] [log] [blame]
Justin Thalerb8807ce2018-05-25 19:16:20 -05001#!/usr/bin/python3
Justin Thalere412dc22018-01-12 16:28:24 -06002"""
3 Copyright 2017 IBM Corporation
Justin Thalerf9aee3e2017-12-05 12:11:09 -06004
Justin Thalere412dc22018-01-12 16:28:24 -06005 Licensed under the Apache License, Version 2.0 (the "License");
6 you may not use this file except in compliance with the License.
7 You may obtain a copy of the License at
8
9 http://www.apache.org/licenses/LICENSE-2.0
10
11 Unless required by applicable law or agreed to in writing, software
12 distributed under the License is distributed on an "AS IS" BASIS,
13 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 See the License for the specific language governing permissions and
15 limitations under the License.
16"""
Justin Thalerf9aee3e2017-12-05 12:11:09 -060017import argparse
18import requests
19import getpass
20import json
21import os
22import urllib3
23import time, datetime
Justin Thalerf9aee3e2017-12-05 12:11:09 -060024import binascii
25import subprocess
26import platform
27import zipfile
Justin Thaler22b1bb52018-03-15 13:31:32 -050028import tarfile
29import tempfile
30import hashlib
Justin Thalera6b5df72018-07-16 11:10:07 -050031import re
Justin Thaler24d4efa2018-11-08 22:48:10 -060032import uuid
Justin Thalerf9aee3e2017-12-05 12:11:09 -060033
Justin Thalerf9aee3e2017-12-05 12:11:09 -060034def hilight(textToColor, color, bold):
Justin Thalere412dc22018-01-12 16:28:24 -060035 """
36 Used to add highlights to various text for displaying in a terminal
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -060037
Justin Thalere412dc22018-01-12 16:28:24 -060038 @param textToColor: string, the text to be colored
39 @param color: string, used to color the text red or green
40 @param bold: boolean, used to bold the textToColor
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -060041 @return: Buffered reader containing the modified string.
42 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -060043 if(sys.platform.__contains__("win")):
44 if(color == "red"):
45 os.system('color 04')
46 elif(color == "green"):
47 os.system('color 02')
48 else:
49 os.system('color') #reset to default
50 return textToColor
51 else:
52 attr = []
53 if(color == "red"):
54 attr.append('31')
55 elif(color == "green"):
56 attr.append('32')
57 else:
58 attr.append('0')
59 if bold:
60 attr.append('1')
61 else:
62 attr.append('0')
63 return '\x1b[%sm%s\x1b[0m' % (';'.join(attr),textToColor)
64
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -060065
Justin Thalerf9aee3e2017-12-05 12:11:09 -060066def connectionErrHandler(jsonFormat, errorStr, err):
Justin Thalere412dc22018-01-12 16:28:24 -060067 """
68 Error handler various connection errors to bmcs
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -060069
70 @param jsonFormat: boolean, used to output in json format with an error code.
Justin Thalere412dc22018-01-12 16:28:24 -060071 @param errorStr: string, used to color the text red or green
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -060072 @param err: string, the text from the exception
73 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -060074 if errorStr == "Timeout":
75 if not jsonFormat:
76 return("FQPSPIN0000M: Connection timed out. Ensure you have network connectivity to the bmc")
77 else:
Justin Thaler115bca72018-05-25 19:29:08 -050078 conerror = {}
79 conerror['CommonEventID'] = 'FQPSPIN0000M'
80 conerror['sensor']="N/A"
81 conerror['state']="N/A"
82 conerror['additionalDetails'] = "N/A"
83 conerror['Message']="Connection timed out. Ensure you have network connectivity to the BMC"
84 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."
85 conerror['Serviceable']="Yes"
86 conerror['CallHomeCandidate']= "No"
87 conerror['Severity'] = "Critical"
88 conerror['EventType'] = "Communication Failure/Timeout"
89 conerror['VMMigrationFlag'] = "Yes"
90 conerror["AffectedSubsystem"] = "Interconnect (Networking)"
91 conerror["timestamp"] = str(int(time.time()))
92 conerror["UserAction"] = "Verify network connectivity between the two systems and the bmc is functional."
93 eventdict = {}
94 eventdict['event0'] = conerror
95 eventdict['numAlerts'] = '1'
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -060096
Justin Thaler115bca72018-05-25 19:29:08 -050097 errorMessageStr = errorMessageStr = json.dumps(eventdict, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
Justin Thalerf9aee3e2017-12-05 12:11:09 -060098 return(errorMessageStr)
99 elif errorStr == "ConnectionError":
100 if not jsonFormat:
101 return("FQPSPIN0001M: " + str(err))
102 else:
Justin Thaler115bca72018-05-25 19:29:08 -0500103 conerror = {}
104 conerror['CommonEventID'] = 'FQPSPIN0001M'
105 conerror['sensor']="N/A"
106 conerror['state']="N/A"
107 conerror['additionalDetails'] = str(err)
108 conerror['Message']="Connection Error. View additional details for more information"
109 conerror['LengthyDescription'] = "A connection error to the specified BMC occurred and additional details are provided. Review these details to resolve the issue."
110 conerror['Serviceable']="Yes"
111 conerror['CallHomeCandidate']= "No"
112 conerror['Severity'] = "Critical"
113 conerror['EventType'] = "Communication Failure/Timeout"
114 conerror['VMMigrationFlag'] = "Yes"
115 conerror["AffectedSubsystem"] = "Interconnect (Networking)"
116 conerror["timestamp"] = str(int(time.time()))
117 conerror["UserAction"] = "Correct the issue highlighted in additional details and try again"
118 eventdict = {}
119 eventdict['event0'] = conerror
120 eventdict['numAlerts'] = '1'
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600121
Justin Thaler115bca72018-05-25 19:29:08 -0500122 errorMessageStr = json.dumps(eventdict, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600123 return(errorMessageStr)
Justin Thaler115bca72018-05-25 19:29:08 -0500124
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600125 else:
126 return("Unknown Error: "+ str(err))
127
Justin Thalere412dc22018-01-12 16:28:24 -0600128
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600129def setColWidth(keylist, numCols, dictForOutput, colNames):
Justin Thalere412dc22018-01-12 16:28:24 -0600130 """
131 Sets the output width of the columns to display
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600132
133 @param keylist: list, list of strings representing the keys for the dictForOutput
Justin Thalere412dc22018-01-12 16:28:24 -0600134 @param numcols: the total number of columns in the final output
135 @param dictForOutput: dictionary, contains the information to print to the screen
136 @param colNames: list, The strings to use for the column headings, in order of the keylist
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600137 @return: A list of the column widths for each respective column.
Justin Thalere412dc22018-01-12 16:28:24 -0600138 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600139 colWidths = []
140 for x in range(0, numCols):
141 colWidths.append(0)
142 for key in dictForOutput:
143 for x in range(0, numCols):
144 colWidths[x] = max(colWidths[x], len(str(dictForOutput[key][keylist[x]])))
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600145
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600146 for x in range(0, numCols):
147 colWidths[x] = max(colWidths[x], len(colNames[x])) +2
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600148
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600149 return colWidths
150
151def loadPolicyTable(pathToPolicyTable):
Justin Thalere412dc22018-01-12 16:28:24 -0600152 """
153 loads a json based policy table into a dictionary
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600154
Justin Thalere412dc22018-01-12 16:28:24 -0600155 @param value: boolean, the value to convert
156 @return: A string of "Yes" or "No"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600157 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600158 policyTable = {}
159 if(os.path.exists(pathToPolicyTable)):
160 with open(pathToPolicyTable, 'r') as stream:
161 try:
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600162 contents =json.load(stream)
163 policyTable = contents['events']
Justin Thalere412dc22018-01-12 16:28:24 -0600164 except Exception as err:
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600165 print(err)
166 return policyTable
167
Justin Thalere412dc22018-01-12 16:28:24 -0600168
169def boolToString(value):
170 """
171 converts a boolean value to a human readable string value
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600172
Justin Thalere412dc22018-01-12 16:28:24 -0600173 @param value: boolean, the value to convert
174 @return: A string of "Yes" or "No"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600175 """
Justin Thalere412dc22018-01-12 16:28:24 -0600176 if(value):
177 return "Yes"
178 else:
179 return "No"
180
Justin Thalera6b5df72018-07-16 11:10:07 -0500181def stringToInt(text):
182 """
183 returns an integer if the string can be converted, otherwise returns the string
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600184
Justin Thalera6b5df72018-07-16 11:10:07 -0500185 @param text: the string to try to convert to an integer
186 """
187 if text.isdigit():
188 return int(text)
189 else:
190 return text
Justin Thalere412dc22018-01-12 16:28:24 -0600191
Justin Thalera6b5df72018-07-16 11:10:07 -0500192def naturalSort(text):
193 """
194 provides a way to naturally sort a list
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600195
Justin Thalera6b5df72018-07-16 11:10:07 -0500196 @param text: the key to convert for sorting
197 @return list containing the broken up string parts by integers and strings
198 """
199 stringPartList = []
200 for c in re.split('(\d+)', text):
201 stringPartList.append(stringToInt(c))
202 return stringPartList
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600203
Justin Thalere412dc22018-01-12 16:28:24 -0600204def tableDisplay(keylist, colNames, output):
205 """
206 Logs into the BMC and creates a session
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600207
Justin Thalere412dc22018-01-12 16:28:24 -0600208 @param keylist: list, keys for the output dictionary, ordered by colNames
209 @param colNames: Names for the Table of the columns
210 @param output: The dictionary of data to display
211 @return: Session object
212 """
213 colWidth = setColWidth(keylist, len(colNames), output, colNames)
214 row = ""
215 outputText = ""
216 for i in range(len(colNames)):
217 if (i != 0): row = row + "| "
218 row = row + colNames[i].ljust(colWidth[i])
219 outputText += row + "\n"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600220
Justin Thalera6b5df72018-07-16 11:10:07 -0500221 output_keys = list(output.keys())
222 output_keys.sort(key=naturalSort)
223 for key in output_keys:
Justin Thalere412dc22018-01-12 16:28:24 -0600224 row = ""
Justin Thaler8fe0c732018-07-24 14:32:35 -0500225 for i in range(len(keylist)):
Justin Thalere412dc22018-01-12 16:28:24 -0600226 if (i != 0): row = row + "| "
227 row = row + output[key][keylist[i]].ljust(colWidth[i])
228 outputText += row + "\n"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600229
Justin Thalere412dc22018-01-12 16:28:24 -0600230 return outputText
231
Justin Thaler22b1bb52018-03-15 13:31:32 -0500232def checkFWactivation(host, args, session):
233 """
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600234 Checks the software inventory for an image that is being activated.
235
Justin Thaler22b1bb52018-03-15 13:31:32 -0500236 @return: True if an image is being activated, false is no activations are happening
237 """
238 url="https://"+host+"/xyz/openbmc_project/software/enumerate"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600239 httpHeader = {'Content-Type':'application/json'}
Justin Thaler22b1bb52018-03-15 13:31:32 -0500240 try:
241 resp = session.get(url, headers=httpHeader, verify=False, timeout=30)
242 except(requests.exceptions.Timeout):
243 print(connectionErrHandler(args.json, "Timeout", None))
244 return(True)
245 except(requests.exceptions.ConnectionError) as err:
246 print( connectionErrHandler(args.json, "ConnectionError", err))
247 return True
248 fwInfo = json.loads(resp.text)['data']
249 for key in fwInfo:
250 if 'Activation' in fwInfo[key]:
251 if 'Activating' in fwInfo[key]['Activation'] or 'Activating' in fwInfo[key]['RequestedActivation']:
252 return True
253 return False
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600254
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600255def login(host, username, pw,jsonFormat):
Justin Thalere412dc22018-01-12 16:28:24 -0600256 """
257 Logs into the BMC and creates a session
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600258
Justin Thalere412dc22018-01-12 16:28:24 -0600259 @param host: string, the hostname or IP address of the bmc to log into
260 @param username: The user name for the bmc to log into
261 @param pw: The password for the BMC to log into
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600262 @param jsonFormat: boolean, flag that will only allow relevant data from user command to be display. This function becomes silent when set to true.
Justin Thalere412dc22018-01-12 16:28:24 -0600263 @return: Session object
264 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600265 if(jsonFormat==False):
266 print("Attempting login...")
267 httpHeader = {'Content-Type':'application/json'}
268 mysess = requests.session()
269 try:
270 r = mysess.post('https://'+host+'/login', headers=httpHeader, json = {"data": [username, pw]}, verify=False, timeout=30)
271 loginMessage = json.loads(r.text)
272 if (loginMessage['status'] != "ok"):
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600273 print(loginMessage["data"]["description"].encode('utf-8'))
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600274 sys.exit(1)
275# if(sys.version_info < (3,0)):
276# urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
277# if sys.version_info >= (3,0):
278# requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
279 return mysess
280 except(requests.exceptions.Timeout):
Justin Thaler115bca72018-05-25 19:29:08 -0500281 return (connectionErrHandler(jsonFormat, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600282 except(requests.exceptions.ConnectionError) as err:
Justin Thaler115bca72018-05-25 19:29:08 -0500283 return (connectionErrHandler(jsonFormat, "ConnectionError", err))
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600284
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600285
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600286def logout(host, username, pw, session, jsonFormat):
Justin Thalere412dc22018-01-12 16:28:24 -0600287 """
288 Logs out of the bmc and terminates the session
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600289
Justin Thalere412dc22018-01-12 16:28:24 -0600290 @param host: string, the hostname or IP address of the bmc to log out of
291 @param username: The user name for the bmc to log out of
292 @param pw: The password for the BMC to log out of
293 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600294 @param jsonFormat: boolean, flag that will only allow relevant data from user command to be display. This function becomes silent when set to true.
295 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600296 httpHeader = {'Content-Type':'application/json'}
Justin Thalere412dc22018-01-12 16:28:24 -0600297 try:
298 r = session.post('https://'+host+'/logout', headers=httpHeader,json = {"data": [username, pw]}, verify=False, timeout=10)
299 except(requests.exceptions.Timeout):
300 print(connectionErrHandler(jsonFormat, "Timeout", None))
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600301
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600302 if(jsonFormat==False):
303 if('"message": "200 OK"' in r.text):
304 print('User ' +username + ' has been logged out')
305
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600306
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600307def fru(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -0600308 """
309 prints out the system inventory. deprecated see fruPrint and fruList
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600310
Justin Thalere412dc22018-01-12 16:28:24 -0600311 @param host: string, the hostname or IP address of the bmc
312 @param args: contains additional arguments used by the fru sub command
313 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600314 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
315 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600316 #url="https://"+host+"/org/openbmc/inventory/system/chassis/enumerate"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600317
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600318 #print(url)
319 #res = session.get(url, headers=httpHeader, verify=False)
320 #print(res.text)
321 #sample = res.text
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600322
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600323 #inv_list = json.loads(sample)["data"]
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600324
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600325 url="https://"+host+"/xyz/openbmc_project/inventory/enumerate"
326 httpHeader = {'Content-Type':'application/json'}
Justin Thalere412dc22018-01-12 16:28:24 -0600327 try:
328 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
329 except(requests.exceptions.Timeout):
330 return(connectionErrHandler(args.json, "Timeout", None))
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600331
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600332 sample = res.text
333# inv_list.update(json.loads(sample)["data"])
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600334#
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600335# #determine column width's
336# colNames = ["FRU Name", "FRU Type", "Has Fault", "Is FRU", "Present", "Version"]
337# colWidths = setColWidth(["FRU Name", "fru_type", "fault", "is_fru", "present", "version"], 6, inv_list, colNames)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600338#
339# print("FRU Name".ljust(colWidths[0])+ "FRU Type".ljust(colWidths[1]) + "Has Fault".ljust(colWidths[2]) + "Is FRU".ljust(colWidths[3])+
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600340# "Present".ljust(colWidths[4]) + "Version".ljust(colWidths[5]))
341# format the output
342# for key in sorted(inv_list.keys()):
343# keyParts = key.split("/")
344# isFRU = "True" if (inv_list[key]["is_fru"]==1) else "False"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600345#
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600346# fruEntry = (keyParts[len(keyParts) - 1].ljust(colWidths[0]) + inv_list[key]["fru_type"].ljust(colWidths[1])+
347# inv_list[key]["fault"].ljust(colWidths[2])+isFRU.ljust(colWidths[3])+
348# inv_list[key]["present"].ljust(colWidths[4])+ inv_list[key]["version"].ljust(colWidths[5]))
349# if(isTTY):
350# if(inv_list[key]["is_fru"] == 1):
351# color = "green"
352# bold = True
353# else:
354# color='black'
355# bold = False
356# fruEntry = hilight(fruEntry, color, bold)
357# print (fruEntry)
358 return sample
Justin Thalere412dc22018-01-12 16:28:24 -0600359
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600360def fruPrint(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -0600361 """
362 prints out all inventory
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600363
Justin Thalere412dc22018-01-12 16:28:24 -0600364 @param host: string, the hostname or IP address of the bmc
365 @param args: contains additional arguments used by the fru sub command
366 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600367 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
368 @return returns the total fru list.
369 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600370 url="https://"+host+"/xyz/openbmc_project/inventory/enumerate"
371 httpHeader = {'Content-Type':'application/json'}
Justin Thalere412dc22018-01-12 16:28:24 -0600372 try:
373 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
374 except(requests.exceptions.Timeout):
375 return(connectionErrHandler(args.json, "Timeout", None))
376
377
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600378# print(res.text)
379 frulist = res.text
380 url="https://"+host+"/xyz/openbmc_project/software/enumerate"
Justin Thalere412dc22018-01-12 16:28:24 -0600381 try:
382 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
383 except(requests.exceptions.Timeout):
384 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600385# print(res.text)
386 frulist = frulist +"\n" + res.text
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600387
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600388 return frulist
389
Justin Thalere412dc22018-01-12 16:28:24 -0600390
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600391def fruList(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -0600392 """
393 prints out all inventory or only a specific specified item
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600394
Justin Thalere412dc22018-01-12 16:28:24 -0600395 @param host: string, the hostname or IP address of the bmc
396 @param args: contains additional arguments used by the fru sub command
397 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600398 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
399 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600400 if(args.items==True):
401 return fruPrint(host, args, session)
402 else:
Justin Thalere412dc22018-01-12 16:28:24 -0600403 return fruPrint(host, args, session)
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600404
405
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600406
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600407def fruStatus(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -0600408 """
409 prints out the status of all FRUs
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600410
Justin Thalere412dc22018-01-12 16:28:24 -0600411 @param host: string, the hostname or IP address of the bmc
412 @param args: contains additional arguments used by the fru sub command
413 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600414 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
415 """
Justin Thalere412dc22018-01-12 16:28:24 -0600416 url="https://"+host+"/xyz/openbmc_project/inventory/enumerate"
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600417 httpHeader = {'Content-Type':'application/json'}
Justin Thalere412dc22018-01-12 16:28:24 -0600418 try:
419 res = session.get(url, headers=httpHeader, verify=False)
420 except(requests.exceptions.Timeout):
421 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600422# print(res.text)
Justin Thalere412dc22018-01-12 16:28:24 -0600423 frulist = json.loads(res.text)['data']
424 frus = {}
425 for key in frulist:
426 component = frulist[key]
427 isFru = False
428 present = False
429 func = False
430 hasSels = False
431 keyPieces = key.split('/')
432 fruName = keyPieces[-1]
433 if 'core' in fruName: #associate cores to cpus
434 fruName = keyPieces[-2] + '-' + keyPieces[-1]
435 if 'Functional' in component:
436 if('Present' in component):
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600437
Justin Thalere412dc22018-01-12 16:28:24 -0600438 if 'FieldReplaceable' in component:
439 if component['FieldReplaceable'] == 1:
440 isFru = True
441 if "fan" in fruName:
442 isFru = True;
443 if component['Present'] == 1:
444 present = True
445 if component['Functional'] == 1:
446 func = True
447 if ((key + "/fault") in frulist):
448 hasSels = True;
449 if args.verbose:
450 if hasSels:
451 loglist = []
452 faults = frulist[key+"/fault"]['endpoints']
453 for item in faults:
454 loglist.append(item.split('/')[-1])
455 frus[fruName] = {"compName": fruName, "Functional": boolToString(func), "Present":boolToString(present), "IsFru": boolToString(isFru), "selList": ', '.join(loglist).strip() }
456 else:
457 frus[fruName] = {"compName": fruName, "Functional": boolToString(func), "Present":boolToString(present), "IsFru": boolToString(isFru), "selList": "None" }
458 else:
459 frus[fruName] = {"compName": fruName, "Functional": boolToString(func), "Present":boolToString(present), "IsFru": boolToString(isFru), "hasSEL": boolToString(hasSels) }
Justin Thalerfb9c81c2018-07-16 11:14:37 -0500460 elif "power_supply" in fruName or "powersupply" in fruName:
Justin Thalere412dc22018-01-12 16:28:24 -0600461 if component['Present'] ==1:
462 present = True
463 isFru = True
464 if ((key + "/fault") in frulist):
465 hasSels = True;
466 if args.verbose:
467 if hasSels:
468 loglist = []
469 faults = frulist[key+"/fault"]['endpoints']
470 for key in faults:
471 loglist.append(faults[key].split('/')[-1])
472 frus[fruName] = {"compName": fruName, "Functional": "No", "Present":boolToString(present), "IsFru": boolToString(isFru), "selList": ', '.join(loglist).strip() }
473 else:
474 frus[fruName] = {"compName": fruName, "Functional": "Yes", "Present":boolToString(present), "IsFru": boolToString(isFru), "selList": "None" }
475 else:
476 frus[fruName] = {"compName": fruName, "Functional": boolToString(not hasSels), "Present":boolToString(present), "IsFru": boolToString(isFru), "hasSEL": boolToString(hasSels) }
477 if not args.json:
478 if not args.verbose:
479 colNames = ["Component", "Is a FRU", "Present", "Functional", "Has Logs"]
480 keylist = ["compName", "IsFru", "Present", "Functional", "hasSEL"]
481 else:
482 colNames = ["Component", "Is a FRU", "Present", "Functional", "Assoc. Log Number(s)"]
483 keylist = ["compName", "IsFru", "Present", "Functional", "selList"]
484 return tableDisplay(keylist, colNames, frus)
485 else:
486 return str(json.dumps(frus, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False))
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600487
Justin Thalere412dc22018-01-12 16:28:24 -0600488def sensor(host, args, session):
489 """
490 prints out all sensors
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600491
Justin Thalere412dc22018-01-12 16:28:24 -0600492 @param host: string, the hostname or IP address of the bmc
493 @param args: contains additional arguments used by the sensor sub command
494 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600495 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
496 """
Justin Thalere412dc22018-01-12 16:28:24 -0600497 httpHeader = {'Content-Type':'application/json'}
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600498 url="https://"+host+"/xyz/openbmc_project/sensors/enumerate"
Justin Thalere412dc22018-01-12 16:28:24 -0600499 try:
500 res = session.get(url, headers=httpHeader, verify=False, timeout=30)
501 except(requests.exceptions.Timeout):
502 return(connectionErrHandler(args.json, "Timeout", None))
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600503
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600504 #Get OCC status
505 url="https://"+host+"/org/open_power/control/enumerate"
Justin Thalere412dc22018-01-12 16:28:24 -0600506 try:
507 occres = session.get(url, headers=httpHeader, verify=False, timeout=30)
508 except(requests.exceptions.Timeout):
509 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600510 if not args.json:
511 colNames = ['sensor', 'type', 'units', 'value', 'target']
512 sensors = json.loads(res.text)["data"]
513 output = {}
514 for key in sensors:
515 senDict = {}
516 keyparts = key.split("/")
517 senDict['sensorName'] = keyparts[-1]
518 senDict['type'] = keyparts[-2]
Justin Thalere412dc22018-01-12 16:28:24 -0600519 try:
520 senDict['units'] = sensors[key]['Unit'].split('.')[-1]
521 except KeyError:
Justin Thaler22b1bb52018-03-15 13:31:32 -0500522 senDict['units'] = "N/A"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600523 if('Scale' in sensors[key]):
524 scale = 10 ** sensors[key]['Scale']
525 else:
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600526 scale = 1
Justin Thaler22b1bb52018-03-15 13:31:32 -0500527 try:
528 senDict['value'] = str(sensors[key]['Value'] * scale)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600529 except KeyError:
Justin Thaler22b1bb52018-03-15 13:31:32 -0500530 if 'value' in sensors[key]:
531 senDict['value'] = sensors[key]['value']
532 else:
533 senDict['value'] = "N/A"
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600534 if 'Target' in sensors[key]:
535 senDict['target'] = str(sensors[key]['Target'])
536 else:
537 senDict['target'] = 'N/A'
538 output[senDict['sensorName']] = senDict
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600539
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600540 occstatus = json.loads(occres.text)["data"]
541 if '/org/open_power/control/occ0' in occstatus:
542 occ0 = occstatus["/org/open_power/control/occ0"]['OccActive']
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600543 if occ0 == 1:
544 occ0 = 'Active'
545 else:
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600546 occ0 = 'Inactive'
547 output['OCC0'] = {'sensorName':'OCC0', 'type': 'Discrete', 'units': 'N/A', 'value': occ0, 'target': 'Active'}
548 occ1 = occstatus["/org/open_power/control/occ1"]['OccActive']
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600549 if occ1 == 1:
550 occ1 = 'Active'
551 else:
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600552 occ1 = 'Inactive'
553 output['OCC1'] = {'sensorName':'OCC1', 'type': 'Discrete', 'units': 'N/A', 'value': occ0, 'target': 'Active'}
554 else:
555 output['OCC0'] = {'sensorName':'OCC0', 'type': 'Discrete', 'units': 'N/A', 'value': 'Inactive', 'target': 'Inactive'}
556 output['OCC1'] = {'sensorName':'OCC1', 'type': 'Discrete', 'units': 'N/A', 'value': 'Inactive', 'target': 'Inactive'}
557 keylist = ['sensorName', 'type', 'units', 'value', 'target']
Justin Thalere412dc22018-01-12 16:28:24 -0600558
559 return tableDisplay(keylist, colNames, output)
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600560 else:
561 return res.text + occres.text
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600562
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600563def sel(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -0600564 """
565 prints out the bmc alerts
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600566
Justin Thalere412dc22018-01-12 16:28:24 -0600567 @param host: string, the hostname or IP address of the bmc
568 @param args: contains additional arguments used by the sel sub command
569 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600570 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
571 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600572
573 url="https://"+host+"/xyz/openbmc_project/logging/entry/enumerate"
574 httpHeader = {'Content-Type':'application/json'}
Justin Thalere412dc22018-01-12 16:28:24 -0600575 try:
576 res = session.get(url, headers=httpHeader, verify=False, timeout=60)
577 except(requests.exceptions.Timeout):
578 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600579 return res.text
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600580
581
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600582def parseESEL(args, eselRAW):
Justin Thalere412dc22018-01-12 16:28:24 -0600583 """
584 parses the esel data and gets predetermined search terms
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600585
Justin Thalere412dc22018-01-12 16:28:24 -0600586 @param eselRAW: string, the raw esel string from the bmc
587 @return: A dictionary containing the quick snapshot data unless args.fullEsel is listed then a full PEL log is returned
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600588 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600589 eselParts = {}
590 esel_bin = binascii.unhexlify(''.join(eselRAW.split()[16:]))
591 #search terms contains the search term as the key and the return dictionary key as it's value
592 searchTerms = { 'Signature Description':'signatureDescription', 'devdesc':'devdesc',
Justin Thaler22b1bb52018-03-15 13:31:32 -0500593 'Callout type': 'calloutType', 'Procedure':'procedure', 'Sensor Type': 'sensorType'}
Justin Thaler24d4efa2018-11-08 22:48:10 -0600594 uniqueID = str(uuid.uuid4())
595 eselBinPath = tempfile.gettempdir() + os.sep + uniqueID + 'esel.bin'
Justin Thalercf1deae2018-05-25 19:35:21 -0500596 with open(eselBinPath, 'wb') as f:
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600597 f.write(esel_bin)
598 errlPath = ""
599 #use the right errl file for the machine architecture
600 arch = platform.machine()
601 if(arch =='x86_64' or arch =='AMD64'):
602 if os.path.exists('/opt/ibm/ras/bin/x86_64/errl'):
603 errlPath = '/opt/ibm/ras/bin/x86_64/errl'
604 elif os.path.exists('errl/x86_64/errl'):
605 errlPath = 'errl/x86_64/errl'
606 else:
607 errlPath = 'x86_64/errl'
608 elif (platform.machine()=='ppc64le'):
609 if os.path.exists('/opt/ibm/ras/bin/ppc64le/errl'):
610 errlPath = '/opt/ibm/ras/bin/ppc64le/errl'
611 elif os.path.exists('errl/ppc64le/errl'):
612 errlPath = 'errl/ppc64le/errl'
613 else:
614 errlPath = 'ppc64le/errl'
615 else:
616 print("machine architecture not supported for parsing eSELs")
617 return eselParts
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600618
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600619 if(os.path.exists(errlPath)):
Justin Thalercf1deae2018-05-25 19:35:21 -0500620 output= subprocess.check_output([errlPath, '-d', '--file='+eselBinPath]).decode('utf-8')
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600621# output = proc.communicate()[0]
622 lines = output.split('\n')
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600623
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600624 if(hasattr(args, 'fullEsel')):
625 return output
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600626
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600627 for i in range(0, len(lines)):
628 lineParts = lines[i].split(':')
629 if(len(lineParts)>1): #ignore multi lines, output formatting lines, and other information
630 for term in searchTerms:
631 if(term in lineParts[0]):
632 temp = lines[i][lines[i].find(':')+1:].strip()[:-1].strip()
633 if lines[i+1].find(':') != -1:
634 if (len(lines[i+1].split(':')[0][1:].strip())==0):
635 while(len(lines[i][:lines[i].find(':')].strip())>2):
Justin Thaler43030422018-11-08 22:50:21 -0600636 #has multiple lines, process and update line counter
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600637 if((i+1) <= len(lines)):
638 i+=1
639 else:
640 i=i-1
641 break
Justin Thaler43030422018-11-08 22:50:21 -0600642 #Append the content from the next line removing the pretty display characters
643 #Finds the first colon then starts 2 characters after, then removes all whitespace
644 temp = temp + lines[i][lines[i].find(':')+2:].strip()[:-1].strip()[:-1].strip()
Justin Thaler22b1bb52018-03-15 13:31:32 -0500645 if(searchTerms[term] in eselParts):
646 eselParts[searchTerms[term]] = eselParts[searchTerms[term]] + ", " + temp
647 else:
648 eselParts[searchTerms[term]] = temp
Justin Thalercf1deae2018-05-25 19:35:21 -0500649 os.remove(eselBinPath)
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600650 else:
651 print("errl file cannot be found")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600652
653 return eselParts
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600654
Justin Thalere412dc22018-01-12 16:28:24 -0600655
Matt Spinler02d0dff2018-08-29 13:19:25 -0500656def getESELSeverity(esel):
657 """
658 Finds the severity type in an eSEL from the User Header section.
659 @param esel - the eSEL data
660 @return severity - e.g. 'Critical'
661 """
662
663 # everything but 1 and 2 are Critical
664 # '1': 'recovered',
665 # '2': 'predictive',
666 # '4': 'unrecoverable',
667 # '5': 'critical',
668 # '6': 'diagnostic',
669 # '7': 'symptom'
670 severities = {
671 '1': 'Informational',
672 '2': 'Warning'
673 }
674
675 try:
676 headerPosition = esel.index('55 48') # 'UH'
677 # The severity is the last byte in the 8 byte section (a byte is ' bb')
678 severity = esel[headerPosition:headerPosition+32].split(' ')[-1]
679 type = severity[0]
680 except ValueError:
681 print("Could not find severity value in UH section in eSEL")
682 type = 'x';
683
684 return severities.get(type, 'Critical')
685
686
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600687def sortSELs(events):
Justin Thalere412dc22018-01-12 16:28:24 -0600688 """
689 sorts the sels by timestamp, then log entry number
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600690
Justin Thalere412dc22018-01-12 16:28:24 -0600691 @param events: Dictionary containing events
692 @return: list containing a list of the ordered log entries, and dictionary of keys
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600693 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600694 logNumList = []
695 timestampList = []
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600696 eventKeyDict = {}
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600697 eventsWithTimestamp = {}
698 logNum2events = {}
699 for key in events:
700 if key == 'numAlerts': continue
701 if 'callout' in key: continue
702 timestamp = (events[key]['timestamp'])
703 if timestamp not in timestampList:
704 eventsWithTimestamp[timestamp] = [events[key]['logNum']]
705 else:
706 eventsWithTimestamp[timestamp].append(events[key]['logNum'])
707 #map logNumbers to the event dictionary keys
708 eventKeyDict[str(events[key]['logNum'])] = key
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600709
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600710 timestampList = list(eventsWithTimestamp.keys())
711 timestampList.sort()
712 for ts in timestampList:
713 if len(eventsWithTimestamp[ts]) > 1:
714 tmplist = eventsWithTimestamp[ts]
715 tmplist.sort()
716 logNumList = logNumList + tmplist
717 else:
718 logNumList = logNumList + eventsWithTimestamp[ts]
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600719
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600720 return [logNumList, eventKeyDict]
721
Justin Thalere412dc22018-01-12 16:28:24 -0600722
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600723def parseAlerts(policyTable, selEntries, args):
Justin Thalere412dc22018-01-12 16:28:24 -0600724 """
725 parses alerts in the IBM CER format, using an IBM policy Table
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600726
Justin Thalere412dc22018-01-12 16:28:24 -0600727 @param policyTable: dictionary, the policy table entries
728 @param selEntries: dictionary, the alerts retrieved from the bmc
729 @return: A dictionary of the parsed entries, in chronological order
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600730 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600731 eventDict = {}
732 eventNum =""
733 count = 0
734 esel = ""
735 eselParts = {}
736 i2cdevice= ""
Matt Spinler02d0dff2018-08-29 13:19:25 -0500737 eselSeverity = None
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600738
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600739 'prepare and sort the event entries'
740 for key in selEntries:
741 if 'callout' not in key:
742 selEntries[key]['logNum'] = key.split('/')[-1]
743 selEntries[key]['timestamp'] = selEntries[key]['Timestamp']
744 sortedEntries = sortSELs(selEntries)
745 logNumList = sortedEntries[0]
746 eventKeyDict = sortedEntries[1]
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600747
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600748 for logNum in logNumList:
749 key = eventKeyDict[logNum]
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600750 hasEsel=False
751 i2creadFail = False
752 if 'callout' in key:
753 continue
754 else:
755 messageID = str(selEntries[key]['Message'])
756 addDataPiece = selEntries[key]['AdditionalData']
757 calloutIndex = 0
758 calloutFound = False
759 for i in range(len(addDataPiece)):
760 if("CALLOUT_INVENTORY_PATH" in addDataPiece[i]):
761 calloutIndex = i
762 calloutFound = True
763 fruCallout = str(addDataPiece[calloutIndex]).split('=')[1]
764 if("CALLOUT_DEVICE_PATH" in addDataPiece[i]):
765 i2creadFail = True
Matt Spinlerd178a472018-08-31 09:48:52 -0500766
767 fruCallout = str(addDataPiece[calloutIndex]).split('=')[1]
768
769 # Fall back to "I2C"/"FSI" if dev path isn't in policy table
770 if (messageID + '||' + fruCallout) not in policyTable:
771 i2cdevice = str(addDataPiece[i]).strip().split('=')[1]
772 i2cdevice = '/'.join(i2cdevice.split('/')[-4:])
773 if 'fsi' in str(addDataPiece[calloutIndex]).split('=')[1]:
774 fruCallout = 'FSI'
775 else:
776 fruCallout = 'I2C'
Justin Thalere34c43a2018-05-25 19:37:55 -0500777 calloutFound = True
778 if("CALLOUT_GPIO_NUM" in addDataPiece[i]):
779 if not calloutFound:
780 fruCallout = 'GPIO'
781 calloutFound = True
782 if("CALLOUT_IIC_BUS" in addDataPiece[i]):
783 if not calloutFound:
784 fruCallout = "I2C"
785 calloutFound = True
786 if("CALLOUT_IPMI_SENSOR_NUM" in addDataPiece[i]):
787 if not calloutFound:
788 fruCallout = "IPMI"
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600789 calloutFound = True
790 if("ESEL" in addDataPiece[i]):
791 esel = str(addDataPiece[i]).strip().split('=')[1]
Matt Spinler02d0dff2018-08-29 13:19:25 -0500792 eselSeverity = getESELSeverity(esel)
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600793 if args.devdebug:
794 eselParts = parseESEL(args, esel)
795 hasEsel=True
796 if("GPU" in addDataPiece[i]):
797 fruCallout = '/xyz/openbmc_project/inventory/system/chassis/motherboard/gpu' + str(addDataPiece[i]).strip()[-1]
798 calloutFound = True
799 if("PROCEDURE" in addDataPiece[i]):
800 fruCallout = str(hex(int(str(addDataPiece[i]).split('=')[1])))[2:]
801 calloutFound = True
Justin Thalere412dc22018-01-12 16:28:24 -0600802 if("RAIL_NAME" in addDataPiece[i]):
803 calloutFound=True
804 fruCallout = str(addDataPiece[i]).split('=')[1].strip()
805 if("INPUT_NAME" in addDataPiece[i]):
806 calloutFound=True
807 fruCallout = str(addDataPiece[i]).split('=')[1].strip()
808 if("SENSOR_TYPE" in addDataPiece[i]):
809 calloutFound=True
810 fruCallout = str(addDataPiece[i]).split('=')[1].strip()
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600811
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600812 if(calloutFound):
Justin Thaler22b1bb52018-03-15 13:31:32 -0500813 if fruCallout != "":
814 policyKey = messageID +"||" + fruCallout
Matt Spinler02d0dff2018-08-29 13:19:25 -0500815
816 # Also use the severity for hostboot errors
817 if eselSeverity and messageID == 'org.open_power.Host.Error.Event':
818 policyKey += '||' + eselSeverity
819
820 # if not in the table, fall back to the original key
821 if policyKey not in policyTable:
822 policyKey = policyKey.replace('||'+eselSeverity, '')
823
Justin Thalere34c43a2018-05-25 19:37:55 -0500824 if policyKey not in policyTable:
825 policyKey = messageID
Justin Thaler22b1bb52018-03-15 13:31:32 -0500826 else:
827 policyKey = messageID
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600828 else:
829 policyKey = messageID
830 event = {}
831 eventNum = str(count)
832 if policyKey in policyTable:
833 for pkey in policyTable[policyKey]:
834 if(type(policyTable[policyKey][pkey])== bool):
835 event[pkey] = boolToString(policyTable[policyKey][pkey])
836 else:
837 if (i2creadFail and pkey == 'Message'):
838 event[pkey] = policyTable[policyKey][pkey] + ' ' +i2cdevice
839 else:
840 event[pkey] = policyTable[policyKey][pkey]
841 event['timestamp'] = selEntries[key]['Timestamp']
842 event['resolved'] = bool(selEntries[key]['Resolved'])
843 if(hasEsel):
844 if args.devdebug:
845 event['eselParts'] = eselParts
846 event['raweSEL'] = esel
847 event['logNum'] = key.split('/')[-1]
848 eventDict['event' + eventNum] = event
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600849
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600850 else:
851 severity = str(selEntries[key]['Severity']).split('.')[-1]
852 if severity == 'Error':
853 severity = 'Critical'
854 eventDict['event'+eventNum] = {}
855 eventDict['event' + eventNum]['error'] = "error: Not found in policy table: " + policyKey
856 eventDict['event' + eventNum]['timestamp'] = selEntries[key]['Timestamp']
857 eventDict['event' + eventNum]['Severity'] = severity
858 if(hasEsel):
859 if args.devdebug:
860 eventDict['event' +eventNum]['eselParts'] = eselParts
861 eventDict['event' +eventNum]['raweSEL'] = esel
862 eventDict['event' +eventNum]['logNum'] = key.split('/')[-1]
863 eventDict['event' +eventNum]['resolved'] = bool(selEntries[key]['Resolved'])
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600864 count += 1
865 return eventDict
866
867
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600868def selDisplay(events, args):
Justin Thalere412dc22018-01-12 16:28:24 -0600869 """
870 displays alerts in human readable format
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600871
Justin Thalere412dc22018-01-12 16:28:24 -0600872 @param events: Dictionary containing events
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600873 @return:
874 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600875 activeAlerts = []
876 historyAlerts = []
877 sortedEntries = sortSELs(events)
878 logNumList = sortedEntries[0]
879 eventKeyDict = sortedEntries[1]
880 keylist = ['Entry', 'ID', 'Timestamp', 'Serviceable', 'Severity','Message']
881 if(args.devdebug):
882 colNames = ['Entry', 'ID', 'Timestamp', 'Serviceable', 'Severity','Message', 'eSEL contents']
883 keylist.append('eSEL')
884 else:
885 colNames = ['Entry', 'ID', 'Timestamp', 'Serviceable', 'Severity', 'Message']
886 for log in logNumList:
887 selDict = {}
888 alert = events[eventKeyDict[str(log)]]
889 if('error' in alert):
890 selDict['Entry'] = alert['logNum']
891 selDict['ID'] = 'Unknown'
892 selDict['Timestamp'] = datetime.datetime.fromtimestamp(int(alert['timestamp']/1000)).strftime("%Y-%m-%d %H:%M:%S")
893 msg = alert['error']
894 polMsg = msg.split("policy table:")[0]
895 msg = msg.split("policy table:")[1]
896 msgPieces = msg.split("||")
897 err = msgPieces[0]
898 if(err.find("org.open_power.")!=-1):
899 err = err.split("org.open_power.")[1]
900 elif(err.find("xyz.openbmc_project.")!=-1):
901 err = err.split("xyz.openbmc_project.")[1]
902 else:
903 err = msgPieces[0]
904 callout = ""
905 if len(msgPieces) >1:
906 callout = msgPieces[1]
907 if(callout.find("/org/open_power/")!=-1):
908 callout = callout.split("/org/open_power/")[1]
909 elif(callout.find("/xyz/openbmc_project/")!=-1):
910 callout = callout.split("/xyz/openbmc_project/")[1]
911 else:
912 callout = msgPieces[1]
913 selDict['Message'] = polMsg +"policy table: "+ err + "||" + callout
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600914 selDict['Serviceable'] = 'Unknown'
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600915 selDict['Severity'] = alert['Severity']
916 else:
917 selDict['Entry'] = alert['logNum']
918 selDict['ID'] = alert['CommonEventID']
919 selDict['Timestamp'] = datetime.datetime.fromtimestamp(int(alert['timestamp']/1000)).strftime("%Y-%m-%d %H:%M:%S")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600920 selDict['Message'] = alert['Message']
921 selDict['Serviceable'] = alert['Serviceable']
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600922 selDict['Severity'] = alert['Severity']
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600923
924
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600925 eselOrder = ['refCode','signatureDescription', 'eselType', 'devdesc', 'calloutType', 'procedure']
926 if ('eselParts' in alert and args.devdebug):
927 eselOutput = ""
928 for item in eselOrder:
929 if item in alert['eselParts']:
930 eselOutput = eselOutput + item + ": " + alert['eselParts'][item] + " | "
931 selDict['eSEL'] = eselOutput
932 else:
933 if args.devdebug:
934 selDict['eSEL'] = "None"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600935
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600936 if not alert['resolved']:
937 activeAlerts.append(selDict)
938 else:
939 historyAlerts.append(selDict)
940 mergedOutput = activeAlerts + historyAlerts
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600941 colWidth = setColWidth(keylist, len(colNames), dict(enumerate(mergedOutput)), colNames)
942
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600943 output = ""
944 if(len(activeAlerts)>0):
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600945 row = ""
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600946 output +="----Active Alerts----\n"
947 for i in range(0, len(colNames)):
948 if i!=0: row =row + "| "
949 row = row + colNames[i].ljust(colWidth[i])
950 output += row + "\n"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600951
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600952 for i in range(0,len(activeAlerts)):
953 row = ""
954 for j in range(len(activeAlerts[i])):
955 if (j != 0): row = row + "| "
956 row = row + activeAlerts[i][keylist[j]].ljust(colWidth[j])
957 output += row + "\n"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600958
959 if(len(historyAlerts)>0):
960 row = ""
961 output+= "----Historical Alerts----\n"
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600962 for i in range(len(colNames)):
963 if i!=0: row =row + "| "
964 row = row + colNames[i].ljust(colWidth[i])
965 output += row + "\n"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600966
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600967 for i in range(0, len(historyAlerts)):
968 row = ""
969 for j in range(len(historyAlerts[i])):
970 if (j != 0): row = row + "| "
971 row = row + historyAlerts[i][keylist[j]].ljust(colWidth[j])
972 output += row + "\n"
973# print(events[eventKeyDict[str(log)]])
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600974 return output
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600975
Justin Thalere412dc22018-01-12 16:28:24 -0600976
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600977def selPrint(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -0600978 """
979 prints out all bmc alerts
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600980
Justin Thalere412dc22018-01-12 16:28:24 -0600981 @param host: string, the hostname or IP address of the bmc
982 @param args: contains additional arguments used by the fru sub command
983 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -0600984 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
985 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -0600986 if(args.policyTableLoc is None):
987 if os.path.exists('policyTable.json'):
988 ptableLoc = "policyTable.json"
989 elif os.path.exists('/opt/ibm/ras/lib/policyTable.json'):
990 ptableLoc = '/opt/ibm/ras/lib/policyTable.json'
991 else:
992 ptableLoc = 'lib/policyTable.json'
993 else:
994 ptableLoc = args.policyTableLoc
995 policyTable = loadPolicyTable(ptableLoc)
996 rawselEntries = ""
997 if(hasattr(args, 'fileloc') and args.fileloc is not None):
998 if os.path.exists(args.fileloc):
999 with open(args.fileloc, 'r') as selFile:
1000 selLines = selFile.readlines()
1001 rawselEntries = ''.join(selLines)
1002 else:
1003 print("Error: File not found")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001004 sys.exit(1)
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001005 else:
1006 rawselEntries = sel(host, args, session)
1007 loadFailed = False
1008 try:
1009 selEntries = json.loads(rawselEntries)
1010 except ValueError:
1011 loadFailed = True
1012 if loadFailed:
1013 cleanSels = json.dumps(rawselEntries).replace('\\n', '')
1014 #need to load json twice as original content was string escaped a second time
1015 selEntries = json.loads(json.loads(cleanSels))
1016 selEntries = selEntries['data']
Justin Thalere412dc22018-01-12 16:28:24 -06001017
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001018 if 'description' in selEntries:
1019 if(args.json):
1020 return("{\n\t\"numAlerts\": 0\n}")
1021 else:
1022 return("No log entries found")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001023
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001024 else:
1025 if(len(policyTable)>0):
1026 events = parseAlerts(policyTable, selEntries, args)
1027 if(args.json):
1028 events["numAlerts"] = len(events)
1029 retValue = str(json.dumps(events, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False))
1030 return retValue
1031 elif(hasattr(args, 'fullSel')):
1032 return events
1033 else:
1034 #get log numbers to order event entries sequentially
1035 return selDisplay(events, args)
1036 else:
1037 if(args.json):
1038 return selEntries
1039 else:
1040 print("error: Policy Table not found.")
1041 return selEntries
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001042
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001043def selList(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001044 """
1045 prints out all all bmc alerts, or only prints out the specified alerts
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001046
Justin Thalere412dc22018-01-12 16:28:24 -06001047 @param host: string, the hostname or IP address of the bmc
1048 @param args: contains additional arguments used by the fru sub command
1049 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001050 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1051 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001052 return(sel(host, args, session))
1053
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001054
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001055def selClear(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001056 """
1057 clears all alerts
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001058
Justin Thalere412dc22018-01-12 16:28:24 -06001059 @param host: string, the hostname or IP address of the bmc
1060 @param args: contains additional arguments used by the fru sub command
1061 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001062 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1063 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001064 url="https://"+host+"/xyz/openbmc_project/logging/action/deleteAll"
1065 httpHeader = {'Content-Type':'application/json'}
1066 data = "{\"data\": [] }"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001067
Justin Thalere412dc22018-01-12 16:28:24 -06001068 try:
1069 res = session.post(url, headers=httpHeader, data=data, verify=False, timeout=30)
1070 except(requests.exceptions.Timeout):
1071 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001072 if res.status_code == 200:
1073 return "The Alert Log has been cleared. Please allow a few minutes for the action to complete."
1074 else:
1075 print("Unable to clear the logs, trying to clear 1 at a time")
1076 sels = json.loads(sel(host, args, session))['data']
1077 for key in sels:
1078 if 'callout' not in key:
1079 logNum = key.split('/')[-1]
1080 url = "https://"+ host+ "/xyz/openbmc_project/logging/entry/"+logNum+"/action/Delete"
1081 try:
1082 session.post(url, headers=httpHeader, data=data, verify=False, timeout=30)
1083 except(requests.exceptions.Timeout):
1084 return connectionErrHandler(args.json, "Timeout", None)
1085 sys.exit(1)
1086 except(requests.exceptions.ConnectionError) as err:
1087 return connectionErrHandler(args.json, "ConnectionError", err)
1088 sys.exit(1)
1089 return ('Sel clearing complete')
1090
1091def selSetResolved(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001092 """
1093 sets a sel entry to resolved
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001094
Justin Thalere412dc22018-01-12 16:28:24 -06001095 @param host: string, the hostname or IP address of the bmc
1096 @param args: contains additional arguments used by the fru sub command
1097 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001098 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1099 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001100 url="https://"+host+"/xyz/openbmc_project/logging/entry/" + str(args.selNum) + "/attr/Resolved"
1101 httpHeader = {'Content-Type':'application/json'}
1102 data = "{\"data\": 1 }"
Justin Thalere412dc22018-01-12 16:28:24 -06001103 try:
1104 res = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
1105 except(requests.exceptions.Timeout):
1106 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001107 if res.status_code == 200:
1108 return "Sel entry "+ str(args.selNum) +" is now set to resolved"
1109 else:
1110 return "Unable to set the alert to resolved"
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001111
Justin Thalere412dc22018-01-12 16:28:24 -06001112def selResolveAll(host, args, session):
1113 """
1114 sets a sel entry to resolved
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001115
Justin Thalere412dc22018-01-12 16:28:24 -06001116 @param host: string, the hostname or IP address of the bmc
1117 @param args: contains additional arguments used by the fru sub command
1118 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001119 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1120 """
Justin Thalere412dc22018-01-12 16:28:24 -06001121 rawselEntries = sel(host, args, session)
1122 loadFailed = False
1123 try:
1124 selEntries = json.loads(rawselEntries)
1125 except ValueError:
1126 loadFailed = True
1127 if loadFailed:
1128 cleanSels = json.dumps(rawselEntries).replace('\\n', '')
1129 #need to load json twice as original content was string escaped a second time
1130 selEntries = json.loads(json.loads(cleanSels))
1131 selEntries = selEntries['data']
1132
1133 if 'description' in selEntries:
1134 if(args.json):
1135 return("{\n\t\"selsResolved\": 0\n}")
1136 else:
1137 return("No log entries found")
1138 else:
1139 d = vars(args)
1140 successlist = []
1141 failedlist = []
1142 for key in selEntries:
1143 if 'callout' not in key:
1144 d['selNum'] = key.split('/')[-1]
1145 resolved = selSetResolved(host,args,session)
1146 if 'Sel entry' in resolved:
1147 successlist.append(d['selNum'])
1148 else:
1149 failedlist.append(d['selNum'])
1150 output = ""
1151 successlist.sort()
1152 failedlist.sort()
1153 if len(successlist)>0:
1154 output = "Successfully resolved: " +', '.join(successlist) +"\n"
1155 if len(failedlist)>0:
1156 output += "Failed to resolve: " + ', '.join(failedlist) + "\n"
1157 return output
1158
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001159def chassisPower(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001160 """
1161 called by the chassis function. Controls the power state of the chassis, or gets the status
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001162
Justin Thalere412dc22018-01-12 16:28:24 -06001163 @param host: string, the hostname or IP address of the bmc
1164 @param args: contains additional arguments used by the fru sub command
1165 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001166 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1167 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001168 if(args.powcmd == 'on'):
Justin Thaler22b1bb52018-03-15 13:31:32 -05001169 if checkFWactivation(host, args, session):
1170 return ("Chassis Power control disabled during firmware activation")
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001171 print("Attempting to Power on...:")
1172 url="https://"+host+"/xyz/openbmc_project/state/host0/attr/RequestedHostTransition"
1173 httpHeader = {'Content-Type':'application/json',}
1174 data = '{"data":"xyz.openbmc_project.State.Host.Transition.On"}'
Justin Thalere412dc22018-01-12 16:28:24 -06001175 try:
1176 res = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
1177 except(requests.exceptions.Timeout):
1178 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001179 return res.text
Justin Thalere412dc22018-01-12 16:28:24 -06001180 elif(args.powcmd == 'softoff'):
Justin Thaler22b1bb52018-03-15 13:31:32 -05001181 if checkFWactivation(host, args, session):
1182 return ("Chassis Power control disabled during firmware activation")
Justin Thalere412dc22018-01-12 16:28:24 -06001183 print("Attempting to Power off gracefully...:")
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001184 url="https://"+host+"/xyz/openbmc_project/state/host0/attr/RequestedHostTransition"
1185 httpHeader = {'Content-Type':'application/json'}
1186 data = '{"data":"xyz.openbmc_project.State.Host.Transition.Off"}'
Justin Thalere412dc22018-01-12 16:28:24 -06001187 try:
1188 res = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
1189 except(requests.exceptions.Timeout):
1190 return(connectionErrHandler(args.json, "Timeout", None))
1191 return res.text
1192 elif(args.powcmd == 'hardoff'):
Justin Thaler22b1bb52018-03-15 13:31:32 -05001193 if checkFWactivation(host, args, session):
1194 return ("Chassis Power control disabled during firmware activation")
Justin Thalere412dc22018-01-12 16:28:24 -06001195 print("Attempting to Power off immediately...:")
1196 url="https://"+host+"/xyz/openbmc_project/state/chassis0/attr/RequestedPowerTransition"
1197 httpHeader = {'Content-Type':'application/json'}
1198 data = '{"data":"xyz.openbmc_project.State.Chassis.Transition.Off"}'
1199 try:
1200 res = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
1201 except(requests.exceptions.Timeout):
1202 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001203 return res.text
1204 elif(args.powcmd == 'status'):
1205 url="https://"+host+"/xyz/openbmc_project/state/chassis0/attr/CurrentPowerState"
1206 httpHeader = {'Content-Type':'application/json'}
1207# print(url)
Justin Thalere412dc22018-01-12 16:28:24 -06001208 try:
1209 res = session.get(url, headers=httpHeader, verify=False, timeout=30)
1210 except(requests.exceptions.Timeout):
1211 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001212 chassisState = json.loads(res.text)['data'].split('.')[-1]
1213 url="https://"+host+"/xyz/openbmc_project/state/host0/attr/CurrentHostState"
Justin Thalere412dc22018-01-12 16:28:24 -06001214 try:
1215 res = session.get(url, headers=httpHeader, verify=False, timeout=30)
1216 except(requests.exceptions.Timeout):
1217 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001218 hostState = json.loads(res.text)['data'].split('.')[-1]
1219 url="https://"+host+"/xyz/openbmc_project/state/bmc0/attr/CurrentBMCState"
Justin Thalere412dc22018-01-12 16:28:24 -06001220 try:
1221 res = session.get(url, headers=httpHeader, verify=False, timeout=30)
1222 except(requests.exceptions.Timeout):
1223 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001224 bmcState = json.loads(res.text)['data'].split('.')[-1]
1225 if(args.json):
1226 outDict = {"Chassis Power State" : chassisState, "Host Power State" : hostState, "BMC Power State":bmcState}
1227 return json.dumps(outDict, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
1228 else:
1229 return "Chassis Power State: " +chassisState + "\nHost Power State: " + hostState + "\nBMC Power State: " + bmcState
1230 else:
1231 return "Invalid chassis power command"
1232
Justin Thalere412dc22018-01-12 16:28:24 -06001233
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001234def chassisIdent(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001235 """
1236 called by the chassis function. Controls the identify led of the chassis. Sets or gets the state
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001237
Justin Thalere412dc22018-01-12 16:28:24 -06001238 @param host: string, the hostname or IP address of the bmc
1239 @param args: contains additional arguments used by the fru sub command
1240 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001241 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
Justin Thalere412dc22018-01-12 16:28:24 -06001242 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001243 if(args.identcmd == 'on'):
1244 print("Attempting to turn identify light on...:")
1245 url="https://"+host+"/xyz/openbmc_project/led/groups/enclosure_identify/attr/Asserted"
1246 httpHeader = {'Content-Type':'application/json',}
1247 data = '{"data":true}'
Justin Thalere412dc22018-01-12 16:28:24 -06001248 try:
1249 res = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
1250 except(requests.exceptions.Timeout):
1251 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001252 return res.text
1253 elif(args.identcmd == 'off'):
1254 print("Attempting to turn identify light off...:")
1255 url="https://"+host+"/xyz/openbmc_project/led/groups/enclosure_identify/attr/Asserted"
1256 httpHeader = {'Content-Type':'application/json'}
1257 data = '{"data":false}'
Justin Thalere412dc22018-01-12 16:28:24 -06001258 try:
1259 res = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
1260 except(requests.exceptions.Timeout):
1261 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001262 return res.text
1263 elif(args.identcmd == 'status'):
1264 url="https://"+host+"/xyz/openbmc_project/led/groups/enclosure_identify"
1265 httpHeader = {'Content-Type':'application/json'}
Justin Thalere412dc22018-01-12 16:28:24 -06001266 try:
1267 res = session.get(url, headers=httpHeader, verify=False, timeout=30)
1268 except(requests.exceptions.Timeout):
1269 return(connectionErrHandler(args.json, "Timeout", None))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001270 status = json.loads(res.text)['data']
1271 if(args.json):
1272 return status
1273 else:
1274 if status['Asserted'] == 0:
1275 return "Identify light is off"
1276 else:
1277 return "Identify light is blinking"
1278 else:
1279 return "Invalid chassis identify command"
1280
Justin Thalere412dc22018-01-12 16:28:24 -06001281
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001282def chassis(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001283 """
1284 controls the different chassis commands
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001285
Justin Thalere412dc22018-01-12 16:28:24 -06001286 @param host: string, the hostname or IP address of the bmc
1287 @param args: contains additional arguments used by the fru sub command
1288 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001289 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1290 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001291 if(hasattr(args, 'powcmd')):
1292 result = chassisPower(host,args,session)
1293 elif(hasattr(args, 'identcmd')):
1294 result = chassisIdent(host, args, session)
1295 else:
Justin Thaler22b1bb52018-03-15 13:31:32 -05001296 return "This feature is not yet implemented"
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001297 return result
Justin Thalere412dc22018-01-12 16:28:24 -06001298
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001299def bmcDumpRetrieve(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001300 """
1301 Downloads a dump file from the bmc
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001302
Justin Thalere412dc22018-01-12 16:28:24 -06001303 @param host: string, the hostname or IP address of the bmc
1304 @param args: contains additional arguments used by the collectServiceData sub command
1305 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001306 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
Justin Thalere412dc22018-01-12 16:28:24 -06001307 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001308 httpHeader = {'Content-Type':'application/json'}
1309 dumpNum = args.dumpNum
1310 if (args.dumpSaveLoc is not None):
1311 saveLoc = args.dumpSaveLoc
1312 else:
Justin Thalercf1deae2018-05-25 19:35:21 -05001313 saveLoc = tempfile.gettempdir()
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001314 url ='https://'+host+'/download/dump/' + str(dumpNum)
1315 try:
Justin Thalere412dc22018-01-12 16:28:24 -06001316 r = session.get(url, headers=httpHeader, stream=True, verify=False, timeout=30)
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001317 if (args.dumpSaveLoc is not None):
1318 if os.path.exists(saveLoc):
1319 if saveLoc[-1] != os.path.sep:
1320 saveLoc = saveLoc + os.path.sep
1321 filename = saveLoc + host+'-dump' + str(dumpNum) + '.tar.xz'
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001322
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001323 else:
1324 return 'Invalid save location specified'
1325 else:
Justin Thalercf1deae2018-05-25 19:35:21 -05001326 filename = tempfile.gettempdir()+os.sep + host+'-dump' + str(dumpNum) + '.tar.xz'
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001327
1328 with open(filename, 'wb') as f:
1329 for chunk in r.iter_content(chunk_size =1024):
1330 if chunk:
1331 f.write(chunk)
1332 return 'Saved as ' + filename
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001333
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001334 except(requests.exceptions.Timeout):
1335 return connectionErrHandler(args.json, "Timeout", None)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001336
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001337 except(requests.exceptions.ConnectionError) as err:
1338 return connectionErrHandler(args.json, "ConnectionError", err)
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001339
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001340def bmcDumpList(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001341 """
1342 Lists the number of dump files on the bmc
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001343
Justin Thalere412dc22018-01-12 16:28:24 -06001344 @param host: string, the hostname or IP address of the bmc
1345 @param args: contains additional arguments used by the collectServiceData sub command
1346 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001347 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1348 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001349 httpHeader = {'Content-Type':'application/json'}
1350 url ='https://'+host+'/xyz/openbmc_project/dump/list'
1351 try:
1352 r = session.get(url, headers=httpHeader, verify=False, timeout=20)
1353 dumpList = json.loads(r.text)
1354 return r.text
1355 except(requests.exceptions.Timeout):
1356 return connectionErrHandler(args.json, "Timeout", None)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001357
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001358 except(requests.exceptions.ConnectionError) as err:
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001359 return connectionErrHandler(args.json, "ConnectionError", err)
1360
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001361def bmcDumpDelete(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001362 """
1363 Deletes BMC dump files from the bmc
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001364
Justin Thalere412dc22018-01-12 16:28:24 -06001365 @param host: string, the hostname or IP address of the bmc
1366 @param args: contains additional arguments used by the collectServiceData sub command
1367 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001368 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
Justin Thalere412dc22018-01-12 16:28:24 -06001369 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001370 httpHeader = {'Content-Type':'application/json'}
1371 dumpList = []
1372 successList = []
1373 failedList = []
1374 if args.dumpNum is not None:
1375 if isinstance(args.dumpNum, list):
1376 dumpList = args.dumpNum
1377 else:
1378 dumpList.append(args.dumpNum)
1379 for dumpNum in dumpList:
1380 url ='https://'+host+'/xyz/openbmc_project/dump/entry/'+str(dumpNum)+'/action/Delete'
1381 try:
1382 r = session.post(url, headers=httpHeader, json = {"data": []}, verify=False, timeout=30)
1383 if r.status_code == 200:
1384 successList.append(str(dumpNum))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001385 else:
1386 failedList.append(str(dumpNum))
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001387 except(requests.exceptions.Timeout):
1388 return connectionErrHandler(args.json, "Timeout", None)
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001389 except(requests.exceptions.ConnectionError) as err:
1390 return connectionErrHandler(args.json, "ConnectionError", err)
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001391 output = "Successfully deleted dumps: " + ', '.join(successList)
1392 if(len(failedList)>0):
1393 output+= '\nFailed to delete dumps: ' + ', '.join(failedList)
1394 return output
1395 else:
1396 return 'You must specify an entry number to delete'
1397
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001398def bmcDumpDeleteAll(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001399 """
1400 Deletes All BMC dump files from the bmc
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001401
Justin Thalere412dc22018-01-12 16:28:24 -06001402 @param host: string, the hostname or IP address of the bmc
1403 @param args: contains additional arguments used by the collectServiceData sub command
1404 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001405 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
Justin Thalere412dc22018-01-12 16:28:24 -06001406 """
1407 dumpResp = bmcDumpList(host, args, session)
1408 if 'FQPSPIN0000M' in dumpResp or 'FQPSPIN0001M'in dumpResp:
1409 return dumpResp
1410 dumpList = json.loads(dumpResp)['data']
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001411 d = vars(args)
1412 dumpNums = []
1413 for dump in dumpList:
1414 if '/xyz/openbmc_project/dump/internal/manager' not in dump:
1415 dumpNums.append(int(dump.strip().split('/')[-1]))
1416 d['dumpNum'] = dumpNums
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001417
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001418 return bmcDumpDelete(host, args, session)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001419
Justin Thalere412dc22018-01-12 16:28:24 -06001420
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001421def bmcDumpCreate(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001422 """
1423 Creates a bmc dump file
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001424
Justin Thalere412dc22018-01-12 16:28:24 -06001425 @param host: string, the hostname or IP address of the bmc
1426 @param args: contains additional arguments used by the collectServiceData sub command
1427 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001428 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
Justin Thalere412dc22018-01-12 16:28:24 -06001429 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001430 httpHeader = {'Content-Type':'application/json'}
1431 url = 'https://'+host+'/xyz/openbmc_project/dump/action/CreateDump'
1432 try:
1433 r = session.post(url, headers=httpHeader, json = {"data": []}, verify=False, timeout=30)
1434 if('"message": "200 OK"' in r.text and not args.json):
1435 return ('Dump successfully created')
1436 else:
1437 return ('Failed to create dump')
1438 except(requests.exceptions.Timeout):
1439 return connectionErrHandler(args.json, "Timeout", None)
1440 except(requests.exceptions.ConnectionError) as err:
1441 return connectionErrHandler(args.json, "ConnectionError", err)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001442
1443
1444
Justin Thalere412dc22018-01-12 16:28:24 -06001445
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001446def collectServiceData(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001447 """
1448 Collects all data needed for service from the BMC
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001449
Justin Thalere412dc22018-01-12 16:28:24 -06001450 @param host: string, the hostname or IP address of the bmc
1451 @param args: contains additional arguments used by the collectServiceData sub command
1452 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001453 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
Justin Thalere412dc22018-01-12 16:28:24 -06001454 """
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001455
Justin Thaler22b1bb52018-03-15 13:31:32 -05001456 global toolVersion
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001457 #create a bmc dump
1458 dumpcount = len(json.loads(bmcDumpList(host, args, session))['data'])
1459 try:
1460 dumpcreated = bmcDumpCreate(host, args, session)
1461 except Exception as e:
1462 print('failed to create a bmc dump')
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001463
1464
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001465 #Collect Inventory
1466 try:
1467 args.silent = True
Justin Thalercf1deae2018-05-25 19:35:21 -05001468 myDir = tempfile.gettempdir()+os.sep + host + "--" + datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S")
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001469 os.makedirs(myDir)
1470 filelist = []
1471 frulist = fruPrint(host, args, session)
1472 with open(myDir +'/inventory.txt', 'w') as f:
1473 f.write(frulist)
1474 print("Inventory collected and stored in " + myDir + "/inventory.txt")
1475 filelist.append(myDir+'/inventory.txt')
1476 except Exception as e:
1477 print("Failed to collect inventory")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001478
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001479 #Read all the sensor and OCC status
1480 try:
1481 sensorReadings = sensor(host, args, session)
1482 with open(myDir +'/sensorReadings.txt', 'w') as f:
1483 f.write(sensorReadings)
1484 print("Sensor readings collected and stored in " +myDir + "/sensorReadings.txt")
1485 filelist.append(myDir+'/sensorReadings.txt')
1486 except Exception as e:
1487 print("Failed to collect sensor readings")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001488
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001489 #Collect all of the LEDs status
1490 try:
1491 url="https://"+host+"/xyz/openbmc_project/led/enumerate"
1492 httpHeader = {'Content-Type':'application/json'}
1493 leds = session.get(url, headers=httpHeader, verify=False, timeout=20)
1494 with open(myDir +'/ledStatus.txt', 'w') as f:
1495 f.write(leds.text)
1496 print("System LED status collected and stored in "+myDir +"/ledStatus.txt")
1497 filelist.append(myDir+'/ledStatus.txt')
1498 except Exception as e:
1499 print("Failed to collect LED status")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001500
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001501 #Collect the bmc logs
1502 try:
1503 sels = selPrint(host,args,session)
1504 with open(myDir +'/SELshortlist.txt', 'w') as f:
1505 f.write(str(sels))
1506 print("sel short list collected and stored in "+myDir +"/SELshortlist.txt")
1507 filelist.append(myDir+'/SELshortlist.txt')
1508 time.sleep(2)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001509
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001510 d = vars(args)
1511 d['json'] = True
1512 d['fullSel'] = True
1513 parsedfullsels = json.loads(selPrint(host, args, session))
1514 d['fullEsel'] = True
1515 sortedSELs = sortSELs(parsedfullsels)
1516 with open(myDir +'/parsedSELs.txt', 'w') as f:
1517 for log in sortedSELs[0]:
1518 esel = ""
1519 parsedfullsels[sortedSELs[1][str(log)]]['timestamp'] = datetime.datetime.fromtimestamp(int(parsedfullsels[sortedSELs[1][str(log)]]['timestamp']/1000)).strftime("%Y-%m-%d %H:%M:%S")
1520 if ('raweSEL' in parsedfullsels[sortedSELs[1][str(log)]] and args.devdebug):
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001521 esel = parsedfullsels[sortedSELs[1][str(log)]]['raweSEL']
1522 del parsedfullsels[sortedSELs[1][str(log)]]['raweSEL']
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001523 f.write(json.dumps(parsedfullsels[sortedSELs[1][str(log)]],sort_keys=True, indent=4, separators=(',', ': ')))
1524 if(args.devdebug and esel != ""):
1525 f.write(parseESEL(args, esel))
1526 print("fully parsed sels collected and stored in "+myDir +"/parsedSELs.txt")
1527 filelist.append(myDir+'/parsedSELs.txt')
1528 except Exception as e:
1529 print("Failed to collect system event logs")
1530 print(e)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001531
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001532 #collect RAW bmc enumeration
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001533 try:
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001534 url="https://"+host+"/xyz/openbmc_project/enumerate"
1535 print("Attempting to get a full BMC enumeration")
1536 fullDump = session.get(url, headers=httpHeader, verify=False, timeout=120)
1537 with open(myDir +'/bmcFullRaw.txt', 'w') as f:
1538 f.write(fullDump.text)
1539 print("RAW BMC data collected and saved into "+myDir +"/bmcFullRaw.txt")
1540 filelist.append(myDir+'/bmcFullRaw.txt')
1541 except Exception as e:
1542 print("Failed to collect bmc full enumeration")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001543
1544 #collect the dump files
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001545 waitingForNewDump = True
1546 count = 0;
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001547 while(waitingForNewDump):
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001548 dumpList = json.loads(bmcDumpList(host, args, session))['data']
1549 if len(dumpList) > dumpcount:
1550 waitingForNewDump = False
1551 break;
1552 elif(count>30):
1553 print("Timed out waiting for bmc to make a new dump file. Dump space may be full.")
1554 break;
1555 else:
1556 time.sleep(2)
1557 count += 1
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001558 try:
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001559 print('Collecting bmc dump files')
1560 d['dumpSaveLoc'] = myDir
1561 dumpList = json.loads(bmcDumpList(host, args, session))['data']
1562 for dump in dumpList:
1563 if '/xyz/openbmc_project/dump/internal/manager' not in dump:
1564 d['dumpNum'] = int(dump.strip().split('/')[-1])
1565 print('retrieving dump file ' + str(d['dumpNum']))
1566 filename = bmcDumpRetrieve(host, args, session).split('Saved as ')[-1]
1567 filelist.append(filename)
1568 time.sleep(2)
1569 except Exception as e:
1570 print("Failed to collect bmc dump files")
1571 print(e)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001572
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001573 #create the zip file
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001574 try:
Justin Thalercf1deae2018-05-25 19:35:21 -05001575 filename = myDir.split(tempfile.gettempdir()+os.sep)[-1] + "_" + toolVersion + '_openbmc.zip'
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001576 zf = zipfile.ZipFile(myDir+'/' + filename, 'w')
1577 for myfile in filelist:
1578 zf.write(myfile, os.path.basename(myfile))
1579 zf.close()
1580 except Exception as e:
1581 print("Failed to create zip file with collected information")
1582 return "data collection complete"
1583
Justin Thalere412dc22018-01-12 16:28:24 -06001584
1585def healthCheck(host, args, session):
1586 """
1587 runs a health check on the platform
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001588
Justin Thalere412dc22018-01-12 16:28:24 -06001589 @param host: string, the hostname or IP address of the bmc
1590 @param args: contains additional arguments used by the bmc sub command
1591 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001592 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1593 """
Justin Thalere412dc22018-01-12 16:28:24 -06001594 #check fru status and get as json to easily work through
1595 d = vars(args)
1596 useJson = d['json']
1597 d['json'] = True
1598 d['verbose']= False
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001599
Justin Thalere412dc22018-01-12 16:28:24 -06001600 frus = json.loads(fruStatus(host, args, session))
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001601
Justin Thalere412dc22018-01-12 16:28:24 -06001602 hwStatus= "OK"
1603 performanceStatus = "OK"
1604 for key in frus:
1605 if frus[key]["Functional"] == "No" and frus[key]["Present"] == "Yes":
1606 hwStatus= "Degraded"
Justin Thalerfb9c81c2018-07-16 11:14:37 -05001607 if("power_supply" in key or "powersupply" in key):
1608 gpuCount =0
1609 for comp in frus:
Justin Thalere412dc22018-01-12 16:28:24 -06001610 if "gv100card" in comp:
1611 gpuCount +=1
1612 if gpuCount > 4:
1613 hwStatus = "Critical"
1614 performanceStatus="Degraded"
1615 break;
1616 elif("fan" in key):
1617 hwStatus = "Degraded"
1618 else:
1619 performanceStatus = "Degraded"
1620 if useJson:
1621 output = {"Hardware Status": hwStatus, "Performance": performanceStatus}
1622 output = json.dumps(output, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
1623 else:
1624 output = ("Hardware Status: " + hwStatus +
1625 "\nPerformance: " +performanceStatus )
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001626
1627
Justin Thalere412dc22018-01-12 16:28:24 -06001628 #SW407886: Clear the duplicate entries
1629 #collect the dups
1630 d['devdebug'] = False
1631 sels = json.loads(selPrint(host, args, session))
1632 logNums2Clr = []
1633 oldestLogNum={"logNum": "bogus" ,"key" : ""}
1634 count = 0
1635 if sels['numAlerts'] > 0:
1636 for key in sels:
1637 if "numAlerts" in key:
1638 continue
1639 try:
1640 if "slave@00:00/00:00:00:06/sbefifo1-dev0/occ1-dev0" in sels[key]['Message']:
1641 count += 1
1642 if count > 1:
1643 #preserve first occurrence
1644 if sels[key]['timestamp'] < sels[oldestLogNum['key']]['timestamp']:
1645 oldestLogNum['key']=key
1646 oldestLogNum['logNum'] = sels[key]['logNum']
1647 else:
1648 oldestLogNum['key']=key
1649 oldestLogNum['logNum'] = sels[key]['logNum']
1650 logNums2Clr.append(sels[key]['logNum'])
1651 except KeyError:
1652 continue
1653 if(count >0):
1654 logNums2Clr.remove(oldestLogNum['logNum'])
1655 #delete the dups
1656 if count >1:
1657 httpHeader = {'Content-Type':'application/json'}
1658 data = "{\"data\": [] }"
1659 for logNum in logNums2Clr:
1660 url = "https://"+ host+ "/xyz/openbmc_project/logging/entry/"+logNum+"/action/Delete"
1661 try:
1662 session.post(url, headers=httpHeader, data=data, verify=False, timeout=30)
1663 except(requests.exceptions.Timeout):
1664 deleteFailed = True
1665 except(requests.exceptions.ConnectionError) as err:
1666 deleteFailed = True
1667 #End of defect resolve code
1668 d['json'] = useJson
1669 return output
1670
1671
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001672
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001673def bmc(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001674 """
1675 handles various bmc level commands, currently bmc rebooting
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001676
Justin Thalere412dc22018-01-12 16:28:24 -06001677 @param host: string, the hostname or IP address of the bmc
1678 @param args: contains additional arguments used by the bmc sub command
1679 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001680 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1681 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001682 if(args.type is not None):
1683 return bmcReset(host, args, session)
Justin Thalere412dc22018-01-12 16:28:24 -06001684 if(args.info):
1685 return "Not implemented at this time"
1686
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001687
Justin Thalere412dc22018-01-12 16:28:24 -06001688
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001689def bmcReset(host, args, session):
Justin Thalere412dc22018-01-12 16:28:24 -06001690 """
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001691 controls resetting the bmc. warm reset reboots the bmc, cold reset removes the configuration and reboots.
1692
Justin Thalere412dc22018-01-12 16:28:24 -06001693 @param host: string, the hostname or IP address of the bmc
1694 @param args: contains additional arguments used by the bmcReset sub command
1695 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001696 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
1697 """
Justin Thaler22b1bb52018-03-15 13:31:32 -05001698 if checkFWactivation(host, args, session):
1699 return ("BMC reset control disabled during firmware activation")
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001700 if(args.type == "warm"):
1701 print("\nAttempting to reboot the BMC...:")
1702 url="https://"+host+"/xyz/openbmc_project/state/bmc0/attr/RequestedBMCTransition"
1703 httpHeader = {'Content-Type':'application/json'}
Justin Thalere412dc22018-01-12 16:28:24 -06001704 data = '{"data":"xyz.openbmc_project.State.BMC.Transition.Reboot"}'
1705 res = session.put(url, headers=httpHeader, data=data, verify=False, timeout=20)
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001706 return res.text
1707 elif(args.type =="cold"):
Justin Thalere412dc22018-01-12 16:28:24 -06001708 print("\nAttempting to reboot the BMC...:")
1709 url="https://"+host+"/xyz/openbmc_project/state/bmc0/attr/RequestedBMCTransition"
1710 httpHeader = {'Content-Type':'application/json'}
1711 data = '{"data":"xyz.openbmc_project.State.BMC.Transition.Reboot"}'
1712 res = session.put(url, headers=httpHeader, data=data, verify=False, timeout=20)
1713 return res.text
Justin Thalerf9aee3e2017-12-05 12:11:09 -06001714 else:
1715 return "invalid command"
Justin Thalere412dc22018-01-12 16:28:24 -06001716
1717def gardClear(host, args, session):
1718 """
1719 clears the gard records from the bmc
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001720
Justin Thalere412dc22018-01-12 16:28:24 -06001721 @param host: string, the hostname or IP address of the bmc
1722 @param args: contains additional arguments used by the gardClear sub command
1723 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001724 """
Justin Thalere412dc22018-01-12 16:28:24 -06001725 url="https://"+host+"/org/open_power/control/gard/action/Reset"
1726 httpHeader = {'Content-Type':'application/json'}
1727 data = '{"data":[]}'
1728 try:
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001729
Justin Thalere412dc22018-01-12 16:28:24 -06001730 res = session.post(url, headers=httpHeader, data=data, verify=False, timeout=30)
1731 if res.status_code == 404:
1732 return "Command not supported by this firmware version"
1733 else:
1734 return res.text
1735 except(requests.exceptions.Timeout):
1736 return connectionErrHandler(args.json, "Timeout", None)
1737 except(requests.exceptions.ConnectionError) as err:
1738 return connectionErrHandler(args.json, "ConnectionError", err)
1739
1740def activateFWImage(host, args, session):
1741 """
1742 activates a firmware image on the bmc
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001743
Justin Thalere412dc22018-01-12 16:28:24 -06001744 @param host: string, the hostname or IP address of the bmc
1745 @param args: contains additional arguments used by the fwflash sub command
1746 @param session: the active session to use
1747 @param fwID: the unique ID of the fw image to activate
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001748 """
Justin Thalere412dc22018-01-12 16:28:24 -06001749 fwID = args.imageID
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001750
Justin Thalere412dc22018-01-12 16:28:24 -06001751 #determine the existing versions
1752 httpHeader = {'Content-Type':'application/json'}
1753 url="https://"+host+"/xyz/openbmc_project/software/enumerate"
1754 try:
1755 resp = session.get(url, headers=httpHeader, verify=False, timeout=30)
1756 except(requests.exceptions.Timeout):
1757 return connectionErrHandler(args.json, "Timeout", None)
1758 except(requests.exceptions.ConnectionError) as err:
1759 return connectionErrHandler(args.json, "ConnectionError", err)
1760 existingSoftware = json.loads(resp.text)['data']
1761 altVersionID = ''
1762 versionType = ''
1763 imageKey = '/xyz/openbmc_project/software/'+fwID
1764 if imageKey in existingSoftware:
1765 versionType = existingSoftware[imageKey]['Purpose']
1766 for key in existingSoftware:
1767 if imageKey == key:
1768 continue
1769 if 'Purpose' in existingSoftware[key]:
1770 if versionType == existingSoftware[key]['Purpose']:
1771 altVersionID = key.split('/')[-1]
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001772
1773
1774
1775
Justin Thalere412dc22018-01-12 16:28:24 -06001776 url="https://"+host+"/xyz/openbmc_project/software/"+ fwID + "/attr/Priority"
1777 url1="https://"+host+"/xyz/openbmc_project/software/"+ altVersionID + "/attr/Priority"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001778 data = "{\"data\": 0}"
Justin Thalere412dc22018-01-12 16:28:24 -06001779 data1 = "{\"data\": 1 }"
1780 try:
1781 resp = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
1782 resp1 = session.put(url1, headers=httpHeader, data=data1, verify=False, timeout=30)
1783 except(requests.exceptions.Timeout):
1784 return connectionErrHandler(args.json, "Timeout", None)
1785 except(requests.exceptions.ConnectionError) as err:
1786 return connectionErrHandler(args.json, "ConnectionError", err)
1787 if(not args.json):
1788 if resp.status_code == 200 and resp1.status_code == 200:
Justin Thaler22b1bb52018-03-15 13:31:32 -05001789 return 'Firmware flash and activation completed. Please reboot the bmc and then boot the host OS for the changes to take effect. '
Justin Thalere412dc22018-01-12 16:28:24 -06001790 else:
1791 return "Firmware activation failed."
1792 else:
1793 return resp.text + resp1.text
Justin Thaler22b1bb52018-03-15 13:31:32 -05001794
1795def activateStatus(host, args, session):
1796 if checkFWactivation(host, args, session):
1797 return("Firmware is currently being activated. Do not reboot the BMC or start the Host OS")
1798 else:
1799 return("No firmware activations are pending")
1800
1801def extractFWimage(path, imageType):
1802 """
1803 extracts the bmc image and returns information about the package
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001804
Justin Thaler22b1bb52018-03-15 13:31:32 -05001805 @param path: the path and file name of the firmware image
1806 @param imageType: The type of image the user is trying to flash. Host or BMC
1807 @return: the image id associated with the package. returns an empty string on error.
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001808 """
Justin Thaler22b1bb52018-03-15 13:31:32 -05001809 f = tempfile.TemporaryFile()
1810 tmpDir = tempfile.gettempdir()
1811 newImageID = ""
1812 if os.path.exists(path):
1813 try:
1814 imageFile = tarfile.open(path,'r')
1815 contents = imageFile.getmembers()
1816 for tf in contents:
1817 if 'MANIFEST' in tf.name:
1818 imageFile.extract(tf.name, path=tmpDir)
1819 with open(tempfile.gettempdir() +os.sep+ tf.name, 'r') as imageInfo:
1820 for line in imageInfo:
1821 if 'purpose' in line:
1822 purpose = line.split('=')[1]
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001823 if imageType not in purpose.split('.')[-1]:
Justin Thaler22b1bb52018-03-15 13:31:32 -05001824 print('The specified image is not for ' + imageType)
1825 print('Please try again with the image for ' + imageType)
1826 return ""
1827 if 'version' == line.split('=')[0]:
1828 version = line.split('=')[1].strip().encode('utf-8')
1829 m = hashlib.sha512()
1830 m.update(version)
1831 newImageID = m.hexdigest()[:8]
1832 break
1833 try:
1834 os.remove(tempfile.gettempdir() +os.sep+ tf.name)
1835 except OSError:
1836 pass
1837 return newImageID
1838 except tarfile.ExtractError as e:
1839 print('Unable to extract information from the firmware file.')
1840 print('Ensure you have write access to the directory: ' + tmpDir)
1841 return newImageID
1842 except tarfile.TarError as e:
1843 print('This is not a valid firmware file.')
1844 return newImageID
1845 print("This is not a valid firmware file.")
1846 return newImageID
1847 else:
1848 print('The filename and path provided are not valid.')
1849 return newImageID
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001850
Justin Thaler22b1bb52018-03-15 13:31:32 -05001851def getAllFWImageIDs(fwInvDict):
1852 """
1853 gets a list of all the firmware image IDs
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001854
Justin Thaler22b1bb52018-03-15 13:31:32 -05001855 @param fwInvDict: the dictionary to search for FW image IDs
1856 @return: list containing string representation of the found image ids
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001857 """
Justin Thaler22b1bb52018-03-15 13:31:32 -05001858 idList = []
1859 for key in fwInvDict:
1860 if 'Version' in fwInvDict[key]:
1861 idList.append(key.split('/')[-1])
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001862 return idList
1863
Justin Thalere412dc22018-01-12 16:28:24 -06001864def fwFlash(host, args, session):
1865 """
1866 updates the bmc firmware and pnor firmware
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001867
Justin Thalere412dc22018-01-12 16:28:24 -06001868 @param host: string, the hostname or IP address of the bmc
1869 @param args: contains additional arguments used by the fwflash sub command
1870 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001871 """
Justin Thaler22b1bb52018-03-15 13:31:32 -05001872 d = vars(args)
Justin Thalere412dc22018-01-12 16:28:24 -06001873 if(args.type == 'bmc'):
1874 purp = 'BMC'
1875 else:
1876 purp = 'Host'
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001877
1878 #check power state of the machine. No concurrent FW updates allowed
Justin Thaler22b1bb52018-03-15 13:31:32 -05001879 d['powcmd'] = 'status'
1880 powerstate = chassisPower(host, args, session)
1881 if 'Chassis Power State: On' in powerstate:
1882 return("Aborting firmware update. Host is powered on. Please turn off the host and try again.")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001883
Justin Thaler22b1bb52018-03-15 13:31:32 -05001884 #determine the existing images on the bmc
Justin Thalere412dc22018-01-12 16:28:24 -06001885 httpHeader = {'Content-Type':'application/json'}
1886 url="https://"+host+"/xyz/openbmc_project/software/enumerate"
1887 try:
1888 resp = session.get(url, headers=httpHeader, verify=False, timeout=30)
1889 except(requests.exceptions.Timeout):
1890 return connectionErrHandler(args.json, "Timeout", None)
1891 except(requests.exceptions.ConnectionError) as err:
1892 return connectionErrHandler(args.json, "ConnectionError", err)
1893 oldsoftware = json.loads(resp.text)['data']
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001894
Justin Thaler22b1bb52018-03-15 13:31:32 -05001895 #Extract the tar and get information from the manifest file
1896 newversionID = extractFWimage(args.fileloc, purp)
1897 if newversionID == "":
1898 return "Unable to verify FW image."
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001899
1900
Justin Thaler22b1bb52018-03-15 13:31:32 -05001901 #check if the new image is already on the bmc
1902 if newversionID not in getAllFWImageIDs(oldsoftware):
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001903
Justin Thaler22b1bb52018-03-15 13:31:32 -05001904 #upload the file
1905 httpHeader = {'Content-Type':'application/octet-stream'}
1906 url="https://"+host+"/upload/image"
1907 data=open(args.fileloc,'rb').read()
1908 print("Uploading file to BMC")
Justin Thalere412dc22018-01-12 16:28:24 -06001909 try:
Justin Thaler22b1bb52018-03-15 13:31:32 -05001910 resp = session.post(url, headers=httpHeader, data=data, verify=False)
Justin Thalere412dc22018-01-12 16:28:24 -06001911 except(requests.exceptions.Timeout):
1912 return connectionErrHandler(args.json, "Timeout", None)
1913 except(requests.exceptions.ConnectionError) as err:
1914 return connectionErrHandler(args.json, "ConnectionError", err)
Justin Thaler22b1bb52018-03-15 13:31:32 -05001915 if resp.status_code != 200:
1916 return "Failed to upload the file to the bmc"
Justin Thalere412dc22018-01-12 16:28:24 -06001917 else:
Justin Thaler22b1bb52018-03-15 13:31:32 -05001918 print("Upload complete.")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001919
Justin Thaler22b1bb52018-03-15 13:31:32 -05001920 #verify bmc processed the image
1921 software ={}
1922 for i in range(0, 5):
1923 httpHeader = {'Content-Type':'application/json'}
1924 url="https://"+host+"/xyz/openbmc_project/software/enumerate"
1925 try:
1926 resp = session.get(url, headers=httpHeader, verify=False, timeout=30)
1927 except(requests.exceptions.Timeout):
1928 return connectionErrHandler(args.json, "Timeout", None)
1929 except(requests.exceptions.ConnectionError) as err:
1930 return connectionErrHandler(args.json, "ConnectionError", err)
1931 software = json.loads(resp.text)['data']
1932 #check if bmc is done processing the new image
1933 if (newversionID in getAllFWImageIDs(software)):
Justin Thalere412dc22018-01-12 16:28:24 -06001934 break
Justin Thaler22b1bb52018-03-15 13:31:32 -05001935 else:
1936 time.sleep(15)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001937
Justin Thaler22b1bb52018-03-15 13:31:32 -05001938 #activate the new image
1939 print("Activating new image: "+newversionID)
1940 url="https://"+host+"/xyz/openbmc_project/software/"+ newversionID + "/attr/RequestedActivation"
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001941 data = '{"data":"xyz.openbmc_project.Software.Activation.RequestedActivations.Active"}'
Justin Thaler22b1bb52018-03-15 13:31:32 -05001942 try:
1943 resp = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
1944 except(requests.exceptions.Timeout):
1945 return connectionErrHandler(args.json, "Timeout", None)
1946 except(requests.exceptions.ConnectionError) as err:
1947 return connectionErrHandler(args.json, "ConnectionError", err)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001948
Justin Thaler22b1bb52018-03-15 13:31:32 -05001949 #wait for the activation to complete, timeout after ~1 hour
1950 i=0
1951 while i < 360:
1952 url="https://"+host+"/xyz/openbmc_project/software/"+ newversionID
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001953 data = '{"data":"xyz.openbmc_project.Software.Activation.RequestedActivations.Active"}'
Justin Thaler22b1bb52018-03-15 13:31:32 -05001954 try:
1955 resp = session.get(url, headers=httpHeader, verify=False, timeout=30)
1956 except(requests.exceptions.Timeout):
1957 return connectionErrHandler(args.json, "Timeout", None)
1958 except(requests.exceptions.ConnectionError) as err:
1959 return connectionErrHandler(args.json, "ConnectionError", err)
1960 fwInfo = json.loads(resp.text)['data']
1961 if 'Activating' not in fwInfo['Activation'] and 'Activating' not in fwInfo['RequestedActivation']:
1962 print('')
1963 break
1964 else:
1965 sys.stdout.write('.')
1966 sys.stdout.flush()
1967 time.sleep(10) #check every 10 seconds
1968 return "Firmware flash and activation completed. Please reboot the bmc and then boot the host OS for the changes to take effect. "
1969 else:
1970 print("This image has been found on the bmc. Activating image: " + newversionID)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001971
Justin Thaler22b1bb52018-03-15 13:31:32 -05001972 d['imageID'] = newversionID
1973 return activateFWImage(host, args, session)
Justin Thalere412dc22018-01-12 16:28:24 -06001974
Justin Thaler3d71d402018-07-24 14:35:39 -05001975def getFWInventoryAttributes(rawFWInvItem, ID):
1976 """
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001977 gets and lists all of the firmware in the system.
1978
Justin Thaler3d71d402018-07-24 14:35:39 -05001979 @return: returns a dictionary containing the image attributes
1980 """
1981 reqActivation = rawFWInvItem["RequestedActivation"].split('.')[-1]
1982 pendingActivation = ""
1983 if reqActivation == "None":
1984 pendingActivation = "No"
1985 else:
1986 pendingActivation = "Yes"
1987 firmwareAttr = {ID: {
1988 "Purpose": rawFWInvItem["Purpose"].split('.')[-1],
1989 "Version": rawFWInvItem["Version"],
1990 "RequestedActivation": pendingActivation,
1991 "ID": ID}}
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001992
Justin Thaler3d71d402018-07-24 14:35:39 -05001993 if "ExtendedVersion" in rawFWInvItem:
1994 firmwareAttr[ID]['ExtendedVersion'] = rawFWInvItem['ExtendedVersion'].split(',')
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06001995 else:
Justin Thaler3d71d402018-07-24 14:35:39 -05001996 firmwareAttr[ID]['ExtendedVersion'] = ""
1997 return firmwareAttr
1998
1999def parseFWdata(firmwareDict):
2000 """
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002001 creates a dictionary with parsed firmware data
2002
Justin Thaler3d71d402018-07-24 14:35:39 -05002003 @return: returns a dictionary containing the image attributes
2004 """
2005 firmwareInfoDict = {"Functional": {}, "Activated":{}, "NeedsActivated":{}}
2006 for key in firmwareDict['data']:
2007 #check for valid endpoint
2008 if "Purpose" in firmwareDict['data'][key]:
2009 id = key.split('/')[-1]
2010 if firmwareDict['data'][key]['Activation'].split('.')[-1] == "Active":
2011 fwActivated = True
2012 else:
2013 fwActivated = False
2014 if firmwareDict['data'][key]['Priority'] == 0:
2015 firmwareInfoDict['Functional'].update(getFWInventoryAttributes(firmwareDict['data'][key], id))
2016 elif firmwareDict['data'][key]['Priority'] >= 0 and fwActivated:
2017 firmwareInfoDict['Activated'].update(getFWInventoryAttributes(firmwareDict['data'][key], id))
2018 else:
2019 firmwareInfoDict['Activated'].update(getFWInventoryAttributes(firmwareDict['data'][key], id))
2020 emptySections = []
2021 for key in firmwareInfoDict:
2022 if len(firmwareInfoDict[key])<=0:
2023 emptySections.append(key)
2024 for key in emptySections:
2025 del firmwareInfoDict[key]
2026 return firmwareInfoDict
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002027
Justin Thaler3d71d402018-07-24 14:35:39 -05002028def displayFWInvenory(firmwareInfoDict, args):
2029 """
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002030 gets and lists all of the firmware in the system.
2031
Justin Thaler3d71d402018-07-24 14:35:39 -05002032 @return: returns a string containing all of the firmware information
2033 """
2034 output = ""
2035 if not args.json:
2036 for key in firmwareInfoDict:
2037 for subkey in firmwareInfoDict[key]:
2038 firmwareInfoDict[key][subkey]['ExtendedVersion'] = str(firmwareInfoDict[key][subkey]['ExtendedVersion'])
2039 if not args.verbose:
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002040 output = "---Running Images---\n"
Justin Thaler3d71d402018-07-24 14:35:39 -05002041 colNames = ["Purpose", "Version", "ID"]
2042 keylist = ["Purpose", "Version", "ID"]
2043 output += tableDisplay(keylist, colNames, firmwareInfoDict["Functional"])
2044 if "Activated" in firmwareInfoDict:
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002045 output += "\n---Available Images---\n"
Justin Thaler3d71d402018-07-24 14:35:39 -05002046 output += tableDisplay(keylist, colNames, firmwareInfoDict["Activated"])
2047 if "NeedsActivated" in firmwareInfoDict:
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002048 output += "\n---Needs Activated Images---\n"
Justin Thaler3d71d402018-07-24 14:35:39 -05002049 output += tableDisplay(keylist, colNames, firmwareInfoDict["NeedsActivated"])
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002050
Justin Thaler3d71d402018-07-24 14:35:39 -05002051 else:
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002052 output = "---Running Images---\n"
Justin Thaler3d71d402018-07-24 14:35:39 -05002053 colNames = ["Purpose", "Version", "ID", "Pending Activation", "Extended Version"]
2054 keylist = ["Purpose", "Version", "ID", "RequestedActivation", "ExtendedVersion"]
2055 output += tableDisplay(keylist, colNames, firmwareInfoDict["Functional"])
2056 if "Activated" in firmwareInfoDict:
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002057 output += "\n---Available Images---\n"
Justin Thaler3d71d402018-07-24 14:35:39 -05002058 output += tableDisplay(keylist, colNames, firmwareInfoDict["Activated"])
2059 if "NeedsActivated" in firmwareInfoDict:
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002060 output += "\n---Needs Activated Images---\n"
Justin Thaler3d71d402018-07-24 14:35:39 -05002061 output += tableDisplay(keylist, colNames, firmwareInfoDict["NeedsActivated"])
2062 return output
2063 else:
2064 return str(json.dumps(firmwareInfoDict, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False))
2065
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002066def firmwareList(host, args, session):
Justin Thaler3d71d402018-07-24 14:35:39 -05002067 """
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002068 gets and lists all of the firmware in the system.
2069
Justin Thaler3d71d402018-07-24 14:35:39 -05002070 @return: returns a string containing all of the firmware information
2071 """
2072 httpHeader = {'Content-Type':'application/json'}
2073 url="https://{hostname}/xyz/openbmc_project/software/enumerate".format(hostname=host)
2074 try:
2075 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2076 except(requests.exceptions.Timeout):
2077 return(connectionErrHandler(args.json, "Timeout", None))
2078 firmwareDict = json.loads(res.text)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002079
Justin Thaler3d71d402018-07-24 14:35:39 -05002080 #sort the received information
2081 firmwareInfoDict = parseFWdata(firmwareDict)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002082
Justin Thaler3d71d402018-07-24 14:35:39 -05002083 #display the information
2084 return displayFWInvenory(firmwareInfoDict, args)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002085
2086
Deepak Kodihalli22d4df02018-09-18 06:52:43 -05002087def restLogging(host, args, session):
2088 """
2089 Called by the logging function. Turns REST API logging on/off.
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002090
Deepak Kodihalli22d4df02018-09-18 06:52:43 -05002091 @param host: string, the hostname or IP address of the bmc
2092 @param args: contains additional arguments used by the logging sub command
2093 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002094 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
Deepak Kodihalli22d4df02018-09-18 06:52:43 -05002095 """
2096
2097 url="https://"+host+"/xyz/openbmc_project/logging/rest_api_logs/attr/Enabled"
2098 httpHeader = {'Content-Type':'application/json'}
2099
2100 if(args.rest_logging == 'on'):
2101 data = '{"data": 1}'
2102 elif(args.rest_logging == 'off'):
2103 data = '{"data": 0}'
2104 else:
2105 return "Invalid logging rest_api command"
2106
2107 try:
2108 res = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
2109 except(requests.exceptions.Timeout):
2110 return(connectionErrHandler(args.json, "Timeout", None))
2111 return res.text
2112
2113
Deepak Kodihalli02d53282018-09-18 06:53:31 -05002114def remoteLogging(host, args, session):
2115 """
2116 Called by the logging function. View config information for/disable remote logging (rsyslog).
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002117
Deepak Kodihalli02d53282018-09-18 06:53:31 -05002118 @param host: string, the hostname or IP address of the bmc
2119 @param args: contains additional arguments used by the logging sub command
2120 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002121 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
Deepak Kodihalli02d53282018-09-18 06:53:31 -05002122 """
2123
2124 url="https://"+host+"/xyz/openbmc_project/logging/config/remote"
2125 httpHeader = {'Content-Type':'application/json'}
2126
2127 try:
2128 if(args.remote_logging == 'view'):
2129 res = session.get(url, headers=httpHeader, verify=False, timeout=30)
2130 elif(args.remote_logging == 'disable'):
2131 res = session.put(url + '/attr/Port', headers=httpHeader, json = {"data": 0}, verify=False, timeout=30)
2132 res = session.put(url + '/attr/Address', headers=httpHeader, json = {"data": ""}, verify=False, timeout=30)
2133 else:
2134 return "Invalid logging remote_logging command"
2135 except(requests.exceptions.Timeout):
2136 return(connectionErrHandler(args.json, "Timeout", None))
2137 return res.text
2138
2139
2140def remoteLoggingConfig(host, args, session):
2141 """
2142 Called by the logging function. Configures remote logging (rsyslog).
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002143
Deepak Kodihalli02d53282018-09-18 06:53:31 -05002144 @param host: string, the hostname or IP address of the bmc
2145 @param args: contains additional arguments used by the logging sub command
2146 @param session: the active session to use
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06002147 @param args.json: boolean, if this flag is set to true, the output will be provided in json format for programmatic consumption
Deepak Kodihalli02d53282018-09-18 06:53:31 -05002148 """
2149
2150 url="https://"+host+"/xyz/openbmc_project/logging/config/remote"
2151 httpHeader = {'Content-Type':'application/json'}
2152
2153 try:
2154 res = session.put(url + '/attr/Port', headers=httpHeader, json = {"data": args.port}, verify=False, timeout=30)
2155 res = session.put(url + '/attr/Address', headers=httpHeader, json = {"data": args.address}, verify=False, timeout=30)
2156 except(requests.exceptions.Timeout):
2157 return(connectionErrHandler(args.json, "Timeout", None))
2158 return res.text
2159
Ratan Gupta9166cd22018-10-01 18:09:40 +05302160
Dhruvaraj Subhashchandran64e7f6f2018-10-02 03:42:14 -05002161def certificateUpdate(host, args, session):
2162 """
2163 Called by certificate management function. update server/client/authority certificates
2164 Example:
2165 certificate update server https -f cert.pem
2166 certificate update authority ldap -f Root-CA.pem
2167 certificate update client ldap -f cert.pem
2168 @param host: string, the hostname or IP address of the bmc
2169 @param args: contains additional arguments used by the certificate update sub command
2170 @param session: the active session to use
2171 """
2172
2173 httpHeader = {'Content-Type': 'application/octet-stream'}
2174 url = "https://" + host + "/xyz/openbmc_project/certs/" + args.type.lower() + "/" + args.service.lower()
2175 data = open(args.fileloc, 'rb').read()
2176 print("Updating certificate url=" + url)
2177 try:
2178 resp = session.put(url, headers=httpHeader, data=data, verify=False)
2179 except(requests.exceptions.Timeout):
2180 return(connectionErrHandler(args.json, "Timeout", None))
2181 except(requests.exceptions.ConnectionError) as err:
2182 return connectionErrHandler(args.json, "ConnectionError", err)
2183 if resp.status_code != 200:
2184 print(resp.text)
2185 return "Failed to update the certificate"
2186 else:
2187 print("Update complete.")
2188
2189
2190def certificateDelete(host, args, session):
2191 """
2192 Called by certificate management function to delete certificate
2193 Example:
2194 certificate delete server https
2195 certificate delete authority ldap
2196 certificate delete client ldap
2197 @param host: string, the hostname or IP address of the bmc
2198 @param args: contains additional arguments used by the certificate delete sub command
2199 @param session: the active session to use
2200 """
2201
2202 httpHeader = {'Content-Type': 'multipart/form-data'}
2203 url = "https://" + host + "/xyz/openbmc_project/certs/" + args.type.lower() + "/" + args.service.lower()
2204 print("Deleting certificate url=" + url)
2205 try:
2206 resp = session.delete(url, headers=httpHeader)
2207 except(requests.exceptions.Timeout):
2208 return(connectionErrHandler(args.json, "Timeout", None))
2209 except(requests.exceptions.ConnectionError) as err:
2210 return connectionErrHandler(args.json, "ConnectionError", err)
2211 if resp.status_code != 200:
2212 print(resp.text)
2213 return "Failed to delete the certificate"
2214 else:
2215 print("Delete complete.")
2216
Deepak Kodihalli02d53282018-09-18 06:53:31 -05002217
Ratan Gupta9166cd22018-10-01 18:09:40 +05302218def enableLDAP(host, args, session):
2219 """
2220 Called by the ldap function. Configures LDAP.
2221
2222 @param host: string, the hostname or IP address of the bmc
2223 @param args: contains additional arguments used by the ldap subcommand
2224 @param session: the active session to use
2225 @param args.json: boolean, if this flag is set to true, the output will
2226 be provided in json format for programmatic consumption
2227 """
2228
2229 url='https://'+host+'/xyz/openbmc_project/user/ldap/action/CreateConfig'
2230 httpHeader = {'Content-Type':'application/json'}
2231 scope = {
2232 'sub' : 'xyz.openbmc_project.User.Ldap.Create.SearchScope.sub',
2233 'one' : 'xyz.openbmc_project.User.Ldap.Create.SearchScope.one',
2234 'base': 'xyz.openbmc_project.User.Ldap.Create.SearchScope.base'
2235 }
2236
2237 serverType = {
2238 'ActiveDirectory' : 'xyz.openbmc_project.User.Ldap.Create.Type.ActiveDirectory',
2239 'OpenLDAP' : 'xyz.openbmc_project.User.Ldap.Create.Type.OpenLdap'
2240 }
2241
2242 data = {"data": [args.uri, args.bindDN, args.baseDN, args.bindPassword, scope[args.scope], serverType[args.serverType]]}
2243
2244 try:
2245 res = session.post(url, headers=httpHeader, json=data, verify=False, timeout=30)
2246 except(requests.exceptions.Timeout):
2247 return(connectionErrHandler(args.json, "Timeout", None))
2248 except(requests.exceptions.ConnectionError) as err:
2249 return connectionErrHandler(args.json, "ConnectionError", err)
2250
2251 return res.text
2252
2253
2254def disableLDAP(host, args, session):
2255 """
2256 Called by the ldap function. Deletes the LDAP Configuration.
2257
2258 @param host: string, the hostname or IP address of the bmc
2259 @param args: contains additional arguments used by the ldap subcommand
2260 @param session: the active session to use
2261 @param args.json: boolean, if this flag is set to true, the output
2262 will be provided in json format for programmatic consumption
2263 """
2264
2265 url='https://'+host+'/xyz/openbmc_project/user/ldap/config/action/delete'
2266 httpHeader = {'Content-Type':'application/json'}
2267 data = {"data": []}
2268
2269 try:
2270 res = session.post(url, headers=httpHeader, json=data, verify=False, timeout=30)
2271 except(requests.exceptions.Timeout):
2272 return(connectionErrHandler(args.json, "Timeout", None))
2273 except(requests.exceptions.ConnectionError) as err:
2274 return connectionErrHandler(args.json, "ConnectionError", err)
2275
2276 return res.text
2277
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06002278
2279def enableDHCP(host, args, session):
2280
2281 """
2282 Called by the network function. Enables DHCP.
2283
2284 @param host: string, the hostname or IP address of the bmc
2285 @param args: contains additional arguments used by the ldap subcommand
2286 args.json: boolean, if this flag is set to true, the output
2287 will be provided in json format for programmatic consumption
2288 @param session: the active session to use
2289 """
2290
2291 url = "https://"+host+"/xyz/openbmc_project/network/"+args.Interface+\
2292 "/attr/DHCPEnabled"
2293 httpHeader = {'Content-Type': 'application/json'}
2294 data = "{\"data\": 1 }"
2295 try:
2296 res = session.put(url, headers=httpHeader, data=data, verify=False,
2297 timeout=30)
2298
2299 except(requests.exceptions.Timeout):
2300 return(connectionErrHandler(args.json, "Timeout", None))
2301 except(requests.exceptions.ConnectionError) as err:
2302 return connectionErrHandler(args.json, "ConnectionError", err)
2303 if res.status_code == 403:
2304 return "The specified Interface"+"("+args.Interface+")"+\
2305 " doesn't exist"
2306
2307 return res.text
2308
2309
2310def disableDHCP(host, args, session):
2311 """
2312 Called by the network function. Disables DHCP.
2313
2314 @param host: string, the hostname or IP address of the bmc
2315 @param args: contains additional arguments used by the ldap subcommand
2316 args.json: boolean, if this flag is set to true, the output
2317 will be provided in json format for programmatic consumption
2318 @param session: the active session to use
2319 """
2320
2321 url = "https://"+host+"/xyz/openbmc_project/network/"+args.Interface+\
2322 "/attr/DHCPEnabled"
2323 httpHeader = {'Content-Type': 'application/json'}
2324 data = "{\"data\": 0 }"
2325 try:
2326 res = session.put(url, headers=httpHeader, data=data, verify=False,
2327 timeout=30)
2328 except(requests.exceptions.Timeout):
2329 return(connectionErrHandler(args.json, "Timeout", None))
2330 except(requests.exceptions.ConnectionError) as err:
2331 return connectionErrHandler(args.json, "ConnectionError", err)
2332 if res.status_code == 403:
2333 return "The specified Interface"+"("+args.Interface+")"+\
2334 " doesn't exist"
2335 return res.text
2336
2337
2338def getHostname(host, args, session):
2339
2340 """
2341 Called by the network function. Prints out the Hostname.
2342
2343 @param host: string, the hostname or IP address of the bmc
2344 @param args: contains additional arguments used by the ldap subcommand
2345 args.json: boolean, if this flag is set to true, the output
2346 will be provided in json format for programmatic consumption
2347 @param session: the active session to use
2348 """
2349
2350 url = "https://"+host+"/xyz/openbmc_project/network/config/attr/HostName"
2351 httpHeader = {'Content-Type': 'application/json'}
2352
2353 try:
2354 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2355 except(requests.exceptions.Timeout):
2356 return(connectionErrHandler(args.json, "Timeout", None))
2357 except(requests.exceptions.ConnectionError) as err:
2358 return connectionErrHandler(args.json, "ConnectionError", err)
2359
2360 return res.text
2361
2362
2363def setHostname(host, args, session):
2364 """
2365 Called by the network function. Sets the Hostname.
2366
2367 @param host: string, the hostname or IP address of the bmc
2368 @param args: contains additional arguments used by the ldap subcommand
2369 args.json: boolean, if this flag is set to true, the output
2370 will be provided in json format for programmatic consumption
2371 @param session: the active session to use
2372 """
2373
2374 url = "https://"+host+"/xyz/openbmc_project/network/config/attr/HostName"
2375 httpHeader = {'Content-Type': 'application/json'}
2376
2377 data = {"data": args.HostName}
2378
2379 try:
2380 res = session.put(url, headers=httpHeader, json=data, verify=False,
2381 timeout=30)
2382 except(requests.exceptions.Timeout):
2383 return(connectionErrHandler(args.json, "Timeout", None))
2384 except(requests.exceptions.ConnectionError) as err:
2385 return connectionErrHandler(args.json, "ConnectionError", err)
2386
2387 return res.text
2388
2389
2390def getDomainName(host, args, session):
2391
2392 """
2393 Called by the network function. Prints out the DomainName.
2394
2395 @param host: string, the hostname or IP address of the bmc
2396 @param args: contains additional arguments used by the ldap subcommand
2397 args.json: boolean, if this flag is set to true, the output
2398 will be provided in json format for programmatic consumption
2399 @param session: the active session to use
2400 """
2401
2402 url = "https://"+host+"/xyz/openbmc_project/network/"+args.Interface+\
2403 "/attr/DomainName"
2404 httpHeader = {'Content-Type': 'application/json'}
2405
2406 try:
2407 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2408 except(requests.exceptions.Timeout):
2409 return(connectionErrHandler(args.json, "Timeout", None))
2410 except(requests.exceptions.ConnectionError) as err:
2411 return connectionErrHandler(args.json, "ConnectionError", err)
2412 if res.status_code == 404:
2413 return "The specified Interface"+"("+args.Interface+")"+\
2414 " doesn't exist"
2415
2416 return res.text
2417
2418
2419def setDomainName(host, args, session):
2420 """
2421 Called by the network function. Sets the DomainName.
2422
2423 @param host: string, the hostname or IP address of the bmc
2424 @param args: contains additional arguments used by the ldap subcommand
2425 args.json: boolean, if this flag is set to true, the output
2426 will be provided in json format for programmatic consumption
2427 @param session: the active session to use
2428 """
2429
2430 url = "https://"+host+"/xyz/openbmc_project/network/"+args.Interface+\
2431 "/attr/DomainName"
2432 httpHeader = {'Content-Type': 'application/json'}
2433
2434 data = {"data": args.DomainName.split(",")}
2435
2436 try:
2437 res = session.put(url, headers=httpHeader, json=data, verify=False,
2438 timeout=30)
2439 except(requests.exceptions.Timeout):
2440 return(connectionErrHandler(args.json, "Timeout", None))
2441 except(requests.exceptions.ConnectionError) as err:
2442 return connectionErrHandler(args.json, "ConnectionError", err)
2443 if res.status_code == 403:
2444 return "The specified Interface"+"("+args.Interface+")"+\
2445 " doesn't exist"
2446
2447 return res.text
2448
2449
2450def getMACAddress(host, args, session):
2451
2452 """
2453 Called by the network function. Prints out the MACAddress.
2454
2455 @param host: string, the hostname or IP address of the bmc
2456 @param args: contains additional arguments used by the ldap subcommand
2457 args.json: boolean, if this flag is set to true, the output
2458 will be provided in json format for programmatic consumption
2459 @param session: the active session to use
2460 """
2461
2462 url = "https://"+host+"/xyz/openbmc_project/network/"+args.Interface+\
2463 "/attr/MACAddress"
2464 httpHeader = {'Content-Type': 'application/json'}
2465
2466 try:
2467 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2468 except(requests.exceptions.Timeout):
2469 return(connectionErrHandler(args.json, "Timeout", None))
2470 except(requests.exceptions.ConnectionError) as err:
2471 return connectionErrHandler(args.json, "ConnectionError", err)
2472 if res.status_code == 404:
2473 return "The specified Interface"+"("+args.Interface+")"+\
2474 " doesn't exist"
2475
2476 return res.text
2477
2478
2479def setMACAddress(host, args, session):
2480 """
2481 Called by the network function. Sets the MACAddress.
2482
2483 @param host: string, the hostname or IP address of the bmc
2484 @param args: contains additional arguments used by the ldap subcommand
2485 args.json: boolean, if this flag is set to true, the output
2486 will be provided in json format for programmatic consumption
2487 @param session: the active session to use
2488 """
2489
2490 url = "https://"+host+"/xyz/openbmc_project/network/"+args.Interface+\
2491 "/attr/MACAddress"
2492 httpHeader = {'Content-Type': 'application/json'}
2493
2494 data = {"data": args.MACAddress}
2495
2496 try:
2497 res = session.put(url, headers=httpHeader, json=data, verify=False,
2498 timeout=30)
2499 except(requests.exceptions.Timeout):
2500 return(connectionErrHandler(args.json, "Timeout", None))
2501 except(requests.exceptions.ConnectionError) as err:
2502 return connectionErrHandler(args.json, "ConnectionError", err)
2503 if res.status_code == 403:
2504 return "The specified Interface"+"("+args.Interface+")"+\
2505 " doesn't exist"
2506
2507 return res.text
2508
2509
2510def getDefaultGateway(host, args, session):
2511
2512 """
2513 Called by the network function. Prints out the DefaultGateway.
2514
2515 @param host: string, the hostname or IP address of the bmc
2516 @param args: contains additional arguments used by the ldap subcommand
2517 args.json: boolean, if this flag is set to true, the output
2518 will be provided in json format for programmatic consumption
2519 @param session: the active session to use
2520 """
2521
2522 url = "https://"+host+"/xyz/openbmc_project/network/config/attr/DefaultGateway"
2523 httpHeader = {'Content-Type': 'application/json'}
2524
2525 try:
2526 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2527 except(requests.exceptions.Timeout):
2528 return(connectionErrHandler(args.json, "Timeout", None))
2529 except(requests.exceptions.ConnectionError) as err:
2530 return connectionErrHandler(args.json, "ConnectionError", err)
2531 if res.status_code == 404:
2532 return "Failed to get Default Gateway info!!"
2533
2534 return res.text
2535
2536
2537def setDefaultGateway(host, args, session):
2538 """
2539 Called by the network function. Sets the DefaultGateway.
2540
2541 @param host: string, the hostname or IP address of the bmc
2542 @param args: contains additional arguments used by the ldap subcommand
2543 args.json: boolean, if this flag is set to true, the output
2544 will be provided in json format for programmatic consumption
2545 @param session: the active session to use
2546 """
2547
2548 url = "https://"+host+"/xyz/openbmc_project/network/config/attr/DefaultGateway"
2549 httpHeader = {'Content-Type': 'application/json'}
2550
2551 data = {"data": args.DefaultGW}
2552
2553 try:
2554 res = session.put(url, headers=httpHeader, json=data, verify=False,
2555 timeout=30)
2556 except(requests.exceptions.Timeout):
2557 return(connectionErrHandler(args.json, "Timeout", None))
2558 except(requests.exceptions.ConnectionError) as err:
2559 return connectionErrHandler(args.json, "ConnectionError", err)
2560 if res.status_code == 403:
2561 return "Failed to set Default Gateway!!"
2562
2563 return res.text
2564
2565
2566def viewNWConfig(host, args, session):
2567 """
2568 Called by the ldap function. Prints out network configured properties
2569
2570 @param host: string, the hostname or IP address of the bmc
2571 @param args: contains additional arguments used by the ldap subcommand
2572 args.json: boolean, if this flag is set to true, the output
2573 will be provided in json format for programmatic consumption
2574 @param session: the active session to use
2575 @return returns LDAP's configured properties.
2576 """
2577 url = "https://"+host+"/xyz/openbmc_project/network/enumerate"
2578 httpHeader = {'Content-Type': 'application/json'}
2579 try:
2580 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2581 except(requests.exceptions.Timeout):
2582 return(connectionErrHandler(args.json, "Timeout", None))
2583 except(requests.exceptions.ConnectionError) as err:
2584 return connectionErrHandler(args.json, "ConnectionError", err)
2585 except(requests.exceptions.RequestException) as err:
2586 return connectionErrHandler(args.json, "RequestException", err)
2587 if res.status_code == 404:
2588 return "LDAP server config has not been created"
2589 return res.text
2590
2591
2592def getDNS(host, args, session):
2593
2594 """
2595 Called by the network function. Prints out DNS servers on the interface
2596
2597 @param host: string, the hostname or IP address of the bmc
2598 @param args: contains additional arguments used by the ldap subcommand
2599 args.json: boolean, if this flag is set to true, the output
2600 will be provided in json format for programmatic consumption
2601 @param session: the active session to use
2602 """
2603
2604 url = "https://" + host + "/xyz/openbmc_project/network/" + args.Interface\
2605 + "/attr/Nameservers"
2606 httpHeader = {'Content-Type': 'application/json'}
2607
2608 try:
2609 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2610 except(requests.exceptions.Timeout):
2611 return(connectionErrHandler(args.json, "Timeout", None))
2612 except(requests.exceptions.ConnectionError) as err:
2613 return connectionErrHandler(args.json, "ConnectionError", err)
2614 if res.status_code == 404:
2615 return "The specified Interface"+"("+args.Interface+")" + \
2616 " doesn't exist"
2617
2618 return res.text
2619
2620
2621def setDNS(host, args, session):
2622 """
2623 Called by the network function. Sets DNS servers on the interface.
2624
2625 @param host: string, the hostname or IP address of the bmc
2626 @param args: contains additional arguments used by the ldap subcommand
2627 args.json: boolean, if this flag is set to true, the output
2628 will be provided in json format for programmatic consumption
2629 @param session: the active session to use
2630 """
2631
2632 url = "https://" + host + "/xyz/openbmc_project/network/" + args.Interface\
2633 + "/attr/Nameservers"
2634 httpHeader = {'Content-Type': 'application/json'}
2635
2636 data = {"data": args.DNSServers.split(",")}
2637
2638 try:
2639 res = session.put(url, headers=httpHeader, json=data, verify=False,
2640 timeout=30)
2641 except(requests.exceptions.Timeout):
2642 return(connectionErrHandler(args.json, "Timeout", None))
2643 except(requests.exceptions.ConnectionError) as err:
2644 return connectionErrHandler(args.json, "ConnectionError", err)
2645 if res.status_code == 403:
2646 return "The specified Interface"+"("+args.Interface+")" +\
2647 " doesn't exist"
2648
2649 return res.text
2650
2651
2652def getNTP(host, args, session):
2653
2654 """
2655 Called by the network function. Prints out NTP servers on the interface
2656
2657 @param host: string, the hostname or IP address of the bmc
2658 @param args: contains additional arguments used by the ldap subcommand
2659 args.json: boolean, if this flag is set to true, the output
2660 will be provided in json format for programmatic consumption
2661 @param session: the active session to use
2662 """
2663
2664 url = "https://" + host + "/xyz/openbmc_project/network/" + args.Interface\
2665 + "/attr/NTPServers"
2666 httpHeader = {'Content-Type': 'application/json'}
2667
2668 try:
2669 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2670 except(requests.exceptions.Timeout):
2671 return(connectionErrHandler(args.json, "Timeout", None))
2672 except(requests.exceptions.ConnectionError) as err:
2673 return connectionErrHandler(args.json, "ConnectionError", err)
2674 if res.status_code == 404:
2675 return "The specified Interface"+"("+args.Interface+")" + \
2676 " doesn't exist"
2677
2678 return res.text
2679
2680
2681def setNTP(host, args, session):
2682 """
2683 Called by the network function. Sets NTP servers on the interface.
2684
2685 @param host: string, the hostname or IP address of the bmc
2686 @param args: contains additional arguments used by the ldap subcommand
2687 args.json: boolean, if this flag is set to true, the output
2688 will be provided in json format for programmatic consumption
2689 @param session: the active session to use
2690 """
2691
2692 url = "https://" + host + "/xyz/openbmc_project/network/" + args.Interface\
2693 + "/attr/NTPServers"
2694 httpHeader = {'Content-Type': 'application/json'}
2695
2696 data = {"data": args.NTPServers.split(",")}
2697
2698 try:
2699 res = session.put(url, headers=httpHeader, json=data, verify=False,
2700 timeout=30)
2701 except(requests.exceptions.Timeout):
2702 return(connectionErrHandler(args.json, "Timeout", None))
2703 except(requests.exceptions.ConnectionError) as err:
2704 return connectionErrHandler(args.json, "ConnectionError", err)
2705 if res.status_code == 403:
2706 return "The specified Interface"+"("+args.Interface+")" +\
2707 " doesn't exist"
2708
2709 return res.text
2710
2711
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06002712def addIP(host, args, session):
2713 """
2714 Called by the network function. Configures IP address on given interface
2715
2716 @param host: string, the hostname or IP address of the bmc
2717 @param args: contains additional arguments used by the ldap subcommand
2718 args.json: boolean, if this flag is set to true, the output
2719 will be provided in json format for programmatic consumption
2720 @param session: the active session to use
2721 """
2722
2723 url = "https://" + host + "/xyz/openbmc_project/network/" + args.Interface\
2724 + "/action/IP"
2725 httpHeader = {'Content-Type': 'application/json'}
2726 protocol = {
2727 'ipv4': 'xyz.openbmc_project.Network.IP.Protocol.IPv4',
2728 'ipv6': 'xyz.openbmc_project.Network.IP.Protocol.IPv6'
2729 }
2730
2731 data = {"data": [protocol[args.type], args.address, int(args.prefixLength),
2732 args.gateway]}
2733
2734 try:
2735 res = session.post(url, headers=httpHeader, json=data, verify=False,
2736 timeout=30)
2737 except(requests.exceptions.Timeout):
2738 return(connectionErrHandler(args.json, "Timeout", None))
2739 except(requests.exceptions.ConnectionError) as err:
2740 return connectionErrHandler(args.json, "ConnectionError", err)
2741 if res.status_code == 404:
2742 return "The specified Interface" + "(" + args.Interface + ")" +\
2743 " doesn't exist"
2744
2745 return res.text
2746
2747
2748def getIP(host, args, session):
2749 """
2750 Called by the network function. Prints out IP address of given interface
2751
2752 @param host: string, the hostname or IP address of the bmc
2753 @param args: contains additional arguments used by the ldap subcommand
2754 args.json: boolean, if this flag is set to true, the output
2755 will be provided in json format for programmatic consumption
2756 @param session: the active session to use
2757 """
2758
2759 url = "https://" + host+"/xyz/openbmc_project/network/" + args.Interface +\
2760 "/enumerate"
2761 httpHeader = {'Content-Type': 'application/json'}
2762 try:
2763 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2764 except(requests.exceptions.Timeout):
2765 return(connectionErrHandler(args.json, "Timeout", None))
2766 except(requests.exceptions.ConnectionError) as err:
2767 return connectionErrHandler(args.json, "ConnectionError", err)
2768 if res.status_code == 404:
2769 return "The specified Interface" + "(" + args.Interface + ")" +\
2770 " doesn't exist"
2771
2772 return res.text
2773
2774
2775def deleteIP(host, args, session):
2776 """
2777 Called by the network function. Deletes the IP address from given Interface
2778
2779 @param host: string, the hostname or IP address of the bmc
2780 @param args: contains additional arguments used by the ldap subcommand
2781 @param session: the active session to use
2782 @param args.json: boolean, if this flag is set to true, the output
2783 will be provided in json format for programmatic consumption
2784 """
2785
2786 url = "https://"+host+"/xyz/openbmc_project/network/" + args.Interface+\
2787 "/enumerate"
2788 httpHeader = {'Content-Type':'application/json'}
2789 data = {"data": []}
2790 try:
2791 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
2792 except(requests.exceptions.Timeout):
2793 return(connectionErrHandler(args.json, "Timeout", None))
2794 except(requests.exceptions.ConnectionError) as err:
2795 return connectionErrHandler(args.json, "ConnectionError", err)
2796 if res.status_code == 404:
2797 return "The specified Interface" + "(" + args.Interface + ")" +\
2798 " doesn't exist"
2799 objDict = json.loads(res.text)
2800 if not objDict['data']:
2801 return "No object found for given address on given Interface"
2802
2803 for obj in objDict['data']:
2804 if args.address in objDict['data'][obj]['Address']:
2805 url = "https://"+host+obj+"/action/delete"
2806 try:
2807 res = session.post(url, headers=httpHeader, json=data,
2808 verify=False, timeout=30)
2809 except(requests.exceptions.Timeout):
2810 return(connectionErrHandler(args.json, "Timeout", None))
2811 except(requests.exceptions.ConnectionError) as err:
2812 return connectionErrHandler(args.json, "ConnectionError", err)
2813 return res.text
2814 else:
2815 continue
2816 return "No object found for given address on given Interface"
2817
2818
Nagaraju Gorugantif21d43c2018-11-19 10:47:19 -06002819def addVLAN(host, args, session):
2820 """
2821 Called by the network function. Creates VLAN on given interface.
2822
2823 @param host: string, the hostname or IP address of the bmc
2824 @param args: contains additional arguments used by the ldap subcommand
2825 args.json: boolean, if this flag is set to true, the output
2826 will be provided in json format for programmatic consumption
2827 @param session: the active session to use
2828 """
2829
2830 url = "https://" + host+"/xyz/openbmc_project/network/action/VLAN"
2831 httpHeader = {'Content-Type': 'application/json'}
2832
2833 data = {"data": [args.Interface,args.Identifier]}
2834
2835 try:
2836 res = session.post(url, headers=httpHeader, json=data, verify=False,
2837 timeout=30)
2838 except(requests.exceptions.Timeout):
2839 return(connectionErrHandler(args.json, "Timeout", None))
2840 except(requests.exceptions.ConnectionError) as err:
2841 return connectionErrHandler(args.json, "ConnectionError", err)
2842 if res.status_code == 400:
2843 return "The specified Interface" + "(" + args.Interface + ")" +\
2844 " doesn't exist"
2845
2846 return res.text
2847
2848
2849def deleteVLAN(host, args, session):
2850 """
2851 Called by the network function. Creates VLAN on given interface.
2852
2853 @param host: string, the hostname or IP address of the bmc
2854 @param args: contains additional arguments used by the ldap subcommand
2855 args.json: boolean, if this flag is set to true, the output
2856 will be provided in json format for programmatic consumption
2857 @param session: the active session to use
2858 """
2859
2860 url = "https://" + host+"/xyz/openbmc_project/network/"+args.Interface+"/action/delete"
2861 httpHeader = {'Content-Type':'application/json'}
2862 data = {"data": []}
2863
2864 try:
2865 res = session.post(url, headers=httpHeader, json=data, verify=False, timeout=30)
2866 except(requests.exceptions.Timeout):
2867 return(connectionErrHandler(args.json, "Timeout", None))
2868 except(requests.exceptions.ConnectionError) as err:
2869 return connectionErrHandler(args.json, "ConnectionError", err)
2870 if res.status_code == 404:
2871 return "The specified VLAN"+"("+args.Interface+"_"+args.Identifier\
2872 +")" +" doesn't exist"
2873
2874 return res.text
2875
2876
2877def viewDHCPConfig(host, args, session):
2878 """
2879 Called by the network function. Shows DHCP configured Properties.
2880
2881 @param host: string, the hostname or IP address of the bmc
2882 @param args: contains additional arguments used by the ldap subcommand
2883 args.json: boolean, if this flag is set to true, the output
2884 will be provided in json format for programmatic consumption
2885 @param session: the active session to use
2886 """
2887
2888 url="https://"+host+"/xyz/openbmc_project/network/config/dhcp"
2889 httpHeader = {'Content-Type':'application/json'}
2890
2891 try:
2892 res = session.get(url, headers=httpHeader, verify=False, timeout=30)
2893 except(requests.exceptions.Timeout):
2894 return(connectionErrHandler(args.json, "Timeout", None))
2895 except(requests.exceptions.ConnectionError) as err:
2896 return connectionErrHandler(args.json, "ConnectionError", err)
2897
2898 return res.text
2899
2900
2901def configureDHCP(host, args, session):
2902 """
2903 Called by the network function. Configures/updates DHCP Properties.
2904
2905 @param host: string, the hostname or IP address of the bmc
2906 @param args: contains additional arguments used by the ldap subcommand
2907 args.json: boolean, if this flag is set to true, the output
2908 will be provided in json format for programmatic consumption
2909 @param session: the active session to use
2910 """
2911
2912 httpHeader = {'Content-Type': 'application/json'}
2913
2914 try:
2915 url="https://"+host+"/xyz/openbmc_project/network/config/dhcp"
2916 if(args.DNSEnabled == True):
2917 data = '{"data": 1}'
2918 else:
2919 data = '{"data": 0}'
2920 res = session.put(url + '/attr/DNSEnabled', headers=httpHeader,
2921 data=data, verify=False, timeout=30)
2922 if(args.HostNameEnabled == True):
2923 data = '{"data": 1}'
2924 else:
2925 data = '{"data": 0}'
2926 res = session.put(url + '/attr/HostNameEnabled', headers=httpHeader,
2927 data=data, verify=False, timeout=30)
2928 if(args.NTPEnabled == True):
2929 data = '{"data": 1}'
2930 else:
2931 data = '{"data": 0}'
2932 res = session.put(url + '/attr/NTPEnabled', headers=httpHeader,
2933 data=data, verify=False, timeout=30)
2934 if(args.SendHostNameEnabled == True):
2935 data = '{"data": 1}'
2936 else:
2937 data = '{"data": 0}'
2938 res = session.put(url + '/attr/SendHostNameEnabled', headers=httpHeader,
2939 data=data, verify=False, timeout=30)
2940 except(requests.exceptions.Timeout):
2941 return(connectionErrHandler(args.json, "Timeout", None))
2942 except(requests.exceptions.ConnectionError) as err:
2943 return connectionErrHandler(args.json, "ConnectionError", err)
2944
2945 return res.text
2946
2947
2948def nwReset(host, args, session):
2949
2950 """
2951 Called by the network function. Resets networks setting to factory defaults.
2952
2953 @param host: string, the hostname or IP address of the bmc
2954 @param args: contains additional arguments used by the ldap subcommand
2955 args.json: boolean, if this flag is set to true, the output
2956 will be provided in json format for programmatic consumption
2957 @param session: the active session to use
2958 """
2959
2960 url = "https://"+host+"/xyz/openbmc_project/network/action/Reset"
2961 httpHeader = {'Content-Type': 'application/json'}
2962 data = '{"data":[] }'
2963 try:
2964 res = session.post(url, headers=httpHeader, data=data, verify=False,
2965 timeout=30)
2966
2967 except(requests.exceptions.Timeout):
2968 return(connectionErrHandler(args.json, "Timeout", None))
2969 except(requests.exceptions.ConnectionError) as err:
2970 return connectionErrHandler(args.json, "ConnectionError", err)
2971
2972 return res.text
2973
2974
Ratan Guptafeee6372018-10-17 23:25:51 +05302975def createPrivilegeMapping(host, args, session):
2976 """
2977 Called by the ldap function. Creates the group and the privilege mapping.
2978
2979 @param host: string, the hostname or IP address of the bmc
2980 @param args: contains additional arguments used by the ldap subcommand
2981 @param session: the active session to use
2982 @param args.json: boolean, if this flag is set to true, the output
2983 will be provided in json format for programmatic consumption
2984 """
2985
2986 url = 'https://'+host+'/xyz/openbmc_project/user/ldap/action/Create'
2987 httpHeader = {'Content-Type':'application/json'}
2988
2989 data = {"data": [args.groupName,args.privilege]}
2990
2991 try:
2992 res = session.post(url, headers=httpHeader, json = data, verify=False, timeout=30)
2993 except(requests.exceptions.Timeout):
2994 return(connectionErrHandler(args.json, "Timeout", None))
2995 except(requests.exceptions.ConnectionError) as err:
2996 return connectionErrHandler(args.json, "ConnectionError", err)
2997 return res.text
2998
2999def listPrivilegeMapping(host, args, session):
3000 """
3001 Called by the ldap function. Lists the group and the privilege mapping.
3002
3003 @param host: string, the hostname or IP address of the bmc
3004 @param args: contains additional arguments used by the ldap subcommand
3005 @param session: the active session to use
3006 @param args.json: boolean, if this flag is set to true, the output
3007 will be provided in json format for programmatic consumption
3008 """
3009 url = 'https://'+host+'/xyz/openbmc_project/user/ldap/enumerate'
3010 httpHeader = {'Content-Type': 'application/json'}
3011 data = {"data": []}
3012
3013 try:
3014 res = session.get(url, headers=httpHeader, json = data, verify=False, timeout=30)
3015 except(requests.exceptions.Timeout):
3016 return(connectionErrHandler(args.json, "Timeout", None))
3017 except(requests.exceptions.ConnectionError) as err:
3018 return connectionErrHandler(args.json, "ConnectionError", err)
3019 return res.text
3020
3021def deletePrivilegeMapping(host, args, session):
3022 """
3023 Called by the ldap function. Deletes the mapping associated with the group.
3024
3025 @param host: string, the hostname or IP address of the bmc
3026 @param args: contains additional arguments used by the ldap subcommand
3027 @param session: the active session to use
3028 @param args.json: boolean, if this flag is set to true, the output
3029 will be provided in json format for programmatic consumption
3030 """
3031 (ldapNameSpaceObjects) = listPrivilegeMapping(host, args, session)
3032 ldapNameSpaceObjects = json.loads(ldapNameSpaceObjects)["data"]
3033 path = ''
3034
3035 # not interested in the config objet
3036 ldapNameSpaceObjects.pop('/xyz/openbmc_project/user/ldap/config', None)
3037
3038 # search for the object having the mapping for the given group
3039 for key,value in ldapNameSpaceObjects.items():
3040 if value['GroupName'] == args.groupName:
3041 path = key
3042 break
3043
3044 if path == '':
3045 return "No privilege mapping found for this group."
3046
3047 # delete the object
3048 url = 'https://'+host+path+'/action/delete'
3049 httpHeader = {'Content-Type': 'application/json'}
3050 data = {"data": []}
3051
3052 try:
3053 res = session.post(url, headers=httpHeader, json = data, verify=False, timeout=30)
3054 except(requests.exceptions.Timeout):
3055 return(connectionErrHandler(args.json, "Timeout", None))
3056 except(requests.exceptions.ConnectionError) as err:
3057 return connectionErrHandler(args.json, "ConnectionError", err)
3058 return res.text
Ratan Gupta9166cd22018-10-01 18:09:40 +05303059
Nagaraju Goruganti7d1fe172018-11-13 06:09:29 -06003060def viewLDAPConfig(host, args, session):
3061 """
3062 Called by the ldap function. Prints out LDAP's configured properties
3063
3064 @param host: string, the hostname or IP address of the bmc
3065 @param args: contains additional arguments used by the ldap subcommand
3066 args.json: boolean, if this flag is set to true, the output
3067 will be provided in json format for programmatic consumption
3068 @param session: the active session to use
3069 @return returns LDAP's configured properties.
3070 """
3071 url = "https://"+host+"/xyz/openbmc_project/user/ldap/config"
3072 httpHeader = {'Content-Type': 'application/json'}
3073 try:
3074 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
3075 except(requests.exceptions.Timeout):
3076 return(connectionErrHandler(args.json, "Timeout", None))
3077 except(requests.exceptions.ConnectionError) as err:
3078 return connectionErrHandler(args.json, "ConnectionError", err)
3079 except(requests.exceptions.RequestException) as err:
3080 return connectionErrHandler(args.json, "RequestException", err)
3081 if res.status_code == 404:
3082 return "LDAP server config has not been created"
3083 return res.text
3084
Nagaraju Gorugantif21d43c2018-11-19 10:47:19 -06003085def str2bool(v):
3086 if v.lower() in ('yes', 'true', 't', 'y', '1'):
3087 return True
3088 elif v.lower() in ('no', 'false', 'f', 'n', '0'):
3089 return False
3090 else:
3091 raise argparse.ArgumentTypeError('Boolean value expected.')
Nagaraju Goruganti7d1fe172018-11-13 06:09:29 -06003092
Matt Spinler7d426c22018-09-24 14:42:07 -05003093def localUsers(host, args, session):
3094 """
3095 Enables and disables local BMC users.
3096
3097 @param host: string, the hostname or IP address of the bmc
3098 @param args: contains additional arguments used by the logging sub command
3099 @param session: the active session to use
3100 """
3101
3102 httpHeader = {'Content-Type':'application/json'}
3103 url="https://{hostname}/xyz/openbmc_project/user/enumerate".format(hostname=host)
3104 try:
3105 res = session.get(url, headers=httpHeader, verify=False, timeout=40)
3106 except(requests.exceptions.Timeout):
3107 return(connectionErrHandler(args.json, "Timeout", None))
3108 usersDict = json.loads(res.text)
3109
3110 if not usersDict['data']:
3111 return "No users found"
3112
3113 output = ""
3114 for user in usersDict['data']:
Matt Spinler015adc22018-10-23 14:30:19 -05003115
3116 # Skip LDAP and another non-local users
3117 if 'UserEnabled' not in usersDict['data'][user]:
3118 continue
3119
Matt Spinler7d426c22018-09-24 14:42:07 -05003120 name = user.split('/')[-1]
3121 url = "https://{hostname}{user}/attr/UserEnabled".format(hostname=host, user=user)
3122
3123 if args.local_users == "queryenabled":
3124 try:
3125 res = session.get(url, headers=httpHeader,verify=False, timeout=30)
3126 except(requests.exceptions.Timeout):
3127 return(connectionErrHandler(args.json, "Timeout", None))
3128
3129 result = json.loads(res.text)
3130 output += ("User: {name} Enabled: {result}\n").format(name=name, result=result['data'])
3131
3132 elif args.local_users in ["enableall", "disableall"]:
3133 action = ""
3134 if args.local_users == "enableall":
3135 data = '{"data": true}'
3136 action = "Enabling"
3137 else:
3138 data = '{"data": false}'
3139 action = "Disabling"
3140
3141 output += "{action} {name}\n".format(action=action, name=name)
3142
3143 try:
3144 resp = session.put(url, headers=httpHeader, data=data, verify=False, timeout=30)
3145 except(requests.exceptions.Timeout):
3146 return connectionErrHandler(args.json, "Timeout", None)
3147 except(requests.exceptions.ConnectionError) as err:
3148 return connectionErrHandler(args.json, "ConnectionError", err)
3149 else:
3150 return "Invalid local users argument"
3151
3152 return output
3153
Marri Devender Rao2c2a5162018-11-05 08:57:11 -06003154def setPassword(host, args, session):
3155 """
3156 Set local user password
3157 @param host: string, the hostname or IP address of the bmc
3158 @param args: contains additional arguments used by the logging sub
3159 command
3160 @param session: the active session to use
3161 @param args.json: boolean, if this flag is set to true, the output
3162 will be provided in json format for programmatic consumption
3163 @return: Session object
3164 """
3165 url = "https://" + host + "/xyz/openbmc_project/user/" + args.user + \
3166 "/action/SetPassword"
3167 httpHeader = {'Content-Type': 'application/json'}
3168 try:
3169 res = session.post(url, headers=httpHeader,
3170 json={"data": [args.password]}, verify=False,
3171 timeout=30)
3172 except(requests.exceptions.Timeout):
3173 return(connectionErrHandler(args.json, "Timeout", None))
3174 except(requests.exceptions.ConnectionError) as err:
3175 return connectionErrHandler(args.json, "ConnectionError", err)
3176 except(requests.exceptions.RequestException) as err:
3177 return connectionErrHandler(args.json, "RequestException", err)
3178 return res.text
3179
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003180def createCommandParser():
Justin Thalere412dc22018-01-12 16:28:24 -06003181 """
3182 creates the parser for the command line along with help for each command and subcommand
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003183
Justin Thalere412dc22018-01-12 16:28:24 -06003184 @return: returns the parser for the command line
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003185 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003186 parser = argparse.ArgumentParser(description='Process arguments')
Justin Thalere412dc22018-01-12 16:28:24 -06003187 parser.add_argument("-H", "--host", help='A hostname or IP for the BMC')
3188 parser.add_argument("-U", "--user", help='The username to login with')
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003189 group = parser.add_mutually_exclusive_group()
3190 group.add_argument("-A", "--askpw", action='store_true', help='prompt for password')
3191 group.add_argument("-P", "--PW", help='Provide the password in-line')
3192 parser.add_argument('-j', '--json', action='store_true', help='output json data only')
3193 parser.add_argument('-t', '--policyTableLoc', help='The location of the policy table to parse alerts')
3194 parser.add_argument('-c', '--CerFormat', action='store_true', help=argparse.SUPPRESS)
3195 parser.add_argument('-T', '--procTime', action='store_true', help= argparse.SUPPRESS)
Justin Thalere412dc22018-01-12 16:28:24 -06003196 parser.add_argument('-V', '--version', action='store_true', help='Display the version number of the openbmctool')
3197 subparsers = parser.add_subparsers(title='subcommands', description='valid subcommands',help="sub-command help", dest='command')
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003198
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003199 #fru command
3200 parser_inv = subparsers.add_parser("fru", help='Work with platform inventory')
Justin Thalere412dc22018-01-12 16:28:24 -06003201 inv_subparser = parser_inv.add_subparsers(title='subcommands', description='valid inventory actions', help="valid inventory actions", dest='command')
Justin Thaler53bf2f12018-07-16 14:05:32 -05003202 inv_subparser.required = True
3203 #fru print
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003204 inv_print = inv_subparser.add_parser("print", help="prints out a list of all FRUs")
3205 inv_print.set_defaults(func=fruPrint)
3206 #fru list [0....n]
3207 inv_list = inv_subparser.add_parser("list", help="print out details on selected FRUs. Specifying no items will list the entire inventory")
3208 inv_list.add_argument('items', nargs='?', help="print out details on selected FRUs. Specifying no items will list the entire inventory")
3209 inv_list.set_defaults(func=fruList)
3210 #fru status
3211 inv_status = inv_subparser.add_parser("status", help="prints out the status of all FRUs")
Justin Thalere412dc22018-01-12 16:28:24 -06003212 inv_status.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003213 inv_status.set_defaults(func=fruStatus)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003214
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003215 #sensors command
3216 parser_sens = subparsers.add_parser("sensors", help="Work with platform sensors")
Justin Thalere412dc22018-01-12 16:28:24 -06003217 sens_subparser=parser_sens.add_subparsers(title='subcommands', description='valid sensor actions', help='valid sensor actions', dest='command')
Justin Thaler53bf2f12018-07-16 14:05:32 -05003218 sens_subparser.required = True
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003219 #sensor print
3220 sens_print= sens_subparser.add_parser('print', help="prints out a list of all Sensors.")
3221 sens_print.set_defaults(func=sensor)
3222 #sensor list[0...n]
3223 sens_list=sens_subparser.add_parser("list", help="Lists all Sensors in the platform. Specify a sensor for full details. ")
3224 sens_list.add_argument("sensNum", nargs='?', help="The Sensor number to get full details on" )
3225 sens_list.set_defaults(func=sensor)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003226
3227
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003228 #sel command
3229 parser_sel = subparsers.add_parser("sel", help="Work with platform alerts")
Justin Thalere412dc22018-01-12 16:28:24 -06003230 sel_subparser = parser_sel.add_subparsers(title='subcommands', description='valid SEL actions', help = 'valid SEL actions', dest='command')
Justin Thaler53bf2f12018-07-16 14:05:32 -05003231 sel_subparser.required = True
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003232 #sel print
3233 sel_print = sel_subparser.add_parser("print", help="prints out a list of all sels in a condensed list")
3234 sel_print.add_argument('-d', '--devdebug', action='store_true', help=argparse.SUPPRESS)
3235 sel_print.add_argument('-v', '--verbose', action='store_true', help="Changes the output to being very verbose")
3236 sel_print.add_argument('-f', '--fileloc', help='Parse a file instead of the BMC output')
3237 sel_print.set_defaults(func=selPrint)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003238
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003239 #sel list
3240 sel_list = sel_subparser.add_parser("list", help="Lists all SELs in the platform. Specifying a specific number will pull all the details for that individual SEL")
3241 sel_list.add_argument("selNum", nargs='?', type=int, help="The SEL entry to get details on")
3242 sel_list.set_defaults(func=selList)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003243
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003244 sel_get = sel_subparser.add_parser("get", help="Gets the verbose details of a specified SEL entry")
3245 sel_get.add_argument('selNum', type=int, help="the number of the SEL entry to get")
3246 sel_get.set_defaults(func=selList)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003247
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003248 sel_clear = sel_subparser.add_parser("clear", help="Clears all entries from the SEL")
3249 sel_clear.set_defaults(func=selClear)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003250
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003251 sel_setResolved = sel_subparser.add_parser("resolve", help="Sets the sel entry to resolved")
Justin Thalere412dc22018-01-12 16:28:24 -06003252 sel_setResolved.add_argument('-n', '--selNum', type=int, help="the number of the SEL entry to resolve")
3253 sel_ResolveAll_sub = sel_setResolved.add_subparsers(title='subcommands', description='valid subcommands',help="sub-command help", dest='command')
3254 sel_ResolveAll = sel_ResolveAll_sub.add_parser('all', help='Resolve all SEL entries')
3255 sel_ResolveAll.set_defaults(func=selResolveAll)
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003256 sel_setResolved.set_defaults(func=selSetResolved)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003257
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003258 parser_chassis = subparsers.add_parser("chassis", help="Work with chassis power and status")
Justin Thalere412dc22018-01-12 16:28:24 -06003259 chas_sub = parser_chassis.add_subparsers(title='subcommands', description='valid subcommands',help="sub-command help", dest='command')
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003260
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003261 parser_chassis.add_argument('status', action='store_true', help='Returns the current status of the platform')
3262 parser_chassis.set_defaults(func=chassis)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003263
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003264 parser_chasPower = chas_sub.add_parser("power", help="Turn the chassis on or off, check the power state")
Justin Thalere412dc22018-01-12 16:28:24 -06003265 parser_chasPower.add_argument('powcmd', choices=['on','softoff', 'hardoff', 'status'], help='The value for the power command. on, off, or status')
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003266 parser_chasPower.set_defaults(func=chassisPower)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003267
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003268 #control the chassis identify led
3269 parser_chasIdent = chas_sub.add_parser("identify", help="Control the chassis identify led")
3270 parser_chasIdent.add_argument('identcmd', choices=['on', 'off', 'status'], help='The control option for the led: on, off, blink, status')
3271 parser_chasIdent.set_defaults(func=chassisIdent)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003272
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003273 #collect service data
3274 parser_servData = subparsers.add_parser("collect_service_data", help="Collect all bmc data needed for service")
3275 parser_servData.add_argument('-d', '--devdebug', action='store_true', help=argparse.SUPPRESS)
3276 parser_servData.set_defaults(func=collectServiceData)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003277
Justin Thalere412dc22018-01-12 16:28:24 -06003278 #system quick health check
3279 parser_healthChk = subparsers.add_parser("health_check", help="Work with platform sensors")
3280 parser_healthChk.set_defaults(func=healthCheck)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003281
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003282 #work with bmc dumps
3283 parser_bmcdump = subparsers.add_parser("dump", help="Work with bmc dump files")
Justin Thalere412dc22018-01-12 16:28:24 -06003284 bmcDump_sub = parser_bmcdump.add_subparsers(title='subcommands', description='valid subcommands',help="sub-command help", dest='command')
Justin Thaler53bf2f12018-07-16 14:05:32 -05003285 bmcDump_sub.required = True
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003286 dump_Create = bmcDump_sub.add_parser('create', help="Create a bmc dump")
3287 dump_Create.set_defaults(func=bmcDumpCreate)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003288
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003289 dump_list = bmcDump_sub.add_parser('list', help="list all bmc dump files")
3290 dump_list.set_defaults(func=bmcDumpList)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003291
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003292 parserdumpdelete = bmcDump_sub.add_parser('delete', help="Delete bmc dump files")
3293 parserdumpdelete.add_argument("-n", "--dumpNum", nargs='*', type=int, help="The Dump entry to delete")
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003294 parserdumpdelete.set_defaults(func=bmcDumpDelete)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003295
Justin Thalere412dc22018-01-12 16:28:24 -06003296 bmcDumpDelsub = parserdumpdelete.add_subparsers(title='subcommands', description='valid subcommands',help="sub-command help", dest='command')
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003297 deleteAllDumps = bmcDumpDelsub.add_parser('all', help='Delete all bmc dump files')
3298 deleteAllDumps.set_defaults(func=bmcDumpDeleteAll)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003299
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003300 parser_dumpretrieve = bmcDump_sub.add_parser('retrieve', help='Retrieve a dump file')
3301 parser_dumpretrieve.add_argument("dumpNum", type=int, help="The Dump entry to delete")
3302 parser_dumpretrieve.add_argument("-s", "--dumpSaveLoc", help="The location to save the bmc dump file")
3303 parser_dumpretrieve.set_defaults(func=bmcDumpRetrieve)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003304
Justin Thaler22b1bb52018-03-15 13:31:32 -05003305 #bmc command for reseting the bmc
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003306 parser_bmc = subparsers.add_parser('bmc', help="Work with the bmc")
Justin Thalere412dc22018-01-12 16:28:24 -06003307 bmc_sub = parser_bmc.add_subparsers(title='subcommands', description='valid subcommands',help="sub-command help", dest='command')
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003308 parser_BMCReset = bmc_sub.add_parser('reset', help='Reset the bmc' )
3309 parser_BMCReset.add_argument('type', choices=['warm','cold'], help="Warm: Reboot the BMC, Cold: CLEAR config and reboot bmc")
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003310 parser_bmc.add_argument('info', action='store_true', help="Displays information about the BMC hardware, including device revision, firmware revision, IPMI version supported, manufacturer ID, and information on additional device support.")
3311 parser_bmc.set_defaults(func=bmc)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003312
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003313 #add alias to the bmc command
3314 parser_mc = subparsers.add_parser('mc', help="Work with the management controller")
Justin Thalere412dc22018-01-12 16:28:24 -06003315 mc_sub = parser_mc.add_subparsers(title='subcommands', description='valid subcommands',help="sub-command help", dest='command')
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003316 parser_MCReset = mc_sub.add_parser('reset', help='Reset the bmc' )
3317 parser_MCReset.add_argument('type', choices=['warm','cold'], help="Reboot the BMC")
3318 #parser_MCReset.add_argument('cold', action='store_true', help="Reboot the BMC and CLEAR the configuration")
3319 parser_mc.add_argument('info', action='store_true', help="Displays information about the BMC hardware, including device revision, firmware revision, IPMI version supported, manufacturer ID, and information on additional device support.")
Justin Thalere412dc22018-01-12 16:28:24 -06003320 parser_MCReset.set_defaults(func=bmcReset)
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003321 parser_mc.set_defaults(func=bmc)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003322
Justin Thalere412dc22018-01-12 16:28:24 -06003323 #gard clear
3324 parser_gc = subparsers.add_parser("gardclear", help="Used to clear gard records")
3325 parser_gc.set_defaults(func=gardClear)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003326
Justin Thalere412dc22018-01-12 16:28:24 -06003327 #firmware_flash
3328 parser_fw = subparsers.add_parser("firmware", help="Work with the system firmware")
3329 fwflash_subproc = parser_fw.add_subparsers(title='subcommands', description='valid firmware commands', help='sub-command help', dest='command')
Justin Thaler53bf2f12018-07-16 14:05:32 -05003330 fwflash_subproc.required = True
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003331
Justin Thalere412dc22018-01-12 16:28:24 -06003332 fwflash = fwflash_subproc.add_parser('flash', help="Flash the system firmware")
3333 fwflash.add_argument('type', choices=['bmc', 'pnor'], help="image type to flash")
3334 fwflash.add_argument('-f', '--fileloc', required=True, help="The absolute path to the firmware image")
3335 fwflash.set_defaults(func=fwFlash)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003336
Justin Thaler22b1bb52018-03-15 13:31:32 -05003337 fwActivate = fwflash_subproc.add_parser('activate', help="Activate existing image on the bmc")
Justin Thalere412dc22018-01-12 16:28:24 -06003338 fwActivate.add_argument('imageID', help="The image ID to activate from the firmware list. Ex: 63c95399")
3339 fwActivate.set_defaults(func=activateFWImage)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003340
Justin Thaler22b1bb52018-03-15 13:31:32 -05003341 fwActivateStatus = fwflash_subproc.add_parser('activation_status', help="Check Status of activations")
3342 fwActivateStatus.set_defaults(func=activateStatus)
3343
Justin Thaler3d71d402018-07-24 14:35:39 -05003344 fwList = fwflash_subproc.add_parser('list', help="List all of the installed firmware")
3345 fwList.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
3346 fwList.set_defaults(func=firmwareList)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003347
Justin Thaler3d71d402018-07-24 14:35:39 -05003348 fwprint = fwflash_subproc.add_parser('print', help="List all of the installed firmware")
3349 fwprint.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
3350 fwprint.set_defaults(func=firmwareList)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003351
Deepak Kodihalli22d4df02018-09-18 06:52:43 -05003352 #logging
3353 parser_logging = subparsers.add_parser("logging", help="logging controls")
3354 logging_sub = parser_logging.add_subparsers(title='subcommands', description='valid subcommands',help="sub-command help", dest='command')
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003355
Deepak Kodihalli22d4df02018-09-18 06:52:43 -05003356 #turn rest api logging on/off
3357 parser_rest_logging = logging_sub.add_parser("rest_api", help="turn rest api logging on/off")
3358 parser_rest_logging.add_argument('rest_logging', choices=['on', 'off'], help='The control option for rest logging: on, off')
3359 parser_rest_logging.set_defaults(func=restLogging)
Deepak Kodihalli02d53282018-09-18 06:53:31 -05003360
3361 #remote logging
3362 parser_remote_logging = logging_sub.add_parser("remote_logging", help="Remote logging (rsyslog) commands")
3363 parser_remote_logging.add_argument('remote_logging', choices=['view', 'disable'], help='Remote logging (rsyslog) commands')
3364 parser_remote_logging.set_defaults(func=remoteLogging)
3365
3366 #configure remote logging
3367 parser_remote_logging_config = logging_sub.add_parser("remote_logging_config", help="Configure remote logging (rsyslog)")
3368 parser_remote_logging_config.add_argument("-a", "--address", required=True, help="Set IP address of rsyslog server")
3369 parser_remote_logging_config.add_argument("-p", "--port", required=True, type=int, help="Set Port of rsyslog server")
3370 parser_remote_logging_config.set_defaults(func=remoteLoggingConfig)
Dhruvaraj Subhashchandran64e7f6f2018-10-02 03:42:14 -05003371
3372 #certificate management
3373 parser_cert = subparsers.add_parser("certificate", help="Certificate management")
3374 certMgmt_subproc = parser_cert.add_subparsers(title='subcommands', description='valid certificate commands', help='sub-command help', dest='command')
3375
3376 certUpdate = certMgmt_subproc.add_parser('update', help="Update the certificate")
3377 certUpdate.add_argument('type', choices=['server', 'client', 'authority'], help="certificate type to update")
3378 certUpdate.add_argument('service', choices=['https', 'ldap'], help="Service to update")
3379 certUpdate.add_argument('-f', '--fileloc', required=True, help="The absolute path to the certificate file")
3380 certUpdate.set_defaults(func=certificateUpdate)
3381
3382 certDelete = certMgmt_subproc.add_parser('delete', help="Delete the certificate")
3383 certDelete.add_argument('type', choices=['server', 'client', 'authority'], help="certificate type to delete")
3384 certDelete.add_argument('service', choices=['https', 'ldap'], help="Service to delete the certificate")
3385 certDelete.set_defaults(func=certificateDelete)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003386
Matt Spinler7d426c22018-09-24 14:42:07 -05003387 # local users
3388 parser_users = subparsers.add_parser("local_users", help="Work with local users")
3389 parser_users.add_argument('local_users', choices=['disableall','enableall', 'queryenabled'], help="Disable, enable or query local user accounts")
3390 parser_users.add_argument('-v', '--verbose', action='store_true', help='Verbose output')
3391 parser_users.set_defaults(func=localUsers)
3392
Ratan Gupta9166cd22018-10-01 18:09:40 +05303393 #LDAP
3394 parser_ldap = subparsers.add_parser("ldap", help="LDAP controls")
3395 ldap_sub = parser_ldap.add_subparsers(title='subcommands', description='valid subcommands',help="sub-command help", dest='command')
3396
3397 #configure and enable LDAP
3398 parser_ldap_config = ldap_sub.add_parser("enable", help="Configure and enables the LDAP")
3399 parser_ldap_config.add_argument("-a", "--uri", required=True, help="Set LDAP server URI")
3400 parser_ldap_config.add_argument("-B", "--bindDN", required=True, help="Set the bind DN of the LDAP server")
3401 parser_ldap_config.add_argument("-b", "--baseDN", required=True, help="Set the base DN of the LDAP server")
3402 parser_ldap_config.add_argument("-p", "--bindPassword", required=True, help="Set the bind password of the LDAP server")
3403 parser_ldap_config.add_argument("-S", "--scope", choices=['sub','one', 'base'],
3404 help='Specifies the search scope:subtree, one level or base object.')
3405 parser_ldap_config.add_argument("-t", "--serverType", choices=['ActiveDirectory','OpenLDAP'],
3406 help='Specifies the configured server is ActiveDirectory(AD) or OpenLdap')
3407 parser_ldap_config.set_defaults(func=enableLDAP)
3408
3409 # disable LDAP
3410 parser_disable_ldap = ldap_sub.add_parser("disable", help="disables the LDAP")
3411 parser_disable_ldap.set_defaults(func=disableLDAP)
Nagaraju Goruganti7d1fe172018-11-13 06:09:29 -06003412 # view-config
3413 parser_ldap_config = \
3414 ldap_sub.add_parser("view-config", help="prints out a list of all \
3415 LDAPS's configured properties")
3416 parser_ldap_config.set_defaults(func=viewLDAPConfig)
Ratan Gupta9166cd22018-10-01 18:09:40 +05303417
Ratan Guptafeee6372018-10-17 23:25:51 +05303418 #create group privilege mapping
3419 parser_ldap_mapper = ldap_sub.add_parser("privilege-mapper", help="LDAP group privilege controls")
3420 parser_ldap_mapper_sub = parser_ldap_mapper.add_subparsers(title='subcommands', description='valid subcommands',
3421 help="sub-command help", dest='command')
3422
3423 parser_ldap_mapper_create = parser_ldap_mapper_sub.add_parser("create", help="Create mapping of ldap group and privilege")
3424 parser_ldap_mapper_create.add_argument("-g","--groupName",required=True,help="Group Name")
3425 parser_ldap_mapper_create.add_argument("-p","--privilege",choices=['priv-admin','priv-user'],required=True,help="Privilege")
3426 parser_ldap_mapper_create.set_defaults(func=createPrivilegeMapping)
3427
3428 #list group privilege mapping
3429 parser_ldap_mapper_list = parser_ldap_mapper_sub.add_parser("list",help="List privilege mapping")
3430 parser_ldap_mapper_list.set_defaults(func=listPrivilegeMapping)
3431
3432 #delete group privilege mapping
3433 parser_ldap_mapper_delete = parser_ldap_mapper_sub.add_parser("delete",help="Delete privilege mapping")
3434 parser_ldap_mapper_delete.add_argument("-g","--groupName",required=True,help="Group Name")
3435 parser_ldap_mapper_delete.set_defaults(func=deletePrivilegeMapping)
3436
Marri Devender Rao2c2a5162018-11-05 08:57:11 -06003437 # set local user password
3438 parser_set_password = subparsers.add_parser("set_password",
3439 help="Set password of local user")
3440 parser_set_password.add_argument( "-p", "--password", required=True,
3441 help="Password of local user")
3442 parser_set_password.set_defaults(func=setPassword)
3443
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003444 # network
3445 parser_nw = subparsers.add_parser("network", help="network controls")
3446 nw_sub = parser_nw.add_subparsers(title='subcommands',
3447 description='valid subcommands',
3448 help="sub-command help",
3449 dest='command')
3450
3451 # enable DHCP
3452 parser_enable_dhcp = nw_sub.add_parser("enableDHCP",
3453 help="enables the DHCP on given "
3454 "Interface")
3455 parser_enable_dhcp.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003456 help="Name of the ethernet interface(it can"
3457 "be obtained by the "
3458 "command:network view-config)"
3459 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003460 parser_enable_dhcp.set_defaults(func=enableDHCP)
3461
3462 # disable DHCP
3463 parser_disable_dhcp = nw_sub.add_parser("disableDHCP",
3464 help="disables the DHCP on given "
3465 "Interface")
3466 parser_disable_dhcp.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003467 help="Name of the ethernet interface(it can"
3468 "be obtained by the "
3469 "command:network view-config)"
3470 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003471 parser_disable_dhcp.set_defaults(func=disableDHCP)
3472
3473 # get HostName
3474 parser_gethostname = nw_sub.add_parser("getHostName",
3475 help="prints out HostName")
3476 parser_gethostname.set_defaults(func=getHostname)
3477
3478 # set HostName
3479 parser_sethostname = nw_sub.add_parser("setHostName", help="sets HostName")
3480 parser_sethostname.add_argument("-H", "--HostName", required=True,
3481 help="A HostName for the BMC")
3482 parser_sethostname.set_defaults(func=setHostname)
3483
3484 # get domainname
3485 parser_getdomainname = nw_sub.add_parser("getDomainName",
3486 help="prints out DomainName of "
3487 "given Interface")
3488 parser_getdomainname.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003489 help="Name of the ethernet interface(it "
3490 "can be obtained by the "
3491 "command:network view-config)"
3492 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003493 parser_getdomainname.set_defaults(func=getDomainName)
3494
3495 # set domainname
3496 parser_setdomainname = nw_sub.add_parser("setDomainName",
3497 help="sets DomainName of given "
3498 "Interface")
3499 parser_setdomainname.add_argument("-D", "--DomainName", required=True,
3500 help="Ex: DomainName=Domain1,Domain2,...")
3501 parser_setdomainname.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003502 help="Name of the ethernet interface(it "
3503 "can be obtained by the "
3504 "command:network view-config)"
3505 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003506 parser_setdomainname.set_defaults(func=setDomainName)
3507
3508 # get MACAddress
3509 parser_getmacaddress = nw_sub.add_parser("getMACAddress",
3510 help="prints out MACAddress the "
3511 "given Interface")
3512 parser_getmacaddress.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003513 help="Name of the ethernet interface(it "
3514 "can be obtained by the "
3515 "command:network view-config)"
3516 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003517 parser_getmacaddress.set_defaults(func=getMACAddress)
3518
3519 # set MACAddress
3520 parser_setmacaddress = nw_sub.add_parser("setMACAddress",
3521 help="sets MACAddress")
3522 parser_setmacaddress.add_argument("-MA", "--MACAddress", required=True,
3523 help="A MACAddress for the given "
3524 "Interface")
3525 parser_setmacaddress.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003526 help="Name of the ethernet interface(it can"
3527 "be obtained by the "
3528 "command:network view-config)"
3529 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003530 parser_setmacaddress.set_defaults(func=setMACAddress)
3531
3532 # get DefaultGW
3533 parser_getdefaultgw = nw_sub.add_parser("getDefaultGW",
3534 help="prints out DefaultGateway "
3535 "the BMC")
3536 parser_getdefaultgw.set_defaults(func=getDefaultGateway)
3537
3538 # set DefaultGW
3539 parser_setdefaultgw = nw_sub.add_parser("setDefaultGW",
3540 help="sets DefaultGW")
3541 parser_setdefaultgw.add_argument("-GW", "--DefaultGW", required=True,
3542 help="A DefaultGateway for the BMC")
3543 parser_setdefaultgw.set_defaults(func=setDefaultGateway)
3544
3545 # view network Config
3546 parser_ldap_config = nw_sub.add_parser("view-config", help="prints out a "
3547 "list of all network's configured "
3548 "properties")
3549 parser_ldap_config.set_defaults(func=viewNWConfig)
3550
3551 # get DNS
3552 parser_getDNS = nw_sub.add_parser("getDNS",
3553 help="prints out DNS servers on the "
3554 "given interface")
3555 parser_getDNS.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003556 help="Name of the ethernet interface(it can"
3557 "be obtained by the "
3558 "command:network view-config)"
3559 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003560 parser_getDNS.set_defaults(func=getDNS)
3561
3562 # set DNS
3563 parser_setDNS = nw_sub.add_parser("setDNS",
3564 help="sets DNS servers on the given "
3565 "interface")
3566 parser_setDNS.add_argument("-d", "--DNSServers", required=True,
3567 help="Ex: DNSSERVERS=DNS1,DNS2,...")
3568 parser_setDNS.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003569 help="Name of the ethernet interface(it can"
3570 "be obtained by the "
3571 "command:network view-config)"
3572 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003573 parser_setDNS.set_defaults(func=setDNS)
3574
3575 # get NTP
3576 parser_getNTP = nw_sub.add_parser("getNTP",
3577 help="prints out NTP servers on the "
3578 "given interface")
3579 parser_getNTP.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003580 help="Name of the ethernet interface(it can"
3581 "be obtained by the "
3582 "command:network view-config)"
3583 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003584 parser_getNTP.set_defaults(func=getNTP)
3585
3586 # set NTP
3587 parser_setNTP = nw_sub.add_parser("setNTP",
3588 help="sets NTP servers on the given "
3589 "interface")
3590 parser_setNTP.add_argument("-N", "--NTPServers", required=True,
3591 help="Ex: NTPSERVERS=NTP1,NTP2,...")
3592 parser_setNTP.add_argument("-I", "--Interface", required=True,
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003593 help="Name of the ethernet interface(it can"
3594 "be obtained by the "
3595 "command:network view-config)"
3596 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
Nagaraju Goruganti9908bcf2018-11-14 22:07:25 -06003597 parser_setNTP.set_defaults(func=setNTP)
3598
Nagaraju Goruganti97a20602018-11-16 03:06:08 -06003599 # configure IP
3600 parser_ip_config = nw_sub.add_parser("addIP", help="Sets IP address to"
3601 "given interface")
3602 parser_ip_config.add_argument("-a", "--address", required=True,
3603 help="IP address of given interface")
3604 parser_ip_config.add_argument("-gw", "--gateway", required=False, default='',
3605 help="The gateway for given interface")
3606 parser_ip_config.add_argument("-l", "--prefixLength", required=True,
3607 help="The prefixLength of IP address")
3608 parser_ip_config.add_argument("-p", "--type", choices=['ipv4', 'ipv6'],
3609 help="The protocol type of the given"
3610 "IP address")
3611 parser_ip_config.add_argument("-I", "--Interface", required=True,
3612 help="Name of the ethernet interface(it can"
3613 "be obtained by the "
3614 "command:network view-config)"
3615 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
3616 parser_ip_config.set_defaults(func=addIP)
3617
3618 # getIP
3619 parser_getIP = nw_sub.add_parser("getIP", help="prints out IP address"
3620 "of given interface")
3621 parser_getIP.add_argument("-I", "--Interface", required=True,
3622 help="Name of the ethernet interface(it can"
3623 "be obtained by the command:network view-config)"
3624 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
3625 parser_getIP.set_defaults(func=getIP)
3626
3627 # rmIP
3628 parser_rmIP = nw_sub.add_parser("rmIP", help="deletes IP address"
3629 "of given interface")
3630 parser_rmIP.add_argument("-a", "--address", required=True,
3631 help="IP address to remove form given Interface")
3632 parser_rmIP.add_argument("-I", "--Interface", required=True,
3633 help="Name of the ethernet interface(it can"
3634 "be obtained by the command:network view-config)"
3635 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
3636 parser_rmIP.set_defaults(func=deleteIP)
3637
Nagaraju Gorugantif21d43c2018-11-19 10:47:19 -06003638 # add VLAN
3639 parser_create_vlan = nw_sub.add_parser("addVLAN", help="enables VLAN "
3640 "on given interface with given "
3641 "VLAN Identifier")
3642 parser_create_vlan.add_argument("-I", "--Interface", required=True,
3643 choices=['eth0', 'eth1'],
3644 help="Name of the ethernet interface")
3645 parser_create_vlan.add_argument("-n", "--Identifier", required=True,
3646 help="VLAN Identifier")
3647 parser_create_vlan.set_defaults(func=addVLAN)
3648
3649 # delete VLAN
3650 parser_delete_vlan = nw_sub.add_parser("deleteVLAN", help="disables VLAN "
3651 "on given interface with given "
3652 "VLAN Identifier")
3653 parser_delete_vlan.add_argument("-I", "--Interface", required=True,
3654 help="Name of the ethernet interface(it can"
3655 "be obtained by the "
3656 "command:network view-config)"
3657 "Ex: eth0 or eth1 or VLAN(VLAN=eth0_50 etc)")
3658 parser_delete_vlan.set_defaults(func=deleteVLAN)
3659
3660 # viewDHCPConfig
3661 parser_viewDHCPConfig = nw_sub.add_parser("viewDHCPConfig",
3662 help="Shows DHCP configured "
3663 "Properties")
3664 parser_viewDHCPConfig.set_defaults(func=viewDHCPConfig)
3665
3666 # configureDHCP
3667 parser_configDHCP = nw_sub.add_parser("configureDHCP",
3668 help="Configures/updates DHCP "
3669 "Properties")
3670 parser_configDHCP.add_argument("-d", "--DNSEnabled", type=str2bool,
3671 required=True, help="Sets DNSEnabled property")
3672 parser_configDHCP.add_argument("-n", "--HostNameEnabled", type=str2bool,
3673 required=True,
3674 help="Sets HostNameEnabled property")
3675 parser_configDHCP.add_argument("-t", "--NTPEnabled", type=str2bool,
3676 required=True,
3677 help="Sets NTPEnabled property")
3678 parser_configDHCP.add_argument("-s", "--SendHostNameEnabled", type=str2bool,
3679 required=True,
3680 help="Sets SendHostNameEnabled property")
3681 parser_configDHCP.set_defaults(func=configureDHCP)
3682
3683 # network factory reset
3684 parser_nw_reset = nw_sub.add_parser("nwReset",
3685 help="Resets networks setting to "
3686 "factory defaults. "
3687 "note:Reset settings will be applied "
3688 "after BMC reboot")
3689 parser_nw_reset.set_defaults(func=nwReset)
3690
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003691 return parser
3692
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003693def main(argv=None):
Justin Thalere412dc22018-01-12 16:28:24 -06003694 """
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003695 main function for running the command line utility as a sub application
3696 """
3697 global toolVersion
Justin Thaler7df51762018-11-08 23:02:56 -06003698 toolVersion = "1.10"
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003699 parser = createCommandParser()
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003700 args = parser.parse_args(argv)
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003701
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003702 totTimeStart = int(round(time.time()*1000))
3703
3704 if(sys.version_info < (3,0)):
3705 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
3706 if sys.version_info >= (3,0):
3707 requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
Justin Thalere412dc22018-01-12 16:28:24 -06003708 if (args.version):
Justin Thaler22b1bb52018-03-15 13:31:32 -05003709 print("Version: "+ toolVersion)
Justin Thalere412dc22018-01-12 16:28:24 -06003710 sys.exit(0)
3711 if (hasattr(args, 'fileloc') and args.fileloc is not None and 'print' in args.command):
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003712 mysess = None
Justin Thalere412dc22018-01-12 16:28:24 -06003713 print(selPrint('N/A', args, mysess))
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003714 else:
Justin Thalere412dc22018-01-12 16:28:24 -06003715 if(hasattr(args, 'host') and hasattr(args,'user')):
3716 if (args.askpw):
3717 pw = getpass.getpass()
3718 elif(args.PW is not None):
3719 pw = args.PW
3720 else:
3721 print("You must specify a password")
3722 sys.exit()
3723 logintimeStart = int(round(time.time()*1000))
3724 mysess = login(args.host, args.user, pw, args.json)
Justin Thalera9415b42018-05-25 19:40:13 -05003725 if(sys.version_info < (3,0)):
3726 if isinstance(mysess, basestring):
3727 print(mysess)
3728 sys.exit(1)
3729 elif sys.version_info >= (3,0):
3730 if isinstance(mysess, str):
3731 print(mysess)
3732 sys.exit(1)
Justin Thalere412dc22018-01-12 16:28:24 -06003733 logintimeStop = int(round(time.time()*1000))
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003734
3735 commandTimeStart = int(round(time.time()*1000))
Justin Thalere412dc22018-01-12 16:28:24 -06003736 output = args.func(args.host, args, mysess)
3737 commandTimeStop = int(round(time.time()*1000))
3738 print(output)
3739 if (mysess is not None):
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003740 logout(args.host, args.user, pw, mysess, args.json)
3741 if(args.procTime):
Justin Thalere412dc22018-01-12 16:28:24 -06003742 print("Total time: " + str(int(round(time.time()*1000))- totTimeStart))
3743 print("loginTime: " + str(logintimeStop - logintimeStart))
3744 print("command Time: " + str(commandTimeStop - commandTimeStart))
3745 else:
3746 print("usage: openbmctool.py [-h] -H HOST -U USER [-A | -P PW] [-j]\n" +
3747 "\t[-t POLICYTABLELOC] [-V]\n" +
Deepak Kodihalli22d4df02018-09-18 06:52:43 -05003748 "\t{fru,sensors,sel,chassis,collect_service_data, \
3749 health_check,dump,bmc,mc,gardclear,firmware,logging}\n" +
Justin Thalere412dc22018-01-12 16:28:24 -06003750 "\t...\n" +
3751 "openbmctool.py: error: the following arguments are required: -H/--host, -U/--user")
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003752 sys.exit()
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003753
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003754if __name__ == '__main__':
Justin Thalere412dc22018-01-12 16:28:24 -06003755 """
3756 main function when called from the command line
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003757
3758 """
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003759 import sys
Nagaraju Gorugantic1a00af2018-11-07 00:52:11 -06003760
Justin Thalerf9aee3e2017-12-05 12:11:09 -06003761 isTTY = sys.stdout.isatty()
3762 assert sys.version_info >= (2,7)
3763 main()