From 20e9f898171e3332b9b723beeeaaa8f98672404f Mon Sep 17 00:00:00 2001 From: bk233321 Date: Fri, 14 Mar 2025 05:30:33 +0100 Subject: [PATCH 1/2] ajout du script de l'autoscale --- backend/autoscaler.py | 65 +++++++++++++++++++++++++++++++++++++++++++ backend/stack.yml | 2 +- 2 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 backend/autoscaler.py diff --git a/backend/autoscaler.py b/backend/autoscaler.py new file mode 100644 index 0000000..d99214c --- /dev/null +++ b/backend/autoscaler.py @@ -0,0 +1,65 @@ +import subprocess +import time +import requests + +# Configuration +SERVICE_NAME = "mon_stack_backend" # Change ce nom si différent +BACKEND_URL = "http://localhost:5000/request_count" + +THRESHOLD_UP = 50 # Si plus de 50 requêtes dans l'intervalle -> scale up +THRESHOLD_DOWN = 10 # Si moins de 10 requêtes -> scale down +MIN_REPLICAS = 1 +MAX_REPLICAS = 10 +CHECK_INTERVAL = 10 # Secondes entre chaque vérification + +# Suivi local des requêtes précédentes +last_request_count = 0 + +def get_request_count(): + """Récupère le nombre total de requêtes reçues (cumulé) depuis l'API backend""" + try: + response = requests.get(BACKEND_URL) + if response.status_code == 200: + return response.json()["data"]["request_received_count"] + except Exception as e: + print(f"❌ Erreur récupération requêtes : {e}") + return 0 + +def get_current_replicas(): + """Récupère le nombre actuel de réplicas du service""" + try: + result = subprocess.run(["docker", "service", "ls"], capture_output=True, text=True) + for line in result.stdout.splitlines(): + if SERVICE_NAME in line: + return int(line.split()[3].split("/")[0]) # e.g., 3/3 -> 3 + except Exception as e: + print(f"❌ Erreur récupération réplicas : {e}") + return MIN_REPLICAS + +def scale_service(replicas): + """Met à jour le nombre de réplicas via Docker Swarm""" + print(f"⚙️ Scaling {SERVICE_NAME} to {replicas} replicas...") + subprocess.run(["docker", "service", "scale", f"{SERVICE_NAME}={replicas}"]) + +print("📈 Autoscaler démarré... (Ctrl+C pour arrêter)\n") + +while True: + current_request_count = get_request_count() + current_replicas = get_current_replicas() + + delta_requests = current_request_count - last_request_count + last_request_count = current_request_count + + print(f"🔄 Requêtes sur les {CHECK_INTERVAL}s : {delta_requests} | Réplicas actuels : {current_replicas}") + + if delta_requests > THRESHOLD_UP and current_replicas < MAX_REPLICAS: + print(f"📈 Augmentation de charge → scaling up !") + scale_service(current_replicas + 1) + elif delta_requests < THRESHOLD_DOWN and current_replicas > MIN_REPLICAS: + print(f"📉 Faible charge → scaling down.") + scale_service(current_replicas - 1) + else: + print("✅ Charge stable. Aucun scaling nécessaire.") + + print("-" * 50) + time.sleep(CHECK_INTERVAL) diff --git a/backend/stack.yml b/backend/stack.yml index 3768f10..3cf2563 100644 --- a/backend/stack.yml +++ b/backend/stack.yml @@ -15,7 +15,7 @@ services: condition: any backend: - image: md5_backend:latest + image: mon-backend:latest deploy: replicas: 1 restart_policy: -- GitLab From 5235fb34ee2067e7f1fcc0fc73324514effc005b Mon Sep 17 00:00:00 2001 From: bk233321 Date: Fri, 14 Mar 2025 05:46:09 +0100 Subject: [PATCH 2/2] suppression du host mode --- backend/stack.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/stack.yml b/backend/stack.yml index 3cf2563..f8c7ab0 100644 --- a/backend/stack.yml +++ b/backend/stack.yml @@ -15,7 +15,7 @@ services: condition: any backend: - image: mon-backend:latest + image: mon-backend:latest deploy: replicas: 1 restart_policy: @@ -27,7 +27,8 @@ services: - target: 5000 published: 5000 protocol: tcp - mode: host + # ❌ SUPPRIMÉ : mode: host + # En mode ingress par défaut, ce port sera load balancé networks: - app_network environment: -- GitLab