-
Notifications
You must be signed in to change notification settings - Fork 15
/
toolbox
executable file
·513 lines (464 loc) · 17.8 KB
/
toolbox
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
#!/bin/bash
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# script based on https://github.com/coreos/toolbox/
set -eo pipefail
# Defaults
REGISTRY=registry.opensuse.org
IMAGE=opensuse/toolbox
TOOLBOX_NAME=toolbox-"${USER}"
TOOLBOXRC="${HOME}"/.toolboxrc
TOOLBOX_SHELL="/bin/bash"
SUDO=
if command -v podman &> /dev/null ; then
CLI=podman
elif command -v docker &> /dev/null ; then
CLI=docker
else
echo "$0: ERROR: neither 'podman' nor 'docker' are available. Exiting!"
fi
test -f /usr/share/toolbox/toolboxrc && . /usr/share/toolbox/toolboxrc
test -f /etc/toolboxrc && . /etc/toolboxrc
MODE="system"
setup() {
# Allow user overrides
if [ -f "${TOOLBOXRC}" ]; then
echo ".toolboxrc file detected, overriding defaults..."
source "${TOOLBOXRC}"
fi
TOOLBOX_IMAGE="${REGISTRY}"/"${IMAGE}"
}
create() {
local msg="created"
if ! container_exists; then
if ! image_exists || [ -z "$NO_PULL" ]; then
image_pull
fi
local runlabel
runlabel=$(image_runlabel) ||:
echo "Spawning a container '$TOOLBOX_NAME' with image '$TOOLBOX_IMAGE'"
if [[ -z "$runlabel" ]]; then
container_create
else
echo "Detected RUN label in the container image. Using that as the default..."
container_runlabel
return
fi
# We want to do the user setup only when the container is created for the first time
[[ -n "${CREATE_AS_USER}" ]] && SETUP_USER=true
else
echo "Container '$TOOLBOX_NAME' already exists. Trying to start..."
echo "(To remove the container and start with a fresh toolbox, run: $CLI rm '$TOOLBOX_NAME')"
msg="started"
fi
local state
state=$(container_state)
if [[ "$state" == configured ]] || [[ "$state" == exited ]] || [[ "$state" == stopped ]] || [[ "$state" == created ]]; then
container_start
elif [[ "$state" != running ]]; then
echo "Container '$TOOLBOX_NAME' in unknown state: '$state'"
return 1
fi
if [[ "${SETUP_USER}" = "true" ]]; then
echo "Setting up user '${USER_NAME}' (with 'sudo' access) inside the container..."
echo "(NOTE that, if 'sudo' and related packages are not present in the image already,"
echo "this may take some time. But this will only happen now that the toolbox is being created)"
local tmp_user_setup
tmp_user_setup=$(mktemp "${HOME}/.${TOOLBOX_NAME}-user-setup-XXXXXX.sh")
tmp_user_setup_log="/dev/null"
# DEBUG: uncomment the following line to see logs of the script in /tmp
#tmp_user_setup_log="/tmp/$(basename -- ${tmp_user_setup}).log"
cat <<EOF > "${tmp_user_setup}"
#!/bin/bash
groupadd -g ${USER_GID} ${USER_GNAME}
useradd -M -N -g ${USER_GNAME} -u ${USER_ID} ${USER_NAME}
if ! command -v sudo &> /dev/null ; then
if command -v zypper &> /dev/null ; then
zypper install -y --no-recommends sudo
elif command -v apt &> /dev/null ; then
apt update && apt -y install sudo
elif command -v dnf ; then
dnf install -y sudo
fi
fi
mkdir -p /etc/sudoers.d/ && echo "${USER_NAME} ALL = (root) NOPASSWD:ALL" > /etc/sudoers.d/${USER_NAME}
# Avoid issues when updating some packages
if [ -d "/usr/lib/rpm/macros.d/" ]; then
# Problematic packages are (on openSUSE):
# - filesystem: touches /dev
# - netcfg: touches /etc/hosts
echo "%_netsharedpath /dev/:/etc/hosts" > /usr/lib/rpm/macros.d/macros.microos-toolbox
fi
EOF
${SUDO} $CLI exec --user root "${TOOLBOX_NAME}" bash "${tmp_user_setup}" &> "${tmp_user_setup_log}"
${SUDO} $CLI exec --user root "${TOOLBOX_NAME}" rm "${tmp_user_setup}"
fi
echo "Container ${msg}."
}
run() {
create
echo "Entering container. To exit, type 'exit'."
container_exec "$@"
}
cleanup() {
active="$(container_active)"
if [ $active != "" ] && [ $active -eq 0 ] && [ -z "$NO_STOP" ]; then
${SUDO} $CLI stop "$TOOLBOX_NAME" &>/dev/null
fi
}
container_exists() {
${SUDO} $CLI inspect "$TOOLBOX_NAME" &>/dev/null
}
container_state() {
${SUDO} $CLI inspect "$TOOLBOX_NAME" --format '{{.State.Status}}' 2> /dev/null
}
container_active() {
${SUDO} $CLI inspect "$TOOLBOX_NAME" --format '{{len .ExecIDs}}' 2> /dev/null
}
image_exists() {
${SUDO} $CLI inspect "$TOOLBOX_IMAGE" &>/dev/null
}
image_runlabel() {
${SUDO} $CLI container runlabel --display RUN "$TOOLBOX_IMAGE" 2> /dev/null
}
image_pull() {
if [ -z ${SUDO} ] && [ $(id -u) -ne 0 ]; then
if [ ! `grep $USER /etc/subuid` ] || [ ! `grep $USER /etc/subgid` ]; then
echo "$0: ERROR: rootless mode wanted but no subuid and/or subgid for user '$USER'"
echo " Toolbox will only work for this user if rootless $CLI is configured properly."
echo " consider doing something like this:"
echo " sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 $USER"
echo " and then restart."
echo " Or use '-r', for using a rootfull container."
exit 1
fi
fi
${SUDO} $CLI pull "$TOOLBOX_IMAGE"
}
list() {
${SUDO} $CLI ps --all
exit $?
}
stop() {
# We can't stop non-existing and non-running toolboxes
if ! container_exists ; then
echo "$0: ERROR: Cannot stop non-existing container '$TOOLBOX_NAME'"
exit 2
fi
if [[ "$(container_state)" != "running" ]]; then
echo "$0: ERROR: Cannot stop non-running container '$TOOLBOX_NAME'"
exit 2
fi
# We don't stop toolboxes with active sessions
if [ $(container_active) -ne 0 ]; then
echo "$0: ERROR: The toolbox '$TOOLBOX_NAME' has active sessions. Not stopping"
exit 1
fi
${SUDO} $CLI stop "$TOOLBOX_NAME" &> /dev/null
}
container_create() {
if [ -z "$SANDBOX" ]; then
# this is the default behavior, unless --sandbox is specified
CREATE_NO_SANDBOX="--mount type=devpts,destination=/dev/pts,uid=$(id -u) --volume /sys:/sys:rslave --volume /:/media/root:rslave"
CREATE_NO_SANDBOX="$CREATE_NO_SANDBOX --privileged --security-opt label=disable --pid host --ipc host"
fi
if ! ${SUDO} $CLI create \
$RUNTIME \
--hostname "$TOOLBOX_NAME" \
--name "$TOOLBOX_NAME" \
--network host \
${CREATE_NO_SANDBOX} \
${CREATE_AS_USER} \
--volume /etc/machine-id:/etc/machine-id:ro \
--volume /etc/localtime:/etc/localtime:ro \
"$TOOLBOX_IMAGE" sleep +Inf > /dev/null; then
echo "$0: failed to create container '$TOOLBOX_NAME'"
exit 1
fi
}
container_start() {
if ! ${SUDO} $CLI start "$TOOLBOX_NAME" > /dev/null ; then
echo "$0: failed to start container '$TOOLBOX_NAME'"
exit 1
fi
}
container_runlabel() {
if ! ${SUDO} $CLI container runlabel --name "$TOOLBOX_NAME" RUN "$TOOLBOX_IMAGE" > /dev/null ; then
echo "$0: failed to runlabel on image '$TOOLBOX_IMAGE'"
exit 1
fi
}
container_exec() {
${SUDO} $CLI exec \
--env LANG="$LANG" \
--env TERM="$TERM" \
--interactive \
--tty "${EXEC_AS_USER[@]}" \
"$TOOLBOX_NAME" \
"$@"
}
show_help() {
echo "USAGE: toolbox [[-h/--help] | [list|create [<name>]|enter [<name>]|run|stop [<name>]] [-r/--root] [-u/--user]
[-n/--nostop] [-S/--sandbox] [-P/--no-pull] [[-R/--reg <registry>] [-I/--img <image>]|[-i/--image <image_URI>]]
[-X/--runtime <runtime_bin>] [[-t/--tag <tag>]|[-c/--container <name>]] [command_to_run]]
toolbox is a small script that launches a container to let you bring in your favorite debugging or admin tools.
The toolbox container is a pet container and will be restarted on following runs.
To remove the container and start fresh, do $CLI rm ${TOOLBOX_NAME}.
Commands are optional and imply user mode (-u):
list: List existing toolboxes
create: Just create the toolbox
enter: Enter inside a toolbox (if it does not exist, it is created)
run: Run command_to_run inside a toolbox (if it does not exist, it is created)
stop: Stop a running toolbox (_only_ if no active sessions exists for it)
For the create, enter and stop commands, the toolbox name can be specified either:
- with -t/--tag, e.g.: 'toolbox enter -t dev'. For user foo, will enter 'toolbox-foo-user-dev'. Or,
- with -c/--container, e.g.: 'toolbox create -c work'. Will create 'work'. Or
- with just the name of the container, e.g.: 'toolbox enter test'. Will enter 'test'.
Options:
-h/--help: Shows this help message
-u/--user: Run as the current user inside the container
-r/--root: Runs $CLI via sudo as root
-X/--runtime <runtime_bin>: Use the specified runtime (e.g., /usr/bin/crun)
-n/--nostop: Does not stop the container on exit, allowing multiple
sessions to use the same toolbox at once
-S/--sandbox: Start a \"less privileged than usual\" toolbox. It remains
true, though, that toolbox is *NOT* meant to be used for when
security and strong isolation are important. Always bear this
in mind, even when using this option.
-P/--no-pull: Skip trying to update the image, if it already exists. This
may speedup toolbox creation, but at the risk of creating the
toolbox out of a potentially (very?) old image.
-t/--tag <tag>: Add <tag> to the toolbox name
-c/--container <name>: Set the name of the toolbox to be equal to <name>
(use this alternatively to -t)
-R/--reg <registry>: Pulls the container image from <registry>
-I/--img <image>: Pulls the image called <image>
-i/--image <image_URI>: Pulls <image_URI> as a container image (use this
alternatively to -R and -I)
You may override the following variables by setting them in ${TOOLBOXRC}:
- REGISTRY: The registry to pull from. Default: $REGISTRY
- IMAGE: The image and tag from the registry to pull. Default: $IMAGE
- TOOLBOX_NAME: The name to use for the local container. Default: $TOOLBOX_NAME
- TOOLBOX_SHELL: Standard shell if no other commands are given. Default: $TOOLBOX_SHELL
Example toolboxrc:
REGISTRY=my.special.registry.example.com
IMAGE=debug:latest
TOOLBOX_NAME=special-debug-container
TOOLBOX_SHELL=/bin/bash"
}
is_option() {
if [ "${1:0:1}" = "-" ]; then
return 1
fi
return 0
}
main() {
# Execute setup first so we get proper variables
setup
# Deal with commands first. We want to support both "command mode"
# (compatible with Silverblue's toolbox) and the current "command-less"
# mode of operation. If wanting to use a command, that has to be the
# first argument. If no command is provided, we basically default to
# 'run', which is 'create, start and fire a shell inside the toolbox'.
#
# Note that, if a command is used, we set "user" mode by default (i.e.,
# even if `-u` is not specified later). This is again for compatibility
# with https://github.com/containers/toolbox).
COMMAND=run
if [ -n "$1" ] && is_option $1 ; then
case $1 in
create | list | enter | run | stop)
MODE="user"
COMMAND=$1
shift
;;
esac
fi
ARGS=$(getopt -o hrunSPt:R:I:c:i:X: --long help,root,user,nostop,sandbox,no-pull,tag:,reg:,img:,container:,image:,runtime: -n toolbox -- "$@")
eval set -- "$ARGS"
while true; do
case "$1" in
-h|--help)
# If we are passed a help switch, show help and exit
show_help
exit 0
;;
-r|--root)
shift
SUDO=sudo
;;
-X|--runtime)
RUNTIME="--runtime $2"
if ! command -v $2 &> /dev/null ; then
echo "ERROR: $2 not available as runtime!"
show_help
exit 1
fi
shift 2
;;
-u|--user)
shift
MODE="user"
;;
-n|--nostop)
NO_STOP="true"
shift
;;
-S|--sandbox)
echo "WARNING: toolbox is not for sandboxing. Using -S removes some privileges, but don't feel too safe!!!"
SANDBOX="true"
shift
;;
-P|--no-pull)
NO_PULL="true"
shift
;;
-c|--container)
if [ -n "$TAG" ]; then
echo "ERROR: Don't use both -c and -t!"
show_help
exit 1
fi
CHANGE_NAME="true"
TOOLBOX_NAME="$2"
shift 2
;;
-t|--tag)
if [ -n "$CHANGE_NAME" ]; then
echo "ERROR: Don't use both -c and -t!"
show_help
exit 1
fi
TAG="$2"
shift 2
;;
-R|--reg)
REGISTRY=$2
shift 2
;;
-I|--img)
IMAGE=$2
shift 2
;;
-i|--image)
REGISTRY=""
IMAGE=$2
shift 2
;;
--)
shift
break
;;
*)
echo "unknown parameter: '$1'"
show_help
exit 1
;;
esac
done
${SUDO} ${CLI} ps &> /dev/null
if [ $? -ne 0 ]; then
echo "$0: ERROR: '${CLI}' is available but does not seem to be usable. Exiting!"
fi
# Let's rebuild the image URI (this means that command
# line, if present, overrides config file)
TOOLBOX_IMAGE=$(echo "${REGISTRY}"/"${IMAGE}" | sed 's/^\///g')
if [ "$MODE" = "user" ]; then
local USER_ENV="DBUS_SESSION_BUS_ADDRESS \
DBUS_SYSTEM_BUS_ADDRESS \
DESKTOP_SESSION \
SESSION_MANAGER \
DISPLAY \
LANG \
SSH_AUTH_SOCK \
USER \
USERNAME \
WAYLAND_DISPLAY \
XAUTHORITY \
XAUTHLOCALHOSTNAME \
XDG_CURRENT_DESKTOP \
XDG_DATA_DIRS \
XDG_MENU_PREFIX \
XDG_RUNTIME_DIR \
XDG_SESSION_CLASS \
XDG_SESSION_DESKTOP \
XDG_SESSION_TYPE"
USER_ID=$(id -u); USER_GID=$(id -g)
USER_NAME=$(id -un) ; USER_GNAME=$(id -gn)
if [ -z "$CHANGE_NAME" ]; then
TOOLBOX_NAME="${TOOLBOX_NAME}-user"
fi
# We want to keep the pid namespace of the running user.
# We, however, use root:root while creating, so that later we
# can modify the user's name, groups, etc, within the container.
VOLUMES="--volume /tmp:/tmp:rslave"
test -d "${HOME}" && VOLUMES="$VOLUMES --volume ${HOME}:${HOME}"
test -d "/run/user/${USER_ID}" && VOLUMES="$VOLUMES --volume /run/user/${USER_ID}:/run/user/${USER_ID}:rslave"
test -d /run/media && VOLUMES="$VOLUMES --volume /run/media/:/run/media/:rslave"
CREATE_AS_USER="--user root:root $VOLUMES"
if [[ "$CLI" == "podman" ]]; then
# Let's retain the user's groupd. This will (probably) only work
# with some runtime, but it's harmless for other, so worth a try.
CREATE_AS_USER="$CREATE_AS_USER --annotation run.oci.keep_original_groups=1"
# userns=keep-id only works if being used rootless
if [[ -z $SUDO ]]; then
CREATE_AS_USER="$CREATE_AS_USER --userns=keep-id"
fi
fi
for ENV in $USER_ENV ; do
eval VAL="$""$ENV"
[[ -n "$VAL" ]] && USER_ENV_ARR+=(--env "$ENV=$VAL")
done
EXEC_AS_USER=(--user "${USER_ID}:${USER_GID}" -w "$(pwd)" "${USER_ENV_ARR[@]}")
fi
if [ -n "$TAG" ]; then
TOOLBOX_NAME="${TOOLBOX_NAME}-$TAG"
fi
# enter, create and stop supports the name of the container being as an
# argument, so use if it's there. But there must be no conflict between
# that and the -c and -t options.
if [ "$COMMAND" = "enter" ] || [ "$COMMAND" = "create" ] || [ "$COMMAND" = "stop" ]; then
if [ $# -ge 1 ]; then
if [ -n "$CHANGE_NAME" ] || [ -n "$TAG" ]; then
echo "ERROR: Cannot determine which container to use between $TOOLBOX_NAME and $1"
show_help
exit 1
fi
TOOLBOX_NAME=$1
shift
fi
fi
case $COMMAND in
create|enter|run)
# Cleanup is only needed if we're really starting the container
trap cleanup EXIT
if [ "$COMMAND" = "create" ]; then
[ $# -gt 0 ] && echo "WARNING: ignoring the following arguments: $@"
create
elif [ "$COMMAND" = "enter" ] || [ $# -eq 0 ]; then
[ "$COMMAND" = "enter" ] && [ $# -gt 0 ] && echo "WARNING: ignoring the following arguments: $@"
run ${TOOLBOX_SHELL}
else
run "$@"
fi
;;
list|stop)
$COMMAND
;;
*)
echo "unknown command: '$COMMAND'"
exit 1
;;
esac
}
main "$@"