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