Projet

Général

Profil

Révision 8152186b

ID8152186b9af6ce5fcb0cbb591818a1a793ec2982
Parent e7e8ff99
Enfant 7cf2dda9

Ajouté par Lars Kruse il y a environ 5 ans

Plugin snmp__juniper_spu: migrate to Python3

Voir les différences:

plugins/router/snmp__juniper_spu
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3

  
4
# Copyright (C) 2014 Johann Schmitz <johann@j-schmitz.net>
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU Library General Public License as published by
8
# the Free Software Foundation; version 2 only
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU Library General Public License for more details.
14
#
15
# You should have received a copy of the GNU Library General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18
#
19

  
1
#!/usr/bin/env python3
20 2
"""
21 3
=head1 NAME
22 4

  
......
27 9
Make sure your Juniper device is accessible via SNMP (e.g. via snmpwalk) and the munin-node
28 10
has been configured correctly.
29 11

  
30
=head1 MAGIC MARKERS
31

  
32
	#%# family=snmpauto
33
	#%# capabilities=snmpconf
34

  
35 12
=head1 VERSION
36 13

  
37 14
0.0.1
......
42 19

  
43 20
=head1 AUTHOR
44 21

  
45
Johann Schmitz <johann@j-schmitz.net>
22
Copyright (C) 2014 Johann Schmitz <johann@j-schmitz.net>
23

  
46 24

  
47 25
=head1 LICENSE
48 26

  
49
GPLv2
27
This program is free software; you can redistribute it and/or modify
28
it under the terms of the GNU Library General Public License as published by
29
the Free Software Foundation; version 2 only
30

  
31
This program is distributed in the hope that it will be useful,
32
but WITHOUT ANY WARRANTY; without even the implied warranty of
33
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34
GNU Library General Public License for more details.
35

  
36
You should have received a copy of the GNU Library General Public License
37
along with this program; if not, write to the Free Software
38
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
39

  
40
SPDX-License-Identifier: GPL-2.0-only
41

  
42

  
43
=head1 MAGIC MARKERS
44

  
45
 #%# family=snmpauto
46
 #%# capabilities=snmpconf
50 47

  
51 48
=cut
52 49
"""
......
65 62
debug = bool(os.getenv('MUNIN_DEBUG', os.getenv('DEBUG', 0)))
66 63

  
67 64
if debug:
68
	logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-7s %(message)s')
65
    logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-7s %(message)s')
69 66

  
70 67
try:
71
	match = re.search("^(?:|.*\/)snmp_([^_]+)_juniper_spu$", sys.argv[0])
72
	host = match.group(1)
73
	request = match.group(2)
74
	match = re.search("^([^:]+):(\d+)$", host)
75
	if match is not None:
76
		host = match.group(1)
77
		port = match.group(2)
78
except:
79
	pass
68
    match = re.search(r"^(?:|.*/)snmp_([^_]+)_juniper_spu$", sys.argv[0])
69
    host = match.group(1)
70
    request = match.group(2)
71
    match = re.search(r"^([^:]+):(\d+)$", host)
72
    if match is not None:
73
        host = match.group(1)
74
        port = match.group(2)
75
except Exception:
76
    pass
