1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package main

import (
	"bufio"
	"database/sql"
	"fmt"
	"os"
	"os/exec"
	"sort"
	"strconv"
	"strings"
	"text/tabwriter"
	"time"
)

type historyRow struct {
	id          int64
	machine     string
	startedAt   time.Time
	mode        string
	commit      sql.NullString
	dirty       sql.NullBool
	outPath     sql.NullString
	closureSize sql.NullInt64
	status      string
	failedPhase sql.NullString
	totalMs     sql.NullInt64
	phases      map[string]time.Duration
}

// runHistory prints recent deploys, newest last, together with what each
// machine still has of them right now.
func runHistory(opts historyOptions) error {
	db, err := openDB()
	if err != nil {
		return err
	}
	defer db.Close()

	rows, err := loadHistory(db, opts)
	if err != nil {
		return err
	}
	if len(rows) == 0 {
		fmt.Fprintln(os.Stderr, "no deploys recorded yet")
		return nil
	}

	// Ask each machine once, about all of its paths together.
	outsByMachine := map[string][]string{}
	for _, r := range rows {
		if r.outPath.Valid {
			outsByMachine[r.machine] = append(outsByMachine[r.machine], r.outPath.String)
		}
	}
	states := map[string]*machineState{}
	for machine, outs := range outsByMachine {
		st, err := queryMachine(newTarget(machine), outs)
		if err != nil {
			warnf("cannot ask %s what it still has: %v", machine, err)
			continue
		}
		states[machine] = st
	}

	w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
	fmt.Fprintln(w, "#\twhen\tmachine\tmode\tstatus\ttotal\teval\tbuild\tcopy\tswitch\tsize\tcommit\tstore\tgen")
	for _, r := range rows {
		store, gen := "–", "–"
		if r.outPath.Valid {
			if st, ok := states[r.machine]; ok {
				store, gen = st.describe(r.outPath.String)
			} else {
				store, gen = "?", "?"
			}
		}
		fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
			r.id,
			r.startedAt.Local().Format("2006-01-02 15:04"),
			r.machine,
			r.mode,
			r.statusText(),
			msText(r.totalMs),
			r.phaseText("eval"),
			r.phaseText("build"),
			r.phaseText("copy"),
			r.phaseText("switch"),
			sizeText(r.closureSize),
			shortCommit(r.commit, r.dirty),
			store,
			gen,
		)
	}
	return w.Flush()
}

func loadHistory(db *sql.DB, opts historyOptions) ([]*historyRow, error) {
	query := `SELECT id, machine, started_at, mode, git_commit, git_dirty, out_path,
	                 closure_size, status, failed_phase, total_ms
	          FROM deploys`
	var args []any
	if opts.machine != "" {
		query += ` WHERE machine = ?`
		args = append(args, opts.machine)
	}
	// The newest count, listed oldest first: the latest deploy is the last
	// line, where a terminal leaves the eye and where `| tail` finds it.
	query = `SELECT * FROM (` + query + ` ORDER BY id DESC LIMIT ?) ORDER BY id`
	args = append(args, opts.limit)

	rs, err := db.Query(query, args...)
	if err != nil {
		return nil, err
	}
	defer rs.Close()

	var rows []*historyRow
	byID := map[int64]*historyRow{}
	for rs.Next() {
		r := &historyRow{phases: map[string]time.Duration{}}
		var started string
		if err := rs.Scan(&r.id, &r.machine, &started, &r.mode, &r.commit, &r.dirty,
			&r.outPath, &r.closureSize, &r.status, &r.failedPhase, &r.totalMs); err != nil {
			return nil, err
		}
		r.startedAt, err = time.Parse(time.RFC3339, started)
		if err != nil {
			return nil, fmt.Errorf("deploy %d: %w", r.id, err)
		}
		rows = append(rows, r)
		byID[r.id] = r
	}
	if err := rs.Err(); err != nil {
		return nil, err
	}
	if len(rows) == 0 {
		return nil, nil
	}

	ids := make([]any, 0, len(rows))
	for _, r := range rows {
		ids = append(ids, r.id)
	}
	ps, err := db.Query(
		`SELECT deploy_id, phase, duration_ms FROM phases WHERE deploy_id IN (`+placeholders(len(ids))+`)`,
		ids...)
	if err != nil {
		return nil, err
	}
	defer ps.Close()
	for ps.Next() {
		var id, ms int64
		var phase string
		if err := ps.Scan(&id, &phase, &ms); err != nil {
			return nil, err
		}
		byID[id].phases[phase] = time.Duration(ms) * time.Millisecond
	}
	return rows, ps.Err()
}

