]> git.proxmox.com Git - mirror_lxc.git/blob - templates/lxc-oci.in
Merge pull request #2244 from brauner/2018-03-29/fixup
[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
268 # Trap all exit signals
269 trap cleanup EXIT HUP INT TERM
270
271 if ! which mktemp >/dev/null 2>&1; then
272 DOWNLOAD_TEMP="${DOWNLOAD_BASE}/lxc-oci.$$"
273 mkdir -p "${DOWNLOAD_TEMP}"
274 else
275 DOWNLOAD_TEMP=$(mktemp -d -p "${DOWNLOAD_BASE}")
276 fi
277
278 # Download the image
279 # shellcheck disable=SC2039
280 skopeo_args=("")
281 if [ -n "$OCI_USERNAME" ]; then
282 CREDENTIALS="${OCI_USERNAME}"
283
284 if [ -n "$OCI_PASSWORD" ]; then
285 CREDENTIALS="${CREDENTIALS}:${OCI_PASSWORD}"
286 fi
287
288 # shellcheck disable=SC2039
289 skopeo_args+=(--src-creds "${CREDENTIALS}")
290 fi
291
292 if [ "${OCI_USE_CACHE}" = "true" ]; then
293 # shellcheck disable=SC2039
294 # shellcheck disable=SC2068
295 skopeo_args+=(--dest-shared-blob-dir "${DOWNLOAD_BASE}")
296 # shellcheck disable=SC2039
297 # shellcheck disable=SC2068
298 skopeo copy ${skopeo_args[@]} "${OCI_URL}" "oci:${DOWNLOAD_TEMP}:latest"
299 ln -s "${DOWNLOAD_BASE}/sha256" "${DOWNLOAD_TEMP}/blobs/sha256"
300 else
301 # shellcheck disable=SC2039
302 # shellcheck disable=SC2068
303 skopeo copy ${skopeo_args[@]} "${OCI_URL}" "oci:${DOWNLOAD_TEMP}:latest"
304 fi
305
306 echo "Unpacking the rootfs"
307 # shellcheck disable=SC2039
308 umoci_args=("")
309 if [ -n "$LXC_MAPPED_UID" ] && [ "$LXC_MAPPED_UID" != "-1" ]; then
310 # shellcheck disable=SC2039
311 umoci_args+=(--rootless)
312 fi
313 # shellcheck disable=SC2039
314 # shellcheck disable=SC2068
315 umoci --log=error unpack ${umoci_args[@]} --image "${DOWNLOAD_TEMP}:latest" "${LXC_ROOTFS}.tmp"
316 rmdir "${LXC_ROOTFS}"
317 mv "${LXC_ROOTFS}.tmp/rootfs" "${LXC_ROOTFS}"
318
319 OCI_CONF_FILE=$(getconfigpath "${DOWNLOAD_TEMP}" latest)
320 LXC_CONF_FILE="${LXC_PATH}/config"
321 entrypoint=$(getep "${OCI_CONF_FILE}")
322 echo "lxc.execute.cmd = '${entrypoint}'" >> "${LXC_CONF_FILE}"
323 echo "lxc.mount.auto = proc:mixed sys:mixed cgroup:mixed" >> "${LXC_CONF_FILE}"
324
325 environment=$(getenv "${OCI_CONF_FILE}")
326 # shellcheck disable=SC2039
327 while read -r line; do
328 echo "lxc.environment = ${line}" >> "${LXC_CONF_FILE}"
329 done <<< "${environment}"
330
331 if [ -e "${LXC_TEMPLATE_CONFIG}/common.conf" ]; then
332 echo "lxc.include = ${LXC_TEMPLATE_CONFIG}/common.conf" >> "${LXC_CONF_FILE}"
333 fi
334
335 if [ -n "$LXC_MAPPED_UID" ] && [ "$LXC_MAPPED_UID" != "-1" ] && [ -e "${LXC_TEMPLATE_CONFIG}/userns.conf" ]; then
336 echo "lxc.include = ${LXC_TEMPLATE_CONFIG}/userns.conf" >> "${LXC_CONF_FILE}"
337 fi
338
339 if [ -e "${LXC_TEMPLATE_CONFIG}/oci.common.conf" ]; then
340 echo "lxc.include = ${LXC_TEMPLATE_CONFIG}/oci.common.conf" >> "${LXC_CONF_FILE}"
341 fi
342
343 if [ "${OCI_USE_DHCP}" = "true" ]; then
344 echo "lxc.hook.start-host = ${LXC_HOOK_DIR}/dhclient" >> "${LXC_CONF_FILE}"
345 echo "lxc.hook.stop = ${LXC_HOOK_DIR}/dhclient" >> "${LXC_CONF_FILE}"
346 fi
347
348 echo "lxc.uts.name = ${LXC_NAME}" >> "${LXC_CONF_FILE}"
349 # set the hostname
350 cat <<EOF > "${LXC_ROOTFS}/etc/hostname"
351 ${LXC_NAME}
352 EOF
353
354 # set minimal hosts
355 cat <<EOF > "${LXC_ROOTFS}/etc/hosts"
356 127.0.0.1 localhost
357 127.0.1.1 ${LXC_NAME}
358 ::1 localhost ip6-localhost ip6-loopback
359 fe00::0 ip6-localnet
360 ff00::0 ip6-mcastprefix
361 ff02::1 ip6-allnodes
362 ff02::2 ip6-allrouters
363 EOF
364
365 # shellcheck disable=SC2039
366 uidgid=($(getuidgid "${OCI_CONF_FILE}"))
367 # shellcheck disable=SC2039
368 echo "lxc.init.uid = ${uidgid[0]}" >> "${LXC_CONF_FILE}"
369 # shellcheck disable=SC2039
370 echo "lxc.init.gid = ${uidgid[1]}" >> "${LXC_CONF_FILE}"
371
372 cwd=$(getcwd "${OCI_CONF_FILE}")
373 echo "lxc.init.cwd = ${cwd}" >> "${LXC_CONF_FILE}"
374
375 if [ -n "$LXC_MAPPED_UID" ] && [ "$LXC_MAPPED_UID" != "-1" ]; then
376 chown "$LXC_MAPPED_UID" "$LXC_PATH/config" "$LXC_PATH/fstab" > /dev/null 2>&1 || true
377 fi
378 if [ -n "$LXC_MAPPED_GID" ] && [ "$LXC_MAPPED_GID" != "-1" ]; then
379 chgrp "$LXC_MAPPED_GID" "$LXC_PATH/config" "$LXC_PATH/fstab" > /dev/null 2>&1 || true
380 fi
381
382 exit 0