Debian Codegraph @

redfishtoollib/Systems.py

raw symbols SCIP
1 # Copyright Notice:
2 # Copyright 2016 DMTF. All rights reserved.
3 # License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfishtool/blob/master/LICENSE.md
4
5 # redfishtool: Systems.py
6 #
7 # contains Systems related subCommands and access functions
8 #
9 # Class RfSystemsMain
10 # - functions init, displayUsage, displayHelp, displayOperations,
11 # - runOperation - Systems command table, dispatch of operation eg get, reset
12 # - SystemsMain - called from redfishMain, enforce legal option combinations,
13 # and call runOperation to run System operation (sub-sub-command)
14 #
15 # Class RfSystemsOperations
16 # All of the Systems sub-command operations eg: Systems reset, setIndicatorLed, etc
17 # - hello - test cmd
18 # - getCollection - return the Systems collection
19 # - get - get a member of a collection -or property of the member
20 # - list - show of list of collection members and key idetifying properties
21 # (Id, AssetTag, UriPath)
22 # - patch - raw subcommand to patch a System Member, with etag support
23 # - reset --reset a system instance
24 # - setAssetTag -- patches the assetTag of system instance w/ etag support
25 # - setIndicatorLed --sets id LED to a specified value w/ etag support
26 # - setBootOverride -set boot override enable, and target to valid values
27 # with proper checking for valid values...
28 # - getProcessors - get Processors collection, processor instance, or all
29 # - getInventory - get inventory of Processors, Memory, Fans, Power Supplies
30 # - getEnetInterfaces - get Ethernet collection, instance, all
31 # - getSimpleStorage - get SimpleStorage collection, instance, all
32 # - getLogService - get LogService collection, instance, all
33 # - clearLog -- clears a specified log (not implemented yet)
34 # - examples --prints some example apis
35 #
36 from .redfishtoolTransport import RfTransport
37 import requests
38 import json
39 import getopt
40 import re
41 import sys
42 from .ServiceRoot import RfServiceRoot
43 from urllib.parse import urljoin
44
45 class RfSystemsMain():
46 def __init__(self):
47 # operation string and remaining args
48 self.operation=None
49 self.args=None
50 self.argnum=0
51 self.nonIdCommands=None
52
53 def displayUsage(self,rft):
54 if(rft.quiet): return(0)
55 print(" Usage:")
56 print(" {} [OPTNS] Systems <operation> [<args>] -- perform <operation> on the system specified ".format(rft.program))
57
58 def displayHelp(self,rft):
59 self.displayUsage(rft)
60 self.displayOperations(rft)
61 print("")
62
63 def displayOperations(self,rft):
64 print(" <operations>:")
65 print(" [collection] -- get the main Systems collection. (Default operation if no member specified)")
66 print(" [get] -- get the computerSystem object. (Default operation if collection member specified)")
67 print(" list -- list information about the Systems collection members(\"Id\", URI, and AssetTag)")
68 print(" patch {A: B,C: D,...} -- patch the json-formatted {prop: value...} data to the object")
69 print(" reset <resetType> -- reset a system. <resetType>= On, GracefulShutdown, GracefulRestart, ")
70 print(" ForceRestart, ForceOff, ForceOn, Nmi, PushPowerButton, PowerCycle")
71 print(" setAssetTag <assetTag> -- set the system's asset tag ")
72 print(" setIndicatorLed <state> -- set the indicator LED. <state>=redfish defined values: Off, Lit, Blinking")
73 print(" setBootOverride <enabledVal> <targetVal> -- set Boot Override properties. <enabledVal>=Disabled|Once|Continuous")
74 print(" -- <targetVal> =None|Pxe|Floppy|Cd|Usb|Hdd|BiosSetup|Utilities|Diags|UefiTarget|")
75 print(" Processors [list] -- get the \"Processors\" collection, or list \"id\" and URI of members.")
76 print(" Processors [IDOPTN] -- get the member specified by IDOPTN: -i<id>, -m<prop>:<val>, -l<link>, -a #all")
77 print(" Inventory [list] -- get the \"Inventory\" collection, or list \"id\" and URI of members.")
78 print("")
79 print(" EthernetInterfaces [list] -- get the \"EthernetInterfaces\" collection, or list \"id\" and URI of members.")
80 print(" EthernetInterfaces [IDOPTN]-- get the member specified by IDOPTN: -i<id>, -m<prop>:<val>, -l<link>, -a #all")
81 print("")
82 print(" SimpleStorage [list] -- get the ComputerSystem \"SimpleStorage\" collection, or list \"id\" and URI of members.")
83 print(" SimpleStorage [IDOPTN] -- get the member specified by IDOPTN: -i<id>, -m<prop>:<val>, -l<link>, -a #all")
84 print("")
85 print(" Logs [list] -- get the ComputerSystem \"LogServices\" collection , or list \"id\" and URI of members.")
86 print(" Logs [IDOPTN] -- get the member specified by IDOPTN: -i<id>, -m<prop>:<val>, -l<link>, -a #all")
87 print(" clearLog <id> -- clears the log defined by <id>")
88 print(" examples -- example commands with syntax")
89 print(" hello -- Systems hello -- debug command")
90 return(0)
91
92
93
94 def runOperation(self,rft):
95 # instantiate SystemsOperations class
96 op=RfSystemsOperations()
97
98 # dispatch table for each subcommand: "cmdName": cmdClass.cmdFunction"
99 operationTable = {
100 "collection": op.getCollection,
101 "get": op.get,
102 "list": op.list,
103 "patch": op.patch,
104 "reset": op.reset,
105 "setAssetTag": op.setAssetTag,
106 "setIndicatorLed": op.setIndicatorLed,
107 "setBootOverride": op.setBootOverride,
108 "Processors": op.getProcessors,
109 "Inventory": op.getInventory,
110 "EthernetInterfaces": op.getEnetInterfaces,
111 "SimpleStorage": op.getSimpleStorage,
112 "Logs": op.getLogService,
113 "-clearLog": op.clearLog,
114 "hello": op.hello,
115 "examples": op.examples
116 }
117
118 rft.printVerbose(5,"Systems:runOperation: operation: {}".format(self.operation))
119 rft.printVerbose(5,"Systems:runOperation: args: {}".format(self.args))
120
121 if self.operation in operationTable:
122 rft.printVerbose(5,"Systems:runOperation: found Oper: {} in table. executing".format(rft.subcommand))
123 rc,r,j,d=operationTable[self.operation](self, op, rft, cmdTop=True)
124 return(rc,r,j,d)
125
126 else: # invalid operation
127 rft.printErr("Systems: Invalid operation: {}".format(self.operation))
128 return(2,None,False,None)
129
130
131
132 def SystemsMain(self,rft,cmdTop=False):
133 rft.printVerbose(4,"SystemsMain: subcommand: {}".format(rft.subcommand))
134
135 if( rft.help ):
136 self.displayHelp(rft)
137 return(0,None,False,None)
138
139 # we will validate usage of -P and -a in action processing
140 # actually, if a non 'get' action is specified, -P and -a are just ignored :)
141
142 args=rft.subcommandArgv[0:]
143
144 #if no args, then if no member Id was specified (with -I|-M|-1|-F) then assume it is a "collection" operation
145 # if a -IM1F was specified, then assume it is a "get" operation for that member
146 if( len(args) < 2 ):
147 if( rft.IdOptnCount==0 ):
148 self.operation="collection"
149 else:
150 self.operation="get"
151 self.args= None
152 else:
153 self.operation=args[1]
154 self.args = args[1:] # now args points to the 1st argument
155 self.argnum =len(self.args)
156
157 rft.printVerbose(5,"Systems: operation={}, args={}".format(self.operation,self.args))
158
159 # check if the command requires a collection member target -I|-M|-L|-1|-F eg sysIdoptn
160 nonIdCommands = ["collection", "list", "examples", "hello"]
161 if( ( not self.operation in nonIdCommands ) and (rft.IdOptnCount==0) ):
162 # default to --One if no Id option specified
163 rft.oneOptn = True
164 rft.IdOptnCount += 1
165
166 # now execute the operation.
167 rc,r,j,d = self.runOperation(rft)
168
169 if(rc !=0 ):
170 rft.printVerbose(5,"Systems: operation returned with error: rc={}".format(rc))
171 return(rc,r,False,None)
172
173 #else, if here, the subcommand executed without error. Return with 0 exit code
174 rft.printVerbose(5,"Systems: operation exited OK")
175 return(rc,r,j,d)
176
177
178 #
179 # contains operations related to the Systems subCommand
180 #
181 class RfSystemsOperations():
182 def __init__(self):
183 self.systemsPath=None
184 self.systemsCollectionDict=None
185
186
187 def hello(self,sc,op,rft,cmdTop=False):
188 rft.printVerbose(4,"in hello")
189 rft.printVerbose(4," subcmd:{}, operation:{}, args:{}".format(rft.subcommand,sc.operation,sc.args))
190 print("hello world from Systems")
191 return(0,None,False,None)
192
193 def getCollection(self,sc,op,rft,cmdTop=False, prop=None):
194 rft.printVerbose(4,"{}:{}: in getCollection".format(rft.subcommand,sc.operation))
195
196 # 1st get serviceRoot
197 svcRoot=RfServiceRoot()
198 rc,r,j,d = svcRoot.getServiceRoot(rft)
199 if( rc != 0 ):
200 rft.printErr("getCollection: Error getting service root, aborting")
201 return(rc,r,False,None)
202
203 # get the link to the Systems collection
204 # need to test we got good data
205 if (("Systems" in d) and ("@odata.id" in d["Systems"])):
206 systemsLink=d["Systems"]["@odata.id"]
207 else:
208
209 rft.printErr("Error: service root does not have a Systems link")
210 return(4)
211
212 rft.printVerbose(4,"Systems:getCollection: link is: {}".format(systemsLink))
213
214
215 # if a -a option was entered with "Systems" or "Systems collection" operation,
216 # then return all members of the Systems collection expanded
217 if((cmdTop is True) and (rft.allOptn is True) ):
218 collName="Systems"
219 rft.printVerbose(4,"Expand Systems collection to return ALL Systems collection members fully expanded in response")
220 rc,r,j,d=rft.getAllCollectionMembers(rft, r.url, relPath=systemsLink)
221 if(rc==0):
222 rft.printVerbose(1," Get ALL {} Collection Members".format(collName,skip1=True, printV12=cmdTop))
223
224 # otherwise, just return the collection
225 # now read the /Systems collection
226 # use the returned url as the base url to read the systems collection
227 else:
228 if cmdTop is True: prop=rft.prop
229 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=systemsLink, prop=prop)
230 if(rc==0):
231 rft.printVerbose(1," Systems Collection:",skip1=True, printV12=cmdTop)
232
233 return(rc,r,j,d)
234
235
236 def get(self,sc,op,rft, cmdTop=False, prop=None):
237 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
238
239 # getCollection
240 rc,r,j,d=op.getCollection(sc,op, rft)
241 if( rc != 0): return(rc,r,False,None)
242 collUrl=r.url
243
244 # search collection to find path to system
245 sysPath,rc,r,j,d=rft.getPathBy(rft, r, d)
246 if( rc !=0 ): #if a path was not found, its an error
247 return(rc,r,j,d)
248
249 rft.printVerbose(4,"SystemsOperations:get: got a path, now get entries")
250
251 if cmdTop is True: prop=rft.prop
252
253 #if here, rc=0
254 #if sysPath returned a response but we need to extract the property do it here
255 if( (r is not None) and (prop is not None) ):
256 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
257
258 # otherwise, we need to do a GET to get the system, if -P show property, else show full response
259 elif( r is None ):
260 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=sysPath, prop=prop)
261
262 if(rc==0): rft.printVerbose(1," Systems Resource:",skip1=True, printV12=cmdTop)
263 return(rc,r,j,d)
264
265
266 def list(self,sc,op,rft, cmdTop=False, prop=None):
267 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
268
269 # getCollection
270 collName="Systems"
271 rc,r,j,d=op.getCollection(sc,op, rft)
272 if( rc != 0): return(rc,r,False,None)
273 #loop through the members and create the list sub-operation response
274 rc,r,j,d=rft.listCollection(rft, r, d, prop="AssetTag")
275 if(rc==0):
276 rft.printVerbose(1," list {} Collection member info: Id, URI, AssetTag".format(collName,skip1=True, printV12=cmdTop))
277 return(rc,r,j,d)
278
279
280 def iterate_op(self, run_single, sc, op, rft, cmdTop=False, prop=None):
281 # Wrapper method to handle issuing commands to a single system or to all systems in the collection
282 if rft.allOptn:
283 # Issue command to all systems in collection
284
285 # get the list of systems
286 rc, r, j, d = op.list(sc, op, rft, cmdTop=cmdTop, prop=prop)
287 if rc != 0 or not j or d is None or not isinstance(d, dict) or 'Members' not in d:
288 rft.printErr("Unable to get list of Systems; return code = {}, list data = {}".format(rc, d))
289 return rc, r, j, d
290
291 # save existing rft options
292 saved_allOptn = rft.allOptn
293 saved_Link = rft.Link
294 saved_gotIdOptn = rft.gotIdOptn
295 saved_IdOptnCount = rft.IdOptnCount
296
297 # set rft options to process a single item
298 rft.allOptn = False
299 rft.gotIdOptn = True
300 rft.IdOptnCount = 1
301
302 # iterate through systems and run operation on each based on the link (@odata.id value)
303 members = d.get('Members')
304 rc, r, j, d = 8, None, False, None
305 for member in members:
306 if '@odata.id' in member:
307 link = member.get('@odata.id')
308 # set rft.Link to point to the target system
309 rft.Link = link
310 # perform the operation
311 rc, r, j, d = run_single(sc, op, rft, cmdTop=cmdTop, prop=prop)
312 else:
313 rft.printErr("No '@odata.id' found in system member: {}".format(member))
314
315 # restore existing rft options
316 rft.allOptn = saved_allOptn
317 rft.Link = saved_Link
318 rft.gotIdOptn = saved_gotIdOptn
319 rft.IdOptnCount = saved_IdOptnCount
320 return rc, r, j, d
321 else:
322 # Issue command to single specified system
323 return run_single(sc, op, rft, cmdTop=cmdTop, prop=prop)
324
325
326 def patch_single(self,sc,op,rft,cmdTop=False, prop=None, patchData=None, r=None):
327 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
328 # verify we have got an argument which is the patch structure
329 # its in form '{ "AssetTag": <val>, "IndicatorLed": <val> }'
330 ##print("patchData: {}".format(patchData))
331 if( len( sc.args) == 2):
332 ##print("data:{}".format(sc.args[1]))
333 try:
334 patchData=json.loads(sc.args[1])
335 except ValueError:
336 rft.printErr("Patch: invalid Json input data:{}".format(sc.args[1]))
337 return(5,None,False,None)
338 ##print("patchData: {}".format(patchData))
339 else:
340 rft.printErr("Patch: error: invalid argument format")
341 rft.printErr(" : args={}".format(sc.args))
342 rft.printErr(" : expect: Systems patch \"{ <prop>: <value> }\"")
343 return(4,None,False,None)
344
345 # read the system resource
346 # this is used by the generic rft.patchResource() function to see if there is an etag in the response
347 # if an etag is in response hdr, then we must include the etag on the patch, so this get is required
348 # note: the format of etag header for redfish is: ETag: W/"<string>" or "<string"
349 rc,r,j,d=op.get(sc,op,rft)
350 if( rc != 0):
351 return(rc,r,False,None)
352
353 # now call the generic patch function to send the patch
354 rc,r,j,d=rft.patchResource(rft, r, patchData)
355
356 if(rc==0): rft.printVerbose(1," Systems Patch:",skip1=True, printV12=cmdTop)
357 return(rc,r,j,d)
358
359
360 def patch(self, sc, op, rft, cmdTop=False, prop=None):
361 return op.iterate_op(op.patch_single, sc, op, rft, cmdTop=cmdTop, prop=prop)
362
363
364 def reset_single(self,sc,op,rft,cmdTop=False, prop=None):
365 # this operation has argument syntaxes below:
366 # ...reset <resetType>
367 # where <resetType> is a subset of Redfish defined redfish resetType values
368 # and will be validated against the allowable values read from the remote service
369 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
370
371 # get the resetType from args
372 validResetTypes=["On","ForceOff","GracefulShutdown","ForceRestart","Nmi","GracefulRestart",
373 "ForceOn","PushPowerButton","PowerCycle"]
374 if(len(sc.args) < 2 ):
375 rft.printErr("Error, no resetType value specified")
376 return(8,None,False,None)
377
378 resetType=sc.args[1]
379 if not resetType in validResetTypes:
380 rft.printErr("Error, Invalid <resetType> value specified: {}".format(resetType))
381 return(8,None,False,None)
382
383 #now read remote service to find out if specified resetType is one of the allowable values for this rhost
384 rc,r,j,d=op.get(sc,op,rft,prop="Actions")
385 if(rc != 0):
386 print("Error, cant read Actions properties from remote service")
387 return(8,None,False,None)
388
389 if( (j is True) and ("Actions" in d) and ("#ComputerSystem.Reset" in d["Actions"])):
390 resetProps=d["Actions"]["#ComputerSystem.Reset"]
391 if( "[email protected]" in resetProps ):
392 supportedResetTypes=resetProps["[email protected]"]
393 if not resetType in supportedResetTypes:
394 rft.printErr("Error, the resetType specified is not supported by the remote service (via @Redfish.AllowableValues)")
395 return(8,None,False,None)
396 elif "@Redfish.ActionInfo" in resetProps:
397 action_info_path = resetProps["@Redfish.ActionInfo"]
398 supportedResetTypes = rft.getActionInfoAllowableValues(rft, r, action_info_path, "ResetType")
399 if supportedResetTypes is not None and resetType not in supportedResetTypes:
400 rft.printErr("Error, the resetType specified is not supported by the remote service (via @Redfish.ActionInfo)")
401 return(8,None,False,None)
402 else: # rhost didn't return any AllowableValues, but it isn't required, so allow the action
403 rft.printVerbose(2, "The remote service does not have a [email protected] or @Redfish.ActionInfo prop")
404 else:
405 rft.printErr("Error, the remote service does not have an Actions: ComputerSystem.Reset property")
406 return(8,None,False,None)
407
408 # now get the target URI from the remote host
409 if( not "target" in resetProps ):
410 rft.printErr("Error, the remote service doesnt have a Reset Target property (the reset path)")
411 return(8,None,False,None)
412 resetPath=resetProps["target"]
413
414 resetData={"ResetType": resetType }
415
416 #since we already did a get, we have the path and can just execute the post directly.
417 #output the post data in json to send over the network
418 reqPostData=json.dumps(resetData)
419 # send post to rhost. Use the resetPath as the relative path
420 rft.printVerbose(1, 'Posting reset command to target {}'.format(resetPath))
421 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'POST', r.url, relPath=resetPath,
422 reqData=reqPostData)
423
424 if(rc==0):
425 rft.printVerbose(1," Systems reset: ", resetType, skip1=True, printV12=cmdTop)
426 resetd=None
427 return(rc,r,False,resetd)
428 else: return(rc,r,False,None)
429
430
431 def reset(self, sc, op, rft, cmdTop=False, prop=None):
432 return op.iterate_op(op.reset_single, sc, op, rft, cmdTop=cmdTop, prop=prop)
433
434
435 def setAssetTag_single(self,sc,op,rft,cmdTop=False, prop=None):
436 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
437
438 propName="AssetTag"
439
440 # get the asset tag from args
441 if(len(sc.args) < 2 ):
442 rft.printErr("Error, no assetTag value specified")
443 rft.printErr("Syntax: {} [options] Systems setAssetTag \"string\" ".format(rft.program))
444 return(8,None,False,None)
445 assetTag=sc.args[1]
446 patchData={propName: assetTag}
447
448 # get the resource to verify it includes AssetTag,
449 # the response will also be used by Patch() to check for etag
450 rc,r,j,d=op.get(sc,op,rft)
451 if( rc != 0): return(rc,r,False,None)
452 if( not propName in d ):
453 rft.printErr("System resource does not have a {} property.".format(propName))
454 return(8,r,False,None)
455
456 rc,r,j,d=rft.patchResource(rft, r, patchData)
457 if(rc==0):
458 rft.printVerbose(1," Systems setAssetTag:",skip1=True, printV12=cmdTop)
459 assetTag={propName: d[propName]}
460 return(rc,r,j,assetTag)
461 else: return(rc,r,False,None)
462
463
464 def setAssetTag(self, sc, op, rft, cmdTop=False, prop=None):
465 return op.iterate_op(op.setAssetTag_single, sc, op, rft, cmdTop=cmdTop, prop=prop)
466
467
468 def setIndicatorLed_single(self,sc,op,rft,cmdTop=False, prop=None):
469 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
470
471 propName="IndicatorLED"
472
473 # get the asset tag from args
474 validLedStates=["Lit","Blinking","Off"]
475 if(len(sc.args) < 2 ):
476 rft.printErr("Error, no ledState value specified")
477 rft.printErr("Syntax: {} [options] Systems setIndicatorLed <Lit|Off|Blinking>".format(rft.program))
478 return(8,None,False,None)
479 targLedState=sc.args[1]
480 if not targLedState in validLedStates:
481 rft.printErr("Error, invalid LED state specified")
482 return(8,None,False,None)
483 patchData={propName: targLedState}
484
485 # get the resource to verify it includes IndicatorLED,
486 # the response will also be used by Patch() to check for etag
487 rc,r,j,d=op.get(sc,op,rft)
488 if( rc != 0): return(rc,r,False,None)
489 if( not propName in d ):
490 rft.printErr("System resource does not have a {} property.".format(propName))
491 return(8,r,False,None)
492
493 #ststststst rc,r,j,d=op.patch(sc,op, rft, patchData=patchData, r=r)
494 rc,r,j,d=rft.patchResource(rft, r, patchData)
495 if(rc==0):
496 rft.printVerbose(1," Systems setIndicatorLed:",skip1=True, printV12=cmdTop)
497 ledState={"IndicatorLED": d["IndicatorLED"]}
498 return(rc,r,j,ledState)
499 else: return(rc,r,False,None)
500
501
502 def setIndicatorLed(self, sc, op, rft, cmdTop=False, prop=None):
503 return op.iterate_op(op.setIndicatorLed_single, sc, op, rft, cmdTop=cmdTop, prop=prop)
504
505
506 def setBootOverride_single(self,sc,op,rft,cmdTop=False, prop=None):
507 # this operation has argument syntaxes below:
508 # ...setBootOverride <enabledVal> [<targetVal>]
509 # where <targetVal> is not required if enabledVal==Disabled
510 # ...setBootOverride Once <targetVal>
511 # ...setBootOverride Continuous <targetVal>
512 # ...setBootOverride Disabled
513 # where TargetValue is subset of Redfish defined targets supported by rhost
514 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
515
516 # get the next boot value from args
517 validTargetVals=("None","Pxe","Floppy","Cd","Usb","Hdd",
518 "BiosSetup","Utilities","Diags","UefiTarget")
519 validEnabledVals=("Once","Disabled","Continuous")
520 if(len(sc.args) < 2 ):
521 rft.printErr("Error, no bootSourceOverrideEnabled value specified")
522 rft.printErr("Syntax: {} [options] Systems setBootOverride <enableVal> [<targetVal>]".format(rft.program))
523 rft.printErr(" <enableVal>=Disabled|Once|Continuous, <targetVal>=None,Pxe,BiosSetup...")
524 return(8,None,False,None)
525
526 enabledVal=sc.args[1]
527 if not enabledVal in validEnabledVals:
528 rft.printErr("Error, Invalid <Enabled> value specified: {}".format(enabledVal))
529 rft.printErr("Syntax: {} [options] Systems setBootOverride <enableVal> [<targetVal>]".format(rft.program))
530 rft.printErr(" <enableVal>=Disabled|Once|Continuous, <targetVal>=None,Pxe,BiosSetup...")
531 return(8,None,False,None)
532
533 #now read target,
534 # we will need to check that the properteis we are patching are there, and chk for etag hdr
535 # and to see if the value specified is one of the allowable values for this rhost
536 rc,r,j,d=op.get(sc,op,rft,prop="Boot")
537 if(rc != 0):
538 print("Error, cant read boot properties from remote service")
539 return(8,None,False,None)
540
541 # verify that they have a BootSourceOverrideEnabled prop
542 bootRes=d["Boot"]
543 if( not "BootSourceOverrideEnabled" in bootRes ):
544 rft.printErr("Error, the service does not have BootSourceOverrideEnabled property")
545 return(8,None,False,None)
546
547 if( enabledVal=="Disabled"):
548 #just patch rhost to set OverrideEnabled=Disabled
549 patchData={"Boot": {"BootSourceOverrideEnabled": enabledVal} }
550 rc,r,j,d=rft.patchResource(rft, r, patchData)
551
552 else: # we are enabling bootOverride and also need to set the target
553 if(len(sc.args) < 3):
554 rft.printErr("Error, no bootSourceOverrideTarget specified")
555 return(8,None,False,None)
556 targetVal=sc.args[2]
557 if not targetVal in validTargetVals:
558 rft.printErr("Error, invalid BootSourceOverrideTarget value specified: {}".format(targetVal))
559 rft.printErr("Syntax: {} [options] Systems setBootOverride <enableVal> [<targetVal>]".format(rft.program))
560 rft.printErr(" <enableVal>=Disabled|Once|Continuous, <targetVal>=None,Pxe,BiosSetup...")
561 return(8,None,False,None)
562
563 if( (j is True) and ("Boot" in d) ):
564 if "[email protected]" in d["Boot"]:
565 rhostSupportedTargets=d["Boot"]["[email protected]"]
566 if not targetVal in rhostSupportedTargets:
567 rft.printErr("Error, the boot target specified is not supported by the remote service (via @Redfish.AllowableValues)")
568 return(8,None,False,None)
569 elif "@Redfish.ActionInfo" in d["Boot"]:
570 action_info_path = d["Boot"]["@Redfish.ActionInfo"]
571 rhostSupportedTargets = rft.getActionInfoAllowableValues(rft, r, action_info_path, "BootSourceOverrideTarget")
572 if rhostSupportedTargets is not None and targetVal not in rhostSupportedTargets:
573 rft.printErr("Error, the boot target specified is not supported by the remote service (via @Redfish.ActionInfo)")
574 return (8, None, False, None)
575 else: # rhost didn't return any AllowableValues, but it isn't required, so allow the action
576 rft.printVerbose(2, "The remote service does not have a [email protected] or @Redfish.ActionInfo prop")
577 else:
578 rft.printErr("Error, the remote service does not have a Boot prop")
579 return (8, None, False, None)
580
581 # verify that they have a BootSourceOverrideEnabled and BootSourceOverrideTarget prop
582 if( not "BootSourceOverrideTarget" in bootRes ):
583 rft.printErr("Error, the service does not have oneOf BootSourceOverride..Enabled or ..Target property")
584 return(8,None,False,None)
585
586 #form the patch data
587 patchData={"Boot": {"BootSourceOverrideEnabled": enabledVal, "BootSourceOverrideTarget": targetVal } }
588
589 #call the generic patch command to send the patch. This takes care of etag support
590 rc,r,j,d=rft.patchResource(rft, r, patchData)
591
592
593 if(rc==0):
594 rft.printVerbose(1," Systems setBootOverride:",skip1=True, printV12=cmdTop)
595 bootd={"Boot": d["Boot"]}
596 return(rc,r,j,bootd)
597
598 else: return(rc,r,False,None)
599
600
601 def setBootOverride(self, sc, op, rft, cmdTop=False, prop=None):
602 return op.iterate_op(op.setBootOverride_single, sc, op, rft, cmdTop=cmdTop, prop=prop)
603
604
605 def getProcessors(self,sc,op, rft, cmdTop=False, prop=None):
606 rft.printVerbose(4,"{}:{}: in operation: getProcessorColl".format(rft.subcommand,sc.operation))
607
608 # get the system resource
609 rc,r,j,d=op.get(sc,op, rft)
610 if( rc != 0): return(rc,r,False,None)
611
612 collName="Processors"
613 # get the link to the Processors collection
614 if ((collName in d) and ("@odata.id" in d[collName])):
615 procsLink=d[collName]["@odata.id"]
616 else:
617 rft.printErr("Error: computer system resource does not have a {} link".format(collName))
618 return(6,None,False,None)
619
620 if cmdTop is True: prop=rft.prop
621
622 # check if there is a list arg for the operation
623 if( sc.argnum > 1 and sc.args[1] == 'list' ):
624 #get the collection
625 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=procsLink)
626 #loop through the members and create the list sub-operation response
627 rc,r,j,d=rft.listCollection(rft, r, d, prop="Socket")
628 if(rc==0):
629 rft.printVerbose(1," list {} Collection member info: Id, URI, Socket".format(collName,skip1=True, printV12=cmdTop))
630
631 # else: check if no proc was specified. If not, return the collection
632 elif(rft.IdLevel2OptnCount==0):
633 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=procsLink, prop=prop)
634 if(rc==0):
635 rft.printVerbose(1," {} Collection ".format(collName,skip1=True, printV12=cmdTop))
636
637 # else: check if the -a (all) option is set. If not, return the proc specific by -i or -m
638 # search collection to find path using getPath2
639 elif( rft.allOptn is not True ):
640 # get the processor collection
641 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=procsLink, prop=prop)
642 collUrl=r.url
643
644 # now search for 2nd level resource and return
645 path2,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d)
646 if(rc!=0):
647 return(rc,r,j,d)
648 # so rc=0
649 #if sysPath returned a response but we need to extract the property do it here
650 if( (r is not None) and (prop is not None) ):
651 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
652
653 # otherwise, we need to do a GET to get the processor, if -P show property, else show full response
654 elif( r is None ):
655 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=path2, prop=prop)
656 if(rc==0):
657 rft.printVerbose(1," {} Collection Member ".format(collName,skip1=True, printV12=cmdTop))
658
659 # else, return ALL of the processor members
660 else:
661 rft.printVerbose(4,"getting expanded Processor Collection")
662 rc,r,j,d=rft.getAllCollectionMembers(rft, r.url, relPath=procsLink)
663 if(rc==0):
664 rft.printVerbose(1," Get ALL {} Collection Members".format(collName,skip1=True, printV12=cmdTop))
665
666 return(rc,r,j,d)
667
668
669 def getInventory(self,sc,op, rft, cmdTop=False, prop=None):
670 rft.printVerbose(4,"{}:{}: in operation: getInventory".format(rft.subcommand,sc.operation))
671
672 sys.stdout.write("%-20s %2s %-20s %2s %-10s\n" % ("Component","|","Present","|","Functional"))
673 # Get Processor and Memory Inventory
674 collection = ['Processors','Memory']
675 for collName in collection:
676 rc,r,j,d=op.get(sc,op, rft)
677 if( rc != 0): return(rc,r,False,None)
678 # get the link to the Processors collection
679 if ((collName in d) and ("@odata.id" in d[collName])):
680 Link=d[collName]["@odata.id"]
681 else:
682 rft.printErr("Error: computer system resource does not have a {} link".format(collName))
683 return(6,None,False,None)
684
685 if cmdTop is True: prop=rft.prop
686
687 rc,r,j,d=rft.getAllCollectionMembers(rft, r.url, relPath=Link)
688 if(rc==0):
689 rft.printVerbose(1," Get ALL {} Collection Members".format(collName,skip1=True, printV12=cmdTop))
690
691 # check if there is a list arg for the operation
692 if( sc.argnum > 1 and sc.args[1] == 'list' ):
693 output=json.dumps(d,indent=4)
694 print(output)
695 else:
696 numOfLinks=len(d["Members"])
697 for i in range (0,numOfLinks):
698 collName="Members"
699 sys.stdout.write("%-20s %2s %-20s %2s %-10s\n" % (d[collName][i]["Id"], "|", d[collName][i].get("Status", {}).get("State","N/A"), "|", d[collName][i].get("Status",{}).get("Health","N/A")))
700
701 # get the system resource
702 rc,r,j,d=op.get(sc,op, rft)
703 if( rc != 0): return(rc,r,False,None)
704
705 # get Fan inventory
706 jsonData=True
707 rc1,r1,j1,d1=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET',r.url, relPath=d["Links"]["Chassis"][0]["@odata.id"]+"/Thermal", prop=prop,jsonData=jsonData)
708
709 # check if there is a list arg for the operation
710 if( sc.argnum > 1 and sc.args[1] == 'list' ):
711 output=json.dumps(d1,indent=4)
712 print(output)
713 else:
714 numOfLinks=len(d1["Fans"])
715 for i in range (0,numOfLinks):
716 collName="Fans"
717 sys.stdout.write("%-20s %2s %-20s %2s %-10s\n" % (d1[collName][i]["Name"], "|", d1[collName][i].get("Status",{}).get("State","N/A"), "|", d1[collName][i].get("Status",{}).get("Health", "N/A")))
718
719 # get Power Supply inventory
720 rc1,r1,j1,d1=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET',r.url, relPath=d["Links"]["Chassis"][0]["@odata.id"]+"/Power", prop=prop,jsonData=jsonData)
721 # check if there is a list arg for the operation
722 if( sc.argnum > 1 and sc.args[1] == 'list' ):
723 output=json.dumps(d1,indent=4)
724 print(output)
725 else:
726 numOfLinks=len(d1["PowerSupplies"])
727 for i in range (0,numOfLinks):
728 collName="PowerSupplies"
729 sys.stdout.write("%-20s %2s %-20s %2s %-10s\n" % (d1[collName][i]["Name"], "|", d1[collName][i].get("Status",{}).get("State", "N/A"), "|", d1[collName][i].get("Status",{}).get("Health","N/A")))
730
731 return(0,None,False,None)
732
733
734
735 def getEnetInterfaces(self,sc,op,rft,cmdTop=False, prop=None):
736 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
737
738 # get the system resource
739 rc,r,j,d=op.get(sc,op, rft)
740 if( rc != 0): return(rc,r,False,None)
741
742 collName="EthernetInterfaces"
743 # get the link to the EthernetInterfaces collection
744 if ((collName in d) and ("@odata.id" in d[collName])):
745 nicLink=d[collName]["@odata.id"]
746 else:
747 rft.printErr("Error: EthernetInterfaces resource does not have a {} link".format(collName))
748 return(6,None,False,None)
749
750 if cmdTop is True: prop=rft.prop
751
752 # check if there is a list arg for the operation
753 if( sc.argnum > 1 and sc.args[1] == 'list' ):
754 #get the collection
755 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=nicLink)
756 #loop through the members and create the list sub-operation response
757 rc,r,j,d=rft.listCollection(rft, r, d, prop="Name")
758 if(rc==0):
759 rft.printVerbose(1," list {} Collection member info: Id, URI, Name".format(collName,skip1=True, printV12=cmdTop))
760
761 # else: check if no NIC was specified. If not, return the collection
762 elif(rft.IdLevel2OptnCount==0):
763 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=nicLink, prop=prop)
764 if(rc==0):
765 rft.printVerbose(1," {} Collection ".format(collName,skip1=True, printV12=cmdTop))
766
767 # else: check if the -a (all) option is set. If not, return the proc specific by -i or -m
768 # search collection to find path using getPath2
769 elif( rft.allOptn is not True ):
770 # get the EthernetInterfaces collection
771 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=nicLink, prop=prop)
772 collUrl=r.url
773
774 # now search for 2nd level resource and return
775 path2,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d)
776 if(rc!=0):
777 return(rc,r,j,d)
778 # so rc=0
779 #if sysPath returned a response but we need to extract the property do it here
780 if( (r is not None) and (prop is not None) ):
781 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
782
783 # otherwise, we need to do a GET to get the EthernetInterfaces, if -P show property, else show full response
784 elif( r is None ):
785 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=path2, prop=prop)
786 if(rc==0):
787 rft.printVerbose(1," {} Collection Member ".format(collName,skip1=True, printV12=cmdTop))
788
789 # else, return ALL of the EthernetInterfaces members
790 else:
791 rft.printVerbose(4,"getting expanded EthernetInterfaces Collection")
792 rc,r,j,d=rft.getAllCollectionMembers(rft, r.url, relPath=nicLink)
793 if(rc==0):
794 rft.printVerbose(1," Get ALL {} Collection Members".format(collName,skip1=True, printV12=cmdTop))
795
796 return(rc,r,j,d)
797
798
799
800 def getSimpleStorage(self,sc,op,rft,cmdTop=False, prop=None):
801 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
802
803 # get the system resource
804 rc,r,j,d=op.get(sc,op, rft)
805 if( rc != 0): return(rc,r,False,None)
806
807 collName="SimpleStorage"
808 # get the link to the SimpleStorage collection
809 if ((collName in d) and ("@odata.id" in d[collName])):
810 cntlrLink=d[collName]["@odata.id"]
811 else:
812 rft.printErr("Error: computer system resource does not have a {} link".format(collName))
813 return(6,None,False,None)
814
815 if cmdTop is True: prop=rft.prop
816
817 # check if there is a list arg for the operation
818 if( sc.argnum > 1 and sc.args[1] == 'list' ):
819 #get the collection
820 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=cntlrLink)
821 #loop through the members and create the list sub-operation response
822 rc,r,j,d=rft.listCollection(rft, r, d, prop="Name" )
823 if(rc==0):
824 rft.printVerbose(1," list {} Collection member info: Id, URI, Name".format(collName,skip1=True, printV12=cmdTop))
825
826 # else: check if no SimpleStorage controller was specified. If not, return the collection
827 elif(rft.IdLevel2OptnCount==0):
828 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=cntlrLink, prop=prop)
829 if(rc==0):
830 rft.printVerbose(1," {} Collection ".format(collName,skip1=True, printV12=cmdTop))
831
832 # else: check if the -a (all) option is set. If not, return the proc specific by -i or -m
833 # search collection to find path using getPath2
834 elif( rft.allOptn is not True ):
835 # get the SimpleStorage collection
836 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=cntlrLink, prop=prop)
837 collUrl=r.url
838
839 # now search for 2nd level resource and return
840 path2,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d)
841 if(rc!=0):
842 return(rc,r,j,d)
843 # so rc=0
844 #if sysPath returned a response but we need to extract the property do it here
845 if( (r is not None) and (prop is not None) ):
846 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
847
848 # otherwise, we need to do a GET to get the SimpleStorage, if -P show property, else show full response
849 elif( r is None ):
850 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=path2, prop=prop)
851 if(rc==0):
852 rft.printVerbose(1," {} Collection Member ".format(collName,skip1=True, printV12=cmdTop))
853
854 # else, return ALL of the SimpleStorage members
855 else:
856 rft.printVerbose(4,"getting expanded SimpleStorage Collection")
857 rc,r,j,d=rft.getAllCollectionMembers(rft, r.url, relPath=cntlrLink)
858 if(rc==0):
859 rft.printVerbose(1," Get ALL {} Collection Members".format(collName,skip1=True, printV12=cmdTop))
860
861 return(rc,r,j,d)
862
863
864
865 def getLogService(self,sc,op,rft,cmdTop=False, prop=None):
866 rft.printVerbose(4,":{}:{}: in operation".format(rft.subcommand,sc.operation))
867
868 # get the system resource
869 rc,r,j,d=op.get(sc,op, rft)
870 if( rc != 0): return(rc,r,False,None)
871
872 collName="LogServices"
873 # get the link to the LogServices collection
874 if ((collName in d) and ("@odata.id" in d[collName])):
875 logLink=d[collName]["@odata.id"]
876 else:
877 rft.printErr("Error: computer system resource does not have a {} link".format(collName))
878 return(6,None,False,None)
879
880 if cmdTop is True: prop=rft.prop
881
882 # check if there is a list arg for the operation
883 if( sc.argnum > 1 and sc.args[1] == 'list' ):
884 #get the collection
885 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=logLink)
886 #loop through the members and create the list sub-operation response
887 rc,r,j,d=rft.listCollection(rft, r, d, prop="Name")
888 if(rc==0):
889 rft.printVerbose(1," list {} Collection member info: Id, URI, Name".format(collName,skip1=True, printV12=cmdTop))
890
891 # else: check if no Log was specified. If not, return the collection
892 elif(rft.IdLevel2OptnCount==0):
893 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=logLink, prop=prop)
894 if(rc==0):
895 rft.printVerbose(1," {} Collection ".format(collName,skip1=True, printV12=cmdTop))
896
897 # else: check if the -a (all) option is set. If not, return the proc specific by -i or -m
898 # search collection to find path using getPath2
899 elif( rft.allOptn is not True ):
900 # get the LogServices collection
901 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=logLink, prop=prop)
902 collUrl=r.url
903
904 # now search for 2nd level resource and return
905 path2,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d)
906 if(rc!=0):
907 return(rc,r,j,d)
908 # so rc=0
909 #if sysPath returned a response but we need to extract the property do it here
910 if( (r is not None) and (prop is not None) ):
911 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
912
913 # otherwise, we need to do a GET to get the LogServices, if -P show property, else show full response
914 elif( r is None ):
915 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=path2, prop=prop)
916 if(rc==0):
917 rft.printVerbose(1," {} Collection Member ".format(collName,skip1=True, printV12=cmdTop))
918
919 # If '--Entries' specified, get "Entries" nav link and read it
920 if rc == 0 and rft.gotEntriesOptn:
921 if r is not None and j and isinstance(d, dict):
922 rft.printVerbose(1, 'getLogService: attempting to get Entries for Logs')
923 entries = d.get('Entries')
924 if entries is not None and isinstance(entries, dict):
925 entries_uri = entries.get('@odata.id')
926 if entries_uri is not None:
927 rc, r, j, d = rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url,
928 relPath=entries_uri, prop=prop)
929 else:
930 rft.printErr('getLogService: @odata.id not found in "Entries" property')
931 else:
932 rft.printErr('getLogService: "Entries" property not found in JSON payload')
933 else:
934 rft.printErr(
935 'Unable to fetch Entries property from previous response: response = {}, is_json = {}, type(json) = {}'
936 .format(r, j, type(d)))
937
938 # else, client specified the -a option requesting ALL of the LogServices members
939 # for logs, we will not support this. Its too much data.
940 else:
941 rft.printErr("Error: -a option not supported for LogServices")
942 return(6,None,False,None)
943
944 return(rc,r,j,d)
945
946
947 def clearLog(self,sc,op,rft,cmdTop=False, prop=None):
948 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
949 return(8,None,False,None)
950
951
952 def examples(self,sc,op,rft,cmdTop=False,prop=None):
953 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
954 print(" {} -r<ip> Systems # shows the systems collection".format(rft.program))
955 print(" {} -r<ip> Systems list # lists Id, Uri, AssetTag for all systems".format(rft.program))
956 print(" {} -r<ip> Systems -I <id> # gets the system with Id=<d>".format(rft.program))
957 print(" {} -r<ip> Systems -M AssetTag:12345 # gets the system with AssetTag=12345".format(rft.program))
958 print(" {} -r<ip> Systems -L <sysUrl> # gets the system at URI=<systemUrl".format(rft.program))
959 print(" {} -r<ip> Systems -F # get the First system returned (for debug)".format(rft.program))
960 print(" {} -r<ip> Systems -1 # get the first system and verify that there is only one system".format(rft.program))
961 print(" {} -r<ip> Systems -I <id> patch {{A: B,C: D,...}} # patch the json-formatted {{prop: value...}} data to the object".format(rft.program))
962 print(" {} -r<ip> Systems -I <id> reset <resetType> # reset a system. <resetType>=the redfish-defined values: On, Off, gracefulOff...".format(rft.program))
963 print(" {} -r<ip> Systems -I <id> setAssetTag <assetTag> # set the system's asset tag ".format(rft.program))
964 print(" {} -r<ip> Systems -I <id> setIndicatorLed <state> # set the indicator LED. <state>=redfish defined values: Off, Lit, Blinking".format(rft.program))
965 print(" {} -r<ip> Systems -I <id> setBootOverride <enabledVal> <targetVal> #-- set Boot Override properties. <enabledVal>=Disabled|Once|Continuous".format(rft.program))
966 print(" {} -r<ip> Systems -I<Id> Processors # get the processors Collection".format(rft.program))
967 print(" {} -r<ip> Systems -I<Id> Processors list # lists Id, Uri, and Socket for all processors in system with Id=<Id>".format(rft.program))
968 print(" {} -r<ip> Systems -I<Id> Processors -i 1 # get the processor with id=1 in system with Id=<Id>".format(rft.program))
969 print(" {} -r<ip> Systems -L <sysUrl> Processors -m Socket:CPU_1 # get processor with property Socket=CPU_1, on system at url <sysUrl>".format(rft.program))
970 return(0,None,False,None)
971
972
973
974
975 '''
976 TODO:
977 1. clearlog not implemented
978 2. handling segmented response to collections not tested (but code is there)
979
980 '''
981
982
983
984