Add helper-monitor.py program
[snf-image] / snf-image-helper / common.sh
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 RESULT=/dev/ttyS1
20 MONITOR=/dev/ttyS2
21
22 FLOPPY_DEV=/dev/fd0
23 PROGNAME=$(basename $0)
24
25 PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
26
27 # Programs
28 XMLSTARLET=xmlstarlet
29 TUNE2FS=tune2fs
30 RESIZE2FS=resize2fs
31 PARTED=parted
32 SFDISK=sfdisk
33 MKSWAP=mkswap
34 BLKID=blkid
35 BLOCKDEV=blockdev
36 REGLOOKUP=reglookup
37 CHNTPW=chntpw
38
39 CLEANUP=( )
40 ERRORS=( )
41 WARNINGS=( )
42
43 MSG_TYPE_TASK_START="TASK_START"
44 MSG_TYPE_TASK_END="TASK_END"
45
46 STDERR_LINE_SIZE=10
47
48 add_cleanup() {
49     local cmd=""
50     for arg; do cmd+=$(printf "%q " "$arg"); done
51     CLEANUP+=("$cmd")
52 }
53
54 log_error() {
55     ERRORS+=("$@")
56     echo "ERROR: $@" | tee $RESULT >&2
57     exit 1
58 }
59
60 warn() {
61     echo "Warning: $@" >&2
62     echo "WARNING:$@" > "$MONITOR"
63 }
64
65 report_task_start() {
66     echo "$MSG_TYPE_TASK_START:${PROGNAME:2}" > "$MONITOR"
67 }
68
69 report_task_end() {
70     echo "$MSG_TYPE_TASK_END:${PROGNAME:2}" > "$MONITOR"
71 }
72
73 report_error() {
74     if [ ${#ERRORS[*]} -eq 0 ]; then
75         # No error message. Print stderr
76         local lines=$(tail --lines=${STDERR_LINE_SIZE} "$STDERR_FILE" | wc -l)
77         echo -n "STDERR:${lines}:" > "$MONITOR"
78         tail --lines=$lines  "$STDERR_FILE" > "$MONITOR"
79     else
80         echo -n "ERROR:" > "$MONITOR"
81         for line in "${ERRORS[@]}"; do
82             echo "$line" > "$MONITOR"
83         done
84     fi
85 }
86
87 get_base_distro() {
88     local root_dir=$1
89
90     if [ -e "$root_dir/etc/debian_version" ]; then
91         echo "debian"
92     elif [ -e "$root_dir/etc/redhat-release" ]; then
93         echo "redhat"
94     elif [ -e "$root_dir/etc/slackware-version" ]; then
95         echo "slackware"
96     elif [ -e "$root_dir/etc/SuSE-release" ]; then
97         echo "suse"
98     elif [ -e "$root_dir/etc/gentoo-release" ]; then
99         echo "gentoo"
100     else
101         warn "Unknown base distro."
102     fi
103 }
104
105 get_distro() {
106     local root_dir=$1
107
108     if [ -e "$root_dir/etc/debian_version" ]; then
109         distro="debian"
110         if [ -e ${root_dir}/etc/lsb-release ]; then
111             ID=$(grep ^DISTRIB_ID= ${root_dir}/etc/lsb-release | cut -d= -f2)
112             if [ "x$ID" = "xUbuntu" ]; then
113                 distro="ubuntu"
114             fi
115         fi
116         echo "$distro"
117     elif [ -e "$root_dir/etc/fedora-release" ]; then
118         echo "fedora"
119     elif [ -e "$root_dir/etc/centos-release" ]; then
120         echo "centos"
121     elif [ -e "$root_dir/etc/redhat-release" ]; then
122         echo "redhat"
123     elif [ -e "$root_dir/etc/slackware-version" ]; then
124         echo "slackware"
125     elif [ -e "$root_dir/etc/SuSE-release" ]; then
126         echo "suse"
127     elif [ -e "$root_dir/etc/gentoo-release" ]; then
128         echo "gentoo"
129     else
130         warn "Unknown distro."
131     fi
132 }
133
134
135 get_partition_table() {
136     local dev="$1"
137     # If the partition table is gpt then parted will raise an error if the
138     # secondary gpt is not it the end of the disk, and a warning that has to
139     # do with the "Last Usable LBA" entry in gpt.
140     if ! output="$("$PARTED" -s -m "$dev" unit s print | grep -E -v "^(Warning|Error): ")"; then
141         log_error "Unable to read partition table for device \`${dev}'"
142     fi
143
144     echo "$output"
145 }
146
147 get_partition_table_type() {
148     local ptable="$1"
149
150     local dev="$(sed -n 2p <<< "$ptable")"
151     declare -a field
152     IFS=':' read -ra field <<< "$dev"
153
154     echo "${field[5]}"
155 }
156
157 get_partition_count() {
158     local ptable="$1"
159
160     expr $(echo "$ptable" | wc -l) - 2
161 }
162
163 get_partition_by_num() {
164     local ptable="$1"
165     local id="$2"
166
167     grep "^$id:" <<< "$ptable"
168 }
169
170 get_last_partition() {
171     local ptable="$1"
172
173     echo "$ptable" | tail -1
174 }
175
176 is_extended_partition() {
177     local dev="$1"
178     local part_num="$2"
179
180     id=$($SFDISK --print-id "$dev" "$part_num")
181     if [ "$id" = "5" ]; then
182         echo "yes"
183     else
184         echo "no"
185     fi
186 }
187
188 get_extended_partition() {
189     local ptable="$1"
190     local dev="$(echo "$ptable" | sed -n 2p | cut -d':' -f1)"
191
192     tail -n +3 <<< "$ptable" | while read line; do
193         part_num=$(cut -d':' -f1 <<< "$line")
194         if [ $(is_extended_partition "$dev" "$part_num") == "yes" ]; then
195             echo "$line"
196             return 0
197         fi
198     done
199     echo ""
200 }
201
202 get_logical_partitions() {
203     local ptable="$1"
204
205     tail -n +3 <<< "$ptable" | while read line; do
206         part_num=$(cut -d':' -f1 <<< "$line")
207         if [ $part_num -ge 5 ]; then
208             echo "$line"
209         fi
210     done
211
212     return 0
213 }
214
215 get_last_primary_partition() {
216     local ptable="$1"
217     local dev=$(echo "ptable" | sed -n 2p | cut -d':' -f1)
218
219     for i in 4 3 2 1; do
220         if output=$(grep "^$i:" <<< "$ptable"); then
221             echo "$output"
222             return 0
223         fi
224     done
225     echo ""
226 }
227
228 get_partition_to_resize() {
229     local dev="$1"
230
231     table=$(get_partition_table "$dev")
232
233     if [ $(get_partition_count "$table") -eq 0 ]; then
234         return 0
235     fi
236
237     table_type=$(get_partition_table_type "$table")
238     last_part=$(get_last_partition "$table")
239     last_part_num=$(cut -d: -f1 <<< "$last_part")
240
241     if [ "$table_type" == "msdos" -a $last_part_num -gt 4 ]; then
242         extended=$(get_extended_partition "$table")
243         last_primary=$(get_last_primary_partition "$table")
244         ext_num=$(cut -d: -f1 <<< "$extended")
245         prim_num=$(cut -d: -f1 <<< "$last_primary")
246
247         if [ "$ext_num" != "$last_prim_num" ]; then
248             echo "$last_prim_num"
249         else
250             echo "$last_part_num"
251         fi
252     else
253         echo "$last_part_num"
254     fi
255 }
256
257 create_partition() {
258     local device="$1"
259     local part="$2"
260     local ptype="$3"
261
262     declare -a fields
263     IFS=":;" read -ra fields <<< "$part"
264     local id="${fields[0]}"
265     local start="${fields[1]}"
266     local end="${fields[2]}"
267     local size="${fields[3]}"
268     local fs="${fields[4]}"
269     local name="${fields[5]}"
270     local flags="${fields[6]//,/ }"
271
272     $PARTED -s -m -- $device mkpart "$ptype" $fs "$start" "$end"
273     for flag in $flags; do
274         $PARTED -s -m $device set "$id" "$flag" on
275     done
276 }
277
278 enlarge_partition() {
279     local device="$1"
280     local part="$2"
281     local ptype="$3"
282     local new_end="$4"
283
284     if [ -z "$new_end" ]; then
285         new_end=$(cut -d: -f 3 <<< "$(get_last_free_sector "$device")")
286     fi
287
288     declare -a fields
289     IFS=":;" read -ra fields <<< "$part"
290     fields[2]="$new_end"
291
292     local new_part=""
293     for ((i = 0; i < ${#fields[*]}; i = i + 1)); do
294         new_part="$new_part":"${fields[$i]}"
295     done
296     new_part=${new_part:1}
297
298     # If this is an extended partition, removing it will also remove the
299     # logical partitions it contains. We need to save them for later.
300     if [ "$ptype" = "extended" ]; then
301         local table="$(get_partition_table "$device")"
302         local logical="$(get_logical_partitions "$table")"
303     fi
304
305     id=${fields[0]}
306     $PARTED -s -m "$device" rm "$id"
307     create_partition "$device" "$new_part" "$ptype"
308
309     if [ "$ptype" = "extended" ]; then
310         # Recreate logical partitions
311         echo "$logical" | while read logical_part; do
312             create_partition "$device" "$logical_part" "logical"
313         done
314     fi
315 }
316
317 get_last_free_sector() {
318     local dev="$1"
319     local unit="$2"
320
321     if [ -n "$unit" ]; then
322         unit="unit $unit"
323     fi
324
325     local last_line="$("$PARTED" -s -m "$dev" "$unit" print free | tail -1)"
326     local ptype="$(cut -d: -f 5 <<< "$last_line")"
327
328     if [ "$ptype" = "free;" ]; then
329         echo "$last_line"
330     fi
331 }
332
333 cleanup() {
334     # if something fails here, it shouldn't call cleanup again...
335     trap - EXIT
336
337     if [ ${#CLEANUP[*]} -gt 0 ]; then
338         LAST_ELEMENT=$((${#CLEANUP[*]}-1))
339         REVERSE_INDEXES=$(seq ${LAST_ELEMENT} -1 0)
340         for i in $REVERSE_INDEXES; do
341             # If something fails here, it's better to retry it for a few times
342             # before we give up with an error. This is needed for kpartx when
343             # dealing with ntfs partitions mounted through fuse. umount is not
344             # synchronous and may return while the partition is still busy. A
345             # premature attempt to delete partition mappings through kpartx on
346             # a device that hosts previously mounted ntfs partition may fail
347             # with a `device-mapper: remove ioctl failed: Device or resource
348             # busy' error. A sensible workaround for this is to wait for a
349             # while and then try again.
350             local cmd=${CLEANUP[$i]}
351             $cmd || for interval in 0.25 0.5 1 2 4; do
352             echo "Command $cmd failed!"
353             echo "I'll wait for $interval secs and will retry..."
354             sleep $interval
355             $cmd && break
356         done
357         if [ "$?" != "0" ]; then
358             echo "Giving Up..."
359             exit 1;
360         fi
361     done
362   fi
363 }
364
365 task_cleanup() {
366     rc=$?
367
368     if [ $rc -eq 0 ]; then
369        report_task_end
370     else
371        report_error
372     fi
373
374     cleanup
375 }
376
377 check_if_excluded() {
378     local name="$(tr [a-z] [A-Z] <<< ${PROGNAME:2})"
379     local exclude="SNF_IMAGE_PROPERTY_EXCLUDE_TASK_${name}"
380     if [ -n "${!exclude}" ]; then
381         warn "Task ${PROGNAME:2} was excluded and will not run."
382         exit 0
383     fi
384
385     return 0
386 }
387
388 trap cleanup EXIT
389 set -o pipefail
390
391 STDERR_FILE=$(mktemp)
392 add_cleanup rm -f "$STDERR_FILE"
393 exec 2> >(tee -a "$STDERR_FILE" >&2)
394
395 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :