#!/bin/bash
#
# diskbenchmark 2013-06-19
# Public Domain

# Configuration section
#

# RAM in MB
ram=8192

# Partition to use, must be bigger than 2 * RAM size
part=/dev/mapper/vg0-test

# Mount point
mnt="/mnt/test"

# Mount options
declare -A moptions
moptions[nilfs2]="-o pp=0"
moptions[reiserfs]="-o barrier=flush"
moptions[xfs]="-o logbufs=8"

# Tar archive to use
archive="/archive/data.tar"

# Number of runs
nruns=10

# Which filesystems to test
usefs="ext2 ext3 ext4 xfs reiserfs reiser4 btrfs jfs nilfs2 zfs"

# End of configuration section
#

if [ ! -x /usr/bin/time ]; then
  echo "/usr/bin/time missing"
  exit 1
fi

count=$((2 * $ram))
sudo umount "$mnt"

fun()
{
  echo "$*"
  $*
}

timefun()
{
  echo "$*"
  /usr/bin/time $*
}

rootfun()
{
  echo "$*"
  sudo $*
}

block()
{
  echo
  echo "$*"
}

#block "Raw speed of partition"
#for i in $(seq 1 $nruns); do
#  rootfun dd if=/dev/zero of="$part" bs=1024k count=$count
#  rootfun dd of=/dev/null if="$part" bs=1024k count=$count
#done

for fs in $usefs; do
  block "Test filesystem $fs"

  opt=
  case $fs in
    xfs)
      opt="-f -q"
      ;;
    btrfs)
      opt=""
      ;;
    reiser4)
      opt="-y"
      ;;
    zfs)
      opt="-m $mnt"
      ;;
    *)
      opt="-q"
      ;;
  esac

  echo "mkfs.$fs $opt $part"
  if [ "$fs" == "zfs" ]; then
    /usr/bin/time -p sudo zpool create $opt barrel "$part"
  else
    /usr/bin/time -p sudo mkfs.$fs $opt "$part"
  fi
  if [ $? != 0 ]; then
    echo "Could not create filesystem $fs"
    exit 1
  fi

  echo "mount ${moptions[$fs]} $part $mnt"
  if [ "$fs" == "zfs" ]; then
    /usr/bin/time -p sudo zfs create barrel/test
  else
    /usr/bin/time -p sudo mount ${moptions[$fs]} "$part" "$mnt"
  fi
  if [ $? != 0 ]; then
    echo "Could not mount filesystem $fs on $mnt"
    exit 1
  fi

  sudo chown $USER "$mnt"
  sudo chmod u+w "$mnt"
  echo -n "Mount options: "
  fgrep "$part" < /proc/mounts

  block "Test block write and read"
  for i in $(seq 1 $nruns); do
    fun dd if=/dev/zero of="$mnt/file" bs=1024k count=$count
    fun dd of=/dev/null if="$mnt/file" bs=1024k count=$count
    echo "rm -f $mnt/file"
    /usr/bin/time -p rm -f "$mnt/file"
  done

  block "Test with bonnie++"
  timefun /usr/sbin/bonnie++ -m $fs -s ${count}m:256k -n 128:1999:0:1 -x $nruns -d "$mnt" -f -q
  sleep 60

  block "Test with tar"
  mkdir "$mnt/ar"
  echo "extract tar archive to $mnt/ar"
  /usr/bin/time -p tar xf "$archive" -C "$mnt/ar"
  echo "Create cpio archive of $mnt/ar"
  /usr/bin/time -p find "$mnt/ar" | cpio -o > "$mnt/ar.cpio"
  echo "rm -rf $mnt/ar"
  /usr/bin/time -p rm -rf "$mnt/ar"

  sync
  if [ "$fs" == "zfs" ]; then
    sudo zfs destroy barrel/test
    sync
    sudo zpool destroy barrel
  else
    sudo umount "$mnt"
  fi
done 
