From 9e932623c78b2d099e44dddae621054d5318889d Mon Sep 17 00:00:00 2001 From: DerTyp7 Date: Fri, 24 Nov 2023 14:29:08 +0100 Subject: [PATCH] Refactor Docker and Nginx setup --- app/app.py | 102 +++++++++---------------------------------- app/dockerHandler.py | 49 +++++++++++++++++++++ 2 files changed, 69 insertions(+), 82 deletions(-) create mode 100644 app/dockerHandler.py diff --git a/app/app.py b/app/app.py index a98a3c6..9ba223e 100644 --- a/app/app.py +++ b/app/app.py @@ -1,85 +1,12 @@ import socket import threading import os -import docker - -client = docker.DockerClient(base_url='unix://var/run/docker.sock') - - -def setup_nginx_config(): - # Stop nginx - os.system('nginx -s stop') - # open nginx.conf for write create if not exist - nginx_conf = open('/etc/nginx/nginx.conf', 'w+') - nginx_conf.truncate() - nginx_conf.write('events { }\n') - nginx_conf.write('stream {\n') - - port_ip_map = docker_container_mapping() - for port in port_ip_map: - nginx_conf.write(' upstream upstream_{} {{\n'.format(port)) - nginx_conf.write(' server {}:{};\n'.format( - port_ip_map[port], port)) - nginx_conf.write(' server 127.0.0.1:{} backup;\n'.format(port)) - nginx_conf.write(' }\n') - - nginx_conf.write(' server {\n') - nginx_conf.write(' listen {}:{};\n'.format( - get_current_container_ip(), port)) - nginx_conf.write(' proxy_pass upstream_{};\n'.format(port)) - nginx_conf.write(' }\n') - nginx_conf.write('}\n') - nginx_conf.close() - os.system('nginx > /dev/null 2>&1 &') - - -def get_current_container_ip(): - # Get IP of current container - current_container_name = os.environ.get('HOSTNAME') - current_container = client.containers.get(current_container_name) - networks = current_container.attrs['NetworkSettings']['Networks'] - current_network = list(networks.keys())[0] - current_container_ip = networks[current_network]['IPAddress'] - return current_container_ip - - -def get_current_network(): - # Get network of current container - current_container_name = os.environ.get('HOSTNAME') - current_container = client.containers.get(current_container_name) - networks = current_container.attrs['NetworkSettings']['Networks'] - current_network = list(networks.keys())[0] - return current_network - - -def get_docker_container_by_ip(ip): - current_network = get_current_network() - print('getting docker container by ip {} in network {}'.format( - ip, current_network)) - containers = client.containers.list(all=True) - - for container in containers: - print('current network: {}'.format(current_network)) - print('checking container {}'.format(container.name)) - print('container networks: {}'.format( - container.attrs['NetworkSettings']['Networks'])) - print('container ip: {}'.format( - container.attrs['NetworkSettings']['Networks'][current_network]['IPAMConfig']['IPv4Address'])) - - networks = container.attrs['NetworkSettings']['Networks'] - if current_network in networks and networks[current_network]['IPAMConfig']['IPv4Address'] == ip: - print('found docker container {} with ip {} in network {}'.format( - container.name, ip, current_network)) - return container - print('no docker container found with ip {} in network {}'.format( - ip, current_network)) - return None +from dockerHandler import DockerHandler +from nginxHandler import NginxHandler def docker_container_mapping(): - # Get the PORT_IP_MAP environment variable - port_ip_map_str = os.getenv('PORT_IP_MAP') - + port_ip_map_str = os.environ.get('PORT_IP_MAP') # Convert the environment variable to a Python dictionary port_ip_map = {} for line in port_ip_map_str.split('\n'): @@ -91,9 +18,10 @@ def docker_container_mapping(): class RequestHandler(threading.Thread): - def __init__(self, port): + def __init__(self, port, docker_handler): super().__init__() self.port = port + self.docker_handler = docker_handler # Create a TCP/IP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port @@ -120,15 +48,25 @@ class RequestHandler(threading.Thread): if container_ip: # Start the Docker container print('starting docker container {}'.format(container_ip)) - get_docker_container_by_ip(container_ip).start() + self.docker_handler.get_container_by_ip(container_ip).start() # Send a response self.connection.sendall(b'Request handled') else: print('no docker container mapped to this port') -for port in range(25560, 25571): - handler = RequestHandler(port) - handler.start() +def main(): + docker_handler = DockerHandler( + 'unix://var/run/docker.sock', docker_container_mapping()) -setup_nginx_config() + for port in range(25560, 25571): + request_handler = RequestHandler(port, docker_handler) + request_handler.start() + + nginx_handler = NginxHandler('/etc/nginx/nginx.conf') + nginx_handler.setup_config_file( + docker_container_mapping(), docker_handler.get_current_container_ip()) + nginx_handler.print_config() + + +main() diff --git a/app/dockerHandler.py b/app/dockerHandler.py new file mode 100644 index 0000000..c62329a --- /dev/null +++ b/app/dockerHandler.py @@ -0,0 +1,49 @@ +import docker +import os + + +class DockerHandler: + def __init__(self, base_url, port_ip_map): + self.base_url = base_url + self.client = docker.DockerClient(base_url=base_url) + self.port_ip_map = port_ip_map + self.current_network = self.get_current_network() + + def get_current_container_ip(self): + # Get IP of current container + current_container_name = os.environ.get('HOSTNAME') + current_container = self.client.containers.get(current_container_name) + networks = current_container.attrs['NetworkSettings']['Networks'] + current_network = list(networks.keys())[0] + current_container_ip = networks[current_network]['IPAddress'] + return current_container_ip + + def get_current_network(self): + # Get network of current container + current_container_name = os.environ.get('HOSTNAME') + current_container = self.client.containers.get(current_container_name) + networks = current_container.attrs['NetworkSettings']['Networks'] + current_network = list(networks.keys())[0] + return current_network + + def get_container_by_ip(self, ip): + print('getting docker container by ip {} in network {}'.format( + ip, self.current_network)) + containers = self.client.containers.list(all=True) + + for container in containers: + print('current network: {}'.format(self.current_network)) + print('checking container {}'.format(container.name)) + print('container networks: {}'.format( + container.attrs['NetworkSettings']['Networks'])) + print('container ip: {}'.format( + container.attrs['NetworkSettings']['Networks'][self.current_network]['IPAMConfig']['IPv4Address'])) + + networks = container.attrs['NetworkSettings']['Networks'] + if self.current_network in networks and networks[self.current_network]['IPAMConfig']['IPv4Address'] == ip: + print('found docker container {} with ip {} in network {}'.format( + container.name, ip, self.current_network)) + return container + print('no docker container found with ip {} in network {}'.format( + ip, self.current_network)) + return None