T13.4: run the Okta sync on a schedule (D18)
A daemon timer thread starts from a new lifespan hook in app.py and calls the T13.3 sync every OKTA_SYNC_INTERVAL_SECONDS (default 900, minimum 300). With no OKTA_API_TOKEN it starts nothing and the startup log says so. The api runs 2 gunicorn workers, so each starts its own timer. A single atomic conditional UPDATE on one app_settings row (key okta_sync) is the gate: exactly one worker wins each cycle, on SQLite and Postgres, with no lock held. The row survives a restart, so a restart inside the interval starts no second run. A fetch is now capped at 120 s in total, so a run is always shorter than the minimum interval and cannot overlap the next. No migration needed. docker-compose.yml passes OKTA_API_TOKEN, OKTA_ORG_URL, OKTA_SYNC_PROFILE_ATTRIBUTE and OKTA_SYNC_INTERVAL_SECONDS to the api service. tests/okta_sync_schedule_check.py: 38 checks including an 8-worker race on a file database (exactly one winner, 16 rounds) and fail-closed through the scheduled path. okta_auth_check.py still 22/22.
This commit is contained in:
@@ -37,13 +37,17 @@ request URL, so the URL is not copied into the message either.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable, Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import models, okta_auth
|
||||
@@ -57,6 +61,10 @@ PAGE_LIMIT = 200
|
||||
# raises when the bound is reached. 50 pages of 200 is 10,000 people.
|
||||
MAX_PAGES = 50
|
||||
TIMEOUT_SECONDS = 15.0
|
||||
# The whole fetch, all pages together, must finish inside this. T13.4 relies on it:
|
||||
# a run is always shorter than the shortest allowed interval, so one cycle can
|
||||
# never still be running when the next is due.
|
||||
TOTAL_DEADLINE_SECONDS = 120.0
|
||||
|
||||
# Which Okta *profile attribute* matches each OIDC claim that OKTA_IDENTITY_CLAIM
|
||||
# may name. The sign-in flow reads a claim from the ID token. This API returns
|
||||
@@ -171,10 +179,13 @@ def fetch_users(http: Optional[httpx.Client] = None) -> "list[OktaUser]":
|
||||
url: Optional[str] = f"{base}/api/v1/users"
|
||||
params: Optional[dict] = {"limit": PAGE_LIMIT}
|
||||
users: "list[OktaUser]" = []
|
||||
started = time.monotonic()
|
||||
try:
|
||||
for _ in range(MAX_PAGES):
|
||||
if not url:
|
||||
break
|
||||
if time.monotonic() - started > TOTAL_DEADLINE_SECONDS:
|
||||
raise _fail(f"took longer than {int(TOTAL_DEADLINE_SECONDS)} seconds in total")
|
||||
try:
|
||||
resp = client.get(url, params=params, headers=headers,
|
||||
follow_redirects=False)
|
||||
@@ -336,3 +347,107 @@ def run_sync(db: Session, fetch: Optional[Callable[[], "list[OktaUser]"]] = None
|
||||
len(okta_users), checked, len(planned))
|
||||
return SyncResult(ok=True, okta_users=len(okta_users), checked=checked,
|
||||
disabled=[name for name, _ in planned])
|
||||
|
||||
|
||||
# ── T13.4: running it on a schedule ───────────────────────────────────────────
|
||||
# The api container runs gunicorn with 2 workers, and a later deploy may run more
|
||||
# than one container. Each worker starts its own timer thread below. Without a
|
||||
# gate, all of them would call Okta every cycle and write overlapping changes.
|
||||
# The gate is one row in app_settings (key "okta_sync"). Its updated_at is "when
|
||||
# the last run was claimed". A worker claims a run with ONE atomic conditional
|
||||
# UPDATE: it succeeds only if the last claim is older than the interval. Exactly
|
||||
# one worker wins each cycle, on SQLite and on Postgres, with no lock held.
|
||||
#
|
||||
# The row survives a restart, so a restart inside the interval does not start a
|
||||
# second run. A slow run cannot overlap the next: a fetch is bounded to
|
||||
# TOTAL_DEADLINE_SECONDS (120) and the interval can never be set below
|
||||
# INTERVAL_MIN_SECONDS (300). Inside one process the timer thread runs one cycle at
|
||||
# a time, so cycles cannot stack there either.
|
||||
CLAIM_KEY = "okta_sync"
|
||||
INTERVAL_DEFAULT_SECONDS = 900 # 15 minutes (D18, proposed, not confirmed)
|
||||
INTERVAL_MIN_SECONDS = 300
|
||||
TICK_SECONDS = 60 # how often each worker checks if a run is due
|
||||
START_DELAY_SECONDS = 10 # let the app finish starting first
|
||||
|
||||
|
||||
def interval_seconds() -> int:
|
||||
"""OKTA_SYNC_INTERVAL_SECONDS, default 900. A value that is not a number uses
|
||||
the default. A value under 300 is raised to 300 (see above for why)."""
|
||||
raw = os.getenv("OKTA_SYNC_INTERVAL_SECONDS", "").strip()
|
||||
if not raw:
|
||||
return INTERVAL_DEFAULT_SECONDS
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
log.warning("OKTA_SYNC_INTERVAL_SECONDS=%r is not a whole number; using %d",
|
||||
raw, INTERVAL_DEFAULT_SECONDS)
|
||||
return INTERVAL_DEFAULT_SECONDS
|
||||
if value < INTERVAL_MIN_SECONDS:
|
||||
log.warning("OKTA_SYNC_INTERVAL_SECONDS=%d is under the minimum; using %d",
|
||||
value, INTERVAL_MIN_SECONDS)
|
||||
return INTERVAL_MIN_SECONDS
|
||||
return value
|
||||
|
||||
|
||||
def claim(db: Session, interval: int, now: Optional[datetime] = None) -> bool:
|
||||
"""Try to claim this cycle. True for exactly one caller per interval."""
|
||||
now = now or datetime.now(timezone.utc)
|
||||
cutoff = now - timedelta(seconds=interval)
|
||||
try:
|
||||
row = db.get(models.AppSetting, CLAIM_KEY)
|
||||
if row is None:
|
||||
db.add(models.AppSetting(key=CLAIM_KEY, value={}, updated_at=now))
|
||||
db.commit() # the insert is the claim
|
||||
return True
|
||||
except IntegrityError:
|
||||
db.rollback() # another worker inserted first: it won
|
||||
return False
|
||||
db.rollback() # end the read; the UPDATE starts fresh
|
||||
result = db.execute(
|
||||
update(models.AppSetting)
|
||||
.where(models.AppSetting.key == CLAIM_KEY, models.AppSetting.updated_at <= cutoff)
|
||||
.values(updated_at=now)
|
||||
)
|
||||
db.commit()
|
||||
return result.rowcount == 1
|
||||
|
||||
|
||||
def run_if_due(session_factory: Callable[[], Session],
|
||||
fetch: Optional[Callable[[], "list[OktaUser]"]] = None,
|
||||
now: Optional[datetime] = None) -> Optional[SyncResult]:
|
||||
"""One timer tick: claim the cycle, and if it is ours, run the sync. Returns
|
||||
the SyncResult, or None when the cycle was not ours (or could not be claimed).
|
||||
Nothing here can turn a failure into a change: run_sync() owns that rule, and
|
||||
anything that goes wrong around it is logged and ends the tick."""
|
||||
try:
|
||||
with session_factory() as db:
|
||||
if not claim(db, interval_seconds(), now=now):
|
||||
return None
|
||||
with session_factory() as db:
|
||||
return run_sync(db, fetch=fetch)
|
||||
except Exception as exc:
|
||||
log.error("Okta sync tick failed, no account was changed: unexpected %s", type(exc).__name__)
|
||||
return None
|
||||
|
||||
|
||||
def start_scheduler(session_factory: Callable[[], Session]) -> "Optional[threading.Event]":
|
||||
"""Start the timer thread. Returns a stop Event (set it to end the thread), or
|
||||
None when the sync is off because OKTA_API_TOKEN or the org URL is missing.
|
||||
Logs one line either way, so an operator can see it in `docker compose logs api`."""
|
||||
log.info(describe())
|
||||
if not is_configured():
|
||||
return None
|
||||
stop = threading.Event()
|
||||
|
||||
def loop():
|
||||
if stop.wait(START_DELAY_SECONDS):
|
||||
return
|
||||
while not stop.is_set():
|
||||
run_if_due(session_factory)
|
||||
if stop.wait(TICK_SECONDS):
|
||||
return
|
||||
|
||||
threading.Thread(target=loop, name="okta-sync", daemon=True).start()
|
||||
log.info("Okta sync scheduled: every %d seconds (checked each %d s by every worker; "
|
||||
"one wins each cycle)", interval_seconds(), TICK_SECONDS)
|
||||
return stop
|
||||
|
||||
Reference in New Issue
Block a user