Add Thread for stoping the container

This commit is contained in:
Jonatan Rek 2025-01-21 14:00:29 +01:00
parent 220d632e7b
commit 97fc644f0d

36
app.py
View File

@ -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)