cow 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/bin/sh
  2. set -e
  3. imgloop=
  4. tmpfile=
  5. tmploop=
  6. dmname=
  7. cowlink=
  8. function cleanup () {
  9. set +e
  10. [ -n "$cowlink" ] && rm $cowlink
  11. [ -n "$dmname" ] && dmsetup remove $dmname
  12. [ -n "$tmploop" ] && losetup -d $tmploop
  13. [ -n "$tmpfile" ] && rm $tmpfile
  14. [ -n "$imgloop" ] && losetup -d $imgloop
  15. }
  16. trap cleanup EXIT
  17. imgfile=$1 ; shift
  18. command=$1 ; shift
  19. if [ -z "$imgfile" -o -z "$command" ] ; then
  20. echo Syntax: $0 /path/to/image/file command [args..]
  21. exit 1
  22. fi
  23. # Set up image loop device
  24. x=`losetup -f` ; losetup -r $x $imgfile ; imgloop=$x
  25. # Create temporary file and set up temporary loop device
  26. tmpfile=`mktemp $imgfile.XXXXXXXXXX`
  27. truncate -r $imgfile $tmpfile
  28. x=`losetup -f` ; losetup $x $tmpfile ; tmploop=$x
  29. # Create snapshot device
  30. imgsize=`blockdev --getsz $imgloop`
  31. x=`basename $imgfile` ; echo 0 $imgsize snapshot $imgloop $tmploop N 16 | \
  32. dmsetup create $x ; dmname=$x
  33. chown --reference=$imgfile /dev/mapper/$dmname
  34. chmod --reference=$imgfile /dev/mapper/$dmname
  35. # Create symlink
  36. x=$imgfile.cow ; ln -s /dev/mapper/$dmname $x ; cowlink=$x
  37. # Wait until killed
  38. echo "Created $cowlink"
  39. $command "$@" $cowlink