2020-05-29 18:56:20 +02:00
|
|
|
#!/usr/bin/env python3
|
2014-12-18 10:49:13 +01:00
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
from docker import Client
|
|
|
|
from docker.errors import APIError
|
|
|
|
from string import Template
|
2014-12-18 10:49:13 +01:00
|
|
|
import json
|
2016-05-17 22:49:15 +02:00
|
|
|
import re
|
2014-12-18 10:49:13 +01:00
|
|
|
import signal
|
2015-01-22 11:04:17 +01:00
|
|
|
import os
|
|
|
|
import logging
|
2014-12-18 10:49:13 +01:00
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
target_path = "/tmp/nginx/"
|
2020-05-29 19:13:57 +02:00
|
|
|
config_path = target_path + "conf/"
|
2016-05-17 07:45:05 +02:00
|
|
|
pid_file = "/var/run/nginx.pid"
|
2015-01-22 11:04:17 +01:00
|
|
|
non_location_template = """# proxy for container '$containername'
|
|
|
|
server {
|
2015-01-07 15:06:15 +01:00
|
|
|
listen $listen;
|
2016-04-03 12:23:38 +02:00
|
|
|
server_name $names;
|
2014-12-18 10:49:13 +01:00
|
|
|
location / {
|
2016-05-14 18:20:28 +02:00
|
|
|
client_max_body_size $body_size;
|
2016-04-12 22:33:55 +02:00
|
|
|
client_body_timeout 300s;
|
2016-12-30 14:42:31 +01:00
|
|
|
if ($$http_x_forwarded_for = "") {
|
|
|
|
add_header X-Forwarded-For $$remote_addr;
|
|
|
|
}
|
2014-12-18 10:49:13 +01:00
|
|
|
proxy_set_header Host $$host;
|
2016-12-31 16:55:12 +01:00
|
|
|
proxy_pass http://$ip:$port;
|
2014-12-18 10:49:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
location_template = """# proxy for container '$containername'
|
2015-01-22 11:04:17 +01:00
|
|
|
server {
|
2015-01-07 15:06:15 +01:00
|
|
|
listen $listen;
|
2016-04-03 12:05:51 +02:00
|
|
|
server_name $names;
|
2014-12-18 10:49:13 +01:00
|
|
|
location / {
|
|
|
|
return 301 $$scheme://$name/$location;
|
|
|
|
}
|
|
|
|
location /$location {
|
2016-05-14 18:20:28 +02:00
|
|
|
client_max_body_size $body_size;
|
2016-04-12 22:33:55 +02:00
|
|
|
client_body_timeout 300s;
|
2016-12-30 14:42:31 +01:00
|
|
|
if ($$http_x_forwarded_for = "") {
|
|
|
|
add_header X-Forwarded-For $$remote_addr;
|
|
|
|
}
|
2014-12-18 10:49:13 +01:00
|
|
|
proxy_set_header Host $$host;
|
2016-12-31 16:55:12 +01:00
|
|
|
proxy_pass http://$ip:$port;
|
2014-12-18 10:49:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
def analyse_env_vars(inspect_data):
|
|
|
|
"""Extracts the environment variables from the given result of an 'inspect
|
|
|
|
container' call."""
|
2014-12-18 10:49:13 +01:00
|
|
|
env_data = {}
|
2016-12-31 16:55:12 +01:00
|
|
|
counter = 0
|
2016-05-17 07:45:05 +02:00
|
|
|
if 'Env' not in inspect_data['Config'] or inspect_data['Config']['Env'] is None:
|
2016-03-25 23:46:51 +01:00
|
|
|
return env_data
|
2015-01-22 11:04:17 +01:00
|
|
|
for env_var in inspect_data['Config']['Env']:
|
2014-12-18 10:49:13 +01:00
|
|
|
t = env_var.split("=")
|
2016-12-31 16:55:12 +01:00
|
|
|
key = t[0]
|
|
|
|
value = t[1]
|
|
|
|
if key == 'PROXY_DATA':
|
|
|
|
if key in env_data:
|
|
|
|
key = "{key}{postfix}".format(key=key, postfix=counter)
|
|
|
|
env_data[key] = value
|
2014-12-18 10:49:13 +01:00
|
|
|
return env_data
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2014-12-18 10:49:13 +01:00
|
|
|
def analyse_proxy_data(data):
|
2015-01-22 11:04:17 +01:00
|
|
|
"""Extracts the data for the proxy configuration (envrionment variable
|
|
|
|
'PROXY_DATA' and converts it to a dictionary."""
|
2014-12-18 10:49:13 +01:00
|
|
|
proxy_data = {}
|
2016-12-31 16:55:12 +01:00
|
|
|
for proxy_var in data.split(','):
|
2015-01-07 15:14:29 +01:00
|
|
|
t = proxy_var.split(":",1)
|
2014-12-18 10:49:13 +01:00
|
|
|
proxy_data[t[0]] = t[1]
|
|
|
|
return proxy_data
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2016-05-17 22:49:15 +02:00
|
|
|
def check_proxy_data_format(var_content):
|
|
|
|
"""
|
|
|
|
Validates the content of the variable.
|
|
|
|
:param var_content: content of the proxy data variable
|
|
|
|
:return: True if the content is of valid format, False otherwise
|
|
|
|
"""
|
|
|
|
return re.match(r"^(\w+:[^:,]+,)+\w+:[^:,]+$", var_content) is not None
|
|
|
|
|
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
def extract_ip(inspect_data):
|
|
|
|
"""extracts the container's ip from the given inspect data"""
|
|
|
|
return inspect_data['NetworkSettings']['IPAddress']
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
def extract_name(inspect_data):
|
|
|
|
"""extracts the container's name from the given inspect data"""
|
|
|
|
return inspect_data['Name']
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
|
|
|
def get_if_available(dictionary, key, defValue):
|
|
|
|
if key in dictionary:
|
|
|
|
return dictionary[key]
|
2015-01-22 11:04:17 +01:00
|
|
|
else:
|
|
|
|
return defValue
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
def handle_container(id):
|
|
|
|
"""This function take a container's id and collects all data required
|
|
|
|
to create a proper proxy configuration. The configuration is then
|
|
|
|
written to the directory of temporary nginx files"""
|
|
|
|
inspect_data = client.inspect_container(id)
|
|
|
|
env_vars = analyse_env_vars(inspect_data)
|
2016-12-31 16:55:12 +01:00
|
|
|
for env_key in env_vars:
|
|
|
|
env_data = env_vars[env_key]
|
|
|
|
if not check_proxy_data_format(env_data):
|
2016-12-31 19:51:49 +01:00
|
|
|
logging.info('cannot handle container with id "%s" named "%s": %s', id, extract_name(inspect_data), env_data)
|
2016-05-17 22:49:15 +02:00
|
|
|
return
|
2016-12-31 16:55:12 +01:00
|
|
|
proxy_data = analyse_proxy_data(env_data)
|
2015-02-19 19:27:52 +01:00
|
|
|
container_listen_ip = get_if_available(proxy_data, 'ip', '0.0.0.0')
|
|
|
|
if container_listen_ip != '0.0.0.0' and container_listen_ip not in listen_ips:
|
|
|
|
logging.info('container "%s"(%s) does not listen on %s.', extract_name(inspect_data), container_listen_ip, str(listen_ips))
|
|
|
|
return
|
|
|
|
logging.info('container "%s"(%s) is allowed to listen on %s.', extract_name(inspect_data), container_listen_ip, str(listen_ips))
|
2015-01-22 11:04:17 +01:00
|
|
|
substitutes = {
|
2016-12-31 16:55:12 +01:00
|
|
|
'containername': '{c} {d}'.format(c=extract_name(inspect_data), d=env_data),
|
2015-01-22 11:04:17 +01:00
|
|
|
'ip': extract_ip(inspect_data),
|
|
|
|
'location': get_if_available(proxy_data, 'location', ''),
|
2016-04-03 12:05:51 +02:00
|
|
|
'names': get_if_available(proxy_data, 'server_names', '').replace(';', ' '),
|
2015-01-22 11:04:17 +01:00
|
|
|
'port': get_if_available(proxy_data, 'port', 80),
|
2016-05-14 18:20:28 +02:00
|
|
|
'body_size': get_if_available(proxy_data, 'body_size', '1m'),
|
2015-02-19 19:27:52 +01:00
|
|
|
'listen': '*:80'
|
2015-01-22 11:04:17 +01:00
|
|
|
}
|
2020-05-29 19:13:57 +02:00
|
|
|
logging.info('writing to %sproxy_%s', config_path, id)
|
|
|
|
with open(config_path + '/proxy_{id}_{code}'.format(id=id,code=env_key), 'w') as file:
|
2015-01-22 11:04:17 +01:00
|
|
|
if substitutes['location'] == '':
|
|
|
|
del substitutes['location']
|
2017-01-22 10:00:43 +01:00
|
|
|
logging.info(Template(non_location_template).safe_substitute(substitutes))
|
|
|
|
file.write(Template(non_location_template).safe_substitute(substitutes))
|
2015-01-22 11:04:17 +01:00
|
|
|
else:
|
2017-01-22 10:00:43 +01:00
|
|
|
# make sure we have a name for the redirect
|
|
|
|
substitutes['name'] = substitutes['names'].split(' ')[0]
|
|
|
|
logging.info(Template(location_template).safe_substitute(substitutes))
|
|
|
|
file.write(Template(location_template).safe_substitute(substitutes))
|
2015-01-22 11:04:17 +01:00
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
def reload_nginx_configuration():
|
|
|
|
logging.info('HUPing nginx')
|
|
|
|
os.kill(pid, signal.SIGHUP)
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
def get_pid():
|
|
|
|
"""This function reads the process id from the given file."""
|
|
|
|
with open(pid_file, 'r') as file:
|
|
|
|
return int(file.read())
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2015-02-19 19:27:52 +01:00
|
|
|
def get_docker_id():
|
|
|
|
"""This function extracts the container's id from /proc/self/cgroup."""
|
|
|
|
id = ''
|
|
|
|
with open('/proc/self/cgroup', 'r') as file:
|
|
|
|
lines = file.read().split('\n')
|
|
|
|
for line in lines:
|
|
|
|
index = line.find('docker-')
|
|
|
|
if index != -1:
|
|
|
|
id = line[index+7:-6]
|
|
|
|
break
|
2015-02-19 20:36:15 +01:00
|
|
|
index = line.find('docker/')
|
|
|
|
if index != -1:
|
|
|
|
id = line[index+7:]
|
|
|
|
break
|
|
|
|
if id == '':
|
|
|
|
logging.error('could not determine container\'s id!')
|
2015-02-19 19:27:52 +01:00
|
|
|
return id
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2015-02-19 19:27:52 +01:00
|
|
|
def get_listen_ips():
|
|
|
|
inspect_data = client.inspect_container(get_docker_id())
|
2016-04-05 18:58:22 +02:00
|
|
|
mappings = inspect_data['NetworkSettings']['Ports']['80/tcp']
|
2015-02-19 19:27:52 +01:00
|
|
|
ips = []
|
2016-04-05 18:58:22 +02:00
|
|
|
if mappings is None or len(mappings) == 0:
|
|
|
|
ips.append('0.0.0.0')
|
|
|
|
else:
|
|
|
|
logging.info('count %s', len(mappings))
|
|
|
|
for data in mappings:
|
|
|
|
ips.append(data['HostIp'])
|
2015-02-19 19:27:52 +01:00
|
|
|
return ips
|
|
|
|
|
2016-05-17 07:45:05 +02:00
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
def setup_logging():
|
|
|
|
logging.basicConfig(format='%(asctime)s [%(levelname)s]: %(message)s', level=logging.INFO)
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
setup_logging()
|
|
|
|
|
|
|
|
# prepare required stuff
|
|
|
|
pid = get_pid()
|
|
|
|
logging.info('nginx pid: %s', str(pid))
|
2020-05-29 19:13:57 +02:00
|
|
|
if not os.path.exists(config_path):
|
2015-01-22 11:04:17 +01:00
|
|
|
logging.info('creating target path: %s', target_path)
|
|
|
|
os.mkdir(target_path)
|
2020-05-29 19:13:57 +02:00
|
|
|
logging.info('creating target path: %s', config_path)
|
|
|
|
os.mkdir(config_path)
|
2015-01-22 11:04:17 +01:00
|
|
|
|
|
|
|
client = Client(base_url='unix://var/run/docker.sock', version='1.15')
|
|
|
|
|
2015-02-19 19:27:52 +01:00
|
|
|
listen_ips = get_listen_ips()
|
|
|
|
logging.info('Listening on %s.', listen_ips)
|
|
|
|
if len(listen_ips) != 1:
|
|
|
|
logging.error('auto_proxy should only listen on 1 IP at a time, everything else can have security implications.')
|
|
|
|
exit()
|
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
# handle all running containers existing at startup of this container
|
|
|
|
container_ids = client.containers(quiet=True)
|
|
|
|
for container_id in container_ids:
|
|
|
|
handle_container(container_id['Id'])
|
|
|
|
reload_nginx_configuration()
|
|
|
|
|
|
|
|
# hook to the events
|
|
|
|
for line in client.events():
|
|
|
|
line_str = line.decode("utf-8")
|
|
|
|
event = json.loads(line_str)
|
|
|
|
|
2016-03-25 17:51:56 +01:00
|
|
|
if not 'id' in event:
|
|
|
|
continue
|
2015-01-22 11:04:17 +01:00
|
|
|
container_id = event['id']
|
|
|
|
try:
|
|
|
|
inspect_data = client.inspect_container(container_id)
|
|
|
|
ip = extract_ip(inspect_data)
|
|
|
|
except APIError:
|
|
|
|
ip = ''
|
|
|
|
|
|
|
|
if ip == '':
|
2017-01-22 10:00:43 +01:00
|
|
|
logging.info('removing data for container %s', container_id)
|
|
|
|
# since a container can expose multiple ports per PROXY_DATA it
|
|
|
|
# will generate multiple files. All names contain the container id.
|
|
|
|
# This will be used to delete all relevant files for a container
|
2020-05-29 19:13:57 +02:00
|
|
|
for filename in os.listdir(config_path):
|
2017-01-22 10:00:43 +01:00
|
|
|
if container_id in filename:
|
2020-05-29 19:13:57 +02:00
|
|
|
logging.info('removing file %s%s', config_path, container_id)
|
|
|
|
os.remove(config_path + filename)
|
2015-01-22 11:04:17 +01:00
|
|
|
else:
|
|
|
|
handle_container(container_id)
|
|
|
|
|
|
|
|
reload_nginx_configuration()
|