Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add service check to the SNMP check #1236

Merged
merged 2 commits into from
Dec 22, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 37 additions & 17 deletions checks.d/snmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ def reply_invalid(oid):
class SnmpCheck(AgentCheck):

cmd_generator = None
# pysnmp default values
RETRIES = 5
TIMEOUT = 1

def __init__(self, name, init_config, agentConfig, instances=None):
AgentCheck.__init__(self, name, init_config, agentConfig, instances)
Expand Down Expand Up @@ -91,15 +94,15 @@ def get_auth_data(cls, instance):
raise Exception("An authentication method needs to be provided")

@classmethod
def get_transport_target(cls, instance):
def get_transport_target(cls, instance, timeout, retries):
'''
Generate a Transport target object based on the instance's configuration
'''
if "ip_address" not in instance:
raise Exception("An IP address needs to be specified")
ip_address = instance["ip_address"]
port = instance.get("port", 161) # Default SNMP port
return cmdgen.UdpTransportTarget((ip_address, port))
return cmdgen.UdpTransportTarget((ip_address, port), timeout=timeout, retries=retries)

def check_table(self, instance, oids, lookup_names):
'''
Expand All @@ -112,7 +115,7 @@ def check_table(self, instance, oids, lookup_names):
dict[oid/metric_name][row index] = value
In case of scalar objects, the row index is just 0
'''
transport_target = self.get_transport_target(instance)
transport_target = self.get_transport_target(instance, self.TIMEOUT, self.RETRIES)
auth_data = self.get_auth_data(instance)

snmp_command = self.cmd_generator.nextCmd
Expand All @@ -126,12 +129,16 @@ def check_table(self, instance, oids, lookup_names):

results = defaultdict(dict)
if error_indication:
raise Exception("{0} for instance {1}".format(error_indication,
instance["ip_address"]))
message = "{0} for instance {1}".format(error_indication,
instance["ip_address"])
instance["service_check_error"] = message
raise Exception(message)
else:
if error_status:
self.log.warning("{0} for instance {1}".format(error_status.prettyPrint(),
instance["ip_address"]))
message = "{0} for instance {1}".format(error_status.prettyPrint(),
instance["ip_address"])
instance["service_check_error"] = message
self.log.warning(message)
else:
for table_row in var_binds:
for result_oid, value in table_row:
Expand Down Expand Up @@ -177,16 +184,29 @@ def check(self, instance):
raw_oids.append(metric['OID'])
else:
raise Exception('Unsupported metric in config file: %s' % metric)

if table_oids:
self.log.debug("Querying device %s for %s oids", ip_address, len(table_oids))
table_results = self.check_table(instance, table_oids, True)
self.report_table_metrics(instance, table_results)

if raw_oids:
self.log.debug("Querying device %s for %s oids", ip_address, len(raw_oids))
raw_results = self.check_table(instance, raw_oids, False)
self.report_raw_metrics(instance, raw_results)
try:
if table_oids:
self.log.debug("Querying device %s for %s oids", ip_address, len(table_oids))
table_results = self.check_table(instance, table_oids, True)
self.report_table_metrics(instance, table_results)

if raw_oids:
self.log.debug("Querying device %s for %s oids", ip_address, len(raw_oids))
raw_results = self.check_table(instance, raw_oids, False)
self.report_raw_metrics(instance, raw_results)
except Exception as e:
if "service_check_error" not in instance:
instance["service_check_error"] = "Fail to collect metrics: {0}".format(e)
raise
finally:
# Report service checks
service_check_name = "snmp.can_check"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you set this variable as a class-level variable as it's done for the other checks for consistency

tags = ["snmp_device:%s" % ip_address]
if "service_check_error" in instance:
self.service_check(service_check_name, AgentCheck.CRITICAL, tags=tags,
message=instance["service_check_error"])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we look at line 140/141, we can set service_check_error without raising, and because you never reset this key in the instance dict, it will fail indefinitely?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I kept the previous logic around error_indication and error_status, however in both case I'll return a ERROR service check.
So this service check will be ERROR if we get at least one error somewhere, OK otherwise.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You sneaky deepcopy 🙈

