usm-spm-apk 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. #!/bin/sh
  2. # USM system-package-manager helper for apk-based systems (Alpine).
  3. #
  4. # Implements the USM SPM contract (see usm/README.md, "System package
  5. # manager integration") for Alpine-style systems:
  6. #
  7. # usm-spm-apk query <usm-ref>... -> contract JSON on STDOUT
  8. # usm-spm-apk install <native-name>... -> contract JSONL events on STDOUT
  9. #
  10. # API choice: pure POSIX shell (busybox ash) on purpose -- the Alpine
  11. # base image ships neither python3 nor jq, and the SPM bootstrap must
  12. # stay at zero extra packages (busybox is already there). apk-tools
  13. # >= 2.10 (alpine:latest currently ships apk-tools 3.0.6) expose
  14. # provides namespaces that map USM refs natively, so file-list indexes
  15. # are not needed for the hot types:
  16. #
  17. # bin:/sbin: X -> provides "cmd:X" (abuild auto-generates for
  18. # every packaged executable, /usr/bin and /sbin)
  19. # lib: X -> provides "so:X" (verbatim soname)
  20. # pc: X -> provides "pc:${X%.pc}" -- apk indexes pkg-config
  21. # module names WITHOUT the ".pc" suffix (observed:
  22. # glib-dev provides pc:glib-2.0, vala provides
  23. # pc:libvala-0.56), so one trailing ".pc" is
  24. # stripped from the ref before querying
  25. #
  26. # Providers are found with `apk search -x <provide>` (exact match that
  27. # also matches provides); the from-scratch solo-install closure comes
  28. # from `apk search --recursive <name>` (runs the solver against the
  29. # repositories only -- same semantics as the dnf helper's repo-only
  30. # sack); installed-dependency-count is the overlap of that closure with
  31. # the installed database (`apk info`). Residual resource types (inc:,
  32. # vapi:, gir:, typelib:, gio:, res:, cfg:, man:, info:, locale:,
  33. # libexec:, rootpath:, tag:) are resolved against the installed database only via
  34. # `apk info -W`/directory sampling: APKINDEX carries no file lists, so
  35. # files of not-yet-installed packages are unresolvable and land in
  36. # "not-found" (documented limitation, the same offline stance as the
  37. # emerge helper).
  38. #
  39. # apk has no per-download progress output on a non-tty stdout; it
  40. # prints one "(k/N) Installing pkg (ver)" line per package instead, so
  41. # "package" events are emitted at package-completion granularity
  42. # (progress 1.0) driven by those lines, and begin.total comes from an
  43. # `apk add --simulate` pass against the current system.
  44. #
  45. # Install transactions expand INSTALL_COMPANIONS (currently gcc ->
  46. # musl-dev): apk's gcc package deliberately ships no crt objects, and a
  47. # USM manifest cannot express them as resource refs.
  48. #
  49. # The query subcommand never modifies system state: repository indexes
  50. # are fetched into a throwaway cache directory (at most refreshing
  51. # package-metadata caches). The install subcommand must run as root;
  52. # apk never prompts interactively: unresolved dependencies or bad
  53. # signatures fail instead.
  54. #
  55. # Alpine path table (musl/busybox layout, no lib64): /usr/bin, /sbin,
  56. # /lib, /usr/lib, /usr/include, /usr/share (+/usr/share/pkgconfig).
  57. set -eu
  58. export LC_ALL=C
  59. PROG=usm-spm-apk
  60. EXIT_OK=0
  61. EXIT_FAILURE=1
  62. EXIT_USAGE=2
  63. EXIT_RESOLVE=3
  64. EXIT_DOWNLOAD=4
  65. EXIT_TRANSACTION=5
  66. WORK=""
  67. cleanup() {
  68. if [ -n "$WORK" ]; then
  69. rm -rf "$WORK"
  70. fi
  71. }
  72. warn() {
  73. printf '%s: %s\n' "$PROG" "$*" >&2
  74. }
  75. die_usage() {
  76. printf 'usage: %s query <usm-ref>...\n' "$PROG" >&2
  77. printf ' %s plan <native-name>...\n' "$PROG" >&2
  78. printf ' %s install <native-name>...\n' "$PROG" >&2
  79. exit "$EXIT_USAGE"
  80. }
  81. emit() {
  82. printf '%s\n' "$1"
  83. }
  84. json_escape() {
  85. printf '%s' "$1" | awk '
  86. {
  87. s = $0
  88. gsub(/\\/, "\\\\", s)
  89. gsub(/"/, "\\\"", s)
  90. gsub(/\t/, "\\t", s)
  91. gsub(/[[:cntrl:]]/, "", s)
  92. print s
  93. }'
  94. }
  95. mkwork() {
  96. WORK=$(mktemp -d "${TMPDIR:-/tmp}/usm-spm-apk.XXXXXX" 2>/dev/null) || {
  97. WORK="${TMPDIR:-/tmp}/usm-spm-apk.$$"
  98. (umask 077 && mkdir "$WORK")
  99. }
  100. trap cleanup EXIT
  101. }
  102. prime_index_cache() {
  103. CACHE="$WORK/cache"
  104. PRIMED=0
  105. if mkdir -p "$CACHE" && apk update -q --cache-dir "$CACHE" >/dev/null 2>"$WORK/prime.err"; then
  106. if [ -n "$(ls -A "$CACHE" 2>/dev/null)" ]; then
  107. PRIMED=1
  108. fi
  109. fi
  110. if [ "$PRIMED" != 1 ]; then
  111. warn "could not prime a repository index cache; every lookup will fetch indexes"
  112. fi
  113. }
  114. sp_search() {
  115. if [ "$PRIMED" = 1 ]; then
  116. apk search --cache-dir "$CACHE" "$@"
  117. else
  118. apk search --no-cache "$@"
  119. fi
  120. }
  121. apk_diag_line() {
  122. [ -r "$1" ] || return 0
  123. sed -n 's/^\(ERROR\|WARNING\):[[:space:]]*//p' "$1" | head -n 1
  124. }
  125. strip_version() {
  126. sed -e 's/-r[0-9][0-9]*$//' -e 's/-[0-9][0-9A-Za-z._+]*$//'
  127. }
  128. not_found_add() {
  129. printf '%s\n' "$1" >>"$WORK/nf"
  130. }
  131. map_add() {
  132. printf '%s\t%s\n' "$1" "$2" >>"$WORK/map"
  133. }
  134. record_providers() {
  135. _rp_ref=$1
  136. _rp_prov=$2
  137. _rp_out=$(sp_search -x -- "$_rp_prov" 2>"$WORK/search.err" || true)
  138. if { [ -z "$_rp_out" ] && [ -s "$WORK/search.err" ]; } || grep -q '^ERROR' "$WORK/search.err" 2>/dev/null; then
  139. warn "apk search failed for \"$_rp_prov\": $(apk_diag_line "$WORK/search.err")"
  140. exit "$EXIT_RESOLVE"
  141. fi
  142. if [ -n "$_rp_out" ]; then
  143. printf '%s\n' "$_rp_out" | strip_version | sort -u >"$WORK/pv"
  144. while IFS= read -r _rp_nm; do
  145. [ -n "$_rp_nm" ] || continue
  146. map_add "$_rp_nm" "$_rp_ref"
  147. done <"$WORK/pv"
  148. else
  149. not_found_add "$_rp_ref"
  150. fi
  151. }
  152. record_file_owner() {
  153. _fo_ref=$1
  154. shift
  155. _fo_hit=0
  156. for _fo_p in "$@"; do
  157. _fo_f=
  158. if [ -d "$_fo_p" ]; then
  159. _fo_f=$(find "$_fo_p" -type f 2>/dev/null | head -n 1) || _fo_f=
  160. elif [ -f "$_fo_p" ]; then
  161. _fo_f=$_fo_p
  162. else
  163. continue
  164. fi
  165. [ -n "$_fo_f" ] || continue
  166. _fo_own=$(apk info -W "$_fo_f" 2>/dev/null) || continue
  167. _fo_nm=$(printf '%s\n' "$_fo_own" | sed -n 's/^.* is owned by //p' | strip_version)
  168. [ -n "$_fo_nm" ] || continue
  169. map_add "$_fo_nm" "$_fo_ref"
  170. _fo_hit=1
  171. done
  172. if [ "$_fo_hit" != 1 ]; then
  173. not_found_add "$_fo_ref"
  174. fi
  175. }
  176. handle_ref() {
  177. _hr_ref=$1
  178. _hr_type=${_hr_ref%%:*}
  179. _hr_res=${_hr_ref#*:}
  180. if [ "$_hr_type" = "$_hr_ref" ] || [ -z "$_hr_res" ]; then
  181. warn "resource type of \"$_hr_ref\" has no system-package-manager translation"
  182. not_found_add "$_hr_ref"
  183. return
  184. fi
  185. case $_hr_res in
  186. *[!A-Za-z0-9._+/-]*)
  187. warn "resource name of \"$_hr_ref\" has no system-package-manager translation"
  188. not_found_add "$_hr_ref"
  189. return
  190. ;;
  191. esac
  192. case $_hr_type in
  193. bin|sbin)
  194. record_providers "$_hr_ref" "cmd:$_hr_res"
  195. ;;
  196. lib)
  197. record_providers "$_hr_ref" "so:$_hr_res"
  198. ;;
  199. pc)
  200. record_providers "$_hr_ref" "pc:${_hr_res%.pc}"
  201. ;;
  202. libexec)
  203. record_file_owner "$_hr_ref" "/usr/libexec/$_hr_res"
  204. ;;
  205. gir)
  206. record_file_owner "$_hr_ref" "/usr/share/gir-1.0/$_hr_res"
  207. ;;
  208. typelib)
  209. record_file_owner "$_hr_ref" "/usr/lib/girepository-1.0/$_hr_res"
  210. ;;
  211. gio)
  212. record_file_owner "$_hr_ref" "/usr/lib/gio/modules/$_hr_res"
  213. ;;
  214. res)
  215. record_file_owner "$_hr_ref" "/usr/share/$_hr_res"
  216. ;;
  217. cfg)
  218. record_file_owner "$_hr_ref" "/etc/$_hr_res"
  219. ;;
  220. man)
  221. record_file_owner "$_hr_ref" "/usr/share/man/$_hr_res"
  222. ;;
  223. info)
  224. record_file_owner "$_hr_ref" "/usr/share/info/$_hr_res"
  225. ;;
  226. locale)
  227. record_file_owner "$_hr_ref" "/usr/share/locale/$_hr_res"
  228. ;;
  229. inc)
  230. record_file_owner "$_hr_ref" "/usr/include/$_hr_res"
  231. ;;
  232. vapi)
  233. set -- "/usr/share/vala/vapi/$_hr_res"
  234. for _hr_d in /usr/share/vala-*/vapi/"$_hr_res"; do
  235. if [ -f "$_hr_d" ]; then
  236. set -- "$@" "$_hr_d"
  237. fi
  238. done
  239. record_file_owner "$_hr_ref" "$@"
  240. ;;
  241. rootpath)
  242. record_file_owner "$_hr_ref" "/$_hr_res"
  243. ;;
  244. tag)
  245. _hr_t=${_hr_res%.tag}
  246. record_file_owner "$_hr_ref" "/usr/share/usm-tags/$(printf '%s' "$_hr_t" | tr '.' '/').tag"
  247. ;;
  248. *)
  249. warn "resource type of \"$_hr_ref\" has no system-package-manager translation"
  250. not_found_add "$_hr_ref"
  251. return
  252. ;;
  253. esac
  254. }
  255. counts_for() {
  256. _cf_name=$1
  257. _cf_cached=
  258. if [ -s "$WORK/counts" ]; then
  259. _cf_cached=$(awk -F'\t' -v n="$_cf_name" '$1 == n { print $2 " " $3; exit }' "$WORK/counts") || _cf_cached=
  260. fi
  261. if [ -n "$_cf_cached" ]; then
  262. printf '%s\n' "$_cf_cached"
  263. return
  264. fi
  265. _cf_cl=$(sp_search --recursive -- "$_cf_name" 2>"$WORK/rec.err" || true)
  266. if [ -z "$_cf_cl" ] || grep -q '^ERROR' "$WORK/rec.err" 2>/dev/null; then
  267. warn "could not resolve solo install of $_cf_name, estimating dependency counts"
  268. if grep -qx -F "$_cf_name" "$WORK/installed" 2>/dev/null; then
  269. printf '1 1\n'
  270. else
  271. printf '1 0\n'
  272. fi
  273. return
  274. fi
  275. printf '%s\n' "$_cf_cl" | strip_version >"$WORK/cl"
  276. _cf_dep=$(awk 'END { print NR }' "$WORK/cl")
  277. _cf_inst=0
  278. if [ -s "$WORK/installed" ]; then
  279. _cf_inst=$(grep -x -F -f "$WORK/installed" "$WORK/cl" | awk 'END { print NR }') || _cf_inst=0
  280. fi
  281. printf '%s\t%s\t%s\n' "$_cf_name" "$_cf_dep" "$_cf_inst" >>"$WORK/counts"
  282. printf '%s %s\n' "$_cf_dep" "$_cf_inst"
  283. }
  284. cmd_query() {
  285. [ $# -ge 1 ] || die_usage
  286. mkwork
  287. prime_index_cache
  288. apk info >"$WORK/installed" 2>/dev/null || : >"$WORK/installed"
  289. : >"$WORK/map"
  290. : >"$WORK/nf"
  291. : >"$WORK/counts"
  292. : >"$WORK/seen"
  293. for _q_ref in "$@"; do
  294. if [ -n "$_q_ref" ] && grep -x -F -q "$_q_ref" "$WORK/seen" 2>/dev/null; then
  295. continue
  296. fi
  297. printf '%s\n' "$_q_ref" >>"$WORK/seen"
  298. handle_ref "$_q_ref"
  299. done
  300. _q_out='{"not-found":['
  301. _q_first=1
  302. while IFS= read -r _q_r; do
  303. [ -n "$_q_r" ] || continue
  304. if [ "$_q_first" = 1 ]; then _q_first=0; else _q_out="$_q_out,"; fi
  305. _q_out="$_q_out\"$(json_escape "$_q_r")\""
  306. done <"$WORK/nf"
  307. _q_out="$_q_out],\"packages\":["
  308. _q_first=1
  309. for _q_nm in $(awk -F'\t' '{ print $1 }' "$WORK/map" | sort -u); do
  310. if [ "$_q_first" = 1 ]; then _q_first=0; else _q_out="$_q_out,"; fi
  311. awk -F'\t' -v n="$_q_nm" '$1 == n { print $2 }' "$WORK/map" >"$WORK/tmpres"
  312. _q_res=""
  313. _q_rf=1
  314. while IFS= read -r _q_rr; do
  315. if [ "$_q_rf" = 1 ]; then _q_rf=0; else _q_res="$_q_res,"; fi
  316. _q_res="$_q_res\"$(json_escape "$_q_rr")\""
  317. done <"$WORK/tmpres"
  318. _q_cnts=$(counts_for "$_q_nm")
  319. _q_dep=${_q_cnts%% *}
  320. _q_inst=${_q_cnts##* }
  321. _q_out="$_q_out{\"name\":\"$(json_escape "$_q_nm")\",\"resources\":[${_q_res}],\"dependency-count\":$_q_dep,\"installed-dependency-count\":$_q_inst}"
  322. done
  323. _q_out="$_q_out]}"
  324. emit "$_q_out"
  325. exit "$EXIT_OK"
  326. }
  327. classify_failure() {
  328. if grep -Eqi 'fetch|download|network|temporary failure|connection refused|timed out|untrusted|checksum|signature|mirror|404|503' "$1" 2>/dev/null; then
  329. printf '%s\n' "$EXIT_DOWNLOAD"
  330. elif grep -Eq 'unable to select|constraint|conflict|world' "$1" 2>/dev/null; then
  331. printf '%s\n' "$EXIT_RESOLVE"
  332. else
  333. printf '%s\n' "$EXIT_TRANSACTION"
  334. fi
  335. }
  336. # Packages whose apk split leaves a toolchain unusable alone: gcc ships no
  337. # crt objects (musl-dev owns Scrt1.o/crti.o/libssp_nonshared.a), so linking
  338. # fails without it. USM manifests cannot express crt files as resource
  339. # refs; this table completes the toolchain at install time instead.
  340. INSTALL_COMPANIONS="gcc:musl-dev"
  341. cmd_install() {
  342. [ $# -ge 1 ] || die_usage
  343. for _i_n in "$@"; do
  344. case $_i_n in
  345. -*) die_usage ;;
  346. esac
  347. done
  348. _i_expanded=""
  349. for _i_n in "$@"; do
  350. _i_expanded="$_i_expanded $_i_n"
  351. for _i_c in $INSTALL_COMPANIONS; do
  352. if [ "${_i_c%%:*}" = "$_i_n" ]; then
  353. _i_expanded="$_i_expanded ${_i_c#*:}"
  354. fi
  355. done
  356. done
  357. set -- $_i_expanded
  358. mkwork
  359. _i_simrc=0
  360. _i_sim=$(apk add --simulate --no-cache --no-progress -- "$@" 2>"$WORK/sim.err") || _i_simrc=$?
  361. if [ "$_i_simrc" != 0 ]; then
  362. _i_msg=$(apk_diag_line "$WORK/sim.err")
  363. [ -n "$_i_msg" ] || _i_msg="apk add --simulate failed with status $_i_simrc"
  364. emit "{\"type\":\"error\",\"message\":\"$(json_escape "$_i_msg")\"}"
  365. exit "$(classify_failure "$WORK/sim.err")"
  366. fi
  367. _i_total=$(printf '%s\n' "$_i_sim" | sed -n 's/^(\([0-9][0-9]*\)\/\([0-9][0-9]*\)).*/\2/p' | tail -n 1)
  368. [ -n "$_i_total" ] || _i_total=0
  369. emit "{\"type\":\"begin\",\"total\":$_i_total}"
  370. {
  371. apk add --no-cache --no-progress -- "$@" 2>"$WORK/inst.err"
  372. printf '%s\n' "$?" >"$WORK/rc"
  373. } | {
  374. _i_done=0
  375. while IFS= read -r _i_line || [ -n "$_i_line" ]; do
  376. case $_i_line in
  377. \(*\))
  378. _i_kn=${_i_line#"("}
  379. _i_kn=${_i_kn%%")"*}
  380. _i_k=${_i_kn%%/*}
  381. _i_n=${_i_kn##*/}
  382. _i_rest=${_i_line#*") "}
  383. _i_verb=${_i_rest%% *}
  384. _i_pkg=${_i_rest#* }
  385. _i_pkg=${_i_pkg%% *}
  386. case $_i_verb in
  387. Installing|Upgrading|Reinstalling|Downgrading)
  388. emit "{\"type\":\"package\",\"name\":\"$(json_escape "$_i_pkg")\",\"current\":$_i_k,\"total\":$_i_n,\"progress\":1.0}"
  389. emit "{\"type\":\"package-complete\",\"name\":\"$(json_escape "$_i_pkg")\"}"
  390. _i_done=$((_i_done + 1))
  391. ;;
  392. esac
  393. ;;
  394. esac
  395. done
  396. printf '%s\n' "$_i_done" >"$WORK/done"
  397. }
  398. _i_rc=$(cat "$WORK/rc" 2>/dev/null) || _i_rc=1
  399. if [ "$_i_rc" = 0 ]; then
  400. _i_done=$(cat "$WORK/done" 2>/dev/null) || _i_done=0
  401. emit "{\"type\":\"complete\",\"status\":\"ok\",\"installed\":$_i_done}"
  402. exit "$EXIT_OK"
  403. fi
  404. _i_msg=$(apk_diag_line "$WORK/inst.err")
  405. [ -n "$_i_msg" ] || _i_msg="apk add failed with status $_i_rc"
  406. emit "{\"type\":\"error\",\"message\":\"$(json_escape "$_i_msg")\"}"
  407. exit "$(classify_failure "$WORK/inst.err")"
  408. }
  409. cmd_plan() {
  410. [ $# -ge 1 ] || die_usage
  411. for _p_n in "$@"; do
  412. case $_p_n in
  413. -*) die_usage ;;
  414. esac
  415. done
  416. _p_expanded=""
  417. for _p_n in "$@"; do
  418. _p_expanded="$_p_expanded $_p_n"
  419. for _p_c in $INSTALL_COMPANIONS; do
  420. if [ "${_p_c%%:*}" = "$_p_n" ]; then
  421. _p_expanded="$_p_expanded ${_p_c#*:}"
  422. fi
  423. done
  424. done
  425. set -- $_p_expanded
  426. mkwork
  427. _p_rc=0
  428. _p_sim=$(apk add --simulate --no-cache --no-progress -- "$@" 2>"$WORK/plan.err") || _p_rc=$?
  429. if [ "$_p_rc" != 0 ]; then
  430. _p_msg=$(apk_diag_line "$WORK/plan.err")
  431. [ -n "$_p_msg" ] || _p_msg="apk add --simulate failed with status $_p_rc"
  432. printf '%s: %s\n' "$PROG" "$_p_msg" >&2
  433. exit "$(classify_failure "$WORK/plan.err")"
  434. fi
  435. # simulate output names every package the transaction would touch:
  436. # "(3/7) Installing musl (1.2.5-r1)"
  437. _p_json=$(printf '%s\n' "$_p_sim" \
  438. | sed -n 's/^(\([0-9][0-9]*\)\/\([0-9][0-9]*\)) Installing \([^ ]*\) .*/"\3"/p' \
  439. | awk 'NR>1{printf ","} {printf "%s", $0}')
  440. printf '{"packages":[%s]}\n' "$_p_json"
  441. exit "$EXIT_OK"
  442. }
  443. main() {
  444. if [ $# -lt 1 ]; then
  445. die_usage
  446. fi
  447. if ! command -v apk >/dev/null 2>&1; then
  448. if [ "$1" = install ]; then
  449. emit '{"type":"error","message":"apk not found in PATH"}'
  450. exit "$EXIT_FAILURE"
  451. fi
  452. warn "apk not found in PATH"
  453. exit "$EXIT_RESOLVE"
  454. fi
  455. _m_cmd=$1
  456. shift
  457. case $_m_cmd in
  458. query)
  459. cmd_query "$@"
  460. ;;
  461. plan)
  462. cmd_plan "$@"
  463. ;;
  464. install)
  465. cmd_install "$@"
  466. ;;
  467. -h|--help|help)
  468. printf 'usage: %s query <usm-ref>...\n' "$PROG"
  469. printf ' %s install <native-name>...\n' "$PROG"
  470. exit "$EXIT_OK"
  471. ;;
  472. *)
  473. die_usage
  474. ;;
  475. esac
  476. }
  477. main "$@"