///| Watched app launches. Every app the launcher, the dock, Super+1..9 or session restore starts /// runs under a small monitor (`@sys.spawn_watch`) that reports how it exited. An app that fails /// to start never fails quietly: when it exits with an error (or a signal) within /// `launch_watch_ms`, or exits cleanly without ever showing a window, the shell shows a notice /// with the command, the exit status and the last lines it printed, and logs the same. ///| How long after starting an app its exit counts as a failed launch (later exits are the user /// quitting it, or a crash the session log keeps). let launch_watch_ms : UInt64 = 30000UL ///| After an app exits 0 without a window, how long to wait for one (an app that hands the launch /// to its running instance opens the window from there, a moment later). let launch_grace_ms : UInt64 = 2000UL ///| struct LaunchWatch { /// Report socket from the monitor (-1 once closed). mut fd : Int id : String name : String command : String started : UInt64 /// Whether the app already had a window here when it was started. had_window : Bool buf : Array[Byte] /// Parsed report, once the pipe hit EOF. mut report : LaunchReport? /// When to check (exited 0 without a window yet) whether a window has appeared since. mut check_at : UInt64 } ///| How a launched command ended, as the monitor reported it. pub(all) struct LaunchReport { /// "exit" or "signal" ("" when the report was unreadable). how : String /// Exit status or signal number. code : Int /// Milliseconds it ran. ran_ms : Int /// The end of what it printed (stdout and stderr). output : String } derive(Eq, Debug) ///| Parse the monitor's report: "exit CODE MS\n" or "signal NUM MS\n", then the output tail. pub fn parse_launch_report(data : Bytes) -> LaunchReport { let text = @utf8.decode_lossy(data) let (head, rest) = match text.find("\n") { Some(i) => (text[:i].to_string(), text[i + 1:].to_string()) None => (text, "") } let parts : Array[String] = head.split(" ").map(x => x.to_string()).collect() if parts.length() != 3 || (parts[0] != "exit" && parts[0] != "signal") { return { how: "", code: -1, ran_ms: 0, output: text } } let num = fn(s : String) { let mut n = 0 for c in s { if c < '0' || c > '9' { return -1 } n = n * 10 + (c.to_int() - '0'.to_int()) } n } { how: parts[0], code: num(parts[1]), ran_ms: num(parts[2]), output: rest } } ///| The last `max` meaningful lines of `output`: blank lines dropped, a line repeated right after /// itself shown once with "(N times)". pub fn output_tail(output : String, max : Int) -> Array[String] { let lines : Array[(String, Int)] = [] for raw in output.split("\n") { let l = raw.trim(chars=" \t\r").to_string() if l.length() == 0 { continue } match lines.last() { Some((prev, n)) if prev == l => lines[lines.length() - 1] = (prev, n + 1) _ => lines.push((l, 1)) } } let start = if lines.length() > max { lines.length() - max } else { 0 } let out : Array[String] = [] for i = start; i < lines.length(); i = i + 1 { let (l, n) = lines[i] out.push(if n > 1 { l + " (" + n.to_string() + " times)" } else { l }) } out } ///| Signal names for the ones apps die of. fn signal_name(n : Int) -> String { match n { 1 => "SIGHUP" 2 => "SIGINT" 4 => "SIGILL" 5 => "SIGTRAP" 6 => "SIGABRT" 7 => "SIGBUS" 8 => "SIGFPE" 9 => "SIGKILL" 11 => "SIGSEGV" 13 => "SIGPIPE" 15 => "SIGTERM" _ => "signal " + n.to_string() } } ///| The notice for a failed launch of `name` (`command`), or None when `r` is not a failure. /// `window` says whether the app has a window here now. pub fn launch_failure(name : String, command : String, r : LaunchReport, window : Bool) -> Array[String]? { let secs = fn(ms : Int) { if ms < 1000 { ms.to_string() + " ms" } else { (ms / 1000).to_string() + "." + (ms % 1000 / 100).to_string() + " s" } } let what = match r.how { "exit" if r.code == 0 => if window { return None } else { "exited (status 0) after " + secs(r.ran_ms) + " without opening a window" } "exit" if r.code == 127 => "failed: command not found (status 127)" "exit" if r.code == 126 => "failed: command not executable (status 126)" "exit" => "exited with status " + r.code.to_string() + " after " + secs(r.ran_ms) "signal" => "was killed by " + signal_name(r.code) + " after " + secs(r.ran_ms) _ => "ended without a report from its monitor" } let lines = ["Could not start " + name + ": " + what, "Command: " + command] let tail = output_tail(r.output, 4) if tail.length() == 0 { lines.push("It printed nothing. More in ~/.local/state/chandra/session.log") } else { lines.append(tail) } Some(lines) } ///| Whether some window here belongs to desktop app `id`. fn DesktopShell::has_window_for(self : DesktopShell, id : String) -> Bool { self.win_list.iter().any(e => resolve_app_id(e.app_id, self.exec, self.wm_classes) == Some(id)) } ///| The catalog name of app `id` (its id when it has none). fn DesktopShell::app_name(self : DesktopShell, id : String) -> String { for a in self.apps { if a.id == id { return a.name } } id } ///| Start desktop app `id` with `command`, watched. False (with a notice) when nothing started. pub fn DesktopShell::start_app(self : DesktopShell, id : String, command : String) -> Bool { let name = self.app_name(id) let fd = @sys.spawn_watch(command, self.display) if fd < 0 { self.say_error(["Could not start " + name + ": the process could not be created", "Command: " + command]) @sys.log("chandra: launch failed: " + name + " (" + id + "): could not create a process for `" + command + "`") return false } @sys.log("chandra: launching " + name + " (" + id + "): " + command) self.launches.push({ fd, id, name, command, started: @sys.monotonic_ms(), had_window: self.has_window_for(id), buf: [], report: None, check_at: 0UL, }) true } ///| Report sockets still open, for the main loop to wake on. pub fn DesktopShell::launch_fds(self : DesktopShell) -> Array[Int] { self.launches.filter(l => l.fd >= 0).map(l => l.fd) } ///| Milliseconds until a launch needs looking at again (-1: nothing pending). pub fn DesktopShell::launch_wake_ms(self : DesktopShell, now : UInt64) -> Int { let mut best = -1 for l in self.launches { let at = if l.check_at > 0UL { l.check_at } else if l.fd >= 0 { l.started + launch_watch_ms } else { now } let d = if at <= now { 0 } else { (at - now).to_int() } if best < 0 || d < best { best = d } } best } ///| Read the monitors' reports and act on them: a notice for each failed launch. pub fn DesktopShell::launch_tick(self : DesktopShell) -> Unit { if self.launches.length() == 0 { return } let now = @sys.monotonic_ms() let buf : FixedArray[Byte] = FixedArray::make(4096, b'\x00') for l in self.launches { if l.fd < 0 { continue } let mut eof = false while @sys.poll_read(l.fd, 0) > 0 { let (n, extra) = @sys.recvmsg_fd(l.fd, buf, buf.length()) if extra >= 0 { @sys.close_fd(extra) } if n == -1 { break } if n <= 0 { eof = true break } for i = 0; i < n; i = i + 1 { l.buf.push(buf[i]) } } if eof { @sys.close_fd(l.fd) l.fd = -1 let r = parse_launch_report(Bytes::from_array(l.buf)) l.report = Some(r) let ran : UInt64 = if r.ran_ms > 0 { r.ran_ms.to_uint64() } else { 0UL } if ran > launch_watch_ms { // Ran a while: the user quit it, or it crashed; the monitor logged how. l.check_at = 0UL } else if r.how == "exit" && r.code == 0 && !l.had_window { l.check_at = now + launch_grace_ms } else { l.check_at = now } } else if now - l.started > launch_watch_ms { // Running past the watch window: it started. Stop listening (the monitor keeps logging). @sys.close_fd(l.fd) l.fd = -1 l.check_at = 0UL } } let keep : Array[LaunchWatch] = [] for l in self.launches { if l.fd >= 0 { keep.push(l) continue } match l.report { Some(r) if l.check_at > 0UL => if l.check_at > now { keep.push(l) } else { let window = l.had_window || self.has_window_for(l.id) match launch_failure(l.name, l.command, r, window) { Some(lines) => { self.say_error(lines) @sys.log("chandra: launch failed: " + l.id + ": " + lines.join("\n ")) } None => () } } _ => () } } self.launches.clear() self.launches.append(keep) } ///| test "parse_launch_report reads the monitor's report" { let r = parse_launch_report(b"exit 1 230\nbwrap: no\n") assert_eq(r, { how: "exit", code: 1, ran_ms: 230, output: "bwrap: no\n" }) let s = parse_launch_report(b"signal 11 5\n") assert_eq(s.how, "signal") assert_eq(s.code, 11) assert_eq(parse_launch_report(b"").how, "") } ///| test "output_tail keeps the last lines and folds repeats" { assert_eq(output_tail("a\n\nb\nb\nb\nc\n", 2), ["b (3 times)", "c"]) assert_eq(output_tail("", 4), []) } ///| test "launch_failure: a clean exit is fine once the app has a window" { let r = { how: "exit", code: 0, ran_ms: 40, output: "" } assert_eq(launch_failure("Kwi", "kwi", r, true), None) match launch_failure("Kwi", "kwi", r, false) { Some(l) => assert_eq(l[0], "Could not start Kwi: exited (status 0) after 40 ms without opening a window") None => fail("expected a notice") } match launch_failure("Kwi", "kwi", { how: "exit", code: 2, ran_ms: 1500, output: "x" }, true) { Some(l) => assert_eq(l, ["Could not start Kwi: exited with status 2 after 1.5 s", "Command: kwi", "x"]) None => fail("expected a notice") } }