80 77

  
81 78
jnxJsSPUMonitoringObjectsTable = '1.3.6.1.4.1.2636.3.39.1.12.1.1'
82
#jnxJsSPUMonitoringIndex = jnxJsSPUMonitoringObjectsTable + '.1.1'
83
#jnxJsSPUMonitoringFPCIndex = jnxJsSPUMonitoringObjectsTable + '.1.2'
84
#jnxJsSPUMonitoringSPUIndex = jnxJsSPUMonitoringObjectsTable + '.1.3'
85
#jnxJsSPUMonitoringCPUUsage = jnxJsSPUMonitoringObjectsTable + '.1.4'
86
#jnxJsSPUMonitoringMemoryUsage = jnxJsSPUMonitoringObjectsTable + '.1.5'
79
# jnxJsSPUMonitoringIndex = jnxJsSPUMonitoringObjectsTable + '.1.1'
80
# jnxJsSPUMonitoringFPCIndex = jnxJsSPUMonitoringObjectsTable + '.1.2'
81
# jnxJsSPUMonitoringSPUIndex = jnxJsSPUMonitoringObjectsTable + '.1.3'
82
# jnxJsSPUMonitoringCPUUsage = jnxJsSPUMonitoringObjectsTable + '.1.4'
83
# jnxJsSPUMonitoringMemoryUsage = jnxJsSPUMonitoringObjectsTable + '.1.5'
87 84
jnxJsSPUMonitoringCurrentFlowSession = jnxJsSPUMonitoringObjectsTable + '.1.6'
88 85
jnxJsSPUMonitoringMaxFlowSession = jnxJsSPUMonitoringObjectsTable + '.1.7'
89 86
jnxJsSPUMonitoringCurrentCPSession = jnxJsSPUMonitoringObjectsTable + '.1.8'
90 87
jnxJsSPUMonitoringMaxCPSession = jnxJsSPUMonitoringObjectsTable + '.1.9'
91
#jnxJsSPUMonitoringNodeIndex = jnxJsSPUMonitoringObjectsTable + '.1.10'
88
# jnxJsSPUMonitoringNodeIndex = jnxJsSPUMonitoringObjectsTable + '.1.10'
92 89
jnxJsSPUMonitoringNodeDescr = jnxJsSPUMonitoringObjectsTable + '.1.11'
93 90
jnxJsSPUMonitoringFlowSessIPv4 = jnxJsSPUMonitoringObjectsTable + '.1.12'
94 91
jnxJsSPUMonitoringFlowSessIPv6 = jnxJsSPUMonitoringObjectsTable + '.1.13'
95 92
jnxJsSPUMonitoringCPSessIPv4 = jnxJsSPUMonitoringObjectsTable + '.1.14'
96 93
jnxJsSPUMonitoringCPSessIPv6 = jnxJsSPUMonitoringObjectsTable + '.1.15'
97 94

  
98
class JunOSSnmpClient(object):
99

  
100
	def __init__(self, host, port, community):
101
		self.hostname = host
102
		self.transport = cmdgen.UdpTransportTarget((host, int(port)))
103
		self.auth = cmdgen.CommunityData('test-agent', community)
104
		self.gen = cmdgen.CommandGenerator()
105

  
106
	def get_data(self):
107
		errorIndication, errorStatus, errorIndex, varBindTable = self.gen.bulkCmd(
108
			self.auth,
109
			self.transport,
110
			0, 10,
111
			jnxJsSPUMonitoringObjectsTable)
112
#			ignoreNonIncreasingOids=True) # only available with pysnmp >= 4.2.4 (?) and broken anyway
113 95

  
114
		if errorIndication:
115
			logging.error("SNMP bulkCmd for devices failed: %s, %s, %s" % (errorIndication, errorStatus, errorIndex))
116
			return {}
117

  
118
		devices = {}
119
		values = {}
120
		for row in varBindTable:
121
			for name, value in row:
122
				if not str(name).startswith(jnxJsSPUMonitoringObjectsTable):
123
					continue
124

  
125
				oid = str(name)
126

  
127
				nodeid = oid[oid.rindex('.'):]
128

  
129
				idx = oid[len(jnxJsSPUMonitoringObjectsTable)+3:]
130
				idx = idx[:idx.index('.')]
131

  
132
				if oid.startswith(jnxJsSPUMonitoringNodeDescr):
133
					devices[nodeid] = str(value)
134
					continue
135

  
136
				values[oid] = int(value)
137
		return devices, values
138

  
139
	def print_config(self):
140
		devices, data = self.get_data()
141

  
142
		data_def = [
143
			('flow', self.hostname, 'Flow sessions', '--base 1000', '# of sessions', jnxJsSPUMonitoringMaxFlowSession),
144
			('cp', self.hostname, 'Central point sessions', '--base 1000', '# of sessions', jnxJsSPUMonitoringMaxCPSession),
145
		]
96
class JunOSSnmpClient(object):
146 97

  
147
		for datarow, hostname, title, args, vlabel, max_prefix in data_def:
