docs: Remove reference to a file:// img_id prefix
[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     if [ -z "$table" ]; then
340         return 0
341     fi
342
343     if [ $(get_partition_count "$table") -eq 0 ]; then
344         return 0
345     fi
346
347     table_type=$(get_partition_table_type "$table")
348     last_part=$(get_last_partition "$table")
349     last_part_num=$(cut -d: -f1 <<< "$last_part")
350
351     if [ "$table_type" == "msdos" -a $last_part_num -gt 4 ]; then
352         extended=$(get_extended_partition "$table")
353         last_primary=$(get_last_primary_partition "$table")
354         ext_num=$(cut -d: -f1 <<< "$extended")
355         last_prim_num=$(cut -d: -f1 <<< "$last_primary")
356
357         if [ "$ext_num" != "$last_prim_num" ]; then
358             echo "$last_prim_num"
359         else
360             echo "$last_part_num"
361         fi
362     else
363         echo "$last_part_num"
364     fi
365 }
366
367 create_partition() {
368     local device="$1"
369     local part="$2"
370     local ptype="$3"
371
372     local fields=()
373     IFS=":;" read -ra fields <<< "$part"
374     local id="${fields[0]}"
375     local start="${fields[1]}"
376     local end="${fields[2]}"
377     local size="${fields[3]}"
378     local fs="${fields[4]}"
379     local name="${fields[5]}"
380     local flags="${fields[6]//,/ }"
381
382     if [ "$ptype" = "primary" -o "$ptype" = "logical" -o "$ptype" = "extended" ]; then
383         $PARTED -s -m -- $device mkpart "$ptype" $fs "$start" "$end"
384         for flag in $flags; do
385             $PARTED -s -m $device set "$id" "$flag" on
386         done
387     else
388         # For gpt
389         start=${start:0:${#start}-1} # remove the s at the end
390         end=${end:0:${#end}-1} # remove the s at the end
391         $SGDISK -n "$id":"$start":"$end" -t "$id":"$ptype" "$device"
392     fi
393 }
394
395 enlarge_partition() {
396     local device part ptype new_end fields new_part table logical id
397     device="$1"
398     part="$2"
399     ptype="$3"
400     new_end="$4"
401
402     if [ -z "$new_end" ]; then
403         new_end=$(cut -d: -f 3 <<< "$(get_last_free_sector "$device")")
404     fi
405
406     fields=()
407     IFS=":;" read -ra fields <<< "$part"
408     fields[2]="$new_end"
409
410     new_part=""
411     for ((i = 0; i < ${#fields[*]}; i = i + 1)); do
412         new_part="$new_part":"${fields[$i]}"
413     done
414     new_part=${new_part:1}
415
416     # If this is an extended partition, removing it will also remove the
417     # logical partitions it contains. We need to save them for later.
418     if [ "$ptype" = "extended" ]; then
419         table="$(get_partition_table "$device")"
420         logical="$(get_logical_partitions "$table")"
421     fi
422
423     id=${fields[0]}
424     $PARTED -s -m "$device" rm "$id"
425     create_partition "$device" "$new_part" "$ptype"
426
427     if [ "$ptype" = "extended" ]; then
428         # Recreate logical partitions
429         echo "$logical" | while read logical_part; do
430             create_partition "$device" "$logical_part" "logical"
431         done
432     fi
433 }
434
435 get_last_free_sector() {
436     local dev unit last_line ptype
437     dev="$1"
438     unit="$2"
439
440     if [ -n "$unit" ]; then
441         unit="unit $unit"
442     fi
443
444     last_line="$($PARTED -s -m "$dev" "$unit" print free | tail -1)"
445     ptype="$(cut -d: -f 5 <<< "$last_line")"
446
447     if [ "$ptype" = "free;" ]; then
448         echo "$last_line"
449     fi
450 }
451
452 get_unattend() {
453     local target exists
454     target="$1"
455
456     # Workaround to search for $target/Unattend.xml in an case insensitive way.
457     exists=$(find "$target"/ -maxdepth 1 -iname unattend.xml)
458     if [ $(wc -l <<< "$exists") -gt 1 ]; then
459         log_error "Found multiple Unattend.xml files in the image:" $exists
460     fi
461
462     echo "$exists"
463 }
464
465 umount_all() {
466     local target mpoints
467     target="$1"
468
469     # Unmount file systems mounted under directory `target'
470     mpoints="$({ awk "{ if (match(\$2, \"^$target\")) { print \$2 } }" < /proc/mounts; } | sort -rbd | uniq)"
471
472     for mpoint in $mpoints; do
473         umount $mpoint
474     done
475 }
476
477 cleanup() {
478     # if something fails here, it shouldn't call cleanup again...
479     trap - EXIT
480
481     if [ ${#CLEANUP[*]} -gt 0 ]; then
482         LAST_ELEMENT=$((${#CLEANUP[*]}-1))
483         REVERSE_INDEXES=$(seq ${LAST_ELEMENT} -1 0)
484         for i in $REVERSE_INDEXES; do
485             # If something fails here, it's better to retry it for a few times
486             # before we give up with an error. This is needed for kpartx when
487             # dealing with ntfs partitions mounted through fuse. umount is not
488             # synchronous and may return while the partition is still busy. A
489             # premature attempt to delete partition mappings through kpartx on
490             # a device that hosts previously mounted ntfs partition may fail
491             # with a `device-mapper: remove ioctl failed: Device or resource
492             # busy' error. A sensible workaround for this is to wait for a
493             # while and then try again.
494             local cmd=${CLEANUP[$i]}
495             $cmd || for interval in 0.25 0.5 1 2 4; do
496             echo "Command $cmd failed!"
497             echo "I'll wait for $interval secs and will retry..."
498             sleep $interval
499             $cmd && break
500         done
501         if [ "$?" != "0" ]; then
502             echo "Giving Up..."
503             exit 1;
504         fi
505     done
506   fi
507 }
508
509 task_cleanup() {
510     local rc=$?
511
512     if [ $rc -eq 0 ]; then
513        report_task_end
514     else
515        report_error
516     fi
517
518     cleanup
519 }
520
521 check_if_excluded() {
522     local name exclude
523     name="$(tr [a-z] [A-Z] <<< ${PROGNAME:2})"
524     exclude="SNF_IMAGE_PROPERTY_EXCLUDE_TASK_${name}"
525     if [ -n "${!exclude}" ]; then
526         warn "Task ${PROGNAME:2} was excluded and will not run."
527         exit 0
528     fi
529
530     return 0
531 }
532
533
534 return_success() {
535     send_result_${HYPERVISOR} "SUCCESS"
536 }
537
538 trap cleanup EXIT
539 set -o pipefail
540
541 STDERR_FILE=$(mktemp)
542 add_cleanup rm -f "$STDERR_FILE"
543 exec 2> >(tee -a "$STDERR_FILE" >&2)
544
545 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :