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