Compare commits

..

No commits in common. "ea975898b0f9220ea6d96c64121e76a77761aa6c" and "30e0322907d7b2cab832c3b18355cc92161b7d59" have entirely different histories.

13 changed files with 93 additions and 340 deletions

View file

@ -4,79 +4,41 @@ Simple health check script for Healthchecks.io, designed to run every minute usi
## Installation ## Installation
### 1. Install Git 1. Copy the systemd unit files to your user systemd directory:
```bash ```bash
# Debian/Ubuntu mkdir -p ~/.config/systemd/user
sudo apt update && sudo apt install -y git python3 cp systemd/chamado-health.service ~/.config/systemd/user/
cp systemd/chamado-health.timer ~/.config/systemd/user/
```
# RHEL/CentOS/Fedora 2. Update the `HEALTHCHECK_URL` in the service unit or set it in `~/.config/chamado-health`.
sudo dnf install -y git python3
```
### 2. Configure Git identity 3. Reload the user daemon and enable the timer:
```bash ```bash
git config --global user.name "Your Name" systemctl --user daemon-reload
git config --global user.email "you@example.com" systemctl --user enable --now chamado-health.timer
``` systemctl --user status chamado-health.timer
```
### 3. Clone the repository 4. If you change the service or timer unit later, reload the user daemon and restart the timer using the unit name (not the file path):
```bash ```bash
mkdir -p ~/src systemctl --user daemon-reload
git clone https://github.com/SantosFC/health-check.git ~/src/health-check systemctl --user restart --now chamado-health.timer
cd ~/src/health-check systemctl --user list-timers --all | grep chamado-health
``` journalctl --user -u chamado-health.service -n 10 --no-pager
```
### 4. Run the setup script
```bash
bash setup.sh
```
The script will:
1. Ask for your `HEALTHCHECK_URL` (Healthchecks.io ping endpoint) and validate it.
2. Ask for a `DEVICE_NAME` to identify this machine.
3. Save the configuration to `~/.config/health-check`.
4. Install and enable the systemd timer.
5. Run a test ping to confirm everything works.
> Both `HEALTHCHECK_URL` and `DEVICE_NAME` can be pre-set as environment variables to skip the interactive prompts:
> ```bash
> HEALTHCHECK_URL=https://hc-ping.com/<your-uuid> DEVICE_NAME=my-machine bash setup.sh
> ```
## Configuration ## Configuration
The configuration file is `~/.config/health-check`: - `HEALTHCHECK_URL` must be set to your Healthchecks.io ping endpoint.
- You can also pass the URL as a command-line argument to the script:
``` ```bash
HEALTHCHECK_URL=https://hc-ping.com/<your-uuid> ./healthcheck.py https://hc-ping.com/<your-uuid>
DEVICE_NAME=my-machine ```
```
You can also pass the URL as a command-line argument to the script:
```bash
./healthcheck.py https://hc-ping.com/<your-uuid>
```
## Systemd units
The unit files installed to `~/.config/systemd/user/` are:
- `health-check.service`
- `health-check.timer`
To reload and restart after changes:
```bash
systemctl --user daemon-reload
systemctl --user restart health-check.timer
systemctl --user list-timers --all | grep health-check
journalctl --user -u health-check.service -n 10 --no-pager
```
## Script behavior ## Script behavior

View file

