alpine-make-rootfs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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.10.
  28. #
  29. # -s --fs-skel-dir FS_SKEL_DIR Path of directory which content to recursively copy
  30. # (using rsync) into / of the rootfs.
  31. #
  32. # --fs-skel-chown FS_SKEL_CHOWN Force all files from FS_SKEL_DIR to be owned by the
  33. # specified USER:GROUP.
  34. #
  35. # --keys-dir KEYS_DIR Path of directory with Alpine keys to copy into
  36. # the rootfs. Default is /etc/apk/keys. If does not exist,
  37. # keys for x86_64 embedded in this script will be used.
  38. #
  39. # -m --mirror-uri ALPINE_MIRROR URI of the Aports mirror to fetch packages; used only
  40. # when --repositories-file is not specified. Default is
  41. # https://nl.alpinelinux.org/alpine.
  42. #
  43. # -C --no-cleanup (CLEANUP) Don't umount and remove temporary directories when done.
  44. #
  45. # --no-default-pkgs (DEFAULT_PKGS) Don't install the default base packages (alpine-baselayout
  46. # busybox busybox-suid musl-utils), i.e. only the packages
  47. # specified in --packages will be installed. Use only if
  48. # you know what are you doing!
  49. #
  50. # -p --packages PACKAGES Additional packages to install into the rootfs.
  51. #
  52. # -r --repositories-file REPOS_FILE Path of repositories file to copy into the rootfs.
  53. # Default is /etc/apk/repositories. If does not exist,
  54. # repositories file with Alpine's main and community
  55. # repositories on --mirror-uri is created.
  56. #
  57. # -c --script-chroot (SCRIPT_CHROOT) Bind <script>'s directory at /mnt inside the rootfs dir
  58. # and chroot into the rootfs before executing <script>.
  59. # Otherwise <script> is executed in the current directory
  60. # and $ROOTFS variable points to the rootfs directory.
  61. #
  62. # -d --temp-dir TEMP_DIR Path where to create a temporary directory; used for
  63. # downloading apk-tools when not available on the host
  64. # sytem or for rootfs when <dest> is "-" (i.e. STDOUT).
  65. # This path must not exist! Defaults to using `mkdir -d`.
  66. #
  67. # -t --timezone TIMEZONE Timezone to set (e.g. Europe/Prague). Default is to leave
  68. # timezone UTC.
  69. #
  70. # -h --help Show this help message and exit.
  71. #
  72. # -v --version Print version and exit.
  73. #
  74. # APK APK command to use. Default is "apk".
  75. #
  76. # APK_OPTS Options to pass into apk on each execution.
  77. # Default is "--no-progress".
  78. #
  79. # APK_TOOLS_URI URL of static apk-tools tarball to download if $APK is
  80. # not found on the host system. Default is x86_64 apk-tools
  81. # from https://github.com/alpinelinux/apk-tools/releases.
  82. #
  83. # APK_TOOLS_SHA256 SHA-256 checksum of $APK_TOOLS_URI.
  84. #
  85. # Each option can be also provided by environment variable. If both option and
  86. # variable is specified and the option accepts only one argument, then the
  87. # option takes precedence.
  88. #
  89. # https://github.com/alpinelinux/alpine-make-rootfs
  90. #---help---
  91. set -eu
  92. readonly PROGNAME='alpine-make-rootfs'
  93. readonly VERSION='0.5.1'
  94. # Base Alpine packages to install in rootfs.
  95. readonly ALPINE_BASE_PKGS='alpine-baselayout busybox busybox-suid musl-utils'
  96. # Alpine APK keys for verification of packages for x86_64.
  97. readonly ALPINE_KEYS='
  98. 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
  99. 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
  100. '
  101. # List of directories to remove when empty.
  102. readonly UNNECESSARY_DIRS='
  103. /home /media/cdrom /media/floppy /media/usb /mnt /srv /usr/local/bin
  104. /usr/local/lib /usr/local/share
  105. '
  106. # An opaque string used to detect changes in resolv.conf.
  107. readonly RESOLVCONF_MARK="### created by $PROGNAME ###"
  108. # Name used as a "virtual package" for temporarily installed packages.
  109. readonly VIRTUAL_PKG=".make-$PROGNAME"
  110. : ${APK:="apk"}
  111. : ${APK_OPTS:="--no-progress"}
  112. : ${APK_TOOLS_URI:="https://github.com/alpinelinux/apk-tools/releases/download/v2.10.4/apk-tools-2.10.4-x86_64-linux.tar.gz"}
  113. : ${APK_TOOLS_SHA256:="efe948160317fe78058e207554d0d9195a3dfcc35f77df278d30448d7b3eb892"}
  114. # Set pipefail if supported.
  115. if ( set -o pipefail 2>/dev/null ); then
  116. set -o pipefail
  117. fi
  118. # For compatibility with systems that does not have "realpath" command.
  119. if ! command -v realpath >/dev/null; then
  120. alias realpath='readlink -f'
  121. fi
  122. die() {
  123. printf '\033[1;31mERROR:\033[0m %s\n' "$@" >&2 # bold red
  124. exit 1
  125. }
  126. einfo() {
  127. printf '\n\033[1;36m> %s\033[0m\n' "$@" >&2 # bold cyan
  128. }
  129. # Prints help and exists with the specified status.
  130. help() {
  131. sed -En '/^#---help---/,/^#---help---/p' "$0" | sed -E 's/^# ?//; 1d;$d;'
  132. exit ${1:-0}
  133. }
  134. # Cleans the host system. This function is executed before exiting the script.
  135. cleanup() {
  136. set +eu
  137. trap '' EXIT HUP INT TERM # unset trap to avoid loop
  138. if [ "$INSTALL_HOST_PKGS" = yes ]; then
  139. _apk del $VIRTUAL_PKG >&2
  140. fi
  141. if [ -d "$TEMP_DIR" ]; then
  142. rm -Rf "$TEMP_DIR"
  143. fi
  144. if [ -d "$rootfs" ]; then
  145. umount_recursively "$rootfs" \
  146. || die "Failed to unmount mounts inside $rootfs!"
  147. [ "$rootfs" = "$ROOTFS_DEST" ] || rm -Rf "$rootfs"
  148. fi
  149. }
  150. _apk() {
  151. "$APK" $APK_OPTS "$@"
  152. }
  153. # Writes Alpine APK keys embedded in this script into directory $1.
  154. dump_alpine_keys() {
  155. local dest_dir="$1"
  156. local content file line
  157. mkdir -p "$dest_dir"
  158. for line in $ALPINE_KEYS; do
  159. file=${line%%:*}
  160. content=${line#*:}
  161. printf -- "-----BEGIN PUBLIC KEY-----\n$content\n-----END PUBLIC KEY-----\n" \
  162. > "$dest_dir/$file"
  163. done
  164. }
  165. # Binds the directory $1 at the mountpoint $2 and sets propagation to private.
  166. mount_bind() {
  167. mkdir -p "$2"
  168. mount --bind "$1" "$2"
  169. mount --make-private "$2"
  170. }
  171. # Prepares chroot at the specified path.
  172. prepare_chroot() {
  173. local dest="$1"
  174. mkdir -p "$dest"/proc
  175. mount -t proc none "$dest"/proc
  176. mount_bind /dev "$dest"/dev
  177. mount_bind /sys "$dest"/sys
  178. install -D -m 644 /etc/resolv.conf "$dest"/etc/resolv.conf
  179. echo "$RESOLVCONF_MARK" >> "$dest"/etc/resolv.conf
  180. }
  181. # Sets up timezone $1 in Alpine rootfs.
  182. setup_timezone() {
  183. local timezone="$1"
  184. local rootfs="${2:-}"
  185. _apk add --root "$rootfs" tzdata
  186. install -D "$rootfs"/usr/share/zoneinfo/$timezone \
  187. "$rootfs"/etc/zoneinfo/$timezone
  188. ln -sf zoneinfo/$timezone "$rootfs"/etc/localtime
  189. _apk del --root "$rootfs" tzdata
  190. }
  191. # Unmounts all filesystems under the directory tree $1 (must be absolute path).
  192. umount_recursively() {
  193. local mount_point=$(realpath "$1")
  194. cat /proc/mounts \
  195. | cut -d ' ' -f 2 \
  196. | { grep "^$mount_point/" || true; } \
  197. | sort -r \
  198. | xargs -r -n 1 umount
  199. }
  200. # Downloads the specified file using wget and checks checksum.
  201. wgets() (
  202. local url="$1"
  203. local sha256="$2"
  204. local dest="${3:-.}"
  205. cd "$dest" \
  206. && wget -T 10 --no-verbose "$url" \
  207. && echo "$sha256 ${url##*/}" | sha256sum -c
  208. )
  209. # Writes STDIN into file $1 and sets it executable bit. If the content does not
  210. # start with a shebang, prepends "#!/bin/sh -e" before the first line.
  211. write_script() {
  212. local filename="$1"
  213. cat > "$filename.tmp"
  214. if ! grep -q -m 1 '^#!' "$filename.tmp"; then
  215. echo "#!/bin/sh -e" > "$filename"
  216. fi
  217. cat "$filename.tmp" >> "$filename"
  218. rm "$filename.tmp"
  219. chmod +x "$filename"
  220. }
  221. #============================= M a i n ==============================#
  222. opts=$(getopt -n $PROGNAME -o b:m:Cp:r:s:cd:t:hV \
  223. -l branch:,fs-skel-chown:,fs-skel-dir:,keys-dir:,mirror-uri:,no-cleanup,no-default-pkgs,packages:,repositories-file:,script-chroot,temp-dir:,timezone:,help,version \
  224. -- "$@") || help 1 >&2
  225. eval set -- "$opts"
  226. while [ $# -gt 0 ]; do
  227. n=2
  228. case "$1" in
  229. -b | --branch) ALPINE_BRANCH="$2";;
  230. -s | --fs-skel-dir) FS_SKEL_DIR="$2";;
  231. --fs-skel-chown) FS_SKEL_CHOWN="$2";;
  232. --keys-dir) KEYS_DIR="$2";;
  233. -m | --mirror-uri) ALPINE_MIRROR="$2";;
  234. -C | --no-cleanup) CLEANUP='no'; n=1;;
  235. --no-default-pkgs) DEFAULT_PKGS='no'; n=1;;
  236. -p | --packages) PACKAGES="${PACKAGES:-} $2";;
  237. -r | --repositories-file) REPOS_FILE="$2";;
  238. -c | --script-chroot) SCRIPT_CHROOT='yes'; n=1;;
  239. -d | --temp-dir) TEMP_DIR="$2";;
  240. -t | --timezone) TIMEZONE="$2";;
  241. -h | --help) help 0;;
  242. -V | --version) echo "$PROGNAME $VERSION"; exit 0;;
  243. --) shift; break;;
  244. esac
  245. shift $n
  246. done
  247. [ $# -ne 0 ] || help 1 >&2
  248. ROOTFS_DEST="$1"; shift
  249. SCRIPT=
  250. [ $# -eq 0 ] || { SCRIPT="$1"; shift; }
  251. [ "$(id -u)" -eq 0 ] || die 'This script must be run as root!'
  252. [ ! -e "${TEMP_DIR:-}" ] || die "Temp path $TEMP_DIR must not exist!"
  253. : ${ALPINE_BRANCH:="v3.10"}
  254. : ${ALPINE_MIRROR:="https://nl.alpinelinux.org/alpine"}
  255. : ${CLEANUP:="yes"}
  256. : ${DEFAULT_PKGS:="yes"}
  257. : ${FS_SKEL_CHOWN:=}
  258. : ${FS_SKEL_DIR:=}
  259. : ${KEYS_DIR:="/etc/apk/keys"}
  260. : ${PACKAGES:=}
  261. : ${REPOS_FILE:="/etc/apk/repositories"}
  262. : ${SCRIPT_CHROOT:="no"}
  263. : ${TEMP_DIR:="$(mktemp -d /tmp/$PROGNAME.XXXXXX)"}
  264. : ${TIMEZONE:=}
  265. case "$ALPINE_BRANCH" in
  266. [0-9]*) ALPINE_BRANCH="v$ALPINE_BRANCH";;
  267. esac
  268. host_pkgs=''
  269. case "$ROOTFS_DEST" in
  270. *.tar.bz2 | *.tbz) tar_opts='-cj';;
  271. *.tar.gz | *.tgz) tar_opts='-cz';;
  272. *.tar.xz) tar_opts='-cJ'; host_pkgs="$host_pkgs xz";;
  273. *.tar | -) tar_opts='-c';;
  274. *) tar_opts='';;
  275. esac
  276. [ -z "$FS_SKEL_DIR" ] || host_pkgs="$host_pkgs rsync"
  277. rootfs_pkgs="$PACKAGES"
  278. if [ "$DEFAULT_PKGS" = 'yes' ]; then
  279. rootfs_pkgs="$ALPINE_BASE_PKGS $rootfs_pkgs"
  280. fi
  281. [ "$rootfs_pkgs" ] || die 'No packages specified to be installed!'
  282. rootfs="$ROOTFS_DEST"
  283. if [ "$ROOTFS_DEST" = '-' ]; then
  284. rootfs="$TEMP_DIR/rootfs"
  285. elif [ "$tar_opts" ]; then
  286. rootfs="${rootfs%.*}"
  287. rootfs="${rootfs%.tar}"
  288. fi
  289. if [ "$SCRIPT" = '-' ]; then
  290. SCRIPT="$TEMP_DIR/setup.sh"
  291. write_script "$SCRIPT"
  292. fi
  293. if [ "$SCRIPT" ]; then
  294. SCRIPT=$(realpath "$SCRIPT")
  295. fi
  296. if [ -f /etc/alpine-release ]; then
  297. : ${INSTALL_HOST_PKGS:="yes"}
  298. else
  299. : ${INSTALL_HOST_PKGS:="no"}
  300. fi
  301. [ "$CLEANUP" = no ] || trap cleanup EXIT HUP INT TERM
  302. #-----------------------------------------------------------------------
  303. if [ "$INSTALL_HOST_PKGS" = yes ] && [ "$host_pkgs" ]; then
  304. einfo "Installing $host_pkgs on host system"
  305. _apk add -t $VIRTUAL_PKG $host_pkgs >&2
  306. fi
  307. #-----------------------------------------------------------------------
  308. if ! command -v "$APK" >/dev/null; then
  309. einfo "$APK not found, downloading static apk-tools"
  310. wgets "$APK_TOOLS_URI" "$APK_TOOLS_SHA256" "$TEMP_DIR"
  311. tar -C "$TEMP_DIR" -xzf "$TEMP_DIR/${APK_TOOLS_URI##*/}"
  312. APK="$(ls "$TEMP_DIR"/apk-tools-*/apk)"
  313. fi
  314. #-----------------------------------------------------------------------
  315. einfo 'Installing system'
  316. mkdir -p "$rootfs"/etc/apk/keys
  317. if [ -f "$REPOS_FILE" ]; then
  318. install -m 644 "$REPOS_FILE" "$rootfs"/etc/apk/repositories
  319. else
  320. cat > "$rootfs"/etc/apk/repositories <<-EOF
  321. $ALPINE_MIRROR/$ALPINE_BRANCH/main
  322. $ALPINE_MIRROR/$ALPINE_BRANCH/community
  323. EOF
  324. fi
  325. if [ -d "$KEYS_DIR" ]; then
  326. cp "$KEYS_DIR"/* "$rootfs"/etc/apk/keys/
  327. else
  328. dump_alpine_keys "$rootfs"/etc/apk/keys/
  329. fi
  330. _apk add --root "$rootfs" --update-cache --initdb $rootfs_pkgs >&2
  331. if ! _apk info --root "$rootfs" --quiet --installed alpine-base; then
  332. # This package contains /etc/os-release, /etc/alpine-release and /etc/issue,
  333. # but we don't wanna install all its dependencies (e.g. openrc).
  334. _apk fetch --root "$rootfs" --stdout alpine-base \
  335. | tar -xz -C "$rootfs" etc >&2
  336. fi
  337. [ -e "$rootfs"/var/run ] || ln -s /run "$rootfs"/var/run
  338. #-----------------------------------------------------------------------
  339. if [ "$TIMEZONE" ]; then
  340. einfo "Setting timezone $TIMEZONE"
  341. setup_timezone "$TIMEZONE" "$rootfs" >&2
  342. fi
  343. #-----------------------------------------------------------------------
  344. if [ "$FS_SKEL_DIR" ]; then
  345. einfo "Copying content of $FS_SKEL_DIR into rootfs"
  346. [ "$FS_SKEL_CHOWN" ] \
  347. && rsync_opts="--chown $FS_SKEL_CHOWN" \
  348. || rsync_opts='--numeric-ids'
  349. rsync --archive --info=NAME2 --whole-file $rsync_opts "$FS_SKEL_DIR"/ "$rootfs"/ >&2
  350. # rsync may modify perms of the rootfs dir itself, so make sure it's correct.
  351. install -d -m 0755 -o root -g root "$rootfs"
  352. fi
  353. #-----------------------------------------------------------------------
  354. if [ "$SCRIPT" ]; then
  355. script_name="${SCRIPT##*/}"
  356. if [ "$SCRIPT_CHROOT" = 'no' ]; then
  357. einfo "Executing script: $script_name $*"
  358. ROOTFS="$rootfs" "$SCRIPT" "$@" >&2 || die 'Script failed'
  359. else
  360. einfo "Executing script in chroot: $script_name $*"
  361. _apk add --root "$rootfs" -t "$VIRTUAL_PKG" apk-tools >&2
  362. prepare_chroot "$rootfs"
  363. mount_bind "${SCRIPT%/*}" "$rootfs"/mnt
  364. chroot "$rootfs" \
  365. /bin/sh -c "cd /mnt && ./$script_name \"\$@\"" -- "$@" >&2 \
  366. || die 'Script failed'
  367. umount_recursively "$rootfs"
  368. fi
  369. fi
  370. #-----------------------------------------------------------------------
  371. einfo 'Cleaning-up rootfs'
  372. if _apk info --root "$rootfs" --quiet --installed "$VIRTUAL_PKG"; then
  373. _apk del --root "$rootfs" --purge "$VIRTUAL_PKG" >&2
  374. fi
  375. if grep -qw "$RESOLVCONF_MARK" "$rootfs"/etc/resolv.conf 2>/dev/null; then
  376. rm "$rootfs"/etc/resolv.conf
  377. fi
  378. rm -Rf "$rootfs"/dev/*
  379. if [ -f "$rootfs"/sbin/apk ]; then
  380. rm -Rf "$rootfs"/var/cache/apk/*
  381. else
  382. rm -Rf "$rootfs"/etc/apk "$rootfs"/lib/apk "$rootfs"/var/cache/apk
  383. fi
  384. for dir in $UNNECESSARY_DIRS; do
  385. rmdir -p "$rootfs$dir" 2>/dev/null || true
  386. done
  387. #-----------------------------------------------------------------------
  388. if [ "$tar_opts" ]; then
  389. einfo 'Creating rootfs archive'
  390. tar -C "$rootfs" $tar_opts --numeric-owner -f "$ROOTFS_DEST" .
  391. if [ -f "$ROOTFS_DEST" ] && [ "${SUDO_UID:-}" ] && [ "${SUDO_GID:-}" ]; then
  392. chown "$SUDO_UID:$SUDO_GID" "$ROOTFS_DEST"
  393. fi
  394. ls -la "$ROOTFS_DEST" >&2
  395. fi