]> git.proxmox.com Git - mirror_lxc.git/blob - templates/lxc-oci.in
Merge pull request #2287 from thyth/master
[mirror_lxc.git] / templates / lxc-oci.in
1 #!/bin/bash
2
3 # Create application containers from OCI images
4
5 # Copyright © 2014 Stéphane Graber <stgraber@ubuntu.com>
6 # Copyright © 2017 Serge Hallyn <serge@hallyn.com>
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12
13 # This library is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # Lesser General Public License for more details.
17
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
21 # USA
22
23 set -eu
24
25 # Make sure the usual locations are in PATH
26 export PATH=$PATH:/usr/sbin:/usr/bin:/sbin:/bin
27
28 # Check for required binaries
29 for bin in skopeo umoci jq; do
30 if ! which $bin >/dev/null 2>&1; then
31 echo "ERROR: Missing required tool: $bin" 1>&2
32 exit 1
33 fi
34 done
35
36 LOCALSTATEDIR="@LOCALSTATEDIR@"
37 LXC_TEMPLATE_CONFIG="@LXCTEMPLATECONFIG@"
38 LXC_HOOK_DIR="@LXCHOOKDIR@"
39
40 # Some useful functions
41 cleanup() {
42 if [ -d "${DOWNLOAD_TEMP}" ]; then
43 rm -Rf "${DOWNLOAD_TEMP}"
44 fi
45
46 if [ -d "${LXC_ROOTFS}.tmp" ]; then
47 rm -Rf "${LXC_ROOTFS}.tmp"
48 fi
49 }
50
51 in_userns() {
52 [ -e /proc/self/uid_map ] || { echo no; return; }
53 while read -r line; do
54 fields="$(echo "$line" | awk '{ print $1 " " $2 " " $3 }')"
55 if [ "${fields}" = "0 0 4294967295" ]; then
56 echo no;
57 return;
58 fi
59 if echo "${fields}" | grep -q " 0 1$"; then
60 echo userns-root;
61 return;
62 fi
63 done < /proc/self/uid_map
64
65 [ "$(cat /proc/self/uid_map)" = "$(cat /proc/1/uid_map)" ] && { echo userns-root; return; }
66 echo yes
67 }
68
69 getconfigpath() {
70 basedir="$1"
71 q="$2"
72
73 digest=$(jq -c -r --arg q "$q" '.manifests[] | if .annotations."org.opencontainers.image.ref.name" == $q then .digest else empty end' < "${basedir}/index.json")
74 if [ -z "${digest}" ]; then
75 echo "$q not found in index.json" >&2
76 return
77 fi
78
79 # Ok we have the image config digest, now get the config from that
80 # shellcheck disable=SC2039
81 d=${digest:7}
82 cdigest=$(jq -c -r '.config.digest' < "${basedir}/blobs/sha256/${d}")
83 if [ -z "${cdigest}" ]; then
84 echo "container config not found" >&2
85 return
86 fi
87
88 # shellcheck disable=SC2039
89 d2=${cdigest:7}
90 echo "${basedir}/blobs/sha256/${d2}"
91 return
92 }
93
94 # Get entrypoint from oci image. Use sh if unspecified
95 getep() {
96 if [ "$#" -eq 0 ]; then
97 echo "/bin/sh"
98 return
99 fi
100
101 configpath="$1"
102
103 ep=$(jq -c '.config.Entrypoint[]?'< "${configpath}" | tr '\n' ' ')
104 cmd=$(jq -c '.config.Cmd[]?'< "${configpath}" | tr '\n' ' ')
105 if [ -z "${ep}" ]; then
106 ep="${cmd}"
107 if [ -z "${ep}" ]; then
108 ep="/bin/sh"
109 fi
110 elif [ -n "${cmd}" ]; then
111 ep="${ep} ${cmd}"
112 fi
113
114 echo "${ep}"
115 return
116 }
117
118 # get environment from oci image.
119 getenv() {
120 if [ "$#" -eq 0 ]; then
121 return
122 fi
123
124 configpath="$1"
125
126 env=$(jq -c -r '.config.Env[]'< "${configpath}")
127
128 echo "${env}"
129 return
130 }
131
132 # FIXME 1: only support numerical values in the configuration file.
133 # FIXME 2: from the OCI image spec: "If group/gid is not specified,
134 # the default group and supplementary groups of the given user/uid in
135 # /etc/passwd from the container are applied."
136 getuidgid() {
137 if [ "$#" -eq 0 ]; then
138 echo "0 0"
139 return
140 fi
141
142 configpath="$1"
143
144 uidgid=$(jq -c -r '.config.User // "0:0"' < "${configpath}")
145 # shellcheck disable=SC2039
146 uidgid=(${uidgid//:/ })
147
148 printf '%d %d' "${uidgid[0]:-0}" "${uidgid[1]:-0}" 2>/dev/null || true
149 return
150 }
151
152 # get cwd from oci image.
153 getcwd() {
154 if [ "$#" -eq 0 ]; then
155 echo "/"
156 return
157 fi
158
159 configpath="$1"
160
161 cwd=$(jq -c -r '.config.WorkingDir // "/"' < "${configpath}")
162
163 echo "${cwd}"
164 return
165 }
166
167 usage() {
168 cat <<EOF
169 LXC container template for OCI images
170
171 Special arguments:
172 [ -h | --help ]: Print this help message and exit.
173
174 Required arguments:
175 [ -u | --url <url> ]: The OCI image URL
176
177 Optional arguments:
178 [ --username <username> ]: The username for the registry
179 [ --password <password> ]: The password for the registry
180
181 LXC internal arguments (do not pass manually!):
182 [ --name <name> ]: The container name
183 [ --path <path> ]: The path to the container
184 [ --rootfs <rootfs> ]: The path to the container's rootfs
185 [ --mapped-uid <map> ]: A uid map (user namespaces)
186 [ --mapped-gid <map> ]: A gid map (user namespaces)
187 EOF
188 return 0
189 }
190
191 if ! options=$(getopt -o u:h -l help,url:,username:,password:,no-cache,dhcp,name:,path:,rootfs:,mapped-uid:,mapped-gid: -- "$@"); then
192 usage
193 exit 1
194 fi
195 eval set -- "$options"
196
197 OCI_URL=""
198 OCI_USERNAME=
199 OCI_PASSWORD=
200 OCI_USE_CACHE="true"
201 OCI_USE_DHCP="false"
202
203 LXC_MAPPED_GID=
204 LXC_MAPPED_UID=
205 LXC_NAME=
206 LXC_PATH=
207 LXC_ROOTFS=
208
209 while :; do
210 case "$1" in
211 -h|--help) usage && exit 1;;
212 -u|--url) OCI_URL=$2; shift 2;;
213 --username) OCI_USERNAME=$2; shift 2;;
214 --password) OCI_PASSWORD=$2; shift 2;;
215 --no-cache) OCI_USE_CACHE="false"; shift 1;;
216 --dhcp) OCI_USE_DHCP="true"; shift 1;;
217 --name) LXC_NAME=$2; shift 2;;
218 --path) LXC_PATH=$2; shift 2;;
219 --rootfs) LXC_ROOTFS=$2; shift 2;;
220 --mapped-uid) LXC_MAPPED_UID=$2; shift 2;;
221 --mapped-gid) LXC_MAPPED_GID=$2; shift 2;;
222 *) break;;
223 esac
224 done
225
226 # Check that we have all variables we need
227 if [ -z "$LXC_NAME" ] || [ -z "$LXC_PATH" ] || [ -z "$LXC_ROOTFS" ]; then
228 echo "ERROR: Not running through LXC" 1>&2
229 exit 1
230 fi
231
232 if [ -z "$OCI_URL" ]; then
233 echo "ERROR: no OCI URL given"
234 exit 1
235 fi
236
237 if [ -n "$OCI_PASSWORD" ] && [ -z "$OCI_USERNAME" ]; then
238 echo "ERROR: password given but no username specified"
239 exit 1
240 fi
241
242 if [ "${OCI_USE_CACHE}" = "true" ]; then
243 if ! skopeo copy --help | grep -q 'dest-shared-blob-dir'; then
244 echo "INFO: skopeo doesn't support blob caching"
245 OCI_USE_CACHE="false"
246 fi
247 fi
248
249 USERNS=$(in_userns)
250
251 if [ "$USERNS" = "yes" ]; then
252 if [ -z "$LXC_MAPPED_UID" ] || [ "$LXC_MAPPED_UID" = "-1" ]; then
253 echo "ERROR: In a user namespace without a map" 1>&2
254 exit 1
255 fi
256 fi
257
258 if [ "${OCI_USE_CACHE}" = "true" ]; then
259 if [ "$USERNS" = "yes" ]; then
260 DOWNLOAD_BASE="${HOME}/.cache/lxc"
261 else
262 DOWNLOAD_BASE="${LOCALSTATEDIR}/cache/lxc"
263 fi
264 else
265 DOWNLOAD_BASE=/tmp
266 fi
267 mkdir -p "${DOWNLOAD_BASE}"
268
269 # Trap all exit signals
270 trap cleanup EXIT HUP INT TERM
271
272 if ! which mktemp >/dev/null 2>&1; then
273 DOWNLOAD_TEMP="${DOWNLOAD_BASE}/lxc-oci.$$"
274 mkdir -p "${DOWNLOAD_TEMP}"
275 else
276 DOWNLOAD_TEMP=$(mktemp -d -p "${DOWNLOAD_BASE}")
277 fi
278
279 # Download the image
280 # shellcheck disable=SC2039
281 skopeo_args=("")
282 if [ -n "$OCI_USERNAME" ]; then
283 CREDENTIALS="${OCI_USERNAME}"
284
285 if [ -n "$OCI_PASSWORD" ]; then
286 CREDENTIALS="${CREDENTIALS}:${OCI_PASSWORD}"
287 fi
288
289 # shellcheck disable=SC2039
290 skopeo_args+=(--src-creds "${CREDENTIALS}")
291 fi
292
293 if [ "${OCI_USE_CACHE}" = "true" ]; then
294 # shellcheck disable=SC2039
295 # shellcheck disable=SC2068
296 skopeo_args+=(--dest-shared-blob-dir "${DOWNLOAD_BASE}")
297 # shellcheck disable=SC2039
298 # shellcheck disable=SC2068
299 skopeo copy ${skopeo_args[@]} "${OCI_URL}" "oci:${DOWNLOAD_TEMP}:latest"
300 ln -s "${DOWNLOAD_BASE}/sha256" "${DOWNLOAD_TEMP}/blobs/sha256"
301 else
302 # shellcheck disable=SC2039
303 # shellcheck disable=SC2068
304 skopeo copy ${skopeo_args[@]} "${OCI_URL}" "oci:${DOWNLOAD_TEMP}:latest"
305 fi
306
307 echo "Unpacking the rootfs"
308 # shellcheck disable=SC2039
309 umoci_args=("")
310 if [ -n "$LXC_MAPPED_UID" ] && [ "$LXC_MAPPED_UID" != "-1" ]; then
311 # shellcheck disable=SC2039
312 umoci_args+=(--rootless)
313 fi
314 # shellcheck disable=SC2039
315 # shellcheck disable=SC2068
316 umoci --log=error unpack ${umoci_args[@]} --image "${DOWNLOAD_TEMP}:latest" "${LXC_ROOTFS}.tmp"
317 rmdir "${LXC_ROOTFS}"
318 mv "${LXC_ROOTFS}.tmp/rootfs" "${LXC_ROOTFS}"
319
320 OCI_CONF_FILE=$(getconfigpath "${DOWNLOAD_TEMP}" latest)
321 LXC_CONF_FILE="${LXC_PATH}/config"
322 entrypoint=$(getep "${OCI_CONF_FILE}")
323 echo "lxc.execute.cmd = '${entrypoint}'" >> "${LXC_CONF_FILE}"
324 echo "lxc.mount.auto = proc:mixed sys:mixed cgroup:mixed" >> "${LXC_CONF_FILE}"
325
326 environment=$(getenv "${OCI_CONF_FILE}")
327 # shellcheck disable=SC2039
328 while read -r line; do
329 echo "lxc.environment = ${line}" >> "${LXC_CONF_FILE}"
330 done <<< "${environment}"
331
332 if [ -e "${LXC_TEMPLATE_CONFIG}/common.conf" ]; then
333 echo "lxc.include = ${LXC_TEMPLATE_CONFIG}/common.conf" >> "${LXC_CONF_FILE}"
334 fi
335
336 if [ -n "$LXC_MAPPED_UID" ] && [ "$LXC_MAPPED_UID" != "-1" ] && [ -e "${LXC_TEMPLATE_CONFIG}/userns.conf" ]; then
337 echo "lxc.include = ${LXC_TEMPLATE_CONFIG}/userns.conf" >> "${LXC_CONF_FILE}"
338 fi
339
340 if [ -e "${LXC_TEMPLATE_CONFIG}/oci.common.conf" ]; then
341 echo "lxc.include = ${LXC_TEMPLATE_CONFIG}/oci.common.conf" >> "${LXC_CONF_FILE}"
342 fi
343
344 if [ "${OCI_USE_DHCP}" = "true" ]; then
345 echo "lxc.hook.start-host = ${LXC_HOOK_DIR}/dhclient" >> "${LXC_CONF_FILE}"
346 echo "lxc.hook.stop = ${LXC_HOOK_DIR}/dhclient" >> "${LXC_CONF_FILE}"
347 fi
348
349 echo "lxc.uts.name = ${LXC_NAME}" >> "${LXC_CONF_FILE}"
350 # set the hostname
351 cat <<EOF > "${LXC_ROOTFS}/etc/hostname"
352 ${LXC_NAME}
353 EOF
354
355 # set minimal hosts
356 cat <<EOF > "${LXC_ROOTFS}/etc/hosts"
357 127.0.0.1 localhost
358 127.0.1.1 ${LXC_NAME}
359 ::1 localhost ip6-localhost ip6-loopback
360 fe00::0 ip6-localnet
361 ff00::0 ip6-mcastprefix
362 ff02::1 ip6-allnodes
363 ff02::2 ip6-allrouters
364 EOF
365
366 # shellcheck disable=SC2039
367 uidgid=($(getuidgid "${OCI_CONF_FILE}"))
368 # shellcheck disable=SC2039
369 echo "lxc.init.uid = ${uidgid[0]}" >> "${LXC_CONF_FILE}"
370 # shellcheck disable=SC2039
371 echo "lxc.init.gid = ${uidgid[1]}" >> "${LXC_CONF_FILE}"
372
373 cwd=$(getcwd "${OCI_CONF_FILE}")
374 echo "lxc.init.cwd = ${cwd}" >> "${LXC_CONF_FILE}"
375
376 if [ -n "$LXC_MAPPED_UID" ] && [ "$LXC_MAPPED_UID" != "-1" ]; then
377 chown "$LXC_MAPPED_UID" "$LXC_PATH/config" "$LXC_PATH/fstab" > /dev/null 2>&1 || true
378 fi
379 if [ -n "$LXC_MAPPED_GID" ] && [ "$LXC_MAPPED_GID" != "-1" ]; then
380 chgrp "$LXC_MAPPED_GID" "$LXC_PATH/config" "$LXC_PATH/fstab" > /dev/null 2>&1 || true
381 fi
382
383 exit 0