-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfritz-7390_
More file actions
executable file
·390 lines (319 loc) · 11.1 KB
/
fritz-7390_
File metadata and controls
executable file
·390 lines (319 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env python
"""
Interrogate a FritzBox to get various statistics. The current supported stats
are:
* CRC and FEC errors
* Sync Speecs (up- and downstream)
* DSL uptime (time passed since last resync)
Usage
-----
This plugin determines which stats to show based on the base filename. So when
linking, you have to link it with a proper filename. Here are examples for the
currently supported stats::
cd /etc/munin/plugins
ln -s /opt/munin-plugins/fritz-7390_ fritz-7390_errors
ln -s /opt/munin-plugins/fritz-7390_ fritz-7390_uptime
ln -s /opt/munin-plugins/fritz-7390_ fritz-7390_syncspeed
And create a config file ``/etc/munin/plugin-conf.d/fritz-7390_`` with
the following contents (replacing the IP with that of your fritz of course)::
[fritz-7390_*]
env.URL http://192.168.0.1
Adding new stats
----------------
Simply create a new sub-class of FritzStat. The name of the class defines the
stat-name. The application will cut off the trailing 4 characters of the
class-name (usually 'Stat'). So if you want to make a new stat named 'foo'
available, you should create a class named ``FooStat(FritzStat)``.
The sub-class must implement the methods ``do_config`` and ``do_fetch`` which
represent the corresponding munin calls. They can optionally define a
``do_autoconf`` method. The "do_" prefix exists to avoid conflicts.
The class has an instance method ``config`` which contains configuration
values.
Example::
class FooStat(FritzStat):
def do_fetch(self):
print(dedent(
u'''\
foo.value 10
'''))
def do_config(self):
print(dedent(
'''\
graph_title FritzBox Example Stat
graph_vlabel static foo
graph_scale no
graph_category FritzBox
graph_args --base 1000 --lower-limit 0
graph_info Example stat values
foo.info Foo value
foo.label foo
foo.draw AREA
''))
Known issues
------------
* Currently only supports interfaces without HTTP AUTH!
"""
#%# family=auto
#%# capabilities=autoconf
from __future__ import print_function
import json
from datetime import timedelta
from collections import namedtuple
from textwrap import dedent
from argparse import ArgumentParser
from os import getenv
from urllib2 import urlopen, URLError
import socket
import sys
import re
Speeds = namedtuple('Speeds', 'upstream, downstream')
Errors = namedtuple(
'Errors',
'fec_fritz_per_min, crc_fritz_per_min, fec_dsl_per_min, crc_dsl_per_min')
Config = namedtuple('Config', 'url, username, password')
STAT_PATTERN = re.compile(r'^\["(.*?)"\] = "(.*?)",?$')
def convert_to_kbits(strdata):
"""
Converts data as reported from the Fritz to an int representing kbit/s. If
the value is not supported, raises a ``ValueError``.
"""
if not strdata.endswith('kbit/s'):
raise ValueError('Unable to convert {!r} to kbit/s'.format(strdata))
return int(strdata[0:-7])
class FritzStat(object):
def __init__(self, config):
self._config = config
def has_access(self):
"""
Determines if the access to the FritzBox works. Returns a tuple
(boolean, reason)
"""
try:
urlopen(self._config.url, timeout=2)
return True, "Successfully connected"
except URLError as exc:
return False, exc.reason
except socket.timeout as exc:
return False, str(exc)
def do_autoconf(self):
"""
Implementation for command "autoconf"
"""
may_access, reason = self.has_access()
if may_access:
print("yes")
else:
print(u"no (unable to access the FritzBox via {!r}): {}".format(
self._config, reason))
class ErrorsStat(FritzStat):
def get(self):
"""
Returns FEC and CRC errors
"""
response = urlopen('{}/internet/dsl_stats_tab.lua'.format(
self._config.url), timeout=2)
data = response.read()
values = {}
for line in data.splitlines():
match = STAT_PATTERN.match(line.strip())
if match:
var, value = match.groups()
values[var] = value
return Errors(
float(values['sar:status/ds_fec_minute']),
float(values['sar:status/ds_crc_minute']),
float(values['sar:status/us_fec_minute']),
float(values['sar:status/us_crc_minute']))
def do_fetch(self):
"""
Implementation for command "fetch"
"""
errors = self.get()
print(dedent(
u"""\
fec_fritz_per_min.value -{0.fec_fritz_per_min!s}
crc_fritz_per_min.value -{0.crc_fritz_per_min!s}
fec_dsl_per_min.value {0.fec_dsl_per_min!s}
crc_dsl_per_min.value {0.crc_dsl_per_min!s}""".format(errors)))
def do_config(self):
"""
Implementation for command "config"
"""
print(dedent(
"""\
graph_title FritzBox errors
graph_vlabel error count
graph_scale no
graph_category FritzBox
graph_args --base 1000 --lower-limit 0
graph_info Error counters for the fritz box.
fec_fritz_per_min.info Fritz recoverable errors per minute (FEC)
fec_fritz_per_min.label fritz_fec
fec_fritz_per_min.draw AREA
crc_fritz_per_min.info Fritz unrecoverable errors per minute (CRC)
crc_fritz_per_min.label fritz_crc
crc_fritz_per_min.draw STACK
fec_dsl_per_min.info DSL recoverable errors per minute (FEC)
fec_dsl_per_min.label dsl_fec
fec_dsl_per_min.draw AREA
crc_dsl_per_min.info DSL unrecoverable errors per minute (CRC)
crc_dsl_per_min.label dsl_crc
crc_dsl_per_min.draw STACK"""))
class SyncSpeedStat(FritzStat):
def get(self):
"""
Returns syncspeeds as a 2-tuple (upstream, downstream).
All speeds are reported a kilobits per second.
"""
url = ('{}/internet/dsl_overview.lua?'
'useajax=1&'
'action=get_data&'
'xhr=1'.format(
self._config.url))
response = urlopen(url, timeout=2)
data = response.read()
struct = json.loads(data)
downstream = convert_to_kbits(struct['ds_rate'])
upstream = convert_to_kbits(struct['us_rate'])
return Speeds(upstream, downstream)
def do_config(self):
"""
Implementation for command "config"
"""
print(dedent(
"""\
graph_title FritzBox Sync Speeds
graph_vlabel Speed (kbit/s)
graph_scale no
graph_category FritzBox
graph_args --base 1000
graph_info Time in minutes since successfully connected to DSL.
upstream.info speed in kbit/s
upstream.label upstream
upstream.draw AREA
downstream.info speed in kbit/s
downstream.label downstream
downstream.draw AREA"""))
def do_fetch(self):
"""
Implementation for command "fetch"
"""
speeds = self.get()
print(dedent(
u"""\
upstream.value {}
downstream.value -{}""".format(speeds.upstream, speeds.downstream))
)
class UptimeStat(FritzStat):
def get(self):
"""
Returns uptime as a timedelta object.
"""
url = ('{}/internet/dsl_overview.lua?'
'useajax=1&'
'action=get_data&'
'xhr=1'.format(
self._config.url))
response = urlopen(url, timeout=2)
data = response.read()
struct = json.loads(data)
uptime = struct['line']['time']
if uptime.isdigit():
uptime = timedelta(seconds=int(uptime))
else:
uptime = uptime[1:-1] # strip brackets
hours, minutes, seconds = uptime.split(':')
uptime = timedelta(
hours=int(hours),
minutes=int(minutes),
seconds=int(seconds))
return uptime
def do_config(self):
"""
Implementation for command "config"
"""
print(dedent(
"""\
graph_title FritzBox uptime
graph_vlabel Uptime (minutes)
graph_scale no
graph_category FritzBox
graph_args --base 1000 --lower-limit 0
graph_info Time in minutes since successfully connected to DSL.
uptime.info Uptime in minutes.
uptime.label uptime
uptime.draw AREA"""))
def do_fetch(self):
"""
Implementation for command "fetch"
"""
uptime = self.get()
print(dedent(
u"""\
uptime.value {}""".format(int(uptime.total_seconds() / 60))))
class Application(object):
"""
The main application code.
"""
def __init__(self, stat, args, config):
self.stat = stat
self.args = args
self.config = config
self.command_map = {}
for cls in FritzStat.__subclasses__():
statname = cls.__name__[0:-4].lower()
self.command_map[statname] = cls(self.config)
def execute(self):
"""
Executes one command
"""
executor = self.command_map.get(self.stat)
if not executor:
print(u'Unknown stats: {!r}'.format(self.stat),
file=sys.stderr)
return 9
cmdfunc = 'do_{}'.format(self.args.command)
if hasattr(executor, cmdfunc):
getattr(executor, cmdfunc)()
else:
print(u'Unknown command: {!r}'.format(self.args.command),
file=sys.stderr)
return 9
return 0
def parse_args():
"""
Parses CLI arguments and returns an object with the following attributes:
* ``command`` - The command to the plugin (config,)
"""
parser = ArgumentParser(
description="Interrogates a FritzBox 7390 for various stats.")
parser.add_argument('-s', '--statname', help=(
u'Statistcs to fetch. By default the stats are determined by the '
u'plugin filename. This lets you override this behaviour for '
u'debugging.'),
dest='stat',
default=None)
parser.add_argument('command', nargs='?', help=u'Plugin command',
default='fetch')
return parser.prog, parser.parse_args()
def main():
"""
Main entry point of the app.
"""
progname, args = parse_args()
if args.stat:
stat = args.stat
else:
_, stat = progname.rsplit('_', 1)
cfg = Config(
getenv('URL'),
getenv('USERNAME'),
getenv('PASSWORD'))
if not cfg.url:
print('No URL specified in the config file! See the docs!',
file=sys.stderr)
return 9
app = Application(stat, args, cfg)
return app.execute()
if __name__ == '__main__':
sys.exit(main())