This commit is contained in:
yumoqing 2021-05-17 10:58:51 +08:00
parent 598889c678
commit 8914c1810d

View File

@ -1,8 +1,10 @@
import os,sys import os,sys
import ssl import ssl
from socket import *
from aiohttp import web from aiohttp import web
from appPublic.folderUtils import ProgramPath from appPublic.folderUtils import ProgramPath
from appPublic.background import Background
from appPublic.jsonConfig import getConfig from appPublic.jsonConfig import getConfig
from sqlor.dbpools import DBPools from sqlor.dbpools import DBPools
@ -11,10 +13,13 @@ from .processorResource import ProcessorResource
from .auth_api import AuthAPI from .auth_api import AuthAPI
from .myTE import setupTemplateEngine from .myTE import setupTemplateEngine
from .globalEnv import initEnv from .globalEnv import initEnv
from natpmp import NATPMP as pmp
class ConfiguredServer: class ConfiguredServer:
def __init__(self,auth_klass=AuthAPI): def __init__(self,auth_klass=AuthAPI):
pp = ProgramPath() pp = ProgramPath()
self.natpmp_loop = True
self.nat_heartbeat = False
workdir = pp workdir = pp
if len(sys.argv) > 1: if len(sys.argv) > 1:
workdir = sys.argv[1] workdir = sys.argv[1]
@ -28,6 +33,34 @@ class ConfiguredServer:
auth.setupAuth(self.app) auth.setupAuth(self.app)
self.configPath(config) self.configPath(config)
def natpmp_heartbeat(self):
config = getConfig()
udpCliSock = socket(AF_INET,SOCK_DGRAM)
msg = f'{config.natpmp.appname}:{config.natpmp.nodename}'.encode('utf-8')
t = config.natpmp.heartbeat_period or 60
addr = (gethostbyname(config.natpmp.natserver), config.natpmp.natport)
while self.nat_heartbeat:
udpCliSock.sendto(msg, addr)
udpCliSock.recv(1024)
time.sleep(t)
def nat_pmp(self):
config = getConfig()
t = config.natpmp.portmap_period or 3600
while self.natpmp_loop:
gateway = pmp.get_gateway_addr()
print('gateway=', gateway)
try:
x = pmp.map_port(pmp.NATPMP_PROTOCOL_TCP,
config.natpmp.public_port, config.website.port,
t, gateway_ip=gateway)
print('gateway=', gateway, 'map_port()=', x)
except Exception as e:
print('mat_pmp():Exception:',e)
time.sleep(t - 1)
def run(self): def run(self):
config = getConfig() config = getConfig()
ssl_context = None ssl_context = None
@ -35,6 +68,18 @@ class ConfiguredServer:
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(config.website.ssl.crtfile, ssl_context.load_cert_chain(config.website.ssl.crtfile,
config.website.ssl.keyfile) config.website.ssl.keyfile)
if config.natpmp:
self.nat_heartbeat = True
b = Background(self.natpmp_heartbeat)
b.start()
if not config.natpmp:
self.natpmp_loop = False
elif config.natpmp.hardmap:
self.natpmp_loop = False
else:
b = Background(self.nat_pmp)
b.start()
web.run_app(self.app,host=config.website.host or '0.0.0.0', web.run_app(self.app,host=config.website.host or '0.0.0.0',
port=config.website.port or 8080, port=config.website.port or 8080,
ssl_context=ssl_context) ssl_context=ssl_context)