osbuilder: fix loop devices manipulation in image-builder.sh

Improve image-builder.sh to avoid the sporadic failures observed during
the CI builds of images. Also, some cosmetic changes to indentation.

Fixes: #172

Signed-off-by: Marco Vedovati <mvedovati@suse.com>
This commit is contained in:
Marco Vedovati 2018-09-20 13:06:41 +02:00
parent d5087c07ca
commit 4a2fdee972

View File

@ -1,4 +1,4 @@
#!/bin/bash
#!/usr/bin/env bash
#
# Copyright (c) 2017 Intel Corporation
#
@ -63,13 +63,15 @@ do
h) usage ;;
o) IMAGE="${OPTARG}" ;;
r) ROOT_FREE_SPACE="${OPTARG}" ;;
s) IMG_SIZE=${OPTARG}
s) {
IMG_SIZE=${OPTARG}
if [ ${IMG_SIZE} -le 0 ]; then
die "Image size has to be greater than 0 MB."
fi
if [ ${IMG_SIZE} -gt ${MAX_IMG_SIZE_MB} ]; then
die "Image size should not be greater than ${MAX_IMG_SIZE_MB} MB."
fi
}
;;
f) FS_TYPE="${OPTARG}" ;;
esac
@ -159,16 +161,42 @@ calculate_img_size()
}
# Cleanup
cleanup()
unmount()
{
sync
umount -l ${MOUNT_DIR}
rmdir ${MOUNT_DIR}
fsck -D -y "${DEVICE}p1"
losetup -d "${DEVICE}"
}
detach()
{
losetup -d "${DEVICE}"
# From `man losetup` about -d option:
# Note that since Linux v3.7 kernel uses "lazy device destruction".
# The detach operation does not return EBUSY error anymore if
# device is actively used by system, but it is marked by autoclear
# flag and destroyed later
info "Waiting for ${DEVICE} to detach"
local i=0
local max_tries=5
while [[ "$i" < "$max_tries" ]]; do
sleep 1
# If either the 'p1' partition has disappeared or partprobe failed, then
# the loop device should be correctly detached
if ! [ -b "${DEVICE}p1" ] || ! partprobe -s ${DEVICE}; then
break
fi
((i+=1))
echo -n "."
done
[[ "$i" == "$max_tries" ]] && die "Cannot detach ${DEVICE}"
info "detached"
}
create_rootfs_disk()
{
ATTEMPT_NUM=$(($ATTEMPT_NUM+1))
@ -199,12 +227,22 @@ create_rootfs_disk()
DEVICE=$(losetup -P -f --show "${IMAGE}")
#Refresh partition table
partprobe "${DEVICE}"
partprobe -s "${DEVICE}"
# Poll for the block device p1
local i=0
local max_tries=5
while [[ "$i" < "$max_tries" ]]; do
[ -b "${DEVICE}p1" ] && break
((i+=1))
echo -n "."
sleep 1
done
[[ "$i" == "$max_tries" ]] && die "File ${DEVICE}p1 is not a block device"
MOUNT_DIR=$(mktemp -d osbuilder-mount-dir.XXXX)
info "Formating Image using ext4 format"
info "Formatting Image using ext4 filesystem"
mkfs.ext4 -q -F -b "${BLOCK_SIZE}" "${DEVICE}p1"
OK "Image formated"
OK "Image formatted"
info "Mounting root partition"
mount "${DEVICE}p1" "${MOUNT_DIR}"
@ -222,10 +260,11 @@ create_rootfs_disk()
if [ $ROOTFS_SIZE -gt $AVAIL_DISK ]; then
# Increase the size but remain aligned to 128
MEM_BOUNDARY=$(($MEM_BOUNDARY+128))
rm -f ${IMAGE}
OLD_IMG_SIZE=${IMG_SIZE}
unset IMG_SIZE
cleanup
unmount
detach
rm -f ${IMAGE}
create_rootfs_disk
fi
}
@ -237,6 +276,9 @@ info "Copying content from rootfs to root partition"
cp -a "${ROOTFS}"/* ${MOUNT_DIR}
OK "rootfs copied"
cleanup
unmount
# Optimize
fsck.ext4 -D -y "${DEVICE}p1"
detach
info "Image created. Virtual size: ${IMG_SIZE}MB."