Ticket #1277: copy_mutable_shares.py

File copy_mutable_shares.py, 2.3 KB (added by davidsarah, at 2010-12-12T01:40:01Z)

Script to copy mutable shares, with changes from kevan's review.

Line 
1import sys, os, shutil, exceptions
2
3# from allmydata.storage.mutable import MutableShareFile
4# MUTABLE_MAGIC = MutableShareFile.MAGIC
5MUTABLE_MAGIC = "Tahoe mutable container v1\n" + "\x75\x09\x44\x03\x8e"
6
7# from allmydata.util.fileutil import make_dirs
8def make_dirs(dirname, mode=0777):
9    """
10    An idempotent version of os.makedirs().  If the dir already exists, do
11    nothing and return without raising an exception.  If this call creates the
12    dir, return without raising an exception.  If there is an error that
13    prevents creation or if the directory gets deleted after make_dirs() creates
14    it and before make_dirs() checks that it exists, raise an exception.
15    """
16    tx = None
17    try:
18        os.makedirs(dirname, mode)
19    except OSError, x:
20        tx = x
21
22    if not os.path.isdir(dirname):
23        if tx:
24            raise tx
25        raise exceptions.IOError, "unknown error prevented creation of directory, or deleted the directory immediately after creation: %s" % dirname # careful not to construct an IOError with a 2-tuple, as that has a special meaning...
26
27
28def copy_mutable_shares(src_base, dest_base, out=sys.stdout, err=sys.stderr):
29    src_shares = os.path.join(src_base, "storage", "shares")
30    if not os.path.exists(src_shares):
31        print >>err, "Shares directory '%s' does not exist." % (src_shares,)
32        return 1
33
34    for short_si in os.listdir(src_shares):
35        src_short = os.path.join(src_shares, short_si)
36        for si in os.listdir(src_short):
37            src_si = os.path.join(src_short, si)
38            files = os.listdir(src_si)
39            if files:
40                f = open(os.path.join(src_si, files[0]), "rb")
41                prefix = f.read(32)
42                f.close()
43                if prefix == MUTABLE_MAGIC:
44                    print >>out, "Copying <%s>..." % (si,),
45                    dest_si = os.path.join(dest_base, "storage", "shares", short_si, si)
46                    make_dirs(dest_si)
47                    for file in files:
48                        shutil.copy2(os.path.join(src_si, file), dest_si)
49                    print >>out, "done"
50
51    return 0
52
53if __name__ == "__main__":
54    if len(sys.argv) != 3:
55        print >>sys.stderr, "Usage: python copy_mutable_shares.py SRC_BASEDIR DEST_BASEDIR"
56        sys.exit(1)
57
58    sys.exit(copy_mutable_shares(sys.argv[1], sys.argv[2]))