2014-12-18 10:49:13 +01:00
|
|
|
#!/usr/bin/python3.4
|
|
|
|
|
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
|
2015-01-22 11:04:17 +01:00
|
|
|
import datetime
|
2014-12-18 10:49:13 +01:00
|
|
|
import signal
|
2015-01-22 11:04:17 +01:00
|
|
|
import os
|
|
|
|
import logging
|
|
|
|
import sys
|
2014-12-18 10:49:13 +01:00
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
target_path="/tmp/nginx/"
|
|
|
|
pid_file="/var/run/nginx.pid"
|
|
|
|
non_location_template = """# proxy for container '$containername'
|
|
|
|
server {
|
2015-01-07 15:06:15 +01:00
|
|
|
listen $listen;
|
2014-12-18 10:49:13 +01:00
|
|
|
server_name $name;
|
|
|
|
location / {
|
|
|
|
proxy_set_header X-Real-IP $$remote_addr;
|
|
|
|
proxy_set_header X-Forwarded-For $$remote_addr;
|
|
|
|
proxy_set_header Host $$host;
|
2015-01-22 11:04:17 +01:00
|
|
|
proxy_pass http://$ip:$port/;
|
2014-12-18 10:49:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
location_template="""# proxy for container '$containername'
|
|
|
|
server {
|
2015-01-07 15:06:15 +01:00
|
|
|
listen $listen;
|
2014-12-18 10:49:13 +01:00
|
|
|
server_name $name;
|
|
|
|
location / {
|
|
|
|
return 301 $$scheme://$name/$location;
|
|
|
|
}
|
|
|
|
location /$location {
|
|
|
|
proxy_set_header X-Real-IP $$remote_addr;
|
|
|
|
proxy_set_header X-Forwarded-For $$remote_addr;
|
|
|
|
proxy_set_header Host $$host;
|
2015-01-22 11:04:17 +01:00
|
|
|
proxy_pass http://$ip:$port/;
|
2014-12-18 10:49:13 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
"""
|
|
|
|
|
2015-01-22 11:04:17 +01:00
|
|
|
def print_json(data):
|
|
|
|
"""Prints the given value in JSON to stdout. Use this for debugging only"""
|
|
|
|
print(json.dumps(data, sort_keys=True, indent=4))
|
2014-12-18 10:49:13 +01: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 = {}
|
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("=")
|
|
|
|
env_data[t[0]] = t[1]
|
|
|
|
return env_data
|
|
|
|
|
|
|
|
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 = {}
|
2015-01-22 11:04:17 +01:00
|
|
|
for proxy_var in data['PROXY_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
|
|
|
|
|
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']
|
|
|
|
|
|
|
|
def extract_name(inspect_data):
|
|
|
|
"""extracts the container's name from the given inspect data"""
|
|
|
|
return inspect_data['Name']
|
|
|
|
|
|
|
|
def get_if_available(dict, key, defValue):
|
|
|
|
if key in dict:
|
|
|
|
return dict[key]
|
|
|
|
else:
|
|
|
|
return defValue
|
|
|
|
|
|
|
|
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)
|
|
|
|
if 'PROXY_DATA' in env_vars:
|
|
|
|
proxy_data = analyse_proxy_data(env_vars)
|
|
|
|
substitutes = {
|
|
|
|
'containername': extract_name(inspect_data),
|
|
|
|
'ip': extract_ip(inspect_data),
|
|
|
|
'location': get_if_available(proxy_data, 'location', ''),
|
|
|
|
'name': get_if_available(proxy_data, 'server_name', ''),
|
|
|
|
'port': get_if_available(proxy_data, 'port', 80),
|
|
|
|
'listen': get_if_available(proxy_data, 'ip', '*') + ':80'
|
|
|
|
}
|
|
|
|
logging.info('writing to %sproxy_%s', target_path, id)
|
|
|
|
with open(target_path + '/proxy_'+id, 'w') as file:
|
|
|
|
if substitutes['location'] == '':
|
|
|
|
del substitutes['location']
|
|
|
|
file.write(Template(non_location_template).substitute(substitutes))
|
|
|
|
else:
|
|
|
|
file.write(Template(location_template).substitute(substitutes))
|
|
|
|
|
|
|
|
def reload_nginx_configuration():
|
|
|
|
logging.info('HUPing nginx')
|
|
|
|
os.kill(pid, signal.SIGHUP)
|
|
|
|
|
|
|
|
def get_pid():
|
|
|
|
"""This function reads the process id from the given file."""
|
|
|
|
with open(pid_file, 'r') as file:
|
|
|
|
return int(file.read())
|
|
|
|
|
|
|
|
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))
|
|
|
|
if not os.path.exists(target_path):
|
|
|
|
logging.info('creating target path: %s', target_path)
|
|
|
|
os.mkdir(target_path)
|
|
|
|
|
|
|
|
client = Client(base_url='unix://var/run/docker.sock', version='1.15')
|
|
|
|
|
|
|
|
# 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)
|
|
|
|
|
|
|
|
container_id = event['id']
|
|
|
|
try:
|
|
|
|
inspect_data = client.inspect_container(container_id)
|
|
|
|
ip = extract_ip(inspect_data)
|
|
|
|
except APIError:
|
|
|
|
ip = ''
|
|
|
|
|
|
|
|
# logging.info(event['status'] + " " + ip)
|
|
|
|
if ip == '':
|
|
|
|
logging.info('removing %sproxy_%s', target_path, container_id)
|
|
|
|
if os.path.exists(target_path + 'proxy_' + container_id):
|
|
|
|
os.remove(target_path + 'proxy_' + container_id)
|
|
|
|
else:
|
|
|
|
handle_container(container_id)
|
|
|
|
|
|
|
|
reload_nginx_configuration()
|
|
|
|
|
|
|
|
# event['timestamp'] = datetime.datetime.fromtimestamp(event['time']).strftime('%Y-%m-%d %H:%M:%S');
|
|
|
|
# print_json(event)
|
|
|
|
|
2014-12-18 10:49:13 +01:00
|
|
|
|