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
27 changes: 23 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ on:
push:
branches: [ main ]

defaults:
run:
working-directory: backend

jobs:
backend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: backend
steps:
- uses: actions/checkout@v7

Expand All @@ -33,3 +32,23 @@ jobs:
env:
RAILS_ENV: test
run: bin/rails db:test:prepare test

frontend:
runs-on: ubuntu-latest
defaults:
run:
working-directory: frontend
steps:
- uses: actions/checkout@v7

- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json

- run: npm ci
- name: Lint
run: npm run lint
- name: Type check and build
run: npm run build
6 changes: 4 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@
- `backend/`: Rails 8.1 API-only app (SQLite, Action Cable). The engine lives in `backend/lib/sim/`:
`world.rb` (state), `shell.rb` (command interpreter), `engine.rb` (time + objectives),
`scenarios/*.rb` (one chapter each, listed in `scenarios.rb`).
- `frontend/`: React + TypeScript (Vite).
- UI follows Royal's UI style (Geist, product-mode tokens).
- `frontend/`: React + TypeScript (Vite), xterm.js terminal. Play screen is `src/components/PlayScreen.tsx`.
- UI follows Royal's UI style rules (Geist, motion, accessibility) with this app's own "System map" theme in
`frontend/src/styles.css`. Don't reuse the helpdesk look (dark sidebar + blue pill).

## Checks before opening a pull request
- `cd backend && bin/rails test && bin/rubocop && bin/brakeman --no-pager`
- `cd frontend && npm run lint && npm run build`
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,32 @@ so you can't break anything.
| 1 | GitHub | Open your first PR | planned |
| 2 | CI | The build is red | planned |
| 3 | Deploy | Roll back a bad release| planned |
| 4 | Linux | The disk is full | playable (API) |
| 5 | Monitoring | Memory is climbing | playable (API) |
| 4 | Linux | The disk is full | playable |
| 5 | Monitoring | Memory is climbing | playable |

Each chapter can be played on its own.

## Running it

In one terminal:

```sh
cd backend
bundle install
bin/rails db:prepare
bin/rails server # API on http://localhost:3000
bin/rails test
```

In another:

```sh
cd frontend
npm install
npm run dev # open http://localhost:5173
```

Tests and checks: `cd backend && bin/rails test && bin/rubocop`, `cd frontend && npm run lint && npm run build`.

## Trying the API

```sh
Expand Down
2 changes: 1 addition & 1 deletion backend/app/controllers/api/scenarios_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module Api
class ScenariosController < ApplicationController
def index
render json: Sim::Scenario.all.map { |s|
{ key: s.key, title: s.title, topic: s.topic, chapter: s.chapter, summary: s.summary }
{ key: s.key, title: s.title, topic: s.topic, chapter: s.chapter, summary: s.summary, focus_metric: s.focus_metric }
}
end
end
Expand Down
9 changes: 7 additions & 2 deletions backend/app/presenters/run_presenter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ def full
status: @run.status,
scenario: {
key: scenario.key, title: scenario.title, topic: scenario.topic,
chapter: scenario.chapter, summary: scenario.summary, briefing: scenario.briefing
chapter: scenario.chapter, summary: scenario.summary, briefing: scenario.briefing,
focus_metric: scenario.focus_metric
}
}.merge(live)
end
Expand All @@ -41,7 +42,11 @@ def live
objectives: @engine.objectives,
alerts: @world.alerts,
metrics: @world.data["metrics"],
services: services
services: services,
current_host: @world.current_host,
hint: @engine.scenario.hint_for(@world),
map: @engine.scenario.map(@world),
logs: @engine.scenario.logs(@world)
}
end

Expand Down
6 changes: 5 additions & 1 deletion backend/lib/sim/scenario.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,17 @@ class << self
def all = Scenarios::ALL.sort_by(&:chapter)
def find(key) = all.find { |s| s.key == key } || raise(KeyError, "Unknown scenario #{key}")

attr_accessor :key, :title, :chapter, :topic, :summary, :briefing
attr_accessor :key, :title, :chapter, :topic, :summary, :briefing, :focus_metric
end

def key = self.class.key

def objectives = []

# The live picture for the play screen. Scenarios set in the shop share one.
def map(world) = ShopWorld.map(world)
def logs(world) = ShopWorld.logs(world)

def build_world
raise NotImplementedError
end
Expand Down
1 change: 1 addition & 0 deletions backend/lib/sim/scenarios/linux_disk_full.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class LinuxDiskFull < Scenario
self.topic = "Linux"
self.title = "The disk is full"
self.summary = "SSH into the server, find what filled the disk, and bring the crashed app back."
self.focus_metric = "disk"
self.briefing = <<~TEXT
Your phone buzzes: "shop.example is showing 502 errors!"
You're on call. The shop runs on a server called web-01.
Expand Down
7 changes: 6 additions & 1 deletion backend/lib/sim/scenarios/monitoring_memory_leak.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class MonitoringMemoryLeak < Scenario
self.topic = "Monitoring"
self.title = "Memory is climbing"
self.summary = "A memory alert fires. Use the dashboard and the server to trace the cause and fix it for good."
self.focus_metric = "memory"
self.briefing = <<~TEXT
It's a quiet afternoon. The site is up and the dashboard looks calm.
Keep an eye on the memory graph for web-01. Monitoring will page you
Expand All @@ -21,7 +22,8 @@ class MonitoringMemoryLeak < Scenario
# Once paged, the leak slows down so a beginner has time to investigate
# before the kernel starts killing processes.
LEAK_AFTER_ALERT = 40
LEAK_STARTS_AT = 2
LEAK_STARTS_AT = 1
HEAD_START_MB = 600
ALERT_AT = 85
RECOVERED_BELOW = 70
OOM_AT = 98
Expand All @@ -33,6 +35,9 @@ def build_world
data["session"] = { "host" => "laptop", "user" => "dev", "cwd" => "/home/dev" }
world = World.new(data)
ShopWorld.boot(self, world, "postgresql", "nginx", "shop-web", WORKER)
# The leak has been going for a while before the player arrives, so
# the alert fires within a minute or so of real time.
world.service_processes(WORKER, WEB).first["mem_mb"] += HEAD_START_MB
data
end

Expand Down
48 changes: 48 additions & 0 deletions backend/lib/sim/shop_world.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,54 @@ def boot(scenario, world, *names, host: "web-01")
names.each { |name| scenario.start_service(world, name, host: host) }
end

MAP_NODES = [
{ "id" => "laptop", "label" => "Your laptop", "kind" => "dev", "inspect" => "cat ~/on-call.md" },
{ "id" => "nginx", "label" => "nginx", "kind" => "front door", "service" => "nginx" },
{ "id" => "shop-web", "label" => "shop-web", "kind" => "Rails app", "service" => "shop-web" },
{ "id" => "shop-worker", "label" => "shop-worker", "kind" => "background jobs", "service" => "shop-worker" },
{ "id" => "postgresql", "label" => "postgresql", "kind" => "database", "service" => "postgresql" },
{ "id" => "disk", "label" => "Disk /", "kind" => "storage", "inspect" => "df -h" }
].freeze
MAP_EDGES = [ %w[laptop nginx], %w[nginx shop-web], %w[shop-web postgresql], %w[shop-worker postgresql],
%w[shop-web shop-worker], %w[shop-web disk] ].freeze

# What the play screen draws: the shop's parts, how they connect, and
# which one is in trouble right now. Status comes straight from the world.
def map(world)
nodes = MAP_NODES.map do |node|
node.merge(map_status(world, node)).merge("host" => node["id"] == "laptop" ? "laptop" : "web-01")
end
{ "nodes" => nodes, "edges" => MAP_EDGES }
end

def map_status(world, node)
if node["id"] == "laptop"
on_server = world.current_host == "web-01"
return { "status" => "ok", "detail" => on_server ? "connected over ssh" : "you are here" }
end
if node["id"] == "disk"
pct = world.disk_percent("web-01")
return { "status" => pct >= 90 ? "bad" : pct >= 80 ? "warn" : "ok", "detail" => "#{pct}% used", "level" => pct }
end

svc = world.service(node["service"], "web-01")
mem = world.service_processes(node["service"], "web-01").sum { |p| p["mem_mb"] }.round
level = (mem * 100.0 / world.host("web-01")["memory_total_mb"]).round
status, detail =
if svc["state"] != "active" then [ "bad", svc["state"] == "failed" ? "crashed" : "stopped" ]
elsif level >= 40 then [ "warn", "#{format_mb(mem)} · high memory" ]
else [ "ok", "running · #{format_mb(mem)}" ]
end
{ "status" => status, "detail" => detail, "level" => level, "inspect" => "systemctl status #{node['service']}" }
end

def format_mb(mb) = mb >= 1024 ? "#{format('%.2f', mb / 1024.0)} GB" : "#{mb} MB"

# Recent journal lines per service, for the Logs tab.
def logs(world)
world.services("web-01").to_h { |name, svc| [ name, Array(svc["journal"]).last(40) ] }
end

# Shared HTTP behaviour: the site is up when nginx and shop-web are running.
def http(world, url)
return nil unless url.match?(%r{\A(https?://)?(shop\.example|localhost|127\.0\.0\.1|web-01)(:\d+)?(/.*)?\z})
Expand Down
2 changes: 1 addition & 1 deletion backend/test/lib/sim/monitoring_memory_leak_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def wait_for_alert
start = @world.memory_percent("web-01")
wait_for_alert
assert_operator @world.memory_percent("web-01"), :>=, 85
assert_operator start, :<, 60
assert_operator start, :<, 70
assert_equal "HighMemoryUsage", @world.firing_alerts.first["id"]
end

Expand Down
34 changes: 34 additions & 0 deletions backend/test/lib/sim/shop_map_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
require "test_helper"

class Sim::ShopMapTest < ActiveSupport::TestCase
def node(engine, id) = engine.scenario.map(engine.world)["nodes"].find { |n| n["id"] == id }

test "the linux chapter shows a crashed app and a full disk" do
engine = Sim::Engine.start("linux-disk-full")
assert_equal "bad", node(engine, "shop-web")["status"]
assert_equal "bad", node(engine, "disk")["status"]
assert_equal "ok", node(engine, "nginx")["status"]
assert_equal "systemctl status shop-web", node(engine, "shop-web")["inspect"]
end

test "the monitoring chapter makes the worker glow as it leaks" do
engine = Sim::Engine.start("monitoring-memory-leak")
assert_equal "ok", node(engine, "shop-worker")["status"]
10.times { engine.tick }
assert_equal "warn", node(engine, "shop-worker")["status"]
assert_match "high memory", node(engine, "shop-worker")["detail"]
end

test "the laptop node follows the ssh session" do
engine = Sim::Engine.start("linux-disk-full")
assert_equal "you are here", node(engine, "laptop")["detail"]
engine.execute("ssh web-01")
assert_equal "connected over ssh", node(engine, "laptop")["detail"]
end

test "every edge points at a real node" do
map = Sim::Engine.start("linux-disk-full").then { |e| e.scenario.map(e.world) }
ids = map["nodes"].map { |n| n["id"] }
assert map["edges"].flatten.all? { |id| ids.include?(id) }
end
end
24 changes: 24 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
8 changes: 8 additions & 0 deletions frontend/.oxlintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
17 changes: 17 additions & 0 deletions frontend/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Learn DevOps by fixing a simulated production system in your browser." />
<title>DevOps Simulator</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500;600&display=swap" rel="stylesheet" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
Loading
Loading