From 268fd3def764d615dce2ba3b533b4fc802a1989f Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Sat, 14 Nov 2026 20:31:29 -0500 Subject: [PATCH] refactor(daemon): rewrite albedo_code in Gleam The boot code snapshot, the macOS clone and copy fallbacks, path publication, the boot warm and the reachable-application preload move to boot_code.gleam. Persistent terms keep their {albedo_code, Name} keys. albedo_code.erl keeps cleanup/0, which albedo_sigterm calls by name. lifecycle builds what its halt needs before the snapshot is removed. --- priv/ready-modules.txt | 1 + src/albedo/daemon/albedo_code.erl | 362 +------------- src/albedo/daemon/boot_code.gleam | 760 ++++++++++++++++++++++++++++++ src/albedo/daemon/lifecycle.gleam | 20 +- src/albedo/daemon/server.gleam | 21 +- 5 files changed, 781 insertions(+), 383 deletions(-) create mode 100644 src/albedo/daemon/boot_code.gleam diff --git a/priv/ready-modules.txt b/priv/ready-modules.txt index c25c49e7e..fc686161d 100644 --- a/priv/ready-modules.txt +++ b/priv/ready-modules.txt @@ -95,6 +95,7 @@ albedo_agents albedo_capabilities albedo_clock albedo_code +albedo@daemon@boot_code albedo_credentials albedo@harness@sdk@credential_store albedo_daemon diff --git a/src/albedo/daemon/albedo_code.erl b/src/albedo/daemon/albedo_code.erl index 879c6060c..3876ed3fd 100644 --- a/src/albedo/daemon/albedo_code.erl +++ b/src/albedo/daemon/albedo_code.erl @@ -1,359 +1,7 @@ -%% Preserve boot-time bytecode without eagerly loading the whole code path. -%% OTP installs can disappear during upgrades; checkout beams can be rebuilt. +%% The boot code snapshot and preload live in boot_code.gleam. albedo_sigterm +%% (Erlang) still calls cleanup/0 by this name, and its test replaces this +%% module with a stub, so the entry point stays here. -module(albedo_code). --export([ - prepare/1, cleanup/0, start/0, preload/0, load_applications/1, runtime_removed/0 -]). +-export([cleanup/0]). -prepare(Home) -> - albedo_priv:pin(), - OriginalPaths = code:get_path(), - Cache = filename:join(unicode:characters_to_list(Home), "code-cache"), - _ = file:del_dir_r(Cache), - case os:getenv("ALBEDO_PRELOAD") of - "0" -> - ok; - "1" -> - ok; - _ -> - Paths = application_paths(), - Pins = pin_store(Paths), - put({?MODULE, store_pins}, Pins), - Mutable = [ - {App, Ebin} - || {App, Ebin} <- Paths, - not lists:keymember(store_root(Ebin), 1, Pins) - ], - %% The worker drops its file lists before readiness. - Parent = self(), - {Pid, Ref} = spawn_monitor(fun() -> - Result = - try - snapshot(Cache, Mutable) - catch - Class:Reason -> {error, {Class, Reason}} - end, - Parent ! {self(), Result} - end), - Outcome = - receive - {Pid, Value} -> - erlang:demonitor(Ref, [flush]), - Value; - {'DOWN', Ref, process, Pid, Failure} -> - {error, Failure} - end, - case Outcome of - ok -> - persistent_term:put({?MODULE, cache}, Cache); - {error, Reason} -> - true = code:set_path(OriginalPaths), - _ = file:del_dir_r(Cache), - io:format("code snapshot: ~0p; falling back to preload~n", [Reason]) - end - end, - nil. - -cleanup() -> - case persistent_term:get({?MODULE, cache}, undefined) of - undefined -> - ok; - Cache -> - _ = file:del_dir_r(Cache), - ok - end. - -start() -> - case {os:getenv("ALBEDO_PRELOAD"), persistent_term:get({?MODULE, cache}, undefined)} of - {"0", _} -> - persistent_term:put({?MODULE, preloaded}, {ok, 0}); - {_, Cache} when Cache =/= undefined -> - persistent_term:put({?MODULE, preloaded}, {ok, 0}), - _ = spawn_opt(fun warm/0, [{priority, low}]); - _ -> - _ = spawn(fun() -> - Outcome = - try - preload() - catch - Class:Reason -> - {error, - iolist_to_binary( - io_lib:format("preload failed: ~p:~0p", [Class, Reason]) - )} - end, - case Outcome of - {ok, _} -> ok; - {error, Detail} -> io:format("code preload: ~ts~n", [Detail]) - end, - persistent_term:put({?MODULE, preloaded}, Outcome) - end) - end, - nil. - -%% Generated by test/manual/record_boot_modules.py from text turns on both protocols. -warm() -> - Path = filename:join(albedo_priv:dir(), "boot-modules.txt"), - case file:read_file(Path) of - {ok, Bytes} -> - Modules = [ - binary_to_atom(Name) - || Name <- binary:split(Bytes, <<"\n">>, [global]), Name =/= <<>> - ], - persistent_term:put({?MODULE, warmed}, warm_batches(Modules, [])); - _ -> - ok - end. - -%% A module that will not load (renamed or removed since the manifest was -%% recorded) is logged and skipped; the rest of the manifest still loads. -warm_batches([], Skipped) -> - {ok, lists:reverse(Skipped)}; -warm_batches(Modules, Skipped) -> - {Batch, Rest} = lists:split(min(2, length(Modules)), Modules), - Failed = - case code:ensure_modules_loaded(Batch) of - ok -> []; - {error, Errors} -> Errors - end, - [io:format("code warm: skipped ~ts: ~0p~n", [Module, Reason]) || {Module, Reason} <- Failed], - erlang:yield(), - warm_batches(Rest, [Module || {Module, _} <- Failed] ++ Skipped). - -application_paths() -> - [ - {list_to_atom(filename:basename(AppFile, ".app")), Ebin} - || Ebin <- code:get_path(), - AppFile <- filelib:wildcard(filename:join(Ebin, "*.app")) - ]. - -store_root(Path) -> - case filename:split(Path) of - ["/", "nix", "store", Root | _] -> filename:join(["/nix/store", Root]); - _ -> none - end. - -%% One open file per store root makes Nix's runtime GC-root scan retain it. -%% Raw descriptors belong to the daemon's main process, not the copy worker. -pin_store(Paths) -> - Roots = maps:from_list([ - {Root, filename:join(Ebin, atom_to_list(App) ++ ".app")} - || {App, Ebin} <- Paths, Root <- [store_root(Ebin)], Root =/= none - ]), - lists:filtermap( - fun({Root, Path}) -> - case file:open(Path, [read, raw, binary]) of - {ok, File} -> {true, {Root, File}}; - {error, _} -> false - end - end, - maps:to_list(Roots) - ). - -snapshot(Cache, Paths) -> - case clone_paths(Cache, Paths) of - {ok, Cloned} -> - publish_paths(Cloned); - error -> - _ = file:del_dir_r(Cache), - copy_paths(Cache, Paths) - end. - -clone_paths(_Cache, []) -> - {ok, []}; -clone_paths(Cache, Paths) -> - case {os:type(), os:find_executable("python3")} of - {{unix, darwin}, Python} when Python =/= false -> - Roots = lists:usort([clone_root(Ebin, Cache) || {_, Ebin} <- Paths]), - Numbered = lists:zip(lists:seq(1, length(Roots)), Roots), - Targets = maps:from_list([ - {Root, filename:join([Cache, integer_to_list(N), filename:basename(Root)])} - || {N, Root} <- Numbered - ]), - lists:foreach(fun(Target) -> ok = filelib:ensure_dir(Target) end, maps:values(Targets)), - Script = - "import ctypes, os, sys\n" - "clone = ctypes.CDLL('/usr/lib/libSystem.B.dylib').clonefile\n" - "for source, destination in zip(sys.argv[1::2], sys.argv[2::2]):\n" - " if clone(os.fsencode(source), os.fsencode(destination), 0) != 0:\n" - " raise SystemExit(1)\n", - Arguments = lists:append([[Root, maps:get(Root, Targets)] || Root <- Roots]), - Port = open_port({spawn_executable, Python}, [ - binary, - exit_status, - hide, - {args, ["-I", "-S", "-c", Script | Arguments]}, - use_stdio, - stderr_to_stdout - ]), - case clone_result(Port) of - ok -> {ok, [{App, cloned_path(Ebin, Cache, Targets)} || {App, Ebin} <- Paths]}; - error -> error - end; - _ -> - error - end. - -cloned_path(Ebin, Cache, Targets) -> - Root = clone_root(Ebin, Cache), - Relative = lists:nthtail(length(filename:split(Root)), filename:split(Ebin)), - filename:join([maps:get(Root, Targets) | Relative]). - -clone_root(Ebin, Cache) -> - Root = filename:dirname(filename:dirname(Ebin)), - case lists:prefix(filename:split(Root), filename:split(Cache)) of - true -> filename:dirname(Ebin); - false -> Root - end. - -clone_result(Port) -> - receive - {Port, {data, _}} -> clone_result(Port); - {Port, {exit_status, 0}} -> ok; - {Port, {exit_status, _}} -> error - after 60_000 -> - port_close(Port), - error - end. - -publish_paths(Paths) -> - Replacements = maps:from_list([ - {filename:join(code:lib_dir(App), "ebin"), Ebin} - || {App, Ebin} <- Paths - ]), - true = code:set_path([maps:get(Path, Replacements, Path) || Path <- code:get_path()]), - ok. - -copy_paths(Cache, Paths) -> - %% Publish paths only after the complete snapshot exists. A failed copy - %% leaves every original path intact for the preload fallback. - Workers = [spawn_monitor(fun() -> snapshot_app(App, Ebin, Cache) end) || {App, Ebin} <- Paths], - Outcomes = [ - receive - {'DOWN', Ref, process, Pid, normal} -> ok; - {'DOWN', Ref, process, Pid, Reason} -> {error, Reason} - end - || {Pid, Ref} <- Workers - ], - case [Reason || {error, Reason} <- Outcomes] of - [] -> ok; - Errors -> error({snapshot_failed, Errors}) - end, - publish_paths([{App, filename:join([Cache, atom_to_list(App), "ebin"])} || {App, _} <- Paths]). - -snapshot_app(App, Ebin, Cache) -> - Destination = filename:join([Cache, atom_to_list(App), "ebin"]), - ok = filelib:ensure_dir(filename:join(Destination, ".keep")), - Installed = lists:prefix(code:root_dir(), Ebin), - lists:foreach( - fun(Source) -> - Target = filename:join(Destination, filename:basename(Source)), - case Installed andalso file:make_link(Source, Target) =:= ok of - true -> ok; - false -> {ok, _} = file:copy({Source, [raw]}, {Target, [raw]}) - end - end, - filelib:wildcard(filename:join(Ebin, "*.beam")) ++ - filelib:wildcard(filename:join(Ebin, "*.app")) - ), - Priv = filename:join(filename:dirname(Ebin), "priv"), - case filelib:is_dir(Priv) of - true -> ok = file:make_symlink(Priv, filename:join(filename:dirname(Destination), "priv")); - false -> ok - end. - -%% {ok, Count} once every reachable module is loaded, or {error, Detail} naming -%% the modules that would not load (each one still fails only when called). -preload() -> - Index = index(), - Apps = close([], [albedo], Index), - Reachable = - beams(filename:join(code:lib_dir(albedo), "ebin")) ++ - lists:append([app_modules(App) || App <- Apps]), - Modules = lists:usort( - case os:getenv("ALBEDO_PRELOAD") of - "1" -> Reachable; - _ -> Reachable ++ lists:append([beams(Ebin) || {_, Ebin} <- application_paths()]) - end - ), - case code:ensure_modules_loaded(Modules) of - ok -> - {ok, length(Modules)}; - {error, Failed} -> - Names = lists:join(<<", ">>, [ - atom_to_binary(Module) - || {Module, _} <- lists:sublist(Failed, 10) - ]), - {error, - iolist_to_binary([ - integer_to_binary(length(Failed)), <<" modules did not preload: ">>, Names - ])} - end. - -%% Loads every module of these applications now. A module that will not load -%% still fails only when it is called, as it would lazily. -load_applications(Names) -> - _ = code:ensure_modules_loaded( - lists:append([app_modules(binary_to_atom(Name)) || Name <- Names]) - ), - nil. - -%% True once the Erlang install this node was started from is gone. -runtime_removed() -> - not filelib:is_dir(filename:join(code:root_dir(), "lib")). - -%% The applications reachable from the daemon: declared dependencies and the -%% owners of every module an application's code imports. Build tools on the -%% code path (Elixir, Mix) stay out unless something calls into them. -close(Done, [], _Index) -> - lists:reverse(Done); -close(Done, [App | Rest], Index) -> - case lists:member(App, Done) of - true -> - close(Done, Rest, Index); - false -> - Declared = app_key(App, applications) ++ app_key(App, included_applications), - Called = [ - Owner - || Module <- app_modules(App), - Imported <- imports(Module), - {ok, Owner} <- [maps:find(Imported, Index)] - ], - close([App | Done], Rest ++ lists:usort(Declared ++ Called), Index) - end. - -imports(Module) -> - case code:where_is_file(atom_to_list(Module) ++ ".beam") of - non_existing -> - []; - File -> - case beam_lib:chunks(File, [imports]) of - {ok, {_, [{imports, Imports}]}} -> lists:usort([M || {M, _, _} <- Imports]); - _ -> [] - end - end. - -%% Module => application for every application directory on the code path. -index() -> - maps:from_list([ - {list_to_atom(filename:basename(Beam, ".beam")), App} - || Dir <- code:get_path(), - AppFile <- filelib:wildcard(filename:join(Dir, "*.app")), - App <- [list_to_atom(filename:basename(AppFile, ".app"))], - Beam <- filelib:wildcard(filename:join(Dir, "*.beam")) - ]). - -app_modules(App) -> app_key(App, modules). - -app_key(App, Key) -> - _ = application:load(App), - case application:get_key(App, Key) of - {ok, Values} -> Values; - undefined -> [] - end. - -beams(Dir) -> - [ - list_to_atom(filename:basename(Beam, ".beam")) - || Beam <- filelib:wildcard(filename:join(Dir, "*.beam")) - ]. +cleanup() -> 'albedo@daemon@boot_code':cleanup(). diff --git a/src/albedo/daemon/boot_code.gleam b/src/albedo/daemon/boot_code.gleam new file mode 100644 index 000000000..998915276 --- /dev/null +++ b/src/albedo/daemon/boot_code.gleam @@ -0,0 +1,760 @@ +//// Preserve boot-time bytecode without eagerly loading the whole code path. +//// OTP installs can disappear during upgrades, and checkout beams can be +//// rebuilt under a running daemon. +//// +//// Code paths stay character lists, as the code server keeps them. + +import albedo/daemon/port_program +import albedo/harness/sdk/getenv +import albedo/harness/sdk/protect +import albedo/harness/sdk/term +import gleam/dict +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/erlang/atom.{type Atom} +import gleam/erlang/charlist.{type Charlist} +import gleam/erlang/process +import gleam/int +import gleam/io +import gleam/list +import gleam/option.{Some} +import gleam/result +import gleam/string + +/// The keys `{albedo_code, Name}` of this module's persistent terms and +/// process dictionary entry. +type Key { + AlbedoCode(name: Atom) +} + +fn key(name: String) -> Key { + AlbedoCode(atom.create(name)) +} + +/// Snapshot the mutable application directories under `home`'s `code-cache` +/// and point the code path at the copies, so a rebuilt checkout does not +/// change code this daemon loads later. Directories in a pinned Nix store +/// root stay where they are. A failed snapshot restores the original path +/// and leaves preloading to `start`. +pub fn prepare(home: String) -> Nil { + priv_pin() + let original = get_path() + let cache = join(characters_to_list(home), charlist.from_string("code-cache")) + let _ = del_dir_r(cache) + case getenv.lookup("ALBEDO_PRELOAD") { + Some("0") | Some("1") -> Nil + _ -> { + let paths = application_paths() + let pins = pin_store(paths) + let _ = put(key("store_pins"), pins) + let pinned = list.map(pins, fn(pin) { pin.0 }) + let mutable = + list.filter(paths, fn(path) { + case store_root(path.1) { + Ok(root) -> !list.contains(pinned, root) + Error(Nil) -> True + } + }) + // The worker drops its file lists before readiness. + case in_worker(fn() { snapshot(cache, mutable) }) { + Ok(Nil) -> { + let _ = put_term(key("cache"), cache) + Nil + } + Error(reason) -> { + let assert True = set_path(original) as "code path not restored" + let _ = del_dir_r(cache) + io.println("code snapshot: " <> reason <> "; falling back to preload") + } + } + } + } +} + +/// Remove this daemon's code snapshot, if it made one. +pub fn cleanup() -> Nil { + case cache() { + Ok(cache) -> { + let _ = del_dir_r(cache) + Nil + } + Error(Nil) -> Nil + } +} + +fn cache() -> Result(Charlist, Nil) { + let found = get_term(key("cache"), undefined()) + case found == undefined() { + True -> Error(Nil) + False -> Ok(unsafe_charlist(found)) + } +} + +/// Load code once the daemon is ready. With a snapshot, warm the modules a +/// first turn needs at low priority. Without one, preload every reachable +/// module, so an install removed later cannot take them away. +pub fn start() -> Nil { + let preloaded = key("preloaded") + case getenv.lookup("ALBEDO_PRELOAD"), cache() { + Some("0"), _ -> { + let _ = put_term(preloaded, Ok(0)) + Nil + } + _, Ok(_) -> { + let _ = put_term(preloaded, Ok(0)) + let _ = spawn_opt(warm, [Priority(Low)]) + Nil + } + _, Error(Nil) -> { + process.spawn_unlinked(fn() { + let outcome = case protect.attempt(preload) { + Ok(outcome) -> outcome + Error(crash) -> Error("preload failed: " <> crash) + } + case outcome { + Ok(_) -> Nil + Error(detail) -> io.println("code preload: " <> detail) + } + let _ = put_term(preloaded, outcome) + Nil + }) + Nil + } + } +} + +/// Load the modules in `boot-modules.txt`, generated by +/// test/manual/record_boot_modules.py from text turns on both protocols. A +/// module that will not load, renamed or removed since the manifest was +/// recorded, is logged and skipped. The rest of the manifest still loads. +fn warm() -> Nil { + let path = join(priv_dir(), charlist.from_string("boot-modules.txt")) + case read_file(path) { + Ok(text) -> { + let modules = + text + |> string.split("\n") + |> list.filter(fn(name) { name != "" }) + |> list.map(atom.create) + let _ = put_term(key("warmed"), warm_batches(modules, [])) + Nil + } + Error(_) -> Nil + } +} + +fn warm_batches( + modules: List(Atom), + skipped: List(Atom), +) -> Result(List(Atom), Nil) { + case modules { + [] -> Ok(list.reverse(skipped)) + _ -> { + let #(batch, rest) = list.split(modules, 2) + let failed = ensure_loaded(batch) + list.each(failed, fn(failure) { + io.println( + "code warm: skipped " + <> atom.to_string(failure.0) + <> ": " + <> reason_text(failure.1), + ) + }) + yield() + warm_batches( + rest, + list.append(list.map(failed, fn(failure) { failure.0 }), skipped), + ) + } + } +} + +/// `Ok(count)` once every reachable module is loaded, or an error naming the +/// modules that would not load. Each of those still fails only when called. +pub fn preload() -> Result(Int, String) { + let index = index() + let apps = close([], [atom.create("albedo")], index) + let reachable = + list.append( + beams(join(lib_dir(atom.create("albedo")), charlist.from_string("ebin"))), + list.flat_map(apps, app_modules), + ) + let modules = + case getenv.lookup("ALBEDO_PRELOAD") { + Some("1") -> reachable + _ -> + list.append( + reachable, + list.flat_map(application_paths(), fn(path) { beams(path.1) }), + ) + } + |> term.unique_sorted + case ensure_loaded(modules) { + [] -> Ok(list.length(modules)) + failed -> { + let names = + failed + |> list.take(10) + |> list.map(fn(failure) { atom.to_string(failure.0) }) + |> string.join(", ") + Error( + int.to_string(list.length(failed)) + <> " modules did not preload: " + <> names, + ) + } + } +} + +/// Load every module of these applications now. A module that will not load +/// still fails only when it is called, as it would lazily. +pub fn load_applications(names: List(String)) -> Nil { + let _ = + names + |> list.flat_map(fn(name) { app_modules(atom.create(name)) }) + |> ensure_loaded + Nil +} + +/// Whether the Erlang install this node was started from is gone. +pub fn runtime_removed() -> Bool { + !is_dir(join(root_dir(), charlist.from_string("lib"))) +} + +// ---- snapshot ------------------------------------------------------------------- + +/// Every application directory on the code path, as `#(App, Ebin)`. +fn application_paths() -> List(#(Atom, Charlist)) { + list.flat_map(get_path(), fn(ebin) { + wildcard(join(ebin, charlist.from_string("*.app"))) + |> list.map(fn(file) { #(application_name(file, ".app"), ebin) }) + }) +} + +fn application_name(file: Charlist, extension: String) -> Atom { + list_to_atom(basename(file, charlist.from_string(extension))) +} + +fn store_root(path: Charlist) -> Result(Charlist, Nil) { + case list.map(split(path), charlist.to_string) { + ["/", "nix", "store", root, ..] -> + Ok(join(charlist.from_string("/nix/store"), charlist.from_string(root))) + _ -> Error(Nil) + } +} + +/// One open file per store root makes Nix's runtime GC-root scan retain it. +/// Raw descriptors belong to the daemon's main process, not the copy worker. +fn pin_store(paths: List(#(Atom, Charlist))) -> List(#(Charlist, File)) { + paths + |> list.filter_map(fn(path) { + store_root(path.1) + |> result.map(fn(root) { + #( + root, + join(path.1, charlist.from_string(atom.to_string(path.0) <> ".app")), + ) + }) + }) + |> dict.from_list + |> dict.to_list + |> list.filter_map(fn(entry) { + open(entry.1, [Read, Raw, Binary]) + |> result.map(fn(file) { #(entry.0, file) }) + |> result.replace_error(Nil) + }) +} + +/// Run `work` in a new process and answer its result. A crash is an error. +fn in_worker(work: fn() -> Result(a, String)) -> Result(a, String) { + let reply = process.new_subject() + let worker = + process.spawn_unlinked(fn() { + process.send(reply, case protect.attempt(work) { + Ok(result) -> result + Error(crash) -> Error(crash) + }) + }) + let monitor = process.monitor(worker) + let outcome = + process.new_selector() + |> process.select(reply) + |> process.select_specific_monitor(monitor, fn(down) { + Error(string.inspect(down)) + }) + |> process.selector_receive_forever + process.demonitor_process(monitor) + outcome +} + +fn snapshot( + cache: Charlist, + paths: List(#(Atom, Charlist)), +) -> Result(Nil, String) { + case clone_paths(cache, paths) { + Ok(cloned) -> publish_paths(cloned) + Error(Nil) -> { + let _ = del_dir_r(cache) + copy_paths(cache, paths) + } + } +} + +/// On macOS, clone each directory tree in one call per root. Elsewhere, or +/// when cloning fails, the caller copies instead. +fn clone_paths( + cache: Charlist, + paths: List(#(Atom, Charlist)), +) -> Result(List(#(Atom, Charlist)), Nil) { + let python = case os_type() { + #(_, family) -> + case atom.to_string(family) { + "darwin" -> port_program.find_executable("python3") + _ -> Error(Nil) + } + } + case paths, python { + [], _ -> Ok([]) + _, Ok(python) -> { + let roots = + term.unique_sorted( + list.map(paths, fn(path) { clone_root(path.1, cache) }), + ) + let targets = + roots + |> list.index_map(fn(root, index) { + #( + root, + join_all([ + cache, + charlist.from_string(int.to_string(index + 1)), + basename_only(root), + ]), + ) + }) + |> dict.from_list + dict.each(targets, fn(_, target) { + let assert True = ensure_parent(target) == ok() as "clone target" + Nil + }) + let arguments = + list.flat_map(roots, fn(root) { + let assert Ok(target) = dict.get(targets, root) + [charlist.to_string(root), charlist.to_string(target)] + }) + let port = + port_program.open(python, [ + port_program.Binary, + port_program.ExitStatus, + port_program.Hide, + port_program.Args(["-I", "-S", "-c", clone_script, ..arguments]), + port_program.UseStdio, + port_program.StderrToStdout, + ]) + case port_program.collect(port, 60_000) { + Ok(#(0, _)) -> + Ok( + list.map(paths, fn(path) { + #(path.0, cloned_path(path.1, cache, targets)) + }), + ) + _ -> Error(Nil) + } + } + _, Error(Nil) -> Error(Nil) + } +} + +const clone_script = + "import ctypes, os, sys +clone = ctypes.CDLL('/usr/lib/libSystem.B.dylib').clonefile +for source, destination in zip(sys.argv[1::2], sys.argv[2::2]): + if clone(os.fsencode(source), os.fsencode(destination), 0) != 0: + raise SystemExit(1) +" + +fn cloned_path( + ebin: Charlist, + cache: Charlist, + targets: dict.Dict(Charlist, Charlist), +) -> Charlist { + let root = clone_root(ebin, cache) + let assert Ok(target) = dict.get(targets, root) + let relative = list.drop(split(ebin), list.length(split(root))) + join_all([target, ..relative]) +} + +/// The directory a clone copies for `ebin`: its application's parent, unless +/// that parent holds the cache itself. +fn clone_root(ebin: Charlist, cache: Charlist) -> Charlist { + let root = dirname(dirname(ebin)) + case is_prefix(split(root), split(cache)) { + True -> dirname(ebin) + False -> root + } +} + +fn publish_paths(paths: List(#(Atom, Charlist))) -> Result(Nil, String) { + let replacements = + paths + |> list.map(fn(path) { + #(join(lib_dir(path.0), charlist.from_string("ebin")), path.1) + }) + |> dict.from_list + let published = + list.map(get_path(), fn(path) { + dict.get(replacements, path) |> result.unwrap(path) + }) + let assert True = set_path(published) as "code path not published" + Ok(Nil) +} + +/// Publish paths only after the complete snapshot exists. A failed copy +/// leaves every original path intact for the preload fallback. +fn copy_paths( + cache: Charlist, + paths: List(#(Atom, Charlist)), +) -> Result(Nil, String) { + let failures = + paths + |> list.map(fn(path) { + let reply = process.new_subject() + let worker = + process.spawn_unlinked(fn() { + snapshot_app(path.0, path.1, cache) + process.send(reply, Nil) + }) + #(reply, process.monitor(worker)) + }) + |> list.filter_map(fn(worker) { + let #(reply, monitor) = worker + let outcome = + process.new_selector() + |> process.select_map(reply, fn(_) { Ok(Nil) }) + |> process.select_specific_monitor(monitor, fn(down) { Error(down) }) + |> process.selector_receive_forever + process.demonitor_process(monitor) + case outcome { + Ok(Nil) -> Error(Nil) + Error(down) -> Ok(string.inspect(down)) + } + }) + case failures { + [] -> + paths + |> list.map(fn(path) { #(path.0, app_ebin(cache, path.0)) }) + |> publish_paths + _ -> Error("snapshot_failed: " <> string.join(failures, ", ")) + } +} + +fn app_ebin(cache: Charlist, app: Atom) -> Charlist { + join_all([ + cache, + charlist.from_string(atom.to_string(app)), + charlist.from_string("ebin"), + ]) +} + +fn snapshot_app(app: Atom, ebin: Charlist, cache: Charlist) -> Nil { + let destination = app_ebin(cache, app) + let assert True = + ensure_parent(join(destination, charlist.from_string(".keep"))) == ok() + as "snapshot directory not made" + let installed = lists_prefix(root_dir(), ebin) + list.append( + wildcard(join(ebin, charlist.from_string("*.beam"))), + wildcard(join(ebin, charlist.from_string("*.app"))), + ) + |> list.each(fn(source) { + let target = join(destination, basename_only(source)) + case installed && make_link(source, target) == ok() { + True -> Nil + False -> { + let assert Ok(_) = copy_raw(#(source, [Raw]), #(target, [Raw])) + as "beam not copied" + Nil + } + } + }) + let priv = join(dirname(ebin), charlist.from_string("priv")) + case is_dir(priv) { + True -> { + let assert True = + make_symlink( + priv, + join(dirname(destination), charlist.from_string("priv")), + ) + == ok() + as "priv not linked" + Nil + } + False -> Nil + } +} + +// ---- reachable applications ----------------------------------------------------- + +/// The applications reachable from the daemon: declared dependencies and the +/// owners of every module an application's code imports. Build tools on the +/// code path, such as Elixir and Mix, stay out unless something calls into +/// them. +fn close( + done: List(Atom), + pending: List(Atom), + index: dict.Dict(Atom, Atom), +) -> List(Atom) { + case pending { + [] -> list.reverse(done) + [app, ..rest] -> + case list.contains(done, app) { + True -> close(done, rest, index) + False -> { + let declared = + list.append( + app_key(app, "applications"), + app_key(app, "included_applications"), + ) + let called = + app_modules(app) + |> list.flat_map(imports) + |> list.filter_map(fn(module) { dict.get(index, module) }) + close( + [app, ..done], + list.append(rest, term.unique_sorted(list.append(declared, called))), + index, + ) + } + } + } +} + +fn imports(module: Atom) -> List(Atom) { + let file = + where_is_file(charlist.from_string(atom.to_string(module) <> ".beam")) + case decode.run(file, decode.list(decode.int)) { + Error(_) -> [] + Ok(_) -> + case + beam_chunks(unsafe_charlist(file), [atom.create("imports")]) + |> decode.run(imports_chunk()) + { + Ok(imported) -> term.unique_sorted(imported) + Error(_) -> [] + } + } +} + +/// The modules of `{ok, {_, [{imports, [{M, F, A}]}]}}`. +fn imports_chunk() -> decode.Decoder(List(Atom)) { + decode.at( + [1, 1], + decode.list(decode.at([1], decode.list(decode.at([0], atom.decoder())))), + ) + |> decode.map(list.flatten) +} + +/// Module to application for every application directory on the code path. +fn index() -> dict.Dict(Atom, Atom) { + get_path() + |> list.flat_map(fn(directory) { + wildcard(join(directory, charlist.from_string("*.app"))) + |> list.flat_map(fn(app_file) { + let app = application_name(app_file, ".app") + wildcard(join(directory, charlist.from_string("*.beam"))) + |> list.map(fn(beam) { #(application_name(beam, ".beam"), app) }) + }) + }) + |> dict.from_list +} + +fn app_modules(app: Atom) -> List(Atom) { + app_key(app, "modules") +} + +fn app_key(app: Atom, name: String) -> List(Atom) { + let _ = load_application(app) + get_key(app, atom.create(name)) + |> decode.run(decode.at([1], decode.list(atom.decoder()))) + |> result.unwrap([]) +} + +fn beams(directory: Charlist) -> List(Atom) { + wildcard(join(directory, charlist.from_string("*.beam"))) + |> list.map(fn(beam) { application_name(beam, ".beam") }) +} + +/// The modules that would not load, with why. +fn ensure_loaded(modules: List(Atom)) -> List(#(Atom, Dynamic)) { + let answer = ensure_modules_loaded(modules) + case answer == ok() { + True -> [] + False -> + answer + |> decode.run(decode.at( + [1], + decode.list({ + use module <- decode.field(0, atom.decoder()) + use reason <- decode.field(1, decode.dynamic) + decode.success(#(module, reason)) + }), + )) + |> result.unwrap([]) + } +} + +fn is_prefix(prefix: List(a), whole: List(a)) -> Bool { + case prefix, whole { + [], _ -> True + [first, ..prefix], [next, ..whole] if first == next -> + is_prefix(prefix, whole) + _, _ -> False + } +} + +fn ok() -> Dynamic { + atom.to_dynamic(atom.create("ok")) +} + +fn undefined() -> Dynamic { + atom.to_dynamic(atom.create("undefined")) +} + +/// An atom reason as Erlang prints it, or any other term inspected. +fn reason_text(reason: Dynamic) -> String { + case decode.run(reason, atom.decoder()) { + Ok(name) -> atom.to_string(name) + Error(_) -> string.inspect(reason) + } +} + +fn join_all(parts: List(Charlist)) -> Charlist { + join_list(parts) +} + +type File + +type Mode { + Read + Raw + Binary +} + +type SpawnOption { + Priority(Level) +} + +type Level { + Low +} + +@external(erlang, "albedo_priv", "pin") +fn priv_pin() -> Dynamic + +@external(erlang, "albedo_priv", "dir") +fn priv_dir() -> Charlist + +@external(erlang, "code", "get_path") +fn get_path() -> List(Charlist) + +@external(erlang, "code", "set_path") +fn set_path(paths: List(Charlist)) -> Bool + +@external(erlang, "code", "lib_dir") +fn lib_dir(app: Atom) -> Charlist + +@external(erlang, "code", "root_dir") +fn root_dir() -> Charlist + +@external(erlang, "code", "where_is_file") +fn where_is_file(name: Charlist) -> Dynamic + +@external(erlang, "code", "ensure_modules_loaded") +fn ensure_modules_loaded(modules: List(Atom)) -> Dynamic + +@external(erlang, "beam_lib", "chunks") +fn beam_chunks(file: Charlist, chunks: List(Atom)) -> Dynamic + +@external(erlang, "application", "load") +fn load_application(app: Atom) -> Dynamic + +@external(erlang, "application", "get_key") +fn get_key(app: Atom, key: Atom) -> Dynamic + +@external(erlang, "unicode", "characters_to_list") +fn characters_to_list(text: String) -> Charlist + +@external(erlang, "filename", "join") +fn join(directory: Charlist, name: Charlist) -> Charlist + +@external(erlang, "filename", "join") +fn join_list(parts: List(Charlist)) -> Charlist + +@external(erlang, "filename", "split") +fn split(path: Charlist) -> List(Charlist) + +@external(erlang, "filename", "dirname") +fn dirname(path: Charlist) -> Charlist + +@external(erlang, "filename", "basename") +fn basename(path: Charlist, extension: Charlist) -> Charlist + +@external(erlang, "filename", "basename") +fn basename_only(path: Charlist) -> Charlist + +@external(erlang, "filelib", "wildcard") +fn wildcard(pattern: Charlist) -> List(Charlist) + +@external(erlang, "filelib", "is_dir") +fn is_dir(path: Charlist) -> Bool + +@external(erlang, "filelib", "ensure_dir") +fn ensure_parent(path: Charlist) -> Dynamic + +@external(erlang, "file", "del_dir_r") +fn del_dir_r(path: Charlist) -> Dynamic + +@external(erlang, "file", "open") +fn open(path: Charlist, modes: List(Mode)) -> Result(File, Dynamic) + +@external(erlang, "file", "read_file") +fn read_file(path: Charlist) -> Result(String, Dynamic) + +@external(erlang, "file", "make_link") +fn make_link(existing: Charlist, new: Charlist) -> Dynamic + +@external(erlang, "file", "make_symlink") +fn make_symlink(existing: Charlist, new: Charlist) -> Dynamic + +@external(erlang, "file", "copy") +fn copy_raw( + source: #(Charlist, List(Mode)), + target: #(Charlist, List(Mode)), +) -> Result(Int, Dynamic) + +@external(erlang, "os", "type") +fn os_type() -> #(Atom, Atom) + +@external(erlang, "lists", "prefix") +fn lists_prefix(prefix: Charlist, whole: Charlist) -> Bool + +@external(erlang, "erlang", "list_to_atom") +fn list_to_atom(name: Charlist) -> Atom + +@external(erlang, "erlang", "put") +fn put(key: Key, value: a) -> Dynamic + +@external(erlang, "persistent_term", "put") +fn put_term(key: Key, value: a) -> Dynamic + +@external(erlang, "persistent_term", "get") +fn get_term(key: Key, default: Dynamic) -> Dynamic + +@external(erlang, "erlang", "spawn_opt") +fn spawn_opt(run: fn() -> Nil, options: List(SpawnOption)) -> process.Pid + +@external(erlang, "erlang", "yield") +fn yield() -> Bool + +@external(erlang, "gleam_stdlib", "identity") +fn unsafe_charlist(value: Dynamic) -> Charlist diff --git a/src/albedo/daemon/lifecycle.gleam b/src/albedo/daemon/lifecycle.gleam index 2236df7c0..ef3b68f63 100644 --- a/src/albedo/daemon/lifecycle.gleam +++ b/src/albedo/daemon/lifecycle.gleam @@ -1,6 +1,7 @@ //// The daemon process on its host: home and token defaults, the //// `daemon.json` record, loopback ports, the parent watch, and the halt. +import albedo/daemon/boot_code import albedo/daemon/build_identity import albedo/daemon/port_program import albedo/harness/sdk/digest @@ -232,7 +233,7 @@ pub fn watch_parent(parent: String) -> Nil { <> int.to_string(status), ) } - code_cleanup() + boot_code.cleanup() init_stop() }) Nil @@ -250,13 +251,15 @@ pub fn watch_parent(parent: String) -> Nil { /// `cpu_sup` is stopped first, which tells its port program to quit. /// Otherwise the program reports the VM's disappearance into the log. pub fn shutdown() -> Nil { - code_cleanup() - let _ = - protect.attempt(fn() { - terminate_child(atom.create("os_mon_sup"), atom.create("cpu_sup")) - }) + // Built before the snapshot goes: a module first loaded after cleanup + // would have no code path left to load from. + let supervisor = atom.create("os_mon_sup") + let child = atom.create("cpu_sup") + let handler_id = std_handler() + boot_code.cleanup() + let _ = protect.attempt(fn() { terminate_child(supervisor, child) }) list.each(handler_config(), fn(handler) { - case decode.run(handler, std_handler()) { + case decode.run(handler, handler_id) { Ok(id) -> { let _ = filesync(id) Nil @@ -385,9 +388,6 @@ fn handler_config() -> List(Dynamic) @external(erlang, "logger_std_h", "filesync") fn filesync(id: Dynamic) -> Dynamic -@external(erlang, "albedo_code", "cleanup") -fn code_cleanup() -> Nil - @external(erlang, "albedo_standby", "flush") fn standby_flush() -> Nil diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index 1211aba80..8110d6e17 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -2,6 +2,7 @@ import albedo/clock import albedo/daemon/acp_attachments import albedo/daemon/active_output import albedo/daemon/api_digest +import albedo/daemon/boot_code import albedo/daemon/build_identity import albedo/daemon/bus import albedo/daemon/command_state @@ -171,7 +172,7 @@ pub fn start( HttpBoundary(instance_id, configured_list("ALBEDO_HTTP_ORIGINS")) // Load the listener's code before its start is timed: under load, finding // and committing each cold module can take hundreds of ms. - load_applications(["mist", "glisten", "gleam_http", "gleam_otp"]) + boot_code.load_applications(["mist", "glisten", "gleam_http", "gleam_otp"]) // A restarted listener comes back on the port it was built with, so port 0 // would bring it back somewhere daemon.json does not say: pick a concrete port. use port <- result.try( @@ -925,7 +926,7 @@ pub fn main() -> Nil { lifecycle.refuse_home(home) Error(error) -> panic as error.message } - startup.measure("preserve code", fn() { preserve_code(home) }) + startup.measure("preserve code", fn() { boot_code.prepare(home) }) // A fixed port gives services such as the proxy a stable base url. let #(port, webhook_port) = case start( @@ -946,7 +947,7 @@ pub fn main() -> Nil { lifecycle.ready(home, port, webhook_port, token) }) // A failed disk snapshot falls back to background preloading. - preload_code() + boot_code.start() lifecycle.watch_parent(lifecycle.env("ALBEDO_PARENT_PID")) process.sleep_forever() } @@ -1000,18 +1001,6 @@ fn inspect(home: String) -> Nil @external(erlang, "albedo_stalls", "start") fn watch_stalls() -> process.Pid -@external(erlang, "albedo_code", "prepare") -fn preserve_code(home: String) -> Nil - -@external(erlang, "albedo_code", "start") -fn preload_code() -> Nil - -@external(erlang, "albedo_code", "load_applications") -fn load_applications(names: List(String)) -> Nil - -@external(erlang, "albedo_code", "runtime_removed") -fn runtime_removed() -> Bool - fn protocol_method(path: List(String)) -> response.Response(mist.ResponseData) { let methods = case path { ["server"] @@ -1077,7 +1066,7 @@ fn protocol_method(path: List(String)) -> response.Response(mist.ResponseData) { /// so dismissing it for one daemon leaves it visible for the next one in the /// same state. fn server_notices(instance_id: String) -> List(#(String, String, String)) { - let removed = case runtime_removed() { + let removed = case boot_code.runtime_removed() { True -> [ #( "runtime-removed-" <> instance_id, -- knotmirror 0.0.1