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