forked from 89luca89/distrobox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistrobox-enter
executable file
·457 lines (415 loc) · 14.6 KB
/
distrobox-enter
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
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-only
#
# This file is part of the distrobox project:
# https://github.com/89luca89/distrobox
#
# Copyright (C) 2021 distrobox contributors
#
# distrobox is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# distrobox is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with distrobox; if not, see <http://www.gnu.org/licenses/>.
# POSIX
# Expected env variables:
# HOME
# USER
# SHELL
# Optional env variables:
# DBX_CONTAINER_NAME
# DBX_CONTAINER_MANAGER
trap '[ "$?" -ne 0 ] && printf "\nAn error occurred\n" && rm -f "/tmp/.*.fifo"' EXIT
# Dont' run this command as sudo.
if [ "$(id -u)" -eq 0 ]; then
printf >&2 "Running %s as sudo is not supported.\n" "$(basename "${0}")"
printf >&2 " try instead running:\n"
printf >&2 " %s --root %s\n" "$(basename "${0}")" "$*"
exit 1
fi
# Defaults
container_command=""
container_shell="${SHELL:-"bash"}"
# Work around for shells that are not in the container's file system, nor PATH.
# For example in hosts that do not follow FHS, like NixOS or for shells in custom
# exotic paths.
container_shell="$(basename "${container_shell}") -l"
container_manager="autodetect"
container_name="fedora-toolbox-35"
container_manager_additional_flags=""
# Use cd + dirname + pwd so that we do not have relative paths in mount points
# We're not using "realpath" here so that symlinks are not resolved this way
# "realpath" would break situations like Nix or similar symlink based package
# management.
distrobox_enter_path="$(cd "$(dirname "$0")" && pwd)/distrobox-enter"
dryrun=0
headless=0
rootful=0
verbose=0
version="1.2.16"
# Source configuration files, this is done in an hierarchy so local files have
# priority over system defaults
# leave priority to environment variables.
config_files="
/usr/share/distrobox/distrobox.conf
/etc/distrobox/distrobox.conf
${HOME}/.config/distrobox/distrobox.conf
${HOME}/.distroboxrc
"
for config_file in ${config_files}; do
# shellcheck disable=SC1090
[ -e "${config_file}" ] && . "${config_file}"
done
[ -n "${DBX_CONTAINER_MANAGER}" ] && container_manager="${DBX_CONTAINER_MANAGER}"
[ -n "${DBX_CONTAINER_NAME}" ] && container_name="${DBX_CONTAINER_NAME}"
# Print usage to stdout.
# Arguments:
# None
# Outputs:
# print usage with examples.
show_help() {
cat << EOF
distrobox version: ${version}
Usage:
distrobox-enter --name fedora-toolbox-35 -- bash -l
distrobox-enter my-alpine-container -- sh -l
distrobox-enter --additional-flags "--preserve-fds" --name test -- bash -l
distrobox-enter --additional-flags "--env MY_VAR=value" --name test -- bash -l
MY_VAR=value distrobox-enter --additional-flags "--preserve-fds" --name test -- bash -l
Options:
--name/-n: name for the distrobox default: fedora-toolbox-35
--/-e: end arguments execute the rest as command to execute at login default: bash -l
--no-tty/-T: do not instantiate a tty
--additional-flags/-a: additional flags to pass to the container manager command
--help/-h: show this message
--root/-r: launch podman/docker with root privileges. Note that if you need root this is the preferred
way over "sudo distrobox"
--dry-run/-d: only print the container manager command generated
--verbose/-v: show more verbosity
--version/-V: show version
EOF
}
# Parse arguments
while :; do
case $1 in
-h | --help)
# Call a "show_help" function to display a synopsis, then exit.
show_help
exit 0
;;
-v | --verbose)
shift
verbose=1
;;
-T | -H | --no-tty)
shift
headless=1
;;
-r | --root)
shift
rootful=1
;;
-V | --version)
printf "distrobox: %s\n" "${version}"
exit 0
;;
-d | --dry-run)
shift
dryrun=1
;;
-n | --name)
if [ -n "$2" ]; then
container_name="$2"
shift
shift
fi
;;
-a | --additional-flags)
if [ -n "$2" ]; then
container_manager_additional_flags="${container_manager_additional_flags} ${2}"
shift
shift
fi
;;
-e | --exec | --)
shift
container_command=$*
break
;;
-*) # Invalid options.
printf >&2 "ERROR: Invalid flag '%s'\n\n" "$1"
show_help
exit 1
;;
*) # Default case: If no more options then break out of the loop.
# If we have a flagless option and container_name is not specified
# then let's accept argument as container_name
if [ -n "$1" ]; then
container_name="$1"
shift
else
break
fi
;;
esac
done
set -o errexit
set -o nounset
# set verbosity
if [ "${verbose}" -ne 0 ]; then
set -o xtrace
fi
# We depend on a container manager let's be sure we have it
# First we use podman, else docker
case "${container_manager}" in
autodetect)
if command -v podman > /dev/null; then
container_manager="podman"
elif command -v docker > /dev/null; then
container_manager="docker"
else
container_manager="not_found"
fi
;;
podman)
container_manager="podman"
;;
docker)
container_manager="docker"
;;
*)
printf >&2 "Invalid input %s.\n" "${container_manager}"
printf >&2 "The available choices are: 'autodetect', 'podman', 'docker'\n"
container_manager="not_found"
;;
esac
# Be sure we have a container manager to work with.
if ! command -v "${container_manager}" > /dev/null; then
# Error: we need at least one between docker or podman.
if [ "${dryrun}" -eq 0 ]; then
printf >&2 "Missing dependency: we need a container manager.\n"
printf >&2 "Please install one of podman or docker.\n"
printf >&2 "You can follow the documentation on:\n"
printf >&2 "\tman distrobox-compatibility\n"
printf >&2 "or:\n"
printf >&2 "\thttps://github.com/89luca89/distrobox/blob/main/docs/compatibility.md\n"
exit 127
fi
fi
# Small performance optimization, using podman socket shaves
# about half the time to access informations.
#
# Accessed file is /run/user/USER_ID/podman/podman.sock
#
# This is not necessary on docker as it is already handled
# in this way.
if [ -z "${container_manager#*podman*}" ] &&
[ "${rootful}" -eq 0 ] &&
[ -S "/run/user/$(id -ru)/podman/podman.sock" ] &&
systemctl --user status podman.socket > /dev/null; then
container_manager="${container_manager} --remote"
fi
# add verbose if -v is specified
if [ "${verbose}" -ne 0 ]; then
container_manager="${container_manager} --log-level debug"
fi
# prepend sudo if we want podman or docker to be rootful
if [ "${rootful}" -ne 0 ]; then
container_manager="sudo ${container_manager}"
fi
# Generate Podman or Docker command to execute.
# Arguments:
# None
# Outputs:
# prints the podman or docker command to enter the distrobox container
generate_command() {
result_command="${container_manager} exec"
result_command="${result_command}
--interactive
--user=\"${USER}\""
# For some usage, like use in service, or launched by non-terminal
# eg. from desktop files, TTY can fail to instantiate, and fail to enter
# the container.
# To work around this, --headless let's you skip the --tty flag and make it
# work in tty-less situations.
# Disable tty also if we're NOT in a tty (test -t 0).
if [ "${headless}" -eq 0 ] && [ -t 0 ]; then
result_command="${result_command}
--tty"
fi
# Entering container using our user and workdir.
# Start container from working directory. Else default to home. Else do /.
# Since we are entering from host, drop at workdir through '/run/host'
# which represents host's root inside container. Any directory on host
# even if not explicitly mounted is bound to exist under /run/host.
# $HOME variable is very likely present in container. It is either equal
# to the user's normal $HOME on host, or a custom dir specified when the
# container was created.
# pass distrobox-enter path, it will be used in the distrobox-export tool.
# Find $HOME as it is defined in the container (could be a custom home)
home="$(${container_manager} inspect --type container --format='{{.Config.Env}}' "${container_name}" |
sed 's/ /\n/g' | awk '/^HOME=/' | cut -d= -f 2)"
# Custom home specified? Let's then start there.
if [ "${home}" != "${HOME}" ]; then
workdir="$(echo "${home}" | sed -e 's/"/\\\"/g')"
else
workdir="$(echo "${PWD:-${home:-"/"}}" | sed -e 's/"/\\\"/g')"
fi
if [ -n "${workdir##*"${home}"*}" ]; then
workdir="/run/host/${workdir}"
fi
result_command="${result_command}
--workdir=\"${workdir}\"
--env=\"DISTROBOX_ENTER_PATH=${distrobox_enter_path}\""
# Loop through all the environment vars
# and export them to the container.
set +o xtrace
# disable logging fot this snippet, or it will be too talkative.
for i in $(printenv | grep '=' | grep -Ev ' |"' |
grep -Ev '^(HOST|HOSTNAME|HOME|PATH|SHELL|USER|XDG_.*_DIRS|_)'); do
# We filter the environment so that we do not have strange variables,
# multiline or containing spaces.
# We also NEED to ignore the HOME variable, as this is set at create time
# and needs to stay that way to use custom home dirs.
result_command="${result_command} --env=\"${i}\""
done
# Start with the $PATH set in the container's config
container_paths="${container_path:-""}"
# Ensure the standard FHS program paths are in PATH environment
standard_paths="/usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin"
# add to the PATH after the existing paths, and only if not already present
for standard_path in ${standard_paths}; do
if [ -n "${container_paths##*:"${standard_path}"*}" ]; then
container_paths="${container_paths}:${standard_path}"
fi
done
# Ensure the $PATH entries from the host are appended as well
for standard_path in $(
IFS=:
for p in ${PATH}; do echo "${p}"; done
); do
if [ -n "${container_paths##*:"${standard_path}"*}" ]; then
container_paths="${container_paths}:${standard_path}"
fi
done
result_command="${result_command} --env=\"PATH=${container_paths}\""
# Ensure the standard FHS program paths are in XDG_DATA_DIRS environment
standard_paths="/usr/local/share /usr/share"
container_paths="${XDG_DATA_DIRS:=}"
# add to the XDG_DATA_DIRS only after the host's paths, and only if not already present.
for standard_path in ${standard_paths}; do
if [ -n "${container_paths##*:"${standard_path}"*}" ]; then
container_paths="${container_paths}:${standard_path}"
fi
done
result_command="${result_command} --env=\"XDG_DATA_DIRS=${container_paths}\""
# Ensure the standard FHS program paths are in XDG_CONFIG_DIRS environment
standard_paths="/etc/xdg"
container_paths="${XDG_CONFIG_DIRS:=}"
# add to the XDG_CONFIG_DIRS only after the host's paths, and only if not already present.
for standard_path in ${standard_paths}; do
if [ -n "${container_paths##*:"${standard_path}"*}" ]; then
container_paths="${container_paths}:${standard_path}"
fi
done
result_command="${result_command} --env=\"XDG_CONFIG_DIRS=${container_paths}\""
# re-enable logging if it was enabled previously.
if [ "${verbose}" -ne 0 ]; then
set -o xtrace
fi
# Add additional flags
result_command="${result_command} ${container_manager_additional_flags}"
# Run selected container with specified command.
result_command="${result_command} ${container_name} ${container_command:-${container_shell}}"
# Return generated command.
printf "%s" "${result_command}"
}
container_path="${PATH}"
# dry run mode, just generate the command and print it. No execution.
if [ "${dryrun}" -ne 0 ]; then
cmd="$(generate_command)"
cmd="$(echo "${cmd}" | tr '[:blank:]\n' ' ' | tr -s ' ')"
printf "%s\n" "${cmd}"
exit 0
fi
# Inspect the container we're working with.
container_status="unknown"
eval "$(${container_manager} inspect --type container "${container_name}" --format \
'container_status={{.State.Status}};
{{range .Config.Env}}{{if slice . 0 6 | eq "SHELL="}}container_shell={{slice . 6 | printf "%q"}};{{end}}{{end}}
{{range .Config.Env}}{{if slice . 0 5 | eq "PATH="}}container_path={{slice . 5 | printf "%q"}}{{end}}{{end}}')"
container_exists="$?"
# Set SHELL as a login shell
container_shell="$(basename "${container_shell}") -l"
# Does the container exists? check if inspect reported errors
if [ "${container_exists}" -gt 0 ]; then
# If not, prompt to create it first
printf >&2 "Cannot find container %s, does it exist?\n" "${container_name}"
printf >&2 "\nTry running first:\n"
printf >&2 "\tdistrobox-create <name-of-container> --image <remote>/<docker>:<tag>\n"
exit 1
fi
# If the container is not already running, we need to start if first
if [ "${container_status}" != "running" ]; then
# If container is not running, start it first
# Here, we save the timestamp before launching the start command, so we can
# be sure we're working with this very same session of logs later.
printf >&2 "Container %s is not running.\n" "${container_name}"
printf >&2 "Starting container %s\n" "${container_name}"
printf >&2 "run this command to follow along:\n\n"
printf >&2 " %s logs -f %s\n\n" "${container_manager}" "${container_name}"
log_timestamp="$(date +%FT%T.%N%:z)"
${container_manager} start "${container_name}" > /dev/null
# Check if the container is going in error status earlier than the
# entrypoint
if [ "$(${container_manager} inspect \
--type container "${container_name}" \
--format "{{.State.Status}}")" != "running" ]; then
printf >&2 "\033[31m Error: could not start entrypoint.\n\033[0m"
container_manager_log="$(${container_manager} logs \
--since "${log_timestamp}" "${container_name}")"
printf >&2 "%s\n" "${container_manager_log}"
exit 1
fi
# Wait for container to finish setup successfully.
rm -f "/tmp/.${container_name}.fifo" && mkfifo "/tmp/.${container_name}.fifo"
${container_manager} logs \
--since "${log_timestamp}" \
-f "${container_name}" 2> /dev/null > "/tmp/.${container_name}.fifo" &
container_log_pid="$!"
printf >&2 "%-40s\t" " Starting container..."
while IFS= read -r line; do
# Check if the container is going in error status at any time during the first init
case "${line}" in
*"Error"*)
printf >&2 "\033[31m %s\n\033[0m" "${line}"
exit 1
;;
*"Warning"*)
printf >&2 "\n\033[33m %s\033[0m" "${line}"
;;
*"distrobox:"*)
printf >&2 "\033[32m [ OK ]\n\033[0m%-40s\t" "$(echo "${line}" | cut -d':' -f2-)"
;;
*"container_setup_done"*)
printf >&2 "\033[32m [ OK ]\n\033[0m"
break
;;
*) ;;
esac
done < "/tmp/.${container_name}.fifo"
# Kill log process, cleanup fifo
kill -INT "${container_log_pid}"
rm -f "/tmp/.${container_name}.fifo"
printf >&2 "\nContainer Setup Complete!\n"
fi
# Generate the exec command and run it
cmd="$(generate_command)"
# shellcheck disable=SC2086
eval ${cmd}