@ -1,133 +0,0 @@
# Ping Payload Standard
This document defines the standard payload for all health check pings sent to Healthchecks.io across all agents (scripts, bots, services).
## Why not use an existing library?
The [`healthchecks-io`](https://pypi.org/project/healthchecks-io/) package on PyPI focuses on the management API and does not send a custom body payload. This library fills that gap with an opinionated, consistent payload that identifies the agent, device, IPs, and uptime on every ping.
---
## Using as a Python module
Install directly from the repository:
```bash
pip install git+https://github.com/SantosFC/health-check.git
```
### Basic usage
```python
from health_check import ping, ping_fail
url = "https://hc-ping.com/<your-uuid>"
try:
status = ping(url, agent="my-telegram-bot", device="my-server")
if 200 <= status < 300:
print("Ping OK")
else:
ping_fail(url, agent="my-telegram-bot", device="my-server")
except Exception as exc:
ping_fail(url, agent="my-telegram-bot", device="my-server")
raise
```
### Loading config from file
```python
from health_check import load_config, ping
config = load_config() # reads ~/.config/health-check
ping(config["HEALTHCHECK_URL"], agent="my-bot", device=config["DEVICE_NAME"])
```
### Custom config path
```python
from pathlib import Path
from health_check import load_config
config = load_config(config_file=Path("/etc/my-bot/config"))
```
### Timeout
```python
ping(url, agent="my-bot", device="server", timeout=5)
```
---
## HTTP Request
- **Method:** `POST`
- **URL:** `https://hc-ping.com/<uuid>`
## Headers
| Header | Value |
|---|---|
| `User-Agent` | `health-check/<version>` |
| `Content-Type` | `application/json` |
## Body
```json
{
"user": "<agent-name>",
"device": "<device-name>",
"ips": ["<ip1>", "<ip2>"],
"uptime": "<Xd Yh Zm>"
}
```
| Field | Type | Description |
|---|---|---|
| `user` | `string` | Name of the agent sending the ping (script, bot, service) |
| `device` | `string` | Name of the device or host where the agent runs |
| `ips` | `array of strings` | List of IP addresses of the device |
| `uptime` | `string` | Device uptime formatted as `Xd Yh Zm` |
## Example
```json
{
"user": "my-telegram-bot",
"device": "my-server",
"ips": ["192.168.1.10", "10.0.0.5"],
"uptime": "3d 14h 22m"
}
```
## Failure Ping
On error, agents must send a POST to `<uuid>/fail` with the same body. The `ping_fail` function handles this automatically.
---
## Telegram Notifications
Healthchecks.io includes the ping body as **Last Ping Body** in Telegram notifications (UP, DOWN, and failure events). The body is displayed as raw JSON with syntax highlighting.
Example of what appears in the Telegram message:
```
🟢 The check mySoccer is now UP.
Project: FastAPI
Tags: Telegram, Soccer
Period: 2 minutes
Total Pings: 860
Last Ping: Success, a second ago
Last Ping Body:
{"user":"ronaldo","device":"sandbox","ips":["192.168.122.71","fe80::f9f:d854:2bed:e454","100.70.8.112"],"uptime":"0d 2h 47m"}
```
### Implications for payload design
- Keep field names short and meaningful — they appear directly in the notification
- `user` identifies who sent the ping (agent name)
- `device` and `uptime` give immediate context for diagnosing incidents without leaving Telegram
- Avoid sensitive data in the body (IPs are acceptable; avoid tokens or passwords)

View file

@ -1,7 +0,0 @@
"""health-check: lightweight Healthchecks.io ping client."""
from health_check._config import load_config
from health_check._ping import ping, ping_fail
__version__ = "1.0.2"
__all__ = ["ping", "ping_fail", "load_config"]

View file

@ -1,17 +0,0 @@
import os
from pathlib import Path
def load_config(config_file: Path | None = None) -> dict:
"""Load configuration from file, falling back to environment variables."""
path = config_file or Path.home() / ".config" / "health-check"
config = {}
if path.exists():
for line in path.read_text().splitlines():
if "=" in line:
key, value = line.split("=", 1)
config[key.strip()] = value.strip()
config.setdefault("HEALTHCHECK_URL", os.environ.get("HEALTHCHECK_URL", ""))
config.setdefault("DEVICE_NAME", os.environ.get("DEVICE_NAME", "unknown"))
return config

View file

@ -1,50 +0,0 @@
import json
import subprocess
import urllib.error
import urllib.request
from pathlib import Path
_USER_AGENT = "health-check/1.0.2"
def _build_body(agent: str, device: str) -> bytes:
try:
ips = subprocess.check_output(["hostname", "-I"], timeout=5).decode().split()
except Exception:
ips = []
try:
seconds = int(float(Path("/proc/uptime").read_text().split()[0]))
d, rem = divmod(seconds, 86400)
h, rem = divmod(rem, 3600)
m = rem // 60
uptime = f"{d}d {h}h {m}m"
except Exception:
uptime = "unknown"
return json.dumps({"user": agent, "device": device, "ips": ips, "uptime": uptime}).encode()
def ping(url: str, agent: str, device: str, timeout: int = 10) -> int:
"""Send a success ping to Healthchecks.io. Returns the HTTP status code."""
body = _build_body(agent, device)
req = urllib.request.Request(
url, data=body, method="POST",
headers={"User-Agent": _USER_AGENT, "Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=timeout) as response:
return response.getcode()
def ping_fail(url: str, agent: str, device: str, timeout: int = 10) -> None:
"""Send a failure ping to Healthchecks.io (<uuid>/fail)."""
body = _build_body(agent, device)
fail_url = url.rstrip("/") + "/fail"
try:
req = urllib.request.Request(
fail_url, data=body, method="POST",
headers={"User-Agent": _USER_AGENT, "Content-Type": "application/json"},
)
urllib.request.urlopen(req, timeout=timeout)
except Exception:
pass

View file

@ -1,47 +1,71 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""CLI entry point for health-check.""" import json
import os import os
import sys import sys
from datetime import datetime, timezone
import urllib.error import urllib.error
from health_check import ping, ping_fail, load_config import urllib.request
from datetime import datetime, timezone
from pathlib import Path
AGENT = "Ronaldo Freitas Dias" PAYLOAD = json.dumps({"name": "Ronaldo Freitas Dias"}).encode()
def main() -> int: def load_url_from_config():
config = load_config() config_file = Path.home() / ".config" / "health-monitor"
url = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("HEALTHCHECK_URL") or config.get("HEALTHCHECK_URL") 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
HEADERS = {"User-Agent": "health-monitor/1.0", "Content-Type": "application/json"}
def ping(url: str, timeout: int) -> int:
req = urllib.request.Request(url, data=PAYLOAD, method="GET", headers=HEADERS)
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, data=PAYLOAD, method="GET", headers=HEADERS)
urllib.request.urlopen(req, timeout=timeout)
except Exception:
pass
def main():
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
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))
try: try:
status = ping(url, agent=AGENT, device=device, timeout=timeout) status = ping(url, timeout)
if 200 <= status < 300: if 200 <= status < 300:
print(f"{datetime.now(timezone.utc).isoformat()} status={status} device={device} url={url}") print(f"{datetime.now(timezone.utc).isoformat()} status={status} 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, agent=AGENT, device=device, timeout=timeout) 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, agent=AGENT, device=device, timeout=timeout) 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, agent=AGENT, device=device, timeout=timeout) 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, agent=AGENT, device=device, timeout=timeout) ping_fail(url, timeout)
return 5 return 5

View file

@ -1,17 +1,17 @@
#!/usr/bin/env fish #!/usr/bin/env fish
set SCRIPT_DIR (dirname (realpath (status filename))) set SCRIPT_DIR (dirname (realpath (status filename)))
set CONFIG_FILE "$HOME/.config/health-check" set CONFIG_FILE "$HOME/.config/health-monitor"
mkdir -p "$HOME/.config/systemd/user" mkdir -p "$HOME/.config/systemd/user"
cp "$SCRIPT_DIR/systemd/health-check.service" "$HOME/.config/systemd/user/" cp "$SCRIPT_DIR/systemd/health-monitor.service" "$HOME/.config/systemd/user/"
cp "$SCRIPT_DIR/systemd/health-check.timer" "$HOME/.config/systemd/user/" cp "$SCRIPT_DIR/systemd/health-monitor.timer" "$HOME/.config/systemd/user/"
echo "Arquivos de unit systemd copiados para ~/.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 health-check.timer systemctl --user enable --now health-monitor.timer
systemctl --user status --no-pager health-check.timer systemctl --user status --no-pager health-monitor.timer
# Ping de teste imediato para confirmar que tudo funciona # Ping de teste imediato para confirmar que tudo funciona
echo "" echo ""

View file

@ -2,17 +2,17 @@
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/health-check" CONFIG_FILE="${HOME}/.config/health-monitor"
mkdir -p "${HOME}/.config/systemd/user" mkdir -p "${HOME}/.config/systemd/user"
cp "${SCRIPT_DIR}/systemd/health-check.service" "${HOME}/.config/systemd/user/" cp "${SCRIPT_DIR}/systemd/health-monitor.service" "${HOME}/.config/systemd/user/"
cp "${SCRIPT_DIR}/systemd/health-check.timer" "${HOME}/.config/systemd/user/" cp "${SCRIPT_DIR}/systemd/health-monitor.timer" "${HOME}/.config/systemd/user/"
echo "Arquivos de unit systemd copiados para ~/.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 health-check.timer systemctl --user enable --now health-monitor.timer
systemctl --user status --no-pager health-check.timer systemctl --user status --no-pager health-monitor.timer
# Ping de teste imediato para confirmar que tudo funciona # Ping de teste imediato para confirmar que tudo funciona
echo "" echo ""

View file

@ -1,19 +1,3 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "health-check"
version = "1.0.2"
description = "Lightweight Healthchecks.io ping client with opinionated payload (agent, device, ips, uptime)"
readme = "README.md"
requires-python = ">=3.9"
license = { text = "MIT" }
dependencies = []
[project.scripts]
health-check = "healthcheck:main"
[tool.ruff] [tool.ruff]
target-version = "py39" target-version = "py39"
line-length = 110 line-length = 110
@ -29,8 +13,8 @@ select = [
"SIM", # flake8-simplify "SIM", # flake8-simplify
] ]
ignore = [ ignore = [
"B904", "B904", # raise from exc — não obrigatório em scripts simples
] ]
[tool.ruff.lint.isort] [tool.ruff.lint.isort]
known-first-party = ["health_check"] known-first-party = ["healthcheck"]

View file

@ -1,8 +1,8 @@
#!/usr/bin/env fish #!/usr/bin/env fish
set REPO_URL "https://github.com/SantosFC/health-check.git" set REPO_URL "https://github.com/SantosFC/health-check.git"
set INSTALL_DIR "$HOME/src/health-check" set INSTALL_DIR "$HOME/src/health-monitor"
set CONFIG_FILE "$HOME/.config/health-check" set CONFIG_FILE "$HOME/.config/health-monitor"
# 1. Verificar pré-requisitos # 1. Verificar pré-requisitos
for cmd in git python3 systemctl loginctl for cmd in git python3 systemctl loginctl
@ -36,30 +36,25 @@ except Exception as e:
end end
end end
# 4. Capturar nome do device # 4. Clonar ou atualizar repositório
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
# 6. Salvar configuração (confirmando antes de sobrescrever) # 5. 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
printf "HEALTHCHECK_URL=%s\nDEVICE_NAME=%s\n" $HEALTHCHECK_URL $DEVICE_NAME > $CONFIG_FILE echo "HEALTHCHECK_URL=$HEALTHCHECK_URL" > $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
printf "HEALTHCHECK_URL=%s\nDEVICE_NAME=%s\n" $HEALTHCHECK_URL $DEVICE_NAME > $CONFIG_FILE echo "HEALTHCHECK_URL=$HEALTHCHECK_URL" > $CONFIG_FILE
echo "Configuração salva em $CONFIG_FILE." echo "Configuração salva em $CONFIG_FILE."
end end

View file

@ -2,8 +2,8 @@
set -euo pipefail set -euo pipefail
REPO_URL="https://github.com/SantosFC/health-check.git" REPO_URL="https://github.com/SantosFC/health-check.git"
INSTALL_DIR="${HOME}/src/health-check" INSTALL_DIR="${HOME}/src/health-monitor"
CONFIG_FILE="${HOME}/.config/health-check" CONFIG_FILE="${HOME}/.config/health-monitor"
# 1. Verificar pré-requisitos # 1. Verificar pré-requisitos
for cmd in git python3 systemctl loginctl; do for cmd in git python3 systemctl loginctl; do
@ -31,30 +31,25 @@ except Exception as e:
[[ "$confirm" =~ ^[sS]$ ]] || { echo "Instalação cancelada."; exit 1; } [[ "$confirm" =~ ^[sS]$ ]] || { echo "Instalação cancelada."; exit 1; }
fi fi
# 4. Capturar nome do device # 4. Clonar ou atualizar repositório
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
# 6. Salvar configuração (confirmando antes de sobrescrever) # 5. 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
printf "HEALTHCHECK_URL=%s\nDEVICE_NAME=%s\n" "${HEALTHCHECK_URL}" "${DEVICE_NAME}" > "${CONFIG_FILE}" echo "HEALTHCHECK_URL=${HEALTHCHECK_URL}" > "${CONFIG_FILE}"
echo "Configuração salva em ${CONFIG_FILE}." echo "Configuração salva em ${CONFIG_FILE}."
fi fi
else else
printf "HEALTHCHECK_URL=%s\nDEVICE_NAME=%s\n" "${HEALTHCHECK_URL}" "${DEVICE_NAME}" > "${CONFIG_FILE}" echo "HEALTHCHECK_URL=${HEALTHCHECK_URL}" > "${CONFIG_FILE}"
echo "Configuração salva em ${CONFIG_FILE}." echo "Configuração salva em ${CONFIG_FILE}."
fi fi

View file

@ -1,12 +1,12 @@
[Unit] [Unit]
Description=Health check script Description=Health Monitor check script
Wants=network-online.target Wants=network-online.target
After=network-online.target After=network-online.target
[Service] [Service]
Type=oneshot Type=oneshot
EnvironmentFile=-%h/.config/health-check EnvironmentFile=-%h/.config/health-monitor
ExecStart=/usr/bin/env python3 %h/src/health-check/healthcheck.py ExecStart=/usr/bin/env python3 %h/src/health-monitor/healthcheck.py
StandardOutput=journal StandardOutput=journal
StandardError=journal StandardError=journal

View file

@ -1,5 +1,5 @@
[Unit] [Unit]
Description=Run health check every 2 minutes Description=Run Health Monitor check every 2 minutes
[Timer] [Timer]
OnCalendar=*:0/2 OnCalendar=*:0/2