Debian Codegraph @

redfishtoollib/redfishtoolTransport.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
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: redfishtoolTransport.py
6 #
7 # Contents:
8 # 1. Class RfSessionAuth -- holds auto-created session Auth info. 'requests' calls to get credentials
9 # 2. Class RfTransport -- has the generic functions to send/receive http requests, generic print functions, etc
10 # - transport object variables used to pass transport parameters from main to cmdTable and subcommand objects
11 # - getApiScheme function -- generates proper scheme (http|https) based on input options and type of API
12 # - getVersionAndSetRootPath function -- executes GET /redfish with optional retry loop to negotiate protocol ver
13 # between this program and remote service, and creates the path of the root object
14 # - rftSendRecvRequest function--general function to send/receive Requests. handles exceptions, retries, error handling, headers
15 # handles proper joining of relative urls, selecting proper Auth and Scheme specified by user, etc
16 # - getPropFromDict --extracts a single property from a dict
17 # - getVersions -- function to return the service versions: GET ^/redfish
18 # - printVerbose -- common function used to print based on verbose level
19 # - printErr -- common function to print errors
20 # - printStatusErr4xx -- expands status_codes >400 to include description eg Unauthorized
21 # - rfSessionLogin, rfSessionDelete -- function to create or delete session if -ASession is selected (default)
22 # - rfCleanup -- called at end before returning. Deletes auto-created sessions
23 # - getPathBy --function that walks collection looking for a specific instance
24 # - getLevel2ResourceById -- searches a 2nd level collection (Processors) for -l urlLink, -m prop:val
25 # - listCollection -- create a list of a collection members including Id, <prop>, <rpath> of each member
26 # this is used by Systems and Chassis... to implement 'list' redfishtool command
27 # - getAllCollectionMembers -- given a url to a collection, get it, and then get all members,
28 # return dict with all members expanded
29 # - patchResource - generic patch function-handles etags and re-reading patched resource if response is 204
30 # - parseOdataType --parse the @odata.type property of a resource into Namespace, VersionString, ResourceType
31 #
32 # **Reference links for main requests
33 # https://github.com/kennethreitz/requests
34 #
35 import os
36 import re
37 import requests
38 import json
39 import sys
40 import socket
41 import time
42 import ipaddress
43 from datetime import datetime, timedelta
44 from dateutil import parser
45 from urllib.parse import urljoin, urlparse, urlunparse
46 from requests.auth import HTTPBasicAuth, AuthBase
47 from .ServiceRoot import RfServiceRoot
48
49 class RfSessionAuth(AuthBase):
50 def __init__(self,authToken):
51 self.authToken=authToken
52 #print("INIT SESSION AUTH")
53
54 def __call__(self, r):
55 r.headers['X-Auth-Token']=self.authToken
56 #print("Call SESSION AUTH")
57 return(r)
58
59 class RfTransport():
60 def __init__(self):
61 # constant parameters-- these dont change and are not updated
62 self.program="redfishtool" # program name (in case we want to change it)
63 self.version="1.1.5" # this redfishtool version
64 self.releaseDate="03/02/2021" # release date for this version of redfishtool
65 self.downloadFrom="https://github.com/DMTF/Redfishtool" # where to find redfishtool
66 self.magic="12345" # used for debug to test for a known parameter in this object
67 self.UNAUTHENTICATED_API=1 # unauthenticated API that doesn't send credentials in body data
68 self.AUTHENTICATED_API=2 # authenticated API that doesn't send credentials in body data
69 self.AUTHENTICATED_WITH_CREDENTIALS_API=3 # Authenticated API that sends credentials eg passwd update, add user
70 self.UNAUTHENTICATED_WITH_CREDENTIALS_API=4 # session login (unauthenticated) but sends credentials
71 self.authValidValues=["None", "Basic", "Session"]
72 self.secureValidValues=["Never", "IfSendingCredentials", "IfLoginOrAuthenticatedApi", "Always"]
73 self.supportedVersions=["v1"] # list of RedfishProtocolVersions that this program supports
74 self.MaxNextLinks=10 # max number of requests allowed with NextLink
75 self.dfltPatchPostPutHdrs = {'OData-Version': '4.0', 'Content-Type': 'application/json', 'Accept': 'application/json' }
76 self.dfltGetDeleteHeadHdrs = {'Accept': 'application/json', 'OData-Version': '4.0' }
77
78
79 # options and argument read from commandline options
80 # these are all set or updated by Main and remain constant for all APIs called for the cmd
81 self.verbose=0
82 self.status=0
83 self.help=False
84 self.quiet=False
85 self.user=""
86 self.password=""
87 self.rhost=None
88 self.token=None
89 self.protocolVer="v1"
90 self.auth="Basic" # or "Session" using Basic as default now
91 self.timeout=10 # http transport timeout in seconds, stored as int here
92 self.checkProtocolVer=False # if -C option, then we need to check/verify the protocol ver. dflt=false
93 self.blocking=True
94 self.no_proxy=False
95
96 # more option parsing variables
97 self.prop=None
98 self.requestMethod=None #used by raw subcommand
99 self.requestData=None #used by raw subcommand
100 self.Id=None
101 self.firstOptn=False
102 self.gotIdOptn=False
103 self.IdOptnCount=0
104 self.gotPropOptn=False
105 self.oneOptn=False
106 self.allOptn=False
107 self.gotMatchOptn=False
108 self.matchProp=None
109 self.matchValue=None
110 self.gotEntriesOptn = False
111
112 self.IdLevel2=None
113 self.gotIdLevel2Optn=False
114 self.IdLevel2OptnCount=0
115
116 self.gotMatchLevel2Optn=False
117 self.matchLevel2Prop=None
118 self.matchLevel2Value=None
119
120 self.linkLevel2=None # -l <link> or --link=<link>
121
122 self.Link=None # -L <Link> or --Link=<link>
123 self.configFile=""
124 self.secure="IfLoginOrAuthenticatedApi" #Never
125 self.waitTime=3
126 self.waitNum=1
127 self.headers=None
128 self.dbgFlag=0
129 self.subcommand=""
130 self.subcommandArgv=""
131
132 # transport parameters -- set by transport based on options and GetVersions
133 # these remain constant for all APIs called for the command
134 self.rhostVersions=None
135 self.rootPath=None
136 self.rootUri=None
137 self.rootResponseDict=None
138 self.rhostSupportedVersions=None
139 self.versionToUse=None
140
141 # API parameters that are calculated for each (multiple) API call used to execute the cmd
142 self.scheme=None #not used any longer
143 self.scheme0=None #not used any longer
144 self.apiType=None
145 #self.sessionId=None
146
147 # addl session login parameters
148 self.sessionId=None
149 self.sessionLink=None
150 self.authToken=None
151 self.cleanupOnExit=True
152
153 # measured execution time
154 self.elapsed=None
155
156 requests.packages.urllib3.disable_warnings()
157
158
159 # calculate the user-specified minimum security scheme based on APItype and --Secure options
160 # usage: userSpecifiedScheme=rft.getApiScheme(apiType)
161 # self.secureValidValues=["IfSendingCredentials", "IfLoginOrAuthenticatedApi", "Always", "Never"]
162 def getApiScheme(self,apiTypeIn):
163 scheme=None
164 if( self.secure == "Always" ):
165 scheme="https"
166 elif( self.secure == "Never" ):
167 scheme="http"
168 elif( (self.secure == "IfSendingCredentials") and
169 ( (apiTypeIn==self.AUTHENTICATED_WITH_CREDENTIALS_API) or
170 (apiTypeIn==self.UNAUTHENTICATED_WITH_CREDENTIALS_API) or
171 ( (apiTypeIn==self.AUTHENTICATED_API) and (self.auth == "Basic") ) ) ):
172 scheme="https"
173 elif( (self.secure=="IfLoginOrAuthenticatedApi") and
174 ( (apiTypeIn==self.AUTHENTICATED_API) or
175 (apiTypeIn==self.UNAUTHENTICATED_WITH_CREDENTIALS_API) )):
176 scheme="https"
177 else:
178 scheme="http"
179 #print("else HTTP dflt")
180 return(scheme) #return ok
181
182 def getVersionsAndSetRootPath(self,rft,forceCheckProtocolVer=False):
183 # Read the Redfish Versions API (/redfish) to determine which protocol versions the service supports
184 # The proper ServiceRoot Path returned for each protocol version eg: { "v1": "/redfish/v1" }.
185 # If self.redfishProtocolVersion="Latest" (which is the default), we will select the latest version
186 # that is supported by both the remote redfish service AND this program.
187 # If the -R <redfishVer> option is called where the user specifies a version to use,
188 # we must verify that the remote redfish client supports that version and that this program supports it
189 # Initially, only "v1" is specified, so this program and services should all support only v1.
190 # But it is important that client code be coded to negotiate properly to be compatible with future services
191 # The versions supported by this program are in a list supportedVersions=["v1",...]
192 # If the -W <waitNum>:<waitTime> was specified with waitNum > 1, then we will loop executing the /redfish
193 # API up to waitNum times with http "connection" timeout=waitTime for the service to respond
194 # Note that we will always send at least one request to /redfish API even if waitNum=0.
195 # Waiting for the service to be up this way can aid in sending commands to services connected through
196 # shared NICs where the network path can goes away for a few seconds as the host OS boots and NICs
197 # reset and authenticate with switches. If we wait until we have a connection to start, most false
198 # failures are avoided (although the connection can also go away during cmd exec-but that window is smaller
199 rft.printVerbose(5,"getVersionsAndRootPath: read versions from rhost")
200
201 # if already executed, just return
202 if( rft.rootPath is not None):
203 rft.printVerbose(5,"Transport.getRootPath: path already exists")
204 #return(0,None,False,None)
205 if( rft.rhost is None):
206 rft.printErr("Transport: -r rHost was not specified and is required by this command. aborting")
207 return(5,None,False,None)
208
209 # if the checkProtocol flag is not set true, dont query rhost for /redfish version
210 # just use what was passed in with -R <redfishVersion> or the default "v1"
211 if( (rft.checkProtocolVer is False) and (forceCheckProtocolVer is not True) ):
212 # If here, checkProtocolVer is false. we will generate the rootURL and hope for the best
213 # This saves additional Get /redfish query that 99.9% of time is ok
214 # the Get Versions API (GET /redfish) calls the routine with forceCheckProtocolVer=True
215 rft.rootPath=urljoin("/redfish/", (rft.protocolVer + "/") )
216 #id of protocolVersion is v1, rft.rootPath="/redfish/v1/"
217
218 # calculate the rootUri including scheme,rhost,rootPath properly
219 scheme=rft.getApiScheme(rft.UNAUTHENTICATED_API)
220
221 rhost = rft.rhost
222 try:
223 if ipaddress.ip_address(rhost).version == 6:
224 rhost = '[{}]'.format(rhost)
225 except ValueError:
226 pass
227
228 scheme_tuple=[scheme, rhost, rft.rootPath, "","",""]
229 rootUrl=urlunparse(scheme_tuple)
230 rft.rootUri=rootUrl
231 # save parameters
232 rft.rhostSupportedVersions=None
233 rft.versionToUse=rft.protocolVer
234 rft.printVerbose(5,"Transport.getRootPath: protocolVer to use={}, rootPath={}".format(rft.versionToUse, rft.rootPath))
235 return(0,None,False,None) # return ok
236
237 # create scheme based on input parameters and apiType(set here) using setApiScheme() function above.
238 scheme=rft.getApiScheme(rft.UNAUTHENTICATED_API)
239
240 #define header and put the full URL together
241 hdrs = dict(rft.dfltGetDeleteHeadHdrs)
242
243 scheme_tuple=[scheme, rft.rhost, "/redfish", "","",""]
244 url=urlunparse(scheme_tuple) # url= "http[s]://<rhost>[:<port>]/redfish"
245
246 rft.printVerbose(5,"Transport.getRootPath: url={}".format(url))
247
248 # now send request to rhost, with retries based on -W <waitNum>:<waitTime> option.
249 # handle exceptions including timeouts.
250 success=None
251 r=None
252 for attempt in range(0,rft.waitNum):
253 try:
254 rft.printVerbose(3,"Transport:getVersions: GET {}".format(url))
255 t1=time.time()
256 r = requests.get(url, headers=hdrs, verify=False, timeout=(rft.waitTime,rft.timeout)) # GET ^/redfish
257 t2=time.time()
258 rft.elapsed = t2 - t1
259 # print request headers
260 rft.printStatus(3,r=r,authMsg=None)
261
262 except requests.exceptions.ConnectTimeout:
263 # connect timeout occured. try again w/o sleeping since a timeout already occured
264 rft.printVerbose(5,"Tranport: connectTimeout, try again")
265 pass
266 except (socket.error):
267 # this exception needed as requests is not catching socket timeouts
268 # especially "connection refused" eg web server not started
269 # issue: https://github.com/kennethreitz/requests/issues/1236
270 # Nothing timed out. this is a connect error. So wait and retry
271 rft.printVerbose(5,"Tranport: socket.error, wait and try again")
272 time.sleep(rft.waitTime)
273 except (requests.exceptions.ReadTimeout):
274 # read timeout occured. This shouldn't happen, so fail it
275 rft.printErr("Transport: Fatal timeout waiting for response from rhost")
276 return(5)
277 except (requests.exceptions.ConnectionError):
278 # eg DNS error, connection refused. wait and try again
279 rft.printVerbose(5,"Tranport: ConnectionError, wait and try again")
280 time.sleep(rft.waitTime)
281 except requests.exceptions.RequestException as e:
282 # otherl requests exceptions. return with error
283 rft.printErr("Transport: Fatal exception trying to connect to rhost. Error:{}".format(e))
284 return(5,None,False,None)
285
286 else: # if no exception
287 #print the response status (-ssss)
288 rft.printStatus(4,r=r,authMsg=None)
289 rft.printStatus(5,r=r,authMsg=None)
290
291 if( r.status_code==requests.codes.ok):
292 success=True
293 break
294
295
296 if not success: # retries were exceeded w/o success
297 rft.printErr("Transport: Cant connect to remote redfish service. Aborting command")
298 if( (r is not None) and ( r.status_code >= 400 )):
299 rft.printStatusErr4xx(r.status_code)
300 else:
301 rft.printErr("Transport Error. No response")
302 return(5,None,False,None)
303
304 #print the response status (-ssss)
305 rft.printStatus(4,r=r)
306
307 # if here, r is the response to the GET /redfish request
308 rft.printVerbose(5,"Transport: getVersionsAndRootPath: Get /redfish: statusCode: {}".format(r.status_code))
309
310 # load it into a python dictionary
311 try:
312 rft.rhostVersions=json.loads(r.text)
313 except ValueError:
314 rft.printErr("Transport: Error reading Versions from /redfish: Bad Json:{}".format(r.text))
315 return(5,None,False,None)
316
317 #create a list of version numbers that the service supports from the response dict.
318 # this will look something like ["v1", "v2"...]
319 serviceSupportedVersions=list(rft.rhostVersions)
320
321 # now determine the right protocol to use based on -P protocolVer option (default=Latest), the versions that
322 # the remote service supports, and the versions that this program supports.
323 rfVer=None # rfVer holds the version we select. It will be a string eg "v1"
324
325 # first calculate the version to use for the default "-P Latest" option setting--means "use the latest common protocol ver"
326 if(rft.protocolVer=="Latest"):
327 #reverse sort the supportedVersions list for this program (latest means highest first in list
328 reverseSortedRftVersions=list(rft.supportedVersions) # make a copy of the list. this list looks like ["v1","v2"...]
329
330 # now reverse sort it based on the number (the 1 in v1). the result looks like ["v2", "v1", ...]
331 reverseSortedRftVersions.sort(key=lambda x: int(x[1:]),reverse=True) # reverse sort it based on number (the 1 in v1)
332 #print("rf",reverseSortedRftVersions)
333
334 #search to find latest version supported by both redfishtool and the remote service
335 for ver in reverseSortedRftVersions:
336 if ver in serviceSupportedVersions:
337 rfVer=ver
338 break
339 if( not rfVer):
340 rft.printErr("Transport: Error: no match looking for latest common protocol version")
341 rft.printErr(" between {} and remote service".format(rft.program),noprog=True)
342
343 # second, calculate the version to use if the user specifies a specific version number eg -P v2
344 else: # user explicitely specified a version to use. Check if service supports it
345 if rft.protocolVer in rft.supportedVersions:
346 if rft.protocolVer in serviceSupportedVersions:
347 rfVer=rft.protocolVer
348 else:
349 rft.printErr("Error: protocol version {} is not supported by remote redfish service".format(rft.protocolVer))
350 rft.printErr(" Versions supported by remote service: {}".format(serviceSupportedVersions),noprog=True)
351
352 else:
353 rft.printErr("Error: protocol version {} is not supported by {}".format( rft.protocolVer,rft.program))
354 rft.printErr(" Versions supported by {}: {}".format(rft.program,rft.supportedVersions),noprog=True)
355
356 if( not rfVer): # more error messages if error
357 return(4,None,False,None)
358
359 # If here, we have a valid protocol version
360 # get the service root path for that version from the Versions response
361 # save the service root path in transport object
362 rft.rootPath=self.rhostVersions[rfVer]
363 rft.rootUri=r.url
364 #rft.rootUri=self.scheme+self.rhost+self.rootPath
365 rft.rhostSupportedVersions=list(serviceSupportedVersions)
366 rft.versionToUse=rfVer
367 rft.printVerbose(5,"Transport.getRootPath: protocolVer to use={}, rootPath={}".format(rfVer, rft.rootPath))
368 return(0,r,True,rft.rhostVersions) # return ok
369
370 #'''
371 # the main workhorse send/receive request function used to send gets, patches, posts, deletes...
372 # handles the following processing within this function:
373 # x-- getting minimum security scheme based on command type input
374 # x-- reconcilling min scheme with baseUrl scheme (will join to use the most secure)
375 # x-- joining with relative path (but not allowing scheme less than min calculated if relPath (input) included a scheme
376 # 1-- setting headers based on: authenticationType, method, etag, dataType for the command
377 # 1-- add appropriate authentication for commandType, and command options
378 # -- calling the Requests function with additional kwargs for header, data
379 # -- if a collection Get where not all members are returned, looping to get all of the members
380 # 1-- processing Requests exceptions correctly
381 # 1-- loading json into Dict with exception handling
382 # -- printing error messages from Requests or json.loads, and setting return codes
383 # x-- returning standard tuple: rc,r,j,d
384 # rc,r,j,d =(returnCode(int: 0=ok), RequestsResponse, jsonData(True/False), data (type: None|dict|text))
385 # Syntax: rc,r,j,d = rftSendRecvRequest( apiType, method, baseUrl, relPath=None, jsonData=True, prop=None,
386 # collection=False, loadData=True, redirect=True, data=None (inputdata),
387 # getEtagFirst=False (for patches, get etag from rhost 1st),**kwargs)
388 # todo:
389 # 1. exception handling on urlparse, urlunparse, urljoin
390
391 def rftSendRecvRequest( rft, apiType, method, baseUrl, relPath=None, data=None, jsonData=True, prop=None,
392 redirects=True, reqData=None, verify=False,
393 headersInput=None, **kwargs ):
394
395 rft.printVerbose(5,"Transport.rftProcessRequest: method={}, baseUrl={}, rpath={}".format(method,baseUrl,relPath))
396 rft.printVerbose(5,"Transport.rftProcessRequest: apiType={}".format(apiType))
397 # get scheme based on input parameters and apiType(set here) using getApiScheme() function above.
398 userSpecifiedScheme=rft.getApiScheme(apiType)
399
400 # parse url into its parts: scheme, netloc, path, params, query fragment
401 # the assumption is that baseUrl was the url sent back from the previous request--might have been a redirect
402 # urlp is a urlparse Response class
403 urlp=urlparse(baseUrl)
404
405 # if baseUrl scheme is https, use https no matter what the user specified scheme is.
406 # this got upgraded from the service side as a redirect.
407 # but we don't allow service to redirect us to a less secure scheme than the user specified one
408 if( urlp.scheme == 'https' ):
409 scheme='https'
410 else:
411 scheme=userSpecifiedScheme;
412
413 # now unparse the api with most secure scheme
414 scheme_tuple=[scheme, urlp.netloc, urlp.path, "","",""]
415 urlBase2=urlunparse(scheme_tuple)
416
417 #join the baseURL and relative path passed in
418 # note that if no relPath was specified, it defaults to None, which joins nothing to base URL
419 # this re-joining logic makes redfishtool correctly follow normal relative URL rules.
420 # although redfish does not allow local relative paths, redfishtool will work if they were implemented
421 url=urljoin(urlBase2,relPath)
422
423 #define headers.
424 # the transport will use defaults specified in the Transport defaults properties dfltXYZHdrs depending on method XYZ.
425 # if headers were passed in by a command function in property headersInput, then add them or modify default with those values
426 # And also: if addl headers were specified in the commandline -H <hdrs> option, add them to the defaults above
427
428 # ex self.dfltPatchPostPutHdrs = {"content-type": "application/json", "Accept": "application/json", "OData-Version": "4.0" }
429 # ex self.dfltGetDeleteHeadHdrs = {"Accept": "application/json", "OData-Version": "4.0" }
430
431
432 # get default headers based on the method being called
433 if( (method == 'PATCH') or (method == 'POST') or (method == 'PUT') ):
434 hdrlist=rft.dfltPatchPostPutHdrs
435 else: # method is GET, DELETE, HEAD
436 hdrlist=rft.dfltGetDeleteHeadHdrs
437
438 # make copy of the dict. Otherwise Requests is sometimes not adding addl headers. a byte vs string bug in requests
439 hdrs=dict(hdrlist)
440
441 # if a list of headers was sent in in the function, then add them (or update defaults with new values)
442 if( headersInput is not None): # headers passed in from a calling function overrides defaults
443 for key in headersInput:
444 hdrs[key]=headersInput[key]
445
446 # check and see if an additional/alternate hdr value was passed in on CLI as -H option
447 if( rft.headers is not None):
448 # a user passed-in an addl header using -H {A:B, C:D},
449 # This changes the current value or adds the new header if it doesn't already exist
450 for key in rft.headers:
451 hdrs[key]=rft.headers[key]
452
453 #print("hdrs:{}".format(hdrs))
454 hdrs['Accept-Encoding']=None
455
456 #calculate the authentication method
457 authType=None
458 authMsg=None
459
460 rft.printVerbose(5,"Transport.ProcessRequest: url={}".format(url))
461 authenticatedApi=None
462 if( (apiType==rft.UNAUTHENTICATED_API) or (apiType==rft.UNAUTHENTICATED_WITH_CREDENTIALS_API)):
463 authenticatedApi=False
464 elif( (apiType==rft.AUTHENTICATED_API) or (apiType==rft.AUTHENTICATED_WITH_CREDENTIALS_API)):
465 authenticatedApi=True
466
467 if( (authenticatedApi is False) or (rft.auth=="None") ):
468 authType=None
469 authMsg=None
470 elif( (authenticatedApi is True) and (rft.auth=="Basic")):
471 authType=HTTPBasicAuth(rft.user, rft.password)
472 authMsg="Basic"
473 elif( (authenticatedApi is True) and (rft.auth=="Session")):
474 if( rft.authToken is None): # ie: we dont already have a token that was passed in or previously loggedin
475 rc,r,j,d=rft.rfSessionLogin(rft) #cleanup=true tells the transport to logout at end of cmd
476 #this will save the authToken at rft.token, and sessionLink at rft.sessionLink
477 if( rc != 0): # error logging in
478 return(rc,r,j,d)
479 # now we should have a valid auth token. create an instance of this auth
480 authMsg="Session"
481 authType=RfSessionAuth(rft.authToken)
482 else: # unknown auth type or API
483 rft.printErr("Transport: Invalid auth type specified, aborting command")
484 return(4,None,False,None)
485
486 # now send request to rhost, with retries based on -W <waitNum>:<waitTime> option.
487 # handle exceptions including timeouts.
488 success=None
489 r=None
490 respd=None
491 nextLink=True
492 for attempt in range(0,rft.MaxNextLinks):
493 try:
494 rft.printVerbose(3,"Transport:SendRecv: {} {}".format(method,url))
495 t1=time.time()
496 r = requests.request(method, url, headers=hdrs, auth=authType, verify=verify, data=reqData,
497 timeout=(rft.waitTime,rft.timeout),**kwargs) # GET ^/redfish
498 t2=time.time()
499 rft.elapsed = t2 - t1
500 # print request headers
501 rft.printStatus(3,r=r,authMsg=authMsg)
502
503 except requests.exceptions.ConnectTimeout:
504 # connect timeout occured. try again w/o sleeping since a timeout already occured
505 rft.printVerbose(5,"Tranport: connectTimeout, try again")
506 return(5,r,False,None)
507 except (socket.error):
508 # this exception needed as requests is not catching socket timeouts
509 # especially "connection refused" eg web server not started
510 # issue: https://github.com/kennethreitz/requests/issues/1236
511 # Nothing timed out. this is a connect error. So wait and retry
512 rft.printVerbose(5,"Tranport: socket.error, wait and try again")
513 time.sleep(rft.waitTime)
514 return(5,r,False,None)
515 except (requests.exceptions.ReadTimeout):
516 # read timeout occured. This shouldn't happen, so fail it
517 rft.printErr("Transport: Fatal timeout waiting for response from rhost")
518 return(5,r,False,None)
519 except (requests.exceptions.ConnectionError):
520 # eg DNS error, connection refused. wait and try again
521 rft.printVerbose(5,"Tranport: ConnectionError, wait and try again")
522 time.sleep(rft.waitTime)
523 return(5,r,False,None)
524 except requests.exceptions.RequestException as e:
525 # otherl requests exceptions. return with error
526 rft.printErr("Transport: Fatal exception trying to connect to rhost. Error:{}".format(e))
527 return(5,r,False,None)
528 else: # if no exception
529 rc=0
530 #print the response status (-ssss)
531 rft.printStatus(4,r=r,authMsg=authMsg)
532 rft.printStatus(5,r=r,authMsg=authMsg)
533 #rft.printStatus(5,data=r.text) # print the response data (-ssssss)
534
535 if( r.status_code >= 400):
536 rft.printStatusErr4xx(r.status_code)
537 return(5,r,False,None)
538 if( r.status_code == 302):
539 rft.printErr("Transport: Redirected: status_code: {}".format(r.status_code))
540 return(5,r,False,None)
541
542 if( r.status_code==204):
543 success=True
544 return(rc,r,False,None)
545 elif( (r.status_code==200) and (method=="HEAD") ):
546 success=True
547 return(rc,r,False,None)
548 elif (r.status_code == 202 and method in ["DELETE", "PATCH", "POST", "PUT"]):
549 success = True
550 if rft.blocking and r.headers.get("Location"):
551 return rft.waitForTask(r, urlBase2, headers=hdrs, auth=authType,
552 verify=verify, jsonData=jsonData, **kwargs)
553 else:
554 rft.printTaskStatus("Task Monitor URL is %s\n" %
555 r.headers.get("Location", "<not available>"))
556 return (rc, r, False, None)
557 elif((r.status_code==200) or (r.status_code==201) ):
558 if( jsonData is True):
559 try:
560 d=json.loads(r.text)
561 except ValueError:
562 rft.printErr("Transport: Error loading Data: uri: {}".format(url))
563 respd=None
564 rc=5
565 jsonData=False
566 return(rc,r,False,None)
567 else:
568 d=r.text #xml data
569 return(rc,r,jsonData,d)
570
571 #if here, no error, and its json data
572 # if specific property was specified, filter here
573 if(( method == "GET") and (prop is not None) ):
574 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
575 return(rc,r,j,d)
576 if( (respd is None) and ( not "[email protected]" in d)):
577 # normal case where single response w/ no next link
578 return(rc,r,jsonData,d)
579 elif( (respd is None ) and ("[email protected]" in d)):
580 #then this is the 1st nextlink
581 respd=d
582 url=urljoin(urlBase2,d["[email protected]"])
583 #dont return--keep looping
584 elif( not respd is None )and ("[email protected]" in d):
585 # this is 2nd or later response-that has a nextlink
586 respd["Members"]= respd["Members"] + d["Members"]
587 url=urljoin(urlBase2,d["[email protected]"])
588 elif( not respd is None )and (not "[email protected]" in d):
589 # this final response to a multi-response request, and it has not nextlink
590 respd["Members"]= respd["Members"] + d["Members"]
591 return(rc,r,jsonData,respd)
592 if respd is not None and attempt + 1 >= rft.MaxNextLinks:
593 # return what we have if we've reached MaxNextLinks
594 return rc, r, jsonData, respd
595 elif( r.status_code!=200):
596 success=False
597 rft.printErr("Transport: unexpected response status code {} for method {}"
598 .format(r.status_code, method))
599 return(5,r,False,None)
600
601 # Should not get here, but log error if we do
602 rft.printErr("Transport: Internal error; reached end of function without returning")
603 return 5, r, False, None
604
605 def sleepFor(self, response):
606 retry_after = response.headers.get("Retry-After", 1)
607 if isinstance(retry_after, int) or retry_after.isdigit():
608 # Retry-After: 120
609 sleep_for = timedelta(seconds=int(retry_after))
610 else:
611 # Retry-After: Fri, 31 Dec 1999 23:59:59 GMT
612 sleep_for = parser.parse(retry_after) - datetime.now()
613 return max(0, sleep_for.total_seconds())
614
615 def taskStatus(self, response):
616 task_state = "Running"
617 if "application/json" in response.headers.get("Content-Type", ""):
618 try:
619 d = response.json()
620 task_state = d.get("TaskState", "Running")
621 task_percent = d.get("PercentComplete")
622 if task_percent is not None:
623 return "Task is {}: {}% complete\r".format(
624 task_state, task_percent)
625 except Exception:
626 pass
627 return "Task is {}\r".format(task_state)
628
629 def printTaskStatus(self, msg):
630 """Print status to STDERR so that scripts that are expecting only JSON
631 on STDOUT do not break. Do not display task status if STDERR is
632 redirected.
633 """
634 if sys.stderr.isatty():
635 sys.stderr.write("\x1b[2K")
636 sys.stderr.write(msg)
637 sys.stderr.flush()
638
639 def waitForTask(self, r, url_base, headers=None, auth=None,
640 verify=False, max_wait=60, jsonData=True, **kwargs):
641 self.printVerbose(2, "Transport:waitForTask: enter")
642 if headers is None:
643 headers = {}
644 else:
645 headers = headers.copy()
646 if "Content-Type" in headers:
647 del headers["Content-Type"]
648 timeout = (self.waitTime, self.timeout)
649 location = r.headers.get("Location")
650 uri = urlparse(location).path
651 url = urljoin(url_base, uri)
652 timeout_at = time.time() + max_wait # time to give up on async task
653 while r.status_code == 202:
654 self.printTaskStatus(self.taskStatus(r))
655 sleep_for = self.sleepFor(r)
656 self.printVerbose(2, "Transport:waitForTask: sleep for %s seconds" % sleep_for)
657 time.sleep(sleep_for)
658 self.printVerbose(3, "Transport:SendRecv: {} {}".format('GET', url))
659 t1 = time.time()
660 r = requests.get(url, headers=headers, auth=auth, verify=verify,
661 timeout=timeout, **kwargs)
662 self.elapsed = time.time() - t1
663 self.printStatus(1, r=r)
664 self.printStatus(2, r=r)
665 if time.time() >= timeout_at and r.status_code == 202:
666 break
667 if r.status_code == 202:
668 self.printTaskStatus("Task still Running (max wait time exceeded)\n")
669 else:
670 self.printTaskStatus("Task is Done\n")
671 if r.ok:
672 if jsonData and "application/json" in r.headers.get("Content-Type", ""):
673 try:
674 d = r.json()
675 return 0, r, jsonData, d
676 except Exception as e:
677 self.printErr("Caught exception decoding JSON from async "
678 "task response; Exception: %s" % e)
679 return 5, r, False, None
680 else:
681 return 0, r, False, None
682 else:
683 return 5, r, False, None
684
685 def getPropFromDict(self,rft,r,d,prop):
686 if(prop in d):
687 propDict={prop: d[prop]}
688 else:
689 rft.printErr("Error: the resource does not have a {} property".format(prop))
690 return(4,None,False,None)
691 return(0,r,True,propDict)
692
693
694
695 # function to return service versions from GET /redfish as a python Dictionary
696 # returns (rc, rhostVersions) to lib main
697 # returns (rc) to CLI main
698 def getVersions(self,rft,cmdTop=False):
699 rft.printVerbose(4,"Transport: in getVersions")
700 if(rft.help):
701 print(" {} versions | redfish [-vh] -- get redfishProtocol versions supported by rhost".format(rft.program))
702 return(0,None,False,None)
703 rc,r,j,d=rft.getVersionsAndSetRootPath(rft, forceCheckProtocolVer=True)
704 if(rc != 0):
705 return(rc,None,False,None)
706
707 # note that getVersionAndSetRootPath() returns the versions data as d,
708 # so there is no need to call GET /redfish again. we have it at rft.versionsDict
709 # So just return it with the response
710
711 # create the addlData dict:
712 rft.printVerbose(2,"Additional Data:",skip1=True)
713 rft.printVerbose(2," redfishtool Supported Redfish Protocol Versions: {}".format(rft.supportedVersions))
714 rft.printVerbose(2," rhost Supported Redfish Protocol Versions: {}".format(rft.rhostSupportedVersions))
715 rft.printVerbose(2," negotiated protocol version to use: {}".format(rft.versionToUse))
716 rft.printVerbose(2," rootServicePath: {}".format(rft.rootPath))
717
718 # some command debug
719 rft.printVerbose(4,"Transport:getVersions: got serviceVersions and root path")
720
721 # if -v print header
722 rft.printVerbose(1," rhost Redfish Protocol Versions: GET /redfish",skip1=True)
723 return(rc,r,True,d)
724
725
726
727 #login to rhost and get a session Id
728 #authToken,sessionId=rft.rfSessionLogin()
729 def rfSessionLogin(self,rft,cmdTop=False,cleanupOnExit=True):
730 rft.printVerbose(4,"Transport: in SessionLogin")
731
732 # get the URL of the Sessions collection from the root service response
733 d=rft.rootResponseDict
734 loginUri=None
735
736 #if we don't have a root resource response, then get it now
737 if( d is None ):
738 # read the rootService
739 svcRoot=RfServiceRoot()
740 rc,r,j,d = svcRoot.getServiceRoot(rft)
741 if(rc!=0):
742 rft.printErr("Error: SessionLogin: could not read service root")
743 return(rc,None,False,None)
744
745 if( ("Links" in d) and ("Sessions" in d["Links"]) and ("@odata.id" in d["Links"]["Sessions"]) ):
746 loginUri=rft.rootResponseDict["Links"]["Sessions"]["@odata.id"]
747 #print("loginUri:{}".format(loginUri))
748 else:
749 rft.printErr("Error: the rootService response does not have a login link: \"Links\":\"Sessions\":{{\"@odata.id\": <uri>}")
750 return(4,None,False,None)
751
752 # create the Credential structure: { "UserName": "<username>", "Password": "<passwd>" }
753 credentials={"UserName": rft.user, "Password": rft.password }
754 loginPostData=json.dumps(credentials)
755
756 # now we have a login uri, login
757 # NOTE: this is API type:UNAUTHENTICATED_WITH_CREDENTIALS_API:
758 # POST the user credentials to the login URI, and read the SessionLink and SessionAuthToken from header
759 rc,r,j,d=rft.rftSendRecvRequest(rft.UNAUTHENTICATED_WITH_CREDENTIALS_API, 'POST', rft.rootUri, relPath=loginUri,
760 reqData=loginPostData)
761 if(rc!=0):
762 rft.printErr("Error: Session Login Failed: Post to Sessions collection failed")
763 return(rc,None,False,None) # save the sessionId and SessionAuthToken
764
765 # SessionAuthToken is in header: X-Auth-Token: <token>
766 # the SessionLink is in header: Location: <sessionLinkUrl>
767 # the sessionId is read from the response: d["Id"]
768 if( not "X-Auth-Token" in r.headers ):
769 rft.printErr("Error: Session Login Failed: Post to Session collection did not return Session Token")
770 return(4,None,False,None)
771 if( not "Location" in r.headers ):
772 rft.printErr("Error: Session Login Failed: Post to Session Collection did not return Link to session in Location hdr")
773 return(4,None,False,None)
774
775 #save auth token, sessionId, and sessionLink in transport database
776 rft.authToken=r.headers["X-Auth-Token"]
777 if( ( d is not None) and ( "Id" in d )):
778 rft.sessionId=d["Id"]
779 else:
780 rft.printErr("Error: Session Login either didn't return the new session or property Id was missing ")
781 return(4,None,False,None)
782 rft.sessionLink=r.headers["Location"]
783 rft.cleanupOnExit=cleanupOnExit
784
785 rft.printStatus(3,r=r,addSessionLoginInfo=True)
786
787 return(rc,r,j,d)
788
789
790
791 def rfSessionDelete(self,rft,cmdTop=False,sessionLink=None):
792 rft.printVerbose(4,"Transport: in Session Delete (Logout)")
793
794 #if session link was passed-in (logout cmd) use that, otherwise, use the saved value in the transport
795 if(sessionLink is None):
796 # delete this session saved in rft.sessionId, rft.sessionLink
797 # delete in rft
798 self.printVerbose(5,"rfSessionDelete: deleting session:{}".format(rft.sessionId))
799 rft.printVerbose(4,"Transport: delete session: id:{}, link:{}".format(rft.sessionId, rft.sessionLink))
800 sessionLink=rft.sessionLink
801
802 # now we have a login uri, login
803 # POST the user credentials to the login URI, and read the SessionLink and SessionAuthToken from header
804 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'DELETE', rft.rootUri, relPath=sessionLink)
805 if(rc!=0):
806 rft.printErr("Error: Logout: Session Delete Failed: Delete to Sessions collection failed")
807 rft.printErr(" sessionId:{}".format(sessionLink))
808 return(rc,None,False,None)
809
810 # save the sessionId and SessionAuthToken to None
811 self.sessionId=None
812 self.sessionLink=None
813 rc=0
814 return(rc,r,False,None)
815
816
817 def rfCleanup(self,rft):
818 #if we created a temp session in this cmd, logout
819 self.printVerbose(5,"rfCleanup:Cleaningup session: {}".format(self.sessionId))
820 if((rft.cleanupOnExit is True ) and (rft.sessionId is not None) ):
821
822 #delete the session
823 rc,r,j,d=rft.rfSessionDelete(rft)
824 #nothing else to do for now
825 return(rc)
826 else:
827 return(0)
828
829
830 def printVerbose(self,v,*argv, skip1=False, printV12=True,**kwargs):
831 if(self.quiet):
832 return(0)
833 if( (v==1 or v==2) and (printV12 is True) and (self.verbose >= v )):
834 if(skip1 is True): print("#")
835 print("#",*argv, **kwargs)
836 elif( (v==1 or v==2) and (self.verbose >4 )):
837 if(skip1 is True): print("#")
838 print("#",*argv, **kwargs)
839 elif((v==3 ) and (printV12 is True) and (self.verbose >=v)):
840 if(skip1 is True): print("#")
841 print("#REQUEST:",*argv,file=sys.stdout,**kwargs)
842 elif((v==4 or v==5) and (self.verbose >=v)):
843 if(skip1 is True): print("#")
844 print("#DB{}:".format(v),*argv,file=sys.stdout,**kwargs)
845 elif( v==0): #print no mater value of verbose, but not if quiet=1
846 if(skip1 is True): print("")
847 print(*argv, **kwargs)
848 else:
849 pass
850
851 sys.stdout.flush()
852 #if you set v= anything except 0,1,2,3,4,5 it is ignored
853
854
855 def printStatus(self, s, r=None, hdrs=None, authMsg=None, addSessionLoginInfo=False):
856 if(self.quiet):
857 return(0)
858 if( (s==1 ) and (self.status >= s ) and (r is not None) ):
859 print("#STATUS: Last Response: r.status_code: {}".format(r.status_code))
860 elif( (s==2 ) and (self.status >= s ) and (r is not None) ):
861 print("#STATUS: Last Response: r.url: {}".format(r.url))
862 print("#STATUS: Last Response: r.elapsed(responseTime): {0:.2f} sec".format(self.elapsed))
863 elif( (s==3 ) and (self.status >= s ) and (r is not None) ):
864 if( addSessionLoginInfo is True):
865 print("#____AUTH_TOKEN: {}".format(self.authToken))
866 print("#____SESSION_ID: {}".format(self.sessionId))
867 print("#____SESSION_URI: {}".format(self.sessionLink))
868 else:
869 print("#REQUEST: {} {} ".format(r.request.method, r.request.url))
870 print("#__Request.Headers: {}".format(r.request.headers))
871 print("#__Request AuthType: {}".format(authMsg))
872 print("#__Request Data: {}".format(r.request.body))
873 print("#__Response.status_code: {}, r.url: {}".format(r.status_code,r.url))
874 print("#__Response.elapsed(responseTime): {0:.2f} sec".format(self.elapsed))
875 elif( (s==4 ) and (self.status >= s ) and (r is not None) ):
876 print("#__Response.Headers: {}".format(r.headers))
877 elif( (s==5 ) and (self.status >= s ) ):
878 print("#__Response. Data: {}".format(r.text))
879 else:
880 pass
881 #if you set v= anything except 1,2,3,4,5 it is ignored
882 sys.stdout.flush()
883
884
885
886
887 def printErr(self,*argv,noprog=False,prepend="",**kwargs):
888 if( self.quiet == False):
889 if(noprog is True):
890 print(prepend,*argv, file=sys.stderr, **kwargs)
891 else:
892 print(prepend," {}:".format(self.program),*argv, file=sys.stderr, **kwargs)
893 else:
894 pass
895
896 sys.stderr.flush()
897 return(0)
898
899
900 def printStatusErr4xx(self, status_code,*argv,noprog=False, prepend="",**kwargs):
901 if(self.quiet):
902 return(0)
903 if( status_code < 400 ):
904 self.printErr("status_code: {}".format(status_code))
905 else:
906 if( status_code == 400 ):
907 errMsg="Bad Request"
908 elif( status_code == 401 ):
909 errMsg="Unauthorized"
910 elif( status_code == 402 ):
911 errMsg="Payment Required ?"
912 elif( status_code == 403 ):
913 errMsg="Forbidden--user not authorized to perform action"
914 elif( status_code == 404 ):
915 errMsg="Not Found"
916 elif( status_code == 405 ):
917 errMsg="Method Not Allowed"
918 elif( status_code == 406 ):
919 errMsg="Not Acceptable"
920 elif( status_code == 407 ):
921 errMsg="Proxy Authentication Required"
922 elif( status_code == 408 ):
923 errMsg="Request Timeout"
924 elif( status_code == 409 ):
925 errMsg="Conflict"
926 elif( status_code == 410 ):
927 errMsg="Gone"
928 elif( status_code == 411 ):
929 errMsg="Length Required"
930 elif( status_code == 412 ):
931 errMsg="Precondition Failed"
932 elif( status_code == 413 ):
933 errMsg="Request Entity Too Large"
934 elif( status_code == 414 ):
935 errMsg="Request-URI Too Long"
936 elif( status_code == 415 ):
937 errMsg="Unsupported Media Type"
938 elif( status_code == 416 ):
939 errMsg="Requested Range Not Satisfiable"
940 elif( status_code == 417 ):
941 errMsg="Expectation Failed"
942 elif( status_code < 500 ):
943 errMsg=""
944 elif( status_code >=500 ):
945 errMsg="Internal Server Error"
946 elif( status_code >=501 ):
947 errMsg="Not Implemented"
948 else:
949 errMsg=""
950 self.printErr("Transport: Response Error: status_code: {} -- {}".format(status_code, errMsg ))
951
952 sys.stdout.flush()
953 return(0)
954
955
956
957 def getPathBy(self,rft, r, coll, prop=None):
958 if('Members' not in coll):
959 rft.printErr("Error: getPathBy: no members array in collection")
960 return(None,1,None,False,None)
961 else:
962 numOfLinks=len(coll['Members'])
963 if( numOfLinks == 0 ):
964 rft.printErr("Error: getPathBy: empty members array")
965 return(None,1,None,False,None)
966
967 if(rft.Link is not None):
968 for i in range (0,numOfLinks):
969 if( '@odata.id' not in coll['Members'][i] ):
970 rft.printErr("Error: getPathBy --Link option: improper formatted link-no @odata.id")
971 return(None,1,None,False,None)
972 else:
973 path=coll['Members'][i]['@odata.id']
974 if( path == rft.Link ):
975 return(path,0,None,False,None)
976
977 #if we get here, there was no link in Members array that matched -L <link>
978 rft.printErr("Error: getPathBy --Link option: none of the links in the collection matched -L<link>")
979 return(None,1,None,False,None)
980
981 elif(rft.oneOptn):
982 if(numOfLinks > 1):
983 rc, r, j, d = rft.listCollection(rft, r, coll, prop)
984 id_list = []
985
986 if not rc and 'Members' in d:
987 if prop is not None:
988 if d['Members'] and '@odata.id' in d['Members'][0]:
989 return(d['Members'][0]['@odata.id'],0,None,False,None)
990 else:
991 id_list = [m['Id'] for m in d['Members'] if 'Id' in m]
992 rft.printErr("Error: No target specified, but multiple {} IDs found: {}"
993 .format(rft.subcommand, repr(id_list)))
994 rft.printErr("Re-issue command with '-I <Id>' to select target.")
995 return(None,1,None,False,None)
996 if('@odata.id' not in coll['Members'][0] ):
997 rft.printErr("Error: getPathBy --One option: improper formatted link-no @odata.id")
998 return(None,1,None,False,None)
999 else:
1000 return(coll['Members'][0]['@odata.id'],0,None,False,None)
1001
1002 elif( rft.firstOptn and not rft.gotMatchOptn):
1003 if( '@odata.id' not in coll['Members'][0] ):
1004 rft.printErr("Error: getPathBy --First option: improper formatted link-no @odata.id")
1005 return(None,1,None,False,None)
1006 else:
1007 return(coll['Members'][0]['@odata.id'],0,None,False,None)
1008
1009 elif(rft.gotMatchOptn):
1010 baseUrl=r.url
1011 matchedPath=None
1012 matches=0
1013 for i in range (0,numOfLinks):
1014 if( '@odata.id' not in coll['Members'][i] ):
1015 rft.printErr("Error: getPathBy --Id or --Match option: improper formatted link-no @odata.id")
1016 return(None,1,None,False,None)
1017 else:
1018 path=coll['Members'][i]['@odata.id']
1019 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', baseUrl, relPath=path)
1020 if(rc==0): # if matchProp found
1021 if( d[rft.matchProp] == rft.matchValue ):
1022 matchedPath=path
1023 matches +=1
1024 if( matches > 1 ):
1025 rft.printErr("Error: getPathBy --Id or --Match option: failed: found multiple matches.")
1026 return(None,1,None,False,None)
1027 if(rft.firstOptn):
1028 return(matchedPath,rc,r,j,d)
1029 else:
1030 rft.printVerbose(4,"Transport:getPathBy:Match: failed match: matchProp={}, matchValue={}, readValue={}".format(rft.matchProp,rft.matchValue,d[rft.matchProp]))
1031 pass
1032 else: # the request to this member failed
1033 rft.printErr("Error: getPathBy --Id or --Match option: failed request to read collection member.")
1034 pass
1035 #after looping over all members in the array,
1036 #if here, if we got a match, return the path. If not, then no match was found. return none
1037 if( matches > 0 ):
1038 return(matchedPath,rc,r,j,d)
1039 else:
1040 rft.printErr("Error: getPathBy --Id or --Match option: no match found in collection")
1041 return(None,1,None,False,None)
1042
1043 else:
1044 rft.printErr("Transport:getPathBy: Error: incorrect option specification")
1045 return(None,1,None,False,None)
1046
1047
1048 # returns <path> rc, r, j, d
1049 def getLevel2ResourceById(self,rft, r, coll):
1050 if('Members' not in coll):
1051 rft.printErr("Error: getPathBy2: no members array in collection")
1052 return(None,1,None,False,None)
1053 else:
1054 numOfLinks=len(coll['Members'])
1055 if( numOfLinks == 0 ):
1056 rft.printErr("Error: getPathBy2: empty members array")
1057 return(None,1,None,False,None)
1058
1059 if(rft.linkLevel2 is not None):
1060 for i in range (0,numOfLinks):
1061 if( '@odata.id' not in coll['Members'][i] ):
1062 rft.printErr("Error: getPathBy --Link option: improper formatted link-no @odata.id")
1063 return(None,1,None,False,None)
1064 else:
1065 path=coll['Members'][i]['@odata.id']
1066 if( path == rft.linkLevel2 ):
1067 return(path,0,None,False,None)
1068
1069 #if we get here, there was no link in Members array that matched -L <link>
1070 rft.printErr("Error: getPathBy --Link option: none of the links in the collection matched -L<link>")
1071 return(None,1,None,False,None)
1072 elif(rft.gotMatchLevel2Optn is True):
1073 baseUrl=r.url
1074 for i in range (0,numOfLinks):
1075 if( '@odata.id' not in coll['Members'][i] ):
1076 rft.printErr("Error: getPathBy2 --Id or --Match option: improper formatted link-no @odata.id")
1077 return(None,1,None,False,None)
1078 else:
1079 path=coll['Members'][i]['@odata.id']
1080 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', baseUrl, relPath=path)
1081 if(rc==0): # if matchProp found
1082 if( d[rft.matchLevel2Prop] == rft.matchLevel2Value ):
1083 return(path,rc,r,j,d)
1084 else:
1085 rft.printVerbose(5,"Transport:getPathBy2:Match: failed match: matchProp={}, matchValue={}, readValue={}".format(rft.matchLevel2Prop,rft.matchLevel2Value,d[rft.matchLevel2Prop]))
1086 pass
1087 else: # the request to this member failed
1088 pass
1089 #after looping over all members in the array,
1090 #if here, if we got a match, return the path. If not, then no match was found. return none
1091 return(None,1,None,False,None)
1092
1093 else:
1094 rft.printErr("Transport:getPathBy2: Error: incorrect option specification")
1095 return(None,1,None,False,None)
1096
1097
1098
1099
1100 # create a dict list of the collection containing: Id, <prop>, <rpath>
1101 # if prop=None, then the additional property is not included
1102 # return rc,r,j,d
1103 def listCollection(self, rft, r, coll, prop=None):
1104 if('Members' not in coll):
1105 rft.printErr("Error: listCollection: no members array in collection")
1106 return(4,None,False,None)
1107
1108 else:
1109 numOfLinks=len(coll['Members'])
1110 if( numOfLinks == 0 ):
1111 rft.printVerbose(4,"listCollection: empty members array: {}")
1112 return(0,r,True,coll) # returns an empty collection
1113
1114 baseUrl=r.url
1115
1116 members=list()
1117 for i in range (0,numOfLinks):
1118 if( '@odata.id' not in coll['Members'][i] ):
1119 rft.printErr("Error: listCollection improper formatted link-no @odata.id")
1120 return(4,None,False,None)
1121 else:
1122 path=coll['Members'][i]['@odata.id']
1123 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=path)
1124 if(rc==0): # if remote host returned a response
1125 if( "Id" not in d ):
1126 rft.printErr("Error: listCollection: no \"Id\" property in Collection member")
1127 return(4,None,False,None)
1128 if( prop is not None):
1129 if( prop not in d):
1130 propVal=None;
1131 else:
1132 propVal=d[prop]
1133 # create a member dict. Always include Id and path
1134 listMember={"Id": d["Id"], "@odata.id": d["@odata.id"] }
1135 # if a property was specified to include, add it to the list dict
1136 if( prop in d ):
1137 listMember[prop]=propVal
1138 # add the member to the list
1139 members.append(listMember)
1140
1141 #create base list dictionary
1142 collPath=urlparse(baseUrl).path
1143 collname=""
1144 if "Name" in coll:
1145 collname=coll["Name"]
1146 listd={ "_Path": collPath, "Name": collname, "[email protected]": numOfLinks, "Members": members }
1147 return(0, None, True, listd)
1148
1149
1150
1151 # given a url to a collection, get it, and then get all members, return dict with all members expanded
1152 def getAllCollectionMembers(self, rft, baseUrl, relPath=None ):
1153 #get all members of a collection expanded
1154 #first get the collection
1155 rc,r,j,coll=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', baseUrl, relPath=relPath)
1156 if('Members' not in coll):
1157 rft.printErr("Error: getAllCollectionMembers: no members array in collection")
1158 return(4,None,False,None)
1159 else:
1160 numOfLinks=len(coll['Members'])
1161 if( numOfLinks == 0 ):
1162 rft.printVerbose(4,"getAllCollectionMembers: empty members array: {}")
1163
1164 #then create new members array
1165 #for each member in members array, read the link into a new memberEntry
1166 baseUrl=r.url
1167 expandedMembers=list()
1168 for i in range (0,numOfLinks):
1169 if( '@odata.id' not in coll['Members'][i] ):
1170 rft.printErr("Error: getAllCollectionMembers improper formatted link-no @odata.id")
1171 return(4,None,False,None)
1172 else:
1173 path=coll['Members'][i]['@odata.id']
1174 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', baseUrl, relPath=path)
1175 if(rc==0): # if remote host returned a response
1176 #save this as new member entry
1177 expandedMembers.append(d)
1178
1179 #update base list dictionary
1180 coll["Members"]=expandedMembers
1181
1182 return(rc,r,j,coll)
1183
1184
1185 # this is the generic patch routing used by Systems patch, Chassis patch, etc
1186 def patchResource(self, rft, r, patchData, getResponseAfterPatch=True ):
1187 if( patchData is None ):
1188 rft.printErr("Transport:Patch: patchData=None")
1189 return(4,None,False,None)
1190 if(r is None):
1191 rft.printErr("Transport:Patch: resource Get response is None")
1192 return(4,None,False,None)
1193
1194 #output the patch data in json to send over the network
1195 reqPatchData=json.dumps(patchData)
1196
1197 # check if an etag was in response header, and extract the etag value if there
1198 # if an etag header was returned in Get, then we must include the etag on the patch, so this is required
1199 # the format of etag header for redfish is: ETag: W/"<string>" or "<string"
1200 # that is: double quotes are around the etag part
1201 # If the get returns an etag header, the patch should include header: If-Match: W/"<string>"
1202 # for some patches (updating users, the service will reject it if not included
1203
1204 #print("DEBUG: etag header:{}".format(r.headers))
1205 if( "Etag" in r.headers ):
1206 getEtag=r.headers["Etag"]
1207 patchHeaders={ "content-type": "application/json", "if-match": getEtag }
1208 #where in this case, the getEtag header will have double quotes embedded in it
1209 else:
1210 getEtag=None
1211 #patchHeaders={ "content-type": "application/json"} --dont need to specifiy this now
1212 patchHeaders=None
1213
1214 # ideally, we should verify that the property to be patched is supported in the get response
1215 # but this routine leaves checking that the patch property is good up to the calling routine
1216 # but since the data passed in may be complex, this is not easy to do for this general patch command
1217 # IE, we are doing this validation in the specific command operations like boot or setIndicatorLed or setAssetTag
1218 # send patch to rhost
1219 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'PATCH', r.url,
1220 headersInput=patchHeaders, reqData=reqPatchData)
1221 # if response was good but no data retured (status_Code=204), then do another GET to get the response
1222 if(rc==0):
1223 if(r.status_code==204): #no data returned, get the response
1224 # if the getResponseAfterPatch was set False, dont get a response
1225 # this is used by change password to not execute after changing password since the
1226 if getResponseAfterPatch is True:
1227 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url )
1228 if( rc != 0): return(rc,r,False,None)
1229 else:
1230 return(rc,r,False,None)
1231 #now check if status_code=200, but the content is a message--not a resource representation
1232 #some 1.0 implementations are returning 200 with message OK
1233 #thus, we need to do another GET
1234 elif( (r.status_code==200) and (not "@odata.id" in d)):
1235 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url )
1236 if( rc != 0): return(rc,r,False,None)
1237 return(rc,r,j,d)
1238
1239
1240
1241 #parse the @odata.type property into {namespace, version, resourceType} following redfish syntax rules
1242 # returns: namespace, version, resourceType.
1243 # If error parsing, returns None,None,None
1244 def parseOdataType(self,rft,resource):
1245 if not "@odata.type" in resource:
1246 rft.printErr("Transport:parseOdataType: Error: No @odata.type in resource")
1247 return(None,None,None)
1248
1249 resourceOdataType=resource["@odata.type"]
1250
1251 #the odataType format is: <namespace>.<version>.<type> where version may have periods in it
•1252 odataTypeMatch = re.compile(r'^#([a-zA-Z0-9]*)\.([a-zA-Z0-9\._]*)\.([a-zA-Z0-9]*)$')
1253 resourceMatch = re.match(odataTypeMatch, resourceOdataType)
1254 if(resourceMatch is None):
1255 # try with no version component
•1256 odataTypeMatch = re.compile(r'^#([a-zA-Z0-9]*)\.([a-zA-Z0-9]*)$')
1257 resourceMatch = re.match(odataTypeMatch, resourceOdataType)
1258 if (resourceMatch is None):
1259 rft.printErr("Transport:parseOdataType: Error parsing @odata.type")
1260 return(None,None,None)
1261 else:
1262 namespace = resourceMatch.group(1)
1263 version = None
1264 resourceType = resourceMatch.group(2)
1265 else:
1266 namespace=resourceMatch.group(1)
1267 version=resourceMatch.group(2)
1268 resourceType=resourceMatch.group(3)
1269
1270 return(namespace, version, resourceType)
1271
1272 def getActionInfoAllowableValues(self, rft, r, relPath, paramName):
1273 allowable_values = None
1274 rc, r, j, d = rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=relPath)
1275 if rc == 0 and j and d is not None:
1276 if "Parameters" in d and isinstance(d["Parameters"], list):
1277 params = d["Parameters"]
1278 for param in params:
1279 if "Name" in param and param["Name"] == paramName and "AllowableValues" in param:
1280 allowable_values = param["AllowableValues"]
1281 rft.printVerbose(2, 'getActionInfoAllowableValues: found "AllowableValues" {}'
1282 .format(allowable_values))
1283 break
1284 else:
1285 rft.printErr('Error getting AllowableValues from uri {}; rc = {}, response = {}'.format(relPath, rc, r))
1286 return allowable_values
1287
1288 '''
1289 TODO:
1290 1.
1291
1292 '''