| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- # encoding: utf-8
- import os
- import subprocess
- import hmac
- import hashlib
- from flask import Flask, request, abort
- app = Flask(__name__)
- #prueba 2
- GITHUB_SECRET = os.environ.get("GITHUB_WEBHOOK_SECRET")
- REPO_PATH = "/home/superti/page"
- SERVICE_NAME = "latapp-server.service"
- def verify_signature(data, github_signature):
- if not GITHUB_SECRET:
- print("GITHUB_SECRET no configurado. PELIGRO Los webhooks no serán validados.")
- return False
- hasher = hmac.new(GITHUB_SECRET.encode("utf-8"), data, hashlib.sha256)
- expected_signature = "sha256="+ hasher.hexdigest()
- return hmac.compare_digest(expected_signature, github_signature)
- @app.route("/webhook", methods=["POST"])
- def webhook():
- print(request.headers)
- if request.method == "POST":
- signature = request.headers.get("X-Hub-Signature-256", type=str)
- if not verify_signature(request.get_data(), signature):
- abort(403)
- event = request.headers.get("X-GitHub-Event")
- if event == "push":
- payload = request.json
- ref = payload["ref"]
- if ref == "refs/heads/main":
- print("Webhook de PR recibido para la rama {}. Iniciando despliegue...".format(ref.split("/")[2]))
- try:
- os.chdir(REPO_PATH)
- print("Ejecutando git pull...")
- subprocess.run(["git", "pull"], check=True)
- print("Creando/activando entorno virtual...")
- if not os.path.exists(".venv"):
- subprocess.run(["python3", "-m", "venv", ".venv"], check=True)
-
- print("Ejecutando pip install...")
- subprocess.run(["{}/.venv/bin/pip".format(REPO_PATH), "install", "-r", "requirements.txt"], check=True)
- print("Reiniciando servicio {}...".format(SERVICE_NAME))
- subprocess.run(["sudo", "systemctl", "restart", SERVICE_NAME], check=True)
-
- print("Despliegue completado con éxito.")
- return "Despliegue iniciado", 200
- except subprocess.CalledProcessError as e:
- print("Error durante el despliegue: {}".format(e))
- print(e.stderr)
- return "Error en el despliegue: {}".format(e), 500
- except Exception as e:
- print("Error inesperado: {}".format(e))
- return "Error inesperado: {}".format(e), 500
- else:
- print("Evento '{}' en rama '{}' no procesada.".format(event,ref.split("/")[2]))
- return "Evento no procesado", 200
- else:
- print("Evento '{}' no es de pull_request. Ignorando.".format(event))
- return "Evento no de PR. Ignorando.", 200
- else:
- abort(400)
- if __name__ == "__main__":
- print("Servidor Flask iniciado. Esperando webhooks en /webhook")
- app.run(host="0.0.0.0", port=9001)
|