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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
|
//! Upgrade (docs/next-daemon.md, "Phase 6: upgrade notes"): a running
//! session, and the daemon, moved onto the pardes installed since they
//! started, in place.
//!
//! At a step boundary a session commits its dump to the state file
//! (Db.zig, as `upgrade-<pid>`) and execs the path it was started from. Its pty masters, terminals, stubs and daemon
//! link stay open across the exec, named in a record on the new command
//! line: `--upgraded=<record>` ahead of the arguments it was started with.
//! The pid stays, so its shells stay its children; the new process loads
//! the dump and takes those fds back (each host's `resume`). A new build
//! that cannot load the dump execs the old one again, from the copy this
//! process left open (Linux), and with none it starts afresh with the
//! shells adopted, the dump left for a Restore by hand. A record of an older
//! build names a `.dump` file instead (0.24 reads one, and deletes it once
//! loaded).
const std = @import("std");
const builtin = @import("builtin");
/// libc: exec of the new build with fds held across it, and /proc/self/exe opened before it.
const libc = std.c;
const posix = std.posix;
const pardes = @import("core");
const daemon = @import("daemon.zig");
pub const supported = builtin.os.tag == .linux or builtin.os.tag == .freebsd;
pub const flag = "--upgraded=";
/// A window's pair's session's first word (main.zig `pair`): its first
/// client's fd, which an Upgrade does not name again (that client joined).
pub const paired_flag = "--paired=";
/// What this build says it is (`pardes --version`'s first line).
pub const version_line = if (pardes.commit) |c| "pardes " ++ pardes.version ++ " (" ++ c ++ ")" else "pardes " ++ pardes.version;
// ---- the path it was started from ----
/// The path this process was started from, what Upgrade execs: a reinstall
/// puts the new build there, while /proc/self/exe names the old file,
/// deleted by then.
var exe_buf: [4096:0]u8 = undefined;
var exe_len: usize = 0;
/// The arguments it was started with (an upgrade's record left out).
var given: []const [:0]const u8 = &.{};
/// The file at that path when it started, and the newer one last said.
var started_inode: ?u64 = null;
var told_inode: ?u64 = null;
var located = false;
/// Its arguments kept, at its start; an upgraded process's path is the one
/// its record names (the system would name a fallback's old binary,
/// deleted).
pub fn remember(args: []const [:0]const u8) void {
given = if (args.len > 1 and std.mem.startsWith(u8, args[1], flag)) args[2..] else if (args.len > 0) args[1..] else &.{};
if (given.len > 0 and std.mem.startsWith(u8, given[0], paired_flag)) given = given[1..];
if (resumed) |*rec| if (rec.exe.len > 0 and rec.exe.len < exe_buf.len) {
@memcpy(exe_buf[0..rec.exe.len], rec.exe);
exe_buf[rec.exe.len] = 0;
exe_len = rec.exe.len;
};
}
/// Its path asked of the system (a readlink) and the file it runs (a
/// stat), once: after the first frame, off a startup's way (the hosts'
/// loops). A build can be installed at that path before then (a pair's
/// session, whose first pass comes after its client's first frame; a
/// loaded machine): Linux then names the path "PATH (deleted)", and the
/// file at the path is not the one it started from, the one it runs is.
pub fn locate() void {
if (located) return;
located = true;
if (exe_len == 0) exe_len = if (startPath(&exe_buf)) |path| path.len else 0;
started_inode = if (builtin.os.tag == .linux) inodeOf("/proc/self/exe") else if (exe()) |path| inodeOf(path) else null;
}
/// The path this process was started from, as the system names it, less
/// the " (deleted)" Linux adds once the file there was replaced (a
/// reinstall): the path is the path (what an Upgrade execs, and a daemon
/// started from here: daemon.zig `spawn`).
pub fn startPath(buf: *[4096:0]u8) ?[:0]const u8 {
const n = std.process.executablePath(std.Io.Threaded.global_single_threaded.io(), buf) catch return null;
const len = if (std.mem.endsWith(u8, buf[0..n], " (deleted)")) n - " (deleted)".len else n;
buf[len] = 0;
return buf[0..len :0];
}
fn inodeOf(path: [:0]const u8) ?u64 {
const st = std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), path, .{}) catch return null;
return @intCast(st.inode);
}
/// A newer build installed at that path since this process started, said
/// in a line, once a build: asked at a focus-in, where one comes back from
/// rebuilding (a stat). Of no pane, as the Upgrade's outcome is: a pane's
/// message names its cause first (pick-ui SPEC §10.1), and the focused
/// file's path is not this one's. ponytail: explicit only, no watch and
/// no automatic upgrade.
pub fn noticeNewer(core: *pardes.Pardes) void {
if (newer()) core.setMessage(.at(pardes.MAX_PANES), pardes.newer_build_words);
}
/// Whether to say a newer build is installed now (`noticeNewer`): asked
/// by a session's own frontend at its focus-in, between steps; the line is
/// an input (setMessage) its replica clients take from the tape.
pub fn newer() bool {
const was = started_inode orelse return false;
const now = inodeOf(exe() orelse return false) orelse return false;
if (now == was or told_inode == now) return false;
told_inode = now;
return true;
}
/// Another file at its start path than the one it started from: a build
/// installed there since (`locate` first). A client's question at an
/// Upgrade (client.zig).
pub fn replaced() bool {
const was = started_inode orelse return false;
return (inodeOf(exe() orelse return false) orelse return false) != was;
}
pub fn exe() ?[:0]const u8 {
return if (exe_len == 0) null else exe_buf[0..exe_len :0];
}
// ---- the record ----
pub const Pty = struct { pane: u8, pid: libc.pid_t, fd: c_int };
/// A terminal and its view: the primary one's stub is daemon.stub; its
/// termios is the cooked one it is put back to at the end (it is raw now).
pub const Tty = struct { view: u8, fd: c_int, stub: c_int, primary: bool, termios: posix.termios };
pub const Record = struct {
/// daemon.link and daemon.stub.
link: c_int = -1,
stub: c_int = -1,
/// The binary being replaced, open (Linux): a new one that cannot load
/// the dump execs it again.
old: c_int = -1,
/// A window was open (the GUI).
window: bool = false,
/// Its size in points at the Upgrade, `WxH` (SDL_GetWindowSize then: the
/// user's since its start), the new window's `--geometry` (gui.zig).
/// None, an older build's record: the default.
size: ?[]const u8 = null,
ptys: [pardes.MAX_PANES]Pty = undefined,
nptys: usize = 0,
ttys: [pardes.views.max]Tty = undefined,
nttys: usize = 0,
/// The path exec'd, the one a later Upgrade execs again.
exe: []const u8 = "",
/// The state file the session's dump is in (an older build's: the
/// `.dump` file it is).
dump: []const u8 = "",
/// The dump's label there; none, `dump` is a file of its own.
label: []const u8 = "",
/// Why the new build could not load it: a start that went back to the
/// old binary says so.
refused: []const u8 = "",
/// This process's own: its dump would not load, so it started afresh
/// and adopts the shells.
fresh: bool = false,
/// A pair's session's state (daemon.State): whether it is kept, which
/// the dump does not say. None: as its frontend says (attached or not).
state: ?daemon.State = null,
pub fn addPty(rec: *Record, pane: usize, pid: libc.pid_t, fd: c_int) void {
if (rec.nptys == rec.ptys.len or fd < 0) return;
rec.ptys[rec.nptys] = .{ .pane = @intCast(pane), .pid = pid, .fd = fd };
rec.nptys += 1;
}
pub fn addTty(rec: *Record, t: Tty) void {
if (rec.nttys == rec.ttys.len or t.fd < 0) return;
rec.ttys[rec.nttys] = t;
rec.nttys += 1;
}
/// Every fd it names, close-on-exec (`on`) or kept across one.
pub fn closeOnExec(rec: *const Record, on: bool) void {
const set = struct {
fn f(fd: c_int, cloexec: bool) void {
if (fd >= 0) _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, if (cloexec) 1 else 0));
}
}.f;
set(rec.link, on);
set(rec.stub, on);
set(rec.old, on);
for (rec.ptys[0..rec.nptys]) |p| set(p.fd, on);
for (rec.ttys[0..rec.nttys]) |t| {
set(t.fd, on);
set(t.stub, on);
}
}
/// One `word value` a line, the dump's path last (its line is all of it).
pub fn encode(rec: *const Record, w: *std.Io.Writer) !void {
try w.print("link {d}\nstub {d}\nold {d}\nwindow {d}\n", .{ rec.link, rec.stub, rec.old, @intFromBool(rec.window) });
if (rec.size) |wh| try w.print("size {s}\n", .{wh});
for (rec.ptys[0..rec.nptys]) |p| try w.print("pty {d} {d} {d}\n", .{ p.pane, p.pid, p.fd });
for (rec.ttys[0..rec.nttys]) |t| try w.print("tty {d} {d} {d} {d} {x}\n", .{ t.view, t.fd, t.stub, @intFromBool(t.primary), std.mem.asBytes(&t.termios) });
if (rec.refused.len > 0) try w.print("refused {s}\n", .{rec.refused});
if (rec.label.len > 0) try w.print("label {s}\n", .{rec.label});
if (rec.state) |s| try w.print("state {t}\n", .{s});
try w.print("exe {s}\ndump {s}\n", .{ rec.exe, rec.dump });
}
/// `text`'s record; its strings are slices of it.
pub fn decode(text: []const u8) !Record {
var rec: Record = .{};
var lines = std.mem.splitScalar(u8, text, '\n');
while (lines.next()) |line| {
if (line.len == 0) continue;
const sp = std.mem.indexOfScalar(u8, line, ' ') orelse return error.BadRecord;
const word = line[0..sp];
const rest = line[sp + 1 ..];
var it = std.mem.tokenizeScalar(u8, rest, ' ');
// A word of a later build's record is passed over.
switch (std.meta.stringToEnum(enum { link, stub, old, window, size, pty, tty, refused, label, state, exe, dump }, word) orelse continue) {
.link => rec.link = try std.fmt.parseInt(c_int, rest, 10),
.stub => rec.stub = try std.fmt.parseInt(c_int, rest, 10),
.old => rec.old = try std.fmt.parseInt(c_int, rest, 10),
.window => rec.window = std.mem.eql(u8, rest, "1"),
.size => rec.size = rest,
.pty => {
if (rec.nptys == rec.ptys.len) return error.BadRecord;
const pane = try std.fmt.parseInt(u8, it.next() orelse return error.BadRecord, 10);
if (pane >= pardes.MAX_PANES) return error.BadRecord;
rec.ptys[rec.nptys] = .{
.pane = pane,
.pid = try std.fmt.parseInt(libc.pid_t, it.next() orelse return error.BadRecord, 10),
.fd = try std.fmt.parseInt(c_int, it.next() orelse return error.BadRecord, 10),
};
rec.nptys += 1;
},
.tty => {
if (rec.nttys == rec.ttys.len) return error.BadRecord;
var t: Tty = .{
.view = try std.fmt.parseInt(u8, it.next() orelse return error.BadRecord, 10),
.fd = try std.fmt.parseInt(c_int, it.next() orelse return error.BadRecord, 10),
.stub = try std.fmt.parseInt(c_int, it.next() orelse return error.BadRecord, 10),
.primary = std.mem.eql(u8, it.next() orelse return error.BadRecord, "1"),
.termios = undefined,
};
const hex = it.next() orelse return error.BadRecord;
// Another build's termios is the kernel's, of one size.
if (hex.len != 2 * @sizeOf(posix.termios) or t.view >= pardes.views.max) return error.BadRecord;
_ = try std.fmt.hexToBytes(std.mem.asBytes(&t.termios), hex);
rec.ttys[rec.nttys] = t;
rec.nttys += 1;
},
.refused => rec.refused = rest,
.label => rec.label = rest,
.state => rec.state = std.meta.stringToEnum(daemon.State, rest),
.exe => rec.exe = rest,
.dump => rec.dump = rest,
}
}
if (rec.dump.len == 0) return error.BadRecord;
return rec;
}
};
/// The record this process was started with (`--upgraded=`), set by main.
pub var resumed: ?Record = null;
// ---- before: asking the new binary, and the exec ----
pub const Checked = union(enum) { ok: []const u8, no: []const u8 };
/// `path --version` run as it is: a binary not there, not a pardes, or one
/// that cannot start, found before anything is let go. Its first line
/// (`pardes <version>`), or why not, in `buf`.
pub fn check(path: [:0]const u8, buf: []u8) Checked {
var pipe: [2]c_int = undefined;
if (libc.pipe(&pipe) != 0) return .{ .no = "Upgrade: no pipe to ask the new pardes its version" };
const argv = [_:null]?[*:0]const u8{ path, "--version", null };
const pid = libc.fork();
if (pid < 0) {
_ = libc.close(pipe[0]);
_ = libc.close(pipe[1]);
return .{ .no = "Upgrade: no process to ask the new pardes its version" };
}
if (pid == 0) {
// Only async-signal-safe calls between fork and exec.
_ = libc.dup2(pipe[1], 1);
const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0));
if (null_fd >= 0) {
_ = libc.dup2(null_fd, 0);
_ = libc.dup2(null_fd, 2);
}
_ = libc.execve(path, &argv, @ptrCast(libc.environ));
libc._exit(127);
}
_ = libc.close(pipe[1]);
var len: usize = 0;
var waited = false;
while (len < buf.len) {
// A pardes answers --version in milliseconds; 10 s is one that hangs.
var fds = [_]libc.pollfd{.{ .fd = pipe[0], .events = libc.POLL.IN, .revents = 0 }};
const ready = libc.poll(&fds, 1, 10_000);
if (ready < 0 and libc.errno(ready) == .INTR) continue;
if (ready <= 0) {
_ = libc.kill(pid, .KILL);
waited = true;
break;
}
const n = libc.read(pipe[0], buf[len..].ptr, buf.len - len);
if (n < 0 and libc.errno(n) == .INTR) continue;
if (n <= 0) break;
len += @intCast(n);
}
_ = libc.close(pipe[0]);
var status: c_int = 0;
while (libc.waitpid(pid, &status, 0) < 0 and libc.errno(-1) == .INTR) {}
const s: u32 = @bitCast(status);
const said = buf[0..len];
const first = said[0 .. std.mem.indexOfScalar(u8, said, '\n') orelse said.len];
if (!waited and libc.W.IFEXITED(s) and libc.W.EXITSTATUS(s) == 0 and std.mem.startsWith(u8, first, "pardes ")) return .{ .ok = first };
// The words go where the line was: the rest of `buf`.
var tail: [96]u8 = undefined;
const how = if (waited)
"did not answer --version in 10 s"
else if (libc.W.IFEXITED(s) and libc.W.EXITSTATUS(s) == 127)
"would not start"
else if (libc.W.IFEXITED(s) and libc.W.EXITSTATUS(s) != 0)
std.fmt.bufPrint(&tail, "exited {d} at --version", .{libc.W.EXITSTATUS(s)}) catch unreachable // a status number fits 96
else if (libc.W.IFSIGNALED(s))
std.fmt.bufPrint(&tail, "died of signal {d} at --version", .{libc.W.TERMSIG(s)}) catch unreachable // a signal number fits 96
else
"does not answer --version as a pardes does";
return .{ .no = std.fmt.bufPrint(buf, "Upgrade: {s} {s}; this session stays as it is", .{ path[0..@min(path.len, 400)], how }) catch "Upgrade: the new pardes would not start; this session stays as it is" };
}
/// The binary this process runs, open, for a new one to fall back to: on
/// Linux the file even once deleted. ponytail: FreeBSD has no /proc by
/// default, so a new build there that cannot load a dump starts afresh.
fn openSelf() c_int {
if (comptime builtin.os.tag != .linux) return -1;
return libc.open("/proc/self/exe", .{ .ACCMODE = .RDONLY, .CLOEXEC = true }, @as(libc.mode_t, 0));
}
/// This process exec'd as `path` (or the binary open on `old`), the record
/// on its command line and the fds it names kept open. Returns only when
/// the exec failed, those fds close-on-exec again: why, in words.
pub fn exec(gpa: std.mem.Allocator, path: ?[:0]const u8, old: c_int, rec: *const Record) []const u8 {
var text: std.Io.Writer.Allocating = .init(gpa);
defer text.deinit();
text.writer.writeAll(flag) catch return "no memory for its record";
rec.encode(&text.writer) catch return "no memory for its record";
text.writer.writeByte(0) catch return "no memory for its record";
const record: [*:0]const u8 = @ptrCast(text.written().ptr);
const argv = gpa.allocSentinel(?[*:0]const u8, given.len + 2, null) catch return "no memory for its arguments";
defer gpa.free(argv);
argv[0] = if (path) |p| p.ptr else if (exe()) |e| e.ptr else "pardes";
argv[1] = record;
for (given, argv[2..]) |a, *slot| slot.* = a.ptr;
rec.closeOnExec(false);
const envp: [*:null]const ?[*:0]const u8 = @ptrCast(libc.environ);
// execveat by its syscall: musl (a static pardes) has no wrapper.
const e = if (path) |p|
libc.errno(libc.execve(p, argv.ptr, envp))
else if (comptime builtin.os.tag == .linux)
std.os.linux.errno(std.os.linux.execveat(old, "", argv.ptr, envp, .{ .SYMLINK_NOFOLLOW = false, .EMPTY_PATH = true }))
else
libc.errno(@as(c_int, -1));
rec.closeOnExec(true);
return switch (e) {
.NOENT => "it is not there",
.ACCES, .PERM => "it may not be run",
.NOEXEC => "it is not a program this system runs",
.@"2BIG" => "its record and arguments are too long",
.NOMEM => "no memory for it",
.TXTBSY => "it is still being written",
else => "the exec failed",
};
}
/// The state file's path an upgrade's record names (`dumpInto`'s).
var state_path: [4200]u8 = undefined;
/// An Upgrade's dump, the terminal's and the window's alike: committed to
/// the state file as `upgrade-<pid>` (its label kept in `at`), where a
/// Restore finds it, and named in `rec`, the binary it replaces held open
/// for a new build that cannot load it. Null when it is, else why in words
/// (`why`'s).
pub fn dumpInto(core: *pardes.Pardes, rec: *Record, at: *[1024:0]u8, why: []u8) ?[]const u8 {
const path = pardes.Db.statePath(&pardes.tape.none, &state_path, core.settings.dump_dir.get()) orelse return "Upgrade: no directory for the session's dump; this session stays as it is";
var name: [64]u8 = undefined;
const label = std.fmt.bufPrint(&name, "upgrade-{d}", .{std.c.getpid()}) catch unreachable;
const bytes = pardes.dump.image(core, label) catch |err| {
var words: [128]u8 = undefined;
return std.fmt.bufPrint(why, "Upgrade: the session would not dump: {s}; it stays as it is", .{pardes.Messages.errorWords(err, &words)}) catch "Upgrade: the session would not dump";
};
defer core.gpa.free(bytes);
const put = core.db.putDump(core, bytes, label, at[0 .. at.len - 1]) catch |err| {
var words: [128]u8 = undefined;
return std.fmt.bufPrint(why, "Upgrade: the session's dump could not be written to {s} ({s}); it stays as it is", .{ path[0..@min(path.len, 600)], pardes.Messages.errorWords(err, &words) }) catch "Upgrade: its dump could not be written";
};
at[put.len] = 0;
rec.dump = path;
rec.label = at[0..put.len];
rec.old = openSelf();
return null;
}
/// The daemon told, 9P's last answers sent (`fs`), and this process
/// exec'd as `path` with `rec`, whose dump `dumpInto` labelled `at`.
/// Returns only when the exec failed, the binary it replaces let go (the
/// dump stays, a dump among the state file's): why, in words (`why`'s).
pub fn execAs(gpa: std.mem.Allocator, path: [:0]const u8, rec: *const Record, at: [*:0]const u8, fs: ?*@import("9p_io.zig").Listener, why: []u8) []const u8 {
_ = at;
daemon.upgraded();
if (fs) |f| f.flushOut();
var with = rec.*;
with.state = switch (daemon.sessionState()) {
.pair, .kept => |s| s,
.attached, .detached => null,
};
const err_words = exec(gpa, path, -1, &with);
// Still here: the exec failed.
if (rec.old >= 0) _ = libc.close(rec.old);
return std.fmt.bufPrint(why, "Upgrade: {s} would not start: {s}; this session stays as it is", .{ path[0..@min(path.len, 600)], err_words }) catch "Upgrade: the new pardes would not start";
}
// ---- after: the new process ----
/// The core an upgraded process starts with: the session its dump is. A
/// build that cannot load it execs the binary it replaced to load it; with
/// none, a fresh session (`fresh`) the host adopts the shells into, the
/// dump left where a Restore finds it. `PARDES_TEST_UPGRADE_REFUSE` refuses
/// a load as such a build would (test/daemon.py's failing upgrade), in the
/// first start only, or (`all`) in the start it falls back to as well.
pub fn load(gpa: std.mem.Allocator, core_gpa: std.mem.Allocator, opts: pardes.Options, rec: *Record) !*pardes.Pardes {
var kept: [pardes.MAX_PANES]bool = @splat(false);
for (rec.ptys[0..rec.nptys]) |p| kept[p.pane] = true;
const loaded = loaded: {
if (libc.getenv("PARDES_TEST_UPGRADE_REFUSE")) |how| if (rec.refused.len == 0 or std.mem.eql(u8, std.mem.span(how), "all"))
break :loaded error.RefusedByTest;
const bytes = (if (rec.label.len > 0) pardes.Db.readDumpAt(gpa, rec.dump, rec.label) else pardes.filesystem.readFile(&pardes.tape.none, gpa, rec.dump)) catch |err| break :loaded err;
defer gpa.free(bytes);
break :loaded pardes.dump.resumeFromDump(core_gpa, opts, bytes, &kept);
};
var buf: [700]u8 = undefined;
// Restore's word for the dump left behind: its label, or its file.
const again_name = if (rec.label.len > 0) rec.label else rec.dump;
if (loaded) |p| {
// An older build's dump, a file of its own, goes once loaded; a
// label stays among the state file's dumps.
if (rec.label.len == 0) {
// fs.readFile read it by this path, 0-terminated in 4096 bytes:
// a longer one was refused there (error.PathTooLong), kept.
var path_buf: [4096]u8 = undefined;
_ = libc.unlink(std.fmt.bufPrintSentinel(&path_buf, "{s}", .{rec.dump}, 0) catch unreachable);
}
// The binary it replaced, let go: held, its file (deleted) would
// keep its blocks for as long as this session runs.
if (rec.old >= 0) _ = libc.close(rec.old);
rec.old = -1;
tellEveryView(p, if (rec.refused.len > 0)
std.fmt.bufPrint(&buf, "Upgrade: the new build could not load this session ({s}); it goes on as {s}", .{ rec.refused[0..@min(rec.refused.len, 200)], version_line }) catch "Upgrade: the new build could not load this session; it goes on as before"
else
"Upgrade: now " ++ version_line);
return p;
} else |err| {
var words_buf: [128]u8 = undefined;
const why = if (err == error.RefusedByTest) "refused by PARDES_TEST_UPGRADE_REFUSE" else pardes.Messages.errorWords(err, &words_buf);
// The binary it replaced loads its own dump: tried once, never from
// a start that is that fallback already.
if (rec.old >= 0 and rec.refused.len == 0) {
var again = rec.*;
again.refused = why;
again.old = -1;
_ = exec(gpa, null, rec.old, &again);
}
if (rec.old >= 0) _ = libc.close(rec.old);
rec.old = -1;
rec.fresh = true;
var o = opts;
o.load_path = null;
const p = try pardes.Pardes.init(core_gpa, o);
p.setMessage(.at(p.view().active), std.fmt.bufPrint(&buf, "Upgrade: no build could load the session ({s}); its shells are here, and Restore {s} brings the rest back", .{ why, again_name[0..@min(again_name.len, 400)] }) catch "Upgrade: no build could load the session; its dump is kept for a Restore");
return p;
}
}
/// An Upgrade is the session's news, not the asking view's: said once, of
/// no pane in particular, it is on every view's notice row (each client
/// reads it on its own screen).
fn tellEveryView(p: *pardes.Pardes, text: []const u8) void {
_ = pardes.Messages.say(p, .notice, pardes.MAX_PANES, text);
}
test "an upgrade's outcome is said in every view, at the pane its keyboard is on, whichever view's input came last" {
const gpa = std.testing.allocator;
const p = try pardes.Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
_ = try p.setTestFile("before the upgrade\n");
const asked = p.view().active;
// A second client's view, its keyboard on a pane of its own, the input
// that came last its own (as a client's keys before an Upgrade over 9P).
const k = p.openView() orelse return error.NoView;
p.toView(k);
try std.testing.expect(p.executeBuiltinLine(p.view().active, "New"));
try std.testing.expect(p.view().active != asked);
const q = try upgradedForTest(gpa, p);
defer q.deinit();
var seen: usize = 0;
for (q.views, 0..) |v, i| if (v != null) {
try std.testing.expect(saysOutcome(q, i));
seen += 1;
};
try std.testing.expectEqual(@as(usize, 2), seen);
try std.testing.expect(q.views[0].?.active != q.views[k.index()].?.active);
}
test "an upgrade's outcome stays on every view's notice row until something else is said: no key and no clock take it" {
const gpa = std.testing.allocator;
const p = try pardes.Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
_ = try p.setTestFile("before the upgrade\n");
// Two clients' views, each its keyboard on a pane of its own, kept for
// their clients as an Upgrade keeps them (Peers.refuseAll: away).
var kept: [2]pardes.Pardes.View.Id = undefined;
for (&kept) |*k| {
k.* = p.openView() orelse return error.NoView;
p.toView(k.*);
try std.testing.expect(p.executeBuiltinLine(p.view().active, "New"));
}
p.toView(.at(0));
for (kept) |k| p.awayView(k);
const q = try upgradedForTest(gpa, p);
defer q.deinit();
const key: pardes.Event = .{ .key = .{ .cp = 'j', .text = "j" } };
q.update(key);
q.unattended = true;
q.update(.tick);
q.unattended = false;
try std.testing.expect(q.rejoinView(kept[0]));
q.update(key);
q.advance(q.views[kept[1].index()].?.away_ns + pardes.views.away_kept_ns);
for (kept) |k| try std.testing.expect(saysOutcome(q, k.index()));
try std.testing.expect(saysOutcome(q, q.live));
}
/// Whether view `k`'s notice row says the Upgrade's outcome (every view
/// has the session's one).
fn saysOutcome(q: *const pardes.Pardes, k: usize) bool {
if (q.views[k] == null) return false;
const said = q.messages.headline() orelse return false;
return std.mem.startsWith(u8, said.text.slice(), "Upgrade: now pardes ");
}
/// `p` dumped and loaded as an Upgrade's new process loads it (`load`).
fn upgradedForTest(gpa: std.mem.Allocator, p: *pardes.Pardes) !*pardes.Pardes {
const bytes = try pardes.dump.byteDump(p);
defer gpa.free(bytes);
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes-upgrade-1.dump", .data = bytes });
var dir_buf: [4096]u8 = undefined;
const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
var text_buf: [4300]u8 = undefined;
var rec = try Record.decode(try std.fmt.bufPrint(&text_buf, "link -1\nstub -1\nold -1\nwindow 0\nexe /x/pardes\ndump {s}/pardes-upgrade-1.dump\n", .{dir}));
const q = try load(gpa, gpa, .{ .tty_only = true }, &rec);
errdefer q.deinit();
try std.testing.expect(!rec.fresh);
return q;
}
test "an upgrade's record reads back as it was written, and refuses one cut short" {
var rec: Record = .{ .link = 5, .stub = 7, .old = 9, .window = true, .size = "1402x1488", .exe = "/a b/pardes", .dump = "/home/u/.local/share/pardes/pardes.xitdb", .label = "upgrade-1", .state = .kept };
rec.addPty(3, 1234, 11);
rec.addPty(0, 99, 12);
var tio: posix.termios = std.mem.zeroes(posix.termios);
std.mem.asBytes(&tio)[0] = 0x5a;
rec.addTty(.{ .view = 2, .fd = 13, .stub = 14, .primary = true, .termios = tio });
var buf: [4096]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
try rec.encode(&w);
const back = try Record.decode(w.buffered());
try std.testing.expectEqual(@as(c_int, 5), back.link);
try std.testing.expectEqual(@as(c_int, 9), back.old);
try std.testing.expect(back.window);
try std.testing.expectEqualStrings("1402x1488", back.size.?);
try std.testing.expectEqual(@as(usize, 2), back.nptys);
try std.testing.expectEqual(Pty{ .pane = 3, .pid = 1234, .fd = 11 }, back.ptys[0]);
try std.testing.expectEqual(@as(usize, 1), back.nttys);
try std.testing.expect(back.ttys[0].primary and back.ttys[0].view == 2 and back.ttys[0].stub == 14);
try std.testing.expectEqual(@as(u8, 0x5a), std.mem.asBytes(&back.ttys[0].termios)[0]);
try std.testing.expectEqualStrings("/a b/pardes", back.exe);
try std.testing.expectEqualStrings("/home/u/.local/share/pardes/pardes.xitdb", back.dump);
try std.testing.expectEqualStrings("upgrade-1", back.label);
try std.testing.expectEqual(daemon.State.kept, back.state.?);
// An older build's: its dump a file, no label, no state, no size.
const older = try Record.decode("link 5\nexe /a\ndump /run/u/pardes-upgrade-1.dump\n");
try std.testing.expectEqualStrings("/run/u/pardes-upgrade-1.dump", older.dump);
try std.testing.expectEqualStrings("", older.label);
try std.testing.expect(older.state == null and older.size == null);
try std.testing.expectError(error.BadRecord, Record.decode("link 5\n"));
try std.testing.expectError(error.BadRecord, Record.decode("tty 0 1 2 1 abc\ndump x\n"));
}
test "an upgrade from the build before reads the dump file its record names, and deletes it once loaded" {
const gpa = std.testing.allocator;
const p = try pardes.Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
_ = try p.setTestFile("before the upgrade\n");
const bytes = try pardes.dump.byteDump(p);
defer gpa.free(bytes);
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes-upgrade-1.dump", .data = bytes });
var dir_buf: [4096]u8 = undefined;
const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
var text_buf: [4300]u8 = undefined;
// The build before's record: its dump a file, no label.
var rec = try Record.decode(try std.fmt.bufPrint(&text_buf, "link -1\nstub -1\nold -1\nwindow 0\nexe /x/pardes\ndump {s}/pardes-upgrade-1.dump\n", .{dir}));
const q = try load(gpa, gpa, .{ .tty_only = true }, &rec);
defer q.deinit();
try std.testing.expect(!rec.fresh);
const text = for (q.panes) |slot| {
if (slot) |pane| if (pane.file) |f| if (f.output == null) break f.content;
} else return error.FileLost;
try std.testing.expectEqualStrings("before the upgrade\n", text);
try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(std.testing.io, "pardes-upgrade-1.dump", .{}));
}
test "an older build's dump named by a path past 4096 bytes is refused in words and kept for a Restore" {
const gpa = std.testing.allocator;
var text_buf: [4200]u8 = undefined;
var long: [4096]u8 = undefined;
@memset(&long, 'd');
long[0] = '/';
var rec = try Record.decode(try std.fmt.bufPrint(&text_buf, "link -1\nstub -1\nold -1\nwindow 0\nexe /x/pardes\ndump {s}\n", .{&long}));
const q = try load(gpa, gpa, .{ .tty_only = true }, &rec);
defer q.deinit();
try std.testing.expect(rec.fresh);
const pane = q.panes[q.view().active].?;
try std.testing.expect(std.mem.indexOf(u8, q.messages.saidBy(pane), "Upgrade: no build could load the session") != null);
}
test "a newer build installed is said on the notice row in its own words, of no pane: the focused file's path is not its cause" {
const gpa = std.testing.allocator;
const p = try pardes.Pardes.init(gpa, .{ .tty_only = true });
defer p.deinit();
const pane = try p.setTestFile("one\ntwo\n");
// The focused file at a path as long as a session's scratch file's.
gpa.free(pane.file.?.path);
pane.file.?.path = try gpa.dupe(u8, "/home/someone/projects/a-rather-long-directory/of-the-session/notes-of-the-week.txt");
// A build installed at the start path since: another file there.
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes", .data = "a newer build" });
exe_len = try tmp.dir.realPathFile(std.testing.io, "pardes", &exe_buf);
exe_buf[exe_len] = 0;
started_inode = inodeOf(exe().?).? +% 1;
defer {
exe_len = 0;
started_inode = null;
told_inode = null;
}
noticeNewer(p);
const said = p.messages.headline() orelse return error.NothingSaid;
try std.testing.expectEqualStrings(pardes.newer_build_words, said.words());
try std.testing.expectEqual(@as(u32, 0), said.pane);
try std.testing.expectEqual(@as(usize, 0), said.src.len);
// An 80-column terminal's notice row leads with its words.
var row_buf: [pardes.Messages.notice_row_cap]u8 = undefined;
const row = pardes.Messages.noticeRow(p, 80, &row_buf);
try std.testing.expect(std.mem.startsWith(u8, row.text, "\u{b7} a newer pardes is installed"));
}
|