Skip to content

Commit

Permalink
redfish-sel: UnboundLocalError: local variable 'sel_path' referenced…
Browse files Browse the repository at this point in the history
… before assignment (fix #779)
  • Loading branch information
markuslf committed Sep 19, 2024
1 parent 413dd07 commit 0b29964
Show file tree
Hide file tree
Showing 6 changed files with 129 additions and 51 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Icinga Director:
Monitoring Plugins:

* docker-stats: ValueError: could not convert string to float: '0B' ([#776](https://github.com/Linuxfabrik/monitoring-plugins/issues/776))
* redfish-sel: UnboundLocalError: local variable 'sel_path' referenced before assignment ([#779](https://github.com/Linuxfabrik/monitoring-plugins/issues/779))


## 2024060401
Expand Down
141 changes: 90 additions & 51 deletions check-plugins/redfish-sel/redfish-sel
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,20 @@

import argparse # pylint: disable=C0413
import base64 # pylint: disable=C0413
import json # pylint: disable=C0413
import sys # pylint: disable=C0413

import lib.args # pylint: disable=C0413
import lib.base # pylint: disable=C0413
import lib.redfish # pylint: disable=C0413
import lib.test # pylint: disable=C0413
import lib.txt # pylint: disable=C0413
import lib.url # pylint: disable=C0413
from lib.globals import (STATE_CRIT, STATE_OK, # pylint: disable=C0413
STATE_UNKNOWN, STATE_WARN)

__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2024031401'
__version__ = '2024091901'

DESCRIPTION = """Checks the System Event Log (SEL) of the Redfish Manager collection. Returns an
alert based on the severity of the messages."""
Expand Down Expand Up @@ -77,6 +80,13 @@ def parse_args():
dest='PASSWORD',
)

parser.add_argument(
'--test',
help='For unit tests. Needs "path-to-stdout-file,path-to-stderr-file,expected-retc".',
dest='TEST',
type=lib.args.csv,
)

parser.add_argument(
'--timeout',
help='Network timeout in seconds. '
Expand Down Expand Up @@ -113,38 +123,48 @@ def main():
except SystemExit:
sys.exit(STATE_UNKNOWN)

base_url = args.URL
if not args.URL.startswith('http'):
lib.base.cu('--url parameter has to start with "http://" or https://".')

# Authorization (if needed)
header = {}
header['Accept'] = 'application/json'
if args.USERNAME and args.PASSWORD:
auth = '{}:{}'.format(args.USERNAME, args.PASSWORD)
encoded_auth = lib.txt.to_text(base64.b64encode(lib.txt.to_bytes(auth)))
header['Authorization'] = 'Basic {}'.format(encoded_auth)

# get the vendor to know which entry point to use
url = '{}/redfish/v1/'.format(base_url)
result = lib.base.coe(lib.url.fetch_json(
url,
header=header,
insecure=args.INSECURE,
no_proxy=args.NO_PROXY,
timeout=args.TIMEOUT,
))
vendor = lib.redfish.get_vendor(result)

# Entry point: Get the main data
url = '{}/redfish/v1/Managers'.format(base_url)
result = lib.base.coe(lib.url.fetch_json(
url,
header=header,
insecure=args.INSECURE,
no_proxy=args.NO_PROXY,
timeout=args.TIMEOUT,
))
# fetch data
if args.TEST is None:
if not args.URL.startswith('http'):
lib.base.cu('--url parameter has to start with "http://" or https://".')

# Authorization (if needed)
header = {}
header['Accept'] = 'application/json'
if args.USERNAME and args.PASSWORD:
auth = '{}:{}'.format(args.USERNAME, args.PASSWORD)
encoded_auth = lib.txt.to_text(base64.b64encode(lib.txt.to_bytes(auth)))
header['Authorization'] = 'Basic {}'.format(encoded_auth)

# get the vendor to know which entry point to use
result = lib.base.coe(lib.url.fetch_json(
'{}/redfish/v1/'.format(args.URL),
header=header,
insecure=args.INSECURE,
no_proxy=args.NO_PROXY,
timeout=args.TIMEOUT,
))
vendor = lib.redfish.get_vendor(result)

# Entry point: Get the main data
result = lib.base.coe(lib.url.fetch_json(
'{}/redfish/v1/Managers'.format(args.URL),
header=header,
insecure=args.INSECURE,
no_proxy=args.NO_PROXY,
timeout=args.TIMEOUT,
))
else:
# do not call the command, put in test data
args.TEST[0] += '-v1'
stdout, _, _ = lib.test.test(args.TEST)
result = json.loads(stdout)
vendor = lib.redfish.get_vendor(result)

args.TEST[0] += '-managers'
stdout, _, _ = lib.test.test(args.TEST)
result = json.loads(stdout)

# "Members": [
# {
# "@odata.id": "/redfish/v1/Managers/BMC"
Expand All @@ -159,43 +179,62 @@ def main():

if vendor == 'generic':
sel_path = '/LogServices/Log/Entries'
if vendor in ['ami']:
elif vendor in ['avigilon']: # which is a relabeled dell
sel_path = '/LogServices'
elif vendor in ['ami']:
sel_path = '/LogServices/BIOS/Entries'
if vendor in ['cisco']:
elif vendor in ['cisco']:
sel_path = '/LogServices/SEL/Entries'
if vendor in ['dell']:
elif vendor in ['dell']:
sel_path = '/LogServices/Sel/Entries'
if vendor in ['hpe', 'hp']:
elif vendor in ['hpe', 'hp']:
sel_path = '/LogServices/IML/Entries'
if vendor in ['lenovo']:
elif vendor in ['lenovo']:
sel_path = '/LogServices/ActiveLog/Entries'
if vendor in ['ts_fujitsu']:
elif vendor in ['ts_fujitsu']:
sel_path = '/LogServices/SystemEventLog/Entries'
else:
sel_path = ''

member_count = 0
# fetch and analyze data by following the "Members" found
for member in result.get('Members', []):
if not sel_path:
continue
member_count += 1
# For example {https://localhost:5000/redfish/v1/Managers/} {BMC} {/LogServices/Log/Entries}
url = '{}{}{}'.format(base_url, member['@odata.id'], sel_path)
sel = lib.base.coe(lib.url.fetch_json(
url,
header=header,
insecure=args.INSECURE,
no_proxy=args.NO_PROXY,
timeout=args.TIMEOUT,
))
if args.TEST is None:
# For example {https://localhost:5000} {/redfish/v1/Managers/BMC} {/LogServices/Log/Entries} # pylint: disable=C0301
sel = lib.base.coe(lib.url.fetch_json(
'{}{}{}'.format(args.URL, member['@odata.id'], sel_path),
header=header,
insecure=args.INSECURE,
no_proxy=args.NO_PROXY,
timeout=args.TIMEOUT,
))
else:
args.TEST[0] += '-vendor'
stdout, _, _ = lib.test.test(args.TEST)
sel = json.loads(stdout)
member_msg, member_state = lib.redfish.get_manager_logservices_sel_entries(sel)
if member_msg:
msg += '{}\n{}\n\n'.format(member['@odata.id'], member_msg)
state = lib.base.get_worst(state, member_state)

if state == STATE_CRIT:
msg = 'Checked SEL on {} {}. There are critical errors.\n\n'.format(member_count, lib.txt.pluralize('member', member_count)) + msg
msg = 'Checked SEL on {} {}. There are critical errors.\n\n'.format(
member_count,
lib.txt.pluralize('member', member_count),
) + msg
elif state == STATE_WARN:
msg = 'Checked SEL on {} {}. There are warnings.\n\n'.format(member_count, lib.txt.pluralize('member', member_count)) + msg
msg = 'Checked SEL on {} {}. There are warnings.\n\n'.format(
member_count,
lib.txt.pluralize('member', member_count),
) + msg
else:
msg = 'Everything is ok, checked SEL on {} {}.\n\n'.format(member_count, lib.txt.pluralize('member', member_count)) + msg
msg = 'Everything is ok, checked SEL on {} {}.\n\n'.format(
member_count,
lib.txt.pluralize('member', member_count),
) + msg

# over and out
lib.base.oao(msg, state, always_ok=args.ALWAYS_OK)
Expand Down
35 changes: 35 additions & 0 deletions check-plugins/redfish-sel/unit-test/run
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.

# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.rst

import sys
sys.path.append("..") # Adds higher directory to python modules path.



import unittest

from lib.globals import STATE_OK, STATE_UNKNOWN, STATE_WARN, STATE_CRIT
import lib.base
import lib.shell


class TestCheck(unittest.TestCase):

check = '../redfish-sel'

def test_if_check_runs_EXAMPLE01(self):
stdout, stderr, retc = lib.base.coe(lib.shell.shell_exec(self.check + ' --test=stdout/EXAMPLE01,,0'))
self.assertIn('Everything is ok, checked SEL on 1 member.', stdout)
self.assertEqual(stderr, '')
self.assertEqual(retc, STATE_OK)


if __name__ == '__main__':
unittest.main()
1 change: 1 addition & 0 deletions check-plugins/redfish-sel/unit-test/stdout/EXAMPLE01-v1
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"@odata.context":"/redfish/v1/$metadata#ServiceRoot.ServiceRoot","@odata.id":"/redfish/v1","@odata.type":"#ServiceRoot.v1_15_0.ServiceRoot","AccountService":{"@odata.id":"/redfish/v1/AccountService"},"CertificateService":{"@odata.id":"/redfish/v1/CertificateService"},"Chassis":{"@odata.id":"/redfish/v1/Chassis"},"Description":"Root Service","EventService":{"@odata.id":"/redfish/v1/EventService"},"Fabrics":{"@odata.id":"/redfish/v1/Fabrics"},"Id":"RootService","JobService":{"@odata.id":"/redfish/v1/JobService"},"JsonSchemas":{"@odata.id":"/redfish/v1/JsonSchemas"},"LicenseService":{"@odata.id":"/redfish/v1/LicenseService"},"Links":{"Sessions":{"@odata.id":"/redfish/v1/SessionService/Sessions"}},"Managers":{"@odata.id":"/redfish/v1/Managers"},"Name":"Root Service","Oem":{"Dell":{"@odata.context":"/redfish/v1/$metadata#DellServiceRoot.DellServiceRoot","@odata.type":"#DellServiceRoot.v1_0_0.DellServiceRoot","IsBranded":1,"ManagerMACAddress":"2c:ea:7f:XX:XX:XX","ServiceTag":"XXXXXXX"}},"Product":"Integrated Remote Access Controller","ProtocolFeaturesSupported":{"DeepOperations":{"DeepPATCH":false,"DeepPOST":false},"ExcerptQuery":false,"ExpandQuery":{"ExpandAll":true,"Levels":true,"Links":true,"MaxLevels":1,"NoLinks":true},"FilterQuery":true,"OnlyMemberQuery":true,"SelectQuery":true},"RedfishVersion":"1.17.0","Registries":{"@odata.id":"/redfish/v1/Registries"},"SessionService":{"@odata.id":"/redfish/v1/SessionService"},"Systems":{"@odata.id":"/redfish/v1/Systems"},"Tasks":{"@odata.id":"/redfish/v1/TaskService"},"TelemetryService":{"@odata.id":"/redfish/v1/TelemetryService"},"UpdateService":{"@odata.id":"/redfish/v1/UpdateService"},"Vendor":"Avigilon"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"@odata.context":"/redfish/v1/$metadata#ManagerCollection.ManagerCollection","@odata.id":"/redfish/v1/Managers","@odata.type":"#ManagerCollection.ManagerCollection","Description":"BMC","Members":[{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1"}],"[email protected]":1,"Name":"Manager"}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"@odata.context":"/redfish/v1/$metadata#Manager.Manager","@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1","@odata.type":"#Manager.v1_17_0.Manager","Actions":{"#Manager.Reset":{"[email protected]":["GracefulRestart"],"target":"/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Manager.Reset"},"#Manager.ResetToDefaults":{"[email protected]":["ResetAll","PreserveNetworkAndUsers"],"target":"/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Manager.ResetToDefaults"},"Oem":{"#DellManager.ResetToDefaults":{"[email protected]":["All","Default","ResetAllWithRootDefaults"],"target":"/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/DellManager.ResetToDefaults"},"#DellManager.SetCustomDefaults":{"target":"/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/DellManager.SetCustomDefaults"},"#OemManager.ExportSystemConfiguration":{"[email protected]":["XML","JSON"],"[email protected]":["Default","Clone","Replace"],"[email protected]":["Default","IncludeReadOnly","IncludePasswordHashValues","IncludeCustomTelemetry"],"ShareParameters":{"[email protected]":["Disabled","Enabled"],"[email protected]":["Disabled","EnabledProxyDefault","Enabled"],"[email protected]":["HTTP","SOCKS4"],"[email protected]":["LOCAL","NFS","CIFS","HTTP","HTTPS"],"[email protected]":["ALL","IDRAC","BIOS","NIC","RAID","FC","InfiniBand","SupportAssist","EventFilters","System","LifecycleController","AHCI","PCIeSSD"]},"target":"/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/EID_674_Manager.ExportSystemConfiguration"},"#OemManager.ImportSystemConfiguration":{"[email protected]":["Default","DeployOnSledInsert","InstantDeploy"],"[email protected]":["On","Off"],"[email protected]":["TimeToWait","ImportBuffer"],"ShareParameters":{"[email protected]":["Disabled","Enabled"],"[email protected]":["Disabled","EnabledProxyDefault","Enabled"],"[email protected]":["HTTP","SOCKS4"],"[email protected]":["LOCAL","NFS","CIFS","HTTP","HTTPS"],"[email protected]":["ALL","IDRAC","BIOS","NIC","RAID","FC","InfiniBand","SupportAssist","EventFilters","System","LifecycleController","AHCI","PCIeSSD"]},"[email protected]":["Graceful","Forced","NoReboot"],"target":"/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/EID_674_Manager.ImportSystemConfiguration"},"#OemManager.ImportSystemConfigurationPreview":{"[email protected]":["ImportBuffer"],"ShareParameters":{"[email protected]":["Disabled","Enabled"],"[email protected]":["Disabled","EnabledProxyDefault","Enabled"],"[email protected]":["HTTP","SOCKS4"],"[email protected]":["LOCAL","NFS","CIFS","HTTP","HTTPS"],"[email protected]":["ALL"]},"target":"/redfish/v1/Managers/iDRAC.Embedded.1/Actions/Oem/EID_674_Manager.ImportSystemConfigurationPreview"}}},"CommandShell":{"ConnectTypesSupported":["SSH","IPMI"],"[email protected]":2,"MaxConcurrentSessions":5,"ServiceEnabled":true},"DateTime":"2024-09-19T07:45:11+02:00","DateTimeLocalOffset":"+02:00","Description":"BMC","EthernetInterfaces":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/EthernetInterfaces"},"FirmwareVersion":"7.00.00.172","GraphicalConsole":{"ConnectTypesSupported":["KVMIP"],"[email protected]":1,"MaxConcurrentSessions":6,"ServiceEnabled":true},"HostInterfaces":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/HostInterfaces"},"Id":"iDRAC.Embedded.1","LastResetTime":"2024-07-22T10:55:44+02:00","Links":{"ActiveSoftwareImage":{"@odata.id":"/redfish/v1/UpdateService/FirmwareInventory/Installed-25227-7.00.00.172__iDRAC.Embedded.1-1"},"ManagerForChassis":[{"@odata.id":"/redfish/v1/Chassis/System.Embedded.1"}],"[email protected]":1,"ManagerForServers":[{"@odata.id":"/redfish/v1/Systems/System.Embedded.1"}],"[email protected]":1,"ManagerInChassis":{"@odata.id":"/redfish/v1/Chassis/System.Embedded.1"},"Oem":{"Dell":{"@odata.type":"#DellOem.v1_3_0.DellOemLinks","DellAttributes":[{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellAttributes/iDRAC.Embedded.1"},{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellAttributes/System.Embedded.1"},{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellAttributes/LifecycleController.Embedded.1"}],"[email protected]":3,"DellJobService":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellJobService"},"DellLCService":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellLCService"},"DellLicensableDeviceCollection":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellLicensableDevices"},"DellLicenseCollection":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellLicenses"},"DellLicenseManagementService":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellLicenseManagementService"},"DellOpaqueManagementDataCollection":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellOpaqueManagementData"},"DellPersistentStorageService":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellPersistentStorageService"},"DellSwitchConnectionCollection":{"@odata.id":"/redfish/v1/Systems/System.Embedded.1/NetworkPorts/Oem/Dell/DellSwitchConnections"},"DellSwitchConnectionService":{"@odata.id":"/redfish/v1/Systems/System.Embedded.1/Oem/Dell/DellSwitchConnectionService"},"DellSystemManagementService":{"@odata.id":"/redfish/v1/Systems/System.Embedded.1/Oem/Dell/DellSystemManagementService"},"DellSystemQuickSyncCollection":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellSystemQuickSync"},"DellTimeService":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellTimeService"},"DellUSBDeviceCollection":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellUSBDevices"},"DelliDRACCardService":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DelliDRACCardService"},"DellvFlashCollection":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DellvFlash"},"Jobs":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs"}}},"SoftwareImages":[{"@odata.id":"/redfish/v1/UpdateService/FirmwareInventory/Previous-25227-7.00.00.171__iDRAC.Embedded.1-1"},{"@odata.id":"/redfish/v1/UpdateService/FirmwareInventory/Installed-25227-7.00.00.172__iDRAC.Embedded.1-1"}],"[email protected]":2},"LogServices":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/LogServices"},"ManagerType":"BMC","Model":"14G Monolithic","Name":"Manager","NetworkProtocol":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/NetworkProtocol"},"Oem":{"Dell":{"@odata.type":"#DellManager.v1_4_0.DellManager","DelliDRACCard":{"@odata.context":"/redfish/v1/$metadata#DelliDRACCard.DelliDRACCard","@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/DelliDRACCard/iDRAC.Embedded.1-1_0x23_IDRACinfo","@odata.type":"#DelliDRACCard.v1_1_0.DelliDRACCard","Description":"An instance of DelliDRACCard will have data specific to the Integrated Dell Remote Access Controller (iDRAC) in the managed system.","IPMIVersion":"2.0","Id":"iDRAC.Embedded.1-1_0x23_IDRACinfo","LastSystemInventoryTime":"2024-02-25T08:47:40+00:00","LastUpdateTime":"2024-09-19T05:45:02+00:00","Name":"DelliDRACCard","URLString":"https://10.123.45.138:443"},"RemoteSystemLogs":{"CA":{"Certificates":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/RemoteSystemLogs/CA/Certificates"}},"HTTPS":{"Certificates":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/RemoteSystemLogs/HTTPS/Certificates"},"SecureClientAuth":"Anonymous","SecurePort":6514,"SecureServers":[""],"[email protected]":1,"SecureSysLogEnable":"Disabled"}}}},"PowerState":"On","Redundancy":[],"[email protected]":0,"SerialConsole":{"ConnectTypesSupported":[],"[email protected]":0,"MaxConcurrentSessions":0,"ServiceEnabled":false},"SerialInterfaces":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/SerialInterfaces"},"Status":{"Health":"OK","State":"Enabled"},"TimeZoneName":"Europe/Berlin","UUID":"3339334f-c0c8-5180-4d10-00584c4c4544","VirtualMedia":{"@odata.id":"/redfish/v1/Managers/iDRAC.Embedded.1/VirtualMedia"},"[email protected]":"Please migrate to use /redfish/v1/Systems/System.Embedded.1/VirtualMedia"}

0 comments on commit 0b29964

Please sign in to comment.