feat: solicitar nome do device na instalação e enviar body no ping
This commit is contained in:
parent
06b7356164
commit
96349e4f22
3 changed files with 47 additions and 30 deletions
|
|
@ -1,71 +1,78 @@
|
||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
import urllib.error
|
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
PAYLOAD = json.dumps({"name": "Ronaldo Freitas Dias"}).encode()
|
USER_NAME = "Ronaldo Freitas Dias"
|
||||||
|
|
||||||
|
|
||||||
def load_url_from_config():
|
def load_config():
|
||||||
config_file = Path.home() / ".config" / "health-check"
|
config_file = Path.home() / ".config" / "health-monitor"
|
||||||
|
config = {}
|
||||||
if config_file.exists():
|
if config_file.exists():
|
||||||
for line in config_file.read_text().splitlines():
|
for line in config_file.read_text().splitlines():
|
||||||
if line.startswith("HEALTHCHECK_URL="):
|
if "=" in line:
|
||||||
return line.split("=", 1)[1].strip()
|
key, value = line.split("=", 1)
|
||||||
return None
|
config[key.strip()] = value.strip()
|
||||||
|
return config
|
||||||
|
|
||||||
|
|
||||||
HEADERS = {"User-Agent": "health-check/1.0", "Content-Type": "application/json"}
|
def ping(url: str, body: bytes, timeout: int) -> int:
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url, data=body, method="POST",
|
||||||
def ping(url: str, timeout: int) -> int:
|
headers={"User-Agent": "health-monitor/1.0", "Content-Type": "text/plain"}
|
||||||
req = urllib.request.Request(url, data=PAYLOAD, method="GET", headers=HEADERS)
|
)
|
||||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||||
return response.getcode()
|
return response.getcode()
|
||||||
|
|
||||||
|
|
||||||
def ping_fail(url: str, timeout: int) -> None:
|
def ping_fail(url: str, body: bytes, timeout: int) -> None:
|
||||||
fail_url = url.rstrip("/") + "/fail"
|
fail_url = url.rstrip("/") + "/fail"
|
||||||
try:
|
try:
|
||||||
req = urllib.request.Request(fail_url, data=PAYLOAD, method="GET", headers=HEADERS)
|
req = urllib.request.Request(
|
||||||
|
fail_url, data=body, method="POST",
|
||||||
|
headers={"User-Agent": "health-monitor/1.0", "Content-Type": "text/plain"}
|
||||||
|
)
|
||||||
urllib.request.urlopen(req, timeout=timeout)
|
urllib.request.urlopen(req, timeout=timeout)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
url = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("HEALTHCHECK_URL") or load_url_from_config()
|
config = load_config()
|
||||||
|
url = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("HEALTHCHECK_URL") or config.get("HEALTHCHECK_URL")
|
||||||
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
|
||||||
|
|
||||||
|
device = os.environ.get("DEVICE_NAME") or config.get("DEVICE_NAME", "unknown")
|
||||||
timeout = int(os.environ.get("HEALTHCHECK_TIMEOUT", 10))
|
timeout = int(os.environ.get("HEALTHCHECK_TIMEOUT", 10))
|
||||||
|
body = f"user={USER_NAME}\ndevice={device}".encode()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
status = ping(url, timeout)
|
status = ping(url, body, timeout)
|
||||||
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} device={device} url={url}")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
print(f"ERROR: HTTP {status} url={url}", file=sys.stderr)
|
print(f"ERROR: HTTP {status} url={url}", file=sys.stderr)
|
||||||
ping_fail(url, timeout)
|
ping_fail(url, body, 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)
|
ping_fail(url, body, 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)
|
ping_fail(url, body, 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)
|
ping_fail(url, body, timeout)
|
||||||
return 5
|
return 5
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
13
setup.fish
13
setup.fish
|
|
@ -36,25 +36,30 @@ except Exception as e:
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
# 4. Clonar ou atualizar repositório
|
# 4. Capturar nome do device
|
||||||
|
if not set -q DEVICE_NAME
|
||||||
|
read -P "Nome do device: " DEVICE_NAME
|
||||||
|
end
|
||||||
|
|
||||||
|
# 5. Clonar ou atualizar repositório
|
||||||
if test -d "$INSTALL_DIR/.git"
|
if test -d "$INSTALL_DIR/.git"
|
||||||
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
|
||||||
end
|
end
|
||||||
|
|
||||||
# 5. Salvar configuração (confirmando antes de sobrescrever)
|
# 6. Salvar configuração (confirmando antes de sobrescrever)
|
||||||
if test -f $CONFIG_FILE
|
if test -f $CONFIG_FILE
|
||||||
echo "Configuração existente encontrada em $CONFIG_FILE."
|
echo "Configuração existente encontrada em $CONFIG_FILE."
|
||||||
read -P "Deseja substituir? [s/N] " confirm
|
read -P "Deseja substituir? [s/N] " confirm
|
||||||
if string match -qi 's' $confirm
|
if string match -qi 's' $confirm
|
||||||
echo "HEALTHCHECK_URL=$HEALTHCHECK_URL" > $CONFIG_FILE
|
printf "HEALTHCHECK_URL=%s\nDEVICE_NAME=%s\n" $HEALTHCHECK_URL $DEVICE_NAME > $CONFIG_FILE
|
||||||
echo "Configuração salva em $CONFIG_FILE."
|
echo "Configuração salva em $CONFIG_FILE."
|
||||||
else
|
else
|
||||||
echo "Configuração mantida. Prosseguindo com valor existente."
|
echo "Configuração mantida. Prosseguindo com valor existente."
|
||||||
end
|
end
|
||||||
else
|
else
|
||||||
echo "HEALTHCHECK_URL=$HEALTHCHECK_URL" > $CONFIG_FILE
|
printf "HEALTHCHECK_URL=%s\nDEVICE_NAME=%s\n" $HEALTHCHECK_URL $DEVICE_NAME > $CONFIG_FILE
|
||||||
echo "Configuração salva em $CONFIG_FILE."
|
echo "Configuração salva em $CONFIG_FILE."
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
|
||||||
13
setup.sh
13
setup.sh
|
|
@ -31,25 +31,30 @@ except Exception as e:
|
||||||
[[ "$confirm" =~ ^[sS]$ ]] || { echo "Instalação cancelada."; exit 1; }
|
[[ "$confirm" =~ ^[sS]$ ]] || { echo "Instalação cancelada."; exit 1; }
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# 4. Clonar ou atualizar repositório
|
# 4. Capturar nome do device
|
||||||
|
if [[ -z "${DEVICE_NAME:-}" ]]; then
|
||||||
|
read -rp "Nome do device: " DEVICE_NAME </dev/tty
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 5. 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
|
||||||
|
|
||||||
# 5. Salvar configuração (confirmando antes de sobrescrever)
|
# 6. Salvar configuração (confirmando antes de sobrescrever)
|
||||||
if [[ -f "${CONFIG_FILE}" ]]; then
|
if [[ -f "${CONFIG_FILE}" ]]; then
|
||||||
echo "Configuração existente encontrada em ${CONFIG_FILE}."
|
echo "Configuração existente encontrada em ${CONFIG_FILE}."
|
||||||
read -rp "Deseja substituir? [s/N] " confirm </dev/tty
|
read -rp "Deseja substituir? [s/N] " confirm </dev/tty
|
||||||
if [[ ! "$confirm" =~ ^[sS]$ ]]; then
|
if [[ ! "$confirm" =~ ^[sS]$ ]]; then
|
||||||
echo "Configuração mantida. Prosseguindo com valor existente."
|
echo "Configuração mantida. Prosseguindo com valor existente."
|
||||||
else
|
else
|
||||||
echo "HEALTHCHECK_URL=${HEALTHCHECK_URL}" > "${CONFIG_FILE}"
|
printf "HEALTHCHECK_URL=%s\nDEVICE_NAME=%s\n" "${HEALTHCHECK_URL}" "${DEVICE_NAME}" > "${CONFIG_FILE}"
|
||||||
echo "Configuração salva em ${CONFIG_FILE}."
|
echo "Configuração salva em ${CONFIG_FILE}."
|
||||||
fi
|
fi
|
||||||
else
|
else
|
||||||
echo "HEALTHCHECK_URL=${HEALTHCHECK_URL}" > "${CONFIG_FILE}"
|
printf "HEALTHCHECK_URL=%s\nDEVICE_NAME=%s\n" "${HEALTHCHECK_URL}" "${DEVICE_NAME}" > "${CONFIG_FILE}"
|
||||||
echo "Configuração salva em ${CONFIG_FILE}."
|
echo "Configuração salva em ${CONFIG_FILE}."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue