diff --git a/backend/autoscaler.py b/backend/autoscaler.py new file mode 100644 index 0000000000000000000000000000000000000000..d99214c932ac9cc79be9b4fc47c592a79b162a82 --- /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 3768f100b9b2cb3d9d69a3db3ffa0b472dda8d59..f8c7ab00772aa7f7d92b816af914eb7682891fa4 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: @@ -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: