Melhorias no fluxo de instalação, suporte Fish shell e correção do timer
- setup.fish + install_systemd.fish: versões Fish shell dos scripts de instalação - setup.sh/.fish: verifica pré-requisitos, valida URL, confirma antes de sobrescrever config - install_systemd.sh/.fish: executa ping de teste após instalar - healthcheck.py: fallback para leitura do config file e ping /fail em caso de erro - chamado-health.timer: OnCalendar=minutely para disparar exatamente a cada 1 minuto
This commit is contained in:
parent
0edcf54e8a
commit
c448a3c01e
5 changed files with 170 additions and 22 deletions
44
healthcheck.py
Executable file → Normal file
44
healthcheck.py
Executable file → Normal file
|
|
@ -4,36 +4,62 @@ import sys
|
||||||
import urllib.request
|
import urllib.request
|
||||||
import urllib.error
|
import urllib.error
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def load_url_from_config():
|
||||||
|
config_file = Path.home() / ".config" / "chamado-health"
|
||||||
|
if config_file.exists():
|
||||||
|
for line in config_file.read_text().splitlines():
|
||||||
|
if line.startswith("HEALTHCHECK_URL="):
|
||||||
|
return line.split("=", 1)[1].strip()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def ping(url: str, timeout: int) -> int:
|
||||||
|
req = urllib.request.Request(url, method="GET", headers={"User-Agent": "chamado-health/1.0"})
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||||
|
return response.getcode()
|
||||||
|
|
||||||
|
|
||||||
|
def ping_fail(url: str, timeout: int) -> None:
|
||||||
|
fail_url = url.rstrip("/") + "/fail"
|
||||||
|
try:
|
||||||
|
req = urllib.request.Request(fail_url, method="GET", headers={"User-Agent": "chamado-health/1.0"})
|
||||||
|
urllib.request.urlopen(req, timeout=timeout)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
url = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("HEALTHCHECK_URL")
|
url = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("HEALTHCHECK_URL") or load_url_from_config()
|
||||||
if not url:
|
if not url:
|
||||||
print("ERROR: HEALTHCHECK_URL not set", file=sys.stderr)
|
print("ERROR: HEALTHCHECK_URL not set", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
timeout = int(os.environ.get("HEALTHCHECK_TIMEOUT", 10))
|
timeout = int(os.environ.get("HEALTHCHECK_TIMEOUT", 10))
|
||||||
req = urllib.request.Request(url, method="GET", headers={"User-Agent": "chamado-health/1.0"})
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
status = ping(url, timeout)
|
||||||
status = response.getcode()
|
if 200 <= status < 300:
|
||||||
if 200 <= status < 300:
|
print(f"{datetime.now(timezone.utc).isoformat()} status={status} url={url}")
|
||||||
print(f"{datetime.now(timezone.utc).isoformat()} status={status} url={url}")
|
return 0
|
||||||
return 0
|
|
||||||
body = response.read(200).decode("utf-8", errors="replace")
|
|
||||||
|
|
||||||
print(f"ERROR: HTTP {status}\n{body}", file=sys.stderr)
|
print(f"ERROR: HTTP {status} url={url}", file=sys.stderr)
|
||||||
|
ping_fail(url, timeout)
|
||||||
return 2
|
return 2
|
||||||
|
|
||||||
except urllib.error.HTTPError as exc:
|
except urllib.error.HTTPError as exc:
|
||||||
print(f"HTTPError {exc.code} {exc.reason} url={url}", file=sys.stderr)
|
print(f"HTTPError {exc.code} {exc.reason} url={url}", file=sys.stderr)
|
||||||
|
ping_fail(url, timeout)
|
||||||
return 3
|
return 3
|
||||||
except urllib.error.URLError as exc:
|
except urllib.error.URLError as exc:
|
||||||
print(f"URLError {exc.reason} url={url}", file=sys.stderr)
|
print(f"URLError {exc.reason} url={url}", file=sys.stderr)
|
||||||
|
ping_fail(url, timeout)
|
||||||
return 4
|
return 4
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print(f"ERROR {exc} url={url}", file=sys.stderr)
|
print(f"ERROR {exc} url={url}", file=sys.stderr)
|
||||||
|
ping_fail(url, timeout)
|
||||||
return 5
|
return 5
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
23
install_systemd.fish
Normal file
23
install_systemd.fish
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
#!/usr/bin/env fish
|
||||||
|
|
||||||
|
set SCRIPT_DIR (dirname (realpath (status filename)))
|
||||||
|
set CONFIG_FILE "$HOME/.config/chamado-health"
|
||||||
|
|
||||||
|
mkdir -p "$HOME/.config/systemd/user"
|
||||||
|
cp "$SCRIPT_DIR/systemd/chamado-health.service" "$HOME/.config/systemd/user/"
|
||||||
|
cp "$SCRIPT_DIR/systemd/chamado-health.timer" "$HOME/.config/systemd/user/"
|
||||||
|
|
||||||
|
echo "Arquivos de unit systemd copiados para ~/.config/systemd/user/."
|
||||||
|
|
||||||
|
systemctl --user daemon-reload
|
||||||
|
systemctl --user enable --now chamado-health.timer
|
||||||
|
systemctl --user status --no-pager chamado-health.timer
|
||||||
|
|
||||||
|
# Ping de teste imediato para confirmar que tudo funciona
|
||||||
|
echo ""
|
||||||
|
echo "Executando ping de teste..."
|
||||||
|
if python3 "$SCRIPT_DIR/healthcheck.py"
|
||||||
|
echo "Ping OK — instalação concluída com sucesso."
|
||||||
|
else
|
||||||
|
echo "AVISO: o ping de teste falhou. Verifique a URL em $CONFIG_FILE."
|
||||||
|
end
|
||||||
12
install_systemd.sh
Executable file → Normal file
12
install_systemd.sh
Executable file → Normal file
|
|
@ -2,13 +2,23 @@
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
CONFIG_FILE="${HOME}/.config/chamado-health"
|
||||||
|
|
||||||
mkdir -p "${HOME}/.config/systemd/user"
|
mkdir -p "${HOME}/.config/systemd/user"
|
||||||
cp "${SCRIPT_DIR}/systemd/chamado-health.service" "${HOME}/.config/systemd/user/"
|
cp "${SCRIPT_DIR}/systemd/chamado-health.service" "${HOME}/.config/systemd/user/"
|
||||||
cp "${SCRIPT_DIR}/systemd/chamado-health.timer" "${HOME}/.config/systemd/user/"
|
cp "${SCRIPT_DIR}/systemd/chamado-health.timer" "${HOME}/.config/systemd/user/"
|
||||||
|
|
||||||
echo "Copied systemd unit files to ~/.config/systemd/user/."
|
echo "Arquivos de unit systemd copiados para ~/.config/systemd/user/."
|
||||||
|
|
||||||
systemctl --user daemon-reload
|
systemctl --user daemon-reload
|
||||||
systemctl --user enable --now chamado-health.timer
|
systemctl --user enable --now chamado-health.timer
|
||||||
systemctl --user status --no-pager chamado-health.timer
|
systemctl --user status --no-pager chamado-health.timer
|
||||||
|
|
||||||
|
# Ping de teste imediato para confirmar que tudo funciona
|
||||||
|
echo ""
|
||||||
|
echo "Executando ping de teste..."
|
||||||
|
if python3 "${SCRIPT_DIR}/healthcheck.py"; then
|
||||||
|
echo "Ping OK — instalação concluída com sucesso."
|
||||||
|
else
|
||||||
|
echo "AVISO: o ping de teste falhou. Verifique a URL em ${CONFIG_FILE}."
|
||||||
|
fi
|
||||||
|
|
|
||||||
64
setup.fish
Normal file
64
setup.fish
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
#!/usr/bin/env fish
|
||||||
|
|
||||||
|
set REPO_URL "https://github.com/SantosFC/chamado-health.git"
|
||||||
|
set INSTALL_DIR "$HOME/src/chamado-health"
|
||||||
|
set CONFIG_FILE "$HOME/.config/chamado-health"
|
||||||
|
|
||||||
|
# 1. Verificar pré-requisitos
|
||||||
|
for cmd in git python3 systemctl loginctl
|
||||||
|
if not command -q $cmd
|
||||||
|
echo "ERRO: '$cmd' não encontrado. Instale e tente novamente."
|
||||||
|
exit 1
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# 2. Capturar URL
|
||||||
|
if not set -q HEALTHCHECK_URL
|
||||||
|
read -P "HEALTHCHECK_URL: " HEALTHCHECK_URL
|
||||||
|
end
|
||||||
|
|
||||||
|
# 3. Validar URL antes de prosseguir
|
||||||
|
echo "Validando URL..."
|
||||||
|
if not python3 -c "
|
||||||
|
import urllib.request, sys
|
||||||
|
try:
|
||||||
|
urllib.request.urlopen('$HEALTHCHECK_URL', timeout=10)
|
||||||
|
print('URL acessível.')
|
||||||
|
except Exception as e:
|
||||||
|
print(f'AVISO: não foi possível alcançar a URL: {e}', file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
" 2>/dev/null
|
||||||
|
echo "AVISO: não foi possível alcançar a URL informada."
|
||||||
|
read -P "Continuar mesmo assim? [s/N] " confirm
|
||||||
|
if not string match -qi 's' $confirm
|
||||||
|
echo "Instalação cancelada."
|
||||||
|
exit 1
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# 4. Clonar ou atualizar repositório
|
||||||
|
if test -d "$INSTALL_DIR/.git"
|
||||||
|
git -C $INSTALL_DIR pull --ff-only
|
||||||
|
else
|
||||||
|
git clone $REPO_URL $INSTALL_DIR
|
||||||
|
end
|
||||||
|
|
||||||
|
# 5. Salvar configuração (confirmando antes de sobrescrever)
|
||||||
|
if test -f $CONFIG_FILE
|
||||||
|
echo "Configuração existente encontrada em $CONFIG_FILE."
|
||||||
|
read -P "Deseja substituir? [s/N] " confirm
|
||||||
|
if string match -qi 's' $confirm
|
||||||
|
echo "HEALTHCHECK_URL=$HEALTHCHECK_URL" > $CONFIG_FILE
|
||||||
|
echo "Configuração salva em $CONFIG_FILE."
|
||||||
|
else
|
||||||
|
echo "Configuração mantida. Prosseguindo com valor existente."
|
||||||
|
end
|
||||||
|
else
|
||||||
|
echo "HEALTHCHECK_URL=$HEALTHCHECK_URL" > $CONFIG_FILE
|
||||||
|
echo "Configuração salva em $CONFIG_FILE."
|
||||||
|
end
|
||||||
|
|
||||||
|
fish "$INSTALL_DIR/install_systemd.fish"
|
||||||
|
|
||||||
|
loginctl enable-linger
|
||||||
|
echo "Linger habilitado — o timer executa mesmo sem sessão ativa."
|
||||||
49
setup.sh
Executable file → Normal file
49
setup.sh
Executable file → Normal file
|
|
@ -4,31 +4,56 @@ set -euo pipefail
|
||||||
REPO_URL="https://github.com/SantosFC/chamado-health.git"
|
REPO_URL="https://github.com/SantosFC/chamado-health.git"
|
||||||
INSTALL_DIR="${HOME}/src/chamado-health"
|
INSTALL_DIR="${HOME}/src/chamado-health"
|
||||||
CONFIG_FILE="${HOME}/.config/chamado-health"
|
CONFIG_FILE="${HOME}/.config/chamado-health"
|
||||||
|
|
||||||
|
# 1. Verificar pré-requisitos
|
||||||
|
for cmd in git python3 systemctl loginctl; do
|
||||||
|
command -v "$cmd" &>/dev/null || { echo "ERRO: '$cmd' não encontrado. Instale e tente novamente."; exit 1; }
|
||||||
|
done
|
||||||
|
|
||||||
|
# 2. Capturar URL
|
||||||
if [[ -z "${HEALTHCHECK_URL:-}" ]]; then
|
if [[ -z "${HEALTHCHECK_URL:-}" ]]; then
|
||||||
read -rp "HEALTHCHECK_URL: " HEALTHCHECK_URL </dev/tty
|
read -rp "HEALTHCHECK_URL: " HEALTHCHECK_URL </dev/tty
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ -z "${HEALTHCHECK_INTERVAL:-}" ]]; then
|
# 3. Validar URL antes de prosseguir
|
||||||
read -rp "Intervalo do timer [1min]: " HEALTHCHECK_INTERVAL </dev/tty
|
echo "Validando URL..."
|
||||||
HEALTHCHECK_INTERVAL="${HEALTHCHECK_INTERVAL:-1min}"
|
if ! python3 -c "
|
||||||
|
import urllib.request, sys
|
||||||
|
try:
|
||||||
|
urllib.request.urlopen('${HEALTHCHECK_URL}', timeout=10)
|
||||||
|
print('URL acessível.')
|
||||||
|
except Exception as e:
|
||||||
|
print(f'AVISO: não foi possível alcançar a URL: {e}', file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
" 2>/dev/null; then
|
||||||
|
echo "AVISO: não foi possível alcançar a URL informada."
|
||||||
|
read -rp "Continuar mesmo assim? [s/N] " confirm </dev/tty
|
||||||
|
[[ "$confirm" =~ ^[sS]$ ]] || { echo "Instalação cancelada."; exit 1; }
|
||||||
fi
|
fi
|
||||||
INTERVAL="${HEALTHCHECK_INTERVAL}"
|
|
||||||
|
|
||||||
|
# 4. Clonar ou atualizar repositório
|
||||||
if [[ -d "${INSTALL_DIR}/.git" ]]; then
|
if [[ -d "${INSTALL_DIR}/.git" ]]; then
|
||||||
git -C "${INSTALL_DIR}" pull --ff-only
|
git -C "${INSTALL_DIR}" pull --ff-only
|
||||||
else
|
else
|
||||||
git clone "${REPO_URL}" "${INSTALL_DIR}"
|
git clone "${REPO_URL}" "${INSTALL_DIR}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "HEALTHCHECK_URL=${HEALTHCHECK_URL}" > "${CONFIG_FILE}"
|
# 5. Salvar configuração (confirmando antes de sobrescrever)
|
||||||
echo "Config saved to ${CONFIG_FILE}."
|
if [[ -f "${CONFIG_FILE}" ]]; then
|
||||||
|
echo "Configuração existente encontrada em ${CONFIG_FILE}."
|
||||||
sed -i "s/OnUnitActiveSec=.*/OnUnitActiveSec=${INTERVAL}/" \
|
read -rp "Deseja substituir? [s/N] " confirm </dev/tty
|
||||||
"${INSTALL_DIR}/systemd/chamado-health.timer"
|
if [[ ! "$confirm" =~ ^[sS]$ ]]; then
|
||||||
sed -i "s/OnBootSec=.*/OnBootSec=${INTERVAL}/" \
|
echo "Configuração mantida. Prosseguindo com valor existente."
|
||||||
"${INSTALL_DIR}/systemd/chamado-health.timer"
|
else
|
||||||
|
echo "HEALTHCHECK_URL=${HEALTHCHECK_URL}" > "${CONFIG_FILE}"
|
||||||
|
echo "Configuração salva em ${CONFIG_FILE}."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "HEALTHCHECK_URL=${HEALTHCHECK_URL}" > "${CONFIG_FILE}"
|
||||||
|
echo "Configuração salva em ${CONFIG_FILE}."
|
||||||
|
fi
|
||||||
|
|
||||||
bash "${INSTALL_DIR}/install_systemd.sh"
|
bash "${INSTALL_DIR}/install_systemd.sh"
|
||||||
|
|
||||||
loginctl enable-linger
|
loginctl enable-linger
|
||||||
echo "Linger enabled — timer runs even without active session."
|
echo "Linger habilitado — o timer executa mesmo sem sessão ativa."
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue