PEP8 fixes

This commit is contained in:
Uggla 2016-04-06 15:20:35 +02:00
parent 92d4aa880a
commit 2f40ce5d24
8 changed files with 134 additions and 104 deletions

View File

@ -6,13 +6,13 @@ from __future__ import print_function
from __future__ import division from __future__ import division
from __future__ import absolute_import from __future__ import absolute_import
from future import standard_library from future import standard_library
standard_library.install_aliases()
from builtins import str from builtins import str
import os import os
import sys import sys
import json import json
import redfish import redfish
standard_library.install_aliases()
# Get $HOME environment. # Get $HOME environment.
@ -52,46 +52,57 @@ print ("Redfish API version : %s \n" % remote_mgmt.get_api_version())
# Uncomment following line to reset the blade !!! # Uncomment following line to reset the blade !!!
# remote_mgmt.Systems.systems_dict["1"].reset_system() # remote_mgmt.Systems.systems_dict["1"].reset_system()
# TODO : create an attribute to link the managed system directly print("Bios version : {}\n".format(
# and avoid systems_dict["1"] remote_mgmt.Systems.systems_dict["1"].get_bios_version()))
# --> will be something like : print("Serial Number : {}\n".format(
# remote_mgmt.Systems.systems_dict["1"] = remote_mgmt.Systems.managed_system remote_mgmt.Systems.systems_dict["1"].get_serial_number()))
print("Power State : {}\n".format(
remote_mgmt.Systems.systems_dict["1"].get_power()))
print("Parameter 'SystemType' : {}\n".format(
remote_mgmt.Systems.systems_dict["1"].get_parameter("SystemType")))
print("Bios version : {}\n".format(remote_mgmt.Systems.systems_dict["1"].get_bios_version())) print("Get bios parameters : {}\n".format(
print("Serial Number : {}\n".format(remote_mgmt.Systems.systems_dict["1"].get_serial_number())) remote_mgmt.Systems.systems_dict["1"].bios.get_parameters()))
print("Power State : {}\n".format(remote_mgmt.Systems.systems_dict["1"].get_power())) print("Get boot parameters : {}\n".format(
print("Parameter 'SystemType' : {}\n".format(remote_mgmt.Systems.systems_dict["1"].get_parameter("SystemType"))) remote_mgmt.Systems.systems_dict["1"].bios.boot.get_parameters()))
print("Get bios parameters : {}\n".format(remote_mgmt.Systems.systems_dict["1"].bios.get_parameters())) # print("Get bios parameter 'AdminPhone' : {}\n".format(
print("Get boot parameters : {}\n".format(remote_mgmt.Systems.systems_dict["1"].bios.boot.get_parameters())) # remote_mgmt.Systems.systems_dict["1"].bios.get_parameter("AdminPhone")))
# print("Set bios parameter 'AdminPhone' to '' : {}\n".format(
# remote_mgmt.Systems.systems_dict["1"].bios.set_parameter("AdminPhone","")))
#print("Get bios parameter 'AdminPhone' : {}\n".format(remote_mgmt.Systems.systems_dict["1"].bios.get_parameter("AdminPhone"))) # Boot server with script
#print("Set bios parameter 'AdminPhone' to '' : {}\n".format(remote_mgmt.Systems.systems_dict["1"].bios.set_parameter("AdminPhone",""))) # remote_mgmt.Systems.systems_dict["1"].bios.set_parameter("Dhcpv4","Enabled")
remote_mgmt.Systems.systems_dict["1"].bios.set_parameter(
"PreBootNetwork", "Auto")
remote_mgmt.Systems.systems_dict["1"].bios.set_parameter(
"UefiShellStartup", "Enabled")
remote_mgmt.Systems.systems_dict["1"].bios.set_parameter(
"UefiShellStartupLocation", "NetworkLocation")
remote_mgmt.Systems.systems_dict["1"].bios.set_parameter(
"UefiShellStartupUrl", "http://10.3.222.88/deploy/startup.nsh")
#Boot server with script # remote_mgmt.Systems.systems_dict["1"].set_parameter_json(
#remote_mgmt.Systems.systems_dict["1"].bios.set_parameter("Dhcpv4","Enabled") # '{"Boot": {"BootSourceOverrideTarget": "UefiShell"}}')
# remote_mgmt.Systems.systems_dict["1"].set_parameter_json(
remote_mgmt.Systems.systems_dict["1"].bios.set_parameter("PreBootNetwork", "Auto") # '{"Boot": {"BootSourceOverrideEnabled" : "Continuous"}}')
remote_mgmt.Systems.systems_dict["1"].bios.set_parameter("UefiShellStartup", "Enabled") # remote_mgmt.Systems.systems_dict["1"].set_parameter_json(
remote_mgmt.Systems.systems_dict["1"].bios.set_parameter("UefiShellStartupLocation", "NetworkLocation") # '{"Boot": {"BootSourceOverrideEnabled" : "Once"}}')
remote_mgmt.Systems.systems_dict["1"].bios.set_parameter("UefiShellStartupUrl", "http://10.3.222.88/deploy/startup.nsh")
#remote_mgmt.Systems.systems_dict["1"].set_parameter_json('{"Boot": {"BootSourceOverrideTarget": "UefiShell"}}')
# remote_mgmt.Systems.systems_dict["1"].set_parameter_json('{"Boot": {"BootSourceOverrideEnabled" : "Continuous"}}')
#remote_mgmt.Systems.systems_dict["1"].set_parameter_json('{"Boot": {"BootSourceOverrideEnabled" : "Once"}}')
mySystem = remote_mgmt.Systems.systems_dict["1"] mySystem = remote_mgmt.Systems.systems_dict["1"]
mySystem.set_boot_source_override("None","Disabled") mySystem.set_boot_source_override("None", "Disabled")
#Uncomment the next line to reset the server # Uncomment the next line to reset the server
#mySystem.reset_system() # mySystem.reset_system()
print("Get manager firmware version : {}\n".format(remote_mgmt.Managers.managers_dict["1"].get_firmware_version())) print("Get manager firmware version : {}\n".format(
print("Get system Bios version : {}\n".format(remote_mgmt.Systems.systems_dict["1"].get_bios_version())) remote_mgmt.Managers.managers_dict["1"].get_firmware_version()))
print("Get system Bios version : {}\n".format(
remote_mgmt.Systems.systems_dict["1"].get_bios_version()))
#Reset of the system is required to apply the changes # Reset of the system is required to apply the changes
#remote_mgmt.Systems.systems_dict["1"].reset_system() # remote_mgmt.Systems.systems_dict["1"].reset_system()
remote_mgmt.logout() remote_mgmt.logout()

