docker-healthcheck/docker-healthcheck.py

48 lines
1.4 KiB
Python
Raw Permalink Normal View History

2024-01-02 11:13:21 +00:00
#! /usr/bin/env python3
2023-12-13 03:17:07 +00:00
import requests
import yaml
import docker
import docker.errors
2024-01-02 11:13:21 +00:00
import sys
2023-12-13 03:17:07 +00:00
def read_checks() -> dict:
2024-01-02 11:13:21 +00:00
if len(sys.argv) < 2:
print("You need to specify a config by path")
sys.exit(1)
with open(sys.argv[1]) as f:
2023-12-13 03:17:07 +00:00
checks = yaml.safe_load(f)
return checks
def main() -> None:
checks = read_checks()
if "self" in checks:
requests.get(checks["self"])
client = docker.from_env()
for container_id in checks:
if container_id == "self":
continue
try:
container = client.containers.get(container_id)
container_status = container.attrs["State"]["Status"]
if container_status in ["healthy", "running"]:
2024-09-29 20:11:53 +00:00
retry_count = 0
while requests.post(checks[container_id]).content != b'OK':
if retry_count > 10:
print(f"error posting to '{container_id}' with url '{checks[container_id]}'")
retry_count += 1
2023-12-13 03:17:07 +00:00
else:
requests.post(
checks[container_id] + "/fail",
f"Container has status '{container_status}' which is not one of 'healthy' or 'running'"
)
except docker.errors.NotFound:
requests.post(checks[container_id] + "/fail", f"Container '{container_id}' not found.")
2023-12-13 03:17:07 +00:00
if __name__ == "__main__":
main()