Bump version to 0.10.1
[snf-image] / snf-image-helper / common.sh
1 # Copyright (C) 2011, 2012, 2013 GRNET S.A.
2 # Copyright (C) 2007, 2008, 2009 Google Inc.
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 # 02110-1301, USA.
18
19 PROGNAME=$(basename $0)
20
21 PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
22
23 # Programs
24 XMLSTARLET=xmlstarlet
25 TUNE2FS=tune2fs
26 RESIZE2FS=resize2fs
27 PARTED=parted
28 SFDISK=sfdisk
29 MKSWAP=mkswap
30 BLKID=blkid
31 BLOCKDEV=blockdev
32 REGLOOKUP=reglookup
33 CHNTPW=chntpw
34 SGDISK=sgdisk
35 GROWFS_UFS=growfs.ufs
36 DUMPFS_UFS=dumpfs.ufs
37 DATE="date -u" # Time in UTC
38 EATMYDATA=eatmydata
39 MOUNT="mount -n"
40
41 CLEANUP=( )
42 ERRORS=( )
43 WARNINGS=( )
44
45 MSG_TYPE_TASK_START="TASK_START"
46 MSG_TYPE_TASK_END="TASK_END"
47
48 STDERR_LINE_SIZE=10
49
50 add_cleanup() {
51     local cmd=""
52     for arg; do cmd+=$(printf "%q " "$arg"); done
53     CLEANUP+=("$cmd")
54 }
55
56 close_fd() {
57     local fd=$1
58
59     exec {fd}>&-
60 }
61
62 send_result_kvm() {
63     echo "$@" > /dev/ttyS1
64 }
65
66 send_monitor_message_kvm() {
67     echo "$@" > /dev/ttyS2
68 }
69
70 send_result_xen() {
71     xenstore-write /local/domain/0/snf-image-helper/$DOMID "$*"
72 }
73
74 send_monitor_message_xen() {
75     #Broadcast the message
76     echo "$@" | socat "STDIO" "UDP-DATAGRAM:${BROADCAST}:${MONITOR_PORT},broadcast"
77 }
78
79 prepare_helper() {
80         local cmdline item key val hypervisor domid
81
82         read -a cmdline  < /proc/cmdline
83         for item in "${cmdline[@]}"; do
84             key=$(cut -d= -f1 <<< "$item")
85             val=$(cut -d= -f2 <<< "$item")
86             if [ "$key" = "hypervisor" ]; then
87                 hypervisor="$val"
88             fi
89             if [ "$key" = "rules_dev" ]; then
90                 export RULES_DEV="$val"
91             fi
92             if [ "$key" = "helper_ip" ]; then
93                 export IP="$val"
94                 export NETWORK="$IP/24"
95                 export BROADCAST="${IP%.*}.255"
96             fi
97             if [ "$key" = "monitor_port" ]; then
98                 export MONITOR_PORT="$val"
99             fi
100         done
101
102     case "$hypervisor" in
103     kvm)
104         HYPERVISOR=kvm
105         ;;
106     xen-hvm|xen-pvm)
107         if [ -z "$IP" ]; then
108             echo "ERROR: \`helper_ip' not defined or empty" >&2
109             exit 1
110         fi
111         if [ -z "$MONITOR_PORT" ]; then
112             echo "ERROR: \`monitor_port' not defined or empty" >&2
113             exit 1
114         fi
115         $MOUNT -t xenfs xenfs /proc/xen
116         ip addr add "$NETWORK" dev eth0
117         ip link set eth0 up
118         ip route add default dev eth0
119         export DOMID=$(xenstore-read domid)
120         HYPERVISOR=xen
121         ;;
122     *)
123         echo "ERROR: Unknown hypervisor: \`$hypervisor'" >&2
124         exit 1
125         ;;
126     esac
127
128     export HYPERVISOR
129 }
130
131 report_error() {
132     msg=""
133     if [ ${#ERRORS[*]} -eq 0 ]; then
134         # No error message. Print stderr
135         local lines stderr
136         stderr="$(tail --lines=${STDERR_LINE_SIZE} "$STDERR_FILE")"
137         lines=$(wc -l <<< "$stderr")
138         msg="STDERR:${lines}:$stderr"
139     else
140         for line in "${ERRORS[@]}"; do
141             msg+="ERROR:$line"$'\n'
142         done
143     fi
144
145     send_monitor_message_${HYPERVISOR} "$msg"
146 }
147
148 log_error() {
149     ERRORS+=("$*")
150
151     send_result_${HYPERVISOR} "ERROR: $@"
152
153     # Use return instead of exit. The set -x options will terminate the script
154     # but will also trigger ERR traps if defined.
155     return 1
156 }
157
158 warn() {
159     echo "Warning: $@" >&2
160     send_monitor_message_${HYPERVISOR} "WARNING: $@"
161 }
162
163 report_task_start() {
164     send_monitor_message_${HYPERVISOR} "$MSG_TYPE_TASK_START:${PROGNAME:2}"
165 }
166
167 report_task_end() {
168     send_monitor_message_${HYPERVISOR} "$MSG_TYPE_TASK_END:${PROGNAME:2}"
169 }
170
171 system_poweroff() {
172     while [ 1 ]; do
173         # Credits to psomas@grnet.gr for this ...
174         echo o > /proc/sysrq-trigger
175         sleep 1
176     done
177 }
178
179 get_base_distro() {
180     local root_dir=$1
181
182     if [ -e "$root_dir/etc/debian_version" ]; then
183         echo "debian"
184     elif [ -e "$root_dir/etc/redhat-release" ]; then
185         echo "redhat"
186     elif [ -e "$root_dir/etc/slackware-version" ]; then
187         echo "slackware"
188     elif [ -e "$root_dir/etc/SuSE-release" ]; then
189         echo "suse"
190     elif [ -e "$root_dir/etc/gentoo-release" ]; then
191         echo "gentoo"
192     elif [ -e "$root_dir/etc/arch-release" ]; then
193         echo "arch"
194     elif [ -e "$root_dir/etc/freebsd-update.conf" ]; then
195         echo "freebsd"
196     else
197         warn "Unknown base distro."
198     fi
199 }
200
201 get_distro() {
202     local root_dir distro
203     root_dir=$1
204
205     if [ -e "$root_dir/etc/debian_version" ]; then
206         distro="debian"
207         if [ -e ${root_dir}/etc/lsb-release ]; then
208             ID=$(grep ^DISTRIB_ID= ${root_dir}/etc/lsb-release | cut -d= -f2)
209             if [ "x$ID" = "xUbuntu" ]; then
210                 distro="ubuntu"
211             fi
212         fi
213         echo "$distro"
214     elif [ -e "$root_dir/etc/fedora-release" ]; then
215         echo "fedora"
216     elif [ -e "$root_dir/etc/centos-release" ]; then
217         echo "centos"
218     elif [ -e "$root_dir/etc/redhat-release" ]; then
219         echo "redhat"
220     elif [ -e "$root_dir/etc/slackware-version" ]; then
221         echo "slackware"
222     elif [ -e "$root_dir/etc/SuSE-release" ]; then
223         echo "suse"
224     elif [ -e "$root_dir/etc/gentoo-release" ]; then
225         echo "gentoo"
226     elif [ -e "$root_dir/etc/arch-release" ]; then
227         echo "arch"
228     elif [ -e "$root_dir/etc/freebsd-update.conf" ]; then
229         echo "freebsd"
230     else
231         warn "Unknown distro."
232     fi
233 }
234
235
236 get_partition_table() {
237     local dev output
238     dev="$1"
239     # If the partition table is gpt then parted will raise an error if the
240     # secondary gpt is not it the end of the disk, and a warning that has to
241     # do with the "Last Usable LBA" entry in gpt.
242     if ! output="$("$PARTED" -s -m "$dev" unit s print | grep -E -v "^(Warning|Error): ")"; then
243         log_error "Unable to read partition table for device \`${dev}'. The image seems corrupted."
244     fi
245
246     echo "$output"
247 }
248
249 get_partition_table_type() {
250     local ptable dev field
251     ptable="$1"
252
253     dev="$(sed -n 2p <<< "$ptable")"
254     IFS=':' read -ra field <<< "$dev"
255
256     echo "${field[5]}"
257 }
258
259 get_partition_count() {
260     local ptable="$1"
261
262     expr $(echo "$ptable" | wc -l) - 2
263 }
264
265 get_partition_by_num() {
266     local ptable="$1"
267     local id="$2"
268
269     grep "^$id:" <<< "$ptable"
270 }
271
272 get_last_partition() {
273     local ptable="$1"
274
275     echo "$ptable" | tail -1
276 }
277
278 is_extended_partition() {
279     local dev="$1"
280     local part_num="$2"
281
282     id=$($SFDISK --force --print-id "$dev" "$part_num")
283     if [ "$id" = "5" -o "$id" = "f" ]; then
284         echo "yes"
285     else
286         echo "no"
287     fi
288 }
289
290 get_extended_partition() {
291     local ptable dev
292     ptable="$1"
293     dev="$(echo "$ptable" | sed -n 2p | cut -d':' -f1)"
294
295     tail -n +3 <<< "$ptable" | while read line; do
296         part_num=$(cut -d':' -f1 <<< "$line")
297         if [ $(is_extended_partition "$dev" "$part_num") == "yes" ]; then
298             echo "$line"
299             return 0
300         fi
301     done
302     echo ""
303 }
304
305 get_logical_partitions() {
306     local ptable part_num
307     ptable="$1"
308
309     tail -n +3 <<< "$ptable" | while read line; do
310         part_num=$(cut -d':' -f1 <<< "$line")
311         if [ $part_num -ge 5 ]; then
312             echo "$line"
313         fi
314     done
315
316     return 0
317 }
318
319 get_last_primary_partition() {
320     local ptable dev output
321     ptable="$1"
322     dev=$(echo "ptable" | sed -n 2p | cut -d':' -f1)
323
324     for i in 4 3 2 1; do
325         if output=$(grep "^$i:" <<< "$ptable"); then
326             echo "$output"
327             return 0
328         fi
329     done
330     echo ""
331 }
332
333 get_partition_to_resize() {
334     local dev table table_type last_part last_part_num extended last_primary \
335         ext_num prim_num
336     dev="$1"
337
338     table=$(get_partition_table "$dev")
339
340     if [ $(get_partition_count "$table") -eq 0 ]; then
341         return 0
342     fi
343
344     table_type=$(get_partition_table_type "$table")
345     last_part=$(get_last_partition "$table")
346     last_part_num=$(cut -d: -f1 <<< "$last_part")
347
348     if [ "$table_type" == "msdos" -a $last_part_num -gt 4 ]; then
349         extended=$(get_extended_partition "$table")
350         last_primary=$(get_last_primary_partition "$table")
351         ext_num=$(cut -d: -f1 <<< "$extended")
352         last_prim_num=$(cut -d: -f1 <<< "$last_primary")
353
354         if [ "$ext_num" != "$last_prim_num" ]; then
355             echo "$last_prim_num"
356         else
357             echo "$last_part_num"
358         fi
359     else
360         echo "$last_part_num"
361     fi
362 }
363
364 create_partition() {
365     local device="$1"
366     local part="$2"
367     local ptype="$3"
368
369     local fields=()
370     IFS=":;" read -ra fields <<< "$part"
371     local id="${fields[0]}"
372     local start="${fields[1]}"
373     local end="${fields[2]}"
374     local size="${fields[3]}"
375     local fs="${fields[4]}"
376     local name="${fields[5]}"
377     local flags="${fields[6]//,/ }"
378
379     if [ "$ptype" = "primary" -o "$ptype" = "logical" -o "$ptype" = "extended" ]; then
380         $PARTED -s -m -- $device mkpart "$ptype" $fs "$start" "$end"
381         for flag in $flags; do
382             $PARTED -s -m $device set "$id" "$flag" on
383         done
384     else
385         # For gpt
386         start=${start:0:${#start}-1} # remove the s at the end
387         end=${end:0:${#end}-1} # remove the s at the end
388         $SGDISK -n "$id":"$start":"$end" -t "$id":"$ptype" "$device"
389     fi
390 }
391
392 enlarge_partition() {
393     local device part ptype new_end fields new_part table logical id
394     device="$1"
395     part="$2"
396     ptype="$3"
397     new_end="$4"
398
399     if [ -z "$new_end" ]; then
400         new_end=$(cut -d: -f 3 <<< "$(get_last_free_sector "$device")")
401     fi
402
403     fields=()
404     IFS=":;" read -ra fields <<< "$part"
405     fields[2]="$new_end"
406
407     new_part=""
408     for ((i = 0; i < ${#fields[*]}; i = i + 1)); do
409         new_part="$new_part":"${fields[$i]}"
410     done
411     new_part=${new_part:1}
412
413     # If this is an extended partition, removing it will also remove the
414     # logical partitions it contains. We need to save them for later.
415     if [ "$ptype" = "extended" ]; then
416         table="$(get_partition_table "$device")"
417         logical="$(get_logical_partitions "$table")"
418     fi
419
420     id=${fields[0]}
421     $PARTED -s -m "$device" rm "$id"
422     create_partition "$device" "$new_part" "$ptype"
423
424     if [ "$ptype" = "extended" ]; then
425         # Recreate logical partitions
426         echo "$logical" | while read logical_part; do
427             create_partition "$device" "$logical_part" "logical"
428         done
429     fi
430 }
431
432 get_last_free_sector() {
433     local dev unit last_line ptype
434     dev="$1"
435     unit="$2"
436
437     if [ -n "$unit" ]; then
438         unit="unit $unit"
439     fi
440
441     last_line="$($PARTED -s -m "$dev" "$unit" print free | tail -1)"
442     ptype="$(cut -d: -f 5 <<< "$last_line")"
443
444     if [ "$ptype" = "free;" ]; then
445         echo "$last_line"
446     fi
447 }
448
449 get_unattend() {
450     local target exists
451     target="$1"
452
453     # Workaround to search for $target/Unattend.xml in an case insensitive way.
454     exists=$(find "$target"/ -maxdepth 1 -iname unattend.xml)
455     if [ $(wc -l <<< "$exists") -gt 1 ]; then
456         log_error "Found multiple Unattend.xml files in the image:" $exists
457     fi
458
459     echo "$exists"
460 }
461
462 umount_all() {
463     local target mpoints
464     target="$1"
465
466     # Unmount file systems mounted under directory `target'
467     mpoints="$({ awk "{ if (match(\$2, \"^$target\")) { print \$2 } }" < /proc/mounts; } | sort -rbd | uniq)"
468
469     for mpoint in $mpoints; do
470         umount $mpoint
471     done
472 }
473
474 cleanup() {
475     # if something fails here, it shouldn't call cleanup again...
476     trap - EXIT
477
478     if [ ${#CLEANUP[*]} -gt 0 ]; then
479         LAST_ELEMENT=$((${#CLEANUP[*]}-1))
480         REVERSE_INDEXES=$(seq ${LAST_ELEMENT} -1 0)
481         for i in $REVERSE_INDEXES; do
482             # If something fails here, it's better to retry it for a few times
483             # before we give up with an error. This is needed for kpartx when
484             # dealing with ntfs partitions mounted through fuse. umount is not
485             # synchronous and may return while the partition is still busy. A
486             # premature attempt to delete partition mappings through kpartx on
487             # a device that hosts previously mounted ntfs partition may fail
488             # with a `device-mapper: remove ioctl failed: Device or resource
489             # busy' error. A sensible workaround for this is to wait for a
490             # while and then try again.
491             local cmd=${CLEANUP[$i]}
492             $cmd || for interval in 0.25 0.5 1 2 4; do
493             echo "Command $cmd failed!"
494             echo "I'll wait for $interval secs and will retry..."
495             sleep $interval
496             $cmd && break
497         done
498         if [ "$?" != "0" ]; then
499             echo "Giving Up..."
500             exit 1;
501         fi
502     done
503   fi
504 }
505
506 task_cleanup() {
507     local rc=$?
508
509     if [ $rc -eq 0 ]; then
510        report_task_end
511     else
512        report_error
513     fi
514
515     cleanup
516 }
517
518 check_if_excluded() {
519     local name exclude
520     name="$(tr [a-z] [A-Z] <<< ${PROGNAME:2})"
521     exclude="SNF_IMAGE_PROPERTY_EXCLUDE_TASK_${name}"
522     if [ -n "${!exclude}" ]; then
523         warn "Task ${PROGNAME:2} was excluded and will not run."
524         exit 0
525     fi
526
527     return 0
528 }
529
530
531 return_success() {
532     send_result_${HYPERVISOR} "SUCCESS"
533 }
534
535 trap cleanup EXIT
536 set -o pipefail
537
538 STDERR_FILE=$(mktemp)
539 add_cleanup rm -f "$STDERR_FILE"
540 exec 2> >(tee -a "$STDERR_FILE" >&2)
541
542 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :