// Planning and applying installs, removals, upgrades and rollbacks. ///| /// One package in an install plan. struct Step { name : String channel : String version : String digest : String manifest : Manifest mut explicit : Bool mut constraint : String keep : Bool // already installed at this digest; nothing to fetch } ///| struct Planner { ctx : Ctx steps : Map[String, Step] order : Array[Step] // dependencies before dependents upgrade : Array[String] // names allowed to move even if satisfied } ///| fn manifest_of_installed(p : Installed) -> Manifest { Manifest::{ name: p.name, version: p.version, description: p.description, documentation: "", depends: p.depends, bins: p.bins, } } ///| /// Every constraint that currently applies to `name`: the request itself, /// the user's own constraint if they installed it explicitly, and what each /// other package requires (using planned manifests for packages being replaced). fn constraints_for( p : Planner, name : String, requested : String, ) -> Array[String] { let cons : Array[String] = [requested] match p.ctx.state.get(name) { Some(inst) => if inst.explicit && inst.constraint != "" && inst.constraint != requested { cons.push(inst.constraint) } None => () } for other, inst in p.ctx.state { if other == name { continue } let deps = match p.steps.get(other) { Some(st) => st.manifest.depends None => inst.depends } match deps.get(name) { Some(c) => cons.push(c) None => () } } for other, st in p.steps { if other != name && !p.ctx.state.contains(other) { match st.manifest.depends.get(name) { Some(c) => cons.push(c) None => () } } } cons } ///| async fn visit( p : Planner, name : String, requested : String, explicit : Bool, pin : String?, // channel the user asked for ) -> Unit raise OrbitError { match p.steps.get(name) { Some(st) => { if pin is Some(c) && c != st.channel { raise OrbitError( "conflict: \{name} is planned from channel '\{st.channel}' but '\{c}' was requested", ) } if !satisfies_all(st.version, [requested]) { raise OrbitError( "conflict: \{name} \{st.version} is planned but '\{requested}' is required", ) } if explicit { st.explicit = true st.constraint = requested } return } None => () } let cons = constraints_for(p, name, requested) let upgrading = p.upgrade.contains(name) match p.ctx.state.get(name) { Some(inst) => { let same_channel = match pin { Some(c) => c == inst.channel None => true } if !upgrading && same_channel && satisfies_all(inst.version, cons) { let st = Step::{ name, channel: inst.channel, version: inst.version, digest: inst.digest, manifest: manifest_of_installed(inst), explicit: explicit || inst.explicit, constraint: if explicit { requested } else { inst.constraint }, keep: true, } p.steps[name] = st p.order.push(st) return } } None => () } // An installed package stays on its channel unless the user names another. let wanted = match pin { Some(c) => Some(c) None => p.ctx.state.get(name).map(fn(i) { i.channel }) } let (ch, tags) = locate(p.ctx, name, wanted) let tag = match pick_tag(tags, cons) { Some(t) => t None => { let avail = sorted_versions(tags) raise OrbitError( "no version of \{name} in channel '\{ch.name}' satisfies [\{join(cons, ", ")}]; available: \{join(avail, ", ")}", ) } } let digest = resolve_digest(ch, name, tag) let prev = p.ctx.state.get(name) // An unchanged build with a saved description needs no metadata fetch. let m = match prev { Some(i) => if i.digest == digest && i.description != "" { manifest_of_installed(i) } else { fetch_manifest(ch, name, digest) } None => fetch_manifest(ch, name, digest) } let st = Step::{ name, channel: ch.name, version: m.version, digest, manifest: m, explicit: explicit || (match prev { Some(i) => i.explicit None => false }), constraint: if explicit { requested } else { match prev { Some(i) => i.constraint None => "*" } }, keep: match prev { Some(i) => i.digest == digest None => false }, } // Register before recursing so dependency cycles terminate. p.steps[name] = st for dep, dc in m.depends { visit(p, dep, dc, false, None) } p.order.push(st) } ///| /// "[channel::]name[@constraint]" fn parse_spec(spec : String) -> (String?, String, String) raise OrbitError { let (channel, rest) = split_channel(spec) let (name, c) = split_first(rest, '@') if !valid_name(name) { raise OrbitError("invalid package name '\{name}'") } (channel, name, if c == "" { "*" } else { c }) } ///| fn owner_of_bin(ctx : Ctx, bin : String) -> String? { for name, p in ctx.state { for b in p.bins { if basename(b) == bin { return Some(name) } } } None } ///| async fn unlink_bins(ctx : Ctx, bins : Array[String]) -> Unit noraise { for b in bins { let path = bin_dir(ctx) + "/" + basename(b) @fs.remove(path) catch { _ => () } } } ///| async fn link_bins( ctx : Ctx, dir : String, bins : Array[String], ) -> Unit raise OrbitError { @fs.mkdir(bin_dir(ctx), recursive=true) catch { e => raise OrbitError("cannot create bin dir: " + e.to_string()) } for b in bins { let target = dir + "/" + b let linkpath = bin_dir(ctx) + "/" + basename(b) let rc = c_symlink(utf8_encode(target), utf8_encode(linkpath)) if rc != 0 { raise OrbitError("cannot symlink " + linkpath + " -> " + target) } } } ///| fn check_bin_conflicts( ctx : Ctx, name : String, bins : Array[String], ) -> Unit raise OrbitError { for b in bins { match owner_of_bin(ctx, basename(b)) { Some(other) => if other != name { raise OrbitError( "\{name} wants to provide '\{basename(b)}', which \{other} already provides", ) } None => () } } } ///| /// Switch `name` to a fetched build, keeping the old one for rollback. async fn activate(ctx : Ctx, st : Step) -> Unit raise OrbitError { let ch = find_channel(ctx, st.channel) let dir = fetch_into_store(ctx, ch, st.name, st.digest) for b in st.manifest.bins { if sh("test -f " + sq(dir + "/" + b)) != 0 { raise OrbitError("\{st.name}: bin '\{b}' missing from package contents") } } check_bin_conflicts(ctx, st.name, st.manifest.bins) match ctx.state.get(st.name) { Some(inst) => { unlink_bins(ctx, inst.bins) inst.history.push(Gen::{ channel: inst.channel, version: inst.version, digest: inst.digest, description: inst.description, bins: inst.bins, depends: inst.depends, }) while inst.history.length() > 2 { inst.history.remove(0) |> ignore } inst.channel = st.channel inst.version = st.version inst.digest = st.digest inst.description = st.manifest.description inst.bins = st.manifest.bins inst.depends = st.manifest.depends inst.explicit = st.explicit inst.constraint = st.constraint println( " \{st.name}: \{inst.history[inst.history.length() - 1].version} -> \{st.version}", ) } None => { ctx.state[st.name] = Installed::{ name: st.name, channel: st.channel, version: st.version, digest: st.digest, description: st.manifest.description, explicit: st.explicit, constraint: st.constraint, bins: st.manifest.bins, depends: st.manifest.depends, history: [], } println(" \{st.name} \{st.version} installed") } } link_bins(ctx, dir, st.manifest.bins) // Persist after each package so a later failure leaves accurate state. save_state(ctx) } ///| async fn apply_plan(ctx : Ctx, p : Planner) -> Unit raise OrbitError { let mut changed = 0 for st in p.order { if st.keep { match ctx.state.get(st.name) { Some(inst) => { inst.channel = st.channel inst.description = st.manifest.description inst.explicit = st.explicit inst.constraint = st.constraint } None => () } continue } activate(ctx, st) changed = changed + 1 } save_state(ctx) if changed == 0 { println("nothing to do") } } ///| fn new_planner(ctx : Ctx, upgrade : Array[String]) -> Planner { Planner::{ ctx, steps: Map([]), order: [], upgrade, } } ///| async fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError { if specs.length() == 0 { raise OrbitError("usage: orbit install [channel::][@constraint]...") } let p = new_planner(ctx, []) for s in specs { let (channel, name, c) = parse_spec(s) visit(p, name, c, true, channel) } apply_plan(ctx, p) } ///| /// Upgrade the named packages (or everything) to the newest versions their /// constraints allow. Dependencies are moved only when required. async fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError { let targets : Array[String] = [] if names.length() == 0 { for name, _ in ctx.state { targets.push(name) } } else { for n in names { if !ctx.state.contains(n) { raise OrbitError("\{n} is not installed") } targets.push(n) } } let p = new_planner(ctx, targets) for n in targets { match ctx.state.get(n) { Some(inst) => visit(p, n, "*", inst.explicit, None) None => () } } apply_plan(ctx, p) } ///| fn reverse_deps(ctx : Ctx, name : String) -> Array[String] { let r : Array[String] = [] for other, p in ctx.state { if other != name && p.depends.contains(name) { r.push(other) } } r } ///| async fn remove_one(ctx : Ctx, name : String) -> Unit raise OrbitError { match ctx.state.get(name) { Some(inst) => { unlink_bins(ctx, inst.bins) sh_ok("rm -rf " + sq(ctx.root + "/store/" + name)) ctx.state.remove(name) println(" \{name} \{inst.version} removed") } None => () } } ///| /// Remove dependencies nobody needs any more. async fn autoremove(ctx : Ctx) -> Unit raise OrbitError { let mut changed = true while changed { changed = false let orphans : Array[String] = [] for name, p in ctx.state { if !p.explicit && reverse_deps(ctx, name).length() == 0 { orphans.push(name) } } for n in orphans { remove_one(ctx, n) changed = true } } } ///| async fn cmd_remove( ctx : Ctx, names : Array[String], force : Bool, ) -> Unit raise OrbitError { if names.length() == 0 { raise OrbitError("usage: orbit remove ...") } for n in names { if !ctx.state.contains(n) { raise OrbitError("\{n} is not installed") } } for n in names { let users : Array[String] = [] for u in reverse_deps(ctx, n) { if !names.contains(u) { users.push(u) } } if users.length() > 0 && !force { raise OrbitError( "\{n} is required by \{join(users, ", ")} (use --force to remove anyway)", ) } } for n in names { remove_one(ctx, n) } autoremove(ctx) save_state(ctx) } ///| /// Swap the current build with the previous one (run twice to undo). async fn cmd_rollback(ctx : Ctx, name : String) -> Unit raise OrbitError { let inst = match ctx.state.get(name) { Some(i) => i None => raise OrbitError("\{name} is not installed") } let prev = match inst.history.pop() { Some(g) => g None => raise OrbitError("\{name} has no previous version to roll back to") } let dir = store_dir(ctx, name, prev.digest) if !exists(dir) { raise OrbitError( "previous build of \{name} (\{prev.version}) is no longer in the store", ) } unlink_bins(ctx, inst.bins) inst.history.push(Gen::{ channel: inst.channel, version: inst.version, digest: inst.digest, description: inst.description, bins: inst.bins, depends: inst.depends, }) inst.channel = prev.channel let from = inst.version inst.version = prev.version inst.digest = prev.digest inst.description = prev.description inst.bins = prev.bins inst.depends = prev.depends check_bin_conflicts(ctx, name, inst.bins) link_bins(ctx, dir, inst.bins) save_state(ctx) println("\{name}: \{from} -> \{prev.version}") let missing : Array[String] = [] for dep, c in inst.depends { match ctx.state.get(dep) { Some(d) => if !satisfies_all(d.version, [c]) { missing.push(dep + "@" + c) } None => missing.push(dep + "@" + c) } } if missing.length() > 0 { println( "warning: \{name} \{prev.version} wants \{join(missing, ", ")}; run `orbit install` for them", ) } } ///| /// Delete store entries that are neither current nor kept for rollback. async fn cmd_gc(ctx : Ctx) -> Unit raise OrbitError { let store = ctx.root + "/store" if !exists(store) { println("store is empty") return } let mut freed = 0 let pkgs = @fs.readdir(store) catch { _ => [] } for pkg in pkgs { match ctx.state.get(pkg) { None => { sh_ok("rm -rf " + sq(store + "/" + pkg)) freed = freed + 1 } Some(inst) => { let keep : Array[String] = [store_id(inst.digest)] for g in inst.history { keep.push(store_id(g.digest)) } let ids = @fs.readdir(store + "/" + pkg) catch { _ => [] } for id in ids { if !keep.contains(id) { sh_ok("rm -rf " + sq(store + "/" + pkg + "/" + id)) freed = freed + 1 } } } } } let tmp = ctx.root + "/tmp" let _ = sh("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp)) println("removed \{freed} store entries") } ///| fn cmd_list(ctx : Ctx) -> Unit { if ctx.state.length() == 0 { println("no packages installed") return } for name, p in ctx.state { let kind = if p.explicit { "" } else { " (dependency)" } let from = if p.channel == MAIN_CHANNEL { "" } else { " [\{p.channel}]" } println("\{name} \{p.version}\{from}\{kind}") } } ///| /// Where to look up "[channel::]name": the channel asked for, else the one it /// was installed from, else by priority. async fn locate_spec( ctx : Ctx, spec : String, ) -> (String, Channel, Array[String]) raise OrbitError { let (pin, name) = split_channel(spec) let wanted = match pin { Some(c) => Some(c) None => ctx.state.get(name).map(fn(i) { i.channel }) } let (ch, tags) = locate(ctx, name, wanted) (name, ch, tags) } ///| fn cmd_info(ctx : Ctx, spec : String) -> Unit raise OrbitError { let (pin, name) = split_channel(spec) let p = match ctx.state.get(name) { Some(p) => p None => raise OrbitError("\{spec} is not installed") } if pin is Some(channel) && channel != p.channel { raise OrbitError("\{spec} is not installed (installed from '\{p.channel}')") } println("\{name} \{p.version} (installed)") if p.description != "" { println(" description: \{p.description}") } println(" channel: \{p.channel}") println(" digest: \{p.digest}") println(" constraint: \{p.constraint}") println(" bin: \{join(p.bins, " ")}") let deps : Array[String] = [] for d, c in p.depends { deps.push(d + "@" + c) } println(" depends: \{join(deps, " ")}") let rd = reverse_deps(ctx, name) println(" needed by: \{join(rd, " ")}") let hist : Array[String] = [] for g in p.history { hist.push(g.version) } println(" rollback: \{join(hist, " ")}") } ///| async fn cmd_versions(ctx : Ctx, spec : String) -> Unit raise OrbitError { let (name, ch, tags) = locate_spec(ctx, spec) for v in sorted_versions(tags) { let mark = match ctx.state.get(name) { Some(p) => if p.version == v && p.channel == ch.name { " *" } else { "" } None => "" } println(v + mark) } } ///| /// What search shows about one Orbit package, read from its manifest. struct RepoInfo { version : String description : String } ///| fn is_orbit_object(o : Map[String, Json]) -> Bool { if jstr(o, "artifactType", "") == ORBIT_ARTIFACT_TYPE { return true } match o.get("config") { Some(Json::Object(c)) => jstr(c, "mediaType", "") == CONFIG_MEDIA_TYPE _ => false } } ///| /// The package info from a manifest, or None if it isn't an Orbit package. /// Version and description come from the standard OCI annotations that publish /// writes, so no extra request is needed. fn orbit_info(text : String) -> RepoInfo? { let parsed : Map[String, Json]? = Some(parse_object(text, "manifest")) catch { _ => None } match parsed { Some(o) => if is_orbit_object(o) { let annotations : Map[String, Json] = match o.get("annotations") { Some(Json::Object(a)) => a _ => Map([]) } Some(RepoInfo::{ version: jstr(annotations, "org.opencontainers.image.version", ""), description: jstr( annotations, "org.opencontainers.image.description", "", ), }) } else { None } None => None } } ///| /// Look at one repository's latest manifest (or any tag if there is no latest). /// Any failure counts as "not an Orbit package", so one broken repo can't hide /// the others. async fn orbit_repo_info(ch : Channel, repo : String) -> RepoInfo? noraise { let tags = lines(capture(oras(ch, "repo tags " + sq(repo_of(ch, repo))))) catch { _ => return None } if tags.length() == 0 { return None } let tag = if tags.contains("latest") { "latest" } else { tags[0] } let text = capture( oras(ch, "manifest fetch " + sq(repo_of(ch, repo) + ":" + tag)), ) catch { _ => return None } orbit_info(text) } ///| /// Check many repositories at once, with one spinner for the whole batch. async fn find_orbit_repos( ch : Channel, repos : Array[String], ) -> Array[RepoInfo?] raise OrbitError { if repos.length() == 0 { return [] } let label = "Checking \{repos.length()} repositories in \{ch.name}" let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb" @async.with_task_group(group => { let spinner = if is_tty { Some( group.spawn(() => ignore(@async.handle_cancellation(() => spin(label)))), ) } else { None } let tasks : Array[@async.Task[RepoInfo?]] = [] for r in repos { tasks.push(group.spawn(() => orbit_repo_info(ch, r))) } let results : Array[RepoInfo?] = [] for t in tasks { results.push(t.wait()) } match spinner { Some(s) => s.cancel() None => () } if is_tty { c_print_err(utf8_encode("\r\u001B[2K")) } results }) catch { e => raise OrbitError(e.to_string()) } } ///| /// Pad on the right to `width` characters, for the table columns. fn pad_right(s : String, width : Int32) -> String { let sb = StringBuilder() sb.write_string(s) let mut n = chars(s).length() while n < width { sb.write_char(' ') n = n + 1 } sb.to_string() } ///| /// Print rows as a table. The first row is the header. The last column is not /// padded, so long descriptions don't leave trailing spaces. fn print_table(rows : Array[Array[String]]) -> Unit { let ncols = rows[0].length() let widths : Array[Int32] = [] for c = 0; c < ncols; c = c + 1 { widths.push(0) } for row in rows { for c = 0; c < ncols; c = c + 1 { let n = chars(row[c]).length() if n > widths[c] { widths[c] = n } } } for row in rows { let sb = StringBuilder() for c = 0; c < ncols; c = c + 1 { if c > 0 { sb.write_string(" ") } if c < ncols - 1 { sb.write_string(pad_right(row[c], widths[c])) } else { sb.write_string(row[c]) } } println(sb.to_string()) } } ///| async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { let rows : Array[Array[String]] = [ ["PACKAGE", "CHANNEL", "VERSION", "DESCRIPTION"], ] let mut listed = 0 for ch in ctx.channels { let out = capture( oras(ch, "repo ls " + sq(ch.url)), progress="Listing packages in \{ch.name}", ) catch { _ => { println("warning: channel '\{ch.name}' does not allow listing packages") continue } } listed = listed + 1 let candidates : Array[String] = [] for r in lines(out) { // A name with "/" is a nested channel namespace (e.g. example/greet under // main), not a package name that `orbit install` could use. if valid_name(r) && contains_str(r, term) { candidates.push(r) } } let found = find_orbit_repos(ch, candidates) for i, r in candidates { match found[i] { Some(info) => rows.push([ r, ch.name, if info.version == "" { "-" } else { info.version }, if info.description == "" { "-" } else { info.description }, ]) None => () } } } if listed == 0 { raise OrbitError( "no channel allows listing packages (catalog API); try `orbit versions `", ) } if rows.length() == 1 { if term == "" { println("no packages found") } else { println("no packages match '\{term}'") } return } print_table(rows) } ///| test "orbit manifests are recognised by artifactType or config media type" { assert_true( orbit_info( "{\"artifactType\":\"application/vnd.latha.orbit.v1\",\"config\":{\"mediaType\":\"x\"}}", ) is Some(_), ) assert_true( orbit_info( "{\"artifactType\":null,\"config\":{\"mediaType\":\"application/vnd.latha.orbit.config.v1+json\"}}", ) is Some(_), ) assert_true( orbit_info( "{\"artifactType\":\"application/vnd.cncf.helm.chart.content.v1.tar+gzip\",\"config\":{\"mediaType\":\"application/vnd.cncf.helm.config.v1+json\"}}", ) is None, ) assert_true(orbit_info("not json") is None) assert_true(orbit_info("{\"config\":\"string\"}") is None) } ///| test "search info comes from OCI annotations" { let info = orbit_info( "{\"artifactType\":\"application/vnd.latha.orbit.v1\",\"annotations\":{\"org.opencontainers.image.version\":\"1.2.3\",\"org.opencontainers.image.description\":\"A tool\"}}", ).unwrap() assert_eq(info.version, "1.2.3") assert_eq(info.description, "A tool") let bare = orbit_info("{\"artifactType\":\"application/vnd.latha.orbit.v1\"}").unwrap() assert_eq(bare.version, "") assert_eq(bare.description, "") } ///| test "search skips nested channel namespaces" { assert_true(valid_name("greet")) assert_true(!valid_name("example/greet")) } ///| test "table columns line up" { assert_eq(pad_right("ab", 4), "ab ") assert_eq(pad_right("abcd", 2), "abcd") }