xd.py 3.0 KB

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