148
			print """multigraph juniper_{datarow}
98
    def __init__(self, host, port, community):
99
        self.hostname = host
100
        self.transport = cmdgen.UdpTransportTarget((host, int(port)))
101
        self.auth = cmdgen.CommunityData('test-agent', community)
102
        self.gen = cmdgen.CommandGenerator()
103

  
104
    def get_data(self):
105
        errorIndication, errorStatus, errorIndex, varBindTable = self.gen.bulkCmd(
106
            self.auth,
107
            self.transport,
108
            0, 10,
109
            jnxJsSPUMonitoringObjectsTable)
110
        # the line below is only available with pysnmp >= 4.2.4 (?) and broken anyway
111
        # ignoreNonIncreasingOids=True)
112

  
113
        if errorIndication:
114
            logging.error("SNMP bulkCmd for devices failed: %s, %s, %s"
115
                          % (errorIndication, errorStatus, errorIndex))
116
            return {}
117

  
118
        devices = {}
119
        values = {}
120
        for row in varBindTable:
121
            for name, value in row:
122
                if not str(name).startswith(jnxJsSPUMonitoringObjectsTable):
123
                    continue
124

  
125
                oid = str(name)
126

  
127
                nodeid = oid[oid.rindex('.'):]
128

  
129
                idx = oid[len(jnxJsSPUMonitoringObjectsTable) + 3:]
130
                idx = idx[:idx.index('.')]
131

  
132
                if oid.startswith(jnxJsSPUMonitoringNodeDescr):
133
                    devices[nodeid] = str(value)
134
                    continue
135

  
136
                values[oid] = int(value)
137
        return devices, values
138

  
139
    def print_config(self):
140
        devices, data = self.get_data()
141

  
142
        data_def = [
143
            ('flow', self.hostname, 'Flow sessions', '--base 1000', '# of sessions',
144
             jnxJsSPUMonitoringMaxFlowSession),
145
            ('cp', self.hostname, 'Central point sessions', '--base 1000', '# of sessions',
146
             jnxJsSPUMonitoringMaxCPSession),
147
        ]
148

  
149
        for datarow, hostname, title, args, vlabel, max_prefix in data_def:
150
            print("""multigraph juniper_{datarow}
149 151
host_name {hostname}
150 152
graph_title {title}
151 153
graph_vlabel {vlabel}
152 154
graph_args {args}
153 155
graph_category network
154
graph_info {title}""".format(datarow=datarow, hostname=hostname, title=title, args=args, vlabel=vlabel)
156
graph_info {title}""".format(datarow=datarow, hostname=hostname, title=title, args=args,
157
                             vlabel=vlabel))
155 158

  
156
			for suffix, node in devices.iteritems():
157
				ident = "%s_%s" % (datarow, node)
158
				print """{label}.info {title} on {node}
159
            for suffix, node in devices.items():
160
                ident = "%s_%s" % (datarow, node)
161
                print("""{label}.info {title} on {node}
159 162
{label}.label {node}
160 163
{label}.type GAUGE
161
{label}.max {max}""".format(title=title, label=ident, node=node, max=data.get(max_prefix + suffix))
164
{label}.max {max}""".format(title=title, label=ident, node=node,
165
                            max=data.get(max_prefix + suffix)))
162 166

  
163
			for suffix, node in devices.iteritems():
164
				print """
167
            for suffix, node in devices.items():
168
                print("""
165 169
multigraph juniper_{datarow}.{node}
166 170
host_name {hostname}
167 171
graph_title {title} on {node}
......
186 190
{datarow}Max.label Max
187 191
{datarow}Max.draw LINE0
188 192
{datarow}Max.type GAUGE
189
""".format(datarow=datarow, hostname=hostname, title=title, args=args, vlabel=vlabel, node=node)
190

  
191
	def execute(self):
192
		devices, data = self.get_data()
193

  
194
		print "multigraph juniper_flow"
195
		for suffix, node in devices.iteritems():
196
			print "flow_%s.value %s" % (node, data.get(jnxJsSPUMonitoringCurrentFlowSession + suffix, 0))
193
""".format(datarow=datarow, hostname=hostname, title=title, args=args, vlabel=vlabel, node=node))
194

  
195
    def execute(self):
196
        devices, data = self.get_data()
197
        print("multigraph juniper_flow")
198
        for suffix, node in devices.items():
199
            print("flow_%s.value %s"
200
                  % (node, data.get(jnxJsSPUMonitoringCurrentFlowSession + suffix, 0)))
201

  
202
        for suffix, node in devices.items():
203
            print("multigraph juniper_flow.%s" % node)
