From 8914c1810ddb07abc1efddfee30250bcc7e7d571 Mon Sep 17 00:00:00 2001 From: yumoqing Date: Mon, 17 May 2021 10:58:51 +0800 Subject: [PATCH] bgfix --- ahserver/configuredServer.py | 45 ++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/ahserver/configuredServer.py b/ahserver/configuredServer.py index 962379f..3cff8c2 100644 --- a/ahserver/configuredServer.py +++ b/ahserver/configuredServer.py @@ -1,8 +1,10 @@ import os,sys import ssl +from socket import * from aiohttp import web from appPublic.folderUtils import ProgramPath +from appPublic.background import Background from appPublic.jsonConfig import getConfig from sqlor.dbpools import DBPools @@ -11,10 +13,13 @@ from .processorResource import ProcessorResource from .auth_api import AuthAPI from .myTE import setupTemplateEngine from .globalEnv import initEnv +from natpmp import NATPMP as pmp class ConfiguredServer: def __init__(self,auth_klass=AuthAPI): pp = ProgramPath() + self.natpmp_loop = True + self.nat_heartbeat = False workdir = pp if len(sys.argv) > 1: workdir = sys.argv[1] @@ -28,6 +33,34 @@ class ConfiguredServer: auth.setupAuth(self.app) 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): config = getConfig() ssl_context = None @@ -35,6 +68,18 @@ class ConfiguredServer: ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) ssl_context.load_cert_chain(config.website.ssl.crtfile, 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', port=config.website.port or 8080, ssl_context=ssl_context)