View File

@ -38,7 +38,6 @@ from __future__ import print_function
from __future__ import division from __future__ import division
from __future__ import absolute_import from __future__ import absolute_import
from future import standard_library from future import standard_library
standard_library.install_aliases()
from builtins import str from builtins import str
from builtins import object from builtins import object
@ -52,6 +51,7 @@ import configparser
import jinja2 import jinja2
import requests.packages.urllib3 import requests.packages.urllib3
import redfish import redfish
standard_library.install_aliases()
class InventoryFile(object): class InventoryFile(object):

View File

@ -17,10 +17,10 @@ from __future__ import print_function
from __future__ import division from __future__ import division
from __future__ import absolute_import from __future__ import absolute_import
from future import standard_library from future import standard_library
standard_library.install_aliases()
import pbr.version import pbr.version
from redfish.main import * from redfish.main import *
standard_library.install_aliases()
try: try:
__version__ = pbr.version.VersionInfo('redfish').release_string() __version__ = pbr.version.VersionInfo('redfish').release_string()

View File

@ -8,7 +8,6 @@ from future import standard_library
import logging import logging
import sys import sys
import os import os
import getpass
from logging.handlers import RotatingFileHandler from logging.handlers import RotatingFileHandler
standard_library.install_aliases() standard_library.install_aliases()
@ -30,8 +29,10 @@ if not os.path.exists(REDFISH_HOME):
os.mkdir(REDFISH_HOME) os.mkdir(REDFISH_HOME)
except IOError: except IOError:
print('ERROR: can\'t create {}.\n'.format(REDFISH_HOME)) print('ERROR: can\'t create {}.\n'.format(REDFISH_HOME))
print(' Try to create directory {}'.format(os.path.dirname(REDFISH_LOGFILE))) print(' Try to create directory {}'.format(
print(' using: mkdir -p {}'.format(os.path.dirname(REDFISH_LOGFILE))) os.path.dirname(REDFISH_LOGFILE)))
print(' using: mkdir -p {}'.format(
os.path.dirname(REDFISH_LOGFILE)))
sys.exit(1) sys.exit(1)
REDFISH_LOGFILE = os.path.join(REDFISH_HOME, "python-redfish.log") REDFISH_LOGFILE = os.path.join(REDFISH_HOME, "python-redfish.log")
@ -59,15 +60,18 @@ def initialize_logger(REDFISH_LOGFILE,
logger = logging.getLogger(logger_name) logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
formatter = logging.Formatter( formatter = logging.Formatter(
'%(asctime)s :: %(levelname)s :: %(message)s' '%(asctime)s :: %(levelname)s :: %(message)s')
)
try: try:
file_handler = RotatingFileHandler(os.path.expandvars(REDFISH_LOGFILE), 'a', 1000000, 1) file_handler = RotatingFileHandler(
os.path.expandvars(REDFISH_LOGFILE), 'a', 1000000, 1)
except IOError: except IOError:
print('ERROR: {} does not exist or is not writeable.\n'.format(REDFISH_LOGFILE)) print('ERROR: {} does not exist or is not writeable.\n'.format(
print(' Try to create directory {}'.format(os.path.dirname(REDFISH_LOGFILE))) REDFISH_LOGFILE))
print(' using: mkdir -p {}'.format(os.path.dirname(REDFISH_LOGFILE))) print(' Try to create directory {}'.format(os.path.dirname(
REDFISH_LOGFILE)))
print(' using: mkdir -p {}'.format(os.path.dirname(
REDFISH_LOGFILE)))
sys.exit(1) sys.exit(1)
# First logger to file # First logger to file

View File

@ -5,9 +5,9 @@ from __future__ import print_function
from __future__ import division from __future__ import division
from __future__ import absolute_import from __future__ import absolute_import
from future import standard_library from future import standard_library
standard_library.install_aliases()
from builtins import str from builtins import str
from . import config from . import config
standard_library.install_aliases()
class RedfishException(Exception): class RedfishException(Exception):
@ -28,7 +28,8 @@ class ConnectionFailureException(RedfishException):
'3- Check if your device has a valid trusted certificat\n' + \ '3- Check if your device has a valid trusted certificat\n' + \
' You can use openssl to validate it using the command :\n' + \ ' You can use openssl to validate it using the command :\n' + \
' openssl s_client -showcerts -connect <server>:443\n' + \ ' openssl s_client -showcerts -connect <server>:443\n' + \
'4- Use option "--insecure" to connect without checking certificate\n' '4- Use option "--insecure" to connect without checking' + \
' certificate\n'
class InvalidRedfishContentException(RedfishException): class InvalidRedfishContentException(RedfishException):

View File

@ -29,8 +29,9 @@ resources.
A URI should be treated by the client as opaque, and thus should not be A URI should be treated by the client as opaque, and thus should not be
attempted to be understood or deconstructed by the client. Only specific top attempted to be understood or deconstructed by the client. Only specific top
level URIs (any URI in this sample code) may be assumed, and even these may be level URIs (any URI in this sample code) may be assumed, and even these may be
absent based upon the implementation (e.g. there might be no /redfish/v1/Systems absent based upon the implementation
collection on something that doesn't have compute nodes.) (e.g. there might be no /redfish/v1/Systems collection on something
that doesn't have compute nodes.)
The other URIs must be discovered dynamically by following href links. This is The other URIs must be discovered dynamically by following href links. This is
because the API will eventually be implemented on a system that breaks any because the API will eventually be implemented on a system that breaks any
@ -141,8 +142,7 @@ def connect(
password, password,
simulator=False, simulator=False,
enforceSSL=True, enforceSSL=True,
verify_cert=True verify_cert=True):
):
return RedfishConnection( return RedfishConnection(
url, url,
@ -214,8 +214,10 @@ class RedfishConnection(object):
mapping.redfish_version = self.get_api_version() mapping.redfish_version = self.get_api_version()
mapping.redfish_root_name = self.Root.get_name() mapping.redfish_root_name = self.Root.get_name()
# Instantiate a global mapping object to handle Redfish version variation # Instantiate a global mapping object to handle
mapping.redfish_mapper = mapping.RedfishVersionMapping(self.get_api_version(), self.Root.get_name()) # Redfish version variation
mapping.redfish_mapper = mapping.RedfishVersionMapping(
self.get_api_version(), self.Root.get_name())
# Now we need to login otherwise we are not allowed to extract data # Now we need to login otherwise we are not allowed to extract data
if self.__simulator is False: if self.__simulator is False:
@ -225,9 +227,8 @@ class RedfishConnection(object):
config.logger.info("Login successful") config.logger.info("Login successful")
except "Error getting token": except "Error getting token":
config.logger.error("Login fail, fail to get auth token") config.logger.error("Login fail, fail to get auth token")
raise exception.AuthenticationFailureException("Fail to get an auth token.") raise exception.AuthenticationFailureException(
"Fail to get an auth token.")
# Structure change with mockup 1.0.0, there is no links # Structure change with mockup 1.0.0, there is no links
# section anymore. # section anymore.
@ -237,30 +238,25 @@ class RedfishConnection(object):
# Types # Types
self.SessionService = types.SessionService( self.SessionService = types.SessionService(
self.Root.get_link_url( self.Root.get_link_url(
mapping.redfish_mapper.map_sessionservice()), mapping.redfish_mapper.map_sessionservice()),
self.connection_parameters self.connection_parameters)
)
self.Managers = types.ManagersCollection(self.Root.get_link_url("Managers"), self.Managers = types.ManagersCollection(
self.connection_parameters self.Root.get_link_url("Managers"),
) self.connection_parameters)
self.Systems = types.SystemsCollection(self.Root.get_link_url("Systems"), self.Systems = types.SystemsCollection(
self.connection_parameters self.Root.get_link_url("Systems"),
) self.connection_parameters)
self.Chassis = types.ChassisCollection(self.Root.get_link_url("Chassis"), self.Chassis = types.ChassisCollection(
self.connection_parameters self.Root.get_link_url("Chassis"), self.connection_parameters)
)
# self.EventService # self.EventService
# self.AccountService # self.AccountService
# self.Tasks # self.Tasks
# ======================================================================== # ========================================================================
# systemCollectionLink = getattr(self.root.Links.Systems,"@odata.id") # systemCollectionLink = getattr(self.root.Links.Systems,"@odata.id")
# self.systemCollection = self.apiUrl.redfish.v1.Systems.get() # self.systemCollection = self.apiUrl.redfish.v1.Systems.get()
@ -280,8 +276,7 @@ class RedfishConnection(object):
def login(self): def login(self):
# Craft full url # Craft full url
url = self.Root.get_link_url( url = self.Root.get_link_url(
mapping.redfish_mapper.map_sessionservice() mapping.redfish_mapper.map_sessionservice())
)
# Handle login with redfish 1.00, url must be : # Handle login with redfish 1.00, url must be :
# /rest/v1/SessionService/Sessions as specified by the specification # /rest/v1/SessionService/Sessions as specified by the specification
@ -293,14 +288,17 @@ class RedfishConnection(object):
"Password": self.connection_parameters.password} "Password": self.connection_parameters.password}
config.logger.debug(requestBody) config.logger.debug(requestBody)
headers = self.connection_parameters.headers headers = self.connection_parameters.headers
# ======================================================================= # ====================================================================
# Tortilla seems not able to provide the header of a post request answer. # Tortilla seems not able to provide the header of a post request
# answer.
# However this is required by redfish standard to get X-Auth-Token. # However this is required by redfish standard to get X-Auth-Token.
# So jump to "requests" library to get the required token. # So jump to "requests" library to get the required token.
# TODO : Patch tortilla to handle this case. # TODO : Patch tortilla to handle this case.
# ======================================================================= # ====================================================================
# sessionsUrl = tortilla.wrap("https://10.3.222.104/rest/v1/Sessions", debug=TORTILLADEBUG) # sessionsUrl = tortilla.wrap(
# sessions = sessionsUrl.post(verify=self.verify_cert, data=requestBody) # "https://10.3.222.104/rest/v1/Sessions", debug=TORTILLADEBUG)
# sessions = sessionsUrl.post(
# verify=self.verify_cert, data=requestBody)
auth = requests.post(url, auth = requests.post(url,
data=json.dumps(requestBody), data=json.dumps(requestBody),
headers=headers, headers=headers,

View File

@ -4,13 +4,14 @@ from __future__ import print_function
from __future__ import division from __future__ import division
from __future__ import absolute_import from __future__ import absolute_import
from future import standard_library from future import standard_library
standard_library.install_aliases()
from builtins import object from builtins import object
standard_library.install_aliases()
redfish_mapper = None redfish_mapper = None
redfish_version = None redfish_version = None
redfish_root_name = None redfish_root_name = None
class RedfishVersionMapping(object): class RedfishVersionMapping(object):
'''Implements basic url path mapping beetween Redfish versions.''' '''Implements basic url path mapping beetween Redfish versions.'''
@ -24,7 +25,7 @@ class RedfishVersionMapping(object):
return 'SessionService' return 'SessionService'
def map_links(self, data_dict=None): def map_links(self, data_dict=None):
if data_dict == None: if data_dict is None:
if self.__version == '0.95': if self.__version == '0.95':
return 'links' return 'links'
else: else:
@ -39,7 +40,7 @@ class RedfishVersionMapping(object):
return 'Links' return 'Links'
def map_links_ref(self, data_dict=None): def map_links_ref(self, data_dict=None):
if data_dict == None: if data_dict is None:
if self.__version == '0.95': if self.__version == '0.95':
return 'href' return 'href'
else: else:
@ -49,11 +50,11 @@ class RedfishVersionMapping(object):
try: try:
data_dict.href data_dict.href
return 'href' return 'href'
except AttributeError: except AttributeError:
pass pass
return '@odata.id' return '@odata.id'
def map_members(self): def map_members(self):
if self.__version == '0.95': if self.__version == '0.95':
return 'Member' return 'Member'
return 'Members' return 'Members'

View File

@ -28,7 +28,7 @@ class Base(object):
def __init__(self, url, connection_parameters): def __init__(self, url, connection_parameters):
'''Class constructor''' '''Class constructor'''
global TORTILLADEBUG global TORTILLADEBUG
self.connection_parameters = connection_parameters # Uggly hack to check self.connection_parameters = connection_parameters # Uggly hack
self.url = url self.url = url
self.api_url = tortilla.wrap(url, debug=config.TORTILLADEBUG) self.api_url = tortilla.wrap(url, debug=config.TORTILLADEBUG)
@ -69,7 +69,9 @@ class Base(object):
if float(mapping.redfish_version) < 1.00: if float(mapping.redfish_version) < 1.00:
links = getattr(self.data, mapping.redfish_mapper.map_links()) links = getattr(self.data, mapping.redfish_mapper.map_links())
if link_type in links: if link_type in links:
return urljoin(self.url, links[link_type][mapping.redfish_mapper.map_links_ref()]) return urljoin(
self.url,
links[link_type][mapping.redfish_mapper.map_links_ref()])
raise AttributeError raise AttributeError
else: else:
links = getattr(self.data, link_type) links = getattr(self.data, link_type)
@ -147,17 +149,22 @@ class BaseCollection(Base):
self.links = [] self.links = []
#linksmembers = self.data.Links.Members # linksmembers = self.data.Links.Members
#linksmembers = self.data.links.Member # linksmembers = self.data.links.Member
if float(mapping.redfish_version) < 1.00: if float(mapping.redfish_version) < 1.00:
linksmembers = getattr(self.data, mapping.redfish_mapper.map_links()) linksmembers = getattr(
linksmembers = getattr(linksmembers, mapping.redfish_mapper.map_members()) self.data, mapping.redfish_mapper.map_links())
linksmembers = getattr(
linksmembers, mapping.redfish_mapper.map_members())
else: else:
linksmembers = getattr(self.data, mapping.redfish_mapper.map_members()) linksmembers = getattr(
self.data, mapping.redfish_mapper.map_members())
for link in linksmembers: for link in linksmembers:
#self.links.append(getattr(link,'@odata.id')) # self.links.append(getattr(link,'@odata.id'))
#self.links.append(getattr(link,'href')) # self.links.append(getattr(link,'href'))
self.links.append(urljoin(self.url, getattr(link, mapping.redfish_mapper.map_links_ref()))) self.links.append(urljoin(
self.url, getattr(
link, mapping.redfish_mapper.map_links_ref())))
config.logger.debug(self.links) config.logger.debug(self.links)
@ -302,18 +309,20 @@ class Managers(Device):
def __init__(self, url, connection_parameters): def __init__(self, url, connection_parameters):
super(Managers, self).__init__(url, connection_parameters) super(Managers, self).__init__(url, connection_parameters)
try: try:
# New proliant firmware now respects Redfish v1.00, so seems to correct below statement # New proliant firmware now respects Redfish v1.00, so seems to
# TODO : better handle exception and if possible support old firmware ? # correct below statement
# TODO : better handle exception and if possible support
# old firmware ?
self.ethernet_interfaces_collection = \ self.ethernet_interfaces_collection = \
EthernetInterfacesCollection( EthernetInterfacesCollection(
self.get_link_url('EthernetInterfaces'), self.get_link_url('EthernetInterfaces'),
connection_parameters) connection_parameters)
# Works on proliant, need to treat 095 vs 0.96 differences # Works on proliant, need to treat 095 vs 0.96 differences
#self.ethernet_interfaces_collection = EthernetInterfacesCollection( # self.ethernet_interfaces_collection = \
# self.get_link_url('EthernetNICs'), # EthernetInterfacesCollection(
# connection_parameters # self.get_link_url('EthernetNICs'),
# ) # connection_parameters)
except exception.InvalidRedfishContentException: except exception.InvalidRedfishContentException:
# This is to avoid invalid content from the mockup # This is to avoid invalid content from the mockup
self.ethernet_interfaces_collection = None self.ethernet_interfaces_collection = None
@ -359,7 +368,9 @@ class Managers(Device):
try: try:
for chassis in links.ManagerForChassis: for chassis in links.ManagerForChassis:
result = re.search(r'Chassis/(\w+)', chassis[mapping.redfish_mapper.map_links_ref(chassis)]) result = re.search(
r'Chassis/(\w+)',
chassis[mapping.redfish_mapper.map_links_ref(chassis)])
chassis_list.append(result.group(1)) chassis_list.append(result.group(1))
return chassis_list return chassis_list
except AttributeError: except AttributeError:
@ -413,7 +424,8 @@ class ManagersCollection(BaseCollection):
self.managers_dict = {} self.managers_dict = {}
for link in self.links: for link in self.links:
index = re.search(r'Managers/(\w+)', link) index = re.search(r'Managers/(\w+)', link)
self.managers_dict[index.group(1)] = Managers(link, connection_parameters) self.managers_dict[index.group(1)] = Managers(
link, connection_parameters)
class Systems(Device): class Systems(Device):
@ -674,14 +686,16 @@ class SystemsCollection(BaseCollection):
for link in self.links: for link in self.links:
index = re.search(r'Systems/(\w+)', link) index = re.search(r'Systems/(\w+)', link)
self.systems_dict[index.group(1)] = Systems(link, connection_parameters) self.systems_dict[index.group(1)] = Systems(
link, connection_parameters)
class Bios(Base): class Bios(Base):
'''Class to manage redfish Bios data.''' '''Class to manage redfish Bios data.'''
def __init__(self, url, connection_parameters): def __init__(self, url, connection_parameters):
super(Bios, self).__init__(url, connection_parameters) super(Bios, self).__init__(url, connection_parameters)
self.boot = Boot(re.findall('.+/Bios', url)[0] + '/Boot/Settings', connection_parameters) self.boot = Boot(re.findall('.+/Bios', url)[0] +
'/Boot/Settings', connection_parameters)
class Boot(Base): class Boot(Base):
@ -878,7 +892,8 @@ class ChassisCollection(BaseCollection):
for link in self.links: for link in self.links:
index = re.search(r'Chassis/(\w+)', link) index = re.search(r'Chassis/(\w+)', link)
self.chassis_dict[index.group(1)] = Chassis(link, connection_parameters) self.chassis_dict[index.group(1)] = Chassis(
link, connection_parameters)
class Chassis(Device): class Chassis(Device):