mirror of
https://opendev.org/x/pyghmi
synced 2026-04-01 15:53:32 +00:00
Merge "Bump hacking to 3.0.0"
This commit is contained in:
@@ -27,8 +27,8 @@ def lifecycle_callback(connection, domain, event, detail, console):
|
||||
|
||||
|
||||
def error_handler(unused, error):
|
||||
if (error[0] == libvirt.VIR_ERR_RPC and
|
||||
error[1] == libvirt.VIR_FROM_STREAMS):
|
||||
if (error[0] == libvirt.VIR_ERR_RPC
|
||||
and error[1] == libvirt.VIR_FROM_STREAMS):
|
||||
return
|
||||
|
||||
|
||||
@@ -91,8 +91,8 @@ class LibvirtBmc(bmc.Bmc):
|
||||
return self.domain.isActive()
|
||||
|
||||
def check_console(self):
|
||||
if (self.state[0] == libvirt.VIR_DOMAIN_RUNNING or
|
||||
self.state[0] == libvirt.VIR_DOMAIN_PAUSED):
|
||||
if (self.state[0] == libvirt.VIR_DOMAIN_RUNNING
|
||||
or self.state[0] == libvirt.VIR_DOMAIN_PAUSED):
|
||||
if self.stream is None:
|
||||
self.stream = self.conn.newStream(libvirt.VIR_STREAM_NONBLOCK)
|
||||
self.domain.openConsole(None, self.stream, 0)
|
||||
|
||||
@@ -130,8 +130,8 @@ class Bmc(serversession.IpmiServer):
|
||||
bootdevice = self.get_boot_device()
|
||||
except NotImplementedError:
|
||||
session.send_ipmi_response(data=[1, 5, 0, 0, 0, 0, 0])
|
||||
if (type(bootdevice) != int and
|
||||
bootdevice in ipmicommand.boot_devices):
|
||||
if (type(bootdevice) != int
|
||||
and bootdevice in ipmicommand.boot_devices):
|
||||
bootdevice = ipmicommand.boot_devices[bootdevice]
|
||||
paramdata = [1, 5, 0b10000000, bootdevice, 0, 0, 0]
|
||||
return session.send_ipmi_response(data=paramdata)
|
||||
|
||||
@@ -269,12 +269,12 @@ class Command(object):
|
||||
raise exc.IpmiException(response['error'])
|
||||
# this should only be invoked for get system boot option complying to
|
||||
# ipmi spec and targeting the 'boot flags' parameter
|
||||
assert (response['command'] == 9 and
|
||||
response['netfn'] == 1 and
|
||||
response['data'][0] == 1 and
|
||||
(response['data'][1] & 0b1111111) == 5)
|
||||
if (response['data'][1] & 0b10000000 or
|
||||
not response['data'][2] & 0b10000000):
|
||||
assert (response['command'] == 9
|
||||
and response['netfn'] == 1
|
||||
and response['data'][0] == 1
|
||||
and (response['data'][1] & 0b1111111) == 5)
|
||||
if (response['data'][1] & 0b10000000
|
||||
or not response['data'][2] & 0b10000000):
|
||||
return {'bootdev': 'default', 'persistent': True}
|
||||
else: # will consult data2 of the boot flags parameter for the data
|
||||
persistent = False
|
||||
@@ -345,8 +345,7 @@ class Command(object):
|
||||
waitattempts = 300
|
||||
if not isinstance(wait, bool):
|
||||
waitattempts = wait
|
||||
if (wait and
|
||||
newpowerstate in ('on', 'off', 'shutdown', 'softoff')):
|
||||
if wait and newpowerstate in ('on', 'off', 'shutdown', 'softoff'):
|
||||
if newpowerstate in ('softoff', 'shutdown'):
|
||||
waitpowerstate = 'off'
|
||||
else:
|
||||
@@ -1029,7 +1028,7 @@ class Command(object):
|
||||
netchan = bytearray(rsp['data'])[0]
|
||||
self._netchannel = netchan & 0b1111
|
||||
break
|
||||
except exc.IpmiException as ie:
|
||||
except exc.IpmiException:
|
||||
# This means the attempt to fetch parameter 5 failed,
|
||||
# therefore move on to next candidate channel
|
||||
continue
|
||||
@@ -1216,8 +1215,9 @@ class Command(object):
|
||||
channel)
|
||||
if destdata:
|
||||
self.xraw_command(netfn=0xc, command=1, data=destdata)
|
||||
if (acknowledge_required is not None or retries is not None or
|
||||
acknowledge_timeout is not None):
|
||||
if (acknowledge_required is not None
|
||||
or retries is not None
|
||||
or acknowledge_timeout is not None):
|
||||
currtype = self.xraw_command(netfn=0xc, command=2, data=(
|
||||
channel, 18, destination, 0))
|
||||
if currtype['data'][0] != b'\x11':
|
||||
|
||||
@@ -181,8 +181,8 @@ class Console(object):
|
||||
if isinstance(data, dict):
|
||||
self.pendingoutput.append(data)
|
||||
else: # it is a text situation
|
||||
if (len(self.pendingoutput) == 0 or
|
||||
isinstance(self.pendingoutput[-1], dict)):
|
||||
if (len(self.pendingoutput) == 0
|
||||
or isinstance(self.pendingoutput[-1], dict)):
|
||||
self.pendingoutput.append(data)
|
||||
else:
|
||||
self.pendingoutput[-1] += data
|
||||
@@ -310,8 +310,8 @@ class Console(object):
|
||||
self.broken = True
|
||||
if self.ipmi_session:
|
||||
self.ipmi_session.unregister_keepalive(self.keepaliveid)
|
||||
if (self.ipmi_session.sol_handler and
|
||||
self.ipmi_session.sol_handler.__self__ is self):
|
||||
if (self.ipmi_session.sol_handler
|
||||
and self.ipmi_session.sol_handler.__self__ is self):
|
||||
self.ipmi_session.sol_handler = None
|
||||
self.ipmi_session = None
|
||||
if type(error) == dict:
|
||||
@@ -388,8 +388,9 @@ class Console(object):
|
||||
# also add pending output for efficiency and ease
|
||||
newtext = self.lastpayload[4 + ackcount:]
|
||||
with self.outputlock:
|
||||
if (self.pendingoutput and
|
||||
not isinstance(self.pendingoutput[0], dict)):
|
||||
if (self.pendingoutput
|
||||
and not isinstance(self.pendingoutput[0],
|
||||
dict)):
|
||||
self.pendingoutput[0] = \
|
||||
newtext + self.pendingoutput[0]
|
||||
else:
|
||||
@@ -510,8 +511,8 @@ class ServerConsole(Console):
|
||||
if nacked and not breakdetected: # the BMC was in some way unhappy
|
||||
newtext = self.lastpayload[4 + ackcount:]
|
||||
with self.outputlock:
|
||||
if (self.pendingoutput and
|
||||
not isinstance(self.pendingoutput[0], dict)):
|
||||
if (self.pendingoutput
|
||||
and not isinstance(self.pendingoutput[0], dict)):
|
||||
self.pendingoutput[0] = newtext + self.pendingoutput[0]
|
||||
else:
|
||||
self.pendingoutput = [newtext] + self.pendingoutput
|
||||
|
||||
@@ -311,10 +311,10 @@ def _fix_sel_time(records, ipmicmd):
|
||||
record = records[index]
|
||||
if 'timecode' not in record or record['timecode'] == 0xffffffff:
|
||||
continue
|
||||
if ('event' in record and record['event'] == 'Clock time change' and
|
||||
record['event_data'] == 'After'):
|
||||
if (lasttimestamp is not None and
|
||||
record['timecode'] > lasttimestamp):
|
||||
if ('event' in record and record['event'] == 'Clock time change'
|
||||
and record['event_data'] == 'After'):
|
||||
if (lasttimestamp is not None
|
||||
and record['timecode'] > lasttimestamp):
|
||||
# if the timestamp did something impossible, declare the rest
|
||||
# of history not meaningfully correctable
|
||||
correctionenabled = False
|
||||
@@ -322,8 +322,8 @@ def _fix_sel_time(records, ipmicmd):
|
||||
continue
|
||||
newtimestamp = record['timecode']
|
||||
trimindexes.append(index)
|
||||
elif ('event' in record and record['event'] == 'Clock time change' and
|
||||
record['event_data'] == 'Before'):
|
||||
elif ('event' in record and record['event'] == 'Clock time change'
|
||||
and record['event_data'] == 'Before'):
|
||||
if not correctionenabled:
|
||||
continue
|
||||
if newtimestamp:
|
||||
@@ -342,8 +342,8 @@ def _fix_sel_time(records, ipmicmd):
|
||||
if not correctearly or not correctionenabled:
|
||||
correctednowtime = nowtime
|
||||
continue
|
||||
if (lasttimestamp is not None and
|
||||
record['timecode'] > lasttimestamp):
|
||||
if (lasttimestamp is not None
|
||||
and record['timecode'] > lasttimestamp):
|
||||
# Time has gone backwards in pre-init, no hope for
|
||||
# accurate time
|
||||
correctearly = False
|
||||
@@ -359,8 +359,8 @@ def _fix_sel_time(records, ipmicmd):
|
||||
# We are in 'normal' time, assume we cannot go to
|
||||
# pre-init time and do corrections unless time sync events
|
||||
# guide us in safely
|
||||
if (lasttimestamp is not None and
|
||||
record['timecode'] > lasttimestamp):
|
||||
if (lasttimestamp is not None
|
||||
and record['timecode'] > lasttimestamp):
|
||||
# Time has gone backwards, without a clock sync
|
||||
# give up any attempt to correct from this point back...
|
||||
correctionenabled = False
|
||||
|
||||
@@ -72,8 +72,8 @@ class _ExpEngine(object):
|
||||
for optkey in self.cfg:
|
||||
opt = self.cfg[optkey]
|
||||
lid = opt['lenovo_id'].replace('-', '_')
|
||||
if (lid == category and
|
||||
opt['lenovo_setting'] == setting):
|
||||
if (lid == category
|
||||
and opt['lenovo_setting'] == setting):
|
||||
self.relatedsettings.add(optkey)
|
||||
return opt['lenovo_value']
|
||||
return None
|
||||
@@ -322,8 +322,8 @@ class LenovoFirmwareConfig(object):
|
||||
default = onedata.get('default', None)
|
||||
if default == '':
|
||||
default = None
|
||||
if (setting.find('cmd_data') is not None or
|
||||
setting.find('boolean_data') is not None):
|
||||
if (setting.find('cmd_data') is not None
|
||||
or setting.find('boolean_data') is not None):
|
||||
protect = True # Hide currently unsupported settings
|
||||
ldata = setting.find("list_data")
|
||||
extraorder = False
|
||||
|
||||
@@ -277,9 +277,9 @@ class OEMHandler(generic.OEMHandler):
|
||||
event['severity'] = pygconst.Health.Critical
|
||||
# For HDD bay events, the event data 2 is the bay, modify
|
||||
# the description to be more specific
|
||||
if (event['event_type_byte'] == 0x6f and
|
||||
(evdata[0] & 0b11000000) == 0b10000000 and
|
||||
event['component_type_id'] == 13):
|
||||
if (event['event_type_byte'] == 0x6f
|
||||
and (evdata[0] & 0b11000000) == 0b10000000
|
||||
and event['component_type_id'] == 13):
|
||||
event['component'] += ' {0}'.format(evdata[1] & 0b11111)
|
||||
|
||||
def reseat_bay(self, bay):
|
||||
@@ -376,8 +376,8 @@ class OEMHandler(generic.OEMHandler):
|
||||
def has_tsm(self):
|
||||
"""True if this particular server have a TSM based service processor"""
|
||||
|
||||
if (self.oemid['manufacturer_id'] == 19046 and
|
||||
self.oemid['device_id'] == 32):
|
||||
if (self.oemid['manufacturer_id'] == 19046
|
||||
and self.oemid['device_id'] == 32):
|
||||
try:
|
||||
self.ipmicmd.xraw_command(netfn=0x3a, command=0xf)
|
||||
except pygexc.IpmiException as ie:
|
||||
|
||||
@@ -188,8 +188,8 @@ class IMMClient(object):
|
||||
try:
|
||||
self.fwo = self.fwc.get_fw_options(fetchimm=fetchimm)
|
||||
except Exception:
|
||||
raise Exception(self.bmcname +
|
||||
' failed to retrieve UEFI configuration')
|
||||
raise Exception('%s failed to retrieve UEFI configuration'
|
||||
% self.bmcname)
|
||||
self.fwovintage = util._monotonic_time()
|
||||
retcfg = {}
|
||||
for opt in self.fwo:
|
||||
@@ -197,8 +197,8 @@ class IMMClient(object):
|
||||
# Suppress the Avago configuration to be consistent with
|
||||
# other tools.
|
||||
continue
|
||||
if (hideadvanced and self.fwo[opt]['lenovo_protect'] or
|
||||
self.fwo[opt]['hidden']):
|
||||
if (hideadvanced and self.fwo[opt]['lenovo_protect']
|
||||
or self.fwo[opt]['hidden']):
|
||||
# Do not enumerate hidden settings
|
||||
continue
|
||||
retcfg[opt] = {}
|
||||
@@ -266,8 +266,8 @@ class IMMClient(object):
|
||||
newnewvalues = []
|
||||
for newvalue in newvalues:
|
||||
newv = re.sub(r'\s+', ' ', newvalue)
|
||||
if (self.fwo[key]['possible'] and
|
||||
newvalue not in self.fwo[key]['possible']):
|
||||
if (self.fwo[key]['possible']
|
||||
and newvalue not in self.fwo[key]['possible']):
|
||||
candlist = []
|
||||
for candidate in self.fwo[key]['possible']:
|
||||
candid = re.sub(r'\s+', ' ', candidate)
|
||||
@@ -370,8 +370,9 @@ class IMMClient(object):
|
||||
|
||||
@property
|
||||
def wc(self):
|
||||
if (not self._wc or (self._wc.vintage and
|
||||
self._wc.vintage < util._monotonic_time() - 30)):
|
||||
if (not self._wc or (self._wc.vintage
|
||||
and self._wc.vintage < util._monotonic_time()
|
||||
- 30)):
|
||||
if not self.updating and self._wc:
|
||||
# in case the existing session is still valid
|
||||
# dispose of the session
|
||||
@@ -552,22 +553,22 @@ class IMMClient(object):
|
||||
bdata = {}
|
||||
if 'versionStr' in firm and firm['versionStr']:
|
||||
bdata['version'] = firm['versionStr']
|
||||
if ('releaseDate' in firm and
|
||||
firm['releaseDate'] and
|
||||
firm['releaseDate'] != 'N/A'):
|
||||
if ('releaseDate' in firm
|
||||
and firm['releaseDate']
|
||||
and firm['releaseDate'] != 'N/A'):
|
||||
try:
|
||||
bdata['date'] = self._parse_builddate(
|
||||
firm['releaseDate'])
|
||||
except ValueError:
|
||||
pass
|
||||
yield ('{0} {1}'.format(aname, fname), bdata)
|
||||
yield '{0} {1}'.format(aname, fname), bdata
|
||||
for fwi in fwu.get('items', []):
|
||||
if fwi.get('key', -1) == adata.get('key', -2):
|
||||
if fwi.get('fw_status', 0) == 2:
|
||||
bdata = {}
|
||||
if 'fw_version_pend' in fwi:
|
||||
bdata['version'] = fwi['fw_version_pend']
|
||||
yield('{0} Pending Update'.format(aname), bdata)
|
||||
yield '{0} Pending Update'.format(aname), bdata
|
||||
for disk in self.disk_inventory():
|
||||
yield disk
|
||||
self.weblogout()
|
||||
@@ -708,8 +709,8 @@ class IMMClient(object):
|
||||
bdata['pcislot'] = '{0:02x}:{1:02x}'.format(
|
||||
fundata[self.BUSNO], fundata[self.DEVNO])
|
||||
serialdata = fundata.get(self.ADP_SERIALNO, None)
|
||||
if (serialdata and serialdata != 'N/A' and
|
||||
'---' not in serialdata):
|
||||
if (serialdata and serialdata != 'N/A'
|
||||
and '---' not in serialdata):
|
||||
bdata['serial'] = serialdata
|
||||
partnum = fundata.get(self.ADP_PARTNUM, None)
|
||||
if partnum and partnum != 'N/A':
|
||||
@@ -929,9 +930,8 @@ class XCCClient(IMMClient):
|
||||
'/redfish/v1/Systems/1/Bios/Actions/Bios.ResetBios',
|
||||
{'Action': 'Bios.ResetBios'},
|
||||
headers={
|
||||
'Authorization': 'Basic ' +
|
||||
base64.b64encode(
|
||||
self.username + ':' + self.password),
|
||||
'Authorization': 'Basic %s' % base64.b64encode(
|
||||
self.username + ':' + self.password),
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
)
|
||||
@@ -1252,8 +1252,8 @@ class XCCClient(IMMClient):
|
||||
elif strsize in ('remainder', 'rest'):
|
||||
volsize = remainingcap
|
||||
elif strsize.endswith('%'):
|
||||
volsize = int(params['capacity'] *
|
||||
float(strsize.replace('%', '')) / 100.0)
|
||||
volsize = int(params['capacity']
|
||||
* float(strsize.replace('%', '')) / 100.0)
|
||||
else:
|
||||
try:
|
||||
volsize = int(strsize)
|
||||
@@ -1445,8 +1445,8 @@ class XCCClient(IMMClient):
|
||||
# then check for agentless, if agentless, get adapter info using
|
||||
# https, using the caller TLS verification scheme
|
||||
components = set(components)
|
||||
if (not components or
|
||||
set(('core', 'imm', 'bmc', 'xcc')) & components):
|
||||
if (not components
|
||||
or set(('core', 'imm', 'bmc', 'xcc')) & components):
|
||||
rsp = self.ipmicmd.xraw_command(netfn=0x3a, command=0x50)
|
||||
immverdata = self.parse_imm_buildinfo(rsp['data'])
|
||||
bmcmajor, bmcminor = [int(x) for x in bmcver.split('.')]
|
||||
@@ -1454,20 +1454,20 @@ class XCCClient(IMMClient):
|
||||
bdata = {'version': bmcver,
|
||||
'build': immverdata[0],
|
||||
'date': immverdata[1]}
|
||||
yield (self.bmcname, bdata)
|
||||
yield self.bmcname, bdata
|
||||
bdata = self.fetch_grouped_properties({
|
||||
'build': '/v2/ibmc/dm/fw/imm3/backup_pending_build_id',
|
||||
'version': '/v2/ibmc/dm/fw/imm3/backup_pending_build_version',
|
||||
'date': '/v2/ibmc/dm/fw/imm3/backup_pending_build_date'})
|
||||
if bdata:
|
||||
yield ('{0} Backup'.format(self.bmcname), bdata)
|
||||
yield '{0} Backup'.format(self.bmcname), bdata
|
||||
else:
|
||||
bdata = self.fetch_grouped_properties({
|
||||
'build': '/v2/ibmc/dm/fw/imm3/backup_build_id',
|
||||
'version': '/v2/ibmc/dm/fw/imm3/backup_build_version',
|
||||
'date': '/v2/ibmc/dm/fw/imm3/backup_build_date'})
|
||||
if bdata:
|
||||
yield ('{0} Backup'.format(self.bmcname), bdata)
|
||||
yield '{0} Backup'.format(self.bmcname), bdata
|
||||
bdata = self.fetch_grouped_properties({
|
||||
'build': '/v2/ibmc/trusted_buildid',
|
||||
})
|
||||
@@ -1476,7 +1476,7 @@ class XCCClient(IMMClient):
|
||||
'build': '/v2/ibmc/trusted_buildid',
|
||||
})
|
||||
if bdata:
|
||||
yield ('{0} Trusted Image'.format(self.bmcname), bdata)
|
||||
yield '{0} Trusted Image'.format(self.bmcname), bdata
|
||||
bdata = self.fetch_grouped_properties({
|
||||
'build': '/v2/ibmc/dm/fw/imm3/primary_pending_build_id',
|
||||
'version': '/v2/ibmc/dm/fw/imm3/primary_pending_build_version',
|
||||
@@ -1566,8 +1566,8 @@ class XCCClient(IMMClient):
|
||||
url = mt['remotepath']
|
||||
if url.startswith('//'):
|
||||
url = 'smb:' + url
|
||||
elif (not url.startswith('http://') and
|
||||
not url.startswith('https://')):
|
||||
elif (not url.startswith('http://')
|
||||
and not url.startswith('https://')):
|
||||
url = url.replace(':', '')
|
||||
url = 'nfs://' + url
|
||||
yield media.Media(mt['filename'], url)
|
||||
@@ -1684,8 +1684,8 @@ class XCCClient(IMMClient):
|
||||
progress({'phase': 'upload',
|
||||
'progress': 100.0 * rsp['received'] / rsp['size']})
|
||||
elif rsp['state'] != 'done':
|
||||
if (rsp.get('status', None) == 413 or
|
||||
uploadthread.rspstatus == 413):
|
||||
if (rsp.get('status', None) == 413
|
||||
or uploadthread.rspstatus == 413):
|
||||
raise Exception('File is larger than supported')
|
||||
raise Exception('Unexpected result:' + repr(rsp))
|
||||
uploadstate = rsp['state']
|
||||
@@ -1814,8 +1814,7 @@ class XCCClient(IMMClient):
|
||||
|
||||
if rsp.get('return', -1) != 0:
|
||||
errmsg = repr(rsp) if rsp else self.wc.lastjsonerror
|
||||
raise Exception('Unexpected result starting update: ' +
|
||||
errmsg)
|
||||
raise Exception('Unexpected result starting update: %s' % errmsg)
|
||||
complete = False
|
||||
while not complete:
|
||||
ipmisession.Session.pause(3)
|
||||
@@ -1831,8 +1830,8 @@ class XCCClient(IMMClient):
|
||||
if rsp['items'][0]['action_status'] != 0:
|
||||
raise Exception('Unexpected failure: ' + repr(rsp))
|
||||
break
|
||||
if (rsp['items'][0]['action_state'] == 'In Progress' and
|
||||
rsp['items'][0]['action_status'] == 2):
|
||||
if (rsp['items'][0]['action_state'] == 'In Progress'
|
||||
and rsp['items'][0]['action_status'] == 2):
|
||||
raise Exception('Unexpected failure: ' + repr(rsp))
|
||||
if rsp['items'][0]['action_state'] != 'In Progress':
|
||||
raise Exception(
|
||||
@@ -1870,7 +1869,7 @@ class XCCClient(IMMClient):
|
||||
def get_health(self, summary):
|
||||
try:
|
||||
wc = self.get_webclient(False)
|
||||
except (socket.timeout, socket.error) as e:
|
||||
except (socket.timeout, socket.error):
|
||||
wc = None
|
||||
if not wc:
|
||||
summary['health'] = pygconst.Health.Critical
|
||||
|
||||
@@ -51,16 +51,16 @@ class IpmiReq(ctypes.Structure):
|
||||
_IONONE = 0
|
||||
_IOWRITE = 1
|
||||
_IOREAD = 2
|
||||
IPMICTL_SET_MY_ADDRESS_CMD = (_IOREAD << 30 |
|
||||
ctypes.sizeof(ctypes.c_uint) << 16 |
|
||||
ord('i') << 8 | 17) # from ipmi.h
|
||||
IPMICTL_SEND_COMMAND = (_IOREAD << 30 |
|
||||
ctypes.sizeof(IpmiReq) << 16 |
|
||||
ord('i') << 8 | 13) # from ipmi.h
|
||||
IPMICTL_SET_MY_ADDRESS_CMD = (
|
||||
_IOREAD << 30 | ctypes.sizeof(ctypes.c_uint) << 16
|
||||
| ord('i') << 8 | 17) # from ipmi.h
|
||||
IPMICTL_SEND_COMMAND = (
|
||||
_IOREAD << 30 | ctypes.sizeof(IpmiReq) << 16
|
||||
| ord('i') << 8 | 13) # from ipmi.h
|
||||
# next is really IPMICTL_RECEIVE_MSG_TRUNC, but will only use that
|
||||
IPMICTL_RECV = ((_IOWRITE | _IOREAD) << 30 |
|
||||
ctypes.sizeof(IpmiRecv) << 16 |
|
||||
ord('i') << 8 | 11) # from ipmi.h
|
||||
IPMICTL_RECV = (
|
||||
(_IOWRITE | _IOREAD) << 30 | ctypes.sizeof(IpmiRecv) << 16
|
||||
| ord('i') << 8 | 11) # from ipmi.h
|
||||
BMC_SLAVE_ADDR = ctypes.c_uint(0x20)
|
||||
CURRCHAN = 0xf
|
||||
ADDRTYPE = 0xc
|
||||
|
||||
@@ -49,9 +49,9 @@ class ServerSession(ipmisession.Session):
|
||||
# table 13-18, integrity, 1 for now is hmac-sha1-96, 4 is sha256
|
||||
# confidentiality: 1 is aes-cbc-128, the only one
|
||||
self.privlevel = 4
|
||||
response = (bytearray([clienttag, 0, self.privlevel, 0]) +
|
||||
self.clientsessionid + self.managedsessionid +
|
||||
bytearray([
|
||||
response = (bytearray([clienttag, 0, self.privlevel, 0])
|
||||
+ self.clientsessionid + self.managedsessionid
|
||||
+ bytearray([
|
||||
0, 0, 0, 8, 1, 0, 0, 0, # auth
|
||||
1, 0, 0, 8, 1, 0, 0, 0, # integrity
|
||||
2, 0, 0, 8, 1, 0, 0, 0, # privacy
|
||||
@@ -114,9 +114,9 @@ class ServerSession(ipmisession.Session):
|
||||
uuidbytes = self.uuid.bytes
|
||||
self.uuiddata = uuidbytes
|
||||
self.Rc = os.urandom(16)
|
||||
hmacdata = (self.clientsessionid + self.managedsessionid +
|
||||
self.Rm + self.Rc + uuidbytes +
|
||||
bytearray([self.rolem, len(self.username)]))
|
||||
hmacdata = (self.clientsessionid + self.managedsessionid
|
||||
+ self.Rm + self.Rc + uuidbytes
|
||||
+ bytearray([self.rolem, len(self.username)]))
|
||||
hmacdata += self.username
|
||||
self.kuid = self.authdata[self.username.decode('utf-8')].encode(
|
||||
'utf-8')
|
||||
@@ -128,8 +128,8 @@ class ServerSession(ipmisession.Session):
|
||||
# akin to a leak of /etc/shadow, not too worrisome if the secret
|
||||
# is complex, but terrible for most likely passwords selected by
|
||||
# a human
|
||||
newmessage = (bytearray([clienttag, 0, 0, 0]) + self.clientsessionid +
|
||||
self.Rc + uuidbytes + authcode)
|
||||
newmessage = (bytearray([clienttag, 0, 0, 0]) + self.clientsessionid
|
||||
+ self.Rc + uuidbytes + authcode)
|
||||
self.send_payload(newmessage, constants.payload_types['rakp2'],
|
||||
retry=False)
|
||||
|
||||
@@ -144,18 +144,15 @@ class ServerSession(ipmisession.Session):
|
||||
# even if rakp2 was good
|
||||
RmRc = self.Rm + self.Rc
|
||||
self.sik = hmac.new(self.kg,
|
||||
bytes(RmRc) +
|
||||
struct.pack("2B", self.rolem,
|
||||
len(self.username)) +
|
||||
self.username, hashlib.sha1).digest()
|
||||
bytes(RmRc)
|
||||
+ struct.pack("2B", self.rolem, len(self.username))
|
||||
+ self.username, hashlib.sha1).digest()
|
||||
self.k1 = hmac.new(self.sik, b'\x01' * 20, hashlib.sha1).digest()
|
||||
self.k2 = hmac.new(self.sik, b'\x02' * 20, hashlib.sha1).digest()
|
||||
self.aeskey = self.k2[0:16]
|
||||
hmacdata = self.Rc +\
|
||||
self.clientsessionid +\
|
||||
struct.pack("2B", self.rolem,
|
||||
len(self.username)) +\
|
||||
self.username
|
||||
hmacdata = (self.Rc + self.clientsessionid
|
||||
+ struct.pack("2B", self.rolem, len(self.username))
|
||||
+ self.username)
|
||||
expectedauthcode = hmac.new(self.kuid, bytes(hmacdata), hashlib.sha1
|
||||
).digest()
|
||||
authcode = struct.pack("%dB" % len(data[8:]), *data[8:])
|
||||
|
||||
@@ -206,8 +206,8 @@ def _io_graball(mysockets, iowaiters):
|
||||
myport = mysocket.getsockname()[1]
|
||||
rdata = rdata + (mysocket,)
|
||||
relsession = None
|
||||
if (rdata[1] in Session.bmc_handlers and
|
||||
myport in Session.bmc_handlers[rdata[1]]):
|
||||
if (rdata[1] in Session.bmc_handlers
|
||||
and myport in Session.bmc_handlers[rdata[1]]):
|
||||
# session data
|
||||
rdata = rdata + (True,)
|
||||
relsession = Session.bmc_handlers[rdata[1]][myport]
|
||||
@@ -436,13 +436,15 @@ class Session(object):
|
||||
if sockaddr in cls.bmc_handlers:
|
||||
for portself in list(dictitems(cls.bmc_handlers[sockaddr])):
|
||||
self = portself[1]
|
||||
if not ((self.logged or self.logging) and
|
||||
cls._is_session_valid(self)):
|
||||
if not ((self.logged or self.logging)
|
||||
and cls._is_session_valid(self)):
|
||||
# we have encountered a leftover broken session
|
||||
del cls.bmc_handlers[sockaddr][portself[0]]
|
||||
continue
|
||||
if (self.bmc == bmc and self.userid == userid and
|
||||
self.password == password and self.kgo == kg):
|
||||
if (self.bmc == bmc
|
||||
and self.userid == userid
|
||||
and self.password == password
|
||||
and self.kgo == kg):
|
||||
trueself = self
|
||||
break
|
||||
# ok, the candidate seems to be working, but does not match
|
||||
@@ -670,9 +672,10 @@ class Session(object):
|
||||
# we are always the requestor for now
|
||||
seqincrement = 7 # IPMI spec forbids gaps bigger then 7 in seq number.
|
||||
# Risk the taboo rather than violate the rules
|
||||
while (not self.servermode and
|
||||
(netfn, command, self.seqlun) in self.tabooseq and
|
||||
self.tabooseq[(netfn, command, self.seqlun)] and seqincrement):
|
||||
while (not self.servermode
|
||||
and (netfn, command, self.seqlun) in self.tabooseq
|
||||
and self.tabooseq[(netfn, command, self.seqlun)]
|
||||
and seqincrement):
|
||||
self.tabooseq[(self.expectednetfn, command, self.seqlun)] -= 1
|
||||
# Allow taboo to eventually expire after a few rounds
|
||||
self.seqlun += 1 # the last two bits are lun, so add 4 to add 1
|
||||
@@ -747,8 +750,8 @@ class Session(object):
|
||||
waiter({'success': True})
|
||||
self.process_pktqueue()
|
||||
with util.protect(WAITING_SESSIONS):
|
||||
if (self in self.waiting_sessions and
|
||||
self.expiration < _monotonic_time()):
|
||||
if (self in self.waiting_sessions
|
||||
and self.expiration < _monotonic_time()):
|
||||
self.waiting_sessions.pop(self, None)
|
||||
self._timedout()
|
||||
|
||||
@@ -763,8 +766,8 @@ class Session(object):
|
||||
callback=None,
|
||||
rslun=0):
|
||||
if not self.logged:
|
||||
if (self.logoutexpiry is not None and
|
||||
_monotonic_time() > self.logoutexpiry):
|
||||
if (self.logoutexpiry is not None
|
||||
and _monotonic_time() > self.logoutexpiry):
|
||||
self._mark_broken()
|
||||
raise exc.IpmiException('Session no longer connected')
|
||||
self._cmdwait()
|
||||
@@ -928,8 +931,8 @@ class Session(object):
|
||||
# advance idle timer since we don't need keepalive while sending
|
||||
# packets out naturally
|
||||
with util.protect(KEEPALIVE_SESSIONS):
|
||||
if (self in Session.keepalive_sessions and not needskeepalive and
|
||||
not self._customkeepalives):
|
||||
if (self in Session.keepalive_sessions and not needskeepalive
|
||||
and not self._customkeepalives):
|
||||
Session.keepalive_sessions[self]['timeout'] = \
|
||||
_monotonic_time() + MAX_IDLE - (random.random() * 4.9)
|
||||
self._xmit_packet(retry, delay_xmit=delay_xmit, timeout=timeout)
|
||||
@@ -1149,8 +1152,8 @@ class Session(object):
|
||||
if parms['timeout'] <= curtime:
|
||||
timeout = 0 # exit after one guaranteed pass
|
||||
break
|
||||
if (timeout is not None and
|
||||
timeout < parms['timeout'] - curtime):
|
||||
if (timeout is not None
|
||||
and timeout < parms['timeout'] - curtime):
|
||||
continue # timeout smaller than the current session
|
||||
# needs
|
||||
timeout = parms['timeout'] - curtime # set new timeout
|
||||
@@ -1160,8 +1163,8 @@ class Session(object):
|
||||
if parms['timeout'] <= curtime:
|
||||
timeout = 0
|
||||
break
|
||||
if (timeout is not None and
|
||||
timeout < parms['timeout'] - curtime):
|
||||
if (timeout is not None
|
||||
and timeout < parms['timeout'] - curtime):
|
||||
continue
|
||||
timeout = parms['timeout'] - curtime
|
||||
# If the loop above found no sessions wanting *and* the caller had no
|
||||
@@ -1305,17 +1308,17 @@ class Session(object):
|
||||
def _handle_ipmi_packet(self, data, sockaddr=None, qent=None):
|
||||
if self.sockaddr is None and sockaddr is not None:
|
||||
self.sockaddr = sockaddr
|
||||
elif (self.sockaddr is not None and
|
||||
sockaddr is not None and
|
||||
self.sockaddr != sockaddr):
|
||||
elif (self.sockaddr is not None
|
||||
and sockaddr is not None
|
||||
and self.sockaddr != sockaddr):
|
||||
return # here, we might have sent an ipv4 and ipv6 packet to kick
|
||||
# things off ignore the second reply since we have one
|
||||
# satisfactory answer
|
||||
if data[4] in (0, 2): # This is an ipmi 1.5 paylod
|
||||
remseqnumber = struct.unpack('<I', bytes(data[5:9]))[0]
|
||||
remsessid = struct.unpack("<I", bytes(data[9:13]))[0]
|
||||
if (remseqnumber == 0 and remsessid == 0 and
|
||||
qent[2] in Session.bmc_handlers):
|
||||
if (remseqnumber == 0 and remsessid == 0
|
||||
and qent[2] in Session.bmc_handlers):
|
||||
# So a new ipmi client happens to get a previously seen and
|
||||
# still active UDP source port. Clear ourselves out and punt
|
||||
# to IpmiServer
|
||||
@@ -1324,8 +1327,8 @@ class Session(object):
|
||||
iserver.pktqueue.append(qent)
|
||||
iserver.process_pktqueue()
|
||||
return
|
||||
if (hasattr(self, 'remseqnumber') and
|
||||
remseqnumber < self.remseqnumber):
|
||||
if (hasattr(self, 'remseqnumber')
|
||||
and remseqnumber < self.remseqnumber):
|
||||
return -5 # remote sequence number is too low, reject it
|
||||
self.remseqnumber = remseqnumber
|
||||
if data[4] != self.authtype:
|
||||
@@ -1402,9 +1405,9 @@ class Session(object):
|
||||
if sid != self.localsid: # session id mismatch, drop it
|
||||
return
|
||||
remseqnumber = struct.unpack("<I", bytes(data[10:14]))[0]
|
||||
if (hasattr(self, 'remseqnumber') and
|
||||
(remseqnumber < self.remseqnumber) and
|
||||
(self.remseqnumber != 0xffffffff)):
|
||||
if (hasattr(self, 'remseqnumber')
|
||||
and (remseqnumber < self.remseqnumber)
|
||||
and (self.remseqnumber != 0xffffffff)):
|
||||
return
|
||||
self.remseqnumber = remseqnumber
|
||||
psize = data[14] + (data[15] << 8)
|
||||
@@ -1520,11 +1523,11 @@ class Session(object):
|
||||
self.remoterandombytes = bytes(data[8:24])
|
||||
self.remoteguid = bytes(data[24:40])
|
||||
userlen = len(self.userid)
|
||||
hmacdata = (struct.pack("<II", localsid, self.pendingsessionid) +
|
||||
self.randombytes + self.remoterandombytes +
|
||||
self.remoteguid + struct.pack(
|
||||
"2B", self.nameonly | self.privlevel, userlen) +
|
||||
self.userid)
|
||||
hmacdata = (struct.pack("<II", localsid, self.pendingsessionid)
|
||||
+ self.randombytes + self.remoterandombytes
|
||||
+ self.remoteguid + struct.pack(
|
||||
"2B", self.nameonly | self.privlevel, userlen)
|
||||
+ self.userid)
|
||||
expectedhash = hmac.new(self.password, hmacdata,
|
||||
self.currhashlib).digest()
|
||||
hashlen = len(expectedhash)
|
||||
@@ -1536,10 +1539,10 @@ class Session(object):
|
||||
# We have now validated that the BMC and client agree on password, time
|
||||
# to store the keys
|
||||
self.sik = hmac.new(self.kg,
|
||||
self.randombytes + self.remoterandombytes +
|
||||
struct.pack("2B", self.nameonly | self.privlevel,
|
||||
userlen) +
|
||||
self.userid, self.currhashlib).digest()
|
||||
self.randombytes + self.remoterandombytes
|
||||
+ struct.pack(
|
||||
"2B", self.nameonly | self.privlevel, userlen)
|
||||
+ self.userid, self.currhashlib).digest()
|
||||
self.k1 = hmac.new(self.sik, b'\x01' * 20, self.currhashlib).digest()
|
||||
self.k2 = hmac.new(self.sik, b'\x02' * 20, self.currhashlib).digest()
|
||||
self.aeskey = self.k2[0:16]
|
||||
@@ -1640,8 +1643,8 @@ class Session(object):
|
||||
# second response is the real response.
|
||||
# If the message is send crrectly, we will discard the first
|
||||
# response or else error message will be parsed and return.
|
||||
if ((entry[0] in [0x06, 0x07]) and (entry[2] == 0x34) and
|
||||
(payload[-2] == 0x0)):
|
||||
if ((entry[0] in [0x06, 0x07]) and (entry[2] == 0x34)
|
||||
and (payload[-2] == 0x0)):
|
||||
return -1
|
||||
else:
|
||||
self._parse_payload(payload)
|
||||
@@ -1718,8 +1721,8 @@ class Session(object):
|
||||
# delayed in this case, it's safe to just redo the request
|
||||
self.lastpayload = None
|
||||
self._open_rmcpplus_request()
|
||||
elif (self.sessioncontext == 'EXPECTINGRAKP2' or
|
||||
self.sessioncontext == 'EXPECTINGRAKP4'):
|
||||
elif (self.sessioncontext == 'EXPECTINGRAKP2'
|
||||
or self.sessioncontext == 'EXPECTINGRAKP4'):
|
||||
# If we can't be sure which RAKP was dropped or if RAKP3/4 was just
|
||||
# delayed, the most reliable thing to do is rewind and start over
|
||||
# bmcs do not take kindly to receiving RAKP1 or RAKP3 twice
|
||||
@@ -1827,8 +1830,8 @@ class Session(object):
|
||||
# replace this one
|
||||
myport = self.socket.getsockname()[1]
|
||||
for sockaddr in self.allsockaddrs:
|
||||
if (sockaddr in Session.bmc_handlers and
|
||||
myport in Session.bmc_handlers[sockaddr]):
|
||||
if (sockaddr in Session.bmc_handlers
|
||||
and myport in Session.bmc_handlers[sockaddr]):
|
||||
del Session.bmc_handlers[sockaddr][myport]
|
||||
if Session.bmc_handlers[sockaddr] == {}:
|
||||
del Session.bmc_handlers[sockaddr]
|
||||
|
||||
@@ -366,9 +366,10 @@ class Session(object):
|
||||
# we are always the requestor for now
|
||||
seqincrement = 7 # IPMI spec forbids gaps bigger then 7 in seq number.
|
||||
# Risk the taboo rather than violate the rules
|
||||
while (not self.servermode and
|
||||
(netfn, command, self.seqlun) in self.tabooseq and
|
||||
self.tabooseq[(netfn, command, self.seqlun)] and seqincrement):
|
||||
while (not self.servermode
|
||||
and (netfn, command, self.seqlun) in self.tabooseq
|
||||
and self.tabooseq[(netfn, command, self.seqlun)]
|
||||
and seqincrement):
|
||||
self.tabooseq[(self.expectednetfn, command, self.seqlun)] -= 1
|
||||
# Allow taboo to eventually expire after a few rounds
|
||||
self.seqlun += 1 # the last two bits are lun, so add 4 to add 1
|
||||
@@ -455,8 +456,8 @@ class Session(object):
|
||||
callback=None,
|
||||
rslun=0):
|
||||
if not self.logged:
|
||||
if (self.logoutexpiry is not None and
|
||||
_monotonic_time() > self.logoutexpiry):
|
||||
if (self.logoutexpiry is not None
|
||||
and _monotonic_time() > self.logoutexpiry):
|
||||
self._mark_broken()
|
||||
raise exc.IpmiException('Session no longer connected')
|
||||
self._cmdwait()
|
||||
@@ -911,17 +912,17 @@ class Session(object):
|
||||
def _handle_ipmi_packet(self, data, sockaddr=None, qent=None):
|
||||
if self.sockaddr is None and sockaddr is not None:
|
||||
self.sockaddr = sockaddr
|
||||
elif (self.sockaddr is not None and
|
||||
sockaddr is not None and
|
||||
self.sockaddr != sockaddr):
|
||||
elif (self.sockaddr is not None
|
||||
and sockaddr is not None
|
||||
and self.sockaddr != sockaddr):
|
||||
return # here, we might have sent an ipv4 and ipv6 packet to kick
|
||||
# things off ignore the second reply since we have one
|
||||
# satisfactory answer
|
||||
if data[4] in (0, 2): # This is an ipmi 1.5 paylod
|
||||
remseqnumber = struct.unpack('<I', bytes(data[5:9]))[0]
|
||||
remsessid = struct.unpack("<I", bytes(data[9:13]))[0]
|
||||
if (hasattr(self, 'remseqnumber') and
|
||||
remseqnumber < self.remseqnumber):
|
||||
if (hasattr(self, 'remseqnumber')
|
||||
and remseqnumber < self.remseqnumber):
|
||||
return -5 # remote sequence number is too low, reject it
|
||||
self.remseqnumber = remseqnumber
|
||||
if data[4] != self.authtype:
|
||||
@@ -997,9 +998,9 @@ class Session(object):
|
||||
if sid != self.localsid: # session id mismatch, drop it
|
||||
return
|
||||
remseqnumber = struct.unpack("<I", bytes(data[10:14]))[0]
|
||||
if (hasattr(self, 'remseqnumber') and
|
||||
(remseqnumber < self.remseqnumber) and
|
||||
(self.remseqnumber != 0xffffffff)):
|
||||
if (hasattr(self, 'remseqnumber')
|
||||
and (remseqnumber < self.remseqnumber)
|
||||
and (self.remseqnumber != 0xffffffff)):
|
||||
return
|
||||
self.remseqnumber = remseqnumber
|
||||
psize = data[14] + (data[15] << 8)
|
||||
@@ -1115,11 +1116,11 @@ class Session(object):
|
||||
self.remoterandombytes = bytes(data[8:24])
|
||||
self.remoteguid = bytes(data[24:40])
|
||||
userlen = len(self.userid)
|
||||
hmacdata = (struct.pack("<II", localsid, self.pendingsessionid) +
|
||||
self.randombytes + self.remoterandombytes +
|
||||
self.remoteguid + struct.pack(
|
||||
"2B", self.nameonly | self.privlevel, userlen) +
|
||||
self.userid)
|
||||
hmacdata = (struct.pack("<II", localsid, self.pendingsessionid)
|
||||
+ self.randombytes + self.remoterandombytes
|
||||
+ self.remoteguid + struct.pack("2B", self.nameonly
|
||||
| self.privlevel, userlen)
|
||||
+ self.userid)
|
||||
expectedhash = hmac.new(self.password, hmacdata,
|
||||
self.currhashlib).digest()
|
||||
hashlen = len(expectedhash)
|
||||
@@ -1131,10 +1132,10 @@ class Session(object):
|
||||
# We have now validated that the BMC and client agree on password, time
|
||||
# to store the keys
|
||||
self.sik = hmac.new(self.kg,
|
||||
self.randombytes + self.remoterandombytes +
|
||||
struct.pack("2B", self.nameonly | self.privlevel,
|
||||
userlen) +
|
||||
self.userid, self.currhashlib).digest()
|
||||
self.randombytes + self.remoterandombytes
|
||||
+ struct.pack("2B", self.nameonly
|
||||
| self.privlevel, userlen)
|
||||
+ self.userid, self.currhashlib).digest()
|
||||
self.k1 = hmac.new(self.sik, b'\x01' * 20, self.currhashlib).digest()
|
||||
self.k2 = hmac.new(self.sik, b'\x02' * 20, self.currhashlib).digest()
|
||||
self.aeskey = self.k2[0:16]
|
||||
@@ -1226,8 +1227,9 @@ class Session(object):
|
||||
# second response is the real response.
|
||||
# If the message is send crrectly, we will discard the first
|
||||
# response or else error message will be parsed and return.
|
||||
if ((entry[0] in [0x06, 0x07]) and (entry[2] == 0x34) and
|
||||
(payload[-2] == 0x0)):
|
||||
if ((entry[0] in [0x06, 0x07])
|
||||
and (entry[2] == 0x34)
|
||||
and (payload[-2] == 0x0)):
|
||||
return -1
|
||||
else:
|
||||
self._parse_payload(payload)
|
||||
@@ -1302,8 +1304,8 @@ class Session(object):
|
||||
# delayed in this case, it's safe to just redo the request
|
||||
self.lastpayload = None
|
||||
self._open_rmcpplus_request()
|
||||
elif (self.sessioncontext == 'EXPECTINGRAKP2' or
|
||||
self.sessioncontext == 'EXPECTINGRAKP4'):
|
||||
elif (self.sessioncontext == 'EXPECTINGRAKP2'
|
||||
or self.sessioncontext == 'EXPECTINGRAKP4'):
|
||||
# If we can't be sure which RAKP was dropped or if RAKP3/4 was just
|
||||
# delayed, the most reliable thing to do is rewind and start over
|
||||
# bmcs do not take kindly to receiving RAKP1 or RAKP3 twice
|
||||
|
||||
@@ -84,8 +84,8 @@ def get_ipmi_error(response, suffix=""):
|
||||
return False
|
||||
command = response['command']
|
||||
netfn = response['netfn']
|
||||
if ((netfn, command) in constants.command_completion_codes and
|
||||
code in constants.command_completion_codes[(netfn, command)]):
|
||||
if ((netfn, command) in constants.command_completion_codes
|
||||
and code in constants.command_completion_codes[(netfn, command)]):
|
||||
res = constants.command_completion_codes[(netfn, command)][code]
|
||||
res += suffix
|
||||
elif code in constants.ipmi_completion_codes:
|
||||
|
||||
@@ -540,8 +540,8 @@ class SDREntry(object):
|
||||
self._set_tmp_formula(value)
|
||||
linearization = 0
|
||||
# time to compute the pre-linearization value.
|
||||
decoded = float((value * self.m + self.b) *
|
||||
(10 ** self.resultexponent))
|
||||
decoded = float((value * self.m + self.b)
|
||||
* (10 ** self.resultexponent))
|
||||
if linearization == 0:
|
||||
return decoded
|
||||
elif linearization == 1:
|
||||
@@ -602,10 +602,8 @@ class SDREntry(object):
|
||||
tstr = ""
|
||||
while len(data) >= 3: # the packing only works with 3 byte chunks
|
||||
tstr += chr((data[0] & 0b111111) + 0x20)
|
||||
tstr += chr(((data[1] & 0b1111) << 2) +
|
||||
(data[0] >> 6) + 0x20)
|
||||
tstr += chr(((data[2] & 0b11) << 4) +
|
||||
(data[1] >> 4) + 0x20)
|
||||
tstr += chr(((data[1] & 0b1111) << 2) + (data[0] >> 6) + 0x20)
|
||||
tstr += chr(((data[2] & 0b11) << 4) + (data[1] >> 4) + 0x20)
|
||||
tstr += chr((data[2] >> 2) + 0x20)
|
||||
if not isinstance(tstr, str):
|
||||
tstr = tstr.decode('utf-8')
|
||||
|
||||
@@ -100,11 +100,11 @@ def _to_boolean(attrval):
|
||||
attrval = attrval.lower()
|
||||
if not attrval:
|
||||
return False
|
||||
if ('true'.startswith(attrval) or 'yes'.startswith(attrval) or
|
||||
'enabled'.startswith(attrval) or attrval == '1'):
|
||||
if ('true'.startswith(attrval) or 'yes'.startswith(attrval)
|
||||
or 'enabled'.startswith(attrval) or attrval == '1'):
|
||||
return True
|
||||
if ('false'.startswith(attrval) or 'no'.startswith(attrval) or
|
||||
'disabled'.startswith(attrval) or attrval == '0'):
|
||||
if ('false'.startswith(attrval) or 'no'.startswith(attrval)
|
||||
or 'disabled'.startswith(attrval) or attrval == '0'):
|
||||
return False
|
||||
raise Exception(
|
||||
'Unrecognized candidate for boolean: {0}'.format(attrval))
|
||||
@@ -542,8 +542,8 @@ class Command(object):
|
||||
if reqpowerstate in ('softoff', 'shutdown'):
|
||||
reqpowerstate = 'off'
|
||||
timeout = os.times()[4] + 300
|
||||
while (self.get_power()['powerstate'] != reqpowerstate and
|
||||
os.times()[4] < timeout):
|
||||
while (self.get_power()['powerstate'] != reqpowerstate
|
||||
and os.times()[4] < timeout):
|
||||
time.sleep(1)
|
||||
if self.get_power()['powerstate'] != reqpowerstate:
|
||||
raise exc.PyghmiException(
|
||||
@@ -619,19 +619,19 @@ class Command(object):
|
||||
elif overridestate == 'Continuous':
|
||||
persistent = True
|
||||
else:
|
||||
raise exc.PyghmiException('Unrecognized Boot state: ' +
|
||||
repr(overridestate))
|
||||
raise exc.PyghmiException('Unrecognized Boot state: %s'
|
||||
% repr(overridestate))
|
||||
uefimode = result.get('Boot', {}).get('BootSourceOverrideMode', None)
|
||||
if uefimode == 'UEFI':
|
||||
uefimode = True
|
||||
elif uefimode == 'Legacy':
|
||||
uefimode = False
|
||||
else:
|
||||
raise exc.PyghmiException('Unrecognized mode: ' + uefimode)
|
||||
raise exc.PyghmiException('Unrecognized mode: %s' % uefimode)
|
||||
bootdev = result.get('Boot', {}).get('BootSourceOverrideTarget', None)
|
||||
if bootdev not in boot_devices_read:
|
||||
raise exc.PyghmiException('Unrecognized boot target: ' +
|
||||
repr(bootdev))
|
||||
raise exc.PyghmiException('Unrecognized boot target: %s'
|
||||
% repr(bootdev))
|
||||
bootdev = boot_devices_read[bootdev]
|
||||
return {'bootdev': bootdev, 'persistent': persistent,
|
||||
'uefimode': uefimode}
|
||||
@@ -656,10 +656,10 @@ class Command(object):
|
||||
:returns: dict or True -- If callback is not provided, the response
|
||||
"""
|
||||
reqbootdev = bootdev
|
||||
if (bootdev not in boot_devices_write and
|
||||
bootdev not in boot_devices_read):
|
||||
raise exc.InvalidParameterValue('Unsupported device ' +
|
||||
repr(bootdev))
|
||||
if (bootdev not in boot_devices_write
|
||||
and bootdev not in boot_devices_read):
|
||||
raise exc.InvalidParameterValue('Unsupported device %s'
|
||||
% repr(bootdev))
|
||||
bootdev = boot_devices_write.get(bootdev, bootdev)
|
||||
if bootdev == 'None':
|
||||
payload = {'Boot': {'BootSourceOverrideEnabled': 'Disabled'}}
|
||||
@@ -1100,8 +1100,8 @@ class Command(object):
|
||||
'{0}'.format(','.join(sorted(blameattrs)))
|
||||
)
|
||||
raise exc.InvalidParameterValue(errstr)
|
||||
if (currsettings.get(change, {}).get('possible', []) and
|
||||
changeval not in currsettings[change]['possible']):
|
||||
if (currsettings.get(change, {}).get('possible', [])
|
||||
and changeval not in currsettings[change]['possible']):
|
||||
normval = changeval.lower()
|
||||
normval = re.sub(r'\s+', ' ', normval)
|
||||
if not normval.endswith('*'):
|
||||
@@ -1148,15 +1148,15 @@ class Command(object):
|
||||
if ipv4_configuration.lower() == 'dhcp':
|
||||
dodhcp = True
|
||||
patch['DHCPv4'] = {'DHCPEnabled': True}
|
||||
elif (ipv4_configuration == 'static' or
|
||||
'IPv4StaticAddresses' in patch):
|
||||
elif (ipv4_configuration == 'static'
|
||||
or 'IPv4StaticAddresses' in patch):
|
||||
dodhcp = False
|
||||
patch['DHCPv4'] = {'DHCPEnabled': False}
|
||||
if patch:
|
||||
nicurl = self._get_bmc_nic_url(name)
|
||||
try:
|
||||
self._do_web_request(nicurl, patch, 'PATCH')
|
||||
except exc.RedfishError as e:
|
||||
except exc.RedfishError:
|
||||
patch = {'IPv4Addresses': [ipinfo]}
|
||||
if dodhcp:
|
||||
ipinfo['AddressOrigin'] = 'DHCP'
|
||||
|
||||
@@ -61,8 +61,8 @@ def read_hpm(filename):
|
||||
currsec.data = hpmfile.read(currlen)
|
||||
hpminfo.append(currsec)
|
||||
sectype, compid = struct.unpack('BB', hpmfile.read(2))
|
||||
upimg = (hpminfo[1].data[:-hpminfo[1].hash_size] +
|
||||
hpminfo[2].data[:-hpminfo[2].hash_size])
|
||||
upimg = (hpminfo[1].data[:-hpminfo[1].hash_size]
|
||||
+ hpminfo[2].data[:-hpminfo[2].hash_size])
|
||||
hpminfo[2].combo_image = upimg
|
||||
hpminfo[1].combo_image = upimg
|
||||
currpos = hpmfile.tell()
|
||||
@@ -314,8 +314,8 @@ class TsmHandler(generic.OEMHandler):
|
||||
break
|
||||
if rsp.get('state', 0) in (6, 10):
|
||||
raise Exception('Update Failure')
|
||||
if (rsp.get('state', 0) == 8 and
|
||||
rsp.get('progress', 0) > 0 and progress):
|
||||
if (rsp.get('state', 0) == 8
|
||||
and rsp.get('progress', 0) > 0 and progress):
|
||||
progress({
|
||||
'phase': 'apply',
|
||||
'progress': 70 + float(rsp.get(
|
||||
|
||||
@@ -78,14 +78,14 @@ class OEMHandler(generic.OEMHandler):
|
||||
bdata = {}
|
||||
if 'versionStr' in firm and firm['versionStr']:
|
||||
bdata['version'] = firm['versionStr']
|
||||
if ('releaseDate' in firm and
|
||||
firm['releaseDate'] and
|
||||
firm['releaseDate'] != 'N/A'):
|
||||
if ('releaseDate' in firm
|
||||
and firm['releaseDate']
|
||||
and firm['releaseDate'] != 'N/A'):
|
||||
try:
|
||||
bdata['date'] = parse_time(firm['releaseDate'])
|
||||
except ValueError:
|
||||
pass
|
||||
yield ('{0} {1}'.format(aname, fname), bdata)
|
||||
yield '{0} {1}'.format(aname, fname), bdata
|
||||
|
||||
def _get_disk_firmware_single(self, diskent, prefix=''):
|
||||
bdata = {}
|
||||
@@ -346,8 +346,9 @@ class OEMHandler(generic.OEMHandler):
|
||||
elif strsize in ('remainder', 'rest'):
|
||||
volsize = remainingcap
|
||||
elif strsize.endswith('%'):
|
||||
volsize = int(params['capacity'] *
|
||||
float(strsize.replace('%', '')) / 100.0)
|
||||
volsize = int(params['capacity']
|
||||
* float(strsize.replace('%', ''))
|
||||
/ 100.0)
|
||||
else:
|
||||
try:
|
||||
volsize = int(strsize)
|
||||
@@ -403,8 +404,9 @@ class OEMHandler(generic.OEMHandler):
|
||||
|
||||
@property
|
||||
def wc(self):
|
||||
if (not self._wc or (self._wc.vintage and
|
||||
self._wc.vintage < util._monotonic_time() - 30)):
|
||||
if (not self._wc or (self._wc.vintage
|
||||
and self._wc.vintage < util._monotonic_time()
|
||||
- 30)):
|
||||
self._wc = self.get_webclient()
|
||||
return self._wc
|
||||
|
||||
@@ -533,8 +535,8 @@ class OEMHandler(generic.OEMHandler):
|
||||
progress({'phase': 'upload',
|
||||
'progress': 100.0 * rsp['received'] / rsp['size']})
|
||||
elif rsp['state'] != 'done':
|
||||
if (rsp.get('status', None) == 413 or
|
||||
uploadthread.rspstatus == 413):
|
||||
if (rsp.get('status', None) == 413
|
||||
or uploadthread.rspstatus == 413):
|
||||
raise Exception('File is larger than supported')
|
||||
raise Exception('Unexpected result:' + repr(rsp))
|
||||
uploadstate = rsp['state']
|
||||
@@ -662,8 +664,7 @@ class OEMHandler(generic.OEMHandler):
|
||||
|
||||
if rsp.get('return', -1) != 0:
|
||||
errmsg = repr(rsp) if rsp else self.wc.lastjsonerror
|
||||
raise Exception('Unexpected result starting update: ' +
|
||||
errmsg)
|
||||
raise Exception('Unexpected result starting update: %s' % errmsg)
|
||||
complete = False
|
||||
while not complete:
|
||||
time.sleep(3)
|
||||
@@ -677,15 +678,15 @@ class OEMHandler(generic.OEMHandler):
|
||||
if rsp['items'][0]['action_state'] == 'Complete OK':
|
||||
complete = True
|
||||
if rsp['items'][0]['action_status'] != 0:
|
||||
raise Exception('Unexpected failure: ' + repr(rsp))
|
||||
raise Exception('Unexpected failure: %s' % repr(rsp))
|
||||
break
|
||||
if (rsp['items'][0]['action_state'] == 'In Progress' and
|
||||
rsp['items'][0]['action_status'] == 2):
|
||||
if (rsp['items'][0]['action_state'] == 'In Progress'
|
||||
and rsp['items'][0]['action_status'] == 2):
|
||||
raise Exception('Unexpected failure: ' + repr(rsp))
|
||||
if rsp['items'][0]['action_state'] != 'In Progress':
|
||||
raise Exception(
|
||||
'Unknown condition waiting for '
|
||||
'firmware update: ' + repr(rsp))
|
||||
'firmware update: %s' % repr(rsp))
|
||||
if bank == 'backup':
|
||||
return 'complete'
|
||||
return 'pending'
|
||||
|
||||
@@ -94,18 +94,16 @@ def get_upload_form(filename, data, formname, otherfields):
|
||||
data = data.read()
|
||||
except AttributeError:
|
||||
pass
|
||||
form = (b'--' +
|
||||
BND +
|
||||
'\r\nContent-Disposition: form-data; '
|
||||
'name="{0}"; filename="{1}"\r\n'.format(
|
||||
formname, filename).encode('utf-8'))
|
||||
form = (b'--' + BND
|
||||
+ '\r\nContent-Disposition: form-data; '
|
||||
'name="{0}"; filename="{1}"\r\n'.format(
|
||||
formname, filename).encode('utf-8'))
|
||||
form += b'Content-Type: application/octet-stream\r\n\r\n' + data
|
||||
for ofield in otherfields:
|
||||
form += (b'\r\n--' +
|
||||
BND +
|
||||
'\r\nContent-Disposition: form-data; '
|
||||
'name="{0}"\r\n\r\n{1}'.format(
|
||||
ofield, otherfields[ofield]).encode('utf-8'))
|
||||
form += (b'\r\n--' + BND
|
||||
+ '\r\nContent-Disposition: form-data; '
|
||||
'name="{0}"\r\n\r\n{1}'.format(
|
||||
ofield, otherfields[ofield]).encode('utf-8'))
|
||||
form += b'\r\n--' + BND + b'--\r\n'
|
||||
uploadforms[filename] = form
|
||||
return form
|
||||
@@ -304,8 +302,8 @@ class SecureHTTPConnection(httplib.HTTPConnection, object):
|
||||
pass
|
||||
self.rspstatus = rsp.status
|
||||
if rsp.status != 200:
|
||||
raise Exception('Unexpected response in file upload: ' +
|
||||
rsp.read())
|
||||
raise Exception('Unexpected response in file upload: %s'
|
||||
% rsp.read())
|
||||
body = rsp.read()
|
||||
if rsp.getheader('Content-Encoding', None) == 'gzip':
|
||||
body = gzip.GzipFile(fileobj=io.BytesIO(body)).read()
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
hacking>=1.1.0,<1.2.0
|
||||
|
||||
hacking>=3.0.0,<3.1.0 # Apache-2.0
|
||||
|
||||
coverage>=4.0
|
||||
fixtures>=3.0.0
|
||||
python-subunit>=1.0.0
|
||||
@@ -9,4 +11,4 @@ stestr>=1.0.0 # Apache-2.0
|
||||
testscenarios>=0.4
|
||||
testtools>=2.2.0
|
||||
oslotest>=3.2.0 # Apache-2.0
|
||||
flake8-import-order>=0.13 # LGPLv3
|
||||
flake8-import-order>=0.13 # LGPLv3
|
||||
|
||||
4
tox.ini
4
tox.ini
@@ -45,8 +45,8 @@ exclude = .venv,.git,.tox,dist,doc,*lib/python*,*egg,build
|
||||
show-source = true
|
||||
# E129 visually indented line with same indent as next logical line
|
||||
# E731 do not assign a lambda expression, use a def
|
||||
# W504 line break after binary operator
|
||||
ignore = E129,E731,W504
|
||||
# W503 Line break occurred before a binary operator. Conflicts with W504.
|
||||
ignore = E129,E731,W503
|
||||
# H106: Don't put vim configuration in source files
|
||||
# H203: Use assertIs(Not)None to check for None
|
||||
# H204: Use assert(Not)Equal to check for equality
|
||||
|
||||
Reference in New Issue
Block a user