forked from sophware/esxidown
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathesxidown.sh
102 lines (83 loc) · 2.66 KB
/
esxidown.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
100
101
102
#!/bin/sh
# ESXi host automated shutdown script (https://github.com/ThisIsTenou/esxidown)
##################################
## !!! DO NOT EDIT THIS FILE!!! ##
##################################
# Get variables from arguments
LOGFILE="$1/esxidown.log"
TEST=$2
WAITTRYS=$3
WAITTIME=$4
exec 2>>"$LOGFILE"
message () {
echo "$(date '+%F %H:%M:%S') [esxidown] $1">>"$LOGFILE"
}
message "esxidown started"
message "Testing enabled (0=No, 1=Yes): $TEST"
# Gather all VM-IDs on the host
SERVERIDS=$(vim-cmd vmsvc/getallvms | sed -e '1d' -e 's/ \[.*$//' | awk '$1 ~ /^[0-9]+$/ {print $1}')
validate_shutdown()
{
vim-cmd vmsvc/power.getstate $SRVID | grep -i "off" > /dev/null 2<&1
STATUS=$?
if [ $STATUS -ne 0 ]; then
if [ $TRY -lt $WAITTRYS ]; then
# if the vm is not off, wait for it to shut down
TRY=$((TRY + 1))
message "Waiting for guest VM ID $SRVID to shutdown (attempt #$TRY)..."
sleep $WAITTIME
validate_shutdown
else
# force power off and wait a little (you could use vmsvc/power.suspend here instead)
message "Unable to gracefully shutdown guest VM ID $SRVID, forcing power off"
if [ $TEST -eq 0 ]; then
vim-cmd vmsvc/power.off $SRVID
fi
sleep $WAITTIME
fi
fi
}
# enter maintenance mode immediately
message "Entering maintenance mode"
if [ $TEST -eq 0 ]; then
esxcli system maintenanceMode set -e true -t 0 &
fi
#send all shutdown messages
for SRVID in $SERVERIDS
do
vim-cmd vmsvc/power.getstate $SRVID | grep -i "off\|Suspended" > /dev/null 2<&1
STATUS=$?
if [ $STATUS -ne 0 ]; then
if [ $TEST -eq 0 ]; then
vim-cmd vmsvc/power.shutdown $SRVID
fi
fi
done
for SRVID in $SERVERIDS
do
TRY=0
vim-cmd vmsvc/power.getstate $SRVID | grep -i "off\|Suspended" > /dev/null 2<&1
STATUS=$?
if [ $STATUS -ne 0 ]; then
message "Checking shutdown of guest VM ID $SRVID..."
validate_shutdown
else
message "Guest VM ID $SRVID is off"
fi
done
# guest vm shutdown complete
message "Guest VM shutdown complete"
# shutdown the ESXi host
message "Shutting down ESXi host after 15 seconds"
if [ $TEST -eq 0 ]; then
esxcli system shutdown poweroff -d 10 -r "Automated ESXi host shutdown // esxidown.sh"
fi
# exit maintenance mode immediately before server has a chance to shutdown/power off
# NOTE: it is possible for this to fail, leaving the server in maintenance mode on reboot!
message "Exiting maintenance mode"
if [ $TEST -eq 0 ]; then
esxcli system maintenanceMode set -e false -t 0
fi
message "Script finished"
# exit the session
exit