# Copyright Notice: # Copyright 2016 DMTF. All rights reserved. # License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfishtool/blob/master/LICENSE.md # redfishtool: redfishtool.py Main # # contains: # - functions called for usage: # -- displayUsage, displayOptions, listSubcommands, displayHelp # - Main routine, with argc/argv option parsing, and valid argument/option checking # after parsing options, runs cmd with runSubCmd function, outputs result, cleansup sessions created # - runSubCmd -- Main subcommand command table and subcommand execution # - hello subcommand for testing # - help subcommand # - about subcommand for info about this version of redfishtool # import sys import getopt import re import json import os from .redfishtoolTransport import RfTransport from .ServiceRoot import RfServiceRoot from .Systems import RfSystemsMain from .Chassis import RfChassisMain from .Managers import RfManagersMain from .SessionService import RfSessionServiceMain from .AccountService import RfAccountServiceMain from .raw import RfRawMain def displayUsage(rft,*argv,**kwargs): rft.printErr(" Usage:",noprog=True) rft.printErr(" {} [OPTIONS] []... ",prepend=" ") rft.printErr(" {} [OPTIONS] hmraw []", prepend=" ") def displayOptions(rft): print("") print(" Common OPTIONS:") print(" -V, --version -- show {} version, and exit".format(rft.program)) print(" -h, --help -- show Usage, Options, and list of subCommands, and exit".format(rft.program)) print(" -v, --verbose -- verbose level, can repeat up to 5 times for more verbose output") print(" -v(header), -vv(+addl info), -vvv(Request trace), -vvvv(+subCmd dbg), -vvvvv(max dbg)") print(" -s, --status -- status level, can repeat up to 5 times for more status output") print(" -s(http_status), ") print(" -ss(+r.url, +r.elapsed executionTime ), ") print(" -sss(+request hdrs,data,authType, +response status_code, +response executionTime, ") print(" +login auth token/sessId/sessUri)") print(" -ssss(+response headers), -sssss(+response data") print(" -u , --user= -- username used for remote redfish authentication") print(" -p , --password= -- password used for remote redfish authentication") print(" -r , --rhost= -- remote redfish service hostname or IP:port") print(" -t , --token= -- redfish auth session token-for sessions across multiple calls") print(" -q, --quiet -- quiet mode--suppress error, warning, and diagnostic messages") print(" -c ,--config= -- read options (including credentials) from file ") print(" -T ,--Timeout= -- timeout in seconds for each http request. Default=10") print("") print(" -P , --Prop= -- return only the specified property. Applies only to all \"get\" operations") print(" -E, --Entries -- Fetch the Logs entries. Applies to Logs sub-command of Systems, Chassis and Managers") print("") print(" Options used by \"raw\" subcommand:") print(" -d --data= -- the http request \"data\" to send on PATCH,POST,or PUT requests") print("") print(" Options to specify top-level collection members: eg: Systems -I ") print(" -I , --Id= -- Use to specify the collection member") print(" -M : --Match=:-- Use = search to find the collection member") print(" -F, --First -- Use the 1st link returned in the collection or 1st \"matching\" link if used with -M") print(" -1, --One -- Use the single link returned in the collection. Return error if more than one member exists") print(" -a, --all -- Returns all members if the operation is a Get on a top-level collection like Systems") print(" -L , --Link= -- Use (eg /redfish/v1/Systems/1) to reference the collection member. ") print(" -- If is not one of the links in the collection, and error is returned.") print(" Options to specify 2nd-level collection members: eg: Systems -I Processors -i") print(" -i , --id= -- use to specify the 2nd-level collection member") print(" -m : --match=:val>--use = search of 2nd-level collection to specify member") print(" -l --link= -- Use (eg /redfish/v1/SYstems/1/Processors/1) to reference a 2nd level resource") print(" -- A -I|M|F|1|L option is still required to specify the link to the top-lvl collection") print(" -a, --all -- Returns all members of the 2nd level collection if the operation is a Get on the ") print(" -- 2nd level collection (eg Processors). -I|M|F|1|L still specifies the top-lvl collection.") print("") print(" Additional OPTIONS:") print(" -W :, -- Send up to {GET /redfish} requests with TCP connection timeout") print(" --Wait=: -- before sending subcommand to rhost. Default is -W 1:3") print(" -A , --Auth -- Authentication type to use: Authn={None|Basic|Session} Default is Basic") print(" -S , --Secure= -- When to use https: (Note: doesn't stop rhost from redirect http to https)") print(" ={Always | IfSendingCredentials | IfLoginOrAuthenticatedApi(default) }") print(" -R , --RedfishVersion=-- The Major Redfish Protocol version to use: ver={v1(dflt), v, Latest}") print(" -C --CheckRedfishVersion -- tells Redfishtool to execute GET /redfish to verify that the rhost supports") print(" the specified redfish protocol version before executing a sub-command. ") print(" The -C flag is auto-set if the -R Latest or -W ... options are selected") print(" -N, --NonBlocking -- Do not wait for asynchronous requests to complete.") print(" -n, --no-proxy -- Ignore any PROXY environment variables.") print(" -H , --Headers= -- Specify the request header list--overrides defaults. Format \"{ A:B, C:D...}\" ") print(" -D , --Debug= -- Flag for dev debug. is a 32-bit uint: 0x or format") print("") def listSubcommands(rft): # print a list of Main subcommands in order to show them in lc subcommand print(" Subcommands:") print(" hello -- redfishtool hello world subcommand for dev testing") print(" about -- display version and other information about this version of {}".format(rft.program)) print(" versions -- get redfishProtocol versions supported by rhost: GET ^/redfish") print(" root | serviceRoot -- get serviceRoot resouce: GET ^/redfish/v1/") print(" Systems -- operations on Computer Systems in the /Systems collection ") print(" Chassis -- operations on Chassis in the /Chassis collection") print(" Managers -- operations on Managers in the /Managers collection") print(" AccountService -- operations on AccountService including user administration") print(" SessionService -- operations on SessionService including Session login/logout") print(" odata -- get the Odata Service document: GET ^/redfish/v1/odata") print(" metadata -- get the CSDL metadata document: GET ^/redfish/v1/$metadata") print(" raw -- subcommand to execute raw http methods(GET,PATCH,POST...) and URIs") return(0) def displayHelp(rft): displayUsage(rft,file=sys.stdout) displayOptions(rft) listSubcommands(rft) print("") print(" For Subcommand usage, options, operations, help:") print(" {} -h -- usage and options for specific subCommand".format(rft.program)) print("") def main(argv): #instantiate transport object which initializes default options rft=RfTransport() try: opts, args = getopt.gnu_getopt(argv[1:],"Vhvsqu:p:r:t:c:T:P:d:EI:M:F1L:i:m:l:aW:A:S:R:H:D:CNn", ["Version", "help", "verbose", "status", "quiet", "user=", "password=", "rhost=", "token=", "config=", "Timeout=", "Prop=", "data=", "Entries", "Id=", "Match=", "First", "One", "Link=", "id=", "match=", "link", "all", "Wait=", "Auth=","Secure=", "RedfishVersion=", "Headers=", "Debug=", "CheckRedfishVersion", "NonBlocking", "no-proxy"]) except getopt.GetoptError: rft.printErr("Error parsing options") displayUsage(rft) sys.exit(1) for opt, arg in opts: if opt in ("-h", "--help"): rft.help=True elif opt in ("-V", "--Version", "--version"): print("{} Version: {}".format(rft.program, rft.version)) sys.exit(0) elif opt in ("-v", "--verbose"): rft.verbose = min((rft.verbose+1), 5) elif opt in ("-s", "--status"): rft.status = min((rft.status+1), 5) elif opt in ("-q", "--quiet"): rft.quiet=True elif opt in ("-u", "--user"): rft.user=arg elif opt in ("-p", "--password"): rft.password=arg elif opt in ("-r", "--rhost"): rft.rhost=arg elif opt in ("-t", "--token"): #Redfish Session authentication token rft.token=arg rft.authToken=rft.token elif opt in ("-c", "--config"): #read additional options from a file rft.configFile=arg try: with open(arg, 'r') as f: configdata = json.load(f) if 'user' in configdata and 'password' in configdata: rft.user = configdata['user'] rft.password = configdata['password'] rft.printVerbose(1,"Main: get pw from configfile, usr:{}, pw:{}".format(rft.user, rft.password)) else: rft.printErr("Invalid --config= filedata: {}".format(configdata)) except IOError: rft.printErr("Invalid: Failed to read configfile") elif opt in ("-T", "--Timeout"): #Specify http timeout in seconds timePattern="^([1-9][0-9]*)$" timeMatch=re.search(timePattern,arg) if( timeMatch ): rft.timeout=int(arg) else: rft.printErr("Invalid -Timeout value: {}".format(arg)) rft.printErr(" Expect: -T where is a decimal int",noprog=True) sys.exit(1) # options that reference a specific property for Get operations elif opt in ("-P", "--Prop"): rft.prop=arg rft.gotPropOptn=True # options used by raw subcommand to specify http method (-X, --request) and request data (-d, --data) elif opt in ("-d", "--data"): rft.requestData=arg # options related to the Logs sub-command of Systems, Chassis and Managers elif opt in ("-E", "--Entries"): rft.gotEntriesOptn = True # options to find the Id or member of a collection in a subcommand elif opt in ("-I", "--Id"): rft.Id=arg rft.gotIdOptn=True rft.IdOptnCount+=1 elif opt in ("-M", "--Match"): # arg is of the form: ":" pair = arg.split(':', 1) if len(pair) == 2: rft.matchProp = pair[0] rft.matchValue = pair[1] rft.IdOptnCount += 1 rft.gotMatchOptn = True else: rft.printErr("Invalid --Match= option format: {}".format(arg)) rft.printErr(" Expect --Match=: Ex -M AssetTag:5555, -Match=AssetTag:5555",noprog=True) sys.exit(1) elif opt in ("-F", "--First"): rft.firstOptn=True rft.IdOptnCount+=1 elif opt in ("-1", "--One"): rft.oneOptn=True rft.IdOptnCount+=1 elif opt in ("-L", "--Link"): rft.Link=arg rft.gotIdOptn=True rft.IdOptnCount+=1 elif opt in ("-i", "--id"): rft.IdLevel2=arg rft.gotIdLevel2Optn=True rft.IdLevel2OptnCount+=1 elif opt in ("-m", "--match"): # arg is of the form: ":" pair = arg.split(':', 1) if len(pair) == 2: rft.matchLevel2Prop = pair[0] rft.matchLevel2Value = pair[1] rft.IdLevel2OptnCount += 1 rft.gotMatchLevel2Optn = True else: rft.printErr("Invalid level2 --match= option format: {}".format(arg)) rft.printErr(" Expect --match=: Ex -m ProcessorType:CPU, -match=ProcessorType:CPU",noprog=True) sys.exit(1) elif opt in ("-l", "--link"): rft.linkLevel2=arg rft.gotIdLevel2Optn=True rft.IdLevel2OptnCount+=1 elif opt in ("-a", "--all"): rft.allOptn=True # additional options rft.IdLevel2OptnCount+=1 elif opt in ("-W", "--Wait"): #specify how long to ping rhost before sending http requests 0=no ping # arg is of the form ":