alpine-make-rootfs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. #!/bin/sh
  2. # vim: set ts=4:
  3. #---help---
  4. # Usage: alpine-make-rootfs [options] [--] <dest> [<script> [<script-opts...>]]
  5. #
  6. # This script creates Alpine Linux rootfs for containers. It must be run as
  7. # root - to create files with correct permissions and use chroot (optional).
  8. # If $APK is not available on the host system, then static apk-tools
  9. # specified by $APK_TOOLS_URI is downloaded and used.
  10. #
  11. # Arguments:
  12. # <dest> Path where to write the rootfs. It may be:
  13. # - path with suffix .tar, .tar.bz2, .tbz, .tar.gz, .tgz,
  14. # or tar.xz to create a TAR archive;
  15. # - other path to keep rootfs as a directory;
  16. # - or "-" to dump TAR archive (w/o compression) to STDOUT.
  17. #
  18. # <script> Path of script to execute after installing base system in
  19. # the prepared rootfs and before clean-up. Use "-" to read
  20. # the script from STDIN; if it doesn't start with a shebang,
  21. # "#!/bin/sh -e" is prepended.
  22. #
  23. # <script-opts> Arguments to pass to the script.
  24. #
  25. # Options and Environment Variables:
  26. # -b --branch ALPINE_BRANCH Alpine branch to install; used only when
  27. # --repositories-file is not specified. Default is v3.8.
  28. #
  29. # --keys-dir KEYS_DIR Path of directory with Alpine keys to copy into
  30. # the rootfs. Default is /etc/apk/keys. If does not exist,
  31. # keys for x86_64 embedded in this script will be used.
  32. #
  33. # -m --mirror-uri ALPINE_MIRROR URI of the Aports mirror to fetch packages; used only
  34. # when --repositories-file is not specified. Default is
  35. # https://nl.alpinelinux.org/alpine.
  36. #
  37. # -C --no-cleanup (CLEANUP) Don't umount and remove temporary directories when done.
  38. #
  39. # -p --packages PACKAGES Additional packages to install into the rootfs.
  40. #
  41. # -r --repositories-file REPOS_FILE Path of repositories file to copy into the rootfs.
  42. # Default is /etc/apk/repositories. If does not exist,
  43. # repositories file with Alpine's main and community
  44. # repositories on --mirror-uri is created.
  45. #
  46. # -c --script-chroot (SCRIPT_CHROOT) Bind <script>'s directory at /mnt inside the rootfs dir
  47. # and chroot into the rootfs before executing <script>.
  48. # Otherwise <script> is executed in the current directory
  49. # and $ROOTFS variable points to the rootfs directory.
  50. #
  51. # -d --temp-dir TEMP_DIR Path where to create a temporary directory; used for
  52. # downloading apk-tools when not available on the host
  53. # sytem or for rootfs when <dest> is "-" (i.e. STDOUT).
  54. # This path must not exist! Defaults to using `mkdir -d`.
  55. #
  56. # -t --timezone TIMEZONE Timezone to set (e.g. Europe/Prague). Default is to leave
  57. # timezone UTC.
  58. #
  59. # -h --help Show this help message and exit.
  60. #
  61. # -v --version Print version and exit.
  62. #
  63. # APK APK command to use. Default is "apk".
  64. #
  65. # APK_OPTS Options to pass into apk on each execution.
  66. # Default is "--no-progress".
  67. #
  68. # APK_TOOLS_URI URL of static apk-tools tarball to download if $APK is
  69. # not found on the host system. Default is x86_64 apk-tools
  70. # from https://github.com/alpinelinux/apk-tools/releases.
  71. #
  72. # APK_TOOLS_SHA256 SHA-256 checksum of $APK_TOOLS_URI.
  73. #
  74. # Each option can be also provided by environment variable. If both option and
  75. # variable is specified and the option accepts only one argument, then the
  76. # option takes precedence.
  77. #
  78. # https://github.com/alpinelinux/alpine-make-rootfs
  79. #---help---
  80. set -eu
  81. readonly PROGNAME='alpine-make-rootfs'
  82. readonly VERSION='0.1.0'
  83. # Base Alpine packages to install in rootfs.
  84. readonly ALPINE_BASE_PKGS='alpine-baselayout busybox busybox-suid musl-utils'
  85. # Alpine APK keys for verification of packages for x86_64.
  86. readonly ALPINE_KEYS='
  87. alpine-devel@lists.alpinelinux.org-4a6a0840.rsa.pub:MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1yHJxQgsHQREclQu4Ohe\nqxTxd1tHcNnvnQTu/UrTky8wWvgXT+jpveroeWWnzmsYlDI93eLI2ORakxb3gA2O\nQ0Ry4ws8vhaxLQGC74uQR5+/yYrLuTKydFzuPaS1dK19qJPXB8GMdmFOijnXX4SA\njixuHLe1WW7kZVtjL7nufvpXkWBGjsfrvskdNA/5MfxAeBbqPgaq0QMEfxMAn6/R\nL5kNepi/Vr4S39Xvf2DzWkTLEK8pcnjNkt9/aafhWqFVW7m3HCAII6h/qlQNQKSo\nGuH34Q8GsFG30izUENV9avY7hSLq7nggsvknlNBZtFUcmGoQrtx3FmyYsIC8/R+B\nywIDAQAB
  88. alpine-devel@lists.alpinelinux.org-5261cecb.rsa.pub:MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwlzMkl7b5PBdfMzGdCT0\ncGloRr5xGgVmsdq5EtJvFkFAiN8Ac9MCFy/vAFmS8/7ZaGOXoCDWbYVLTLOO2qtX\nyHRl+7fJVh2N6qrDDFPmdgCi8NaE+3rITWXGrrQ1spJ0B6HIzTDNEjRKnD4xyg4j\ng01FMcJTU6E+V2JBY45CKN9dWr1JDM/nei/Pf0byBJlMp/mSSfjodykmz4Oe13xB\nCa1WTwgFykKYthoLGYrmo+LKIGpMoeEbY1kuUe04UiDe47l6Oggwnl+8XD1MeRWY\nsWgj8sF4dTcSfCMavK4zHRFFQbGp/YFJ/Ww6U9lA3Vq0wyEI6MCMQnoSMFwrbgZw\nwwIDAQAB
  89. '
  90. # List of directories to remove when empty.
  91. readonly FUTILE_DIRS='
  92. /home /media/cdrom /media/floppy /media/usb /mnt /srv /usr/local/bin
  93. /usr/local/lib /usr/local/share
  94. '
  95. # Name used as a "virtual package" for temporarily installed packages.
  96. readonly VIRTUAL_PKG=".make-$PROGNAME"
  97. : ${APK:="apk"}
  98. : ${APK_OPTS:="--no-progress"}
  99. : ${APK_TOOLS_URI:="https://github.com/alpinelinux/apk-tools/releases/download/v2.10.1/apk-tools-2.10.1-x86_64-linux.tar.gz"}
  100. : ${APK_TOOLS_SHA256:="5b7e1a55de82c6713ad491f879e1a27bc0df8f2c815288e656b3e26e6f026f65"}
  101. # Set pipefail if supported.
  102. if ( set -o pipefail 2>/dev/null ); then
  103. set -o pipefail
  104. fi
  105. # For compatibility with systems that does not have "realpath" command.
  106. if ! command -v realpath >/dev/null; then
  107. alias realpath='readlink -f'
  108. fi
  109. die() {
  110. printf '\033[1;31mERROR:\033[0m %s\n' "$@" >&2 # bold red
  111. exit 1
  112. }
  113. einfo() {
  114. printf '\n\033[1;36m> %s\033[0m\n' "$@" >&2 # bold cyan
  115. }
  116. # Prints help and exists with the specified status.
  117. help() {
  118. sed -En '/^#---help---/,/^#---help---/p' "$0" | sed -E 's/^# ?//; 1d;$d;'
  119. exit ${1:-0}
  120. }
  121. # Cleans the host system. This function is executed before exiting the script.
  122. cleanup() {
  123. set +eu
  124. trap '' EXIT HUP INT TERM # unset trap to avoid loop
  125. if [ "$INSTALL_HOST_PKGS" = yes ]; then
  126. _apk del $VIRTUAL_PKG >&2
  127. fi
  128. if [ -d "$TEMP_DIR" ]; then
  129. rm -Rf "$TEMP_DIR"
  130. fi
  131. if [ -d "$rootfs" ]; then
  132. umount_recursively "$rootfs" \
  133. || die "Failed to unmount mounts inside $rootfs!"
  134. [ "$rootfs" = "$ROOTFS_DEST" ] || rm -Rf "$rootfs"
  135. fi
  136. }
  137. _apk() {
  138. "$APK" $APK_OPTS "$@"
  139. }
  140. # Writes Alpine APK keys embedded in this script into directory $1.
  141. dump_alpine_keys() {
  142. local dest_dir="$1"
  143. local content file line
  144. mkdir -p "$dest_dir"
  145. for line in $ALPINE_KEYS; do
  146. file=${line%%:*}
  147. content=${line#*:}
  148. printf -- "-----BEGIN PUBLIC KEY-----\n$content\n-----END PUBLIC KEY-----\n" \
  149. > "$dest_dir/$file"
  150. done
  151. }
  152. # Binds the directory $1 at the mountpoint $2 and sets propagation to private.
  153. mount_bind() {
  154. mkdir -p "$2"
  155. mount --bind "$1" "$2"
  156. mount --make-private "$2"
  157. }
  158. # Prepares chroot at the specified path.
  159. prepare_chroot() {
  160. local dest="$1"
  161. mkdir -p "$dest"/proc
  162. mount -t proc none "$dest"/proc
  163. mount_bind /dev "$dest"/dev
  164. mount_bind /sys "$dest"/sys
  165. install -D -m 644 /etc/resolv.conf "$dest"/etc/resolv.conf
  166. }
  167. # Sets up timezone $1 in Alpine rootfs.
  168. setup_timezone() {
  169. local timezone="$1"
  170. local rootfs="${2:-}"
  171. _apk add --root "$rootfs" tzdata
  172. install -D "$rootfs"/usr/share/zoneinfo/$timezone \
  173. "$rootfs"/etc/zoneinfo/$timezone
  174. ln -sf zoneinfo/$timezone "$rootfs"/etc/localtime
  175. _apk del --root "$rootfs" tzdata
  176. }
  177. # Unmounts all filesystems under the directory tree $1 (must be absolute path).
  178. umount_recursively() {
  179. local mount_point=$(realpath "$1")
  180. cat /proc/mounts \
  181. | cut -d ' ' -f 2 \
  182. | { grep "^$mount_point" || true; } \
  183. | sort -r \
  184. | xargs -r -n 1 umount
  185. }
  186. # Downloads the specified file using wget and checks checksum.
  187. wgets() (
  188. local url="$1"
  189. local sha256="$2"
  190. local dest="${3:-.}"
  191. cd "$dest" \
  192. && wget -T 10 --no-verbose "$url" \
  193. && echo "$sha256 ${url##*/}" | sha256sum -c
  194. )
  195. # Writes STDIN into file $1 and sets it executable bit. If the content does not
  196. # start with a shebang, prepends "#!/bin/sh -e" before the first line.
  197. write_script() {
  198. local filename="$1"
  199. cat > "$filename.tmp"
  200. if ! grep -q -m 1 '^#!' "$filename.tmp"; then
  201. echo "#!/bin/sh -e" > "$filename"
  202. fi
  203. cat "$filename.tmp" >> "$filename"
  204. rm "$filename.tmp"
  205. chmod +x "$filename"
  206. }
  207. #============================= M a i n ==============================#
  208. opts=$(getopt -n $PROGNAME -o b:m:Cp:r:cd:t:hV \
  209. -l branch:,keys-dir:,mirror-uri:,no-cleanup,packages:,repositories-file:,script-chroot,temp-dir:,timezone:,help,version \
  210. -- "$@") || help 1 >&2
  211. eval set -- "$opts"
  212. while [ $# -gt 0 ]; do
  213. n=2
  214. case "$1" in
  215. -b | --branch) ALPINE_BRANCH="$2";;
  216. --keys-dir) KEYS_DIR="$2";;
  217. -m | --mirror-uri) ALPINE_MIRROR="$2";;
  218. -C | --no-cleanup) CLEANUP='no'; n=1;;
  219. -p | --packages) PACKAGES="${PACKAGES:-} $2";;
  220. -r | --repositories-file) REPOS_FILE="$2";;
  221. -c | --script-chroot) SCRIPT_CHROOT='yes'; n=1;;
  222. -d | --temp-dir) TEMP_DIR="$2";;
  223. -t | --timezone) TIMEZONE="$2";;
  224. -h | --help) help 0;;
  225. -V | --version) echo "$PROGNAME $VERSION"; exit 0;;
  226. --) shift; break;;
  227. esac
  228. shift $n
  229. done
  230. [ $# -ne 0 ] || help 1 >&2
  231. ROOTFS_DEST="$1"; shift
  232. SCRIPT=${1:-}; shift
  233. [ "$(id -u)" -eq 0 ] || die 'This script must be run as root!'
  234. [ ! -e "${TEMP_DIR:-}" ] || die "Temp path $TEMP_DIR must not exist!"
  235. : ${ALPINE_BRANCH:="v3.8"}
  236. : ${ALPINE_MIRROR:="https://nl.alpinelinux.org/alpine"}
  237. : ${CLEANUP:="yes"}
  238. : ${KEYS_DIR:="/etc/apk/keys"}
  239. : ${PACKAGES:=}
  240. : ${REPOS_FILE:="/etc/apk/repositories"}
  241. : ${SCRIPT_CHROOT:="no"}
  242. : ${TEMP_DIR:="$(mktemp -d /tmp/$PROGNAME.XXXXXX)"}
  243. : ${TIMEZONE:=}
  244. host_pkgs=''
  245. case "$ROOTFS_DEST" in
  246. *.tar.bz2 | *.tbz) tar_opts='-cj';;
  247. *.tar.gz | *.tgz) tar_opts='-cz';;
  248. *.tar.xz) tar_opts='-cJ'; host_pkgs="$host_pkgs xz";;
  249. *.tar | -) tar_opts='-c';;
  250. *) tar_opts='';;
  251. esac
  252. rootfs="$ROOTFS_DEST"
  253. if [ "$ROOTFS_DEST" = '-' ]; then
  254. rootfs="$TEMP_DIR/rootfs"
  255. elif [ "$tar_opts" ]; then
  256. rootfs="${rootfs%.*}"
  257. rootfs="${rootfs%.tar}"
  258. fi
  259. if [ "$SCRIPT" = '-' ]; then
  260. SCRIPT="$TEMP_DIR/setup.sh"
  261. write_script "$SCRIPT"
  262. fi
  263. if [ "$SCRIPT" ]; then
  264. SCRIPT=$(realpath "$SCRIPT")
  265. fi
  266. if [ -f /etc/alpine-release ]; then
  267. : ${INSTALL_HOST_PKGS:="yes"}
  268. else
  269. : ${INSTALL_HOST_PKGS:="no"}
  270. fi
  271. [ "$CLEANUP" = no ] || trap cleanup EXIT HUP INT TERM
  272. #-----------------------------------------------------------------------
  273. if [ "$INSTALL_HOST_PKGS" = yes ] && [ "$host_pkgs" ]; then
  274. einfo "Installing $host_pkgs on host system"
  275. _apk add -t $VIRTUAL_PKG $host_pkgs >&2
  276. fi
  277. #-----------------------------------------------------------------------
  278. if ! command -v "$APK" >/dev/null; then
  279. einfo "$APK not found, downloading static apk-tools"
  280. wgets "$APK_TOOLS_URI" "$APK_TOOLS_SHA256" "$TEMP_DIR"
  281. tar -C "$TEMP_DIR" -xzf "$TEMP_DIR/${APK_TOOLS_URI##*/}"
  282. APK="$(ls "$TEMP_DIR"/apk-tools-*/apk)"
  283. fi
  284. #-----------------------------------------------------------------------
  285. einfo 'Installing base system'
  286. mkdir -p "$rootfs"/etc/apk/keys
  287. if [ -f "$REPOS_FILE" ]; then
  288. install -m 644 "$REPOS_FILE" "$rootfs"/etc/apk/repositories
  289. else
  290. cat > "$rootfs"/etc/apk/repositories <<-EOF
  291. $ALPINE_MIRROR/$ALPINE_BRANCH/main
  292. $ALPINE_MIRROR/$ALPINE_BRANCH/community
  293. EOF
  294. fi
  295. if [ -d "$KEYS_DIR" ]; then
  296. cp "$KEYS_DIR"/* "$rootfs"/etc/apk/keys/
  297. else
  298. dump_alpine_keys "$rootfs"/etc/apk/keys/
  299. fi
  300. _apk add --root "$rootfs" --update-cache --initdb $ALPINE_BASE_PKGS >&2
  301. # This package contains /etc/os-release, /etc/alpine-release and /etc/issue,
  302. # but we don't wanna install all its dependencies (e.g. openrc).
  303. _apk fetch --root "$rootfs" --stdout alpine-base \
  304. | tar -xz -C "$rootfs" etc >&2
  305. ln -sf /run "$rootfs"/var/run
  306. _apk add --root "$rootfs" -t "$VIRTUAL_PKG" apk-tools >&2
  307. #-----------------------------------------------------------------------
  308. if [ "$TIMEZONE" ]; then
  309. einfo "Setting timezone $TIMEZONE"
  310. setup_timezone "$TIMEZONE" "$rootfs" >&2
  311. fi
  312. #-----------------------------------------------------------------------
  313. if [ "$PACKAGES" ]; then
  314. einfo 'Installing additional packages'
  315. _apk add --root "$rootfs" $PACKAGES >&2
  316. fi
  317. #-----------------------------------------------------------------------
  318. if [ "$SCRIPT" ]; then
  319. script_name="${SCRIPT##*/}"
  320. if [ "$SCRIPT_CHROOT" = 'no' ]; then
  321. einfo "Executing script: $script_name $*"
  322. ROOTFS="$rootfs" "$SCRIPT" "$@" >&2 || die 'Script failed'
  323. else
  324. einfo "Executing script in chroot: $script_name $*"
  325. prepare_chroot "$rootfs"
  326. mount_bind "${SCRIPT%/*}" "$rootfs"/mnt
  327. chroot "$rootfs" \
  328. sh -c "cd /mnt && ./$script_name \"\$@\"" -- "$@" >&2 \
  329. || die 'Script failed'
  330. umount_recursively "$rootfs"
  331. fi
  332. fi
  333. #-----------------------------------------------------------------------
  334. einfo 'Cleaning-up rootfs'
  335. _apk del --root "$rootfs" --purge "$VIRTUAL_PKG" >&2
  336. rm -Rf "$rootfs"/var/cache/apk "$rootfs"/etc/resolv.conf
  337. rm -Rf "$rootfs"/dev/*
  338. [ -f "$rootfs"/sbin/apk ] \
  339. || rm -Rf "$rootfs"/etc/apk "$rootfs"/lib/apk
  340. for dir in $FUTILE_DIRS; do
  341. rmdir -p "$rootfs$dir" 2>/dev/null || true
  342. done
  343. #-----------------------------------------------------------------------
  344. if [ "$tar_opts" ]; then
  345. einfo 'Creating rootfs archive'
  346. tar -C "$rootfs" $tar_opts --numeric-owner -f "$ROOTFS_DEST" .
  347. if [ -f "$ROOTFS_DEST" ] && [ "${SUDO_UID:-}" ] && [ "${SUDO_GID:-}" ]; then
  348. chown "$SUDO_UID:$SUDO_GID" "$ROOTFS_DEST"
  349. fi
  350. ls -la "$ROOTFS_DEST" >&2
  351. fi