Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
163 changes: 6 additions & 157 deletions .github/workflows/scheduler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,122 +33,7 @@ jobs:

- name: Evaluate schedule and decide whether to fetch
id: schedule
shell: python
run: |
import json
import os
import random
from datetime import datetime, timezone
from pathlib import Path
from zoneinfo import ZoneInfo

BERLIN = ZoneInfo("Europe/Berlin")

now_utc = datetime.now(timezone.utc)
now = now_utc.astimezone(BERLIN) # schedule logic runs in Berlin time
today_str = now.strftime("%Y-%m-%d") # "today" = Berlin calendar date
current_hour = now.hour # hour 0-23 in Berlin time
state_path = Path("state/today.json")

state = {}
if state_path.exists():
try:
state = json.loads(state_path.read_text())
except Exception:
state = {}

# New day — generate a fresh random schedule
if state.get("date") != today_str:
target_runs = random.randint(1, 10)

# Pick target_runs unique hours from the 24-hour day
scheduled_hours = sorted(random.sample(range(0, 24), min(target_runs, 24)))

# Carry over last_fetch_end from the previous day so the time window
# correctly spans the overnight gap on the first run of the new day.
prev_last_fetch_end = state.get("last_fetch_end")

state = {
"date": today_str,
"target_runs": target_runs,
"completed_runs": 0,
"scheduled_hours": scheduled_hours,
"completed_hours": [],
"last_fetch_end": prev_last_fetch_end,
"last_run_failed": False,
}

state_path.parent.mkdir(exist_ok=True)
state_path.write_text(json.dumps(state, indent=2))

print(f"New day (Berlin) — scheduled {target_runs} runs at hours: {scheduled_hours}")

# workflow_dispatch always fetches (bypass schedule gate)
is_manual = os.environ.get("GITHUB_EVENT_NAME") == "workflow_dispatch"

# Retry logic: if the last run failed, attempt again this tick regardless
# of the schedule so we don't silently lose a run.
last_run_failed = state.get("last_run_failed", False)

# Fire if:
# - manual dispatch, OR
# - last run failed (retry), OR
# - any scheduled hour up to and including current_hour has not yet
# been completed — this catches late cron ticks (e.g. hour 8 run
# fires at 08:47 or even 09:03 and would otherwise be skipped).
completed_hours = set(state.get("completed_hours", []))
scheduled_hours = state.get("scheduled_hours", [])
overdue_hours = [
h for h in scheduled_hours
if h <= current_hour and h not in completed_hours
]

should_fetch = is_manual or last_run_failed or (
bool(overdue_hours)
and state.get("completed_runs", 0) < state.get("target_runs", 0)
)

if is_manual:
print("Manual dispatch — bypassing schedule gate, fetch forced")
elif last_run_failed:
print(f"Last run failed — retrying this tick (Berlin hour={current_hour})")
elif overdue_hours:
print(f"Overdue scheduled hours detected: {overdue_hours} — triggering fetch")

# Determine time window for the fetch.
# Always start from last_fetch_end regardless of day boundary so gaps
# (overnight, missed runs) are fully covered.
if should_fetch:
if state.get("last_fetch_end"):
window_start = state["last_fetch_end"]
else:
from datetime import timedelta
window_start = (now_utc - timedelta(hours=6)).strftime("%Y-%m-%dT%H:%M:%SZ")
window_end = now_utc.strftime("%Y-%m-%dT%H:%M:%SZ")
else:
window_start = ""
window_end = ""

# Write outputs for subsequent steps
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
f.write(f"should_fetch={'true' if should_fetch else 'false'}\n")
f.write(f"window_start={window_start}\n")
f.write(f"window_end={window_end}\n")
f.write(f"current_hour={current_hour}\n")
f.write(f"target_runs={state.get('target_runs', 0)}\n")
f.write(f"completed_runs={state.get('completed_runs', 0)}\n")
# Pass overdue_hours as a comma-separated string for the state update step
overdue_str = ",".join(str(h) for h in overdue_hours) if overdue_hours else ""
f.write(f"overdue_hours={overdue_str}\n")

if should_fetch:
print(f"Fetch triggered for Berlin hour {current_hour} — window: {window_start} → {window_end}")
else:
scheduled = state.get("scheduled_hours", [])
completed = state.get("completed_runs", 0)
target = state.get("target_runs", 0)
print(f"No fetch this hour (Berlin hour={current_hour}, scheduled={scheduled}, "
f"completed={completed}/{target})")
run: python scripts/scheduler.py evaluate

- name: Install dependencies
if: steps.schedule.outputs.should_fetch == 'true'
Expand All @@ -164,50 +49,14 @@ jobs:

- name: Update state after successful fetch
if: steps.schedule.outputs.should_fetch == 'true' && steps.fetch.outcome == 'success'
shell: python
run: |
import json
from datetime import datetime, timezone
from pathlib import Path

state_path = Path("state/today.json")
state = json.loads(state_path.read_text())

