Skip to content

Commit

Permalink
Check container
Browse files Browse the repository at this point in the history
  • Loading branch information
thueske committed Feb 18, 2024
1 parent dc5612d commit 051397a
Showing 1 changed file with 20 additions and 20 deletions.
40 changes: 20 additions & 20 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,39 @@
import docker, os
import docker
import os
from docker.errors import APIError, NotFound

label_key = "ofelia.enabled"
label_value = "true"

# Lese den Namen des Containers/Services aus einer Umgebungsvariable
container_name_to_restart = os.getenv('CONTAINER_NAME_TO_RESTART')
if not container_name_to_restart:
print("Die Umgebungsvariable 'CONTAINER_NAME_TO_RESTART' muss gesetzt sein.")
exit(1)

label_key = "ofelia.enabled"
label_value = "true"

client = docker.from_env()

def restart_container(container_name):
try:
container = client.containers.get(container_name)
container.restart()
print(f"Container {container_name} wurde neu gestartet.")
except NotFound:
print(f"Container {container_name} nicht gefunden.")
# Filtere Container nach dem Service-Namen
containers = client.containers.list(filters={"label": f"com.docker.compose.service={container_name}"})
for container in containers:
container.restart()
print(f"Container {container.name} ({container.id}) wurde neu gestartet.")
return # Beendet die Schleife nach dem ersten Neustart
except APIError as e:
print(f"API Fehler beim Neustarten des Containers {container_name}: {e}")
print(f"Fehler beim Neustarten des Containers {container_name}: {e}")

def handle_event(event):
if event.get("Type") == "container" and event.get("Action") == "start":
container_id = event.get("Actor").get("ID")
try:
container = client.containers.get(container_id)
labels = container.labels
if labels.get(label_key) == label_value:
print(f"Container mit Label {label_key}:{label_value} gestartet: {container.name}")
restart_container(container_name_to_restart)
except NotFound:
print(f"Container {container_id} nicht gefunden.")
except APIError as e:
print(f"API Fehler beim Abrufen des Containers {container_id}: {e}")
container = client.containers.get(container_id)
labels = container.labels

# Überprüfe, ob der Container das spezifische Label hat und nicht der Container ist, der neu gestartet werden soll
if labels.get(label_key) == label_value and container.attrs['Config']['Labels'].get('com.docker.compose.service') != container_name_to_restart:
print(f"Container mit Label {label_key}:{label_value} gestartet: {container.name}")
restart_container(container_name_to_restart)

def main():
print("Skript läuft und hört auf Container-Ereignisse...")
Expand Down

0 comments on commit 051397a

Please sign in to comment.