]> arthur.barton.de Git - bup.git/blob - cmd-index.py
1999c9d490539b9a84c2cb3d8ed9f5db763a5f34
[bup.git] / cmd-index.py
1 #!/usr/bin/env python2.5
2 import sys, re, errno, stat, tempfile, struct, mmap
3 import options
4 from helpers import *
5
6 INDEX_SIG = '!IIIIIQ20sH'
7 ENTLEN = struct.calcsize(INDEX_SIG)
8
9 IX_EXISTS = 0x8000
10 IX_HASHVALID = 0x4000
11
12
13 class OsFile:
14     def __init__(self, path):
15         self.fd = None
16         self.fd = os.open(path, os.O_RDONLY|os.O_LARGEFILE|os.O_NOFOLLOW)
17         #self.st = os.fstat(self.fd)
18         
19     def __del__(self):
20         if self.fd:
21             fd = self.fd
22             self.fd = None
23             os.close(fd)
24
25     def fchdir(self):
26         os.fchdir(self.fd)
27
28
29 class IxEntry:
30     def __init__(self, name, m, ofs):
31         self._m = m
32         self._ofs = ofs
33         self.name = str(name)
34         (self.dev, self.ctime, self.mtime, self.uid, self.gid,
35          self.size, self.sha,
36          self.flags) = struct.unpack(INDEX_SIG, buffer(m, ofs, ENTLEN))
37
38     def __repr__(self):
39         return ("(%s,0x%04x,%d,%d,%d,%d,%d,0x%04x)" 
40                 % (self.name, self.dev,
41                    self.ctime, self.mtime, self.uid, self.gid,
42                    self.size, self.flags))
43
44     def pack(self):
45         return struct.pack(INDEX_SIG, self.dev, self.ctime, self.mtime,
46                            self.uid, self.gid, self.size, self.sha,
47                            self.flags)
48
49     def repack(self):
50         self._m[self._ofs:self._ofs+ENTLEN] = self.pack()
51
52     def from_stat(self, st):
53         old = (self.dev, self.ctime, self.mtime,
54                self.uid, self.gid, self.size)
55         new = (st.st_dev, int(st.st_ctime), int(st.st_mtime),
56                st.st_uid, st.st_gid, st.st_size)
57         self.dev = st.st_dev
58         self.ctime = int(st.st_ctime)
59         self.mtime = int(st.st_mtime)
60         self.uid = st.st_uid
61         self.gid = st.st_gid
62         self.size = st.st_size
63         self.flags |= IX_EXISTS
64         if old != new:
65             self.flags &= ~IX_HASHVALID
66             return 1  # dirty
67         else:
68             return 0  # not dirty
69             
70
71 class IndexReader:
72     def __init__(self, filename):
73         self.filename = filename
74         self.m = ''
75         self.writable = False
76         f = None
77         try:
78             f = open(filename, 'r+')
79         except IOError, e:
80             if e.errno == errno.ENOENT:
81                 pass
82             else:
83                 raise
84         if f:
85             st = os.fstat(f.fileno())
86         if f and st.st_size:
87             self.m = mmap.mmap(f.fileno(), 0,
88                                mmap.MAP_SHARED, mmap.PROT_READ|mmap.PROT_WRITE)
89             f.close()  # map will persist beyond file close
90             self.writable = True
91
92     def __iter__(self):
93         ofs = 0
94         while ofs < len(self.m):
95             eon = self.m.find('\0', ofs)
96             assert(eon >= 0)
97             yield IxEntry(buffer(self.m, ofs, eon-ofs),
98                           self.m, eon+1)
99             ofs = eon + 1 + ENTLEN
100
101     def save(self):
102         if self.writable:
103             self.m.flush()
104
105
106 def ix_encode(st, sha, flags):
107     return struct.pack(INDEX_SIG, st.st_dev, int(st.st_ctime),
108                        int(st.st_mtime), st.st_uid, st.st_gid,
109                        st.st_size, sha, flags)
110
111
112 class IndexWriter:
113     def __init__(self, filename):
114         self.f = None
115         self.lastfile = None
116         self.filename = None
117         self.filename = filename = os.path.realpath(filename)
118         (dir,name) = os.path.split(filename)
119         (ffd,self.tmpname) = tempfile.mkstemp('.tmp', filename, dir)
120         self.f = os.fdopen(ffd, 'wb', 65536)
121
122     def __del__(self):
123         self.abort()
124
125     def abort(self):
126         f = self.f
127         self.f = None
128         if f:
129             f.close()
130             os.unlink(self.tmpname)
131
132     def close(self):
133         f = self.f
134         self.f = None
135         if f:
136             f.close()
137             os.rename(self.tmpname, self.filename)
138
139     def add(self, name, st):
140         #log('ADDING %r\n' % name)
141         if self.lastfile:
142             assert(cmp(self.lastfile, name) > 0) # reverse order only
143         self.lastfile = name
144         data = name + '\0' + ix_encode(st, '\0'*20, IX_EXISTS|IX_HASHVALID)
145         self.f.write(data)
146
147     def add_ixentry(self, e):
148         if self.lastfile:
149             assert(cmp(self.lastfile, e.name) > 0) # reverse order only
150         self.lastfile = e.name
151         data = e.name + '\0' + e.pack()
152         self.f.write(data)
153
154     def new_reader(self):
155         self.f.flush()
156         return IndexReader(self.tmpname)
157
158
159 saved_errors = []
160 def add_error(e):
161     saved_errors.append(e)
162     log('\n%s\n' % e)
163
164
165 # the use of fchdir() and lstat() are for two reasons:
166 #  - help out the kernel by not making it repeatedly look up the absolute path
167 #  - avoid race conditions caused by doing listdir() on a changing symlink
168 def handle_path(ri, wi, dir, name, pst):
169     dirty = 0
170     path = dir + name
171     #log('handle_path(%r,%r)\n' % (dir, name))
172     if stat.S_ISDIR(pst.st_mode):
173         if opt.verbose == 1: # log dirs only
174             sys.stdout.write('%s\n' % path)
175             sys.stdout.flush()
176         try:
177             OsFile(name).fchdir()
178         except OSError, e:
179             add_error(Exception('in %s: %s' % (dir, str(e))))
180             return
181         try:
182             try:
183                 ld = os.listdir('.')
184                 #log('* %r: %r\n' % (name, ld))
185             except OSError, e:
186                 add_error(Exception('in %s: %s' % (path, str(e))))
187                 return
188             lds = []
189             for p in ld:
190                 try:
191                     st = os.lstat(p)
192                 except OSError, e:
193                     add_error(Exception('in %s: %s' % (path, str(e))))
194                     continue
195                 if stat.S_ISDIR(st.st_mode):
196                     p += '/'
197                 lds.append((p, st))
198             for p,st in reversed(sorted(lds)):
199                 dirty += handle_path(ri, wi, path, p, st)
200         finally:
201             os.chdir('..')
202     #log('endloop: ri.cur:%r path:%r\n' % (ri.cur.name, path))
203     while ri.cur and ri.cur.name > path:
204         #log('ricur:%r path:%r\n' % (ri.cur, path))
205         if dir and ri.cur.name.startswith(dir):
206             #log('    --- deleting\n')
207             ri.cur.flags &= ~(IX_EXISTS | IX_HASHVALID)
208             ri.cur.repack()
209             dirty += 1
210         ri.next()
211     if ri.cur and ri.cur.name == path:
212         dirty += ri.cur.from_stat(pst)
213         if dirty:
214             #log('   --- updating %r\n' % path)
215             ri.cur.repack()
216         ri.next()
217     else:
218         wi.add(path, pst)
219         dirty += 1
220     if opt.verbose > 1:  # all files, not just dirs
221         sys.stdout.write('%s\n' % path)
222         sys.stdout.flush()
223     return dirty
224
225
226 def _next(i):
227     try:
228         return i.next()
229     except StopIteration:
230         return None
231
232
233 def merge_indexes(out, r1, r2):
234     i1 = iter(r1)
235     i2 = iter(r2)
236
237     e1 = _next(i1)
238     e2 = _next(i2)
239     while e1 or e2:
240         if e1 and (not e2 or e2.name < e1.name):
241             if e1.flags & IX_EXISTS:
242                 out.add_ixentry(e1)
243             e1 = _next(i1)
244         elif e2 and (not e1 or e1.name < e2.name):
245             if e2.flags & IX_EXISTS:
246                 out.add_ixentry(e2)
247             e2 = _next(i2)
248         elif e1.name == e2.name:
249             assert(0)  # duplicate name? should never happen anymore.
250             if e2.flags & IX_EXISTS:
251                 out.add_ixentry(e2)
252             e1 = _next(i1)
253             e2 = _next(i2)
254
255
256 class MergeGetter:
257     def __init__(self, l):
258         self.i = iter(l)
259         self.cur = None
260         self.next()
261
262     def next(self):
263         try:
264             self.cur = self.i.next()
265         except StopIteration:
266             self.cur = None
267         return self.cur
268
269
270 def update_index(path):
271     ri = IndexReader('index')
272     wi = IndexWriter('index')
273     rpath = os.path.realpath(path)
274     st = os.lstat(rpath)
275     f = OsFile('.')
276     if rpath[-1] == '/':
277         rpath = rpath[:-1]
278     (dir, name) = os.path.split(rpath)
279     if dir and dir[-1] != '/':
280         dir += '/'
281     if stat.S_ISDIR(st.st_mode) and rpath[-1] != '/':
282         name += '/'
283     rig = MergeGetter(ri)
284     OsFile(dir).fchdir()
285     dirty = handle_path(rig, wi, dir, name, st)
286
287     # make sure all the parents of the updated path exist and are invalidated
288     # if appropriate.
289     while 1:
290         (rpath, junk) = os.path.split(rpath)
291         if not rpath:
292             break
293         elif rpath == '/':
294             p = rpath
295         else:
296             p = rpath + '/'
297         while rig.cur and rig.cur.name > p:
298             #log('FINISHING: %r path=%r d=%r\n' % (rig.cur.name, p, dirty))
299             rig.next()
300         if rig.cur and rig.cur.name == p:
301             if dirty:
302                 rig.cur.flags &= ~IX_HASHVALID
303                 rig.cur.repack()
304         else:
305             wi.add(p, os.lstat(p))
306         if p == '/':
307             break
308     
309     f.fchdir()
310     ri.save()
311     mi = IndexWriter('index')
312     merge_indexes(mi, ri, wi.new_reader())
313     wi.abort()
314     mi.close()
315
316
317 optspec = """
318 bup index [-v] <filenames...>
319 --
320 v,verbose  increase log output (can be used more than once)
321 """
322 o = options.Options('bup index', optspec)
323 (opt, flags, extra) = o.parse(sys.argv[1:])
324
325 for path in extra:
326     update_index(path)
327
328 for ent in IndexReader('index'):
329     if not ent.flags & IX_EXISTS:
330         print 'D ' + ent.name
331     elif not ent.flags & IX_HASHVALID:
332         print 'M ' + ent.name
333     else:
334         print '  ' + ent.name
335     #print repr(ent)
336
337 if saved_errors:
338     log('WARNING: %d errors encountered.\n' % len(saved_errors))
339     exit(1)