current_hour = int("${{ steps.schedule.outputs.current_hour }}")
overdue_str = "${{ steps.schedule.outputs.overdue_hours }}"
overdue_hours = [int(h) for h in overdue_str.split(",") if h.strip()]
now_str = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

state["completed_runs"] += 1
# Mark all overdue hours that triggered this run as completed
for h in overdue_hours:
if h not in state["completed_hours"]:
state["completed_hours"].append(h)
# Also mark current_hour if it was a manual/retry run
if current_hour not in state["completed_hours"]:
state["completed_hours"].append(current_hour)
state["last_fetch_end"] = now_str
state["last_run_failed"] = False

state_path.write_text(json.dumps(state, indent=2))
print(f"State updated — completed {state['completed_runs']}/{state['target_runs']} runs today")
env:
CURRENT_HOUR: ${{ steps.schedule.outputs.current_hour }}
OVERDUE_HOURS: ${{ steps.schedule.outputs.overdue_hours }}
run: python scripts/scheduler.py success

- name: Record fetch failure in state
if: steps.schedule.outputs.should_fetch == 'true' && steps.fetch.outcome == 'failure'
shell: python
run: |
import json
from pathlib import Path

state_path = Path("state/today.json")
try:
state = json.loads(state_path.read_text())
except Exception:
state = {}

state["last_run_failed"] = True
state_path.write_text(json.dumps(state, indent=2))
print("Fetch failed — last_run_failed set to True, will retry next cron tick")
run: python scripts/scheduler.py failure

- name: Commit and push
shell: bash
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Automated collector for [GreyNoise Project Swarm](https://www.greynoise.io/proje
- Output: full feed + filtered feed + high-confidence feed + enriched metadata + run logs + monthly archive
- Multi-sensor: map multiple sensors with human-readable labels; IPs corroborated by 2+ sensors flagged in metadata
- Runtime: GitHub Actions only (no self-hosted infrastructure)
- Update model: randomized 1 to 10 fetches/day via hourly scheduler checks
- Update model: randomized 1 to 10 fetches/day via hourly scheduler checks (UTC)
- Integration: direct HTTPS feed consumption by any firewall supporting external IP block lists
- Access model: private fork with PAT-based HTTP Basic Auth on the firewall (recommended)

Expand Down
20 changes: 10 additions & 10 deletions scripts/archive_month.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,17 @@
"""

import json
import os
import sys
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path

_REPO_ROOT = Path(os.environ.get("ARCHIVE_REPO_ROOT", Path(__file__).parent.parent))
FEEDS_DIR = _REPO_ROOT / "feeds"
RUNS_DIR = _REPO_ROOT / "runs"
ARCHIVE_DIR = _REPO_ROOT / "archive"


def load_json(path: Path) -> dict | list:
try:
Expand Down Expand Up @@ -134,21 +140,15 @@ def load_run_logs(runs_dir: Path) -> list:


def main() -> None:
repo_root = Path(__file__).parent.parent

feeds_dir = repo_root / "feeds"
runs_dir = repo_root / "runs"
archive_dir = repo_root / "archive"

# Determine the month being archived
now = datetime.now(timezone.utc)
month_str = now.strftime("%Y-%m")

print(f"[*] Archiving month: {month_str}")

# --- Load source files ---
filtered_metadata_path = feeds_dir / "filtered_metadata.json"
ip_metadata_path = feeds_dir / "ip_metadata.json"
filtered_metadata_path = FEEDS_DIR / "filtered_metadata.json"
ip_metadata_path = FEEDS_DIR / "ip_metadata.json"

if not filtered_metadata_path.exists():
print("[error] feeds/filtered_metadata.json not found — nothing to archive.",
Expand All @@ -162,7 +162,7 @@ def main() -> None:

filtered_metadata = load_json(filtered_metadata_path)
ip_metadata = load_json(ip_metadata_path)
run_logs = load_run_logs(runs_dir)
run_logs = load_run_logs(RUNS_DIR)

print(f" [+] Loaded {len(filtered_metadata)} filtered IPs, "
f"{len(ip_metadata)} full feed IPs, "
Expand All @@ -179,7 +179,7 @@ def main() -> None:
f"{month_runs} runs this month")

# --- Write archive ---
out_dir = archive_dir / month_str
out_dir = ARCHIVE_DIR / month_str
out_dir.mkdir(parents=True, exist_ok=True)

(out_dir / "filtered_metadata.json").write_text(
Expand Down
7 changes: 6 additions & 1 deletion scripts/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@
failure — Record a fetch failure for retry at next tick.

Environment variables:
TZ — Timezone for scheduling (default: UTC)
TZ — Timezone for scheduling (default: UTC). The provided
workflow does not set TZ, so the scheduler runs in UTC.
Power users may override this via a GitHub Actions
variable (Settings → Variables → Actions) if a different
day-boundary is required — but for most deployments UTC
is correct and requires no configuration.
GITHUB_EVENT_NAME — Set by GitHub Actions (workflow_dispatch for manual runs)
GITHUB_OUTPUT — File path for writing step outputs
"""
Expand Down
Loading
Loading