forked from bitsandsalsa/lxd_gui_container
-
Notifications
You must be signed in to change notification settings - Fork 0
/
attach_app.sh
executable file
·99 lines (79 loc) · 2.53 KB
/
attach_app.sh
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
#!/bin/bash
#
# Wrapper to attach to running GUI app. Run on host.
# directory on host where bind mounts are created
readonly CONTAINER_MOUNTS_DIR=${HOME}/container_mounts
# number of times to connect to xpra server
declare -ri NUM_ATTEMPTS=10
readonly JQ_CMD="jq -rM"
function usage() {
echo "$(basename $0) container-name app-cmdline [xpra-options...]"
echo
}
function print_status() {
echo "[+] $*"
}
function print_err() {
echo "[!] $*"
}
function cleanup() {
xpra stop ssh://ubuntu@"${container_ip}"/${display_num}
lxc exec "${CONTAINER_NAME}" -- sudo -u ubuntu -i xauth remove ":${display_num}"
}
if [ $# -lt 2 ]; then
usage
exit
fi
readonly CONTAINER_NAME=$1
shift
readonly APP_CMDLINE=$1
shift
# Check for running container #
container_info="$(lxc query \
--wait "/1.0/containers/${CONTAINER_NAME}/state" 2>/dev/null)"
if [[ -n "${container_info}" ]]; then
if [[ $(echo "${container_info}" | ${JQ_CMD} .status) != "Running" ]]; then
print_status "Container not in \"Running\" state. Starting it."
lxc start "${CONTAINER_NAME}" || exit 1
lxc exec "${CONTAINER_NAME}" -- cloud-init status --wait || exit 1
container_info="$(lxc query \
--wait "/1.0/containers/${CONTAINER_NAME}/state" 2>/dev/null)"
fi
else
print_err "Container \"${CONTAINER_NAME}\" does not exist."
exit 1
fi
# Start an xpra server in container for target app #
readonly container_ip="$(echo "${container_info}" \
| ${JQ_CMD} '.network.eth0.addresses[] | select(.family == "inet").address')"
if [[ -z "${container_ip}" ]]; then
print_err "Failed to determine container IP address."
exit 1
fi
declare -ri display_num=${RANDOM}
# note that we add group permissions so that ACL mask is set
xpra start ssh://ubuntu@"${container_ip}"/${display_num} \
--socket-permissions=660 \
--socket-dir=~/.xpra \
--start-child="${APP_CMDLINE}" \
--exit-with-children \
--start-via-proxy=no \
--attach=no \
--mdns=no \
--html=off || exit 1
trap cleanup EXIT
readonly XPRA_SOCK="${CONTAINER_MOUNTS_DIR}/${CONTAINER_NAME}/xpra/${CONTAINER_NAME}-${display_num}"
# Try to connect to xpra server #
declare -i try_count=0
while [ $((try_count++)) -lt ${NUM_ATTEMPTS} ]; do
print_status "Attempt ${try_count}/${NUM_ATTEMPTS}: Connecting to xpra server."
sleep 1
if xpra version socket:"${XPRA_SOCK}"; then
break
fi
done
if [[ ${try_count} -ge ${NUM_ATTEMPTS} ]]; then
print_err "Failed to connect to xpra server."
exit 1
fi
exec xpra attach socket:"${XPRA_SOCK}" "$@" || exit 1