iLO-manager first main commitgit status

This commit is contained in:
Jiří Stach committed 2026-02-03 15:56:53 +01:00
1 parent e6f4cc04ca
commit 599d8da562
3271 files changed
+550655

No files matched your search

@@ -0,0 +1,219 @@
###
# Copyright 2016-2021 Hewlett Packard Enterprise, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
# -*- coding: utf-8 -*-
"""RawDelete Command for rdmc"""
import sys
try:
from rdmc_helper import (
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
ReturnCodes,
)
except ImportError:
from ilorest.rdmc_helper import (
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
ReturnCodes,
)
class RawDeleteCommand:
"""Raw form of the delete command"""
def __init__(self):
self.ident = {
"name": "rawdelete",
"usage": None,
"description": "Run to to delete data from"
' the passed in path.\n\texample: rawdelete "/redfish/v1/'
'Sessions/(session ID)"\n',
"summary": "Raw form of the DELETE command.",
"aliases": [],
"auxcommands": [],
}
self.cmdbase = None
self.rdmc = None
self.auxcommands = dict()
def run(self, line, help_disp=False):
"""Main raw delete worker function
:param line: command line input
:type line: string.
:param help_disp: display help flag
:type line: bool.
"""
if help_disp:
self.parser.print_help()
return ReturnCodes.SUCCESS
try:
(options, args) = self.rdmc.rdmc_parse_arglist(self, line)
except (InvalidCommandLineErrorOPTS, SystemExit):
if ("-h" in line) or ("--help" in line):
return ReturnCodes.SUCCESS
else:
raise InvalidCommandLineErrorOPTS("")
headers = {}
if hasattr(options, "sessionid") and options.sessionid:
self.sessionvalidation(options)
else:
self.deletevalidation(options)
if options.path.startswith('"') and options.path.endswith('"'):
options.path = options.path[1:-1]
if options.expand:
options.path = options.path + "?$expand=."
try:
currentsess = self.rdmc.app.current_client.session_location
except:
currentsess = None
if options.headers:
extraheaders = options.headers.split(",")
for item in extraheaders:
header = item.split(":")
try:
headers[header[0]] = header[1]
except:
InvalidCommandLineError("Invalid format for --headers option.")
if currentsess and (options.path in currentsess):
self.rdmc.app.logout()
self.rdmc.ui.printer(
"Your session has been terminated (deleted).\nPlease log " "back in if you wish to continue.\n"
)
else:
returnresponse = False
if options.response or options.getheaders:
returnresponse = True
results = self.rdmc.app.delete_handler(
options.path,
headers=headers,
silent=options.silent,
service=options.service,
)
if returnresponse and results:
if options.getheaders:
self.rdmc.ui.print_out_json(dict(results.getheaders()))
if options.response:
sys.stdout.write(results.read)
self.rdmc.ui.printer("\n")
elif results.status == 404:
return ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION
elif results.status != 200:
return ReturnCodes.UI_CLI_USAGE_EXCEPTION
self.cmdbase.logout_routine(self, options)
# Return code
return ReturnCodes.SUCCESS
def deletevalidation(self, options):
"""Raw delete validation function
:param options: command line options
:type options: list.
"""
self.rdmc.login_select_validation(self, options, skipbuild=True)
def sessionvalidation(self, options):
"""Raw delete session validation function
:param options: command line options
:type options: list.
"""
url = None
if options.user or options.password or options.url:
if options.url:
url = options.url
else:
if self.rdmc.app.config.get_url():
url = self.rdmc.app.config.get_url()
if url and "https://" not in url:
url = "https://" + url
return url
def definearguments(self, customparser):
"""Wrapper function for new command main function
:param customparser: command line input
:type customparser: parser.
"""
if not customparser:
return
self.cmdbase.add_login_arguments_group(customparser)
customparser.add_argument(
"path",
help="Uri on iLO to be deleted.",
)
customparser.add_argument(
"--response",
dest="response",
action="store_true",
help="Use this flag to return the iLO response body.",
default=False,
)
customparser.add_argument(
"--getheaders",
dest="getheaders",
action="store_true",
help="Use this flag to return the iLO response headers.",
default=False,
)
customparser.add_argument(
"--headers",
dest="headers",
help="Use this flag to add extra headers to the request."
"\t\t\t\t\t Usage: --headers=HEADER:VALUE,HEADER:VALUE",
default=None,
)
customparser.add_argument(
"--silent",
dest="silent",
action="store_true",
help="""Use this flag to silence responses""",
default=False,
)
customparser.add_argument(
"--service",
dest="service",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
customparser.add_argument(
"--expand",
dest="expand",
action="store_true",
help="""Use this flag to expand the path specified using the """ """expand notation '?$expand=.'""",
default=False,
)
@@ -0,0 +1,322 @@
###
# Copyright 2016-2021 Hewlett Packard Enterprise, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
# -*- coding: utf-8 -*-
"""RawGet Command for rdmc"""
import json
import redfish
import requests
from urllib.parse import urljoin
import sys
try:
from rdmc_helper import (
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
ResourceNotReadyError,
ReturnCodes,
)
except ImportError:
from ilorest.rdmc_helper import (
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
ResourceNotReadyError,
ReturnCodes,
)
class RawGetCommand:
"""Raw form of the get command"""
def __init__(self):
self.ident = {
"name": "rawget",
"usage": None,
"description": "Run to to retrieve data from "
'the passed in path.\n\tExample: rawget "/redfish/v1/'
'systems/(system ID)"',
"summary": "Raw form of the GET command.",
"aliases": [],
"auxcommands": [],
}
self.cmdbase = None
self.rdmc = None
self.auxcommands = dict()
def run(self, line, help_disp=False):
"""Main raw get worker function
:param line: command line input
:type line: string.
:param help_disp: display help flag
:type line: bool.
"""
if help_disp:
self.parser.print_help()
return ReturnCodes.SUCCESS
try:
(options, _) = self.rdmc.rdmc_parse_arglist(self, line)
except (InvalidCommandLineErrorOPTS, SystemExit):
if ("-h" in line) or ("--help" in line):
return ReturnCodes.SUCCESS
else:
raise InvalidCommandLineErrorOPTS("")
headers = {}
if getattr(options, "no_auth"):
pass
else:
if hasattr(options, "sessionid") and options.sessionid:
_ = self.sessionvalidation(options)
else:
self.getvalidation(options)
if options.path.endswith("?=."):
path = options.path
strip = path[:-3]
options.path = strip + "?$expand=."
if options.path.startswith('"') and options.path.endswith('"'):
options.path = options.path[1:-1]
if options.expand:
options.path = options.path + "?$expand=."
if options.headers:
extraheaders = options.headers.split(",")
for item in extraheaders:
header = item.split(":")
try:
headers[header[0]] = header[1]
except:
InvalidCommandLineError("Invalid format for --headers " "option.")
returnresponse = False
if options.response or options.getheaders:
returnresponse = True
extra_path = None
if "#" in options.path:
path_list = options.path.split("#")
options.path = path_list[0]
extra_path = path_list[1]
if "/" in extra_path:
extra_path_list = extra_path.split("/")
extra_path_list = list(filter(None, extra_path_list))
if getattr(options, "no_auth"):
if options.url:
url = "https://" + options.url.rstrip("/")
else:
url = "https://16.1.15.1"
path = urljoin(url, options.path.lstrip("/"))
try:
response = requests.get(path, verify=False)
if response.status_code == 200:
data = response.json()
self.rdmc.ui.printer("%s\n" % json.dumps(data, indent=4))
return ReturnCodes.SUCCESS
except Exception as e:
sys.stdout.write("Error: Failed to complete operation.\n")
return ReturnCodes.INVALID_COMMAND_LINE_ERROR
results = self.rdmc.app.get_handler(
options.path,
sessionid=options.sessionid,
headers=headers,
silent=options.silent,
service=options.service,
username=options.user,
password=options.password,
base_url=options.url,
noauth=options.no_auth,
stderr_flag=options.stderr_flag,
)
result = None
if results.dict:
if extra_path:
result = results.dict
for p in extra_path_list:
if p.isdigit():
p = int(p)
result = result[p]
else:
result = results.dict
if results and results.status == 200 and options.binfile:
output = results.read
filehndl = open(options.binfile[0], "wb")
filehndl.write(output)
filehndl.close()
elif results and returnresponse:
if options.getheaders:
self.rdmc.ui.printer(json.dumps(dict(results.getheaders())) + "\n")
if options.response:
self.rdmc.ui.printer(results.read + "\n")
elif results and results.status == 200:
if results.dict:
if options.filename:
output = json.dumps(
result,
indent=2,
cls=redfish.ris.JSONEncoder,
sort_keys=True,
)
filehndl = open(options.filename[0], "w")
filehndl.write(output)
filehndl.close()
self.rdmc.ui.printer("Results written out to '%s'.\n" % options.filename[0])
else:
if not result:
result = results.dict
if options.service:
self.rdmc.ui.printer("%s\n" % result)
else:
self.rdmc.ui.print_out_json(result)
else:
json_payload = json.loads(results._http_response.data)
try:
message_id = json_payload["error"]["@Message.ExtendedInfo"][0]["MessageId"]
self.rdmc.ui.error("%s" % message_id)
if "ResourceNotReadyRetry" in message_id:
raise ResourceNotReadyError("Resources are not ready in iLO, Please wait for some time and retry")
except:
self.rdmc.ui.error("An invalid or incomplete response was received: %s\n" % json_payload)
return ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION
self.cmdbase.logout_routine(self, options)
# Return code
return ReturnCodes.SUCCESS
def getvalidation(self, options):
"""Raw get validation function
:param options: command line options
:type options: list.
"""
self.rdmc.login_select_validation(self, options, skipbuild=True)
def sessionvalidation(self, options):
"""Raw patch session validation function
:param options: command line options
:type options: list.
"""
url = None
if options.user or options.password or options.url:
if options.url:
url = options.url
else:
if self.rdmc.app.redfishinst and self.rdmc.app.redfishinst.base_url:
url = self.rdmc.app.redfishinst.base_url
if url and "blobstore://" not in url and "https://" not in url:
url = "https://" + url
return url
def definearguments(self, customparser):
"""Wrapper function for new command main function
:param customparser: command line input
:type customparser: parser.
"""
if not customparser:
return
self.cmdbase.add_login_arguments_group(customparser)
customparser.add_argument(
"path",
help="Uri on iLO",
)
customparser.add_argument(
"--response",
dest="response",
action="store_true",
help="Use this flag to return the iLO response body.",
default=False,
)
customparser.add_argument(
"--getheaders",
dest="getheaders",
action="store_true",
help="Use this flag to return the iLO response headers.",
default=False,
)
customparser.add_argument(
"--headers",
dest="headers",
help="Use this flag to add extra headers to the request." " example: --headers=HEADER:VALUE,HEADER:VALUE",
default=None,
)
customparser.add_argument(
"--silent",
dest="silent",
action="store_true",
help="""Use this flag to silence responses""",
default=False,
)
customparser.add_argument(
"-f",
"--filename",
dest="filename",
help="""Write results to the specified file.""",
action="append",
default=None,
)
customparser.add_argument(
"-b",
"--writebin",
dest="binfile",
help="""Write the results to the specified file in binary.""",
action="append",
default=None,
)
customparser.add_argument(
"--service",
dest="service",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
customparser.add_argument(
"--expand",
dest="expand",
action="store_true",
help="""Use this flag to expand the path specified using the """ """expand notation '?$expand=.'""",
default=False,
)
customparser.add_argument(
"--no_auth",
dest="no_auth",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
customparser.add_argument(
"--stderr_out",
"--stderr_flag",
dest="stderr_flag",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
@@ -0,0 +1,148 @@
###
# Copyright 2016-2021 Hewlett Packard Enterprise, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
# -*- coding: utf-8 -*-
"""RawHead Command for rdmc"""
import json
import redfish
try:
from rdmc_helper import InvalidCommandLineErrorOPTS, ReturnCodes
except ImportError:
from ilorest.rdmc_helper import InvalidCommandLineErrorOPTS, ReturnCodes
class RawHeadCommand:
"""Raw form of the head command"""
def __init__(self):
self.ident = {
"name": "rawhead",
"usage": None,
"description": "Run to to retrieve data from the "
'passed in path\n\texample: rawhead "/redfish/v1/systems/'
'(system ID)"\n',
"summary": "Raw form of the HEAD command.",
"aliases": [],
"auxcommands": [],
}
self.cmdbase = None
self.rdmc = None
self.auxcommands = dict()
def run(self, line, help_disp=False):
"""Main raw head worker function
:param line: command line input
:type line: string.
:param help_disp: display help flag
:type line: bool.
"""
if help_disp:
self.parser.print_help()
return ReturnCodes.SUCCESS
try:
(options, _) = self.rdmc.rdmc_parse_arglist(self, line)
except (InvalidCommandLineErrorOPTS, SystemExit):
if ("-h" in line) or ("--help" in line):
return ReturnCodes.SUCCESS
else:
raise InvalidCommandLineErrorOPTS("")
self.headvalidation(options)
if options.path.startswith('"') and options.path.endswith('"'):
options.path = options.path[1:-1]
results = self.rdmc.app.head_handler(options.path, silent=options.silent, service=options.service)
content = None
tempdict = dict()
if results and results.status == 200:
if results._http_response:
content = results.getheaders()
else:
content = results._headers
tempdict = dict(content)
if options.filename:
output = json.dumps(tempdict, indent=2, cls=redfish.ris.JSONEncoder, sort_keys=True)
filehndl = open(options.filename[0], "w")
filehndl.write(output)
filehndl.close()
self.rdmc.ui.printer("Results written out to '%s'.\n" % options.filename[0])
else:
if options.service:
self.rdmc.ui.printer("%s\n" % tempdict)
else:
self.rdmc.ui.print_out_json(tempdict)
else:
return ReturnCodes.NO_CONTENTS_FOUND_FOR_OPERATION
self.cmdbase.logout_routine(self, options)
# Return code
return ReturnCodes.SUCCESS
def headvalidation(self, options):
"""Raw head validation function
:param options: command line options
:type options: list.
"""
self.rdmc.login_select_validation(self, options, skipbuild=True)
def definearguments(self, customparser):
"""Wrapper function for new command main function
:param customparser: command line input
:type customparser: parser.
"""
if not customparser:
return
self.cmdbase.add_login_arguments_group(customparser)
customparser.add_argument(
"path",
help="Uri on iLO to query HEAD.",
)
customparser.add_argument(
"--silent",
dest="silent",
action="store_true",
help="""Use this flag to silence responses""",
default=None,
)
customparser.add_argument(
"-f",
"--filename",
dest="filename",
help="""Use the provided filename to perform operations.""",
action="append",
default=None,
)
customparser.add_argument(
"--service",
dest="service",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
@@ -0,0 +1,264 @@
###
# Copyright 2016-2021 Hewlett Packard Enterprise, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
# -*- coding: utf-8 -*-
"""RawPatch Command for rdmc"""
import json
import re
import sys
from collections import OrderedDict
from urllib.parse import urljoin
import requests
try:
from rdmc_helper import (
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
InvalidFileFormattingError,
InvalidFileInputError,
ReturnCodes,
)
except ImportError:
from ilorest.rdmc_helper import (
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
InvalidFileFormattingError,
InvalidFileInputError,
ReturnCodes,
)
class RawPatchCommand:
"""Raw form of the patch command"""
def __init__(self):
self.ident = {
"name": "rawpatch",
"usage": None,
"description": "Run to send a patch from the data"
" in the input file.\n\tMultiple PATCHes can be performed in sequence by "
"\n\tadding more path/body key/value pairs.\n"
"\n\texample: rawpatch rawpatch.txt"
'\n\n\tExample input file:\n\t{\n\t "/redfish/'
'v1/systems/(system ID)":\n\t {\n\t '
'"AssetTag": "NewAssetTag"\n\t }\n\t}',
"summary": "Raw form of the PATCH command.",
"aliases": [],
"auxcommands": [],
}
self.cmdbase = None
self.rdmc = None
self.auxcommands = dict()
def run(self, line, help_disp=False):
"""Main raw patch worker function
:param line: command line input
:type line: string.
:param help_disp: display help flag
:type line: bool.
"""
if help_disp:
self.parser.print_help()
return ReturnCodes.SUCCESS
try:
(options, _) = self.rdmc.rdmc_parse_arglist(self, line)
except (InvalidCommandLineErrorOPTS, SystemExit):
if ("-h" in line) or ("--help" in line):
return ReturnCodes.SUCCESS
else:
raise InvalidCommandLineErrorOPTS("")
headers = {}
results = []
if getattr(options, "no_auth"):
pass
else:
if hasattr(options, "sessionid") and options.sessionid:
_ = self.sessionvalidation(options)
else:
self.patchvalidation(options)
contentsholder = None
try:
with open(options.path, "r") as _if:
contentsholder = json.loads(_if.read(), object_pairs_hook=OrderedDict)
except IOError:
raise InvalidFileInputError(
"File '%s' doesn't exist. " "Please create file by running 'save' command." % options.path
)
except ValueError:
raise InvalidFileFormattingError("Input file '%s' was not " "formatted properly." % options.path)
if options.headers:
extraheaders = options.headers.split(",")
for item in extraheaders:
header = item.split(":")
try:
headers[header[0]] = header[1]
except:
raise InvalidCommandLineError("Invalid format for --headers option.")
if getattr(options, "no_auth"):
if options.url:
url = "https://" + options.url.rstrip("/")
else:
url = "https://16.1.15.1"
path = urljoin(url, contentsholder["path"].lstrip("/"))
body = contentsholder["body"]
try:
response = requests.patch(path, json=body, verify=False)
if response.status_code == 200:
sys.stdout.write(response.content.decode("utf-8") + "\n")
return ReturnCodes.SUCCESS
except Exception as e:
sys.stdout.write("Error: Failed to complete operation.\n")
return ReturnCodes.INVALID_COMMAND_LINE_ERROR
if "path" in contentsholder and "body" in contentsholder:
results.append(
self.rdmc.app.patch_handler(
contentsholder["path"],
contentsholder["body"],
headers=headers,
silent=options.silent,
optionalpassword=options.biospassword,
service=options.service,
noauth=options.no_auth,
)
)
elif all([re.match(r"^/(\S+/?)+$", key) for key in contentsholder]):
for path, body in contentsholder.items():
results.append(
self.rdmc.app.patch_handler(
path,
body,
headers=headers,
silent=options.silent,
optionalpassword=options.biospassword,
service=options.service,
noauth=options.no_auth,
)
)
else:
raise InvalidFileFormattingError("Input file '%s' was not format properly." % options.path)
returnresponse = False
if options.response or options.getheaders:
returnresponse = True
if results and returnresponse:
for result in results:
if options.getheaders:
self.rdmc.ui.print_out_json(dict(result.getheaders()))
if options.response:
self.rdmc.ui.printer(result.read)
self.rdmc.ui.printer("\n")
self.cmdbase.logout_routine(self, options)
# Return code
return ReturnCodes.SUCCESS
def patchvalidation(self, options):
"""Raw patch validation function
:param options: command line options
:type options: list.
"""
self.rdmc.login_select_validation(self, options, skipbuild=True)
def sessionvalidation(self, options):
"""Raw patch session validation function
:param options: command line options
:type options: list.
"""
url = None
if options.user or options.password or options.url:
if options.url:
url = options.url
else:
if self.rdmc.app.redfishinst.base_url:
url = self.rdmc.app.redfishinst.base_url
if url and "https://" not in url:
url = "https://" + url
return url
def definearguments(self, customparser):
"""Wrapper function for new command main function
:param customparser: command line input
:type customparser: parser.
"""
if not customparser:
return
self.cmdbase.add_login_arguments_group(customparser)
customparser.add_argument(
"path",
help="Path to the JSON file containing the data to be patched.",
)
customparser.add_argument(
"--silent",
dest="silent",
action="store_true",
help="""Use this flag to silence responses""",
default=False,
)
customparser.add_argument(
"--response",
dest="response",
action="store_true",
help="Use this flag to return the iLO response body.",
default=False,
)
customparser.add_argument(
"--getheaders",
dest="getheaders",
action="store_true",
help="Use this flag to return the iLO response headers.",
default=False,
)
customparser.add_argument(
"--headers",
dest="headers",
help="Use this flag to add extra headers to the request."
"\t\t\t\t\t Usage: --headers=HEADER:VALUE,HEADER:VALUE",
default=None,
)
customparser.add_argument(
"--service",
dest="service",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
customparser.add_argument(
"--no_auth",
dest="no_auth",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
@@ -0,0 +1,276 @@
###
# Copyright 2016-2021 Hewlett Packard Enterprise, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
# -*- coding: utf-8 -*-
"""RawPost Command for rdmc"""
import json
import re
import sys
from collections import OrderedDict
import requests
from urllib.parse import urljoin
try:
from rdmc_helper import (
Encryption,
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
InvalidFileFormattingError,
InvalidFileInputError,
ReturnCodes,
)
except ImportError:
from ilorest.rdmc_helper import (
Encryption,
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
InvalidFileFormattingError,
InvalidFileInputError,
ReturnCodes,
)
class RawPostCommand:
"""Raw form of the post command"""
def __init__(self):
self.ident = {
"name": "rawpost",
"usage": None,
"description": "Run to send a post from "
"the data in the input file.\n\tMultiple POSTs can be performed in sequence by"
" \n\tadding more path/body key/value pairs.\n"
"\n\texample: rawpost rawpost."
'txt\n\n\tExample input file:\n\t{\n\t "/'
"redfish/v1/systems/(system ID)/Actions/ComputerSystem."
'Reset":\n\t {\n\t "ResetType": '
'"ForceRestart"\n\t }\n\t}',
"summary": "Raw form of the POST command.",
"aliases": [],
"auxcommands": [],
}
self.cmdbase = None
self.rdmc = None
self.auxcommands = dict()
def run(self, line, help_disp=False):
"""Main raw patch worker function
:param line: command line input
:type line: string.
:param help_disp: display help flag
:type line: bool.
"""
if help_disp:
self.parser.print_help()
return ReturnCodes.SUCCESS
try:
(options, _) = self.rdmc.rdmc_parse_arglist(self, line)
except (InvalidCommandLineErrorOPTS, SystemExit):
if ("-h" in line) or ("--help" in line):
return ReturnCodes.SUCCESS
else:
raise InvalidCommandLineErrorOPTS("")
headers = {}
results = []
if getattr(options, "no_auth"):
pass
else:
if hasattr(options, "sessionid") and options.sessionid:
self.sessionvalidation(options)
else:
self.postvalidation(options)
contentsholder = None
try:
with open(options.path, "r") as _if:
contentsholder = json.loads(_if.read(), object_pairs_hook=OrderedDict)
except IOError:
raise InvalidFileInputError(
"File '%s' doesn't exist. " "Please create file by running 'save' command." % options.path
)
except ValueError:
raise InvalidFileFormattingError("Input file '%s' was not " "formatted properly." % options.path)
if options.encode:
if (
"body" in contentsholder
and "UserName" in contentsholder["body"]
and "Password" in contentsholder["body"]
and len(list(contentsholder["body"].keys())) == 2
):
encobj = Encryption()
contentsholder["body"]["UserName"] = encobj.decode_credentials(contentsholder["body"]["UserName"])
contentsholder["body"]["Password"] = encobj.decode_credentials(contentsholder["body"]["Password"])
if options.headers:
extraheaders = options.headers.split(",")
for item in extraheaders:
header = item.split(":")
try:
headers[header[0]] = header[1]
except:
raise InvalidCommandLineError("Invalid format for --headers option.")
if getattr(options, "no_auth"):
if options.url:
url = "https://" + options.url.rstrip("/")
else:
url = "https://16.1.15.1"
path = urljoin(url, contentsholder["path"].lstrip("/"))
body = contentsholder["body"]
try:
response = requests.post(path, json=body, verify=False)
if response.status_code == 200:
sys.stdout.write(response.content.decode("utf-8") + "\n")
# sys.stdout.write("Operation completed successfully.\n")
return ReturnCodes.SUCCESS
except Exception as e:
sys.stdout.write("Error: Failed to complete operation.\n")
return ReturnCodes.INVALID_COMMAND_LINE_ERROR
if "path" in contentsholder and "body" in contentsholder:
results.append(
self.rdmc.app.post_handler(
contentsholder["path"],
contentsholder["body"],
headers=headers,
silent=options.silent,
service=options.service,
noauth=options.no_auth,
)
)
elif all([re.match(r"^/(\S+/?)+$", key) for key in contentsholder]):
for path, body in contentsholder.items():
results.append(
self.rdmc.app.post_handler(
path,
body,
headers=headers,
silent=options.silent,
service=options.service,
noauth=options.no_auth,
)
)
else:
raise InvalidFileFormattingError("Input file '%s' was not " "formatted properly." % options.path)
returnresponse = False
if options.response or options.getheaders:
returnresponse = True
if results and returnresponse:
for result in results:
if options.getheaders:
self.rdmc.ui.print_out_json(dict(result.getheaders()))
if options.response:
if isinstance(result.ori, bytes):
self.rdmc.ui.printer(result.ori.decode("utf-8") + "\n")
else:
self.rdmc.ui.printer(result.ori + "\n")
self.cmdbase.logout_routine(self, options)
# Return code
return ReturnCodes.SUCCESS
def postvalidation(self, options):
"""Raw post validation function
:param options: command line options
:type options: list.
"""
self.cmdbase.login_select_validation(self, options, skipbuild=True)
def sessionvalidation(self, options):
"""Raw post session validation function
:param options: command line options
:type options: list.
"""
url = None
if options.user or options.password or options.url:
if options.url:
url = options.url
else:
if self.rdmc.app.redfishinst.base_url:
url = self.rdmc.app.redfishinst.base_url
if url and "https://" not in url:
url = "https://" + url
return url
def definearguments(self, customparser):
"""Wrapper function for new command main function
:param customparser: command line input
:type customparser: parser.
"""
if not customparser:
return
self.cmdbase.add_login_arguments_group(customparser)
customparser.add_argument(
"path",
help="Path to the JSON file containing the data to be patched.",
)
customparser.add_argument(
"--response",
dest="response",
action="store_true",
help="Use this flag to return the iLO response body.",
default=False,
)
customparser.add_argument(
"--getheaders",
dest="getheaders",
action="store_true",
help="Use this flag to return the iLO response headers.",
default=False,
)
customparser.add_argument(
"--headers",
dest="headers",
help="Use this flag to add extra headers to the request."
"\t\t\t\t\t Usage: --headers=HEADER:VALUE,HEADER:VALUE",
default=None,
)
customparser.add_argument(
"--silent",
dest="silent",
action="store_true",
help="""Use this flag to silence responses""",
default=False,
)
customparser.add_argument(
"--service",
dest="service",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
customparser.add_argument(
"--no_auth",
dest="no_auth",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
@@ -0,0 +1,268 @@
###
# Copyright 2016-2021 Hewlett Packard Enterprise, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
# -*- coding: utf-8 -*-
"""RawPut Command for rdmc"""
import json
import re
import sys
from collections import OrderedDict
from urllib.parse import urljoin
import requests
try:
from rdmc_helper import (
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
InvalidFileFormattingError,
InvalidFileInputError,
ReturnCodes,
)
except ImportError:
from ilorest.rdmc_helper import (
InvalidCommandLineError,
InvalidCommandLineErrorOPTS,
InvalidFileFormattingError,
InvalidFileInputError,
ReturnCodes,
)
class RawPutCommand:
"""Raw form of the put command"""
def __init__(self):
self.ident = {
"name": "rawput",
"usage": None,
"description": "Run to send a post from "
"the data in the input file.\n\tMultiple PUTs can be performed in sequence by "
"\n\tadding more path/body key/value pairs.\n"
"\n\texample: rawput rawput."
'txt\n\n\tExample input file:\n\t{\n\t "/redfish/'
'v1/systems/(system ID)/bios/Settings/":\n\t {\n\t'
'\t"Attributes": {\n\t\t'
' "BaseConfig": "default"\n\t\t}\n\t }\n\t}',
"summary": "Raw form of the PUT command.",
"aliases": [],
"auxcommands": [],
}
self.cmdbase = None
self.rdmc = None
self.auxcommands = dict()
def run(self, line, help_disp=False):
"""Main raw put worker function
:param line: command line input
:type line: string.
:param help_disp: display help flag
:type line: bool.
"""
if help_disp:
self.parser.print_help()
return ReturnCodes.SUCCESS
try:
(options, args) = self.rdmc.rdmc_parse_arglist(self, line)
except (InvalidCommandLineErrorOPTS, SystemExit):
if ("-h" in line) or ("--help" in line):
return ReturnCodes.SUCCESS
else:
raise InvalidCommandLineErrorOPTS("")
headers = {}
results = []
if hasattr(options, "sessionid") and options.sessionid:
self.sessionvalidation(options)
else:
self.putvalidation(options)
contentsholder = None
try:
with open(options.path, "r") as _if:
contentsholder = json.loads(_if.read(), object_pairs_hook=OrderedDict)
except IOError:
raise InvalidFileInputError(
"File '%s' doesn't exist. " "Please create file by running 'save' command." % options.path
)
except ValueError:
raise InvalidFileFormattingError("Input file '%s' was not " "formatted properly." % options.path)
if options.headers:
extraheaders = options.headers.split(",")
for item in extraheaders:
header = item.split(":")
try:
headers[header[0]] = header[1]
except:
raise InvalidCommandLineError("Invalid format for --headers option.")
if getattr(options, "no_auth"):
if options.url:
url = "https://" + options.url.rstrip("/")
else:
url = "https://16.1.15.1"
path = urljoin(url, contentsholder["path"].lstrip("/"))
body = contentsholder["body"]
try:
response = requests.put(path, json=body, verify=False)
if response.status_code == 200:
sys.stdout.write(response.content.decode("utf-8") + "\n")
# sys.stdout.write("Operation completed successfully.\n")
return ReturnCodes.SUCCESS
except Exception as e:
sys.stdout.write("Error: Failed to complete operation.\n")
return ReturnCodes.INVALID_COMMAND_LINE_ERROR
if "path" in contentsholder and "body" in contentsholder:
results.append(
self.rdmc.app.put_handler(
contentsholder["path"],
contentsholder["body"],
headers=headers,
silent=options.silent,
optionalpassword=options.biospassword,
service=options.service,
noauth=options.no_auth,
)
)
elif all([re.match(r"^/(\S+/?)+$", key) for key in contentsholder]):
for path, body in contentsholder.items():
results.append(
self.rdmc.app.put_handler(
path,
body,
headers=headers,
silent=options.silent,
optionalpassword=options.biospassword,
service=options.service,
noauth=options.no_auth,
)
)
else:
raise InvalidFileFormattingError("Input file '%s' was not " "formatted properly." % options.path)
returnresponse = False
if options.response or options.getheaders:
returnresponse = True
if results and returnresponse:
for result in results:
if options.getheaders:
sys.stdout.write(json.dumps(dict(result.getheaders())) + "\n")
if options.response:
if isinstance(result.read, bytes):
sys.stdout.write(result.read.decode("utf-8"))
else:
sys.stdout.write(result.read)
sys.stdout.write("\n")
self.cmdbase.logout_routine(self, options)
# Return code
return ReturnCodes.SUCCESS
def putvalidation(self, options):
"""Raw put validation function
:param options: command line options
:type options: list.
"""
self.rdmc.login_select_validation(self, options, skipbuild=True)
def sessionvalidation(self, options):
"""Raw put session validation function
:param options: command line options
:type options: list.
"""
url = None
if options.user or options.password or options.url:
if options.url:
url = options.url
else:
if getattr(self.rdmc.app.redfishinst, "base_url", False):
url = self.rdmc.app.redfishinst.base_url
if url and "https://" not in url:
url = "https://" + url
return url
def definearguments(self, customparser):
"""Wrapper function for new command main function
:param customparser: command line input
:type customparser: parser.
"""
if not customparser:
return
self.cmdbase.add_login_arguments_group(customparser)
customparser.add_argument(
"path",
help="Path to the JSON file containing the data to be patched.",
)
customparser.add_argument(
"--response",
dest="response",
action="store_true",
help="Use this flag to return the iLO response body.",
default=False,
)
customparser.add_argument(
"--getheaders",
dest="getheaders",
action="store_true",
help="Use this flag to return the iLO response headers.",
default=False,
)
customparser.add_argument(
"--headers",
dest="headers",
help="Use this flag to add extra headers to the request."
"\t\t\t\t\t Usage: --headers=HEADER:VALUE,HEADER:VALUE",
default=None,
)
customparser.add_argument(
"--silent",
dest="silent",
action="store_true",
help="""Use this flag to silence responses""",
default=False,
)
customparser.add_argument(
"--service",
dest="service",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)
customparser.add_argument(
"--no_auth",
dest="no_auth",
action="store_true",
help="""Use this flag to enable service mode and increase the function speed""",
default=False,
)