func (r *historyRow) statusText() string {
	switch r.status {
	case "failed":
		if r.failedPhase.Valid {
			return "failed@" + r.failedPhase.String
		}
		return "failed"
	case "running":
		// Either still going in another terminal, or it died without being
		// able to say so.
		return "unfinished"
	default:
		return r.status
	}
}

func (r *historyRow) phaseText(name string) string {
	d, ok := r.phases[name]
	if !ok {
		return "–"
	}
	return fmtDuration(d)
}

func msText(ms sql.NullInt64) string {
	if !ms.Valid {
		return "–"
	}
	return fmtDuration(time.Duration(ms.Int64) * time.Millisecond)
}

func sizeText(b sql.NullInt64) string {
	if !b.Valid {
		return "–"
	}
	return fmtSize(b.Int64)
}

// machineState is what a machine has of the system closures we asked about.
type machineState struct {
	// current is what the machine is running: /run/current-system.
	current string
	// generations maps a store path to the system profile generations that
	// point at it. A generation keeps its closure alive and is what you can
	// roll back to.
	generations map[string][]int
	// invalid holds the asked-about paths that are not in the store (any
	// more): never copied there, or garbage collected since.
	invalid map[string]bool
}

// describe renders the store and gen columns for one out path.
func (st *machineState) describe(out string) (store, gen string) {
	store = "✓"
	if st.invalid[out] {
		store = "✗"
	}
	gens := st.generations[out]
	switch {
	case len(gens) == 0:
		gen = "–"
	default:
		// Several generations can point at the same closure (a redeploy of
		// an unchanged system); the newest is the interesting one.
		gen = strconv.Itoa(gens[len(gens)-1])
	}
	if out == st.current {
		gen += " (current)"
	}
	return store, gen
}

// stateScript prints what the machine has, one fact per line:
//
//	current <path>
//	gen <n> <path>
//	invalid <path>
//
// It is fed to sh on stdin with the out paths as arguments, the same way
// locally and over ssh — that sidesteps ssh's re-joining of arguments into a
// single shell string. Nothing here needs root.
const stateScript = `
echo "current $(readlink /run/current-system)"
for l in /nix/var/nix/profiles/system-*-link; do
  [ -L "$l" ] || continue
  n=${l##*/system-}; n=${n%-link}
  echo "gen $n $(readlink "$l")"
done
if [ $# -gt 0 ]; then
  nix-store --check-validity --print-invalid "$@" | sed 's/^/invalid /'
fi
`

func queryMachine(t target, outs []string) (*machineState, error) {
	args := append([]string{"sh", "-s", "--"}, outs...)
	if !t.local {
		// BatchMode: a history listing must not stop to ask for a password,
		// and an unreachable machine must not hang it for minutes.
		args = append([]string{"ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "root@" + t.machine}, args...)
	}
	c := exec.Command(args[0], args[1:]...)
	c.Stdin = strings.NewReader(stateScript)
	var stderr strings.Builder
	c.Stderr = &stderr
	out, err := c.Output()
	if err != nil {
		if msg := strings.TrimSpace(stderr.String()); msg != "" {
			return nil, fmt.Errorf("%w: %s", err, msg)
		}
		return nil, err
	}
	return parseMachineState(string(out))
}

func parseMachineState(s string) (*machineState, error) {
	st := &machineState{generations: map[string][]int{}, invalid: map[string]bool{}}
	sc := bufio.NewScanner(strings.NewReader(s))
	for sc.Scan() {
		kind, rest, _ := strings.Cut(sc.Text(), " ")
		switch kind {
		case "current":
			st.current = rest
		case "gen":
			nStr, path, ok := strings.Cut(rest, " ")
			n, err := strconv.Atoi(nStr)
			if !ok || err != nil {
				return nil, fmt.Errorf("bad generation line %q", sc.Text())
			}
			st.generations[path] = append(st.generations[path], n)
		case "invalid":
			st.invalid[rest] = true
		case "":
		default:
			return nil, fmt.Errorf("unexpected line %q", sc.Text())
		}
	}
	for _, gens := range st.generations {
		sort.Ints(gens)
	}
	return st, sc.Err()
}