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