[~] Refactor

This commit is contained in:
Siarhei Siniak 2024-06-08 15:18:33 +03:00
parent 64ce890d44
commit d059f0c25d
2 changed files with 108 additions and 52 deletions

@ -1,4 +1,5 @@
import json import json
import os
import io import io
import sys import sys
@ -30,12 +31,12 @@ def forward(
sections = dict() sections = dict()
for entry in forward_nginx: for entry in forward_nginx:
location = None location_path = None
if entry['app_name'] != '': if entry['app_name'] != '':
location = '/%s/' % entry['app_name'] location_path = '/%s/' % entry['app_name']
else: else:
location = '/' location_path = '/'
if 'server_name' in entry: if 'server_name' in entry:
server_name = entry['server_name'] server_name = entry['server_name']
@ -45,38 +46,84 @@ def forward(
if not server_name in sections: if not server_name in sections:
sections[server_name] = [] sections[server_name] = []
if 'target_endpoint' in entry:
section_body = r''' location_get = lambda location_body, location_path2, prefix=None,: (
proxy_set_header Host $http_host; r'''
proxy_set_header X-Forwarded-For $t1; location {location} {
proxy_set_header X-Forwarded-Proto $scheme; {location_body}
proxy_set_header Upgrade $http_upgrade; }
proxy_set_header Connection $connection_upgrade;
proxy_redirect off;
proxy_buffering off;
proxy_pass {target_endpoint};
'''.replace( '''.replace(
'{target_endpoint}', entry['target_endpoint'], '{location_body}', location_body,
).replace(
'{location}', '%s %s' % (
(
'^~'
if prefix is None
else prefix
),
location_path2
),
) )
)
if 'target_endpoint' in entry:
location_body_get = lambda target_endpoint: \
r'''
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $t1;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_redirect off;
proxy_buffering off;
proxy_pass {target_endpoint};
'''.replace(
'{target_endpoint}', target_endpoint,
)
if 'fallback_endpoint' in entry:
fallback_name = '@fallback-%s' % os.urandom(10).hex()
sections[server_name].append(
location_get(
location_body_get(entry['target_endpoint']) + r'''
proxy_intercept_errors on;
error_page 502 {fallback_name};
'''.replace(
'{fallback_name}', fallback_name,
),
location_path,
)
)
sections[server_name].append(
location_get(
location_body_get(entry['fallback_endpoint']),
fallback_name,
'',
)
)
else:
sections[server_name].append(
location_get(
location_body_get(entry['target_endpoint']),
location_path,
)
)
elif 'redirect_url' in entry: elif 'redirect_url' in entry:
section_body = r''' sections[server_name].append(
return 302 {redirect_url}$request_uri; location_get(
'''.replace( r'''
'{redirect_url}', entry['redirect_url'], return 302 {redirect_url}$request_uri;
'''.replace(
'{redirect_url}', entry['redirect_url'],
),
location_path,
)
) )
else: else:
raise NotImplementedError raise NotImplementedError
sections[server_name].append(r'''
location ^~ {location} {
{section_body}
}
'''.replace(
'{section_body}', section_body,
).replace(
'{location}', location,
))
servers = [] servers = []
for server_name, current_sections in sections.items(): for server_name, current_sections in sections.items():
@ -115,30 +162,30 @@ server {
) )
f.write(r''' f.write(r'''
events { events {
multi_accept on; multi_accept on;
worker_connections 64; worker_connections 64;
} }
http { http {
log_format main log_format main
'[$time_local][$remote_addr:$remote_port, $http_x_forwarded_for, $t1, $http_host]' '[$time_local][$remote_addr:$remote_port, $http_x_forwarded_for, $t1, $http_host]'
'[$request_length,$bytes_sent,$request_time]' '[$request_length,$bytes_sent,$request_time]'
'[$status][$request]' '[$status][$request]'
'[$http_user_agent][$http_referer]'; '[$http_user_agent][$http_referer]';
access_log /dev/null combined; access_log /dev/null combined;
access_log /dev/stderr main; access_log /dev/stderr main;
gzip on; gzip on;
server_tokens off; server_tokens off;
{servers_config} {servers_config}
map $http_upgrade $connection_upgrade { map $http_upgrade $connection_upgrade {
default upgrade; default upgrade;
'' close; '' close;
} }
} }
'''.replace( '''.replace(
'{servers_config}', '\n'.join(servers) '{servers_config}', '\n'.join(servers)
)) ))

@ -2883,10 +2883,16 @@ def share_wifi(argv):
last_timestamp = datetime.datetime.now() last_timestamp = datetime.datetime.now()
hostapd = None hostapd = None
restart = False restart = False
shutdown = False
def on_interrupt(*args, **kwargs): def on_interrupt(sig, *args, **kwargs):
nonlocal restart nonlocal restart
restart = True if sig == signal.SIGINT:
restart = True
elif sig == signal.SIGTERM:
shutdown = True
else:
raise NotImplementedError
signal.signal( signal.signal(
signal.SIGINT, signal.SIGINT,
@ -2906,7 +2912,7 @@ def share_wifi(argv):
pw, pw,
] ]
if not options.channel is None: if not options.channel is None:
hostapd_args.extend(['-c', '%d' % option.channell]) hostapd_args.extend(['-c', '%d' % options.channel])
while True: while True:
try: try:
@ -2914,7 +2920,7 @@ def share_wifi(argv):
print('\n%s, start new' % last_timestamp) print('\n%s, start new' % last_timestamp)
hostapd = subprocess.Popen(hostapd_args) hostapd = subprocess.Popen(hostapd_args)
else: else:
if restart: if restart or shutdown:
print('\n%s, shutdown current' % last_timestamp) print('\n%s, shutdown current' % last_timestamp)
os.kill( os.kill(
hostapd.pid, hostapd.pid,
@ -2929,6 +2935,9 @@ def share_wifi(argv):
if not hostapd.poll() is None: if not hostapd.poll() is None:
hostapd = None hostapd = None
if shutdown:
break
if ( if (
datetime.datetime.now() - last_timestamp datetime.datetime.now() - last_timestamp
).total_seconds() > options.restart_delay: ).total_seconds() > options.restart_delay: