Metadata-Version: 2.4
Name: django-server-healthcheck
Version: 0.1.0
Summary: Persistent Django server health reports with read-only administration
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: Django>=4.2
Requires-Dist: psutil>=5.9
Provides-Extra: integrations
Requires-Dist: django-email-ledger>=0.1.0; extra == "integrations"
Requires-Dist: django-postgres-backup-restore[gcs]>=0.1.0; extra == "integrations"
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"

# django-server-healthcheck

Reusable Django app extracted from limcweb's daily health report. One database
record is retained for every invocation of `python manage.py health_check`.
Version 0.1.0 is prepared locally; publication and deployment are separate steps.

## Installation

After publishing:

```powershell
pip install "django-server-healthcheck[integrations]==0.1.0"
```

Add `django_server_healthcheck` to `INSTALLED_APPS`, then run:

```powershell
python manage.py migrate django_server_healthcheck
python manage.py health_check
```

The core installation only requires Django and psutil. The `integrations` extra
adds django-email-ledger and django-postgres-backup-restore with GCS support.
Configure those libraries separately. Missing/unavailable integrations are
reported as concerns; other checks continue. Backup storage currently uses the
backup library's internal `_storage` API, so verify compatibility when upgrading it.

## Collected information

- CPU utilisation over a one-second sample, logical CPU count, and 1/5/15-minute
  load averages where the operating system supports them. Load averages are
  runnable/waiting work counts, not percentages.
- Memory total, available, used and utilisation percentage; swap total, used and
  utilisation percentage. These and CPU utilisation are snapshots, not daily peaks.
- Root and backup filesystem total/free bytes and usage percentage. Both paths
  are stored; a shared filesystem is displayed once in the report.
- Local and remote recent backup names, inspection errors, remote storage usage
  and quota percentage when the backend provides a quota.
- Last 24 hours of nginx requests, GET /, POST/PUT/PATCH and error log counts,
  including rotated gzip logs.
- Email recipient attempts, accepted sends, failures, pending attempts and success
  percentage for the previous 24 hours. Acceptance is not confirmed delivery.
- Trends against the latest completed run per previous day, up to six days,
  restricted to the same hostname. Today's run forms the seventh day.

## Model and administration

`django_server_healthcheck.models.HealthCheck` contains timestamps `started_at`,
`finished_at`, `period_start`, `period_end`; `hostname`; `status` (running, healthy,
concern, failed); JSON `metrics` and `concerns`; `error`; `report_subject` and
`report_body`; and `notification_status` (pending, sent, failed, skipped) and
`notification_error`.

Metrics have the top-level keys `nginx`, `system`, `disk`, `email`, and `backups`.
`system` contains `cpu`, `memory`, and `swap`. Unavailable collectors have null
results and an explanation in concerns. Records are not automatically deleted.
No historical JSON files are imported or modified.

The Django admin lists and filters runs and shows every field read-only. Add,
change, delete and bulk actions are disabled even for superusers. Staff need the
model's view permission. Read-only applies to admin; the command writes using the
ORM. There are no public HTTP API endpoints.

A running record is created before collection; the generated report is saved
before notification. Failed notifications retain the report and health status,
record the delivery exception and cause the command to fail. Unexpected collection
failures mark the run failed. A forcibly terminated process can leave a running
record. A working database and applied migrations are required; unlike the old
file-based command, a database write failure may prevent notification.

## Configuration

```python
HEALTH_CHECK_SUBJECT = 'lidecoder.com daily health check'
HEALTH_CHECK_NOTIFICATION_FUNCTION = 'liwebapp.emails.send_notification'
HEALTH_CHECK_CPU_WARNING_THRESHOLD = 90
HEALTH_CHECK_MEMORY_WARNING_THRESHOLD = 90
HEALTH_CHECK_SWAP_WARNING_THRESHOLD = 90
DISK_USAGE_WARNING_THRESHOLD = 90
HEALTH_CHECK_GOOGLE_USAGE_WARNING_THRESHOLD = 90
HEALTH_CHECK_NGINX_ACCESS_LOG_GLOB = '/var/log/nginx/access*'
HEALTH_CHECK_NGINX_ERROR_LOG_GLOBS = [
    '/var/log/nginx/error.log*', '/var/log/nginx.error.log*',
]
```

Thresholds are percentages; usage at or above a threshold produces a concern.
The remote storage threshold retains its legacy Google setting name but applies
to any supported backend with a quota. The subject defaults to `Daily server
health check`. Concerning reports use the existing `CONCERN: health check` prefix.

The optional notification callback receives `(subject, body)` and should raise
on failure; returning `False` also signals failure. `None` is accepted for existing
callbacks. Without a callback, Django `mail_admins` uses `ADMINS` and the configured
email backend. With no admins, notification is skipped. A sent status means the
sender returned without failure, not that delivery was confirmed.

Existing backup settings are preserved: `BACKUPS_DIR` (default `BASE_DIR/backups`),
`STORE_LOCAL_BACKUPS` (default true), and `BACKUP_STORAGE_BACKEND`, plus settings
required by the backup library. Log timestamps and backup filenames retain the
original command's server-local timezone interpretation; configure the server
and Django timezones consistently. The command runs once; use cron or systemd
to schedule it, and give that account read access to the logs and backup paths.

## Publishing

```powershell
.\publish.ps1 -BuildOnly
.\publish.ps1 -Repository testpypi
.\publish.ps1 -Repository pypi
```

The script installs development packaging tools, builds wheel and sdist into a
fresh uniquely named directory, validates them with `twine check --strict`, and
uploads only those artifacts unless `-BuildOnly` is passed. Select an interpreter
with `-Python C:\path\to\venv\Scripts\python.exe`. Configure Twine credentials
using keyring, `.pypirc`, or `TWINE_USERNAME=__token__` and `TWINE_PASSWORD`; do not
commit credentials. Bump the version before publishing another release.

## Future limcweb integration

After verifying publication, pin the dependency, add the app and migrate. Remove
limcweb's existing `liwebapp/management/commands/health_check.py` so it cannot shadow
the packaged command, configure the callback and subject above, and validate a
report. The existing systemd command name can remain unchanged. The old
`HEALTH_CHECK_DATA_DIR` is no longer used. Existing JSON trend history stays on disk;
database trend history accumulates from new runs. No limcweb files or requirements
have been changed as part of preparing this library.

## Development

```powershell
python -m pip install -e '.[dev]'
python -m django test tests --settings=test_settings
python -m django makemigrations --check --dry-run --settings=test_settings
```

Tests use SQLite, mocked system/service integrations and Django's in-memory email
backend. They do not send real reports or contact backup storage.
