usm-spm-apk 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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 install <native-name>...\n' "$PROG" >&2
  78. exit "$EXIT_USAGE"
  79. }
  80. emit() {
  81. printf '%s\n' "$1"
  82. }
  83. json_escape() {
  84. printf '%s' "$1" | awk '
  85. {
  86. s = $0
  87. gsub(/\\/, "\\\\", s)
  88. gsub(/"/, "\\\"", s)
  89. gsub(/\t/, "\\t", s)
  90. gsub(/[[:cntrl:]]/, "", s)
  91. print s
  92. }'
  93. }
  94. mkwork() {
  95. WORK=$(mktemp -d "${TMPDIR:-/tmp}/usm-spm-apk.XXXXXX" 2>/dev/null) || {
  96. WORK="${TMPDIR:-/tmp}/usm-spm-apk.$$"
  97. (umask 077 && mkdir "$WORK")
  98. }
  99. trap cleanup EXIT
  100. }
  101. prime_index_cache() {
  102. CACHE="$WORK/cache"
  103. PRIMED=0
  104. if mkdir -p "$CACHE" && apk update -q --cache-dir "$CACHE" >/dev/null 2>"$WORK/prime.err"; then
  105. if [ -n "$(ls -A "$CACHE" 2>/dev/null)" ]; then
  106. PRIMED=1
  107. fi
  108. fi
  109. if [ "$PRIMED" != 1 ]; then
  110. warn "could not prime a repository index cache; every lookup will fetch indexes"
  111. fi
  112. }
  113. sp_search() {
  114. if [ "$PRIMED" = 1 ]; then
  115. apk search --cache-dir "$CACHE" "$@"
  116. else
  117. apk search --no-cache "$@"
  118. fi
  119. }
  120. apk_diag_line() {
  121. [ -r "$1" ] || return 0
  122. sed -n 's/^\(ERROR\|WARNING\):[[:space:]]*//p' "$1" | head -n 1
  123. }
  124. strip_version() {
  125. sed -e 's/-r[0-9][0-9]*$//' -e 's/-[0-9][0-9A-Za-z._+]*$//'
  126. }
  127. not_found_add() {
  128. printf '%s\n' "$1" >>"$WORK/nf"
  129. }
  130. map_add() {
  131. printf '%s\t%s\n' "$1" "$2" >>"$WORK/map"
  132. }
  133. record_providers() {
  134. _rp_ref=$1
  135. _rp_prov=$2
  136. _rp_out=$(sp_search -x -- "$_rp_prov" 2>"$WORK/search.err" || true)
  137. if { [ -z "$_rp_out" ] && [ -s "$WORK/search.err" ]; } || grep -q '^ERROR' "$WORK/search.err" 2>/dev/null; then
  138. warn "apk search failed for \"$_rp_prov\": $(apk_diag_line "$WORK/search.err")"
  139. exit "$EXIT_RESOLVE"
  140. fi
  141. if [ -n "$_rp_out" ]; then
  142. printf '%s\n' "$_rp_out" | strip_version | sort -u >"$WORK/pv"
  143. while IFS= read -r _rp_nm; do
  144. [ -n "$_rp_nm" ] || continue
  145. map_add "$_rp_nm" "$_rp_ref"
  146. done <"$WORK/pv"
  147. else
  148. not_found_add "$_rp_ref"
  149. fi
  150. }
  151. record_file_owner() {
  152. _fo_ref=$1
  153. shift
  154. _fo_hit=0
  155. for _fo_p in "$@"; do
  156. _fo_f=
  157. if [ -d "$_fo_p" ]; then
  158. _fo_f=$(find "$_fo_p" -type f 2>/dev/null | head -n 1) || _fo_f=
  159. elif [ -f "$_fo_p" ]; then
  160. _fo_f=$_fo_p
  161. else
  162. continue
  163. fi
  164. [ -n "$_fo_f" ] || continue
  165. _fo_own=$(apk info -W "$_fo_f" 2>/dev/null) || continue
  166. _fo_nm=$(printf '%s\n' "$_fo_own" | sed -n 's/^.* is owned by //p' | strip_version)
  167. [ -n "$_fo_nm" ] || continue
  168. map_add "$_fo_nm" "$_fo_ref"
  169. _fo_hit=1
  170. done
  171. if [ "$_fo_hit" != 1 ]; then
  172. not_found_add "$_fo_ref"
  173. fi
  174. }
  175. handle_ref() {
  176. _hr_ref=$1
  177. _hr_type=${_hr_ref%%:*}
  178. _hr_res=${_hr_ref#*:}
  179. if [ "$_hr_type" = "$_hr_ref" ] || [ -z "$_hr_res" ]; then
  180. warn "resource type of \"$_hr_ref\" has no system-package-manager translation"
  181. not_found_add "$_hr_ref"
  182. return
  183. fi
  184. case $_hr_res in
  185. *[!A-Za-z0-9._+/-]*)
  186. warn "resource name of \"$_hr_ref\" has no system-package-manager translation"
  187. not_found_add "$_hr_ref"
  188. return
  189. ;;
  190. esac
  191. case $_hr_type in
  192. bin|sbin)
  193. record_providers "$_hr_ref" "cmd:$_hr_res"
  194. ;;
  195. lib)
  196. record_providers "$_hr_ref" "so:$_hr_res"
  197. ;;
  198. pc)
  199. record_providers "$_hr_ref" "pc:${_hr_res%.pc}"
  200. ;;
  201. libexec)
  202. record_file_owner "$_hr_ref" "/usr/libexec/$_hr_res"
  203. ;;
  204. gir)
  205. record_file_owner "$_hr_ref" "/usr/share/gir-1.0/$_hr_res"
  206. ;;
  207. typelib)
  208. record_file_owner "$_hr_ref" "/usr/lib/girepository-1.0/$_hr_res"
  209. ;;
  210. gio)
  211. record_file_owner "$_hr_ref" "/usr/lib/gio/modules/$_hr_res"
  212. ;;
  213. res)
  214. record_file_owner "$_hr_ref" "/usr/share/$_hr_res"
  215. ;;
  216. cfg)
  217. record_file_owner "$_hr_ref" "/etc/$_hr_res"
  218. ;;
  219. man)
  220. record_file_owner "$_hr_ref" "/usr/share/man/$_hr_res"
  221. ;;
  222. info)
  223. record_file_owner "$_hr_ref" "/usr/share/info/$_hr_res"
  224. ;;
  225. locale)
  226. record_file_owner "$_hr_ref" "/usr/share/locale/$_hr_res"
  227. ;;
  228. inc)
  229. record_file_owner "$_hr_ref" "/usr/include/$_hr_res"
  230. ;;
  231. vapi)
  232. set -- "/usr/share/vala/vapi/$_hr_res"
  233. for _hr_d in /usr/share/vala-*/vapi/"$_hr_res"; do
  234. if [ -f "$_hr_d" ]; then
  235. set -- "$@" "$_hr_d"
  236. fi
  237. done
  238. record_file_owner "$_hr_ref" "$@"
  239. ;;
  240. rootpath)
  241. record_file_owner "$_hr_ref" "/$_hr_res"
  242. ;;
  243. tag)
  244. _hr_t=${_hr_res%.tag}
  245. record_file_owner "$_hr_ref" "/usr/share/usm-tags/$(printf '%s' "$_hr_t" | tr '.' '/').tag"
  246. ;;
  247. *)
  248. warn "resource type of \"$_hr_ref\" has no system-package-manager translation"
  249. not_found_add "$_hr_ref"
  250. return
  251. ;;
  252. esac
  253. }
  254. counts_for() {
  255. _cf_name=$1
  256. _cf_cached=
  257. if [ -s "$WORK/counts" ]; then
  258. _cf_cached=$(awk -F'\t' -v n="$_cf_name" '$1 == n { print $2 " " $3; exit }' "$WORK/counts") || _cf_cached=
  259. fi
  260. if [ -n "$_cf_cached" ]; then
  261. printf '%s\n' "$_cf_cached"
  262. return
  263. fi
  264. _cf_cl=$(sp_search --recursive -- "$_cf_name" 2>"$WORK/rec.err" || true)
  265. if [ -z "$_cf_cl" ] || grep -q '^ERROR' "$WORK/rec.err" 2>/dev/null; then
  266. warn "could not resolve solo install of $_cf_name, estimating dependency counts"
  267. if grep -qx -F "$_cf_name" "$WORK/installed" 2>/dev/null; then
  268. printf '1 1\n'
  269. else
  270. printf '1 0\n'
  271. fi
  272. return
  273. fi
  274. printf '%s\n' "$_cf_cl" | strip_version >"$WORK/cl"
  275. _cf_dep=$(awk 'END { print NR }' "$WORK/cl")
  276. _cf_inst=0
  277. if [ -s "$WORK/installed" ]; then
  278. _cf_inst=$(grep -x -F -f "$WORK/installed" "$WORK/cl" | awk 'END { print NR }') || _cf_inst=0
  279. fi
  280. printf '%s\t%s\t%s\n' "$_cf_name" "$_cf_dep" "$_cf_inst" >>"$WORK/counts"
  281. printf '%s %s\n' "$_cf_dep" "$_cf_inst"
  282. }
  283. cmd_query() {
  284. [ $# -ge 1 ] || die_usage
  285. mkwork
  286. prime_index_cache
  287. apk info >"$WORK/installed" 2>/dev/null || : >"$WORK/installed"
  288. : >"$WORK/map"
  289. : >"$WORK/nf"
  290. : >"$WORK/counts"
  291. : >"$WORK/seen"
  292. for _q_ref in "$@"; do
  293. if [ -n "$_q_ref" ] && grep -x -F -q "$_q_ref" "$WORK/seen" 2>/dev/null; then
  294. continue
  295. fi
  296. printf '%s\n' "$_q_ref" >>"$WORK/seen"
  297. handle_ref "$_q_ref"
  298. done
  299. _q_out='{"not-found":['
  300. _q_first=1
  301. while IFS= read -r _q_r; do
  302. [ -n "$_q_r" ] || continue
  303. if [ "$_q_first" = 1 ]; then _q_first=0; else _q_out="$_q_out,"; fi
  304. _q_out="$_q_out\"$(json_escape "$_q_r")\""
  305. done <"$WORK/nf"
  306. _q_out="$_q_out],\"packages\":["
  307. _q_first=1
  308. for _q_nm in $(awk -F'\t' '{ print $1 }' "$WORK/map" | sort -u); do
  309. if [ "$_q_first" = 1 ]; then _q_first=0; else _q_out="$_q_out,"; fi
  310. awk -F'\t' -v n="$_q_nm" '$1 == n { print $2 }' "$WORK/map" >"$WORK/tmpres"
  311. _q_res=""
  312. _q_rf=1
  313. while IFS= read -r _q_rr; do
  314. if [ "$_q_rf" = 1 ]; then _q_rf=0; else _q_res="$_q_res,"; fi
  315. _q_res="$_q_res\"$(json_escape "$_q_rr")\""
  316. done <"$WORK/tmpres"
  317. _q_cnts=$(counts_for "$_q_nm")
  318. _q_dep=${_q_cnts%% *}
  319. _q_inst=${_q_cnts##* }
  320. _q_out="$_q_out{\"name\":\"$(json_escape "$_q_nm")\",\"resources\":[${_q_res}],\"dependency-count\":$_q_dep,\"installed-dependency-count\":$_q_inst}"
  321. done
  322. _q_out="$_q_out]}"
  323. emit "$_q_out"
  324. exit "$EXIT_OK"
  325. }
  326. classify_failure() {
  327. if grep -Eqi 'fetch|download|network|temporary failure|connection refused|timed out|untrusted|checksum|signature|mirror|404|503' "$1" 2>/dev/null; then
  328. printf '%s\n' "$EXIT_DOWNLOAD"
  329. elif grep -Eq 'unable to select|constraint|conflict|world' "$1" 2>/dev/null; then
  330. printf '%s\n' "$EXIT_RESOLVE"
  331. else
  332. printf '%s\n' "$EXIT_TRANSACTION"
  333. fi
  334. }
  335. # Packages whose apk split leaves a toolchain unusable alone: gcc ships no
  336. # crt objects (musl-dev owns Scrt1.o/crti.o/libssp_nonshared.a), so linking
  337. # fails without it. USM manifests cannot express crt files as resource
  338. # refs; this table completes the toolchain at install time instead.
  339. INSTALL_COMPANIONS="gcc:musl-dev"
  340. cmd_install() {
  341. [ $# -ge 1 ] || die_usage
  342. for _i_n in "$@"; do
  343. case $_i_n in
  344. -*) die_usage ;;
  345. esac
  346. done
  347. _i_expanded=""
  348. for _i_n in "$@"; do
  349. _i_expanded="$_i_expanded $_i_n"
  350. for _i_c in $INSTALL_COMPANIONS; do
  351. if [ "${_i_c%%:*}" = "$_i_n" ]; then
  352. _i_expanded="$_i_expanded ${_i_c#*:}"
  353. fi
  354. done
  355. done
  356. set -- $_i_expanded
  357. mkwork
  358. _i_simrc=0
  359. _i_sim=$(apk add --simulate --no-cache --no-progress -- "$@" 2>"$WORK/sim.err") || _i_simrc=$?
  360. if [ "$_i_simrc" != 0 ]; then
  361. _i_msg=$(apk_diag_line "$WORK/sim.err")
  362. [ -n "$_i_msg" ] || _i_msg="apk add --simulate failed with status $_i_simrc"
  363. emit "{\"type\":\"error\",\"message\":\"$(json_escape "$_i_msg")\"}"
  364. exit "$(classify_failure "$WORK/sim.err")"
  365. fi
  366. _i_total=$(printf '%s\n' "$_i_sim" | sed -n 's/^(\([0-9][0-9]*\)\/\([0-9][0-9]*\)).*/\2/p' | tail -n 1)
  367. [ -n "$_i_total" ] || _i_total=0
  368. emit "{\"type\":\"begin\",\"total\":$_i_total}"
  369. {
  370. apk add --no-cache --no-progress -- "$@" 2>"$WORK/inst.err"
  371. printf '%s\n' "$?" >"$WORK/rc"
  372. } | {
  373. _i_done=0
  374. while IFS= read -r _i_line || [ -n "$_i_line" ]; do
  375. case $_i_line in
  376. \(*\))
  377. _i_kn=${_i_line#"("}
  378. _i_kn=${_i_kn%%")"*}
  379. _i_k=${_i_kn%%/*}
  380. _i_n=${_i_kn##*/}
  381. _i_rest=${_i_line#*") "}
  382. _i_verb=${_i_rest%% *}
  383. _i_pkg=${_i_rest#* }
  384. _i_pkg=${_i_pkg%% *}
  385. case $_i_verb in
  386. Installing|Upgrading|Reinstalling|Downgrading)
  387. emit "{\"type\":\"package\",\"name\":\"$(json_escape "$_i_pkg")\",\"current\":$_i_k,\"total\":$_i_n,\"progress\":1.0}"
  388. emit "{\"type\":\"package-complete\",\"name\":\"$(json_escape "$_i_pkg")\"}"
  389. _i_done=$((_i_done + 1))
  390. ;;
  391. esac
  392. ;;
  393. esac
  394. done
  395. printf '%s\n' "$_i_done" >"$WORK/done"
  396. }
  397. _i_rc=$(cat "$WORK/rc" 2>/dev/null) || _i_rc=1
  398. if [ "$_i_rc" = 0 ]; then
  399. _i_done=$(cat "$WORK/done" 2>/dev/null) || _i_done=0
  400. emit "{\"type\":\"complete\",\"status\":\"ok\",\"installed\":$_i_done}"
  401. exit "$EXIT_OK"
  402. fi
  403. _i_msg=$(apk_diag_line "$WORK/inst.err")
  404. [ -n "$_i_msg" ] || _i_msg="apk add failed with status $_i_rc"
  405. emit "{\"type\":\"error\",\"message\":\"$(json_escape "$_i_msg")\"}"
  406. exit "$(classify_failure "$WORK/inst.err")"
  407. }
  408. main() {
  409. if [ $# -lt 1 ]; then
  410. die_usage
  411. fi
  412. if ! command -v apk >/dev/null 2>&1; then
  413. if [ "$1" = install ]; then
  414. emit '{"type":"error","message":"apk not found in PATH"}'
  415. exit "$EXIT_FAILURE"
  416. fi
  417. warn "apk not found in PATH"
  418. exit "$EXIT_RESOLVE"
  419. fi
  420. _m_cmd=$1
  421. shift
  422. case $_m_cmd in
  423. query)
  424. cmd_query "$@"
  425. ;;
  426. install)
  427. cmd_install "$@"
  428. ;;
  429. -h|--help|help)
  430. printf 'usage: %s query <usm-ref>...\n' "$PROG"
  431. printf ' %s install <native-name>...\n' "$PROG"
  432. exit "$EXIT_OK"
  433. ;;
  434. *)
  435. die_usage
  436. ;;
  437. esac
  438. }
  439. main "$@"