Debian Codegraph @

redfishtoollib/SessionService.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: SessionService.py
6 #
7 # contains SessionService related subCommands and access functions
8 #
9 # Class RfSessionServiceMain
10 # - functions init, displayUsage, displayHelp, displayOperations,
11 # - runOperation - SessionService command table, dispatch of operation eg get, reset
12 # - SessionServiceMain - called from redfishMain, enforce legal option combinations,
13 # and call runOperation to run SessionService operation (sub-sub-command)
14 #
15 # Class RfSessionServiceOperations
16 # All of the SessionService sub-command operations eg: login, logout, get sessionService, etc
17 # - hello - test cmd
18 # - get - get the session service
19 # - patch - raw subcommand to patch a sessionService, with etag support
20 # - setSessionTimeout -- patches the SessionTimeout property w/ etag support
21 # - Sessions - get Sessions collection, Session instance, list Sessions, get all Sessions
22 # - login - Session login (post to add a new session)
23 # - logout - Session logout (delete to delete a session)
24 # - examples --prints some example apis
25 #
26 from .redfishtoolTransport import RfTransport
27 import requests
28 import json
29 import getopt
30 import re
31 import sys
32 from .ServiceRoot import RfServiceRoot
33 from urllib.parse import urljoin
34
35 class RfSessionServiceMain():
36 def __init__(self):
37 # operation string and remaining args
38 self.operation=None
39 self.args=None
40 self.argnum=0
41 self.nonIdCommands=None
42
43 def displayUsage(self,rft):
44 if(rft.quiet): return(0)
45 print(" Usage:")
46 print(" {} [OPTNS] SessionService <operation> [<args>] -- perform <operation> on the SessionService ".format(rft.program))
47
48 def displayHelp(self,rft):
49 self.displayUsage(rft)
50 self.displayOperations(rft)
51 print("")
52
53 def displayOperations(self,rft):
54 print(" <operations>:")
55 print(" [get] -- get the sessionService object. ")
56 print(" patch {A: B,C: D,...} -- patch the sessionService w/ json-formatted {prop: value...} ")
57 print(" setSessionTimeout <timeout> -- patches the SessionTimeout property w/ etag support ")
58 print(" Sessions [list] -- get the \"Sessions\" collection, or list \"Id\", username, and Url ")
59 print(" Sessions [IDOPTN] -- get the member specified by IDOPTN: -i<Id>, -m<prop>:<val>, -l<link>, -a #all")
60 print(" login -- sessionLogin. post to Sessions collection to create a session")
61 print(" the user is -u<user>, password is -p<password>")
62 print(" logout -- logout or delete the session by identified by -i<SessionId> or -l<link>")
63 print(" where <link> is the session path returned in Location from login")
64 print(" examples -- example commands with syntax")
65 print(" hello -- Systems hello -- debug command")
66 return(0)
67
68
69 def runOperation(self,rft):
70 # instantiate SessionServiceOperations class
71 op=RfSessionServiceOperations()
72
73 # dispatch table for each subcommand: "cmdName": cmdClass.cmdFunction"
74 operationTable = {
75 "get": op.get,
76 "patch": op.patch,
77 "setSessionTimeout": op.setSessionTimeout,
78 "Sessions": op.getSessions,
79 "login": op.sessionLogin,
80 "logout": op.sessionLogout,
81 "hello": op.hello,
82 "examples": op.examples
83 }
84
85 rft.printVerbose(5,"SessionService:runOperation: operation: {}".format(self.operation))
86 rft.printVerbose(5,"SessionService:runOperation: args: {}".format(self.args))
87
88 if self.operation in operationTable:
89 rft.printVerbose(5,"SessionService:runOperation: found Oper: {} in table. executing".format(rft.subcommand))
90 rc,r,j,d=operationTable[self.operation](self, op, rft, cmdTop=True)
91 return(rc,r,j,d)
92
93 else: # invalid operation
94 rft.printErr("SessionService: Invalid operation: {}".format(self.operation))
95 return(2,None,False,None)
96
97
98
99 def SessionServiceMain(self,rft,cmdTop=False):
100 rft.printVerbose(4,"SessionServiceMain: subcommand: {}".format(rft.subcommand))
101
102 if( rft.help ):
103 self.displayHelp(rft)
104 return(0,None,False,None)
105
106 # we will validate usage of -P and -a in action processing
107 # actually, if a non 'get' action is specified, -P and -a are just ignored :)
108
109 args=rft.subcommandArgv[0:]
110
111 #if no args, this is a getSessionService command
112 if( len(args) < 2 ):
113 self.operation="get"
114 self.args= None
115 else:
116 self.operation=args[1]
117 self.args = args[1:] # now args points to the 1st argument
118 self.argnum =len(self.args)
119
120 rft.printVerbose(5,"SessionService: operation={}, args={}".format(self.operation,self.args))
121
122 # now execute the operation.
123 rc,r,j,d = self.runOperation(rft)
124
125 if(rc !=0 ):
126 rft.printVerbose(5,"SessionService: operation returned with error: rc={}".format(rc))
127 return(rc,r,False,None)
128
129 #else, if here, the subcommand executed without error. Return with 0 exit code
130 rft.printVerbose(5,"SessionService: operation exited OK")
131 return(rc,r,j,d)
132
133
134 #
135 # contains operations related to the SessionService subCommand
136 #
137 class RfSessionServiceOperations():
138 def __init__(self):
139 self.SessionServicePath=None
140 self.SessionServiceCollectionDict=None
141
142
143 def hello(self,sc,op,rft,cmdTop=False):
144 rft.printVerbose(4,"in hello")
145 rft.printVerbose(4," subcmd:{}, operation:{}, args:{}".format(rft.subcommand,sc.operation,sc.args))
146 print("hello world from SessionService")
147 return(0,None,False,None)
148
149
150
151 def get(self,sc,op,rft, cmdTop=False, prop=None):
152 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
153
154 # 1st get serviceRoot
155 svcRoot=RfServiceRoot()
156 rc,r,j,d = svcRoot.getServiceRoot(rft)
157 if( rc != 0 ):
158 rft.printErr("get SessionService: Error getting service root, aborting")
159 return(rc,r,False,None)
160
161 # get the link to the SessionService
162 # need to test we got good data
163 if (("SessionService" in d) and ("@odata.id" in d["SessionService"])):
164 sessionServiceLink=d["SessionService"]["@odata.id"]
165 else:
166 rft.printErr("Error: root does not have a SessionService link")
167 return(4)
168
169 rft.printVerbose(4,"SessionService: get SessionService: link is: {}".format(sessionServiceLink))
170
171 if cmdTop is True: prop=rft.prop
172
173 # do a GET to get the SessionService, if -P show property, else show full response
174 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=sessionServiceLink, prop=prop)
175
176 if(rc==0): rft.printVerbose(1," SessionService Resource:",skip1=True, printV12=cmdTop)
177 return(rc,r,j,d)
178
179
180
181 def patch(self,sc,op,rft,cmdTop=False, prop=None, patchData=None, r=None):
182 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
183 # verify we have got an argument which is the patch structure
184 # its in form '{ "AssetTag": <val>, "IndicatorLed": <val> }'
185 ##print("patchData: {}".format(patchData))
186 if( len( sc.args) == 2):
187 ##print("data:{}".format(sc.args[1]))
188 try:
189 patchData=json.loads(sc.args[1])
190 except ValueError:
191 rft.printErr("Patch: invalid Json input data:{}".format(sc.args[1]))
192 return(5,None,False,None)
193 ##print("patchData: {}".format(patchData))
194 else:
195 rft.printErr("Patch: error: invalid argument format")
196 rft.printErr(" : args={}".format(sc.args))
197 rft.printErr(" : expect: SessionService patch \"{ <prop>: <value> }\"")
198 return(4,None,False,None)
199
200 # read the sessionServiceLink resource
201 # this is used by the generic rft.patchResource() function to see if there is an etag in the response
202 # if an etag is in response hdr, then we must include the etag on the patch, so this get is required
203 # note: the format of etag header for redfish is: ETag: W/"<string>" or "<string"
204 rc,r,j,d=op.get(sc,op,rft)
205 if( rc != 0):
206 return(rc,r,False,None)
207
208 # now call the generic patch function to send the patch
209 rc,r,j,d=rft.patchResource(rft, r, patchData)
210
211 if(rc==0): rft.printVerbose(1," SessionService Patch:",skip1=True, printV12=cmdTop)
212 return(rc,r,j,d)
213
214
215
216 def setSessionTimeout(self,sc,op,rft,cmdTop=False, prop=None):
217 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
218
219 propName="SessionTimeout"
220
221 # get the SessionTimeout from args
222 if(len(sc.args) < 2 ):
223 rft.printErr("Error, no SessionTimeout value specified")
224 rft.printErr("Syntax: {} [options] SessionService setSessionTimeout <timeoutInt> ".format(rft.program))
225 return(8,None,False,None)
226 sessTimeout=int(sc.args[1],0) # base 0 means int() will interpret 0x<num> as hex and <num> as decimal
227 patchData={propName: sessTimeout}
228
229 # get the resource to verify it includes AssetTag,
230 # the response will also be used by Patch() to check for etag
231 rc,r,j,d=op.get(sc,op,rft)
232 if( rc != 0): return(rc,r,False,None)
233 if( not propName in d ):
234 rft.printErr("SessionService resource does not have a {} property.".format(propName))
235 return(8,r,False,None)
236
237 rc,r,j,d=rft.patchResource(rft, r, patchData)
238 if(rc==0):
239 rft.printVerbose(1," SessionService setSessionTimeout:",skip1=True, printV12=cmdTop)
240 assetTag={propName: d[propName]}
241 return(rc,r,j,assetTag)
242 else: return(rc,r,False,None)
243
244
245
246 def getSessions(self,sc,op, rft, cmdTop=False, prop=None):
247 rft.printVerbose(4,"{}:{}: in operation: getSessions collection".format(rft.subcommand,sc.operation))
248
249 # get the system resource
250 rc,r,j,d=op.get(sc,op, rft)
251 if( rc != 0): return(rc,r,False,None)
252
253 collName="Sessions"
254 # get the link to the Sessions collection
255 if ((collName in d) and ("@odata.id" in d[collName])):
256 sessionsLink=d[collName]["@odata.id"]
257 else:
258 rft.printErr("Error: SessionService resource does not have a {} link".format(collName))
259 return(6,None,False,None)
260
261 if cmdTop is True: prop=rft.prop
262
263 # check if there is a list arg for the operation
264 if( sc.argnum > 1 and sc.args[1] == 'list' ):
265 #get the collection
266 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=sessionsLink)
267 #loop through the members and create the list sub-operation response
268 rc,r,j,d=rft.listCollection(rft, r, d, prop="UserName")
269 if(rc==0):
270 rft.printVerbose(1," list {} Collection member info: Id, URI, Socket".format(collName,skip1=True, printV12=cmdTop))
271
272 # else: check if no session was specified. If not, return the collection
273 elif(rft.IdLevel2OptnCount==0):
274 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=sessionsLink, prop=prop)
275 if(rc==0):
276 rft.printVerbose(1," {} Collection ".format(collName,skip1=True, printV12=cmdTop))
277
278 # else: check if the -a (all) option is set. If not, return the session specific by -i or -m or -l
279 # search collection to find path using getPath2
280 elif( rft.allOptn is not True ):
281 # get the Sessions collection
282 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=sessionsLink, prop=prop)
283 collUrl=r.url
284
285 # now search for 2nd level resource and return
286 path2,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d)
287 if(rc!=0):
288 return(rc,r,j,d)
289 # so rc=0
290 #if sysPath returned a response but we need to extract the property do it here
291 if( (r is not None) and (prop is not None) ):
292 rc,r,j,d=rft.getPropFromDict(rft,r,d,prop)
293
294 # otherwise, we need to do a GET to get the session, if -P show property, else show full response
295 elif( r is None ):
296 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', collUrl, relPath=path2, prop=prop)
297 if(rc==0):
298 rft.printVerbose(1," {} Collection Member ".format(collName,skip1=True, printV12=cmdTop))
299
300 # else, return ALL of the Sessions members
301 else:
302 rft.printVerbose(4,"getting expanded Sessions Collection")
303 rc,r,j,d=rft.getAllCollectionMembers(rft, r.url, relPath=sessionsLink)
304 if(rc==0):
305 rft.printVerbose(1," Get ALL {} Collection Members".format(collName,skip1=True, printV12=cmdTop))
306
307 return(rc,r,j,d)
308
309
310
311
312 #SessionService -u <username> -p <passwd> login, returns authToken and sessionId
313 def sessionLogin(self,sc,op,rft,cmdTop=False, prop=None):
314 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
315
316 #note that <username> and <password> were passed-in in -u and -p options and are stores in
317 # rft.user and rft.password
318
319 # 1st get serviceRoot
320 svcRoot=RfServiceRoot()
321 rc,r,j,d = svcRoot.getServiceRoot(rft)
322 if( rc != 0 ):
323 rft.printErr("SessionService: login: Error getting service root, aborting")
324 return(rc,r,False,None)
325
326 #call rfSessionLogin in transport class to login
327 rc,r,j,d=rft.rfSessionLogin(rft,cleanupOnExit=False)
328 if(rc == 0):
329 # return sessionId and authToken
330 respData={"SessionId": rft.sessionId, "SessionLocation": rft.sessionLink, "X-Auth-Token": rft.authToken}
331 rft.printVerbose(1," SessionLogin: {}".format(respData, skip1=True, printV12=cmdTop))
332 return(rc,r,j,respData)
333 else:
334 return(rc,r,j,d)
335
336
337 #SessionService -t<token> logout [-i<sessionId>|-l<sessionLink>], returns 204 no content
338 def sessionLogout(self,sc,op,rft,cmdTop=False, prop=None):
339 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
340
341 if( (rft.linkLevel2 is None) and( rft.IdLevel2 is None) ):
342 rft.printErr("Error, logout: no sessionId or sessionLink specified")
343 rft.printErr("Syntax: {} [options] [SessionService] logout [-i<sessionId> | -l <sessionLink>]".format(rft.program))
344 return(8,None,False,None)
345
346 # 1st get serviceRoot
347 svcRoot=RfServiceRoot()
348 rc,r,j,d = svcRoot.getServiceRoot(rft)
349 if( rc != 0 ):
350 rft.printErr("SessionService: login: Error getting service root, aborting")
351 return(rc,r,False,None)
352
353 #find Sessions collection
354 if( ("Links" in d) and ("Sessions" in d["Links"]) and ("@odata.id" in d["Links"]["Sessions"]) ):
355 sessionsLink=rft.rootResponseDict["Links"]["Sessions"]["@odata.id"]
356 #print("loginUri:{}".format(loginUri))
357 else:
358 rft.printErr("Error: the rootService response does not have a login link: \"Links\":\"Sessions\":{{\"@odata.id\": <uri>}")
359 return(4,None,False,None)
360
361 # get the Sessions collection
362 rc,r,j,d=rft.rftSendRecvRequest(rft.AUTHENTICATED_API, 'GET', r.url, relPath=sessionsLink, prop=prop)
363 if(rc != 0):
364 rft.printErr("Error: logout: cant read sessions collection")
365 return(6,None,False,None)
366 # now search for 2nd level resource and return
367 path2,rc,r,j,d=rft.getLevel2ResourceById(rft,r,d)
368 if(rc!=0):
369 rft.printErr("Error: the specified sessionId or sessionLink was not a valid Sessions collection entry")
370 return(rc,r,j,d)
371
372 #path2 is the path the the session we want to delete
373 rc,r,j,d=rft.rfSessionDelete(rft,sessionLink=path2)
374 if(rc!=0):
375 rft.printErr("Error: Logout: the session delete failed")
376 return(rc,r,j,d)
377 else:
378 rft.printVerbose(1," SessionLogout successful".format(skip1=True, printV12=cmdTop))
379 return(rc,r,j,d)
380
381
382
383
384 def examples(self,sc,op,rft,cmdTop=False,prop=None):
385 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
386 print(" {} -r<ip> SessionService # gets the sessionService".format(rft.program))
387 print(" {} -r<ip> SessionService setSessionTimeout <timeout> # sets the session timeout property".format(rft.program))
388 print(" {} -r<ip> SessionService Sessions # gets Sessions collection".format(rft.program))
389 print(" {} -r<ip> SessionService Sessions -l<sessUrl> # gets the session at URI=<sessUrl".format(rft.program))
390 print(" {} -r<ip> SessionService Sessions -i<sessId> # gets the session with session Id <sessId>".format(rft.program))
391 print(" {} -r<ip> SessionService patch {{A: B,C: D,...}} # patch the json-formatted {{prop: value...}} data to the sessionService object".format(rft.program))
392 print(" {} -r<ip> SessionService login <usernm> <passwd> # login (create session)".format(rft.program))
393 print(" {} -r<ip> SessionService logout <sessionId> # logout (delete session <sessId>".format(rft.program))
394 return(0,None,False,None)
395
396
397
398 '''
399 TODO:
400 1. e
401
402 '''
403
404
405
406