This commit is contained in:
Jonatan Rek 2025-01-21 15:28:54 +01:00
parent 97fc644f0d
commit 610ef79690

26
app.py
View File

@ -5,12 +5,14 @@ import docker
import threading
import time
from datetime import datetime, timezone
from socketserver import ThreadingMixIn
from queue import Queue
import multiprocessing
# Define the target server to proxy requests to
class ProxyHandler(http.server.BaseHTTPRequestHandler):
def __init__(self, configuration, docker_client):
global activity
self.configuration = configuration
self.docker_client = docker_client
@ -57,8 +59,10 @@ class ProxyHandler(http.server.BaseHTTPRequestHandler):
self.send_header('refresh', proxy_host_configuration['proxy_timeout_seconds'])
self.end_headers()
self.wfile.write(bytes("starting container: {0} waiting for {1}s".format(container['container_name'], proxy_host_configuration['proxy_timeout_seconds']),"utf-8"))
self.wfile.flush()
return
activity[proxy_host_configuration['domain']] = datetime.now(timezone.utc)
# Open a connection to the target server
conn = http.client.HTTPConnection(proxy_host_configuration['proxy_host'], proxy_host_configuration['proxy_port'])
conn.request(method, self.path, headers=self.headers)
@ -72,6 +76,7 @@ class ProxyHandler(http.server.BaseHTTPRequestHandler):
self.end_headers()
self.wfile.write(response.read())
conn.close()
class ThreadedHTTPServer(ThreadingMixIn, http.server.HTTPServer):
@ -84,6 +89,7 @@ class BackgroundTasks(threading.Thread):
self.docker_client = docker_client
def run(self,*args,**kwargs):
global activity
while True:
sleep_time = 900
for apps in self.configuration['proxy_hosts']:
@ -93,19 +99,21 @@ class BackgroundTasks(threading.Thread):
for container in apps['containers']:
container_object = self.docker_client.containers.get(container['container_name'])
if (container_object.status == 'running'):
dt = datetime.fromisoformat(container_object.attrs['State']['StartedAt'])
diff_seconds = (datetime.now(timezone.utc) - dt).total_seconds()
print("stopping container: {0}".format(container['container_name']))
print("{0}s ".format(diff_seconds))
if(diff_seconds > sleep_time):
dt = datetime.now(timezone.utc)
if (apps['domain'] in activity):
dt = activity[apps['domain']]
diff_seconds = (datetime.now(timezone.utc) - dt).total_seconds()
if(diff_seconds > apps['proxy_timeout_seconds']):
print("stopping container: {0} ({1}) after {2}s".format(container['container_name'], container_object.id, diff_seconds))
container_object.stop()
time.sleep(15)
time.sleep(sleep_time)
if __name__ == '__main__':
activity = {}
with open('config.yml', 'r') as file:
configuration = yaml.safe_load(file)