-
Notifications
You must be signed in to change notification settings - Fork 7
/
omv-backup-vm
executable file
·284 lines (249 loc) · 6.87 KB
/
omv-backup-vm
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
#!/bin/bash
#
# shellcheck disable=SC2086,SC2181
#
# Copyright (c) 2022-2024 OpenMediaVault Plugin Developers
#
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.
#
# version: 0.3.1
#
if [[ $(id -u) -ne 0 ]]; then
echo "This script must be executed as root or using sudo."
exit 99
fi
export LANG=C.UTF-8
# declare/initialize
declare -i keep=0
declare -i poweroff=0
declare -i poweredoff=0
declare -i samefmt=0
declare -i snap=0
declare -i used=0
declare -i vmId=0
backupDir=""
backupVm=""
backupVmDir=""
compress=""
diskSpecs=""
# logging location
logDir="/var/log/"
logFile="${logDir}/omv-backup-vm.log"
listFile="/etc/omv-backup-vm.list"
_log()
{
msg=${1}
echo "[$(date +'%Y-%m-%d %H:%M:%S%z')] [backup] ${msg}" | tee -a ${logFile} >&2
}
# loop through options
while getopts "cd:hk:psv:" opt; do
case "${opt}" in
c)
compress=" -c -o compression_type=zstd"
_log "compression :: enabled"
;;
d)
backupDir="${OPTARG}"
_log "Backup dir :: ${backupDir}"
;;
h)
echo "Use the following flags:"
echo " -c"
echo " compress backup (slower)"
echo " -d dir"
echo " set backup directory"
echo " -h"
echo " show this help"
echo " -k #"
echo " keep last number of backups"
echo " -p"
echo " power off VM before backup if powered on"
echo " VM will be powered back on if powered off by script"
echo " -s"
echo " use same format as source"
echo " will use cp command"
echo " compression flag will be ignored"
echo " -v vm-name"
echo " VM name to backup"
echo ""
echo "Examples:"
echo " omv-backup-vm -d /srv/backup/ -k 5 -v testvm1"
echo ""
exit 100
;;
k)
keep=${OPTARG}
_log "Keep :: ${keep}"
;;
p)
poweroff=1
_log "poweroff :: ${poweroff}"
;;
s)
samefmt=1
_log "Same format :: ${samefmt}"
;;
v)
backupVm=${OPTARG}
_log "Backup VM :: ${backupVm}"
;;
\?)
echo "Invalid option: -${OPTARG}"
;;
esac
done
if [ ! -f "/usr/bin/virsh" ]; then
_log "virsh command not found!"
exit 2
fi
# check if directory exists
if [ ! -d "${backupDir}" ]; then
_log "Backup directory '${backupDir}' does not exist!"
exit 3
fi
# check if VM name was specified
if [ -z "${backupVm}" ]; then
_log "No VM specified!"
exit 4
fi
# check if VM is defined by libvirt
if ! virsh dominfo ${backupVm} > /dev/null 2>&1; then
_log "VM '${backupVm}' not defined!"
exit 5
fi
# get date
date="$(date +'%Y-%m-%d_%H-%M-%S')"
start=$(date +%s)
_log "Starting backup..."
# get VM power state
powerState="$(virsh dominfo ${backupVm} | awk '$1 == "State:" { print $2 }')"
# get VM ID
if [ "${powerState}" = "running" ]; then
vmId=$(virsh domid ${backupVm})
fi
_log "${backupVm} ID :: ${vmId}"
# create backup directory for VM
backupVmDir="${backupDir}/${backupVm}/${date}"
mkdir -p "${backupVmDir}"
# create backup xml
backupXml="${backupVm}_${date}.xml"
_log "Dump XML for backup :: ${backupXml}"
virsh dumpxml ${backupVm} > "${backupVmDir}/${backupXml}"
grep -i 'loader.*pflash' "${backupVmDir}/${backupXml}"
if [ $? -eq 0 ]; then
_log "VM is using pflash"
fi
# get list of disks for VM
disks=$(virsh domblklist ${backupVm} --details | sed 1,2d | awk NF | awk '$2 == "disk" { print $3","$4 }')
# power off VM if poweroff flag passed
if [ ${poweroff} -eq 1 ] && [ ${vmId} -gt 0 ]; then
_log "Shutting down ${backupVm}..."
virsh shutdown --domain ${vmId}
countDown=300 # seconds, 5 minutes
while [ $countDown -gt 0 ]; do
if virsh domstate ${backupVm} | grep 'shut off' ; then
poweredoff=1
break
fi
sleepIntervalSeconds=5
sleep $sleepIntervalSeconds
countDown=$((countDown-sleepIntervalSeconds))
done
if [ ${poweredoff} -ne 1 ]; then
_log "Unable to shut down ${backupVm}, will create a snapshot instead"
fi
fi
# skip snapshot if the VM is not powered on
if [ ${poweredoff} -ne 1 ] && [ ${vmId} -gt 0 ]; then
# create disk spec
for disk in ${disks}; do
_log "Adding disk to snapshot :: ${disk%%,*}"
diskSpecs="${diskSpecs} --diskspec ${disk%%,*},snapshot=external"
done
_log "Creating snapshot..."
virsh snapshot-create-as \
--domain ${vmId} \
--atomic \
--disk-only \
--name "backup-snapshot_${date}" \
--no-metadata \
${diskSpecs}
if [ $? -ne 0 ]; then
_log "Failed to create snapshot!"
exit 7
fi
snap=1
else
_log "Skip snapshot - VM is not powered on"
fi
# copy disks to VM backup directory
_log "Copy disks to backup directory..."
for disk in ${disks}; do
_log "Copying disk :: ${disk#*,}"
filename="$(basename ${disk#*,})"
if [ ${samefmt} -eq 1 ]; then
cp -v "${disk#*,}" "${backupVmDir}/${filename}_${date}.bak"
else
qemu-img convert -O qcow2 ${compress} "${disk#*,}" "${backupVmDir}/${filename}_${date}.bak"
fi
done
# skip commit and remove if the VM is not powered on
if [ ${vmId} -gt 0 ] && [ ${snap} -eq 1 ]; then
# get list of disks
disks=$(virsh domblklist ${vmId} --details | sed 1,2d | awk NF | awk '$2 == "disk" { print $3","$4 }')
# commit changes
_log "Commit changes back to original disks..."
for disk in ${disks}; do
_log "Disk :: ${disk}"
if ! virsh blockcommit ${vmId} "${disk#*,}" --active --pivot; then
_log "Failed to commit changes. VM '${backupVm}' may be in a bad state."
exit 8
fi
sync
done
# wait 5 secs before removing files
sleep 5
# remove temp files
_log "Remove temp files..."
for disk in ${disks}; do
_log "Disk :: ${disk}"
rm -fv "${disk#*,}"
done
else
_log "Skip commit and remove - VM is not powered on"
fi
# power on VM if poweroff flag passed and VM was actually powered off
if [ ${poweroff} -eq 1 ] && [ ${poweredoff} -eq 1 ]; then
_log "Power on ${backupVm}..."
virsh start ${backupVm}
fi
# add entry to list file
used=$(du --block-size=1 "${backupVmDir}" | awk '{ print $1 }')
_log "Adding entry to list file '${listFile}'"
echo "$(uuid),${backupDir},${backupVm},${date},${used}" >> ${listFile}
end=$(date +%s)
backuptime=$((end-start))
_log "Backup size :: ${used} bytes"
_log "Backup time :: ${backuptime} secs"
if [ ${keep} -gt 0 ]; then
_log "Keeping the most recent ${keep} backups..."
keepDir="${backupDir}/${backupVm}/"
OFS=$IFS
IFS=$'\n'
delDirs=$(find "${keepDir}" -mindepth 1 -maxdepth 1 -type d | sort -r | awk "NR>${keep}")
for d in ${delDirs}; do
delDate="$(basename "${d}")"
_log "delete date :: ${delDate}"
delDir="$(dirname "${keepDir}")/"
_log "delete dir :: ${delDir}"
_log "Removing ${d}..."
rm -rv "${d}"
grep "${delDir},${backupVm},${delDate}" ${listFile}
sed -i "\|${delDir},${backupVm},${delDate}|d" ${listFile}
done
IFS=$OFS
fi
_log "Done."
exit 0