else:
self.service_check(service_check_name, AgentCheck.OK, tags=tags)

def report_raw_metrics(self, instance, results):
'''
Expand Down
97 changes: 97 additions & 0 deletions tests/test_snmp.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,17 @@ def test_scalar_SNMPCheck(self):
else:
self.fail("Missing metric: %s" % metric)

# Service checks
service_checks = self.check.get_service_checks()
service_checks = [sc for sc in service_checks if sc['check'].startswith('snmp')]
service_checks_count = len(service_checks)
# We run the check twice
self.assertEquals(service_checks_count, 2, service_checks)
for sc in service_checks:
self.assertEquals(sc['status'], self.check.OK, sc)
self.assertEquals(sc['tags'], ['snmp_device:localhost'], sc)


def test_table_SNMPCheck(self):
self.config = {
"instances": [{
Expand Down Expand Up @@ -130,5 +141,91 @@ def test_table_SNMPCheck(self):
else:
self.fail("Tag discovered not pretty printed %s" % interface_type)

# Service checks
service_checks = self.check.get_service_checks()
service_checks = [sc for sc in service_checks if sc['check'].startswith('snmp')]
service_checks_count = len(service_checks)
# We run the check twice
self.assertEquals(service_checks_count, 2, service_checks)
for sc in service_checks:
self.assertEquals(sc['status'], self.check.OK, sc)
self.assertEquals(sc['tags'], ['snmp_device:localhost'], sc)

def test_network_error(self):
self.config = {
"instances": [{
"ip_address": "localhost",
"port":162,
"community_string": "public",
"metrics": [{
"MIB": "IF-MIB",
"table": "ifTable",
"symbols": ["ifInOctets", "ifOutOctets"],
"metric_tags": [{
"tag":"interface",
"column":"ifDescr"
}, {
"tag":"dumbindex",
"index":1
}]
}]
}]
}

self.check = load_check('snmp', self.config, self.agentConfig)

# Make it fails faster
self.check.RETRIES = 0
self.check.TIMEOUT = 0.5

# We expect: No SNMP response received before timeout for instance localhost
self.assertRaises(Exception, self.check.check, self.config['instances'][0])

# Service checks
service_checks = self.check.get_service_checks()
service_checks = [sc for sc in service_checks if sc['check'].startswith('snmp')]
service_checks_count = len(service_checks)
self.assertEquals(service_checks_count, 1, service_checks)
for sc in service_checks:
self.assertEquals(sc['status'], self.check.CRITICAL, sc)
self.assertEquals(sc['tags'], ['snmp_device:localhost'], sc)

def test_invalid_metric(self):
self.config = {
"instances": [{
"ip_address": "localhost",
"port":161,
"community_string": "public",
"metrics": [{
"MIB": "IF-MIB",
"table": "ifTable",
"symbols": ["ifInOctets", "ifOutOctets"],
},{
"MIB": "IF-MIB",
"table": "noIdeaWhatIAmDoingHere",
"symbols": ["ifInOctets", "ifOutOctets"],
}]
}]
}

self.check = load_check('snmp', self.config, self.agentConfig)

# Make it fails faster
self.check.RETRIES = 0
self.check.TIMEOUT = 0.5

# We expect: No symbol IF-MIB::noIdeaWhatIAmDoingHere
self.assertRaises(Exception, self.check.check, self.config['instances'][0])

# Service checks
service_checks = self.check.get_service_checks()
service_checks = [sc for sc in service_checks if sc['check'].startswith('snmp')]
service_checks_count = len(service_checks)
self.assertEquals(service_checks_count, 1, service_checks)
for sc in service_checks:
self.assertEquals(sc['status'], self.check.CRITICAL, sc)
self.assertEquals(sc['tags'], ['snmp_device:localhost'], sc)


if __name__ == "__main__":
unittest.main()