docker-debian.sh 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #!/usr/bin/env bash
  2. #-------------------------------------------------------------------------------------------------------------
  3. # Copyright (c) Microsoft Corporation. All rights reserved.
  4. # Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
  5. #-------------------------------------------------------------------------------------------------------------
  6. #
  7. # Docs: https://github.com/microsoft/vscode-dev-containers/blob/main/script-library/docs/docker.md
  8. # Maintainer: The VS Code and Codespaces Teams
  9. #
  10. # Syntax: ./docker-debian.sh [enable non-root docker socket access flag] [source socket] [target socket] [non-root user] [use moby] [CLI version]
  11. ENABLE_NONROOT_DOCKER=${1:-"true"}
  12. SOURCE_SOCKET=${2:-"/var/run/docker-host.sock"}
  13. TARGET_SOCKET=${3:-"/var/run/docker.sock"}
  14. USERNAME=${4:-"automatic"}
  15. USE_MOBY=${5:-"true"}
  16. DOCKER_VERSION=${6:-"latest"}
  17. MICROSOFT_GPG_KEYS_URI="https://packages.microsoft.com/keys/microsoft.asc"
  18. DOCKER_DASH_COMPOSE_VERSION="1"
  19. set -e
  20. if [ "$(id -u)" -ne 0 ]; then
  21. echo -e 'Script must be run as root. Use sudo, su, or add "USER root" to your Dockerfile before running this script.'
  22. exit 1
  23. fi
  24. # Determine the appropriate non-root user
  25. if [ "${USERNAME}" = "auto" ] || [ "${USERNAME}" = "automatic" ]; then
  26. USERNAME=""
  27. POSSIBLE_USERS=("vscode" "node" "codespace" "$(awk -v val=1000 -F ":" '$3==val{print $1}' /etc/passwd)")
  28. for CURRENT_USER in ${POSSIBLE_USERS[@]}; do
  29. if id -u ${CURRENT_USER} > /dev/null 2>&1; then
  30. USERNAME=${CURRENT_USER}
  31. break
  32. fi
  33. done
  34. if [ "${USERNAME}" = "" ]; then
  35. USERNAME=root
  36. fi
  37. elif [ "${USERNAME}" = "none" ] || ! id -u ${USERNAME} > /dev/null 2>&1; then
  38. USERNAME=root
  39. fi
  40. # Get central common setting
  41. get_common_setting() {
  42. if [ "${common_settings_file_loaded}" != "true" ]; then
  43. curl -sfL "https://aka.ms/vscode-dev-containers/script-library/settings.env" 2>/dev/null -o /tmp/vsdc-settings.env || echo "Could not download settings file. Skipping."
  44. common_settings_file_loaded=true
  45. fi
  46. if [ -f "/tmp/vsdc-settings.env" ]; then
  47. local multi_line=""
  48. if [ "$2" = "true" ]; then multi_line="-z"; fi
  49. local result="$(grep ${multi_line} -oP "$1=\"?\K[^\"]+" /tmp/vsdc-settings.env | tr -d '\0')"
  50. if [ ! -z "${result}" ]; then declare -g $1="${result}"; fi
  51. fi
  52. echo "$1=${!1}"
  53. }
  54. # Function to run apt-get if needed
  55. apt_get_update_if_needed()
  56. {
  57. if [ ! -d "/var/lib/apt/lists" ] || [ "$(ls /var/lib/apt/lists/ | wc -l)" = "0" ]; then
  58. echo "Running apt-get update..."
  59. apt-get update
  60. else
  61. echo "Skipping apt-get update."
  62. fi
  63. }
  64. # Checks if packages are installed and installs them if not
  65. check_packages() {
  66. if ! dpkg -s "$@" > /dev/null 2>&1; then
  67. apt_get_update_if_needed
  68. apt-get -y install --no-install-recommends "$@"
  69. fi
  70. }
  71. # Figure out correct version of a three part version number is not passed
  72. find_version_from_git_tags() {
  73. local variable_name=$1
  74. local requested_version=${!variable_name}
  75. if [ "${requested_version}" = "none" ]; then return; fi
  76. local repository=$2
  77. local prefix=${3:-"tags/v"}
  78. local separator=${4:-"."}
  79. local last_part_optional=${5:-"false"}
  80. if [ "$(echo "${requested_version}" | grep -o "." | wc -l)" != "2" ]; then
  81. local escaped_separator=${separator//./\\.}
  82. local last_part
  83. if [ "${last_part_optional}" = "true" ]; then
  84. last_part="(${escaped_separator}[0-9]+)?"
  85. else
  86. last_part="${escaped_separator}[0-9]+"
  87. fi
  88. local regex="${prefix}\\K[0-9]+${escaped_separator}[0-9]+${last_part}$"
  89. local version_list="$(git ls-remote --tags ${repository} | grep -oP "${regex}" | tr -d ' ' | tr "${separator}" "." | sort -rV)"
  90. if [ "${requested_version}" = "latest" ] || [ "${requested_version}" = "current" ] || [ "${requested_version}" = "lts" ]; then
  91. declare -g ${variable_name}="$(echo "${version_list}" | head -n 1)"
  92. else
  93. set +e
  94. declare -g ${variable_name}="$(echo "${version_list}" | grep -E -m 1 "^${requested_version//./\\.}([\\.\\s]|$)")"
  95. set -e
  96. fi
  97. fi
  98. if [ -z "${!variable_name}" ] || ! echo "${version_list}" | grep "^${!variable_name//./\\.}$" > /dev/null 2>&1; then
  99. echo -e "Invalid ${variable_name} value: ${requested_version}\nValid values:\n${version_list}" >&2
  100. exit 1
  101. fi
  102. echo "${variable_name}=${!variable_name}"
  103. }
  104. # Ensure apt is in non-interactive to avoid prompts
  105. export DEBIAN_FRONTEND=noninteractive
  106. # Install dependencies
  107. check_packages apt-transport-https curl ca-certificates gnupg2 dirmngr
  108. if ! type git > /dev/null 2>&1; then
  109. apt_get_update_if_needed
  110. apt-get -y install git
  111. fi
  112. # Source /etc/os-release to get OS info
  113. . /etc/os-release
  114. # Fetch host/container arch.
  115. architecture="$(dpkg --print-architecture)"
  116. # Set up the necessary apt repos (either Microsoft's or Docker's)
  117. if [ "${USE_MOBY}" = "true" ]; then
  118. cli_package_name="moby-cli"
  119. # Import key safely and import Microsoft apt repo
  120. get_common_setting MICROSOFT_GPG_KEYS_URI
  121. curl -sSL ${MICROSOFT_GPG_KEYS_URI} | gpg --dearmor > /usr/share/keyrings/microsoft-archive-keyring.gpg
  122. echo "deb [arch=${architecture} signed-by=/usr/share/keyrings/microsoft-archive-keyring.gpg] https://packages.microsoft.com/repos/microsoft-${ID}-${VERSION_CODENAME}-prod ${VERSION_CODENAME} main" > /etc/apt/sources.list.d/microsoft.list
  123. else
  124. # Name of proprietary engine package
  125. cli_package_name="docker-ce-cli"
  126. # Import key safely and import Docker apt repo
  127. curl -fsSL https://download.docker.com/linux/${ID}/gpg | gpg --dearmor > /usr/share/keyrings/docker-archive-keyring.gpg
  128. echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/${ID} ${VERSION_CODENAME} stable" > /etc/apt/sources.list.d/docker.list
  129. fi
  130. # Refresh apt lists
  131. apt-get update
  132. # Soft version matching for CLI
  133. if [ "${DOCKER_VERSION}" = "latest" ] || [ "${DOCKER_VERSION}" = "lts" ] || [ "${DOCKER_VERSION}" = "stable" ]; then
  134. # Empty, meaning grab whatever "latest" is in apt repo
  135. cli_version_suffix=""
  136. else
  137. # Fetch a valid version from the apt-cache (eg: the Microsoft repo appends +azure, breakfix, etc...)
  138. docker_version_dot_escaped="${DOCKER_VERSION//./\\.}"
  139. docker_version_dot_plus_escaped="${docker_version_dot_escaped//+/\\+}"
  140. # Regex needs to handle debian package version number format: https://www.systutorials.com/docs/linux/man/5-deb-version/
  141. docker_version_regex="^(.+:)?${docker_version_dot_plus_escaped}([\\.\\+ ~:-]|$)"
  142. set +e # Don't exit if finding version fails - will handle gracefully
  143. cli_version_suffix="=$(apt-cache madison ${cli_package_name} | awk -F"|" '{print $2}' | sed -e 's/^[ \t]*//' | grep -E -m 1 "${docker_version_regex}")"
  144. set -e
  145. if [ -z "${cli_version_suffix}" ] || [ "${cli_version_suffix}" = "=" ]; then
  146. echo "(!) No full or partial Docker / Moby version match found for \"${DOCKER_VERSION}\" on OS ${ID} ${VERSION_CODENAME} (${architecture}). Available versions:"
  147. apt-cache madison ${cli_package_name} | awk -F"|" '{print $2}' | grep -oP '^(.+:)?\K.+'
  148. exit 1
  149. fi
  150. echo "cli_version_suffix ${cli_version_suffix}"
  151. fi
  152. # Install Docker / Moby CLI if not already installed
  153. if type docker > /dev/null 2>&1; then
  154. echo "Docker / Moby CLI already installed."
  155. else
  156. if [ "${USE_MOBY}" = "true" ]; then
  157. apt-get -y install --no-install-recommends moby-cli${cli_version_suffix} moby-buildx
  158. apt-get -y install --no-install-recommends moby-compose || echo "(*) Package moby-compose (Docker Compose v2) not available for OS ${ID} ${VERSION_CODENAME} (${architecture}). Skipping."
  159. else
  160. apt-get -y install --no-install-recommends docker-ce-cli${cli_version_suffix}
  161. fi
  162. fi
  163. # Install Docker Compose if not already installed and is on a supported architecture
  164. if type docker-compose > /dev/null 2>&1; then
  165. echo "Docker Compose already installed."
  166. else
  167. TARGET_COMPOSE_ARCH="$(uname -m)"
  168. if [ "${TARGET_COMPOSE_ARCH}" = "amd64" ]; then
  169. TARGET_COMPOSE_ARCH="x86_64"
  170. fi
  171. if [ "${TARGET_COMPOSE_ARCH}" != "x86_64" ]; then
  172. # Use pip to get a version that runns on this architecture
  173. if ! dpkg -s python3-minimal python3-pip libffi-dev python3-venv > /dev/null 2>&1; then
  174. apt_get_update_if_needed
  175. apt-get -y install python3-minimal python3-pip libffi-dev python3-venv
  176. fi
  177. export PIPX_HOME=/usr/local/pipx
  178. mkdir -p ${PIPX_HOME}
  179. export PIPX_BIN_DIR=/usr/local/bin
  180. export PYTHONUSERBASE=/tmp/pip-tmp
  181. export PIP_CACHE_DIR=/tmp/pip-tmp/cache
  182. pipx_bin=pipx
  183. if ! type pipx > /dev/null 2>&1; then
  184. pip3 install --disable-pip-version-check --no-cache-dir --user pipx
  185. pipx_bin=/tmp/pip-tmp/bin/pipx
  186. fi
  187. ${pipx_bin} install --pip-args '--no-cache-dir --force-reinstall' docker-compose
  188. rm -rf /tmp/pip-tmp
  189. else
  190. find_version_from_git_tags DOCKER_DASH_COMPOSE_VERSION "https://github.com/docker/compose" "tags/"
  191. echo "(*) Installing docker-compose ${DOCKER_DASH_COMPOSE_VERSION}..."
  192. curl -fsSL "https://github.com/docker/compose/releases/download/${DOCKER_DASH_COMPOSE_VERSION}/docker-compose-Linux-x86_64" -o /usr/local/bin/docker-compose
  193. chmod +x /usr/local/bin/docker-compose
  194. fi
  195. fi
  196. # If init file already exists, exit
  197. if [ -f "/usr/local/share/docker-init.sh" ]; then
  198. exit 0
  199. fi
  200. echo "docker-init doesnt exist, adding..."
  201. # By default, make the source and target sockets the same
  202. if [ "${SOURCE_SOCKET}" != "${TARGET_SOCKET}" ]; then
  203. touch "${SOURCE_SOCKET}"
  204. ln -s "${SOURCE_SOCKET}" "${TARGET_SOCKET}"
  205. fi
  206. # Add a stub if not adding non-root user access, user is root
  207. if [ "${ENABLE_NONROOT_DOCKER}" = "false" ] || [ "${USERNAME}" = "root" ]; then
  208. echo '/usr/bin/env bash -c "\$@"' > /usr/local/share/docker-init.sh
  209. chmod +x /usr/local/share/docker-init.sh
  210. exit 0
  211. fi
  212. # If enabling non-root access and specified user is found, setup socat and add script
  213. chown -h "${USERNAME}":root "${TARGET_SOCKET}"
  214. if ! dpkg -s socat > /dev/null 2>&1; then
  215. apt_get_update_if_needed
  216. apt-get -y install socat
  217. fi
  218. tee /usr/local/share/docker-init.sh > /dev/null \
  219. << EOF
  220. #!/usr/bin/env bash
  221. #-------------------------------------------------------------------------------------------------------------
  222. # Copyright (c) Microsoft Corporation. All rights reserved.
  223. # Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
  224. #-------------------------------------------------------------------------------------------------------------
  225. set -e
  226. SOCAT_PATH_BASE=/tmp/vscr-docker-from-docker
  227. SOCAT_LOG=\${SOCAT_PATH_BASE}.log
  228. SOCAT_PID=\${SOCAT_PATH_BASE}.pid
  229. # Wrapper function to only use sudo if not already root
  230. sudoIf()
  231. {
  232. if [ "\$(id -u)" -ne 0 ]; then
  233. sudo "\$@"
  234. else
  235. "\$@"
  236. fi
  237. }
  238. # Log messages
  239. log()
  240. {
  241. echo -e "[\$(date)] \$@" | sudoIf tee -a \${SOCAT_LOG} > /dev/null
  242. }
  243. echo -e "\n** \$(date) **" | sudoIf tee -a \${SOCAT_LOG} > /dev/null
  244. log "Ensuring ${USERNAME} has access to ${SOURCE_SOCKET} via ${TARGET_SOCKET}"
  245. # If enabled, try to add a docker group with the right GID. If the group is root,
  246. # fall back on using socat to forward the docker socket to another unix socket so
  247. # that we can set permissions on it without affecting the host.
  248. if [ "${ENABLE_NONROOT_DOCKER}" = "true" ] && [ "${SOURCE_SOCKET}" != "${TARGET_SOCKET}" ] && [ "${USERNAME}" != "root" ] && [ "${USERNAME}" != "0" ]; then
  249. SOCKET_GID=\$(stat -c '%g' ${SOURCE_SOCKET})
  250. if [ "\${SOCKET_GID}" != "0" ]; then
  251. log "Adding user to group with GID \${SOCKET_GID}."
  252. if [ "\$(cat /etc/group | grep :\${SOCKET_GID}:)" = "" ]; then
  253. sudoIf groupadd --gid \${SOCKET_GID} docker-host
  254. fi
  255. # Add user to group if not already in it
  256. if [ "\$(id ${USERNAME} | grep -E "groups.*(=|,)\${SOCKET_GID}\(")" = "" ]; then
  257. sudoIf usermod -aG \${SOCKET_GID} ${USERNAME}
  258. fi
  259. else
  260. # Enable proxy if not already running
  261. if [ ! -f "\${SOCAT_PID}" ] || ! ps -p \$(cat \${SOCAT_PID}) > /dev/null; then
  262. log "Enabling socket proxy."
  263. log "Proxying ${SOURCE_SOCKET} to ${TARGET_SOCKET} for vscode"
  264. sudoIf rm -rf ${TARGET_SOCKET}
  265. (sudoIf socat UNIX-LISTEN:${TARGET_SOCKET},fork,mode=660,user=${USERNAME} UNIX-CONNECT:${SOURCE_SOCKET} 2>&1 | sudoIf tee -a \${SOCAT_LOG} > /dev/null & echo "\$!" | sudoIf tee \${SOCAT_PID} > /dev/null)
  266. else
  267. log "Socket proxy already running."
  268. fi
  269. fi
  270. log "Success"
  271. fi
  272. # Execute whatever commands were passed in (if any). This allows us
  273. # to set this script to ENTRYPOINT while still executing the default CMD.
  274. set +e
  275. exec "\$@"
  276. EOF
  277. chmod +x /usr/local/share/docker-init.sh
  278. chown ${USERNAME}:root /usr/local/share/docker-init.sh
  279. echo "Done!"