// 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 explicit : Bool constraint : String keep : Bool // already installed at this digest; nothing to fetch } ///| fn manifest_of_installed(p : Installed) -> Manifest { Manifest::{ name: p.name, version: p.version, description: p.description, documentation: "", depends: p.depends, bins: p.bins, } } ///| /// "[channel::]name[@constraint]" -> (channel, name, constraint, has_explicit_constraint) fn parse_spec_full( spec : String, ) -> (String?, String, String, Bool) raise OrbitError { let (channel, rest) = split_channel(spec) match channel { Some(ch) => if !valid_name(ch) { raise OrbitError("invalid channel name '\{ch}'") } None => () } let (name, c) = split_first(rest, '@') if !valid_name(name) { raise OrbitError("invalid package name '\{name}'") } if c == "" { (channel, name, "*", false) } else { if !valid_constraint(c) { raise OrbitError("invalid version constraint '\{c}' for '\{name}'") } (channel, name, c, true) } } ///| /// "[channel::]name[@constraint]" fn parse_spec(spec : String) -> (String?, String, String) raise OrbitError { let (channel, name, c, _) = parse_spec_full(spec) (channel, name, c) } ///| /// Build a SAT-solved install/upgrade plan for global state. async fn plan_global( ctx : Ctx, req_specs : Array[(String?, String, String, String)], upgrade : Array[String], explicit_new : Map[String, String], ) -> Array[Step] raise OrbitError { let ch_by_name : Map[String, Channel] = Map([]) for c in ctx.channels { ch_by_name[c.name] = c } let tags_cache : Map[String, (Channel, Array[String])] = Map([]) let digest_cache : Map[String, String] = Map([]) let manifest_cache : Map[String, Manifest] = Map([]) let locked_bins : Map[String, String] = Map([]) for name, inst in ctx.state { if !upgrade.contains(name) && !explicit_new.contains(name) { for b in inst.bins { locked_bins[basename(b)] = name } } } let provider = SolverProvider::{ candidates: async fn(name, pin) { let wanted = match pin { Some(c) => Some(c) None => match ctx.state.get(name) { Some(inst) => Some(inst.channel) None => None } } let cache_key = name + "|" + wanted.unwrap_or("") let (ch, tags) = match tags_cache.get(cache_key) { Some(pair) => pair None => { let pair = locate(ctx, name, wanted) tags_cache[cache_key] = pair ch_by_name[pair.0.name] = pair.0 pair } } let favored = if upgrade.contains(name) { None } else { match ctx.state.get(name) { Some(inst) => if inst.channel == ch.name { Some((inst.channel, inst.version, inst.digest)) } else { None } None => None } } (ch.name, candidates_from_tags(name, ch.name, tags, favored)) }, details: async fn(cand) { if false { @async.sleep(0) } if cand.favored && cand.digest != "" { match ctx.state.get(cand.name) { Some(inst) => if inst.digest == cand.digest && inst.channel == cand.channel { return CandidateDetail::{ digest: cand.digest, manifest: manifest_of_installed(inst), } } None => () } } let ch = match ch_by_name.get(cand.channel) { Some(c) => c None => find_channel(ctx, cand.channel) } let dkey = cand.channel + "::" + cand.name + "@" + cand.tag let digest = match digest_cache.get(dkey) { Some(d) => d None => { let d = resolve_digest(ch, cand.name, cand.tag) digest_cache[dkey] = d d } } let mkey = cand.channel + "::" + cand.name + "@" + digest let m = match manifest_cache.get(mkey) { Some(mf) => mf None => { let mf = fetch_manifest_cached(ctx.root, ch, cand.name, digest) manifest_cache[mkey] = mf mf } } CandidateDetail::{ digest, manifest: m } }, extra_reqs: fn(pkg_name) { let reqs : Array[SolveReq] = [] match ctx.state.get(pkg_name) { Some(inst) => if inst.explicit && !explicit_new.contains(pkg_name) { reqs.push(SolveReq::{ name: pkg_name, channel: Some(inst.channel), constraint: if inst.constraint == "" { "*" } else { inst.constraint }, label: "installed \{pkg_name}", }) } None => () } for other, oinst in ctx.state { if other != pkg_name && !upgrade.contains(other) && !explicit_new.contains(other) { for dk, dc in oinst.depends { let (dch, dname) = parse_dep_key(dk) if dname == pkg_name { reqs.push(SolveReq::{ name: pkg_name, channel: dch, constraint: dc, label: "installed \{other} \{oinst.version}", }) } } } } reqs }, locked_bins, } let reqs : Array[SolveReq] = [] for item in req_specs { let (pin, name, constraint, label) = item reqs.push(SolveReq::{ name, channel: pin, constraint, label }) } let solved = solve(reqs, provider) let steps : Array[Step] = [] for sp in solved { let prev = ctx.state.get(sp.name) let explicit = explicit_new.contains(sp.name) || (match prev { Some(i) => i.explicit None => false }) let constraint = match explicit_new.get(sp.name) { Some(c) => c None => match prev { Some(i) => i.constraint None => "*" } } let keep = match prev { Some(i) => i.digest == sp.digest && i.channel == sp.channel None => false } steps.push(Step::{ name: sp.name, channel: sp.channel, version: sp.version, digest: sp.digest, manifest: sp.manifest, explicit, constraint, keep, }) } steps } ///| 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, allow_exist=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, steps : Array[Step]) -> Unit raise OrbitError { let mut changed = 0 for st in steps { 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") } } ///| async fn cmd_install(ctx : Ctx, specs : Array[String]) -> Unit raise OrbitError { if specs.length() == 0 { raise OrbitError("usage: orbit install [channel::][@constraint]...") } let reqs : Array[(String?, String, String, String)] = [] let explicit_new : Map[String, String] = Map([]) for s in specs { let (channel, name, c) = parse_spec(s) reqs.push((channel, name, c, "command line")) explicit_new[name] = c } let steps = plan_global(ctx, reqs, [], explicit_new) apply_plan(ctx, steps) } ///| /// Upgrade the named packages (or everything) jointly to the newest versions /// their constraints allow. async fn cmd_upgrade(ctx : Ctx, names : Array[String]) -> Unit raise OrbitError { let targets : Array[String] = [] let reqs : Array[(String?, String, String, String)] = [] if names.length() == 0 { if ctx.state.length() == 0 { println("no packages installed") return } let mut has_explicit = false for name, inst in ctx.state { targets.push(name) if inst.explicit { has_explicit = true reqs.push(( Some(inst.channel), name, if inst.constraint == "" { "*" } else { inst.constraint }, "installed \{name}", )) } } if !has_explicit { for name, inst in ctx.state { reqs.push(( Some(inst.channel), name, if inst.constraint == "" { "*" } else { inst.constraint }, "installed \{name}", )) } } } else { for n in names { let inst = match ctx.state.get(n) { Some(i) => i None => raise OrbitError("\{n} is not installed") } targets.push(n) reqs.push(( Some(inst.channel), n, if inst.constraint == "" { "*" } else { inst.constraint }, "installed \{n}", )) } } let steps = plan_global(ctx, reqs, targets, Map([])) apply_plan(ctx, steps) if names.length() == 0 { autoremove(ctx) save_state(ctx) } } ///| fn reverse_deps(ctx : Ctx, name : String) -> Array[String] { let r : Array[String] = [] for other, p in ctx.state { if other != name { let mut uses = false for dk, _ in p.depends { if parse_dep_key(dk).1 == name { uses = true break } } if uses { 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 { let (_, dep_name) = parse_dep_key(dep) match ctx.state.get(dep_name) { 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 = match (list_tags_quiet(ch, repo) catch { _ => return None }) { Some(ts) => ts None => return None } if tags.length() == 0 { return None } let tag = if tags.contains("latest") { "latest" } else { tags[0] } let text = fetch_raw_manifest(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 repos = list_repos(ch) catch { _ => { println("warning: channel '\{ch.name}' does not allow listing packages") continue } } listed = listed + 1 let candidates : Array[String] = [] for r in repos { // 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") }