-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·250 lines (214 loc) · 7.52 KB
/
main.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
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
#!/usr/bin/python3.7
# file -- main.py --
import logging
import signal
import subprocess
import sys
import os
import time as t
from configparser import ConfigParser
from datetime import *
import threading
import pytz
import flask
import library
app = flask.Flask(__name__)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("Dgate.log"),
logging.StreamHandler()
]
)
class Gateway:
speed = {}
def __init__(self, _gw_ip, _gw_name, _gw_weight=1, _start_time=None, _end_time=None,
_gw_status="offline", _available=False):
self.ip = _gw_ip
self.weight = _gw_weight
self.name = _gw_name
self.status = _gw_status
self.available = _available
self.start_time = _start_time
self.end_time = _end_time
self.weight_conf = _gw_weight
def print_available(self):
logging.info("Gateway: {} Available: {}".format(self.name, self.available))
def runApp(host="0.0.0.0", port=5000, debug=False):
app.run(host=host, port=port, debug=debug)
@app.route('/sping', methods=['GET'])
def sping():
speed_test()
result = []
for i in section:
result.append(globals()[i].speed['ping'])
return f"True\n{result}"
@app.route('/sdown', methods=['GET'])
def sdown():
speed_test('download')
result = []
for i in section:
result.append(globals()[i].w)
return f"True\n{result}"
@app.route('/weight', methods=['GET'])
def weight():
result = {}
for i in section:
result.update({globals()[i].name:globals()[i].weight})
return result
@app.route('/reloadweight', methods=['GET'])
def reloadweight():
try:
reload_weight()
return "True"
except Exception as e:
logging.error(e)
return "False"
def load_config():
logging.info("Dgate started")
library.create_dir()
logging.info("load config")
config = ConfigParser()
config.read('config.cfg')
global section
global time_weight
global speed_weight
section = config.sections()
time_weight = config['general']['time_weight']
speed_weight = config['general']['speed_weight']
section.remove("general")
for gw in section:
if gw != "general":
globals()[gw] = Gateway(config[gw]['gwip'], gw, int(config[gw]['weight']),
config[gw]['start_time'], config[gw]['end_time'])
global tz
tz = pytz.timezone(config['general']['timezone'])
logging.info("timezone: {}".format(tz))
logging.info("config loaded")
def startapp():
load_config()
switch_gateway()
def reload_weight():
logging.info('reload weight')
for i in section:
globals()[i].weight = globals()[i].weight_conf
return
def available_status():
remove_gateway()
for i in section:
library.add_gateway(globals()[i].ip, globals()[i].name)
globals()[i].state = "online"
ping = subprocess.call(['ping', '-c', '5', '1.1.1.1'])
if ping == 0:
globals()[i].available = True
else:
globals()[i].available = False
globals()[i].print_available()
library.remove_gateway(globals()[i].ip, globals()[i].name)
globals()[i].status = "offline"
def if_needed_change_weight_base_on_time():
now = datetime.now(tz).time()
for i in section:
if library.in_between(now, time(int(globals()[i].start_time)), time(int(globals()[i].end_time))):
if globals()[i].weight == globals()[i].weight_conf:
logging.info("Gateway: {} wight is down".format(globals()[i].name))
globals()[i].weight -= int(time_weight)
return 1
if not library.in_between(now, time(int(globals()[i].start_time)), time(int(globals()[i].end_time))):
if globals()[i].weight != globals()[i].weight_conf:
globals()[i].weight += int(time_weight)
logging.info("Gateway: {} wight is up".format(globals()[i].name))
return 1
return 0
def chose_gateway():
if_needed_change_weight_base_on_time()
section.sort(key=lambda x: globals()[x].weight)
available_status()
result = {}
for i in section:
result.update({globals()[i].name:globals()[i].weight})
logging.info(result)
for i in section:
if globals()[i].available:
logging.info("Gateway: {} is available".format(globals()[i].name))
return globals()[i].name
logging.warning("No gateway available")
return None
def switch_gateway():
gateway_list = []
for i in section:
gateway_list.append(globals()[i].ip)
gateway_name = chose_gateway()
if gateway_name is None:
while True:
logging.info("No gateway available, waiting for new gateway")
gateway_name = chose_gateway()
if gateway_name is not None:
break
logging.info("Switch to Gateway: {}".format(gateway_name))
library.switch_gateway(gateway_list, globals()[gateway_name].ip, gateway_name)
globals()[gateway_name].status = "online"
def check_gateway():
for i in section:
if globals()[i].status == "online":
ping = subprocess.call(['ping', '-c', '1', '1.1.1.1'])
if ping == 0:
globals()[i].available = True
logging.info("Gateway: {} checked and is available".format(globals()[i].name))
return 0
else:
globals()[i].available = False
logging.info("Gateway: {} checked and is not available".format(globals()[i].name))
library.remove_gateway(globals()[i].ip, globals()[i].name)
globals()[i].status = "offline"
return 1
def always_available():
while True:
t.sleep(30)
res_time_check = if_needed_change_weight_base_on_time()
res_gateway_check = check_gateway()
if res_time_check == 1 or res_gateway_check == 1:
switch_gateway()
def terminate_process(signal_number, frame):
logging.info('(SIGTERM) terminating the process')
switch_gateway()
sys.exit(0)
def read_configuration(signal_number, frame):
logging.info('(SIGHUP) reading configuration')
load_config()
return
def remove_gateway():
gateway_list = []
for i in section:
gateway_list.append(globals()[i].ip)
globals()[i].status = "offline"
library.remove_gateways(gateway_list)
def speed_test(factor='ping'):
logging.info("Gateways are testing ... ")
reload_weight()
remove_gateway()
for i in section:
library.add_gateway(globals()[i].ip, globals()[i].name)
globals()[i].state = "online"
globals()[i].speed = library.speed_test()
logging.info(globals()[i].speed)
logging.info("Gateway: {} {} is {} ".format(globals()[i].name, factor, globals()[i].speed.get(factor)))
library.remove_gateway(globals()[i].ip, globals()[i].name)
globals()[i].status = "offline"
remove_gateway()
for i in section:
for j in section:
if globals()[i].speed.get(factor) < globals()[j].speed.get(factor):
globals()[i].weight -= speed_weight
logging.info("Gateway: {} is better than {}".format(globals()[i].name, globals()[j].name))
break
if __name__ == '__main__':
signal.signal(signal.SIGHUP, read_configuration)
signal.signal(signal.SIGTERM, terminate_process)
startapp()
n = os.fork()
if n > 0:
always_available()
else:
runApp()