docker_ssl_endpoint/list_domains.py

85 lines
2.4 KiB
Python
Raw Normal View History

#!/usr/bin/python3.4
from docker import Client
from docker.errors import APIError
from string import Template
import json
import signal
import os
from socket import getaddrinfo
import logging
2016-04-10 12:36:43 +02:00
def get_if_available(dict, key, defValue):
if key in dict:
return dict[key]
else:
return defValue
2016-04-10 12:36:43 +02:00
def analyse_proxy_data(data):
"""Extracts the data for the proxy configuration (envrionment variable
'PROXY_DATA' and converts it to a dictionary."""
proxy_data = {}
for proxy_var in data['PROXY_DATA'].split(','):
2016-04-10 12:36:43 +02:00
t = proxy_var.split(":", 1)
proxy_data[t[0]] = t[1]
return proxy_data
2016-04-10 12:36:43 +02:00
def analyse_env_vars(inspect_data):
"""Extracts the environment variables from the given result of an 'inspect
container' call."""
env_data = {}
if not 'Env' in inspect_data['Config'] or inspect_data['Config']['Env'] is None:
return env_data
for env_var in inspect_data['Config']['Env']:
t = env_var.split("=")
env_data[t[0]] = t[1]
return env_data
2016-04-10 12:36:43 +02:00
def handle_container(docker_client, 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 = docker_client.inspect_container(id)
env_vars = analyse_env_vars(inspect_data)
if 'PROXY_DATA' in env_vars:
proxy_data = analyse_proxy_data(env_vars)
names = get_if_available(proxy_data, 'server_names', '').split(';')
return names
return []
2016-04-10 12:36:43 +02:00
def get_resolving_domains_from_containers(docker_client):
container_ids = docker_client.containers(quiet=True)
logging.info('list of containers: %s', str(container_ids))
domains = []
for container_id in container_ids:
domains.extend(handle_container(docker_client, container_id['Id']))
logging.info('list of activated domains on containers: %s', str(domains))
resolved_domains = []
for domain in domains:
try:
getaddrinfo(domain, None)
resolved_domains.append(domain)
except Exception:
pass
logging.info('list of resolved domains on containers: %s', str(resolved_domains))
return resolved_domains
2016-04-10 12:36:43 +02:00
if __name__ == '__main__':
client = Client(base_url='unix://var/run/docker.sock', version='1.15')
resolved_domains = get_resolving_domains_from_containers(client)
print(str(resolved_domains))