"""
Definitions for MRTG
"""
class Target (object) :
"""
A monitoring target
"""
def __init__ (self, name, target_def, max_bytes, title, comment=None) :
"""
Store values corresponding to the MRTG configuration statements:
name - the unique identifier for this target
target_def - the Target[] definition, see target_def()
max_bytes - maximum number of bytes/s accepted for this interface, used to determine % load
title - human-readable title
comment - optional comment field
"""
self.name = name
self.target_def = target_def
self.max_bytes = max_bytes
self.title = title
self.comment = comment
def rrd_name (self) :
"""
Return the relative path to the .rrd file for this target
"""
return "%s.rrd" % (self.name, )
def img_name (self) :
"""
Return the relative path to the .png image for this target
"""
return "%s.png" % (self.name, )
def statement (self, name, value) :
"""
Yield the line for a single stanza:
Stanza[identifier]: value
"""
return "%s[%s]: %s" % (name, self.name, value)
def generate (self) :
"""
Return a series of lines for this target
"""
if self.comment :
yield "# %s" % (self.comment, )
yield self.statement('Target', self.target_def)
yield self.statement('MaxBytes', self.max_bytes)
yield self.statement('Title', self.title)
class Host (object) :
"""
A SNMP target
"""
def __init__ (self, name, hostname, snmp_community) :
"""
Store values corresponding to the MRTG Target stanza bits:
name - short name
hostname - the snmp target
snmp_community - the SNMP community to use
"""
self.name = name
self.hostname = hostname
self.snmp_community = snmp_community
def port (self, port_name, mbps, port=None, desc=None, port_title=None) :
"""
Create and return a Target describing the given port/interface on this host.
"""
# figure out which ifref to use
ifid = iftitle = None
for prefix, tprefix, value in (
('', "#", port),
('\\', "", desc),
) :
if value :
# ok, use this
ifid = prefix + str(value)
if port_title :
iftitle = port_title
else :
iftitle = tprefix + str(value)
break
if not ifid :
raise ValueError("No interface identifier given")
# compose
name = "%s_%s" % (self.hostname, port_name)
target = "%s:%s@%s" % (ifid, self.snmp_community, self.hostname)
max_bytes = mbps * 1000 * 1000 / 8
title = "Traffic @ %s %s -> %s" % (self.name, iftitle, port_name)
# build and return Target
return Target(name, target, max_bytes, title)
def write_cfg (path, targets) :
"""
Write out the given targets to the given file
"""
fh = open(path, 'w')
# generate() each target
for target in targets :
for line in target.generate() :
# output line
fh.write(line + '\n')
# separate by empty line
fh.write('\n')
fh.close()