Add helper-monitor.py program
[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 KPARTX="kpartx"
21 LOSETUP="losetup"
22 SFDISK="sfdisk"
23 QEMU_IMG="qemu-img"
24 INSTALL_MBR="install-mbr"
25 TIMEOUT="timeout"
26 CURL="curl"
27
28 network_backend_support="@network_backend_support@"
29
30 MSG_TYPE_ERROR="error"
31
32 CLEANUP=( )
33 ERROR_MSGS=( )
34
35 add_cleanup() {
36     local cmd=""
37     for arg; do cmd+=$(printf "%q " "$arg"); done
38     CLEANUP+=("$cmd")
39 }
40
41 log_error() {
42     ERROR_MSGS+=("$@")
43     echo "$@" >&2
44 }
45
46 close_fd() {
47     local fd="$1"
48     exec {fd}>&-
49 }
50
51 report_error() {
52     local error_file=$1
53     local monitor_fd=$2
54
55     local type="$MSG_TYPE_ERROR"
56     local location="host"
57
58     report="\"type\":\"$type\","
59     report+="\"timestamp\":$(date +%s.%N),"
60     report+="\"location\":\"$location\","
61
62     if [ ${#ERROR_MSGS[@]} -gt 0 ]; then
63         local msg="["
64         for err in "${ERROR_MSGS[@]}"; do
65             msg+="\"$(sed 's/"/\\"/g' <<< "$err")\","
66         done
67         if [ ${#msg} -gt 1 ]; then
68             # remove last comma (,)
69             msg="${msg%?}"
70         fi
71         msg+="]"
72         report+="\"messages\":$msg}"
73     else
74         local stderr="$(cat "$error_file" | sed 's/"/\\"/g')"
75         report+="\"stderr\":\"$stderr\"}"
76     fi
77
78     eval "echo $(printf "%q" "$report") >&${monitor_fd}"
79 }
80
81 get_api5_arguments() {
82     GETOPT_RESULT=$*
83     # Note the quotes around `$TEMP': they are essential!
84     eval set -- "$GETOPT_RESULT"
85     while true; do
86         case "$1" in
87             -i|-n) instance=$2; shift 2;;
88
89             -o) old_name=$2; shift 2;;
90
91             -b) blockdev=$2; shift 2;;
92
93             -s) swapdev=$2; shift 2;;
94
95             --) shift; break;;
96
97             *)  log_error "Internal error!" >&2; exit 1;;
98         esac
99     done
100     if [ -z "$instance" -o -z "$blockdev" ]; then
101         log_error "Missing OS API Argument (-i, -n, or -b)"
102         exit 1
103     fi
104     if [ "$SCRIPT_NAME" != "export" -a -z "$swapdev"  ]; then
105         log_error "Missing OS API Argument -s (swapdev)"
106         exit 1
107     fi
108     if [ "$SCRIPT_NAME" = "rename" -a -z "$old_name"  ]; then
109         log_error "Missing OS API Argument -o (old_name)"
110         exit 1
111     fi
112 }
113
114 get_api10_arguments() {
115     if [ -z "$INSTANCE_NAME" -o -z "$HYPERVISOR" -o -z "$DISK_COUNT" ]; then
116         log_error "Missing OS API Variable:"
117         log_error "(INSTANCE_NAME HYPERVISOR or DISK_COUNT)"
118         exit 1
119     fi
120     instance=$INSTANCE_NAME
121     if [ $DISK_COUNT -lt 1 -o -z "$DISK_0_PATH" ]; then
122         log_error "At least one disk is needed"
123         exit 1
124     fi
125     if [ "$SCRIPT_NAME" = "export" ]; then
126         if [ -z "$EXPORT_DEVICE" ]; then
127         log_error "Missing OS API Variable EXPORT_DEVICE"
128     fi
129     blockdev=$EXPORT_DEVICE
130     elif [ "$SCRIPT_NAME" = "import" ]; then
131         if [ -z "$IMPORT_DEVICE" ]; then
132         log_error "Missing OS API Variable IMPORT_DEVICE"
133         fi
134         blockdev=$IMPORT_DEVICE
135     else
136         blockdev=$DISK_0_PATH
137     fi
138     if [ "$SCRIPT_NAME" = "rename" -a -z "$OLD_INSTANCE_NAME" ]; then
139         log_error "Missing OS API Variable OLD_INSTANCE_NAME"
140     fi
141     old_name=$OLD_INSTANCE_NAME
142 }
143
144 get_api20_arguments() {
145     get_api10_arguments
146     if [ -z "$OSP_IMG_ID" ]; then
147         log_error "Missing OS API Parameter: OSP_IMG_ID"
148         exit 1
149     fi
150     if [ -z "$OSP_IMG_FORMAT" ]; then
151         log_error "Missing OS API Parameter: OSP_IMG_FORMAT"
152         exit 1
153     fi
154     if [ -z "$OSP_IMG_PASSWD" ]; then
155         log_error "Missing OS API Parameter: OSP_IMG_PASSWD"
156         exit 1
157     fi
158
159     IMG_ID=$OSP_IMG_ID
160     IMG_FORMAT=$OSP_IMG_FORMAT
161     IMG_PASSWD=$OSP_IMG_PASSWD
162     if [ -n "$OSP_IMG_PROPERTIES" ]; then
163         IMG_PROPERTIES="$OSP_IMG_PROPERTIES"
164     fi
165     if [ -n "$OSP_IMG_PERSONALITY" ]; then
166         IMG_PERSONALITY="$OSP_IMG_PERSONALITY"
167     fi
168 }
169
170 map_disk0() {
171     blockdev="$1"
172     filesystem_dev_base=$($KPARTX -l -p- $blockdev | \
173                             grep -m 1 -- "-1.*$blockdev" | \
174                             $AWK '{print $1}')
175     if [ -z "$filesystem_dev_base" ]; then
176         log_error "Cannot interpret kpartx output and get partition mapping"
177         exit 1
178     fi
179     $KPARTX -a -p- "$blockdev" > /dev/null
180     filesystem_dev="/dev/mapper/${filesystem_dev_base/%-1/}"
181     if [ ! -b "/dev/mapper/$filesystem_dev_base" ]; then
182         log_error "Can't find kpartx mapped partition:" \
183                                             "/dev/mapper/$filesystem_dev_base"
184         exit 1
185     fi
186     echo "$filesystem_dev"
187 }
188
189 unmap_disk0() {
190     $KPARTX -d -p- "$1"
191 }
192
193 format_disk0() {
194     local device="$1"
195     local image_type="$2"
196
197     declare -A part_id=( ['extdump']="83" ["ntfsdump"]="7" )
198
199     # The -f is needed, because we use an optimal alignment and sfdisk complains
200     # about partitions not ending on clylinder boundary.
201     local sfdisk_cmd="$SFDISK -uS -H 255 -S 63 -f --quiet --Linux --DOS $device"
202
203     $sfdisk_cmd > /dev/null <<EOF
204 2048,,${part_id["$image_type"]},*
205 EOF
206 }
207
208 create_floppy() {
209     local img=$1
210
211     local target=$(mktemp -d)
212     add_cleanup rmdir "$target"
213
214     dd bs=512 count=2880 if=/dev/zero of="$img"
215     mkfs.ext2 -F "$img" > /dev/null
216     mount "$img" "$target" -o loop
217     set | egrep ^snf_export_\\w+= | sed -e 's/^snf_export_/export SNF_IMAGE_/' \
218         > "$target/rules"
219     if [ -n "$UNATTEND" ]; then
220         if [ -f "$UNATTEND" ]; then
221             cat "$UNATTEND" > "$target/unattend.xml"
222         else
223             log_error "Unattend file: \`"$UNATTEND"' does not exist"
224         fi
225     fi
226     umount "$target"
227 }
228
229 get_backend_type() {
230     local id=$1
231
232     if [[ "$id" =~ ^pithos: ]]; then
233         echo "pithos"
234     elif [[ "$id" =~ ^(http|ftp)s?: ]]; then
235         if [ "$network_backend_support" = "yes" ]; then
236             echo "network";
237         else
238             log_error "Retrieving images from the network is not supported."
239             exit 1
240         fi
241     else
242         echo "local";
243     fi
244 }
245
246 # this one is only to be called by create
247 ganeti_os_main() {
248     if [ -z "$OS_API_VERSION" -o "$OS_API_VERSION" = "5" ]; then
249         OS_API_VERSION=5
250         GETOPT_RESULT=`getopt -o o:n:i:b:s: -n '$0' -- "$@"`
251         if [ $? != 0 ] ; then log_error "Terminating..."; exit 1 ; fi
252         get_api5_arguments $GETOPT_RESULT
253     elif [ "$OS_API_VERSION" = "10" -o "$OS_API_VERSION" = "15" ]; then
254         get_api10_arguments
255     elif [ "$OS_API_VERSION" = "20" ]; then
256         get_api20_arguments
257         IMAGE_NAME="$IMG_ID"
258         IMAGE_TYPE="$IMG_FORMAT"
259         BACKEND_TYPE=$(get_backend_type $IMG_ID)
260     else
261         log_error "Unknown OS API VERSION $OS_API_VERSION"
262         exit 1
263     fi
264     
265     if [ -n "$OS_VARIANT" ]; then
266         if [ ! -d "$VARIANTS_DIR" ]; then
267             log_error "OS Variants directory $VARIANTS_DIR doesn't exist"
268             exit 1
269         fi
270         VARIANT_CONFIG="$VARIANTS_DIR/$OS_VARIANT.conf"
271         if [ -f "$VARIANT_CONFIG" ]; then
272             . "$VARIANT_CONFIG"
273         else
274             if grep -qxF "$OS_VARIANT" variants.list; then
275                 log_error "ERROR: instance-image configuration error"
276                 log_error "  Published variant $OS_VARIANT is missing its" \
277                     "config file"
278                 log_error "  Please create $VARIANT_CONFIG or unpublish the" \
279                     "variant"
280                 log_error "  (by removing $OS_VARIANT from variants.list)"
281             else
282                 log_error "Unofficial variant $OS_VARIANT is unsupported"
283                 log_error "Most probably this is a user error, forcing a" \
284                     "wrong name"
285                 log_error "To support this variant please create file" \
286                     "$VARIANT_CONFIG"
287             fi
288             exit 1
289         fi
290     fi
291
292 }
293
294 do_debootstrap() {
295     local target="$1"
296
297     echo "Debootstraping to create a new root filesystem:"
298
299     # Create a policy-rc.d file to deny init script execution
300     mkdir -p "$target/usr/sbin"
301     cat > "$target/usr/sbin/policy-rc.d" <<EOF
302 #!/bin/sh
303 exit 101
304 EOF
305     chmod +x "$target/usr/sbin/policy-rc.d"
306
307     debootstrap --arch $(dpkg --print-architecture) \
308         --include "$HELPER_EXTRA_PKGS" --variant=minbase stable "$target" \
309         "$HELPER_MIRROR" 2>&1 | sed -e 's/^/DEBOOTSTRAP: /g'
310
311     # Save the package list
312     chroot "$target" dpkg-query -W -f "\${Package}\n" > "$HELPER_CACHE_PKGS"
313
314     rm "$target/usr/sbin/policy-rc.d"
315
316     # remove the downloaded debs, as they are no longer needed
317     find "$target/var/cache/apt/archives" -type f -name '*.deb' -print0 | \
318         xargs -r0 rm -f
319
320     local tmp_cache=$(mktemp "$CACHE_FILE.XXXXXX")
321     tar cf "$tmp_cache" --one-file-system -C "$target" . || \
322         { rm "$tmp_cache"; false; }
323     # Overwrite the default cache file. Not the user specified if present.
324     mv -f "$tmp_cache" "$HELPER_CACHE_FILE"
325 }
326
327 report_and_cleanup(){
328
329     local err_file="$1"
330     local fd="$2"
331
332     report_error "$err_file" "$fd"
333     cleanup
334 }
335
336 cleanup() {
337     # if something fails here, it souldn't call cleanup again...
338     trap - EXIT
339
340     if [ ${#CLEANUP[*]} -gt 0 ]; then
341         LAST_ELEMENT=$((${#CLEANUP[*]}-1))
342         REVERSE_INDEXES=$(seq ${LAST_ELEMENT} -1 0)
343         for i in $REVERSE_INDEXES; do
344             # If something fails here, it's better to retry it for a few times
345             # before we give up with an error. This is needed for kpartx when
346             # dealing with ntfs partitions mounted through fuse. umount is not
347             # synchronous and may return while the partition is still busy. A
348             # premature attempt to delete partition mappings through kpartx on
349             # a device that hosts previously mounted ntfs partition may fail
350             # with errors like this one:
351             # `device-mapper: remove ioctl failed: Device or resource busy'
352             # A sensible workaround for this is to wait for a while and then
353             # retry it.
354             local cmd=${CLEANUP[$i]}
355             $cmd || for interval in 0.25 0.5 1 2 4; do
356             echo "Command $cmd failed!"
357             echo "I'll wait for $interval secs and will retry..."
358             sleep $interval
359             $cmd && break
360         done
361         if [ "$?" != "0" ]; then
362             echo "Giving Up..."
363             exit 1;
364         fi
365     done
366   fi
367 }
368
369 trap cleanup EXIT
370
371 DEFAULT_FILE="@sysconfdir@/default/snf-image"
372 if [ -f "$DEFAULT_FILE" ]; then
373     . "$DEFAULT_FILE"
374 fi
375
376 : ${VARIANTS_DIR:="@sysconfdir@/ganeti/snf-image/variants"}
377 : ${IMAGE_DIR:="@localstatedir@/lib/snf-image"}
378 : ${HELPER_DIR:="@HELPER_DIR@"}
379 : ${HELPER_IMG:="@HELPER_IMG@"}
380 : ${HELPER_KERNEL:="@HELPER_KERNEL@"}
381 : ${HELPER_INITRD:="@HELPER_INITRD@"}
382 : ${HELPER_PKG:="@HELPER_DIR@/snf-image-helper.deb"}
383 : ${HELPER_SOFT_TIMEOUT:=20}
384 : ${HELPER_HARD_TIMEOUT:=5}
385 : ${HELPER_USER:="nobody"}
386 : ${HELPER_CACHE_FILE:="@HELPER_DIR@/cache.tar"}
387 : ${HELPER_CACHE_PKGS:="@HELPER_DIR@/packages"}
388 : ${HELPER_EXTRA_PKGS:="linux-image-amd64,e2fsprogs,ntfs-3g,ntfsprogs,xmlstarlet,python,parted,reglookup,chntpw,util-linux"}
389 : ${HELPER_MIRROR:=""}
390 : ${PITHOS_DB:="sqlite:////@localstatedir@/lib/pithos/backend.db"}
391 : ${PITHOS_DATA:="@localstatedir@/lib/pithos/data/"}
392 : ${PROGRESS_MONITOR:="@PROGRESS_MONITOR@"}
393 : ${UNATTEND:="@UNATTEND@"}
394
395 SCRIPT_NAME=$(basename $0)
396
397 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :