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
7 changes: 6 additions & 1 deletion docs/MODULES.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ Register exactly one `Module` in `init()`:
- `Secrets(c)` — names of every secret this module's config references (so the UI can show 已设置).

Rollback (failed/unconfirmed apply, `mr rollback`) restores files, restarts their services and
reconciles the default runlevel with the restored config (`reconcileRunlevel`). From the snapshot until the
reconciles the default runlevel with the restored config (`reconcileRunlevel`). Every apply records a revision
(`history.go`): `<snapshot>.json` next to its snapshot with rev, time, origin, comment, the config-level diff
(from `gen/applied.yaml` + `gen/applied-secrets`, bookkeeping files the plan writes and a rollback restores; secrets
only as "(changed)") and the result (applying → applied | pending → confirmed | rolled back: why); `mr rollback N`
and the web UI's 回滚到此前 apply the config from before change N as a new change (the web UI password stays the
current one). From the snapshot until the
change is accepted (the apply ends without `--confirm`, or `mr confirm`) the marker
`/etc/mini-router/confirm-pending` (JSON: snapshot, state applying | pending | reverting, deadline, origin) is on
flash: if the router goes down in that window, the next boot restores the snapshot before any service starts
Expand Down
5 changes: 3 additions & 2 deletions docs/modules/sys.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ system:
ntp_server: false # also answer NTP (udp/123) — only the LAN zone gets through the firewall
sysctl: {net.ipv4.tcp_congestion_control: bbr} # added to / overriding 90-mini-router.conf
zram: true # zram swap (1/4 of RAM, zstd); also MGLRU min_ttl_ms=1000: OOM kill instead of thrashing
history: 20 # config snapshots / change records kept (5-200)

services:
tailscale: {enabled: true, port: 41641} # tailscaled --port; the same UDP port is opened on the WANs
Expand Down Expand Up @@ -152,7 +153,7 @@ load; output and exit code go to `/run/mini-router/fw-run.{log,rc}`.
directories) rejects the whole archive.
2. Secrets: the backup's are laid over the current ones; `webui_password` always stays the current one.
3. List files that differ are saved first as `<time>-restore-lists.tar.gz` in the snapshot history (the
core snapshot format, so 备份与回滚 can also roll back to it), then written.
core snapshot format, so 变更历史 can also roll back to it), then written.
4. The candidate config is validated and rendered; on any error the list files go back and nothing else
has changed.
5. The candidate is written where the web UI's apply writes it and the core `apply-job` runs:
Expand Down Expand Up @@ -217,7 +218,7 @@ mr sys keys # authorized_keys: mana
- 固件升级:选镜像 → 浏览器算 SHA-256 → 分块上传(有进度条)→ 确认后刷写,路由器自动重启。
镜像被平台脚本拒绝时显示原因。当前构建没有升级脚本时显示“当前构建不支持”。
- 恢复出厂设置:确认两次(第二次要输入 RESET)。
- 每次应用前的自动快照仍在“备份与回滚”页面。
- 每次应用都记在“变更历史”页面(来源、备注、结果、改了什么),可以对比或回滚到任意一次之前。
- **日志**:按级别(错误及以上、警告及以上……)、服务(下拉里有每个服务的行数)、关键字过滤,
可选 300–5000 行、自动刷新。时间是路由器时区。
- **网络诊断**:Ping / Ping6 / Traceroute / Traceroute6 / nslookup,有几个常用目标的快捷按钮。
Expand Down
133 changes: 108 additions & 25 deletions mr/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,19 @@ import (
)

const (
RunDir = "/run/mini-router"
SessionDir = RunDir + "/sessions"
JobFile = RunDir + "/job.json"
JobLog = RunDir + "/job.log"
RunDir = "/run/mini-router"
SessionDir = RunDir + "/sessions"
JobFile = RunDir + "/job.json"
JobLog = RunDir + "/job.log"
sessionTTL = 12 * time.Hour
pwSecretKey = "webui_password"
pbkdfIter = 120000
)

