Add some missing "exit 1" statements
[snf-image] / snf-image-host / common.sh.in
1 # Copyright (C) 2011 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 AWK="awk"
20 LOSETUP="losetup"
21 KPARTX="kpartx"
22 SFDISK="sfdisk"
23 QEMU_IMG="qemu-img"
24 INSTALL_MBR="install-mbr"
25 TIMEOUT="timeout"
26 CURL="curl"
27 DATE="date -u" # Time in UTC
28
29 # Temporary use stderr as monitoring file descriptor.
30 # `create' will overwrite this
31 MONITOR_FD="2"
32
33 MSG_TYPE_ERROR="image-error"
34 MSG_TYPE_INFO="image-info"
35
36 CLEANUP=( )
37 ERROR_MSGS=( )
38
39
40 add_cleanup() {
41     local cmd=""
42     for arg; do cmd+=$(printf "%q " "$arg"); done
43     CLEANUP+=("$cmd")
44 }
45
46 log_error() {
47     echo "[ERROR] $*" >&2
48 }
49
50 report_error() {
51     ERROR_MSGS+=("$@")
52 }
53
54 report_info() {
55     local report
56     echo "[INFO] $*" >&2
57     report="$(./host-monitor.py info <<< "$*")"
58     eval "echo $(printf "%q" "$report") >&${MONITOR_FD}"
59 }
60
61
62 close_fd() {
63     local fd="$1"
64     exec {fd}>&-
65 }
66
67 send_errors() {
68     local report=""
69     if [ ${#ERROR_MSGS[@]} -gt 0 ]; then
70         local msg=""
71         for err in "${ERROR_MSGS[@]}"; do
72             msg+="$(echo "$err")"
73         done
74         report="$(./host-monitor.py error <<< "$msg")"
75     else
76         report=$(./host-monitor.py error <<< "Internal Error: Image deployment failed.")
77     fi
78
79     eval "echo $(printf "%q" "$report") >&${MONITOR_FD}"
80 }
81
82 get_api5_arguments() {
83     GETOPT_RESULT=$*
84     # Note the quotes around `$TEMP': they are essential!
85     eval set -- "$GETOPT_RESULT"
86     while true; do
87         case "$1" in
88             -i|-n) instance=$2; shift 2;;
89
90             -o) old_name=$2; shift 2;;
91
92             -b) blockdev=$2; shift 2;;
93
94             -s) swapdev=$2; shift 2;;
95
96             --) shift; break;;
97
98             *)  log_error "Internal error!" >&2; exit 1;;
99         esac
100     done
101     if [ -z "$instance" -o -z "$blockdev" ]; then
102         log_error "Missing OS API Argument (-i, -n, or -b)"
103         exit 1
104     fi
105     if [ "$SCRIPT_NAME" != "export" -a -z "$swapdev"  ]; then
106         log_error "Missing OS API Argument -s (swapdev)"
107         exit 1
108     fi
109     if [ "$SCRIPT_NAME" = "rename" -a -z "$old_name"  ]; then
110         log_error "Missing OS API Argument -o (old_name)"
111         exit 1
112     fi
113 }
114
115 get_api10_arguments() {
116     if [ -z "$INSTANCE_NAME" -o -z "$HYPERVISOR" -o -z "$DISK_COUNT" ]; then
117         log_error "Missing OS API Variable:"
118         log_error "(INSTANCE_NAME HYPERVISOR or DISK_COUNT)"
119         exit 1
120     fi
121     instance=$INSTANCE_NAME
122     if [ $DISK_COUNT -lt 1 -o -z "$DISK_0_PATH" ]; then
123         log_error "At least one disk is needed"
124         exit 1
125     fi
126     if [ "$SCRIPT_NAME" = "export" ]; then
127         if [ -z "$EXPORT_DEVICE" ]; then
128             log_error "Missing OS API Variable EXPORT_DEVICE"
129             exit 1
130         fi
131         blockdev=$EXPORT_DEVICE
132     elif [ "$SCRIPT_NAME" = "import" ]; then
133         if [ -z "$IMPORT_DEVICE" ]; then
134             log_error "Missing OS API Variable IMPORT_DEVICE"
135             exit 1
136         fi
137         blockdev=$IMPORT_DEVICE
138     else
139         blockdev=$DISK_0_PATH
140     fi
141     if [ "$SCRIPT_NAME" = "rename" -a -z "$OLD_INSTANCE_NAME" ]; then
142         log_error "Missing OS API Variable OLD_INSTANCE_NAME"
143         exit 1
144     fi
145     old_name=$OLD_INSTANCE_NAME
146 }
147
148 get_api20_arguments() {
149     get_api10_arguments
150
151     local required_osparams="IMG_ID IMG_FORMAT IMG_PASSWD"
152     local osparams="$required_osparams IMG_PROPERTIES IMG_PERSONALITY CONFIG_URL"
153
154     # Store OSP_VAR in VAR
155     for param in $osparams; do
156         eval $param=\"\$OSP_$param\"
157     done
158
159     if [ -n "$CONFIG_URL" ]; then
160         local config config_params
161         config=$($CURL -f "$CONFIG_URL")
162         config_params=$(./decode-config.py $osparams <<< "$config")
163         eval "$config_params"
164     fi
165
166     for var in $required_osparams; do
167         if [ -z "${!var}" ]; then
168              log_error "Missing OS API Parameter: ${var}"
169              exit 1
170         fi
171     done
172 }
173
174 map_disk0() {
175     blockdev="$1"
176     filesystem_dev_base=$($KPARTX -l -p- $blockdev | \
177                             grep -m 1 -- "-1.*$blockdev" | \
178                             $AWK '{print $1}')
179     if [ -z "$filesystem_dev_base" ]; then
180         log_error "Cannot interpret kpartx output and get partition mapping"
181         exit 1
182     fi
183     $KPARTX -a -p- "$blockdev" > /dev/null
184     filesystem_dev="/dev/mapper/${filesystem_dev_base/%-1/}"
185     if [ ! -b "/dev/mapper/$filesystem_dev_base" ]; then
186         log_error "Can't find kpartx mapped partition:" \
187                                             "/dev/mapper/$filesystem_dev_base"
188         exit 1
189     fi
190     echo "$filesystem_dev"
191 }
192
193 unmap_disk0() {
194     $KPARTX -d -p- "$1"
195 }
196
197 format_disk0() {
198     local device="$1"
199     local image_type="$2"
200
201     declare -A part_id=( ['extdump']="83" ["ntfsdump"]="7" )
202
203     # The -f is needed, because we use an optimal alignment and sfdisk complains
204     # about partitions not ending on clylinder boundary.
205     local sfdisk_cmd="$SFDISK -uS -H 255 -S 63 -f --quiet --Linux --DOS $device"
206
207     $sfdisk_cmd > /dev/null <<EOF
208 2048,,${part_id["$image_type"]},*
209 EOF
210 }
211
212 create_floppy() {
213     local img target
214
215     img=$1
216
217     target=$(mktemp -d)
218     add_cleanup rmdir "$target"
219
220     dd bs=512 count=2880 if=/dev/zero of="$img"
221     mkfs.ext2 -F "$img" > /dev/null
222     mount "$img" "$target" -o loop
223     set | egrep ^snf_export_\\w+= | sed -e 's/^snf_export_/export SNF_IMAGE_/' \
224         > "$target/rules"
225     if [ -n "$UNATTEND" ]; then
226         if [ -f "$UNATTEND" ]; then
227             cat "$UNATTEND" > "$target/unattend.xml"
228         else
229             log_error "Unattend file: \`"$UNATTEND"' does not exist"
230             exit 1
231         fi
232     fi
233     umount "$target"
234 }
235
236 get_backend_type() {
237     local id=$1
238
239     if [[ "$id" =~ ^pithos: ]]; then
240         echo "pithos"
241     elif [[ "$id" =~ ^pithosmap: ]]; then
242         echo "pithos"
243     elif [[ "$id" =~ ^(http|ftp)s?: ]]; then
244         echo "network"
245     elif [ "$id" = "null" ]; then
246         echo "null"
247     else
248         echo "local"
249     fi
250 }
251
252 # this one is only to be called by create
253 ganeti_os_main() {
254     if [ -z "$OS_API_VERSION" -o "$OS_API_VERSION" = "5" ]; then
255         OS_API_VERSION=5
256         GETOPT_RESULT=`getopt -o o:n:i:b:s: -n '$0' -- "$@"`
257         if [ $? != 0 ] ; then log_error "Terminating..."; exit 1 ; fi
258         get_api5_arguments $GETOPT_RESULT
259     elif [ "$OS_API_VERSION" = "10" -o "$OS_API_VERSION" = "15" ]; then
260         get_api10_arguments
261     elif [ "$OS_API_VERSION" = "20" ]; then
262         get_api20_arguments
263         IMAGE_NAME="$IMG_ID"
264         IMAGE_TYPE="$IMG_FORMAT"
265         BACKEND_TYPE=$(get_backend_type $IMG_ID)
266     else
267         log_error "Unknown OS API VERSION $OS_API_VERSION"
268         exit 1
269     fi
270     
271     if [ -n "$OS_VARIANT" ]; then
272         if [ ! -d "$VARIANTS_DIR" ]; then
273             log_error "OS Variants directory $VARIANTS_DIR doesn't exist"
274             exit 1
275         fi
276         VARIANT_CONFIG="$VARIANTS_DIR/$OS_VARIANT.conf"
277         if [ -f "$VARIANT_CONFIG" ]; then
278             . "$VARIANT_CONFIG"
279         else
280             if grep -qxF "$OS_VARIANT" variants.list; then
281                 log_error "ERROR: instance-image configuration error"
282                 log_error "  Published variant $OS_VARIANT is missing its" \
283                     "config file"
284                 log_error "  Please create $VARIANT_CONFIG or unpublish the" \
285                     "variant"
286                 log_error "  (by removing $OS_VARIANT from variants.list)"
287             else
288                 log_error "Unofficial variant $OS_VARIANT is unsupported"
289                 log_error "Most probably this is a user error, forcing a" \
290                     "wrong name"
291                 log_error "To support this variant please create file" \
292                     "$VARIANT_CONFIG"
293             fi
294             exit 1
295         fi
296     fi
297
298 }
299
300 do_multistrap() {
301    local target="$1"
302    local cache="$2"
303    local pkgs="$3"
304
305     # Create preferences.d for apt
306     mkdir -p "$target/etc/apt/preferences.d"
307     if [ -d "$MULTISTRAP_APTPREFDIR" ]; then
308         find "$MULTISTRAP_APTPREFDIR" -maxdepth 1 -type f -exec cp {} "$target/etc/apt/preferences.d" \;
309     fi
310
311     # Create a policy-rc.d file to deny init script execution
312     mkdir -p "$target/usr/sbin"
313     cat > "$target/usr/sbin/policy-rc.d" <<EOF
314 #!/bin/sh
315 exit 101
316 EOF
317     chmod +x "$target/usr/sbin/policy-rc.d"
318
319    multistrap -d "$target" -f "$MULTISTRAP_CONFIG" 2>&1 | sed -u -e 's/^/MULTISTRAP: /g'
320
321    rm "$target/usr/sbin/policy-rc.d"
322    rm -rf "$target/etc/apt/preferences.d"
323 }
324
325 report_and_cleanup() {
326     send_errors
327     cleanup
328 }
329
330 suppress_errors() {
331     "$@" &> /dev/null || true
332 }
333
334 check_helper_rc() {
335     local rc=$1
336
337     if [ $rc -ne 0 ]; then
338         if [ $rc -eq 124 ];  then
339             log_error "Customization VM was terminated. Did not finish on time."
340             report_error "Image customization failed. Did not finish on time."
341         elif [ $rc -eq 137 ]; then # (128 + SIGKILL)
342             log_error "Customization VM was killed. Did not finish on time."
343             report_error "Image customization failed. Did not finish on time."
344         elif [ $rc -eq 141 ]; then # (128 + SIGPIPE)
345             log_error "Customization VM was terminated by a SIGPIPE."
346             log_error "Maybe progress monitor has died unexpectedly."
347         elif [ $rc -eq 125 ]; then
348             log_error "Internal Error. Image customization could not start."
349             log_error "timeout did not manage to run."
350         else
351             log_error "Customization VM died unexpectedly (return code $rc)."
352         fi
353         exit 1
354     else
355         report_info "Customization VM exited normally."
356     fi
357 }
358
359 check_helper_result() {
360    local result=$1
361
362     if [ "x$result" != "xSUCCESS" ]; then
363         log_error "Image customization failed."
364         report_error "Image customization failed."
365         exit 1
366     fi
367 }
368
369 cleanup() {
370     # if something fails here, it souldn't call cleanup again...
371     trap - EXIT
372
373     if [ ${#CLEANUP[*]} -gt 0 ]; then
374         LAST_ELEMENT=$((${#CLEANUP[*]}-1))
375         REVERSE_INDEXES=$(seq ${LAST_ELEMENT} -1 0)
376         for i in $REVERSE_INDEXES; do
377             # If something fails here, it's better to retry it for a few times
378             # before we give up with an error. This is needed for kpartx when
379             # dealing with ntfs partitions mounted through fuse. umount is not
380             # synchronous and may return while the partition is still busy. A
381             # premature attempt to delete partition mappings through kpartx on
382             # a device that hosts previously mounted ntfs partition may fail
383             # with errors like this one:
384             # `device-mapper: remove ioctl failed: Device or resource busy'
385             # A sensible workaround for this is to wait for a while and then
386             # retry it.
387             local cmd=${CLEANUP[$i]}
388             $cmd || for interval in 0.25 0.5 1 2 4; do
389             echo "Command $cmd failed!"
390             echo "I'll wait for $interval secs and will retry..."
391             sleep $interval
392             $cmd && break
393         done
394         if [ "$?" != "0" ]; then
395             echo "Giving Up..."
396             exit 1;
397         fi
398     done
399   fi
400 }
401
402 trap cleanup EXIT
403
404 DEFAULT_FILE="@sysconfdir@/default/snf-image"
405 if [ -f "$DEFAULT_FILE" ]; then
406     . "$DEFAULT_FILE"
407 fi
408
409 : ${VARIANTS_DIR:="@sysconfdir@/ganeti/snf-image/variants"}
410 : ${IMAGE_DIR:="@localstatedir@/lib/snf-image"}
411 : ${IMAGE_DEBUG:="no"}
412 : ${VERSION_CHECK:="@VERSION_CHECK@"}
413 : ${HELPER_DIR:="@HELPER_DIR@"}
414 : ${HELPER_SIZE:="600"}
415 : ${HELPER_SOFT_TIMEOUT:=120}
416 : ${HELPER_HARD_TIMEOUT:=5}
417 : ${HELPER_USER:="nobody"}
418 : ${PITHOS_DB:="sqlite:////@localstatedir@/lib/pithos/backend.db"}
419 : ${PITHOS_DATA:="@localstatedir@/lib/pithos/data/"}
420 : ${PROGRESS_MONITOR:="@PROGRESS_MONITOR@"}
421 : ${UNATTEND:="@UNATTEND@"}
422 : ${XEN_SCRIPTS_DIR="@sysconfdir@/xen/scripts"}
423 : ${MULTISTRAP_CONFIG:="@MULTISTRAP_CONFIG@"}
424 : ${MULTISTRAP_APTPREFDIR:="@MULTISTRAP_APTPREFDIR@"}
425
426 case $HYPERVISOR in
427     xen-hvm|xen-pvm) . xen-common.sh ;;
428     kvm) . kvm-common.sh ;;
429 esac
430
431 SCRIPT_NAME=$(basename $0)
432
433 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :