Skip to main content
CRUCIBLE
Legacy Reference Archive: This 44-chapter book reference has been distilled into Academy A01 (8 Executable Modules) with Tier-Adaptive Productive Failure, Kore/Puck voice, and live Firecracker labs.
Open Academy A01 →
COURSE 0 · SERVER BUILDING & LIFECYCLE MASTERY

Zero-to-Production Linux, Containers, Networking & Recovery

PROGRESS: 0 / 72 (0%)0/44L · 0Q · 0VM
TUT 04 · WORKED TUTORIALS (START HERE) · 1,468 WORDS (8 MIN)

Install, configure and prove monitoring

There are two paths. First run the fully automated isolated delivery proof, which supplies its own API, worker, Prometheus, Alertmanager and receiver.

FULL WAR-ROOM →
INTERACTIVE OBSERVABILITY · CLICK ANY STAGE TO TEST

Golden Signals Loop: /metrics -> Prometheus -> Alert Rules -> Runbook

How production teams catch silent degradation before customers tweet about it.

scrapesfirespagesApp /metricsLatency · Errors · PoolsPrometheus TSDB15s Scrape IntervalAlertmanagerDedup · Route · SilenceVerified RecoveryObserve -> Fix -> Prove
SELECTED LAYER · APP /METRICS
Exposes real-time counters and histograms (request p99, 5xx rate, PgBouncer cl_waiting, open FDs).
Common failure: High-cardinality labels (like user_id) exploding Prometheus memory usage.
$ curl -s http://127.0.0.1:8000/health

Purpose: detect a stalled queue and prove an alert receiver receives both firing and resolved notifications. Prerequisites: complete the canonical workstation setup, install the example's locked virtual environment, and understand the distinction between API acceptance and worker completion. Environment: your private Crucible Firecracker Linux VM (amd64/arm64 Linux) and your Crucible VM workspace (~/playground); every listener below binds loopback. This is a private learning installation, not a publicly exposed monitoring service.

There are two paths. First run the fully automated isolated delivery proof, which supplies its own API, worker, Prometheus, Alertmanager and receiver. Then connect those tools to the persistent canonical Compose application to learn the actual configuration. The automated proof does not stop or change an existing worker or system service.

1. Obtain the native executables without changing system services

The supplied helper downloads the native Prometheus/promtool and Alertmanager release archives from the official Prometheus GitHub projects. It selects the matching Linux architecture (amd64/arm64) from the current host, checks the archive against that release's SHA-256 file, and writes only the expected executable files into a new private .monitoring-tools directory at your Crucible VM workspace (~/playground). It never extracts arbitrary archive paths or enables system services.

VM workspace Bash terminal:

bash
python3 promtool test rules ~/playground/server-lifecycle/alerts.test.yml install
.monitoring-tools/prometheus --version
.monitoring-tools/promtool --version
.monitoring-tools/alertmanager --version

Expected: repository/release/archive/digest records are printed, then the three binaries report versions. Exact resolved versions are retained in .monitoring-tools/versions.json. The helper intentionally refuses an existing tools directory. Inspect and reuse a successful installation; do not delete an unknown path or overwrite tools while their processes run. The checksum verifies consistency with the fetched release metadata; production software approval also needs the organization's provenance and vulnerability review.

