alpine-make-rootfs 15 KB

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