-
Notifications
You must be signed in to change notification settings - Fork 27
/
lxc-halt-container
executable file
·75 lines (59 loc) · 1.74 KB
/
lxc-halt-container
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
#!/bin/bash
#
# Halts a running container
#
# Triggers a 'halt' in the machine, then waits for the init process to be the
# only one left, then runs lxc-stop. There is a configurable timeout length for
# if containers are taking too long to shutdown.
#
# Copyright (c) 2010 Nigel McNie
#
# Default command for halting the container
SHUTDOWN_CMD="lxc-shutdown -n [container]"
# Default timeout for container shutdown
TIMEOUT=20
# No user configuration beyond this point
[ -f /etc/default/lxc ] && . /etc/default/lxc
if [ "$(id -u)" != "0" ]; then
echo "This script should be run as 'root'"
exit 1
fi
while getopts "n:c:t:" flag
do
case $flag in
n) CONTAINER="$OPTARG" ;;
c) SHUTDOWN_CMD="$OPTARG" ;;
t) TIMEOUT="$OPTARG" ;;
*) echo "Unknown flag: $flag"; exit 1; ;;
esac
done
if [ -z "$CONTAINER" ]; then
echo "lxc-halt-container: missing container name, use -n option"
exit 1
fi
if [ ! -d /var/lib/lxc/$CONTAINER ]; then
echo "lxc-halt-container: container $CONTAINER does not exist"
exit 1
fi
if [[ `lxc-info -n $CONTAINER | grep RUNNING` ]]; then
cmd="${SHUTDOWN_CMD//\[container\]/$CONTAINER}"
( $cmd )
starttime=$(date "+%s")
while true
do
count=$(lxc-ps --lxc -n $CONTAINER ax | grep "^$CONTAINER " | wc -l)
if [ $count -le 1 ]; then
lxc-stop -n $CONTAINER
exit 0
fi
sleep .25
curtime=$(date "+%s")
if [ $(( $curtime - $starttime )) -gt $TIMEOUT ]; then
echo "Container $CONTAINER has been stopping for longer than $TIMEOUT seconds, forcing shutdown" >&2
lxc-stop -n $CONTAINER
exit 0
fi
done
else
echo "Container $CONTAINER is already stopped" >&2
fi