204
            print("flowV4.value %s" % data.get(jnxJsSPUMonitoringFlowSessIPv4 + suffix, 0))
205
            print("flowV6.value %s" % data.get(jnxJsSPUMonitoringFlowSessIPv6 + suffix, 0))
206
            print("flowCurrent.value %s"
207
                  % data.get(jnxJsSPUMonitoringCurrentFlowSession + suffix, 0))
208
            print("flowMax.value %s" % data.get(jnxJsSPUMonitoringMaxFlowSession + suffix, 0))
209

  
210
        print("multigraph juniper_cp")
211
        for suffix, node in devices.items():
212
            print("cp_%s.value %s"
213
                  % (node, data.get(jnxJsSPUMonitoringCurrentCPSession + suffix, 0)))
214

  
215
        for suffix, node in devices.items():
216
            print("multigraph juniper_cp.%s" % node)
217
            print("cpV4.value %s" % data.get(jnxJsSPUMonitoringCPSessIPv4 + suffix, 0))
218
            print("cpV6.value %s" % data.get(jnxJsSPUMonitoringCPSessIPv6 + suffix, 0))
219
            print("cpCurrent.value %s" % data.get(jnxJsSPUMonitoringCurrentCPSession + suffix, 0))
220
            print("cpMax.value %s" % data.get(jnxJsSPUMonitoringMaxCPSession + suffix, 0))
197 221

  
198
		for suffix, node in devices.iteritems():
199
			print "multigraph juniper_flow.%s" % node
200
			print "flowV4.value %s" % data.get(jnxJsSPUMonitoringFlowSessIPv4 + suffix, 0)
201
			print "flowV6.value %s" % data.get(jnxJsSPUMonitoringFlowSessIPv6 + suffix, 0)
202
			print "flowCurrent.value %s" % data.get(jnxJsSPUMonitoringCurrentFlowSession + suffix, 0)
203
			print "flowMax.value %s" % data.get(jnxJsSPUMonitoringMaxFlowSession + suffix, 0)
204

  
205
		print "multigraph juniper_cp"
206
		for suffix, node in devices.iteritems():
207
			print "cp_%s.value %s" % (node, data.get(jnxJsSPUMonitoringCurrentCPSession + suffix, 0))
208

  
209
		for suffix, node in devices.iteritems():
210
			print "multigraph juniper_cp.%s" % node
211
			print "cpV4.value %s" % data.get(jnxJsSPUMonitoringCPSessIPv4 + suffix, 0)
212
			print "cpV6.value %s" % data.get(jnxJsSPUMonitoringCPSessIPv6 + suffix, 0)
213
			print "cpCurrent.value %s" % data.get(jnxJsSPUMonitoringCurrentCPSession + suffix, 0)
214
			print "cpMax.value %s" % data.get(jnxJsSPUMonitoringMaxCPSession + suffix, 0)
215 222

  
216 223
c = JunOSSnmpClient(host, port, community)
217 224

  
225

  
218 226
if "snmpconf" in sys.argv[1:]:
219
	print "require %s" % (jnxJsSPUMonitoringObjectsTable, )
220
	sys.exit(0)
227
    print("require %s" % (jnxJsSPUMonitoringObjectsTable, ))
228
    sys.exit(0)
221 229
else:
222
	if not (host and port and community):
223
		print "# Bad configuration. Cannot run with Host=%s, port=%s and community=%s" % (host, port, community)
224
		sys.exit(1)
225

  
226
	if "config" in sys.argv[1:]:
227
		c.print_config()
228
	else:
229
		c.execute()
230
    if not (host and port and community):
231
        print("# Bad configuration. Cannot run with Host=%s, port=%s and community=%s"
232
              % (host, port, community), file=sys.stderr)
233
        sys.exit(1)
234

  
235
    if "config" in sys.argv[1:]:
236
        c.print_config()
237
    else:
238
        c.execute()
t/test-exception-wrapper.expected-failures
401 401
plugins/router/freeboxuptime
402 402
plugins/router/motorola_sb6141
403 403
plugins/router/snmp__juniper
404
plugins/router/snmp__juniper_spu
405 404
plugins/router/snmp__linksys_poe
406 405
plugins/router/speedport_300
407 406
plugins/rsync/rsyncd_bytes

Formats disponibles : Unified diff