feat: add installation and update script for VPS Monitor Agent
Some checks failed
Build and Push Docker Images / docker (push) Failing after 11s
Some checks failed
Build and Push Docker Images / docker (push) Failing after 11s
This commit is contained in:
220
vps-monitor/agent/install.sh
Executable file
220
vps-monitor/agent/install.sh
Executable file
@@ -0,0 +1,220 @@
|
||||
#!/usr/bin/env bash
|
||||
# =============================================================================
|
||||
# VPS Monitor Agent — script d'installation / mise à jour
|
||||
# Télécharge les fichiers depuis le dépôt Gitea et configure un service systemd.
|
||||
#
|
||||
# Usage :
|
||||
# sudo bash install.sh [--port PORT] [--key API_KEY] [--branch BRANCH]
|
||||
# sudo bash install.sh --update [--branch BRANCH]
|
||||
# sudo bash install.sh --uninstall
|
||||
# =============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
# ─── Constantes ───────────────────────────────────────────────────────────────
|
||||
REPO_BASE="https://git.jeanbonapp.com/jeanbon/ScriptVPS/raw/branch"
|
||||
REPO_FILES=(
|
||||
"vps-monitor/agent/agent.py"
|
||||
"vps-monitor/agent/requirements.txt"
|
||||
)
|
||||
|
||||
INSTALL_DIR="/opt/vps-monitor-agent"
|
||||
SERVICE_NAME="vps-monitor-agent"
|
||||
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
|
||||
DEFAULT_PORT=8001
|
||||
DEFAULT_BRANCH="main"
|
||||
|
||||
# ─── Couleurs ─────────────────────────────────────────────────────────────────
|
||||
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; NC='\033[0m'
|
||||
info() { echo -e "${CYAN}[INFO]${NC} $*"; }
|
||||
success() { echo -e "${GREEN}[OK]${NC} $*"; }
|
||||
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
|
||||
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; exit 1; }
|
||||
|
||||
# ─── Arguments ────────────────────────────────────────────────────────────────
|
||||
AGENT_PORT=$DEFAULT_PORT
|
||||
AGENT_API_KEY=""
|
||||
REPO_BRANCH=$DEFAULT_BRANCH
|
||||
MODE="install" # install | update | uninstall
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case $1 in
|
||||
--port) AGENT_PORT="$2"; shift 2 ;;
|
||||
--key) AGENT_API_KEY="$2"; shift 2 ;;
|
||||
--branch) REPO_BRANCH="$2"; shift 2 ;;
|
||||
--update) MODE="update"; shift ;;
|
||||
--uninstall) MODE="uninstall"; shift ;;
|
||||
*) error "Argument inconnu : $1. Voir INSTALL.md pour l'aide." ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# ─── Vérifications communes ───────────────────────────────────────────────────
|
||||
check_root() { [[ $EUID -ne 0 ]] && error "Ce script doit être exécuté en root (sudo)."; }
|
||||
check_deps() {
|
||||
command -v python3 &>/dev/null || error "Python 3 est requis : apt install python3 python3-venv"
|
||||
command -v docker &>/dev/null || error "Docker est requis. Consultez https://docs.docker.com/engine/install/"
|
||||
command -v curl &>/dev/null || error "curl est requis : apt install curl"
|
||||
}
|
||||
|
||||
# ─── Téléchargement des fichiers depuis le dépôt ─────────────────────────────
|
||||
download_files() {
|
||||
info "Téléchargement des fichiers (branche : ${REPO_BRANCH})..."
|
||||
mkdir -p "$INSTALL_DIR"
|
||||
for file in "${REPO_FILES[@]}"; do
|
||||
filename=$(basename "$file")
|
||||
url="${REPO_BASE}/${REPO_BRANCH}/${file}"
|
||||
info " ↓ $filename"
|
||||
curl -fsSL "$url" -o "$INSTALL_DIR/$filename" \
|
||||
|| error "Impossible de télécharger : $url"
|
||||
done
|
||||
success "Fichiers téléchargés."
|
||||
}
|
||||
|
||||
# ─── Désinstallation ──────────────────────────────────────────────────────────
|
||||
if [[ "$MODE" == "uninstall" ]]; then
|
||||
check_root
|
||||
info "Désinstallation de l'agent..."
|
||||
systemctl stop "$SERVICE_NAME" 2>/dev/null || true
|
||||
systemctl disable "$SERVICE_NAME" 2>/dev/null || true
|
||||
rm -f "$SERVICE_FILE"
|
||||
systemctl daemon-reload
|
||||
rm -rf "$INSTALL_DIR"
|
||||
success "Agent désinstallé."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ─── Mise à jour ──────────────────────────────────────────────────────────────
|
||||
if [[ "$MODE" == "update" ]]; then
|
||||
check_root
|
||||
[[ ! -d "$INSTALL_DIR" ]] && error "L'agent n'est pas installé. Lancez d'abord l'installation."
|
||||
|
||||
info "Mise à jour de l'agent VPS Monitor..."
|
||||
|
||||
# Conserver la clé API et le port existants
|
||||
if [[ -f "$INSTALL_DIR/.env" ]]; then
|
||||
AGENT_API_KEY=$(grep -E '^AGENT_API_KEY=' "$INSTALL_DIR/.env" | cut -d= -f2- || true)
|
||||
SAVED_PORT=$(grep -E '^AGENT_PORT=' "$INSTALL_DIR/.env" | cut -d= -f2- || true)
|
||||
[[ -n "$SAVED_PORT" ]] && AGENT_PORT="$SAVED_PORT"
|
||||
fi
|
||||
|
||||
download_files
|
||||
|
||||
info "Mise à jour des dépendances Python..."
|
||||
"$INSTALL_DIR/venv/bin/pip" install --quiet --upgrade pip
|
||||
"$INSTALL_DIR/venv/bin/pip" install --quiet -r "$INSTALL_DIR/requirements.txt"
|
||||
success "Dépendances à jour."
|
||||
|
||||
info "Redémarrage du service..."
|
||||
systemctl restart "$SERVICE_NAME"
|
||||
sleep 2
|
||||
|
||||
if systemctl is-active --quiet "$SERVICE_NAME"; then
|
||||
success "Service redémarré avec succès."
|
||||
CURRENT_VERSION=$(curl -sf --max-time 3 \
|
||||
"http://localhost:${AGENT_PORT}/health" 2>/dev/null | python3 -c \
|
||||
"import sys,json; d=json.load(sys.stdin); print(d.get('version','?'))" 2>/dev/null || echo "?")
|
||||
echo -e "\n${GREEN}Mise à jour terminée.${NC} Version active : ${CYAN}${CURRENT_VERSION}${NC}\n"
|
||||
else
|
||||
warn "Le service ne semble pas actif après la mise à jour."
|
||||
echo " journalctl -u ${SERVICE_NAME} -n 30 --no-pager"
|
||||
exit 1
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ─── Installation ─────────────────────────────────────────────────────────────
|
||||
check_root
|
||||
check_deps
|
||||
|
||||
info "Python : $(python3 --version)"
|
||||
info "Docker : $(docker --version)"
|
||||
|
||||
# Clé API : fournie > existante > générée
|
||||
if [[ -z "$AGENT_API_KEY" ]]; then
|
||||
if [[ -f "$INSTALL_DIR/.env" ]]; then
|
||||
AGENT_API_KEY=$(grep -E '^AGENT_API_KEY=' "$INSTALL_DIR/.env" | cut -d= -f2- || true)
|
||||
[[ -n "$AGENT_API_KEY" ]] && info "Clé API existante conservée."
|
||||
fi
|
||||
if [[ -z "$AGENT_API_KEY" ]]; then
|
||||
AGENT_API_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")
|
||||
warn "Aucune clé fournie — clé aléatoire générée."
|
||||
fi
|
||||
fi
|
||||
|
||||
download_files
|
||||
|
||||
# ─── Environnement virtuel ────────────────────────────────────────────────────
|
||||
if [[ ! -d "$INSTALL_DIR/venv" ]]; then
|
||||
info "Création de l'environnement virtuel Python..."
|
||||
python3 -m venv "$INSTALL_DIR/venv"
|
||||
fi
|
||||
|
||||
info "Installation des dépendances Python..."
|
||||
"$INSTALL_DIR/venv/bin/pip" install --quiet --upgrade pip
|
||||
"$INSTALL_DIR/venv/bin/pip" install --quiet -r "$INSTALL_DIR/requirements.txt"
|
||||
success "Dépendances installées."
|
||||
|
||||
# ─── Fichier .env ─────────────────────────────────────────────────────────────
|
||||
cat > "$INSTALL_DIR/.env" <<EOF
|
||||
AGENT_API_KEY=${AGENT_API_KEY}
|
||||
AGENT_PORT=${AGENT_PORT}
|
||||
EOF
|
||||
chmod 600 "$INSTALL_DIR/.env"
|
||||
success ".env configuré (chmod 600)."
|
||||
|
||||
# ─── Service systemd ──────────────────────────────────────────────────────────
|
||||
info "Configuration du service systemd..."
|
||||
cat > "$SERVICE_FILE" <<EOF
|
||||
[Unit]
|
||||
Description=VPS Monitor Agent
|
||||
After=docker.service network-online.target
|
||||
Requires=docker.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=root
|
||||
WorkingDirectory=${INSTALL_DIR}
|
||||
EnvironmentFile=${INSTALL_DIR}/.env
|
||||
ExecStart=${INSTALL_DIR}/venv/bin/uvicorn agent:app --host 0.0.0.0 --port \${AGENT_PORT}
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable "$SERVICE_NAME"
|
||||
systemctl restart "$SERVICE_NAME"
|
||||
|
||||
# ─── Vérification ─────────────────────────────────────────────────────────────
|
||||
sleep 2
|
||||
if systemctl is-active --quiet "$SERVICE_NAME"; then
|
||||
success "Service démarré et actif."
|
||||
else
|
||||
warn "Le service ne semble pas avoir démarré. Consultez les logs :"
|
||||
echo " journalctl -u ${SERVICE_NAME} -n 30 --no-pager"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ─── Résumé ───────────────────────────────────────────────────────────────────
|
||||
PUBLIC_IP=$(curl -sf --max-time 3 https://api.ipify.org 2>/dev/null \
|
||||
|| hostname -I | awk '{print $1}')
|
||||
|
||||
echo ""
|
||||
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
|
||||
echo -e "${GREEN} Agent VPS Monitor installé avec succès !${NC}"
|
||||
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
|
||||
echo -e " Adresse : ${CYAN}http://${PUBLIC_IP}:${AGENT_PORT}${NC}"
|
||||
echo -e " Clé API : ${YELLOW}${AGENT_API_KEY}${NC}"
|
||||
echo -e " Branche : ${CYAN}${REPO_BRANCH}${NC}"
|
||||
echo ""
|
||||
echo -e " Commandes utiles :"
|
||||
echo -e " journalctl -u ${SERVICE_NAME} -f # logs en direct"
|
||||
echo -e " systemctl status ${SERVICE_NAME} # état du service"
|
||||
echo -e " sudo bash install.sh --update # mise à jour"
|
||||
echo -e " sudo bash install.sh --uninstall # désinstallation"
|
||||
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
|
||||
echo ""
|
||||
warn "Notez la clé API — elle est nécessaire pour configurer le backend central."
|
||||
Reference in New Issue
Block a user