Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad383b602e | ||
|
|
65cd610468 |
No files matched your search
@@ -10,6 +10,10 @@ CORS_ORIGINS=http://localhost:8080
|
|||||||
# Where Last.fm clients are redirected to approve desktop auth tokens.
|
# Where Last.fm clients are redirected to approve desktop auth tokens.
|
||||||
UI_BASE_URL=http://localhost:8080
|
UI_BASE_URL=http://localhost:8080
|
||||||
|
|
||||||
|
# Logging: level (DEBUG, INFO, WARNING, ERROR) and format ("text", or "json" for log aggregators).
|
||||||
|
LOG_LEVEL=INFO
|
||||||
|
LOG_FORMAT=text
|
||||||
|
|
||||||
# Prometheus metrics are served on a separate port.
|
# Prometheus metrics are served on a separate port.
|
||||||
METRICS_PORT=9100
|
METRICS_PORT=9100
|
||||||
|
|
||||||
|
|||||||
@@ -87,11 +87,10 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Scrobbler <-> GoToSocial
|
- name: Scrobbler <-> GoToSocial
|
||||||
env:
|
env:
|
||||||
|
# Own compose project, network and image tags, so concurrent runs can't collide
|
||||||
INTEROP_PROJECT: interop-${{ github.run_id }}
|
INTEROP_PROJECT: interop-${{ github.run_id }}
|
||||||
run: |
|
SCROBBLER_IMAGE_TAG: interop-${{ github.run_id }}
|
||||||
# A subnet of its own, so concurrent runs can't collide
|
run: scripts/interop/run.sh
|
||||||
export INTEROP_SUBNET="172.30.$(( ${{ github.run_number }} % 200 + 20 )).0/24"
|
|
||||||
scripts/interop/run.sh
|
|
||||||
|
|
||||||
# ---- Publishing (main and v* tags only) -------------------------------------
|
# ---- Publishing (main and v* tags only) -------------------------------------
|
||||||
|
|
||||||
|
|||||||
@@ -18,11 +18,10 @@ x-federation: &federation
|
|||||||
FEDERATION_INSECURE_TESTING: "1"
|
FEDERATION_INSECURE_TESTING: "1"
|
||||||
UI_BASE_URL: https://scrobble.test
|
UI_BASE_URL: https://scrobble.test
|
||||||
|
|
||||||
|
# Docker picks the network's subnet, so concurrent runs can't collide on one. GoToSocial
|
||||||
|
# is therefore told to trust any private range rather than one specific /24.
|
||||||
networks:
|
networks:
|
||||||
fedi:
|
fedi:
|
||||||
ipam:
|
|
||||||
config:
|
|
||||||
- subnet: ${INTEROP_SUBNET:-172.30.0.0/24}
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
db:
|
db:
|
||||||
@@ -63,9 +62,9 @@ services:
|
|||||||
GTS_PORT: "80"
|
GTS_PORT: "80"
|
||||||
GTS_DB_TYPE: sqlite
|
GTS_DB_TYPE: sqlite
|
||||||
GTS_DB_ADDRESS: /gotosocial/storage/sqlite.db
|
GTS_DB_ADDRESS: /gotosocial/storage/sqlite.db
|
||||||
GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_SUBNET:-172.30.0.0/24} # let it reach Scrobbler on this network
|
GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16} # let it reach Scrobbler on this network
|
||||||
GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate
|
GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate
|
||||||
GTS_TRUSTED_PROXIES: ${INTEROP_SUBNET:-172.30.0.0/24}
|
GTS_TRUSTED_PROXIES: ${INTEROP_PRIVATE_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16}
|
||||||
GTS_ACCOUNTS_REGISTRATION_OPEN: "false"
|
GTS_ACCOUNTS_REGISTRATION_OPEN: "false"
|
||||||
GTS_LOG_LEVEL: ${GTS_LOG_LEVEL:-info}
|
GTS_LOG_LEVEL: ${GTS_LOG_LEVEL:-info}
|
||||||
sysctls:
|
sysctls:
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ services:
|
|||||||
UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080}
|
UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080}
|
||||||
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
||||||
FORWARDED_ALLOW_IPS: "*"
|
FORWARDED_ALLOW_IPS: "*"
|
||||||
|
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||||
|
LOG_FORMAT: ${LOG_FORMAT:-text}
|
||||||
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
LASTFM_API_KEY: ${LASTFM_API_KEY:-}
|
||||||
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
|
MUSICBRAINZ_CONTACT: ${MUSICBRAINZ_CONTACT:-}
|
||||||
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
|
ART_STORAGE_DIR: ${ART_STORAGE_DIR:-/data/album-art}
|
||||||
@@ -68,6 +70,8 @@ services:
|
|||||||
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-}
|
||||||
FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-}
|
FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-}
|
||||||
RUN_MIGRATIONS: "0" # the api service applies them
|
RUN_MIGRATIONS: "0" # the api service applies them
|
||||||
|
LOG_LEVEL: ${LOG_LEVEL:-INFO}
|
||||||
|
LOG_FORMAT: ${LOG_FORMAT:-text}
|
||||||
expose:
|
expose:
|
||||||
- "9101" # metrics: internal network only
|
- "9101" # metrics: internal network only
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ read **Putting it behind TLS** below — the quick start above serves plain HTTP
|
|||||||
| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated origins allowed to call `/api/v1`: wherever browsers actually load the UI from |
|
| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated origins allowed to call `/api/v1`: wherever browsers actually load the UI from |
|
||||||
| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins, and (with federation on) the public identity users are found under |
|
| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins, and (with federation on) the public identity users are found under |
|
||||||
| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` |
|
| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` |
|
||||||
|
| `LOG_LEVEL` | api, worker | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR`. The worker logs each task pass that did work at `INFO` (with its duration); idle polls show at `DEBUG` |
|
||||||
|
| `LOG_FORMAT` | api, worker | `text` | `json` writes one JSON object per line (with `task` and `duration_ms` fields for worker tasks), for log aggregators |
|
||||||
| `METRICS_PORT` | api | `9100` | Prometheus metrics port — keep it off the public network |
|
| `METRICS_PORT` | api | `9100` | Prometheus metrics port — keep it off the public network |
|
||||||
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
|
| `WEB_CONCURRENCY` | api | `2` | gunicorn workers |
|
||||||
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
|
| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start |
|
||||||
|
|||||||
@@ -11,11 +11,21 @@ wsgi_app = "scrobbler:create_app()"
|
|||||||
bind = os.environ.get("BIND", "0.0.0.0:8000")
|
bind = os.environ.get("BIND", "0.0.0.0:8000")
|
||||||
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
|
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
|
||||||
accesslog = "-"
|
accesslog = "-"
|
||||||
|
loglevel = os.environ.get("LOG_LEVEL", "INFO").lower()
|
||||||
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
|
forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1")
|
||||||
# gunicorn 26's control socket lives in $HOME, which the container user doesn't have.
|
# gunicorn 26's control socket lives in $HOME, which the container user doesn't have.
|
||||||
control_socket_disable = True
|
control_socket_disable = True
|
||||||
|
|
||||||
|
|
||||||
|
def post_fork(server, worker):
|
||||||
|
# Gunicorn's own messages go through the app's handler too, so the format is uniform.
|
||||||
|
import logging
|
||||||
|
|
||||||
|
gunicorn_error = logging.getLogger("gunicorn.error")
|
||||||
|
gunicorn_error.handlers.clear()
|
||||||
|
gunicorn_error.propagate = True
|
||||||
|
|
||||||
|
|
||||||
def on_starting(server):
|
def on_starting(server):
|
||||||
# Stale files from a previous run would double-count.
|
# Stale files from a previous run would double-count.
|
||||||
shutil.rmtree(MULTIPROC_DIR, ignore_errors=True)
|
shutil.rmtree(MULTIPROC_DIR, ignore_errors=True)
|
||||||
|
|||||||
@@ -2,6 +2,6 @@
|
|||||||
# docker compose for the federation interop stack (Scrobbler + GoToSocial).
|
# docker compose for the federation interop stack (Scrobbler + GoToSocial).
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
root="$(cd "$(dirname "$0")/../.." && pwd)"
|
root="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||||
# INTEROP_PROJECT and INTEROP_SUBNET let concurrent runs (e.g. in CI) stay apart.
|
# INTEROP_PROJECT (with a distinct SCROBBLER_IMAGE_TAG) lets concurrent runs (e.g. in CI) stay apart.
|
||||||
exec docker compose -p "${INTEROP_PROJECT:-scrobbler-interop}" \
|
exec docker compose -p "${INTEROP_PROJECT:-scrobbler-interop}" \
|
||||||
-f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@"
|
-f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@"
|
||||||
@@ -6,7 +6,14 @@ here="$(cd "$(dirname "$0")" && pwd)"
|
|||||||
compose="$here/compose.sh"
|
compose="$here/compose.sh"
|
||||||
keep=0; [ "${1:-}" = "--keep" ] && keep=1
|
keep=0; [ "${1:-}" = "--keep" ] && keep=1
|
||||||
|
|
||||||
cleanup() { [ "$keep" = 1 ] || "$compose" down -v --remove-orphans >/dev/null 2>&1; }
|
cleanup() {
|
||||||
|
[ "$keep" = 1 ] && return 0
|
||||||
|
"$compose" down -v --remove-orphans --rmi local >/dev/null 2>&1
|
||||||
|
# Per-run api/ui images (tagged with SCROBBLER_IMAGE_TAG) would otherwise pile up
|
||||||
|
[ -n "${SCROBBLER_IMAGE_TAG:-}" ] && "$compose" config --images 2>/dev/null \
|
||||||
|
| grep ":${SCROBBLER_IMAGE_TAG}$" | xargs -r docker rmi >/dev/null 2>&1
|
||||||
|
return 0
|
||||||
|
}
|
||||||
trap cleanup EXIT
|
trap cleanup EXIT
|
||||||
|
|
||||||
"$compose" down -v --remove-orphans >/dev/null 2>&1
|
"$compose" down -v --remove-orphans >/dev/null 2>&1
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ def create_app(config_object=None):
|
|||||||
app = Flask(__name__, static_folder=None) # API only: the UI is hosted separately
|
app = Flask(__name__, static_folder=None) # API only: the UI is hosted separately
|
||||||
app.config.from_object(config_object or Config)
|
app.config.from_object(config_object or Config)
|
||||||
|
|
||||||
|
from scrobbler.logsetup import configure_logging
|
||||||
|
|
||||||
|
configure_logging(app.config["LOG_LEVEL"], app.config["LOG_FORMAT"])
|
||||||
|
|
||||||
db.init_app(app)
|
db.init_app(app)
|
||||||
migrate.init_app(app, db, directory=_migrations_dir())
|
migrate.init_app(app, db, directory=_migrations_dir())
|
||||||
http_metrics.init_app(app)
|
http_metrics.init_app(app)
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ from flask.cli import AppGroup, with_appcontext
|
|||||||
def _run_worker(once: bool, poll: float, serve_metrics: bool) -> None:
|
def _run_worker(once: bool, poll: float, serve_metrics: bool) -> None:
|
||||||
from scrobbler import worker
|
from scrobbler import worker
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
||||||
if serve_metrics:
|
if serve_metrics:
|
||||||
from scrobbler.metrics.server import start_metrics_server
|
from scrobbler.metrics.server import start_metrics_server
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,9 @@ class Config:
|
|||||||
CORS_ORIGINS = _csv(os.environ.get("CORS_ORIGINS", "http://localhost:8080"))
|
CORS_ORIGINS = _csv(os.environ.get("CORS_ORIGINS", "http://localhost:8080"))
|
||||||
UI_BASE_URL = os.environ.get("UI_BASE_URL", "http://localhost:8080").rstrip("/")
|
UI_BASE_URL = os.environ.get("UI_BASE_URL", "http://localhost:8080").rstrip("/")
|
||||||
|
|
||||||
|
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
|
||||||
|
LOG_FORMAT = os.environ.get("LOG_FORMAT", "text").lower() # "text" or "json"
|
||||||
|
|
||||||
METRICS_PORT = int(os.environ.get("METRICS_PORT", "9100"))
|
METRICS_PORT = int(os.environ.get("METRICS_PORT", "9100"))
|
||||||
# Start the metrics HTTP server from create_app (dev server). Under gunicorn the
|
# Start the metrics HTTP server from create_app (dev server). Under gunicorn the
|
||||||
# server is started by gunicorn.conf.py instead, so this stays off there.
|
# server is started by gunicorn.conf.py instead, so this stays off there.
|
||||||
@@ -92,6 +95,8 @@ class TestConfig(Config):
|
|||||||
"postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test",
|
"postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test",
|
||||||
)
|
)
|
||||||
START_METRICS_SERVER = False
|
START_METRICS_SERVER = False
|
||||||
|
LOG_LEVEL = "INFO"
|
||||||
|
LOG_FORMAT = "text"
|
||||||
# Tests never inherit optional features or URLs from a developer's .env or
|
# Tests never inherit optional features or URLs from a developer's .env or
|
||||||
# environment; tests that need them turn them on, or override them, explicitly.
|
# environment; tests that need them turn them on, or override them, explicitly.
|
||||||
LASTFM_API_KEY = ""
|
LASTFM_API_KEY = ""
|
||||||
|
|||||||
@@ -68,6 +68,13 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No
|
|||||||
delivery.last_status, delivery.last_error = status, error[:1000]
|
delivery.last_status, delivery.last_error = status, error[:1000]
|
||||||
if _now() - delivery.created_at >= GIVE_UP_AFTER:
|
if _now() - delivery.created_at >= GIVE_UP_AFTER:
|
||||||
delivery.status = "abandoned"
|
delivery.status = "abandoned"
|
||||||
|
log.warning(
|
||||||
|
"delivery %s to %s abandoned after %s attempts: %s",
|
||||||
|
delivery.id,
|
||||||
|
delivery.inbox,
|
||||||
|
delivery.attempts,
|
||||||
|
error[:200],
|
||||||
|
)
|
||||||
return "abandoned"
|
return "abandoned"
|
||||||
delay = (
|
delay = (
|
||||||
RETRY_DELAYS[delivery.attempts - 1]
|
RETRY_DELAYS[delivery.attempts - 1]
|
||||||
@@ -75,6 +82,14 @@ def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | No
|
|||||||
else LATER_DELAY
|
else LATER_DELAY
|
||||||
)
|
)
|
||||||
delivery.next_attempt_at = _now() + delay
|
delivery.next_attempt_at = _now() + delay
|
||||||
|
log.warning(
|
||||||
|
"delivery %s to %s failed (attempt %s), retrying in %s: %s",
|
||||||
|
delivery.id,
|
||||||
|
delivery.inbox,
|
||||||
|
delivery.attempts,
|
||||||
|
delay,
|
||||||
|
error[:200],
|
||||||
|
)
|
||||||
return "retry"
|
return "retry"
|
||||||
|
|
||||||
|
|
||||||
@@ -135,7 +150,7 @@ def _deliver_in_context(app, delivery_id: int) -> str:
|
|||||||
try:
|
try:
|
||||||
return deliver(delivery_id)
|
return deliver(delivery_id)
|
||||||
except Exception:
|
except Exception:
|
||||||
log.exception("delivery %s failed unexpectedly", delivery_id)
|
log.exception("delivery %s failed unexpectedly (will be retried)", delivery_id)
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
return "retry" # the lease expires and it becomes due again
|
return "retry" # the lease expires and it becomes due again
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
@@ -224,7 +224,13 @@ def process(item: FederationInboxItem) -> None:
|
|||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
transient = isinstance(err, FetchError) and err.reason == "network"
|
transient = isinstance(err, FetchError) and err.reason == "network"
|
||||||
if not transient:
|
if not transient:
|
||||||
log.exception("inbox item %s failed", item.id)
|
log.exception(
|
||||||
|
"inbox item %s (%s) failed on attempt %s of %s",
|
||||||
|
item.id,
|
||||||
|
item.activity_type,
|
||||||
|
item.attempts,
|
||||||
|
MAX_ATTEMPTS,
|
||||||
|
)
|
||||||
if item.attempts < MAX_ATTEMPTS:
|
if item.attempts < MAX_ATTEMPTS:
|
||||||
_finish(item, "queued", f"retrying: {err}"[:255], done=False)
|
_finish(item, "queued", f"retrying: {err}"[:255], done=False)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Logging set-up shared by the API and the worker (`LOG_LEVEL`, `LOG_FORMAT`).
|
||||||
|
|
||||||
|
`text` is human-readable; `json` is one object per line for log aggregators. Fields passed
|
||||||
|
as `extra=` to a log call (e.g. `task`, `duration_ms`) appear as keys in the JSON output.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
from datetime import UTC, datetime
|
||||||
|
|
||||||
|
TEXT_FORMAT = "%(asctime)s %(levelname)s %(name)s %(message)s"
|
||||||
|
|
||||||
|
# Attributes every LogRecord has; anything else on a record came from `extra=`.
|
||||||
|
_STANDARD = set(logging.makeLogRecord({}).__dict__) | {"message", "asctime", "taskName"}
|
||||||
|
_HANDLER_FLAG = "_scrobbler_handler"
|
||||||
|
|
||||||
|
|
||||||
|
class JsonFormatter(logging.Formatter):
|
||||||
|
def format(self, record: logging.LogRecord) -> str:
|
||||||
|
entry = {
|
||||||
|
"time": datetime.fromtimestamp(record.created, UTC).isoformat(timespec="milliseconds"),
|
||||||
|
"level": record.levelname,
|
||||||
|
"logger": record.name,
|
||||||
|
"message": record.getMessage(),
|
||||||
|
}
|
||||||
|
entry.update((k, v) for k, v in record.__dict__.items() if k not in _STANDARD)
|
||||||
|
if record.exc_info:
|
||||||
|
entry["exception"] = self.formatException(record.exc_info)
|
||||||
|
return json.dumps(entry, default=str)
|
||||||
|
|
||||||
|
|
||||||
|
def configure_logging(level: str = "INFO", fmt: str = "text") -> None:
|
||||||
|
"""Point the root logger at stderr. Safe to call repeatedly (it replaces its own
|
||||||
|
handler); an unknown level falls back to INFO."""
|
||||||
|
root = logging.getLogger()
|
||||||
|
for handler in [h for h in root.handlers if getattr(h, _HANDLER_FLAG, False)]:
|
||||||
|
root.removeHandler(handler)
|
||||||
|
handler = logging.StreamHandler(sys.stderr)
|
||||||
|
setattr(handler, _HANDLER_FLAG, True)
|
||||||
|
handler.setFormatter(JsonFormatter() if fmt == "json" else logging.Formatter(TEXT_FORMAT))
|
||||||
|
root.addHandler(handler)
|
||||||
|
resolved = logging.getLevelName(str(level).upper())
|
||||||
|
root.setLevel(resolved if isinstance(resolved, int) else logging.INFO)
|
||||||
@@ -11,7 +11,7 @@ config = context.config
|
|||||||
|
|
||||||
# Interpret the config file for Python logging.
|
# Interpret the config file for Python logging.
|
||||||
# This line sets up loggers basically.
|
# This line sets up loggers basically.
|
||||||
fileConfig(config.config_file_name)
|
fileConfig(config.config_file_name, disable_existing_loggers=False)
|
||||||
logger = logging.getLogger('alembic.env')
|
logger = logging.getLogger('alembic.env')
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -602,6 +602,7 @@ def resolve_one_pending() -> bool:
|
|||||||
row.checked_at = datetime.now(UTC)
|
row.checked_at = datetime.now(UTC)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
metrics.art_worker_resolve_seconds.observe(time.perf_counter() - start)
|
metrics.art_worker_resolve_seconds.observe(time.perf_counter() - start)
|
||||||
|
log.info("album art for %r/%r: %s", row.artist, row.album, result.status)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -549,7 +549,7 @@ def process_job(job: ImportJob) -> None:
|
|||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
_finish(job, "failed", err.message)
|
_finish(job, "failed", err.message)
|
||||||
except Exception:
|
except Exception:
|
||||||
log.exception("import job %s failed", job.id)
|
log.exception("import job %s (%s) for user %s failed", job.id, job.source, job.user_id)
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
_finish(
|
_finish(
|
||||||
job, "failed", "The import failed unexpectedly. Try again, or check the server logs."
|
job, "failed", "The import failed unexpectedly. Try again, or check the server logs."
|
||||||
|
|||||||
+28
-2
@@ -50,18 +50,44 @@ def registered(app: Flask | None = None) -> list[str]:
|
|||||||
|
|
||||||
|
|
||||||
def _call(task: _Task) -> bool:
|
def _call(task: _Task) -> bool:
|
||||||
|
started = time.monotonic()
|
||||||
try:
|
try:
|
||||||
worked = bool(task.fn())
|
result = task.fn()
|
||||||
except Exception:
|
except Exception:
|
||||||
log.exception("worker task %s failed", task.name)
|
log.exception(
|
||||||
|
"worker task %s failed after %.0f ms",
|
||||||
|
task.name,
|
||||||
|
_elapsed_ms(started),
|
||||||
|
extra={"task": task.name, "outcome": "error", "duration_ms": _elapsed_ms(started)},
|
||||||
|
)
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
metrics.worker_tasks_total.labels(task=task.name, outcome="error").inc()
|
metrics.worker_tasks_total.labels(task=task.name, outcome="error").inc()
|
||||||
return False
|
return False
|
||||||
|
worked = bool(result)
|
||||||
if worked or task.every is not None:
|
if worked or task.every is not None:
|
||||||
metrics.worker_tasks_total.labels(task=task.name, outcome="worked").inc()
|
metrics.worker_tasks_total.labels(task=task.name, outcome="worked").inc()
|
||||||
|
duration = _elapsed_ms(started)
|
||||||
|
# Queue tasks are polled every couple of seconds, so only passes that did work are
|
||||||
|
# worth an INFO line; periodic tasks say so only when they report work (a truthy result).
|
||||||
|
log.log(
|
||||||
|
logging.INFO if worked else logging.DEBUG,
|
||||||
|
"worker task %s %s in %.0f ms",
|
||||||
|
task.name,
|
||||||
|
"worked" if worked else "ran (nothing to do)",
|
||||||
|
duration,
|
||||||
|
extra={
|
||||||
|
"task": task.name,
|
||||||
|
"outcome": "worked" if worked else "idle",
|
||||||
|
"duration_ms": duration,
|
||||||
|
},
|
||||||
|
)
|
||||||
return worked
|
return worked
|
||||||
|
|
||||||
|
|
||||||
|
def _elapsed_ms(started: float) -> float:
|
||||||
|
return round((time.monotonic() - started) * 1000, 1)
|
||||||
|
|
||||||
|
|
||||||
def run_once() -> bool:
|
def run_once() -> bool:
|
||||||
"""One pass: due periodic tasks, then each queue task once. True if any queue
|
"""One pass: due periodic tasks, then each queue task once. True if any queue
|
||||||
task did work (so there may be more waiting)."""
|
task did work (so there may be more waiting)."""
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import json
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from scrobbler.logsetup import JsonFormatter, configure_logging
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def restore_root_logger():
|
||||||
|
root = logging.getLogger()
|
||||||
|
handlers, level = list(root.handlers), root.level
|
||||||
|
yield
|
||||||
|
root.handlers[:] = handlers
|
||||||
|
root.setLevel(level)
|
||||||
|
|
||||||
|
|
||||||
|
def _record(msg="hello %s", args=("world",), **extra):
|
||||||
|
record = logging.LogRecord("test.logger", logging.INFO, __file__, 1, msg, args, None)
|
||||||
|
record.__dict__.update(extra)
|
||||||
|
return record
|
||||||
|
|
||||||
|
|
||||||
|
def test_json_formatter_emits_fields_and_extras():
|
||||||
|
entry = json.loads(JsonFormatter().format(_record(task="art", duration_ms=12.5)))
|
||||||
|
assert entry["message"] == "hello world"
|
||||||
|
assert entry["level"] == "INFO"
|
||||||
|
assert entry["logger"] == "test.logger"
|
||||||
|
assert entry["task"] == "art"
|
||||||
|
assert entry["duration_ms"] == 12.5
|
||||||
|
assert "time" in entry
|
||||||
|
|
||||||
|
|
||||||
|
def test_json_formatter_includes_exceptions():
|
||||||
|
try:
|
||||||
|
raise ValueError("boom")
|
||||||
|
except ValueError:
|
||||||
|
record = _record()
|
||||||
|
import sys
|
||||||
|
|
||||||
|
record.exc_info = sys.exc_info()
|
||||||
|
assert "ValueError: boom" in json.loads(JsonFormatter().format(record))["exception"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_configure_logging_is_idempotent_and_sets_level():
|
||||||
|
root = logging.getLogger()
|
||||||
|
configure_logging("DEBUG", "json")
|
||||||
|
configure_logging("warning", "text")
|
||||||
|
ours = [h for h in root.handlers if getattr(h, "_scrobbler_handler", False)]
|
||||||
|
assert len(ours) == 1
|
||||||
|
assert root.level == logging.WARNING
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_level_falls_back_to_info():
|
||||||
|
configure_logging("LOUD", "text")
|
||||||
|
assert logging.getLogger().level == logging.INFO
|
||||||
@@ -89,3 +89,32 @@ def test_worker_cli_lists_and_runs_tasks(app, tasks):
|
|||||||
assert ran == [1]
|
assert ran == [1]
|
||||||
alias = app.test_cli_runner().invoke(args=["imports", "worker", "--once", "--no-metrics"])
|
alias = app.test_cli_runner().invoke(args=["imports", "worker", "--once", "--no-metrics"])
|
||||||
assert alias.exit_code == 0, alias.output
|
assert alias.exit_code == 0, alias.output
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_pass_that_did_work_is_logged_with_its_duration(tasks, caplog):
|
||||||
|
tasks.register_task("busy", lambda: True)
|
||||||
|
with caplog.at_level("INFO", logger="scrobbler.worker"):
|
||||||
|
worker.run_once()
|
||||||
|
record = next(r for r in caplog.records if r.__dict__.get("task") == "busy")
|
||||||
|
assert record.levelname == "INFO"
|
||||||
|
assert record.outcome == "worked"
|
||||||
|
assert record.duration_ms >= 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_idle_passes_are_only_logged_at_debug(tasks, caplog):
|
||||||
|
tasks.register_task("idle", lambda: False)
|
||||||
|
with caplog.at_level("INFO", logger="scrobbler.worker"):
|
||||||
|
worker.run_once()
|
||||||
|
assert not [r for r in caplog.records if r.__dict__.get("task") == "idle"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_failures_log_the_task_name_and_duration(tasks, caplog):
|
||||||
|
def boom():
|
||||||
|
raise RuntimeError("nope")
|
||||||
|
|
||||||
|
tasks.register_task("broken", boom)
|
||||||
|
with caplog.at_level("ERROR", logger="scrobbler.worker"):
|
||||||
|
worker.run_once()
|
||||||
|
record = next(r for r in caplog.records if r.__dict__.get("task") == "broken")
|
||||||
|
assert record.outcome == "error"
|
||||||
|
assert "broken" in record.getMessage()
|
||||||
Reference in new issue
Block a user