Add orbit self-update to replace the running binary
Rolling Release / build (push) Successful in 1m58s
Rolling Release / publish (push) Successful in 10s

- `orbit self-update [constraint]` replaces the running orbit with the newest `orbit` package in its channel, or one matching a constraint (which may downgrade).
- The new build must print its version before it is renamed over the old binary.
- An orbit installed as a global package is upgraded instead, keeping rollback.
- `orbit upgrade orbit` does the same when orbit isn't installed as a package.
- Read `/proc/self/exe` through a new C stub; document in README; mock-registry test.
This commit is contained in:
nandi committed 2026-12-02 13:32:29 -08:00
1 parent f14a1900af
commit d3b1dedeb5
7 files changed
+293 -2

No files matched your search

+27 -1
View File
@@ -15,6 +15,7 @@ A small package manager written in MoonBit that uses any OCI registry (Gitea, GH
- **Conflicts:** packages can declare that they can't be installed together, and a global install offers to replace the one in the way. - **Conflicts:** packages can declare that they can't be installed together, and a global install offers to replace the one in the way.
- **Upgrade and rollback:** global installs keep the previous two builds, and `orbit rollback <name>` switches back instantly with no network. - **Upgrade and rollback:** global installs keep the previous two builds, and `orbit rollback <name>` switches back instantly with no network.
- **Remove:** `orbit remove` refuses to delete what other global packages need and autoremoves orphaned dependencies; in projects it updates `orbit.toml` and `orbit.lock`. - **Remove:** `orbit remove` refuses to delete what other global packages need and autoremoves orphaned dependencies; in projects it updates `orbit.toml` and `orbit.lock`.
- **Self-update:** `orbit self-update` replaces the running Orbit with the newest `orbit` package in the registry, wherever it was installed.
- **gc** deletes store builds that are neither globally current nor kept for rollback. - **gc** deletes store builds that are neither globally current nor kept for rollback.
## Package format ## Package format
@@ -210,6 +211,9 @@ curl -fLO "$base/orbit-linux-x86_64" -fLO "$base/SHA256SUMS" &&
install -Dm755 orbit-linux-x86_64 ~/.local/bin/orbit install -Dm755 orbit-linux-x86_64 ~/.local/bin/orbit
``` ```
After that, `orbit self-update` keeps it current from the registry (see
[Updating Orbit](#updating-orbit)).
`just build-musl` makes the same binary locally in `dist/`. It needs `zig`, `just build-musl` makes the same binary locally in `dist/`. It needs `zig`,
`perl`, `make`, and `curl`. [scripts/build-musl.sh](scripts/build-musl.sh) compiles `perl`, `make`, and `curl`. [scripts/build-musl.sh](scripts/build-musl.sh) compiles
MoonBit's C output and a pinned OpenSSL with `zig cc -target x86_64-linux-musl`. MoonBit's C output and a pinned OpenSSL with `zig cc -target x86_64-linux-musl`.
@@ -217,6 +221,27 @@ MoonBit's C output and a pinned OpenSSL with `zig cc -target x86_64-linux-musl`.
can't do, so [openssl_static.c](scripts/musl/openssl_static.c) supplies the can't do, so [openssl_static.c](scripts/musl/openssl_static.c) supplies the
linked-in functions instead. linked-in functions instead.
## Updating Orbit
```sh
orbit self-update # newest orbit in its channel, if newer than this one
orbit self-update '~0.1' # newest build matching a constraint (can go back)
```
Orbit is the `orbit` package in `main`, built by orbit-packages whenever the
version in `moon.mod` changes.
- An Orbit installed some other way (`just install`, the rolling release) is
replaced where it runs, such as `~/.local/bin/orbit`. It downloads the
package, checks that the new binary runs and reports the version it should,
then swaps it in with one rename. Nothing is added to your installed
packages, and the download is deleted afterwards. `orbit upgrade orbit` does
the same when `orbit` isn't an installed package.
- An Orbit installed with `orbit install orbit` is upgraded like any other
package, so `orbit rollback orbit` still works.
- It uses the channel `orbit` is installed from, else the usual channel
priority. The directory holding the binary must be writable by you.
## Building ## Building
```sh ```sh
@@ -257,7 +282,7 @@ for future upgrades and rollbacks:
bootstrap=_build/native/release/build/main/main.exe bootstrap=_build/native/release/build/main/main.exe
"$bootstrap" install orbit "$bootstrap" install orbit
eval "$("$bootstrap" env)" eval "$("$bootstrap" env)"
orbit upgrade orbit orbit self-update # same as `orbit upgrade orbit` here
# If needed: orbit rollback orbit # If needed: orbit rollback orbit
``` ```
@@ -285,6 +310,7 @@ src/main/
project.mbt orbit.toml, orbit.lock, .orbit/ environments, project CLI (+ tests) project.mbt orbit.toml, orbit.lock, .orbit/ environments, project CLI (+ tests)
conflicts.mbt declared conflicts, replacing installed packages (+ tests) conflicts.mbt declared conflicts, replacing installed packages (+ tests)
channels.mbt config.toml, channel priority and lookup (+ tests) channels.mbt config.toml, channel priority and lookup (+ tests)
self_update.mbt replacing the running orbit with a newer build
main.mbt CLI main.mbt CLI
registry_wbtest.mbt mock-OCI registry, SAT global, and project workflow tests registry_wbtest.mbt mock-OCI registry, SAT global, and project workflow tests
``` ```
@@ -0,0 +1,23 @@
---
data:
priority: normal
status: done
type: feature
id: 4thyv
title: Update Orbit itself from the registry
---
Orbit is published as the `orbit` package in `main` (built by orbit-packages, versioned by moon.mod). A copy installed outside Orbit (`just install`, the rolling release in `~/.local/bin`) had no way to update itself.
## Acceptance criteria
- `orbit self-update [constraint]` replaces the running binary with the newest `orbit` build in its channel when that is newer than the running version, or with the newest build matching an explicit constraint (which may downgrade).
- The new binary is checked to run (`--version`) before it atomically replaces the old one.
- When the running binary is the one Orbit installed globally, it upgrades the `orbit` package instead, keeping rollback.
- `orbit upgrade orbit` does the same when `orbit` isn't installed as a package.
- Mock-registry test; README documents it.
## Outcome
Done in `src/main/self_update.mbt` (`cmd_self_update`, `replace_self`), with `orbit_self_exe` in `stub.c` reading `/proc/self/exe`. The new build is staged as `<exe>.orbit-new`, must print `orbit <version>`, then is renamed over the old binary; the store download is deleted unless that build is installed. Tested with the mock registry (upgrade, up to date, downgrade by constraint, broken build left out) and by hand against `main` (0.1.0 reports up to date; a store-installed orbit hands off to `orbit upgrade orbit`).
Users only see an update once `moon.mod`'s version is bumped and orbit-packages publishes it. The published 0.1.0 doesn't have the command yet.
+25 -1
View File
@@ -40,6 +40,8 @@ let usage : String =
#| orbit remove [-g] <name>... [--force] remove, then drop unused dependencies #| orbit remove [-g] <name>... [--force] remove, then drop unused dependencies
#| orbit upgrade [-g] [name...] jointly upgrade within constraints #| orbit upgrade [-g] [name...] jointly upgrade within constraints
#| orbit rollback <name> switch to the previous global build #| orbit rollback <name> switch to the previous global build
#| orbit self-update [constraint] update this orbit to the newest build of
#| the `orbit` package (or one matching)
#| orbit list [-g] installed global packages #| orbit list [-g] installed global packages
#| orbit info [-g] [channel::]<name>[@constraint] #| orbit info [-g] [channel::]<name>[@constraint]
#| details of an installed package, else of #| details of an installed package, else of
@@ -338,8 +340,30 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
"upgrade" | "up" | "update" => "upgrade" | "up" | "update" =>
match resolve_project_or_none(force_global, manifest_path) { match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_update(load_ctx(), mf, pos) Some(mf) => cmd_project_update(load_ctx(), mf, pos)
None => cmd_upgrade(load_ctx(), pos) None => {
let ctx = load_ctx()
// An orbit installed some other way updates itself.
if pos == ["orbit"] && ctx.state.get("orbit") is None {
cmd_self_update(ctx, None)
} else {
cmd_upgrade(ctx, pos)
}
}
} }
"self-update" => {
if pos.length() > 1 {
raise OrbitError("usage: orbit self-update [constraint]")
}
let constraint = if pos.length() == 1 { Some(pos[0]) } else { None }
match constraint {
Some(c) =>
if !valid_constraint(c) {
raise OrbitError("invalid version constraint '\{c}'")
}
None => ()
}
cmd_self_update(load_ctx(), constraint)
}
"rollback" => { "rollback" => {
need(pos, 1, "rollback <name>") need(pos, 1, "rollback <name>")
cmd_rollback(load_ctx(), pos[0]) cmd_rollback(load_ctx(), pos[0])
+86
View File
@@ -1255,3 +1255,89 @@ async test "orbit --version matches moon.mod" {
let manifest = @fs.read_file(path).text() let manifest = @fs.read_file(path).text()
assert_true(contains_str(manifest, "\nversion = \"\{orbit_version}\"\n")) assert_true(contains_str(manifest, "\nversion = \"\{orbit_version}\"\n"))
} }
///|
async test "self-update replaces the running binary with a newer build" {
token_cache.clear()
let work = @fs.tmpdir(prefix="orbit-wb-self-update-")
defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () })
let st = new_mock_oci_state()
let upload_seq = Ref(0)
let server = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
@async.with_task_group(group => {
defer server.close()
group.spawn_bg(no_wait=true, () => {
server.run_forever((req, body, conn) => {
let req_bytes = body.read_all().binary()
handle_mock_oci(st, upload_seq, req, req_bytes, conn)
})
})
let main_ch = Channel::{
name: "main",
url: "127.0.0.1:" + server.addr.port().to_string() + "/main",
plain_http: true,
}
for v in ["0.1.5", "0.2.0"] {
publish_mock_pkg(
main_ch,
work,
"orbit",
v,
Map([]),
["bin/orbit"],
script="#!/bin/sh\necho orbit \{v}\n",
)
}
let root = work + "/orbit"
let ctx = Ctx::{ root, channels: [main_ch], state: Map([]) }
let exe = work + "/bin/orbit"
@fs.mkdir(work + "/bin", recursive=true)
@fs.write_file(
exe,
"#!/bin/sh\necho orbit 0.1.0\n",
create_mode=CreateOrTruncate,
permission=0o755,
)
let runs = async fn() {
let (_, out) = run_with_stdin(exe, ["--version"], "")
trim(out)
}
replace_self(ctx, exe, "0.1.0", None)
assert_eq(runs(), "orbit 0.2.0")
assert_false(exists(exe + ".orbit-new"))
// Only a download: nothing is left in the store, and nothing installed.
assert_eq(@fs.readdir(root + "/store/orbit"), [])
assert_eq(ctx.state.length(), 0)
// Already newest, or newer than the channel: nothing changes.
replace_self(ctx, exe, "0.2.0", None)
replace_self(ctx, exe, "0.3.0", None)
assert_eq(runs(), "orbit 0.2.0")
// A constraint can go back.
replace_self(ctx, exe, "0.2.0", Some("~0.1"))
assert_eq(runs(), "orbit 0.1.5")
// A build that doesn't report its version is never moved into place.
publish_mock_pkg(
main_ch,
work,
"orbit",
"0.4.0",
Map([]),
["bin/orbit"],
script="#!/bin/sh\nexit 1\n",
)
let failed = try {
replace_self(ctx, exe, "0.1.5", None)
""
} catch {
OrbitError(m) => m
}
assert_true(contains_str(failed, "does not run here"))
assert_eq(runs(), "orbit 0.1.5")
assert_false(exists(exe + ".orbit-new"))
})
}
+121
View File
@@ -0,0 +1,121 @@
// Updating the running Orbit from the `orbit` package in a channel.
///|
/// Path of the running executable, with symlinks resolved.
fn self_exe() -> String raise OrbitError {
let p = utf8_decode(c_self_exe())
if p == "" {
raise OrbitError("cannot find the running orbit in /proc/self/exe")
}
p
}
///|
/// `path` with symlinks resolved, or as given if that fails.
async fn real_path(path : String) -> String noraise {
let (code, out) = run_with_stdin("realpath", ["--", path], "") catch {
_ => return path
}
let p = trim(out)
if code == 0 && p != "" {
p
} else {
path
}
}
///|
/// Update Orbit from the registry. An `orbit` installed as a global package
/// is upgraded like any other, keeping rollback; a copy installed some other
/// way (`just install`, the rolling release) is replaced where it is.
async fn cmd_self_update(
ctx : Ctx,
constraint : String?,
) -> Unit raise OrbitError {
let exe = self_exe()
let store = real_path(ctx.root + "/store/orbit") + "/"
if !has_prefix(exe, store) {
replace_self(ctx, exe, orbit_version, constraint)
return
}
if ctx.state.get("orbit") is None {
raise OrbitError(
"\{exe} belongs to a project environment; run `orbit update orbit` in that project",
)
}
match constraint {
Some(c) => cmd_install(ctx, ["orbit@" + c])
None => cmd_upgrade(ctx, ["orbit"])
}
}
///|
/// Replace the Orbit binary at `exe`, which is version `current`, with the
/// newest `orbit` build matching `constraint`. Without a constraint only a
/// newer version replaces it. The new binary has to run before it is moved
/// into place, and the old one is replaced in a single rename.
async fn replace_self(
ctx : Ctx,
exe : String,
current : String,
constraint : String?,
) -> Unit raise OrbitError {
let pin = ctx.state.get("orbit").map(i => i.channel)
let (ch, tags) = locate(ctx, "orbit", pin)
let c = constraint.unwrap_or("*")
let versions = sorted_versions(tags)
let version = match versions.search_by(v => satisfies_all(v, [c])) {
Some(i) => versions[i]
None => raise OrbitError("no version of \{ch.name}::orbit matches '\{c}'")
}
let order = match (parse_ver(version), parse_ver(current)) {
(Some(a), Some(b)) => cmp_ver(a, b)
_ => if version == current { 0 } else { 1 }
}
if order == 0 || (constraint is None && order < 0) {
println("orbit \{current} is up to date (newest in \{ch.name}: \{version})")
return
}
let digest = resolve_digest(ch, "orbit", version)
let m = fetch_manifest_cached(ctx.root, ch, "orbit", digest)
if !m.bins.contains("bin/orbit") {
raise OrbitError("\{ch.name}::orbit \{version} has no bin/orbit")
}
let dir = path_dirname(exe)
if sh("test -w " + sq(dir)) != 0 {
raise OrbitError(
"cannot write to \{dir}; update \{exe} as a user who can, or `orbit install orbit` instead",
)
}
let pkg = fetch_into_store(ctx, ch, "orbit", digest)
let staged = exe + ".orbit-new"
errdefer (@async.protect_from_cancel(() => sh("rm -f " + sq(staged))) catch {
_ => 0
})
|> ignore
sh_ok(
"cp " +
sq(pkg + "/bin/orbit") +
" " +
sq(staged) +
" && chmod 755 " +
sq(staged),
)
let (code, out) = run_with_stdin(staged, ["--version"], "")
if code != 0 || trim(out) != "orbit \{version}" {
raise OrbitError(
"\{ch.name}::orbit \{version} does not run here (`--version` gave '\{trim(out)}')",
)
}
sh_ok("mv -f " + sq(staged) + " " + sq(exe))
// The store copy was only a download, unless the package is installed there.
let kept = match ctx.state.get("orbit") {
Some(inst) =>
inst.digest == digest || inst.history.iter().any(g => g.digest == digest)
None => false
}
if !kept {
sh("rm -rf " + sq(pkg)) |> ignore
}
println("orbit \{current} -> \{version} (\{exe})")
}
+7
View File
@@ -74,3 +74,10 @@ int32_t orbit_set_echo(int32_t enable) {
} }
return tcsetattr(0, TCSANOW, &t); return tcsetattr(0, TCSANOW, &t);
} }
moonbit_bytes_t orbit_self_exe(void) {
char buf[4096];
ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf));
if (n < 0 || (size_t)n >= sizeof(buf)) return from_buf("", 0);
return from_buf(buf, (size_t)n);
}
+4
View File
@@ -29,6 +29,10 @@ extern "C" fn c_utc_now() -> Bytes = "orbit_utc_now"
///| ///|
extern "C" fn c_set_echo(enable : Int32) -> Int32 = "orbit_set_echo" extern "C" fn c_set_echo(enable : Int32) -> Int32 = "orbit_set_echo"
///|
/// Path of the running executable, or "" if it can't be read.
extern "C" fn c_self_exe() -> Bytes = "orbit_self_exe"
// ---------------------------------------------------------------- UTF-8 // ---------------------------------------------------------------- UTF-8
///| ///|