Debian Codegraph @

redfishtoollib/raw.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: rawMain.py
6 #
7 # contains raw subCommands and access functions
8 #
9 # Class RfRawMain
10 # - functions init, displayUsage, displayHelp, displayOperations,
11 # - runOperation - raw subcommand table, dispatch of operations: get, patch, post..
12 # - RfRawMain - called from redfishMain, enforce legal option combinations,
13 # and call runOperation to run System operation (sub-sub-command)
14 #
15 # Class RfRawOperations
16 # All of the Systems sub-command operations eg: Systems reset, setIndicatorLed, etc
17 # - hello - test cmd
18 # - httpGet -- send GET method
19 # - httpPatch -- send GET method
20 # - httpPost -- send GET method
21 # - httpDelete -- send GET method
22 # - httpHead -- send GET method
23 # - httpPut -- send GET method (not implemented in 0.9)
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, urlparse, urlunparse
34
35 class RfRawMain():
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] raw <method> <path> ".format(rft.program))
47 print("")
48 print(" {} raw -h # for help".format(rft.program))
49 print(" {} raw examples #for example commands".format(rft.program))
50 print("")
51 print(" <method> is one of: GET, PATCH, POST, DELETE, HEAD, PUT")
52 print(" <path> is full URI path to a redfish resource--the full path following <ipaddr:port>, starting with forward slash /")
53 print("")
54 print(" Common OPTNS:")
55 print(" -u <user>, --user=<usernm> -- username used for remote redfish authentication")
56 print(" -p <passwd>, --password=<passwd> -- password used for remote redfish authentication")
57 print(" -t <token>, --token=<token> - redfish auth session token-for sessions across multiple calls")
58 print("")
59 print(" -r <rhost>, --rhost=<rhost> -- remote redfish service hostname or IP:port")
60 print(" -X <method> --request=<method> -- the http method to use. <method>={GET,PATCH,POST,DELETE,HEAD,PUT}. Default=GET")
61 print(" -d <data> --data=<data> -- the http request \"data\" to send on PATCH,POST,or PUT requests")
62 print(" -H <hdrs>, --Headers=<hdrs> -- Specify the request header list--overrides defaults. Format \"{ A:B, C:D...}\" ")
63 print(" -S <Secure>, --Secure=<Secure> -- When to use https: (Note: doesn't stop rhost from redirect http to https)")
64
65
66 def displayHelp(self,rft):
67 self.displayUsage(rft)
68 self.displayOperations(rft)
69 print("")
70
71 def displayOperations(self,rft):
72 print(" <operations / methods>:")
73 print(" GET -- HTTP GET method")
74 print(" PATCH -- HTTP PATCH method")
75 print(" POST -- HTTP POST method")
76 print(" DELETE -- HTTP DELETE method")
77 print(" HEAD -- HTTP HEAD method")
78 print(" PUT -- HTTP PUT method")
79 print(" examples -- example raw commands with syntax")
80 print(" hello -- raw hello -- debug command")
81 return(0)
82
83
84 def runOperation(self,rft):
85 # instantiate SystemsOperations class
86 op=RfRawOperations()
87
88 # dispatch table for each subcommand: "cmdName": cmdClass.cmdFunction"
89 operationTable = {
90 "GET": op.httpGet,
91 "PATCH": op.httpPatch,
92 "POST": op.httpPost,
93 "DELETE": op.httpDelete,
94 "HEAD": op.httpHead,
95 "PUT": op.httpPut,
96 "hello": op.hello,
97 "examples": op.examples
98 }
99
100 rft.printVerbose(5,"raw: runOperation: operation: {}".format(self.operation))
101 rft.printVerbose(5,"raw:runOperation: args: {}".format(self.args))
102
103 if self.operation in operationTable:
104 rft.printVerbose(5,"raw:runOperation: found Oper: {} in table. executing".format(rft.subcommand))
105 rc,r,j,d=operationTable[self.operation](self, op, rft, cmdTop=True)
106 return(rc,r,j,d)
107
108 else: # invalid operation
109 rft.printErr("raw: Invalid operation: {}".format(self.operation))
110 return(2,None,False,None)
111
112
113
114 def RawMain(self,rft,cmdTop=False):
115 rft.printVerbose(4,"RawMain: subcommand: {}".format(rft.subcommand))
116
117 if( rft.help ):
118 self.displayHelp(rft)
119 return(2,None,False,None)
120
121 args=rft.subcommandArgv[0:]
122
123 # if 2 args, only operations are: hello and examples
124 nonMethodOperations=("hello","examples")
125 if( len(args)==2):
126 nonMethodOp=args[1]
127 if( not nonMethodOp in nonMethodOperations):
128 rft.printErr("Syntax error: \"raw\" subcommands require 2 arguments\n")
129 rft.printErr("")
130 self.displayHelp(rft)
131 return(2,None,False,None)
132 # else all operations require two args <method> <path>
133 elif( len(args) < 3 ):
134 rft.printErr("Syntax error: \"raw\" subcommands require 2 arguments\n")
135 self.displayHelp(rft)
136 return(2,None,False,None)
137
138 self.operation=args[1] # for raw subcommand, this is the http method (eg GET)
139 self.args = args[1:] # now args points to the 1st argument
140 self.argnum =len(self.args)
141
142 rft.printVerbose(5,"raw: operation={}, args={}".format(self.operation,self.args))
143
144
145 # now execute the operation.
146 rc,r,j,d = self.runOperation(rft)
147
148 if(rc !=0 ):
149 rft.printVerbose(5,"raw: operation returned with error: rc={}".format(rc))
150 return(rc,r,False,None)
151
152 #else, if here, the subcommand executed without error. Return with 0 exit code
153 rft.printVerbose(5,"raw: operation exited OK")
154 return(rc,r,j,d)
155
156
157 #
158 # contains operations related to the Systems subCommand
159 #
160 class RfRawOperations():
161 def __init__(self):
162 self.systemsPath=None
163 self.systemsCollectionDict=None
164
165 # function to return API type: authenticated or unauthenticated
166 # authenticated APIs require authentication
167 # unauthenticated APIs are /redfish, /redfish/v1, /redfish/v1/odata, /redfish/v1/$metadata
168 def getApiType(self,rft,uri):
169 unauthenticatedAPIs=("/redfish", "/redfish/v1", "/redfish/v1/", "/redfish/v1/odata", "/redfish/v1/$metadata")
170 if not uri in unauthenticatedAPIs:
171 return( rft.AUTHENTICATED_API )
172 else:
173 return( rft.UNAUTHENTICATED_API )
174
175
176 def hello(self,sc,op,rft,cmdTop=False):
177 rft.printVerbose(4,"in hello")
178 rft.printVerbose(4," subcmd:{}, operation:{}, args:{}".format(rft.subcommand,sc.operation,sc.args))
179 print("hello world from raw subcommand")
180 return(0,None,False,None)
181
182
183 def httpGet(self,sc,op,rft,cmdTop=False, prop=None):
184 rft.printVerbose(4,"{}:{}: in raw".format(rft.subcommand,sc.operation))
185
186 # we verified that we had two args in RawMain(), so we can just read the <uri> arg here
187 path=sc.args[1]
188 method="GET"
189 rft.printVerbose(4,"raw: GET: method:{} path:{}".format(method,path))
190
191 apiType=self.getApiType(rft,path) # UNAUTHENTICATED API or Authenticated API
192
193 # calculate rootUrl--with correct scheme, root path, and rhost IP (w/o querying rhost)
194 scheme=rft.getApiScheme(apiType)
195 scheme_tuple=[scheme, rft.rhost, "/redfish", "","",""]
196 rootUrl=urlunparse(scheme_tuple) # so rootUrl="http[s]://<rhost>[:<port>]/redfish"
197
198 if cmdTop is True: prop=rft.prop
199 jsonData=True
200 if (path=="/redfish/v1/$metadata"): jsonData=False
201 rc,r,j,d=rft.rftSendRecvRequest(apiType, method, rootUrl, relPath=path, prop=prop,jsonData=jsonData)
202 if(rc==0):
203 rft.printVerbose(1," raw GET:",skip1=True, printV12=cmdTop)
204 return(rc,r,j,d)
205 else:
206 rft.printErr("raw: Error getting response")
207 return(rc,r,False,None)
208
209 def httpHead(self,sc,op,rft,cmdTop=False, prop=None):
210 rft.printVerbose(4,"{}:{}: in raw".format(rft.subcommand,sc.operation))
211
212 # we verified that we had two args in RawMain(), so we can just read the <uri> arg here
213 path=sc.args[1]
214 method="HEAD"
215 rft.printVerbose(4,"raw: HEAD: method:{} path:{}".format(method,path))
216
217 apiType=self.getApiType(rft,path) # UNAUTHENTICATED API or Authenticated API
218
219 # calculate rootUrl--with correct scheme, root path, and rhost IP (w/o querying rhost)
220 scheme=rft.getApiScheme(apiType)
221 scheme_tuple=[scheme, rft.rhost, "/redfish", "","",""]
222 rootUrl=urlunparse(scheme_tuple) # so rootUrl="http[s]://<rhost>[:<port>]/redfish"
223
224 rc,r,j,d=rft.rftSendRecvRequest(apiType, method, rootUrl, relPath=path)
225 if(rc==0):
226 rft.printVerbose(1," raw HEAD:",skip1=True, printV12=cmdTop)
227 return(rc,r,False,None)
228 else:
229 rft.printErr("raw: Error getting response")
230 return(rc,r,False,None)
231
232
233
234
235 def httpPatch(self,sc,op,rft,cmdTop=False, prop=None):
236 rft.printVerbose(4,"{}:{}: in raw".format(rft.subcommand,sc.operation))
237
238 # load patch data--verify its good json
239 # get the patchData from rft.requestData readin on commandline via: -d <patchData>
240 try:
241 patchData=json.loads(rft.requestData)
242 except ValueError:
243 rft.printErr("Patch: invalid Json input data:{}".format(rft.requestData))
244 return(5,None,False,None)
245 ##print("patchData: {}".format(patchData))
246
247
248 # we verified that we had two args in RawMain(), so we can just read the <uri> arg here
249 path=sc.args[1]
250 method="PATCH"
251 rft.printVerbose(4,"raw: PATCH: method:{} path:{}".format(method,path))
252
253 apiType=self.getApiType(rft,path) # UNAUTHENTICATED API or Authenticated API
254
255 # calculate rootUrl--with correct scheme, root path, and rhost IP (w/o querying rhost)
256 scheme=rft.getApiScheme(apiType)
257 scheme_tuple=[scheme, rft.rhost, "/redfish", "","",""]
258 rootUrl=urlunparse(scheme_tuple) # so rootUrl="http[s]://<rhost>[:<port>]/redfish"
259
260 #read the resource--the generic patch command needs it to get the etag
261 rc,r,j,d=rft.rftSendRecvRequest(apiType, "GET", rootUrl, relPath=path)
262 if(rc!=0):
263 rft.printErr("raw: Error getting resource prior to patching it, aborting")
264 return(rc,r,False,None)
265
266 # now call the generic patch function to send the patch
267 rc,r,j,d=rft.patchResource(rft, r, patchData)
268
269 if(rc==0): rft.printVerbose(1," Systems Patch:",skip1=True, printV12=cmdTop)
270 return(rc,r,j,d)
271
272
273 def httpPost(self,sc,op,rft,cmdTop=False, prop=None):
274 rft.printVerbose(4,"{}:{}: in raw".format(rft.subcommand,sc.operation))
275
276 # load post data--verify its good json
277 # get the postData from rft.requestData readin on commandline via: -d <patchData>
278 try:
279 postData=json.loads(rft.requestData)
280 except ValueError:
281 rft.printErr("Post: invalid Json input data:{}".format(rft.requestData))
282 return(5,None,False,None)
283 ##print("postData: {}".format(postData))
284
285 # we verified that we had two args in RawMain(), so we can just read the <uri> arg here
286 path=sc.args[1]
287 method="POST"
288 rft.printVerbose(4,"raw: POST: method:{} path:{}".format(method,path))
289
290 apiType=self.getApiType(rft,path) # UNAUTHENTICATED API or Authenticated API
291
292 # calculate rootUrl--with correct scheme, root path, and rhost IP (w/o querying rhost)
293 scheme=rft.getApiScheme(apiType)
294 scheme_tuple=[scheme, rft.rhost, "/redfish", "","",""]
295 rootUrl=urlunparse(scheme_tuple) # so rootUrl="http[s]://<rhost>[:<port>]/redfish"
296
297 #output the post data in json to send over the network
298 reqPostData=json.dumps(postData)
299 #Post the data
300 rc,r,j,d=rft.rftSendRecvRequest(apiType, method, rootUrl, relPath=path, reqData=reqPostData)
301 if(rc!=0):
302 rft.printErr("raw: Error sending POST to resource, aborting")
303 return(rc,r,False,None)
304
305
306 if(rc==0): rft.printVerbose(1," raw POST:",skip1=True, printV12=cmdTop)
307 return(rc,r,j,d)
308
309
310 def httpPut(self,sc,op,rft,cmdTop=False, prop=None):
311 rft.printVerbose(4,"{}:{}: in raw".format(rft.subcommand,sc.operation))
312
313 # load put data--verify its good json
314 # get the postData from rft.requestData readin on commandline via: -d <patchData>
315 try:
316 putData=json.loads(rft.requestData)
317 except ValueError:
318 rft.printErr("Put: invalid Json input data:{}".format(rft.requestData))
319 return(5,None,False,None)
320 ##print("postData: {}".format(postData))
321
322 # we verified that we had two args in RawMain(), so we can just read the <uri> arg here
323 path=sc.args[1]
324 method="PUT"
325 rft.printVerbose(4,"raw: POST: method:{} path:{}".format(method,path))
326
327 apiType=self.getApiType(rft,path) # UNAUTHENTICATED API or Authenticated API
328
329 # calculate rootUrl--with correct scheme, root path, and rhost IP (w/o querying rhost)
330 scheme=rft.getApiScheme(apiType)
331 scheme_tuple=[scheme, rft.rhost, "/redfish", "","",""]
332 rootUrl=urlunparse(scheme_tuple) # so rootUrl="http[s]://<rhost>[:<port>]/redfish"
333
334 #output the post data in json to send over the network
335 reqPutData=json.dumps(putData)
336 #Put the data
337 rc,r,j,d=rft.rftSendRecvRequest(apiType, method, rootUrl, relPath=path, reqData=reqPutData)
338 if(rc!=0):
339 rft.printErr("raw: Error sending PUT to resource, aborting")
340 return(rc,r,False,None)
341
342
343 if(rc==0): rft.printVerbose(1," raw PUT:",skip1=True, printV12=cmdTop)
344 return(rc,r,j,d)
345
346
347 def httpDelete(self,sc,op,rft,cmdTop=False, prop=None):
348 rft.printVerbose(4,"{}:{}: in raw".format(rft.subcommand,sc.operation))
349
350 # we verified that we had two args in RawMain(), so we can just read the <uri> arg here
351 path=sc.args[1]
352 method="DELETE"
353 rft.printVerbose(4,"raw: DELETE: method:{} path:{}".format(method,path))
354
355 apiType=self.getApiType(rft,path) # UNAUTHENTICATED API or Authenticated API
356
357 # calculate rootUrl--with correct scheme, root path, and rhost IP (w/o querying rhost)
358 scheme=rft.getApiScheme(apiType)
359 scheme_tuple=[scheme, rft.rhost, "/redfish", "","",""]
360 rootUrl=urlunparse(scheme_tuple) # so rootUrl="http[s]://<rhost>[:<port>]/redfish"
361
362 #send DELETE to the resource path specified
363 rc,r,j,d=rft.rftSendRecvRequest(apiType, method, rootUrl, relPath=path)
364 if(rc!=0):
365 rft.printErr("raw: Error sending DELETE to resource, aborting")
366 return(rc,r,False,None)
367
368
369 if(rc==0): rft.printVerbose(1," raw DELETE:",skip1=True, printV12=cmdTop)
370 return(rc,r,j,d)
371
372
373 def examples(self,sc,op,rft,cmdTop=False,prop=None):
374 rft.printVerbose(4,"{}:{}: in operation".format(rft.subcommand,sc.operation))
375 print(" {} -r<ip> raw GET /redfish/v1/ # returns the root collection".format(rft.program))
376
377 return(0,None,False,None)
378
379
380
381
382 '''
383 TODO:
384 1. need to handle case where no patch or post data (no -d)
385 2. add raw PUT
386 CHANGES:
387 0.9.2: no longer call /redfish and /redfish/v1 before executing the raw api
388 '''
389
390
391
392