// the apply job's input (variables so tests can point them elsewhere)
var (
CandidateYAML = RunDir + "/candidate.yaml"
CandidateSec = RunDir + "/candidate-secrets.yaml"
sessionTTL = 12 * time.Hour
pwSecretKey = "webui_password"
pbkdfIter = 120000
)

type apiReq struct {
Expand Down Expand Up @@ -154,6 +158,8 @@ func handleAPI(r apiReq) apiResp {
return apiResp{body: map[string]any{"ok": true}}
case "history":
return apiHistory()
case "history.diff":
return apiHistoryDiff(r)
case "rollback":
return apiRollback(r)
case "logs":
Expand Down Expand Up @@ -413,6 +419,7 @@ type configSubmit struct {
Config json.RawMessage `json:"config"`
Secrets map[string]string `json:"secrets"` // only keys being changed; empty value = keep
Confirm int `json:"confirm"`
Comment string `json:"comment"` // for the history
}

// candidate builds the would-be config + secrets without touching the live files.
Expand Down Expand Up @@ -463,7 +470,12 @@ func apiValidate(r apiReq) apiResp {
if err != nil {
return apiResp{body: map[string]any{"errors": []string{err.Error()}}}
}
return apiResp{body: map[string]any{"errors": []string{}, "plan": p.String(), "empty": p.Empty()}}
changes, known := changesSinceApplied(c)
if changes == nil {
changes = []string{}
}
return apiResp{body: map[string]any{"errors": []string{}, "plan": p.String(), "empty": p.Empty(),
"changes": changes, "changes_known": known}}
}

type jobState struct {
Expand All @@ -472,7 +484,9 @@ type jobState struct {
Ended int64 `json:"ended,omitempty"`
Output string `json:"output"`
Confirm int `json:"confirm"`
Via string `json:"via,omitempty"` // origin recorded in the pending marker (web UI | restore)
Via string `json:"via,omitempty"` // origin recorded in the pending marker (web UI | restore | rollback)
From string `json:"from,omitempty"`
Comment string `json:"comment,omitempty"`
}

func apiApply(r apiReq) apiResp {
Expand All @@ -495,14 +509,19 @@ func apiApply(r apiReq) apiResp {
if confirmSecs <= 0 {
confirmSecs = 120
}
var in configSubmit
json.Unmarshal(r.body, &in)
if len(in.Comment) > 200 || strings.ContainsAny(in.Comment, "\r\n") {
return errResp(400, "comment: one line, at most 200 characters")
}
os.MkdirAll(RunDir, 0700)
if err := writeAtomic(CandidateYAML, uiConfigYAML(y, c), 0600); err != nil {
return errResp(500, "%v", err)
}
if err := writeSecrets(CandidateSec, sec); err != nil {
return errResp(500, "%v", err)
}
writeJob(jobState{State: "running", Started: time.Now().Unix(), Confirm: confirmSecs, Via: "web UI"})
writeJob(jobState{State: "running", Started: time.Now().Unix(), Confirm: confirmSecs, Via: "web UI", From: r.remote, Comment: in.Comment})
self, _ := os.Executable()
startDetached(self, "apply-job", strconv.Itoa(confirmSecs))
return apiResp{body: map[string]any{"ok": true, "confirm": confirmSecs}}
Expand All @@ -512,11 +531,12 @@ func apiApply(r apiReq) apiResp {
func runApplyJob(confirmSecs int) error {
logFile, _ := os.OpenFile(JobLog, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
os.Stdout, os.Stderr = logFile, logFile
via := readJob().Via
if via == "" {
via = "web UI"
j0 := readJob()
o := applyOpts{Via: j0.Via, From: j0.From, Comment: j0.Comment}
if o.Via == "" {
o.Via = "web UI"
}
err := ApplyCandidate(CandidateYAML, CandidateSec, confirmSecs, via)
err := ApplyCandidate(CandidateYAML, CandidateSec, confirmSecs, o)
logFile.Close()
out, _ := os.ReadFile(JobLog)
j := readJob()
Expand Down Expand Up @@ -565,31 +585,94 @@ func pendingView() map[string]any {
return map[string]any{"state": p.State, "via": p.Via, "left": p.left()}
}

// apiHistory: the revisions, newest first, and snapshots older than revisions (no record).
func apiHistory() apiResp {
rs := readRevisions()
known := map[string]bool{}
for _, r := range rs {
known[r.Snapshot] = true
}
for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
rs[i], rs[j] = rs[j], rs[i]
}
ents, _ := os.ReadDir(HistoryDir)
var names []string
var older []string
for _, e := range ents {
if strings.HasSuffix(e.Name(), ".tar.gz") {
names = append(names, e.Name())
if strings.HasSuffix(e.Name(), ".tar.gz") && !known[e.Name()] && !strings.HasSuffix(e.Name(), "-restore-lists.tar.gz") {
older = append(older, e.Name())
}
}
sort.Sort(sort.Reverse(sort.StringSlice(names)))
return apiResp{body: map[string]any{"snapshots": names}}
sort.Sort(sort.Reverse(sort.StringSlice(older)))
if rs == nil {
rs = []revision{}
}
return apiResp{body: map[string]any{"revisions": rs, "snapshots": older}}
}

type historyRef struct {
Rev int `json:"rev"`
Snapshot string `json:"snapshot"`
}

// snap resolves a revision number or a snapshot file name to the snapshot's path.
func (h historyRef) snap() (string, error) {
if h.Rev > 0 {
return revSnapshot(h.Rev)
}
name := filepath.Base(h.Snapshot)
if !strings.HasSuffix(name, ".tar.gz") {
return "", errors.New("bad snapshot")
}
return filepath.Join(HistoryDir, name), nil
}

// apiHistoryDiff: what changed from the config before a revision to the live one.
func apiHistoryDiff(r apiReq) apiResp {
var in historyRef
json.Unmarshal(r.body, &in)
snap, err := in.snap()
if err != nil {
return errResp(400, "%v", err)
}
ch, err := snapshotChanges(snap)
if err != nil {
return errResp(404, "%v", err)
}
if ch == nil {
ch = []string{}
}
return apiResp{body: map[string]any{"changes": ch}}
}

// apiRollback puts the config from before a revision back as a new change: the standard apply job
// (verify, confirm countdown, automatic rollback) with the snapshot's router.yaml and secrets.
func apiRollback(r apiReq) apiResp {
if r.method != "POST" {
return errResp(405, "POST required")
}
var in struct{ Snapshot string }
if j := readJob(); j.State == "running" {
return errResp(409, "another apply is running")
}
if err := pendingBlocks(); err != nil {
return apiResp{status: 409, body: map[string]any{"error": err.Error(), "pending": pendingView()}}
}
var in historyRef
json.Unmarshal(r.body, &in)
name := filepath.Base(in.Snapshot)
if !strings.HasSuffix(name, ".tar.gz") {
return errResp(400, "bad snapshot")
snap, err := in.snap()
if err != nil {
return errResp(400, "%v", err)
}
if err := stageSnapshot(snap); err != nil {
return errResp(404, "%v", err)
}
comment := "back to before " + filepath.Base(snap)
if in.Rev > 0 {
comment = fmt.Sprintf("back to before #%d", in.Rev)
}
writeJob(jobState{State: "running", Started: time.Now().Unix(), Confirm: 120, Via: "rollback", From: r.remote, Comment: comment})
self, _ := os.Executable()
startDetached(self, "rollback", name)
return apiResp{body: map[string]any{"ok": true}}
startDetached(self, "apply-job", "120")
return apiResp{body: map[string]any{"ok": true, "confirm": 120}}
}

func apiLogs() apiResp {
Expand Down
Loading
Loading