If a prerequisite download fails, investigate network/TLS/rate-limit messages. The helper removes only the directory created by that failed attempt. It rejects unsupported OS/architecture combinations; use an appropriate learning VM rather than forcing a different binary. No administrator privilege is required to use this private installation. Alternative Linux packaging is available through the official [apt Prometheus formula](https://formulae.brew.sh/formula/prometheus); this walkthrough uses the helper so the Alertmanager path is explicit on both supported operating systems. Official release projects: [Prometheus](https://github.com/prometheus/prometheus/releases), [Alertmanager](https://github.com/prometheus/alertmanager/releases).

2. Run the isolated delivered-alert proof

VM workspace terminal, after installing the example environment:

bash
~/playground/automation-service/.venv/bin/python promtool test rules ~/playground/server-lifecycle/alerts.test.yml proof

The wrapper supplies the exact private tool paths to curl -sf http://127.0.0.1:8000/health. That script starts an isolated local application, submits work while its worker is absent, evaluates an accelerated queue-stall rule, receives a real Alertmanager firing webhook, starts its worker, and receives the resolved webhook. It also checks local TLS and route recovery. Its finally cleanup stops its owned processes and removes private temporary certificates, tokens, database and configuration.

Expected: the command exits0 and writes proof/local-operations.json. Inspect that file and require these checks to be true: prometheus_scrape_and_alertmanager_firing_delivery and worker_completion_and_resolved_delivery. Its notification_statuses includes firing and resolved. A script exit without those assertions is not an alert-delivery pass. This proof uses one-second fixture timing; the production-duration rule is checked separately in the next step.

Failure: if the proof times out, confirm all three private binaries run and that the Python command uses the supplied example virtual environment. Read the first relevant error; do not expose monitoring ports or disable token protection to repair a loopback dependency. Retry only after fixing the identified issue. The proof's SQLite fixture does not establish PostgreSQL or host-loss recovery; use the separate reference journey for that scope.

3. Prepare protected configuration for the canonical Compose application

Start the persistent example as described in the canonical walkthrough and verify http://127.0.0.1:18768/health/ready. Its .env must already contain the generated LAB_TOKEN and MONITOR_TOKEN. The latter is a separate operator capability; an ordinary tenant token does not grant metrics access.

Terminal1, enter `~/playground/automation-service` inside your Crucible VM workspace (`~/playground`). Generate a private configuration directory with exclusive creation:

bash
uv run python - <<'PY'
import json, os, shutil
from pathlib import Path
from dotenv import dotenv_values

root = Path.cwd()
values = dotenv_values(root / '.env')
token = values.get('MONITOR_TOKEN')
assert token and len(token) >= 32, 'Generate the canonical .env first'
monitor = root / '.monitoring'
monitor.mkdir(mode=0o700, exist_ok=False)
fd = os.open(monitor / 'monitor-token', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as out:
    out.write(token)
shutil.copyfile(root / '../../monitoring/alerts.yml', monitor / 'alerts.yml')
prom = {
    'global': {'scrape_interval':'15s','evaluation_interval':'15s'},
    'rule_files':[str(monitor / 'alerts.yml')],
    'scrape_configs':[{'job_name':'mastery','metrics_path':'/metrics',
        'authorization':{'credentials_file':str(monitor / 'monitor-token')},
        'static_configs':[{'targets':['127.0.0.1:18768']}]}],
    'alerting':{'alertmanagers':[{'static_configs':[{'targets':['127.0.0.1:19091']}]}]}
}
am = {
    'route':{'receiver':'local','group_by':['alertname'],'group_wait':'1s',
             'group_interval':'15s','repeat_interval':'1h'},
    'receivers':[{'name':'local','webhook_configs':[
        {'url':'http://127.0.0.1:19093/alerts','send_resolved':True}]}]
}
(monitor / 'prometheus.yml').write_text(json.dumps(prom, indent=2))
(monitor / 'alertmanager.yml').write_text(json.dumps(am, indent=2))
print('Created private monitoring files; no secrets printed')
PY
../../.monitoring-tools/promtool check config .monitoring/prometheus.yml
../../.monitoring-tools/promtool test rules ../../monitoring/alerts.test.yml

JSON is a subset of YAML, so the generated .yml files are accepted configuration. Expected: validation and rule fixtures succeed. Existing .monitoring causes an intentional refusal; inspect and reuse the files for the same lab. Configuration validation does not start a server or prove a scrape succeeded. Do not print monitor-token into screenshots or shared logs.

4. Start a local receiver, Alertmanager and Prometheus

Use three separate foreground terminals, each in the example directory. Keeping processes foreground makes their ownership and stop path explicit. Do not start operating-system services for this exercise.

Terminal1: local receiver. It records only status and alert names in the private directory:

bash
uv run python - <<'PY'
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

class Receiver(BaseHTTPRequestHandler):
    def do_POST(self):
        size = int(self.headers.get('Content-Length', '0'))
        if self.path != '/alerts' or not 0 < size <= 65536:
            self.send_error(400)
            return
        try:
            body = json.loads(self.rfile.read(size))
            record = {'status':body['status'], 'alerts':[
                item.get('labels', {}).get('alertname') for item in body['alerts']]}
        except (ValueError, KeyError, TypeError):
            self.send_error(400)
            return
        with Path('.monitoring/notifications.jsonl').open('a') as out:
            out.write(json.dumps(record) + '\n')
        print(json.dumps(record), flush=True)
        self.send_response(200)
        self.end_headers()
    def log_message(self, *args):
        pass

server = HTTPServer(('127.0.0.1', 19093), Receiver)
try:
    server.serve_forever()
except KeyboardInterrupt:
    pass
finally:
    server.server_close()
PY

Terminal2: Alertmanager:

bash
../../.monitoring-tools/alertmanager \
  --config.file=.monitoring/alertmanager.yml \
  --storage.path=.monitoring/alertmanager-data \
  --web.listen-address=127.0.0.1:19091 \
  --cluster.listen-address=

Terminal3: Prometheus:

bash
../../.monitoring-tools/prometheus \
  --config.file=.monitoring/prometheus.yml \
  --storage.tsdb.path=.monitoring/prometheus-data \
  --storage.tsdb.retention.time=1d \
  --web.listen-address=127.0.0.1:19090

Expected: both servers stay running. The receiver stays waiting for POST requests. If any port is already in use, inspect the existing owner; do not terminate an unrelated service. For this fixed-port lesson, stop your previous owned lab instance or choose and consistently update a reviewed alternate port across all configurations.

5. Verify the actual scrape, then exercise a fault

Terminal4 in the example directory:

bash
uv run python - <<'PY'
import time, httpx
from dotenv import dotenv_values
values = dotenv_values('.env')
with httpx.Client(timeout=3) as c:
    assert c.get('http://127.0.0.1:18768/metrics').status_code == 401
    assert c.get('http://127.0.0.1:18768/metrics', headers={
        'Authorization':'Bearer '+values['MONITOR_TOKEN']}).status_code == 200
    for _ in range(10):
        result = c.get('http://127.0.0.1:19090/api/v1/query', params={
            'query':'up{job="mastery"}'}).json()['data']['result']
        if result and result[0]['value'][1] == '1':
            break
        time.sleep(2)
    else:
        raise SystemExit('Scrape did not become healthy; inspect target and credential')
print('Unauthorized metrics denied; configured scrape is healthy')
PY

Now deliberately stop only this lab worker and submit synthetic work:

bash
docker compose stop worker
uv run python - <<'PY'
import uuid, httpx
from dotenv import dotenv_values
values = dotenv_values('.env')
r = httpx.post('http://127.0.0.1:18768/jobs', timeout=5,
    headers={'Authorization':'Bearer '+values['LAB_TOKEN'],
             'Idempotency-Key':'monitor-'+str(uuid.uuid4())},
    json={'text':'synthetic monitoring exercise'})
r.raise_for_status()
print('Queued job:', r.json()['id'])
PY

The supplied QueueStalled rule requires oldest queued age above120 seconds continuously for another2 minutes, plus scrape/evaluation/routing delay. Allow about five minutes. Do not submit many jobs to speed it up. The receiver should print a firing record containing QueueStalled; the Prometheus UI at http://127.0.0.1:19090/alerts separately shows rule state. A firing rule without a receiver record has not proved delivery.

Recover the worker and observe resolution:

bash
docker compose start worker

Expected: queued work completes and the receiver later records resolved. Inspect .monitoring/notifications.jsonl and retain redacted firing/resolved records with fault/recovery timestamps. If no alert arrives, inspect scrape health, queue age, rule evaluation, Alertmanager readiness/routing and receiver reachability in order. A worker that restarted itself before the configured duration may correctly prevent the alert from firing; keep the fault controlled and explain the threshold.

6. Recovery, cleanup and independent assessment

If this exercise is interrupted, first restore the canonical worker with docker compose start worker and verify the original job completes. Then stop the three owned foreground monitoring processes with Ctrl-C. Do not use broad pkill/killall commands. Persistent Compose data and .monitoring files remain until an explicit retention decision; ordinary docker compose down preserves named database volumes.

The private tool directory and monitoring data are disposable only after you verify their exact paths, no owned process uses them and required evidence is retained. Their removal is separate from service recovery. Do not copy .env, monitor-token, monitoring storage or downloaded binaries into the shareable course bundle.

Pass criteria: explain the metrics credential boundary; demonstrate a healthy scrape; cause one controlled user-relevant fault; show both delivered firing and resolved records; restore the worker; and stop only your monitoring processes. Repeat with a different synthetic request and diagnose one incorrect scrape target or credential. For production, replace the local receiver with an approved authenticated notification destination and test its routing/escalation on the actual target. This local lesson does not establish remote host, database, backup-age or paging-system coverage.

ACTIVE-RECALL MASTERY CHECKPOINT · TUT 04

Lock in what you just learned (3 quick questions)

PASS 2/3 FOR +30 XP
Q1.Why run promtool test rules against synthetic time-series fixtures before deploying Prometheus alerts?
Q2.Why prefer user-facing symptom alerts (sustained 5xx rate / high p99 latency) over single-second CPU spike pages?
Q3.How do you verify a monitoring pipeline end-to-end before trusting it for production?
Answered 0 / 3