Debian Codegraph @

redfishtoollib/Chassis.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: Chassis.py
6 #
7 # contains Chassis subCommands and access functions
8 #
9 # Class RfSystemsMain
10 # - functions init, displayUsage, displayHelp, displayOperations,
11 # - runOperation - Chassis command table, dispatch of operation eg get, reset
12 # - ChassisMain - called from redfishMain, enforce legal option combinations,
13 # and call runOperation to run Chassis operations (sub-sub-command)
14 #
15 # Class RfChassisOperations
16 # All of the Chassis sub-command operations eg: get, setIndicatorLed, etc
17 # - hello - test cmd
18 # - getCollection - return the Chassis 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 Chassis Member, with etag support
23 # - setAssetTag -- patches the assetTag of Chassis instance w/ etag support
24 # - setIndicatorLed --sets id LED to a specified value w/ etag support
25 # - getPower - get Processors collection, processor instance, or all
26 # - getSensors - get all sensors
27 # - getThermal - get Ethernet collection, instance, all
28 # - setPowerLimit - Set the PowerLimit for a member of the powerControl array
29 # - getPowerReading [consumed] - get the powerControl array, or ConsumedWatts from pwrCntl[0]
30 # - getLogService - get LogService collection, instance, all
31 # - clearLog -- clears a specified log (not implemented yet)
32 # - examples --prints some example apis
33 #
34 from .redfishtoolTransport import RfTransport
35 import requests
36 import json
37 import getopt
38 import re
39 import sys
40 from .ServiceRoot import RfServiceRoot
41 from urllib.parse import urljoin
42
43 class RfChassisMain():
44 def __init__(self):
45 # operation string and remaining args
46 self.operation=None
47 self.args=None
48 self.argnum=0
49 self.nonIdCommands=None
50
51 def displayUsage(self,rft):
52 if(rft.quiet): return(0)
53 print(" Usage:")
54 print(" {} [OPTNS] Chassis <operation> [<args>] -- perform <operation> on the Chassis specified ".format(rft.program))
55
56 def displayHelp(self,rft):
57 self.displayUsage(rft)
58 self.displayOperations(rft)
59 print(" ")
60
61 def displayOperations(self,rft):
62 print(" <operations>:")
63 print(" [collection] -- get the main Chassis collection. (Default operation if no member specified)")
64 print(" [get] -- get the Chassis object. (Default operation if collection member specified)")
65 print(" list -- list information about the Chassis collection members(\"Id\", URI, and AssetTag)")
66 print(" patch {A: B,C: D,...} -- patch the json-formatted {prop: value...} data to the object")
67 print(" setAssetTag <assetTag> -- set the Chassis's asset tag ")
68 print(" setIndicatorLed <state> -- set the indicator LED. <state>=redfish defined values: Off, Lit, Blinking")
69 print(" Power -- get the full Power resource under a specified Chassis instance.")
70 print(" Thermal -- get the full Thermal resource under a specified Chassis instance.")
71 print(" Sensors -- get all sensors.")
72 print("")
73 print(" getPowerReading [-i<indx>] [consumed]-- get powerControl resource w/ power capacity, PowerConsumed, and power limits")
74 print(" if \"consumed\" keyword is added, then only current usage of powerControl[indx] is returned")
75 print(" <indx> is the powerControl array index. default is 0. normally, 0 is the only entry")
76 print(" setPowerLimit [-i<indx>] <limit> [<exception> [<correctionTime>]] -- set powerLimit control properties")
77 print(" <limit>=null disables power limiting. <indx> is the powerControl array indx (dflt=0)")
78 print("")
79 print(" Logs [list] -- get the Chassis \"LogServices\" collection , or list \"id\" and URI of members.")
80 print(" Logs [IDOPTN] -- get the member specified by IDOPTN: -i<id>, -m<prop>:<val>, -l<link>, -a #all")
81 print(" clearLog <id> -- clears the log defined by <id>")
82 print(" examples -- example commands with syntax")
83 print(" hello -- Chassis hello -- debug command")
84 return(0)
85
86
87
88 def runOperation(self,rft):
89 # instantiate ChassisOperations class
90 op=RfChassisOperations()
91
92 # dispatch table for each subcommand: "cmdName": cmdClass.cmdFunction"
93 operationTable = {
94 "collection": op.getCollection,
95 "get": op.get,
96 "list": op.clist,
97 "patch": op.patch,
98 "setAssetTag": op.setAssetTag,
99 "setIndicatorLed": op.setIndicatorLed,
100 "Power": op.getPower,
101 "Thermal": op.getThermal,
102 "Sensors": op.getSensors,
103 "setPowerLimit": op.setPowerLimit,
104 "getPowerReading": op.getPowerReading,
105 "Logs": op.getLogService,
106 "-clearLog": op.clearLog,
107 "hello": op.hello,
108 "examples": op.examples
109 }
110
111 rft.printVerbose(5,"Chassis:runOperation: operation: {}".format(self.operation))
112 rft.printVerbose(5,"Chassis:runOperation: args: {}".format(self.args))
113
114 if self.operation in operationTable:
115 rft.printVerbose(5,"Chassis:runOperation: found Oper: {} in table. executing".format(rft.subcommand))
116 rc,r,j,d=operationTable[self.operation](self, op, rft, cmdTop=True)
117 return(rc,r,j,d)
118
119 else: # invalid operation
120 rft.printErr("Chassis: Invalid operation: {}".format(self.operation))
121 return(2,None,False,None)
122
123
124
125 def ChassisMain(self,rft,cmdTop=False):
126 rft.printVerbose(4,"ChassisMain: subcommand: {}".format(rft.subcommand))
127
128 if( rft.help ):
129 self.displayHelp(rft)
130 return(0,None,False,None)
131
132 # we will validate usage of -P and -a in action processing
133 # actually, if a non 'get' action is specified, -P and -a are just ignored :)
134
135 args=rft.subcommandArgv[0:]
136
137 #if no args, then if no member Id was specified (with -I|-M|-1|-F) then assume it is a "collection" operation
138 # if a -IM1F was specified, then assume it is a "get" operation for that member
139 if( len(args) < 2 ):
140 if( rft.IdOptnCount==0 ):
141 self.operation="collection"
142 else:
143 self.operation="get"
144 self.args= None
145 else:
146 self.operation=args[1]
147 self.args = args[1:] # now args points to the 1st argument
148 self.argnum =len(self.args)
149
150 rft.printVerbose(5,"Chassis: operation={}, args={}".format(self.operation,self.args))
151
152 # check if the command requires a collection member target -I|-M|-L|-1|-F eg sysIdoptn
153 nonIdCommands = ["collection", "list", "examples", "hello"]
154 if( ( not self.operation in nonIdCommands ) and (rft.IdOptnCount==0) ):
155 # default to --One if no Id option specified
156 rft.oneOptn = True
157 rft.IdOptnCount += 1
158
159 # now execute the operation.
160 rc,r,j,d = self.runOperation(rft)
161
162 if(rc !=0 ):
163 rft.printVerbose(5,"Chassis: operation returned with error: rc={}".format(rc))
164 return(rc,r,False,None)
165
166 #else, if here, the subcommand executed without error. Return with 0 exit code
167 rft.printVerbose(5,"Chassis: operation exited OK")
168 return(rc,r,j,d)
169
170
171 #
172 # contains operations related to the Chassis subCommand
173 #
174 class RfChassisOperations():
175 def __init__(self):
176 self.chassisPath=None
177 self.chassisCollectionDict=None
178
179
180 def hello(self,sc,op,rft,cmdTop=False):
181 rft.printVerbose(4,"in hello")
182 rft.printVerbose(4," subcmd:{}, operation:{}, args:{}".format(rft.subcommand,sc.operation,sc.args))
183 print("hello world from Chassis")
184 return(0,None,False,None)
185
186 def getCollection(self,sc,op,rft,cmdTop=False, prop=None):
187 rft.printVerbose(4,"{}:{}: in getCollection".format(rft.subcommand,sc.operation))
188
189 # 1st get serviceRoot
190 svcRoot=RfServiceRoot()
191 rc,r,j,d = svcRoot.getServiceRoot(rft)
192 if( rc != 0 ):
193 rft.printErr("getCollection: Error getting service root, aborting")
194 return(rc,r,False,None)
195
196 # get the link to the Systems collection
197 # need to test we got good data
198 if (("Chassis" in d) and ("@odata.id" in d["Chassis"])):
199 systemsLink=d["Chassis"]["@odata.id"]
200 else:
201 rft.printErr("Error: service root does not have a Chassis link")
202 return(4)
203
204 rft.printVerbose(4,"Chassis:getCollection: link is: {}".format(systemsLink))
205
206
207 # if a -a option was entered with "Chassis" or "Chassis collection" operation,
208 # then return all members of the Chassis collection expanded
209 if((cmdTop is True) and (rft.allOptn is True) ):
210 collName="Chassis"
211 rft.printVerbose(4,"Expand Chassis collection to return ALL Chassis collection members fully expanded in response")
212 rc,r,j,d=rft.getAllCollectionMembers(rft, r.url, relPath=systemsLink)
213 if(rc==0):
214 rft.printVerbose(1," Get ALL {} Collection Members".format(collName,skip1=True, printV12=cmdTop))
215
216 # otherwise, just return the collection
217 # now read the /Chassis collection
218 # use the returned url as the base url to read the Chassis collection
219 else:
220 if cmdTop is True: prop=rft.prop
221 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=systemsLink, prop=prop)
222 if(rc==0):
223 rft.printVerbose(1," Chassis Collection:",skip1=True, printV12=cmdTop)
224
225 return(rc,r,j,d)
226
227
228 def get(self,sc,op,rft, cmdTop=False, prop=None):
229 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
230
231 # getCollection
232 rc,r,j,d=op.getCollection(sc,op, rft)
233 if( rc != 0): return(rc,r,False,None)
234 collUrl=r.url
235
236 # search collection to find path to system
237 sysPath,rc,r,j,d=rft.getPathBy(rft, r, d, prop)
238 if( rc !=0 ): #if a path was not found, its an error
239 return(rc,r,j,d)
240
241 rft.printVerbose(4,"ChassisOperations:get: got a path, now get entries")
242
243 if cmdTop is True: prop=rft.prop
244
245 #if here, rc=0
246 #if sysPath returned a response but we need to extract the property do it here
247 if( (r is not None) and (prop is not None) ):
248 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
249
250 # otherwise, we need to do a GET to get the Chassis, if -P show property, else show full response
251 elif( r is None ):
252 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=sysPath, prop=prop)
253
254 if(rc==0): rft.printVerbose(1," Chassis Resource:",skip1=True, printV12=cmdTop)
255 return(rc,r,j,d)
256
257
258 def clist(self,sc,op,rft, cmdTop=False, prop=None):
259 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
260
261 # getCollection
262 collName="Chassis"
263 rc,r,j,d=op.getCollection(sc,op, rft)
264 if( rc != 0): return(rc,r,False,None)
265 #loop through the members and create the list sub-operation response
266 rc,r,j,d=rft.listCollection(rft, r, d, prop="AssetTag")
267 if(rc==0):
268 rft.printVerbose(1," list {} Collection member info: Id, URI, AssetTag".format(collName,skip1=True, printV12=cmdTop))
269 return(rc,r,j,d)
270
271
272 def iterate_op(self, run_single, sc, op, rft, cmdTop=False, prop=None):
273 # Wrapper method to handle issuing commands to a single chassis or to all chassis in the collection
274 if rft.allOptn:
275 # Issue command to all chassis in collection
276
277 # get the list of chassis
278 rc, r, j, d = op.clist(sc, op, rft, cmdTop=cmdTop, prop=prop)
279 if rc != 0 or not j or d is None or not isinstance(d, dict) or 'Members' not in d:
280 rft.printErr("Unable to get list of Chassis; return code = {}, list data = {}".format(rc, d))
281 return rc, r, j, d
282
283 # save existing rft options
284 saved_allOptn = rft.allOptn
285 saved_Link = rft.Link
286 saved_gotIdOptn = rft.gotIdOptn
287 saved_IdOptnCount = rft.IdOptnCount
288
289 # set rft options to process a single item
290 rft.allOptn = False
291 rft.gotIdOptn = True
292 rft.IdOptnCount = 1
293
294 # iterate through chassis and run operation on each based on the link (@odata.id value)
295 members = d.get('Members')
296 rc, r, j, d = 8, None, False, None
297 for member in members:
298 if '@odata.id' in member:
299 link = member.get('@odata.id')
300 # set rft.Link to point to the target chassis
301 rft.Link = link
302 # perform the operation
303 rc, r, j, d = run_single(sc, op, rft, cmdTop=cmdTop, prop=prop)
304 else:
305 rft.printErr("No '@odata.id' found in chassis member: {}".format(member))
306
307 # restore existing rft options
308 rft.allOptn = saved_allOptn
309 rft.Link = saved_Link
310 rft.gotIdOptn = saved_gotIdOptn
311 rft.IdOptnCount = saved_IdOptnCount
312 return rc, r, j, d
313 else:
314 # Issue command to single specified chassis
315 return run_single(sc, op, rft, cmdTop=cmdTop, prop=prop)
316
317
318 def patch_single(self,sc,op,rft,cmdTop=False, prop=None, patchData=None, r=None):
319 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
320 # verify we have got an argument which is the patch structure
321 # its in form '{ "AssetTag": <val>, "IndicatorLed": <val> }'
322 ##print("patchData: {}".format(patchData))
323 if( len( sc.args) == 2):
324 ##print("data:{}".format(sc.args[1]))
325 try:
326 patchData=json.loads(sc.args[1])
327 except ValueError:
328 rft.printErr("Patch: invalid Json input data:{}".format(sc.args[1]))
329 return(5,None,False,None)
330 ##print("patchData: {}".format(patchData))
331 else:
332 rft.printErr("Patch: error: invalid argument format")
333 rft.printErr(" : args={}".format(sc.args))
334 rft.printErr(" : expect: Systems patch \"{ <prop>: <value> }\"")
335 return(4,None,False,None)
336
337 # read the Chassis resource
338 # this is used by the generic rft.patchResource() function to see if there is an etag in the response
339 # if an etag is in response hdr, then we must include the etag on the patch, so this get is required
340 # note: the format of etag header for redfish is: ETag: W/"<string>" or "<string"
341 rc,r,j,d=op.get(sc,op,rft)
342 if( rc != 0):
343 return(rc,r,False,None)
344
345 # now call the generic patch function to send the patch
346 rc,r,j,d=rft.patchResource(rft, r, patchData)
347
348 if(rc==0): rft.printVerbose(1," Chassis Patch:",skip1=True, printV12=cmdTop)
349 return(rc,r,j,d)
350
351
352 def patch(self, sc, op, rft, cmdTop=False, prop=None):
353 return op.iterate_op(op.patch_single, sc, op, rft, cmdTop=cmdTop, prop=prop)
354
355
356 def setAssetTag_single(self,sc,op,rft,cmdTop=False, prop=None):
357 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
358
359 propName="AssetTag"
360
361 # get the asset tag from args
362 if(len(sc.args) < 2 ):
363 rft.printErr("Error, no assetTag value specified")
364 rft.printErr("Syntax: {} [options] Chassis setAssetTag \"string\" ".format(rft.program))
365 return(8,None,False,None)
366 assetTag=sc.args[1]
367 patchData={propName: assetTag}
368
369 # get the resource to verify it includes AssetTag,
370 # the response will also be used by Patch() to check for etag
371 rc,r,j,d=op.get(sc,op,rft)
372 if( rc != 0): return(rc,r,False,None)
373 if( not propName in d ):
374 rft.printErr("Chassis resource does not have a {} property.".format(propName))
375 return(8,r,False,None)
376
377 rc,r,j,d=rft.patchResource(rft, r, patchData)
378 if(rc==0):
379 rft.printVerbose(1," Chassis setAssetTag:",skip1=True, printV12=cmdTop)
380 assetTag={propName: d[propName]}
381 return(rc,r,j,assetTag)
382 else: return(rc,r,False,None)
383
384
385 def setAssetTag(self, sc, op, rft, cmdTop=False, prop=None):
386 return op.iterate_op(op.setAssetTag_single, sc, op, rft, cmdTop=cmdTop, prop=prop)
387
388
389 def setIndicatorLed_single(self,sc,op,rft,cmdTop=False, prop=None):
390 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
391
392 propName="IndicatorLED"
393
394 # get the asset tag from args
395 validLedStates=["Lit","Blinking","Off"]
396 if(len(sc.args) < 2 ):
397 rft.printErr("Error, no ledState value specified")
398 rft.printErr("Syntax: {} [options] Chassis setIndicatorLed <Lit|Off|Blinking>".format(rft.program))
399 return(8,None,False,None)
400 targLedState=sc.args[1]
401 if not targLedState in validLedStates:
402 rft.printErr("Error, invalid LED state specified")
403 return(8,None,False,None)
404 patchData={propName: targLedState}
405
406 # get the resource to verify it includes IndicatorLED,
407 # the response will also be used by Patch() to check for etag
408 rc,r,j,d=op.get(sc,op,rft)
409 if( rc != 0): return(rc,r,False,None)
410 if( not propName in d ):
411 rft.printErr("System resource does not have a {} property.".format(propName))
412 return(8,r,False,None)
413
414 rc,r,j,d=rft.patchResource(rft, r, patchData)
415 if(rc==0):
416 rft.printVerbose(1," Chassis setIndicatorLed:",skip1=True, printV12=cmdTop)
417 ledState={"IndicatorLED": d["IndicatorLED"]}
418 return(rc,r,j,ledState)
419 else: return(rc,r,False,None)
420
421
422 def setIndicatorLed(self, sc, op, rft, cmdTop=False, prop=None):
423 return op.iterate_op(op.setIndicatorLed_single, sc, op, rft, cmdTop=cmdTop, prop=prop)
424
425
426 def getPower(self,sc,op, rft, cmdTop=False, prop=None):
427 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
428 resName="Power"
429
430 # get the Chassis resource first
431 rc,r,j,d=op.get(sc, op, rft, cmdTop, resName)
432 if( rc != 0): return(rc,r,False,None)
433
434 # get the link to the Power resource under Chassis
435 if ((resName in d) and ("@odata.id" in d[resName])):
436 resLink=d[resName]["@odata.id"]
437 else:
438 rft.printErr("Error: Chassis resource does not have a {} link".format(resName))
439 return(6,None,False,None)
440
441 if cmdTop is True: prop=rft.prop
442
443 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=resLink, prop=prop)
444 if(rc==0):
445 rft.printVerbose(1," {} Resource ".format(resName,skip1=True, printV12=cmdTop))
446
447 return(rc,r,j,d)
448
449
450
451 def getThermal(self,sc,op,rft,cmdTop=False, prop=None):
452 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
453 resName="Thermal"
454 # get the Chassis resource first
455 rc,r,j,d=op.get(sc, op, rft, cmdTop, resName)
456 if( rc != 0): return(rc,r,False,None)
457
458 # get the link to the Thermal resource under Chassis
459 if ((resName in d) and ("@odata.id" in d[resName])):
460 resLink=d[resName]["@odata.id"]
461 else:
462 rft.printErr("Error: Chassis resource does not have a {} link".format(resName))
463 return(6,None,False,None)
464
465 if cmdTop is True: prop=rft.prop
466
467 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=resLink, prop=prop)
468 if(rc==0):
469 rft.printVerbose(1," {} Resource ".format(resName,skip1=True, printV12=cmdTop))
470
471 return(rc,r,j,d)
472
473
474
475 def getPowerReading(self,sc,op,rft,cmdTop=False, prop=None):
476 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
477
478 if cmdTop is True: prop=rft.prop
479
480 # check if there is an arg for the operation
481 if( sc.argnum > 1 ):
482 if( sc.args[1] == 'consumed' ):
483 prop="PowerConsumedWatts"
484 else:
485 rft.printErr("Error: getPowerReading: invalid argument: {}".format(sc.args[1]))
486 rft.printErr("Syntax: getPowerReading [-i<indx>] [consumed]")
487 return(4,None,False,None)
488
489 # get the Chassis Power resource
490 rc,r,j,d=op.getPower(sc,op, rft)
491 if( rc != 0): return(rc,r,False,None)
492
493 # get the Power Control Object
494 if ("PowerControl" in d ):
495 powerControl=d["PowerControl"]
496 powerControlMembers=len(powerControl)
497 else:
498 rft.printErr("Error: Chassis resource does not have a PowerControl resource")
499 return(4,None,False,None)
500 if(powerControlMembers == 0 ):
501 rft.printErr("Error: Chassis PowerControl array is empty")
502 return(4,None,False,None)
503
504 # get the powerControl array index
505 if( rft.IdLevel2 is None ):
506 indx=0
507 else:
508 indxPattern="(^0$)|(^([1-9][0-9]{,2})$)" # <decimal>: 33...
509 indxMatch=re.search(indxPattern,rft.IdLevel2)
510 if( indxMatch ):
511 indx=int(rft.IdLevel2) # convert base10 to integer
512 rft.printVerbose(4,"getPowerReading: Indx={}".format(indx))
513 else:
514 rft.printErr("Error: getPowerReading: invalid PowerControl index value: {}".format(rft.IdLevel2))
515 rft.printErr("Chassis getPowerReading [current] [-i<indx>] --<indx> is integer 0 - 99 (default is 0)")
516
517 if( (indx+1) > powerControlMembers ):
518 rft.printErr("Error: specified PowerControl index does not exist: indx={}, members={}".format(indx,powerControlMembers))
519 return(4,None,False,None)
520
521 #if here, we have a valid indx
522 if(prop is not None):
523 if( prop in powerControl[indx] ):
524 respDataVal=powerControl[indx][prop]
525 respData={prop: respDataVal}
526 rft.printVerbose(1," Get Current Power consumption (PowerConsumedWatts) of PowerControl[{}] resource".format(indx,skip1=True, printV12=cmdTop))
527 else:
528 rft.printErr("Error: Property {} not not returned in PowerControl[{}] resource".format(prop,indx))
529 return(4,r,j,d)
530 else:
531 respData=powerControl[indx] #return the full powerControl array
532 rft.printVerbose(1," Chassis PowerControl[{}] array:".format(indx,skip1=True, printV12=cmdTop))
533
534 return(rc,r,j,respData)
535
536
537
538
539 #setPowerLimit [-i<indx>] <limit> [<exception> [<correctionTime>]] -- set powerLimit control properties")
540 def setPowerLimit_single(self,sc,op,rft,cmdTop=False, prop=None):
541 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
542
543 if cmdTop is True: prop=rft.prop
544
545 # check if there is a required 2nd arg <limit>
546 if( sc.argnum > 1 ):
547 limitPattern="(^null$)|(^0$)|(^([1-9][0-9]{,5})$)" # null | 0 | 8 | 33 |344 | 34333
548 limitMatch=re.search(limitPattern,sc.args[1]) # sc.args[1]=<limit>
549 if( limitMatch ):
550 if(sc.args[1] == "null"):
551 limit=None
552 else:
553 limit=int(sc.args[1]) # keep it a string
554 rft.printVerbose(4,"setPowerLimit: limit={}".format(limit))
555 powerLimitData={"LimitInWatts": limit }
556 else:
557 rft.printErr("Error: setPowerLimit: invalid <limit> value specified: {}".format(sc.args[1]))
558 rft.printErr("Chassis setPowerLimit [-i<indx>] <limit> [<exception> [<correctionTime>]] --limit=null | 0-99999")
559 return(8,None,False,None)
560 else:
561 rft.printErr("Error: setPowerLimit: no <limit> value specified: {}")
562 rft.printErr("Chassis setPowerLimit [-i<indx>] <limit> [<exception> [<correctionTime>]] --limit=null | 0-99999")
563 return(8,None,False,None)
564 # check if there is an optional 3rd arg <exception>
565 includeException=False
566 validExceptionVals=("NoAction", "HardPowerOff", "LogEventOnly", "Oem")
567 if (sc.argnum > 2 ):
568 exceptionVal=sc.args[2] # sc.args[2]=<exceptionEnum>
569 if( not exceptionVal in validExceptionVals ):
570 rft.printErr("Error: setPowerLimit: invalid <limit> value specified: {}".format(sc.args[2]))
571 rft.printErr("Chassis setPowerLimit [-i<indx>] <limit> [<exception> [<correctionTime>]] --limit=null | 0-99999")
572 return(8,None,False,None)
573 else:
574 rft.printVerbose(4,"setPowerLimit: exception={}".format(exceptionVal))
575 powerLimitData["LimitException"]=exceptionVal
576 includeException=True
577
578 # check if there is an optional 4th arg <correctionTime> in miliseconds
579 includeCorrectionTime=False
580 if (sc.argnum > 3 ):
581 correctionPattern="(^([1-9][0-9]{,6})$)" # 1-999999 ms
582 correctionMatch=re.search(correctionPattern,sc.args[3]) # sc.args[3]=<correctionInMs>
583 if( correctionMatch ):
584 correctionTime=int(sc.args[3]) # keep it a string
585 rft.printVerbose(4,"setPowerLimit: correctionInMs={}".format(correctionTime))
586 powerLimitData["CorrectionInMs"]=correctionTime
587 includeCorrectionTime=True
588 else:
589 rft.printErr("Error: setPowerLimit: invalid <correctionTime> value specified: {}".format(sc.args[3]))
590 rft.printErr("Chassis setPowerLimit [-i<indx>] <limit> [<exception> [<correctionTime>]] --correctionTime=1-999999 ms")
591 return(8,None,False,None)
592
593 # get the Chassis Power resource
594 rc,r,j,d=op.getPower(sc,op, rft)
595 if( rc != 0): return(rc,r,False,None)
596
597 # get the Power Control Object
598 if ("PowerControl" in d ):
599 powerControl=d["PowerControl"]
600 powerControlMembers=len(powerControl)
601 else:
602 rft.printErr("Error: Chassis resource does not have a PowerControl resource")
603 return(4,None,False,None)
604 if(powerControlMembers == 0 ):
605 rft.printErr("Error: Chassis PowerControl array is empty")
606 return(4,None,False,None)
607
608 # get the powerControl array index
609 if( rft.IdLevel2 is None ):
610 indx=0
611 else:
612 indxPattern="(^0$)|(^([1-9][0-9]*)$)" # <decimal>: 33...
613 indxMatch=re.search(indxPattern,rft.IdLevel2)
614 if( indxMatch ):
615 indx=int(rft.IdLevel2) # convert base10 to integer
616 rft.printVerbose(4,"setPowerLimit: Indx={}".format(indx))
617 else:
618 rft.printErr("Error: setPowerLimit: invalid PowerControl index: {}".format(rft.IdLevel2))
619 rft.printErr("Chassis setPowerLimit [current] [-i<indx>] --<indx> is integer 0 - 99 (default is 0)")
620 return(8,None,False,None)
621
622 if( (indx+1) > powerControlMembers ):
623 rft.printErr("Error: specified PowerControl index does not exist: indx={}, members={}".format(indx,powerControlMembers))
624 return(8,None,False,None)
625
626 # check that this PowerControl index member has the properties
627 if( not "LimitInWatts" in powerControl[indx]["PowerLimit"] ):
628 rft.printErr("Error: setPowerLimit: LimitInWatts property is not in rhost PowerControl[{}]".format(indx))
629 return(8,None,False,None)
630 if( ( includeException is True ) and ( not "LimitException" in powerControl[indx]["PowerLimit"] ) ):
631 rft.printErr("Error: setPowerLimit: LimitException property is not in rhost PowerControl[{}]".format(indx))
632 return(8,None,False,None)
633 if( ( includeCorrectionTime is True ) and ( not "CorrectionInMs" in powerControl[indx]["PowerLimit"] ) ):
634 rft.printErr("Error: setPowerLimit: CorrectionInMs property is not in rhost PowerControl[{}]".format(indx))
635 return(8,None,False,None)
636
637 # now build the final full patch data
638 #patchData={"PowerControl"[indx]: { "PowerLimit": powerLimitData } }
639 powerLimitRes={ "PowerLimit": powerLimitData }
640 patchData={ "PowerControl": [ {} ] }
641 empty={}
642 powerControlArray=list()
643 for i in range (0,powerControlMembers):
644 powerControlArray.append(empty)
645 powerControlArray[indx]=powerLimitRes
646 patchData["PowerControl"]=powerControlArray
647
648 rft.printVerbose(4,"setPowerLimit: patchData: {}".format(json.dumps(patchData)))
649
650 #call the generic patch command to send the patch. This takes care of etag support
651 rc,r,j,d=rft.patchResource(rft, r, patchData)
652
653 if(rc==0):
654 rft.printVerbose(1," SetPowerLimit [{}]:",indx, skip1=True, printV12=cmdTop)
655 powerLimit={"PowerLimit": d["PowerControl"][indx]["PowerLimit"]}
656 return(rc,r,j,powerLimit)
657
658 else: return(rc,r,False,None)
659
660
661 def setPowerLimit(self, sc, op, rft, cmdTop=False, prop=None):
662 return op.iterate_op(op.setPowerLimit_single, sc, op, rft, cmdTop=cmdTop, prop=prop)
663
664
665 def getLogService(self,sc,op,rft,cmdTop=False, prop=None):
666 rft.printVerbose(4,":{}:{}: in operation".format(rft.subcommand,sc.operation))
667
668 # get the Chassis resource
669 rc,r,j,d=op.get(sc,op, rft)
670 if( rc != 0): return(rc,r,False,None)
671
672 collName="LogServices"
673 # get the link to the LogServices collection
674 if ((collName in d) and ("@odata.id" in d[collName])):
675 logLink=d[collName]["@odata.id"]
676 else:
677 rft.printErr("Error: Chassis resource does not have a {} link".format(collName))
678 return(6,None,False,None)
679
680 if cmdTop is True: prop=rft.prop
681
682 # check if there is a list arg for the operation
683 if( sc.argnum > 1 and sc.args[1] == 'list' ):
684 #get the collection
685 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=logLink)
686 #loop through the members and create the list sub-operation response
687 rc,r,j,d=rft.listCollection(rft, r, d, prop="Name")
688 if(rc==0):
689 rft.printVerbose(1," list {} Collection member info: Id, URI, Name".format(collName,skip1=True, printV12=cmdTop))
690
691 # else: check if no Log was specified. If not, return the collection
692 elif(rft.IdLevel2OptnCount==0):
693 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=logLink, prop=prop)
694 if(rc==0):
695 rft.printVerbose(1," {} Collection ".format(collName,skip1=True, printV12=cmdTop))
696
697 # else: check if the -a (all) option is set. If not, return the proc specific by -i or -m
698 # search collection to find path using getPath2
699 elif( rft.allOptn is not True ):
700 # get the LogServices collection
701 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=logLink, prop=prop)
702 collUrl=r.url
703
704 # now search for 2nd level resource and return
705 path2,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d)
706 if(rc!=0):
707 return(rc,r,j,d)
708 # so rc=0
709 #if sysPath returned a response but we need to extract the property do it here
710 if( (r is not None) and (prop is not None) ):
711 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
712
713 # otherwise, we need to do a GET to get the LogServices, if -P show property, else show full response
714 elif( r is None ):
715 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=path2, prop=prop)
716 if(rc==0):
717 rft.printVerbose(1," {} Collection Member ".format(collName,skip1=True, printV12=cmdTop))
718
719 # If '--Entries' specified, get "Entries" nav link and read it
720 if rc == 0 and rft.gotEntriesOptn:
721 if r is not None and j and isinstance(d, dict):
722 rft.printVerbose(1, 'getLogService: attempting to get Entries for Logs')
723 entries = d.get('Entries')
724 if entries is not None and isinstance(entries, dict):
725 entries_uri = entries.get('@odata.id')
726 if entries_uri is not None:
727 rc, r, j, d = rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url,
728 relPath=entries_uri, prop=prop)
729 else:
730 rft.printErr('getLogService: @odata.id not found in "Entries" property')
731 else:
732 rft.printErr('getLogService: "Entries" property not found in JSON payload')
733 else:
734 rft.printErr(
735 'Unable to fetch Entries property from previous response: response = {}, is_json = {}, type(json) = {}'
736 .format(r, j, type(d)))
737
738 # else, client specified the -a option requesting ALL of the LogServices members
739 # for logs, we will not support this. Its too much data.
740 else:
741 rft.printErr("Error: -a option not supported for LogServices")
742 return(6,None,False,None)
743
744 return(rc,r,j,d)
745
746
747 def clearLog(self,sc,op,rft,cmdTop=False, prop=None):
748 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
749 return(8,None,False,None)
750
751
752 def getSensors(self,sc,op, rft, cmdTop=False, prop=None):
753 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
754
755 sys.stdout.write("%-50s %-10s %-10s\n" % ("Sensor", "Reading", "UpperCritical"))
756 resName="Thermal"
757 # get the Chassis resource first
758 rc,r,j,d=op.get(sc, op, rft, cmdTop, resName)
759 if( rc != 0): return(rc,r,False,None)
760
761 # get the link to the Thermal resource under Chassis
762 if ((resName in d) and ("@odata.id" in d[resName])):
763 resLink=d[resName]["@odata.id"]
764 else:
765 rft.printErr("Error: Chassis resource does not have a {} link".format(resName))
766 return(6,None,False,None)
767
768 if cmdTop is True: prop=rft.prop
769
770 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=resLink, prop=prop)
771 if(rc==0):
772 rft.printVerbose(1," {} Resource ".format(resName,skip1=True, printV12=cmdTop))
773
774 collection = ['Temperatures','Fans']
775 for collName in collection:
776 numOfLinks=len(d[collName])
777 for i in range (0,numOfLinks):
778 if collName== 'Fans':
779 sys.stdout.write("%-50s %-10s %-10s\n" % (d[collName][i]["MemberId"], d[collName][i].get("Reading","N/A"),"N/A"))
780 else:
781 sys.stdout.write("%-50s %-10s %-10s\n" % (d[collName][i]["MemberId"], d[collName][i].get("ReadingCelsius","N/A"), d[collName][i].get("UpperThresholdCritical","N/A)")))
782
783
784 resName="Sensors"
785 # get the Chassis resource first
786 rc,r,j,d=op.get(sc, op, rft, cmdTop, resName)
787 if( rc != 0): return(rc,r,False,None)
788
789 # get the link to the Thermal resource under Chassis
790 if ((resName in d) and ("@odata.id" in d[resName])):
791 resLink=d[resName]["@odata.id"]
792 else:
793 rft.printErr("Error: Chassis resource does not have a {} link".format(resName))
794 return(6,None,False,None)
795
796 if cmdTop is True: prop=rft.prop
797
798 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=resLink, prop=prop)
799 if(rc==0):
800 rft.printVerbose(1," {} Resource ".format(resName,skip1=True, printV12=cmdTop))
801
802 numOfLinks=len(d["Members"])
803 for i in range (0,numOfLinks):
804 collName="Members"
805 rc1,r1,j1,d1=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=d[collName][i]["@odata.id"], prop=prop)
806 output=json.dumps(d1,indent=4)
807 sys.stdout.write("%-50s %-10s %-10s\n" % (d1["Id"], d1.get("Reading", "N/A"), d1.get("Thresholds", {}).get("UpperCritical",{}).get("Reading","N/A")))
808
809
810 return(rc,r,False,None)
811
812
813 def examples(self,sc,op,rft,cmdTop=False,prop=None):
814 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
815 print(" {} -r<ip> Chassis # shows the Chassis collection".format(rft.program))
816 print(" {} -r<ip> Chassis list # lists Id, Uri, AssetTag for all Chassis".format(rft.program))
817 print(" {} -r<ip> Chassis -I <id> # gets the Chassis with Id=<d>".format(rft.program))
818 print(" {} -r<ip> Chassis -M AssetTag:12345 # gets the Chassis with AssetTag=12345".format(rft.program))
819 print(" {} -r<ip> Chassis -L <sysUrl> # gets the Chassis at URI=<systemUrl".format(rft.program))
820 print(" {} -r<ip> Chassis -F # get the First Chassis returned (for debug)".format(rft.program))
821 print(" {} -r<ip> Chassis -1 # get the first Chassis and verify that there is only one system".format(rft.program))
822 print(" {} -r<ip> Chassis -I <id> patch {{A: B,C: D,...}} # patch the json-formatted {{prop: value...}} data to the object".format(rft.program))
823 print(" {} -r<ip> Chassis -I <id> setAssetTag <assetTag> # set the system's asset tag ".format(rft.program))
824 print(" {} -r<ip> Chassis -I <id> setIndicatorLed <state> # set the indicator LED. <state>=redfish defined values: Off, Lit, Blinking".format(rft.program))
825 print(" {} -r<ip> Chassis -I<Id> Power # get the full chassis Power resource".format(rft.program))
826 print(" {} -r<ip> Chassis -I<Id> Thermal # get the full chassis Thermal resource".format(rft.program))
827 print(" {} -r<ip> Chassis -I<Id> getPowerReading[-i<indx> [consumed] # get chassis/Power powerControl[<indx>] resource".format(rft.program))
828 print(" # if optional \"consumed\" arg, then return only the PowerConsumedWatts prop")
829 print(" {} -r<ip> Chassis -L<Url> setPowerLimit [-i<indx>] <limit> [<exception> [<correctionTime>]] # set power limit".format(rft.program))
830 return(0,None,False,None)
831
832
833
834
835 '''
836 TODO:
837 1. clearlog not implemented
838
839 '''
840
841
842
843