xd.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # encoding: utf-8
  2. import json
  3. import os
  4. import subprocess
  5. import hmac
  6. import hashlib
  7. from flask import Flask, request, abort
  8. app = Flask(__name__)
  9. #prueba 2
  10. GITHUB_SECRET = os.environ.get("GITHUB_WEBHOOK_SECRET")
  11. REPO_PATH = "/home/superti/page"
  12. SERVICE_NAME = "latapp-server.service"
  13. def verify_signature(data, github_signature):
  14. if not GITHUB_SECRET:
  15. print("GITHUB_SECRET no configurado. PELIGRO Los webhooks no serán validados.")
  16. return False
  17. hasher = hmac.new(GITHUB_SECRET.encode("utf-8"), data, hashlib.sha256)
  18. expected_signature = "sha256="+ hasher.hexdigest()
  19. return hmac.compare_digest(expected_signature, github_signature)
  20. @app.route("/webhook", methods=["POST"])
  21. def webhook():
  22. print(request.headers)
  23. if request.method == "POST":
  24. signature = request.headers.get("X-Hub-Signature-256", type=str)
  25. if not verify_signature(request.get_data(), signature):
  26. abort(403)
  27. event = request.headers.get("X-GitHub-Event")
  28. if event == "push":
  29. payload = request.json
  30. ref = payload["ref"]
  31. if ref == "refs/heads/main":
  32. print("Webhook de PR recibido para la rama {}. Iniciando despliegue...".format(ref.split("/")[2]))
  33. try:
  34. os.chdir(REPO_PATH)
  35. print("Ejecutando git pull...")
  36. subprocess.run(["git", "pull"], check=True)
  37. print("Creando/activando entorno virtual...")
  38. if not os.path.exists(".venv"):
  39. subprocess.run(["python3", "-m", "venv", ".venv"], check=True)
  40. print("Ejecutando pip install...")
  41. subprocess.run(["{}/.venv/bin/pip".format(REPO_PATH), "install", "-r", "requirements.txt"], check=True)
  42. print("Reiniciando servicio {}...".format(SERVICE_NAME))
  43. subprocess.run(["sudo", "systemctl", "restart", SERVICE_NAME], check=True)
  44. print("Despliegue completado con éxito.")
  45. return "Despliegue iniciado", 200
  46. except subprocess.CalledProcessError as e:
  47. print("Error durante el despliegue: {}".format(e))
  48. print(e.stderr)
  49. return "Error en el despliegue: {}".format(e), 500
  50. except Exception as e:
  51. print("Error inesperado: {}".format(e))
  52. return "Error inesperado: {}".format(e), 500
  53. else:
  54. print("Evento '{}' en rama '{}' no procesada.".format(event,ref.split("/")[2]))
  55. return "Evento no procesado", 200
  56. else:
  57. print("Evento '{}' no es de pull_request. Ignorando.".format(event))
  58. return "Evento no de PR. Ignorando.", 200
  59. else:
  60. abort(400)
  61. if __name__ == "__main__":
  62. print("Servidor Flask iniciado. Esperando webhooks en /webhook")
  63. app.run(host="0.0.0.0", port=9001)