- Frontend v4 accessible sur réseau local (192.168.1.40) - Ports ouverts: 3002 (frontend), 5001 (backend), 5004 (dashboard) - Ollama GPU fonctionnel - Self-healing interactif - Dashboard confiance Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
227 lines
7.6 KiB
Python
227 lines
7.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Démarre un serveur API local pour le développement avec les bons tokens.
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import time
|
|
import subprocess
|
|
import requests
|
|
from pathlib import Path
|
|
|
|
def load_env_local():
|
|
"""Charge les variables d'environnement depuis .env.local"""
|
|
env_path = Path(".env.local")
|
|
if not env_path.exists():
|
|
print("❌ Fichier .env.local non trouvé")
|
|
return False
|
|
|
|
print(f"📁 Chargement de {env_path}")
|
|
with open(env_path, 'r') as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if line and not line.startswith('#') and '=' in line:
|
|
key, value = line.split('=', 1)
|
|
os.environ[key.strip()] = value.strip()
|
|
if key.strip() in ['RPA_TOKEN_ADMIN', 'RPA_TOKEN_READONLY']:
|
|
print(f" ✓ {key.strip()}: {value.strip()[:16]}...")
|
|
return True
|
|
|
|
def check_port_available(port=8000):
|
|
"""Vérifie si le port est disponible"""
|
|
try:
|
|
response = requests.get(f"http://localhost:{port}/health", timeout=2)
|
|
return False # Port occupé
|
|
except:
|
|
return True # Port libre
|
|
|
|
def find_available_port(start_port=8001):
|
|
"""Trouve un port disponible"""
|
|
for port in range(start_port, start_port + 10):
|
|
if check_port_available(port):
|
|
return port
|
|
return None
|
|
|
|
def start_local_server():
|
|
"""Démarre le serveur API local"""
|
|
print("🚀 === DÉMARRAGE SERVEUR API LOCAL ===")
|
|
|
|
# Charger les variables d'environnement
|
|
if not load_env_local():
|
|
return False
|
|
|
|
# Vérifier si le port 8000 est libre
|
|
if not check_port_available(8000):
|
|
print("⚠️ Port 8000 occupé par un autre serveur")
|
|
|
|
# Trouver un port libre
|
|
free_port = find_available_port(8001)
|
|
if free_port:
|
|
print(f"🔄 Utilisation du port {free_port} à la place")
|
|
os.environ['PORT'] = str(free_port)
|
|
server_url = f"http://localhost:{free_port}/api/traces/upload"
|
|
else:
|
|
print("❌ Aucun port libre trouvé")
|
|
return False
|
|
else:
|
|
server_url = "http://localhost:8000/api/traces/upload"
|
|
|
|
# Vérifier que le dossier server existe
|
|
server_dir = Path("server")
|
|
if not server_dir.exists():
|
|
print("❌ Dossier server/ non trouvé")
|
|
return False
|
|
|
|
api_upload_path = server_dir / "api_upload.py"
|
|
if not api_upload_path.exists():
|
|
print("❌ Fichier server/api_upload.py non trouvé")
|
|
return False
|
|
|
|
# Démarrer le serveur
|
|
print(f"🚀 Démarrage du serveur sur {server_url}")
|
|
|
|
try:
|
|
# Démarrer en arrière-plan
|
|
process = subprocess.Popen([
|
|
sys.executable, "api_upload.py"
|
|
], cwd="server", env=os.environ.copy())
|
|
|
|
# Attendre que le serveur démarre
|
|
print("⏳ Attente du démarrage du serveur...")
|
|
port = int(os.environ.get('PORT', '8000'))
|
|
|
|
for i in range(15): # Attendre jusqu'à 15 secondes
|
|
time.sleep(1)
|
|
try:
|
|
# Tester avec le token admin
|
|
token = os.environ.get('RPA_TOKEN_ADMIN')
|
|
response = requests.get(
|
|
f"http://localhost:{port}/api/traces/status",
|
|
headers={"Authorization": f"Bearer {token}"},
|
|
timeout=2
|
|
)
|
|
if response.status_code == 200:
|
|
print("✅ Serveur démarré et authentification fonctionnelle!")
|
|
print(f" URL: http://localhost:{port}")
|
|
print(f" Token: {token[:16]}...")
|
|
|
|
# Mettre à jour .env.local avec la nouvelle URL si nécessaire
|
|
if port != 8000:
|
|
update_env_server_url(f"http://localhost:{port}/api/traces/upload")
|
|
|
|
return True
|
|
elif response.status_code == 401:
|
|
print(f"⚠️ Serveur démarré mais authentification échoue (tentative {i+1}/15)")
|
|
else:
|
|
print(f"⚠️ Serveur répond avec code {response.status_code} (tentative {i+1}/15)")
|
|
except requests.exceptions.ConnectionError:
|
|
print(f"⏳ Serveur pas encore prêt (tentative {i+1}/15)")
|
|
except Exception as e:
|
|
print(f"⚠️ Erreur test serveur: {e}")
|
|
|
|
print("❌ Serveur n'a pas démarré correctement dans les temps")
|
|
process.terminate()
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f"❌ Erreur démarrage serveur: {e}")
|
|
return False
|
|
|
|
def update_env_server_url(new_url):
|
|
"""Met à jour l'URL du serveur dans .env.local"""
|
|
env_path = Path(".env.local")
|
|
if not env_path.exists():
|
|
return
|
|
|
|
with open(env_path, 'r') as f:
|
|
lines = f.readlines()
|
|
|
|
# Chercher et modifier la ligne RPA_SERVER_URL
|
|
modified = False
|
|
for i, line in enumerate(lines):
|
|
if line.strip().startswith('RPA_SERVER_URL='):
|
|
lines[i] = f"RPA_SERVER_URL={new_url}\n"
|
|
modified = True
|
|
break
|
|
|
|
# Ajouter la ligne si elle n'existe pas
|
|
if not modified:
|
|
lines.append(f"RPA_SERVER_URL={new_url}\n")
|
|
|
|
with open(env_path, 'w') as f:
|
|
f.writelines(lines)
|
|
|
|
print(f"✓ URL serveur mise à jour dans .env.local: {new_url}")
|
|
|
|
def test_agent_upload():
|
|
"""Teste l'upload avec l'agent v0"""
|
|
print("\n🧪 === TEST UPLOAD AGENT V0 ===")
|
|
|
|
# Simuler un upload
|
|
token = os.environ.get('RPA_TOKEN_ADMIN')
|
|
port = int(os.environ.get('PORT', '8000'))
|
|
|
|
if not token:
|
|
print("❌ Token non disponible")
|
|
return False
|
|
|
|
try:
|
|
test_data = b"test upload data from agent v0"
|
|
response = requests.post(
|
|
f"http://localhost:{port}/api/traces/upload",
|
|
headers={
|
|
"Authorization": f"Bearer {token}",
|
|
"Content-Type": "application/octet-stream"
|
|
},
|
|
data=test_data,
|
|
timeout=10
|
|
)
|
|
|
|
print(f"Status: {response.status_code}")
|
|
print(f"Réponse: {response.text}")
|
|
|
|
if response.status_code == 200:
|
|
print("✅ Test d'upload réussi!")
|
|
return True
|
|
else:
|
|
print(f"❌ Test d'upload échoué: {response.status_code}")
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f"❌ Erreur test upload: {e}")
|
|
return False
|
|
|
|
def main():
|
|
"""Démarrage complet du serveur local"""
|
|
print("🎯 === DÉMARRAGE SERVEUR API LOCAL POUR DÉVELOPPEMENT ===")
|
|
|
|
if not start_local_server():
|
|
print("❌ Échec du démarrage du serveur")
|
|
return False
|
|
|
|
if not test_agent_upload():
|
|
print("❌ Test d'upload échoué")
|
|
return False
|
|
|
|
print("\n🎉 === SERVEUR LOCAL PRÊT ===")
|
|
print("✅ Serveur API local démarré avec succès")
|
|
print("✅ Authentification fonctionnelle")
|
|
print("✅ Upload testé avec succès")
|
|
|
|
port = int(os.environ.get('PORT', '8000'))
|
|
print(f"\n📝 INFORMATIONS:")
|
|
print(f" URL serveur: http://localhost:{port}")
|
|
print(f" Token admin: {os.environ.get('RPA_TOKEN_ADMIN', 'N/A')[:16]}...")
|
|
|
|
print(f"\n🚀 PROCHAINES ÉTAPES:")
|
|
print("1. Le serveur local tourne maintenant en arrière-plan")
|
|
print("2. Démarrer l'agent v0: cd agent_v0 && python main.py")
|
|
print("3. Capturer une session de test")
|
|
print("4. Vérifier que l'upload fonctionne sans erreur 401")
|
|
|
|
return True
|
|
|
|
if __name__ == "__main__":
|
|
success = main()
|
|
exit(0 if success else 1) |