forked from freifunk-stuttgart/loadbalancer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenGwStatus.py
executable file
·90 lines (72 loc) · 2.29 KB
/
genGwStatus.py
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
#!/usr/bin/python3
# encoding: utf-8
'''
genGwStatus -- generator for gwstatus.json
'''
import sys
import os
import time
import json
import subprocess
from argparse import ArgumentParser
from argparse import RawDescriptionHelpFormatter
__all__ = []
__version__ = 0.1
__date__ = '2017-09-03'
__updated__ = '2017-09-03'
DEBUG = 1
TESTRUN = 0
PROFILE = 0
class CLIError(Exception):
'''Generic exception to raise and log different fatal errors.'''
def __init__(self, msg):
super(CLIError).__init__(type(self))
self.msg = "E: %s" % msg
def __str__(self):
return self.msg
def __unicode__(self):
return self.msg
def getPeak24h():
vnstat = json.loads(subprocess.check_output(["/usr/bin/vnstat", "-h", "--json"]).decode('utf-8'))
#with open("/home/leonard/freifunk/FfsScripts/vnstat.json","r") as fp:
# vnstat = json.load(fp)
hours = vnstat["interfaces"][0]["traffic"]["hours"]
peak = 0
for h in hours:
if h["tx"] > peak:
peak = h["tx"]
return peak/1024/3600*8
def getDnsStatus(segment):
hostname = "gw01s%02i.gw.freifunk-stuttgart.de"%(segment)
try:
subprocess.check_output(["/usr/bin/host",hostname,"dns1.lihas.de"])
return 1
except:
return 0
def getPreference():
preference = int((300-getPeak24h()) / 3) # max 300mbit
return preference
def genData(preference=0):
data = {}
data["version"] = "1"
data["timestamp"] = int(time.time())
segments = {}
for s in range(1,32+1):
segments[s] = {}
segments[s]["preference"] = preference
segments[s]["dnsactive"] = getDnsStatus(s)
data["segments"] = segments
return data
def genJson(data,output):
with open(output,"w") as fp:
json.dump(data,fp ,indent=4,separators=(',', ': '))
#def main(argv=None): # IGNORE:C0111
if __name__ == "__main__":
# Setup argument parser
parser = ArgumentParser(description="Generator for gwstats.json", formatter_class=RawDescriptionHelpFormatter)
parser.add_argument("-o", "--output", dest="output", action="store", required=True, help="output filename")
# Process arguments
args = parser.parse_args()
preference = getPreference()
data = genData(preference=preference)
genJson(data,args.output)