1 | #!/usr/bin/env python2.5 |
---|
2 | |
---|
3 | import sys |
---|
4 | import os |
---|
5 | from subprocess import call |
---|
6 | |
---|
7 | def losetup(source, offset=0): |
---|
8 | # XXX we avoid colliding with other instances of ourself, |
---|
9 | # but when it comes to other loop-device users we just |
---|
10 | # pick a range things don't seem to use and hope... |
---|
11 | lockfilename = '/tmp/losetup.lock' |
---|
12 | os.close(os.open(lockfilename, os.O_CREAT+os.O_EXCL)) #lock |
---|
13 | try: |
---|
14 | loopdevice = None |
---|
15 | for i in xrange(32,60): # totally arbitrary, just looks to be unused on black-mesa |
---|
16 | filename = '/dev/loop%d'%i |
---|
17 | if 0 == len(file(filename).read(1)): |
---|
18 | loopdevice = filename # it's empty |
---|
19 | break |
---|
20 | if loopdevice is not None: |
---|
21 | call(['losetup', '-o', str(offset), loopdevice, source]) |
---|
22 | else: |
---|
23 | raise RuntimeError('out of loop devices for copying VM image: too many at once?') |
---|
24 | finally: |
---|
25 | os.unlink(lockfilename) #unlock |
---|
26 | return loopdevice |
---|
27 | |
---|
28 | def main(*argv): |
---|
29 | args = argv[1:] |
---|
30 | os.environ['PATH'] = '/usr/sbin:/usr/bin:/sbin:/bin' |
---|
31 | if not (1 <= len(args) <= 2): |
---|
32 | print >>sys.stderr, 'usage: %s sourcedevice [offset]' % argv[0] |
---|
33 | print >>sys.stderr, 'prints resulting loopback device; don\'t forget to losetup -d' |
---|
34 | return 2 |
---|
35 | print losetup(*args) |
---|
36 | return 0 |
---|
37 | |
---|
38 | if __name__ == '__main__': |
---|
39 | sys.exit(main(*sys.argv)) |
---|