From 97fc644f0dd857a85ba4926c7cbabd3f81d92775 Mon Sep 17 00:00:00 2001 From: Jonatan Rek Date: Tue, 21 Jan 2025 14:00:29 +0100 Subject: [PATCH] Add Thread for stoping the container --- app.py | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/app.py b/app.py index e12b72a..2a72356 100644 --- a/app.py +++ b/app.py @@ -2,8 +2,11 @@ import http.server import http.client import yaml import docker -from socketserver import ThreadingMixIn import threading +import time +from datetime import datetime, timezone + +from socketserver import ThreadingMixIn # Define the target server to proxy requests to class ProxyHandler(http.server.BaseHTTPRequestHandler): @@ -74,12 +77,43 @@ class ProxyHandler(http.server.BaseHTTPRequestHandler): class ThreadedHTTPServer(ThreadingMixIn, http.server.HTTPServer): """Handle requests in a separate thread.""" +class BackgroundTasks(threading.Thread): + def __init__(self, configuration, docker_client): + super(BackgroundTasks, self).__init__() + self.configuration = configuration + self.docker_client = docker_client + + def run(self,*args,**kwargs): + while True: + sleep_time = 900 + for apps in self.configuration['proxy_hosts']: + if(sleep_time > apps['proxy_timeout_seconds']): + sleep_time = apps['proxy_timeout_seconds'] + + 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): + container_object.stop() + + time.sleep(15) + + + if __name__ == '__main__': with open('config.yml', 'r') as file: configuration = yaml.safe_load(file) docker_client = docker.from_env() + t = BackgroundTasks(configuration, docker_client) + t.start() + # Start the reverse proxy server on port 8888 server_address = ('', configuration['proxy_port']) proxy_handler = ProxyHandler(configuration, docker_client)