|
| 1 | +import docker |
| 2 | +import os |
| 3 | +from prometheus_client import start_http_server, Counter, Gauge, CollectorRegistry |
| 4 | +import time |
| 5 | + |
| 6 | +# Create a registry |
| 7 | +registry = CollectorRegistry() |
| 8 | + |
| 9 | +# Define metrics |
| 10 | +container_state = Gauge('docker_container_state', 'Docker container state (1=running, 0=stopped, -1=error)', |
| 11 | + ['container_name', 'container_id', 'ports'], registry=registry) |
| 12 | +container_info = Gauge('docker_container_info', 'Docker container info', |
| 13 | + ['container_name', 'container_id', 'ports', 'status'], registry=registry) |
| 14 | + |
| 15 | +def get_container_ports(container): |
| 16 | + """Extract ports from container""" |
| 17 | + ports = [] |
| 18 | + if container.ports: |
| 19 | + for port_key, port_list in container.ports.items(): |
| 20 | + if port_list: |
| 21 | + for port_info in port_list: |
| 22 | + host_port = port_info.get('HostPort', '') |
| 23 | + if host_port: |
| 24 | + ports.append(f"{host_port}:{port_key}") |
| 25 | + return ','.join(ports) if ports else 'no-ports' |
| 26 | + |
| 27 | +def get_container_status(container): |
| 28 | + """Get container status: running (1), stopped (0), error (-1)""" |
| 29 | + state = container.status |
| 30 | + if state == 'running': |
| 31 | + return 1, 'Запущен' |
| 32 | + elif state == 'exited': |
| 33 | + return 0, 'Не запущен' |
| 34 | + elif state == 'created' or state == 'restarting': |
| 35 | + return 0, 'Перезагрузка' |
| 36 | + else: |
| 37 | + return -1, 'Ошибка' |
| 38 | + |
| 39 | +def update_metrics(): |
| 40 | + """Update metrics from Docker daemon""" |
| 41 | + try: |
| 42 | + client = docker.from_env() |
| 43 | + containers = client.containers.list(all=True) |
| 44 | + |
| 45 | + for container in containers: |
| 46 | + # Skip non-delux containers |
| 47 | + if not container.name.startswith('delux_'): |
| 48 | + continue |
| 49 | + |
| 50 | + ports = get_container_ports(container) |
| 51 | + state, status_text = get_container_status(container) |
| 52 | + |
| 53 | + # Update metrics |
| 54 | + container_state.labels( |
| 55 | + container_name=container.name, |
| 56 | + container_id=container.short_id, |
| 57 | + ports=ports |
| 58 | + ).set(state) |
| 59 | + |
| 60 | + container_info.labels( |
| 61 | + container_name=container.name, |
| 62 | + container_id=container.short_id, |
| 63 | + ports=ports, |
| 64 | + status=status_text |
| 65 | + ).set(state) |
| 66 | + |
| 67 | + print(f"Updated: {container.name} ({ports}) - {status_text}") |
| 68 | + except Exception as e: |
| 69 | + print(f"Error updating metrics: {e}") |
| 70 | + |
| 71 | +if __name__ == '__main__': |
| 72 | + # Start HTTP server on port 8888 |
| 73 | + start_http_server(8888, registry=registry) |
| 74 | + print("Docker exporter started on port 8888") |
| 75 | + |
| 76 | + # Update metrics every 5 seconds |
| 77 | + while True: |
| 78 | + update_metrics() |
| 79 | + time.sleep(5) |
0 commit comments