1 import os, stat, struct, tempfile
3 from bup.helpers import *
8 INDEX_HDR = 'BUPI\0\0\0\4'
10 # Time values are handled as integer nanoseconds since the epoch in
11 # memory, but are written as xstat/metadata timespecs. This behavior
12 # matches the existing metadata/xstat/.bupm code.
14 # Record times (mtime, ctime, atime) as xstat/metadata timespecs, and
15 # store all of the times in the index so they won't interfere with the
16 # forthcoming metadata cache.
17 INDEX_SIG = '!QQQqQqQqQIIQII20sHII'
19 ENTLEN = struct.calcsize(INDEX_SIG)
21 FOOTLEN = struct.calcsize(FOOTER_SIG)
23 IX_EXISTS = 0x8000 # file exists on filesystem
24 IX_HASHVALID = 0x4000 # the stored sha1 matches the filesystem
25 IX_SHAMISSING = 0x2000 # the stored sha1 object doesn't seem to exist
27 class Error(Exception):
32 def __init__(self, ename, parent):
39 (ofs,n) = (f.tell(), len(self.list))
41 count = len(self.list)
42 #log('popping %r with %d entries\n'
43 # % (''.join(self.ename), count))
47 self.parent.count += count + self.count
51 def _golevel(level, f, ename, newentry, tmax):
52 # close nodes back up the tree
54 while ename[:len(level.ename)] != level.ename:
55 n = BlankNewEntry(level.ename[-1], tmax)
57 (n.children_ofs,n.children_n) = level.write(f)
58 level.parent.list.append(n)
61 # create nodes down the tree
62 while len(level.ename) < len(ename):
63 level = Level(ename[:len(level.ename)+1], level)
65 # are we in precisely the right place?
66 assert(ename == level.ename)
67 n = newentry or BlankNewEntry(ename and level.ename[-1] or None, tmax)
68 (n.children_ofs,n.children_n) = level.write(f)
70 level.parent.list.append(n)
77 def __init__(self, basename, name, tmax):
78 self.basename = str(basename)
85 return ("(%s,0x%04x,%d,%d,%d,%d,%d,%d,%d,%d,%s/%s,0x%04x,0x%08x/%d)"
86 % (self.name, self.dev, self.ino, self.nlink,
87 self.ctime, self.mtime, self.atime, self.uid, self.gid,
88 self.size, self.mode, self.gitmode,
89 self.flags, self.children_ofs, self.children_n))
93 ctime = xstat.nsecs_to_timespec(self.ctime)
94 mtime = xstat.nsecs_to_timespec(self.mtime)
95 atime = xstat.nsecs_to_timespec(self.atime)
96 return struct.pack(INDEX_SIG,
97 self.dev, self.ino, self.nlink,
101 self.uid, self.gid, self.size, self.mode,
102 self.gitmode, self.sha, self.flags,
103 self.children_ofs, self.children_n)
104 except (DeprecationWarning, struct.error), e:
105 log('pack error: %s (%r)\n' % (e, self))
108 def from_stat(self, st, tstart):
109 old = (self.dev, self.ino, self.nlink, self.ctime, self.mtime,
110 self.uid, self.gid, self.size, self.flags & IX_EXISTS)
111 new = (st.st_dev, st.st_ino, st.st_nlink, st.st_ctime, st.st_mtime,
112 st.st_uid, st.st_gid, st.st_size, IX_EXISTS)
115 self.nlink = st.st_nlink
116 self.ctime = st.st_ctime
117 self.mtime = st.st_mtime
118 self.atime = st.st_atime
121 self.size = st.st_size
122 self.mode = st.st_mode
123 self.flags |= IX_EXISTS
124 # Check that the ctime's "second" is at or after tstart's.
125 ctime_sec_in_ns = xstat.fstime_floor_secs(st.st_ctime) * 10**9
126 if ctime_sec_in_ns >= tstart or old != new \
127 or self.sha == EMPTY_SHA or not self.gitmode:
133 self.uid += 0x100000000
135 self.gid += 0x100000000
136 assert(self.uid >= 0)
137 assert(self.gid >= 0)
138 self.mtime = self._fixup_time(self.mtime)
139 self.ctime = self._fixup_time(self.ctime)
141 def _fixup_time(self, t):
142 if self.tmax != None and t > self.tmax:
148 f = IX_HASHVALID|IX_EXISTS
149 return (self.flags & f) == f
151 def invalidate(self):
152 self.flags &= ~IX_HASHVALID
154 def validate(self, gitmode, sha):
157 assert(gitmode+0 == gitmode)
158 self.gitmode = gitmode
160 self.flags |= IX_HASHVALID|IX_EXISTS
163 return not self.is_deleted()
165 def sha_missing(self):
166 return (self.flags & IX_SHAMISSING) or not (self.flags & IX_HASHVALID)
168 def is_deleted(self):
169 return (self.flags & IX_EXISTS) == 0
171 def set_deleted(self):
172 if self.flags & IX_EXISTS:
173 self.flags &= ~(IX_EXISTS | IX_HASHVALID)
176 return not self.is_fake()
179 return not self.ctime
182 return (cmp(b.name, a.name)
183 or cmp(a.is_valid(), b.is_valid())
184 or cmp(a.is_fake(), b.is_fake()))
187 f.write(self.basename + '\0' + self.packed())
190 class NewEntry(Entry):
191 def __init__(self, basename, name, tmax, dev, ino, nlink,
193 uid, gid, size, mode, gitmode, sha, flags,
194 children_ofs, children_n):
195 Entry.__init__(self, basename, name, tmax)
196 (self.dev, self.ino, self.nlink, self.ctime, self.mtime, self.atime,
197 self.uid, self.gid, self.size, self.mode, self.gitmode, self.sha,
198 self.flags, self.children_ofs, self.children_n
199 ) = (dev, ino, nlink, ctime, mtime, atime, uid, gid,
200 size, mode, gitmode, sha, flags, children_ofs, children_n)
204 class BlankNewEntry(NewEntry):
205 def __init__(self, basename, tmax):
206 NewEntry.__init__(self, basename, basename, tmax,
207 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
208 0, EMPTY_SHA, 0, 0, 0)
211 class ExistingEntry(Entry):
212 def __init__(self, parent, basename, name, m, ofs):
213 Entry.__init__(self, basename, name, None)
217 (self.dev, self.ino, self.nlink,
218 self.ctime, ctime_ns, self.mtime, mtime_ns, self.atime, atime_ns,
219 self.uid, self.gid, self.size, self.mode, self.gitmode, self.sha,
220 self.flags, self.children_ofs, self.children_n
221 ) = struct.unpack(INDEX_SIG, str(buffer(m, ofs, ENTLEN)))
222 self.atime = xstat.timespec_to_nsecs((self.atime, atime_ns))
223 self.mtime = xstat.timespec_to_nsecs((self.mtime, mtime_ns))
224 self.ctime = xstat.timespec_to_nsecs((self.ctime, ctime_ns))
226 # effectively, we don't bother messing with IX_SHAMISSING if
227 # not IX_HASHVALID, since it's redundant, and repacking is more
228 # expensive than not repacking.
229 # This is implemented by having sha_missing() check IX_HASHVALID too.
230 def set_sha_missing(self, val):
232 oldval = self.sha_missing() and 1 or 0
234 flag = val and IX_SHAMISSING or 0
235 newflags = (self.flags & (~IX_SHAMISSING)) | flag
236 self.flags = newflags
239 def unset_sha_missing(self, flag):
240 if self.flags & IX_SHAMISSING:
241 self.flags &= ~IX_SHAMISSING
245 self._m[self._ofs:self._ofs+ENTLEN] = self.packed()
246 if self.parent and not self.is_valid():
247 self.parent.invalidate()
250 def iter(self, name=None, wantrecurse=None):
252 if dname and not dname.endswith('/'):
254 ofs = self.children_ofs
255 assert(ofs <= len(self._m))
256 assert(self.children_n < 1000000)
257 for i in xrange(self.children_n):
258 eon = self._m.find('\0', ofs)
262 basename = str(buffer(self._m, ofs, eon-ofs))
263 child = ExistingEntry(self, basename, self.name + basename,
266 or child.name.startswith(dname)
267 or child.name.endswith('/') and dname.startswith(child.name)):
268 if not wantrecurse or wantrecurse(child):
269 for e in child.iter(name=name, wantrecurse=wantrecurse):
271 if not name or child.name == name or child.name.startswith(dname):
273 ofs = eon + 1 + ENTLEN
280 def __init__(self, filename):
281 self.filename = filename
283 self.writable = False
287 f = open(filename, 'r+')
289 if e.errno == errno.ENOENT:
294 b = f.read(len(INDEX_HDR))
296 log('warning: %s: header: expected %r, got %r\n'
297 % (filename, INDEX_HDR, b))
299 st = os.fstat(f.fileno())
301 self.m = mmap_readwrite(f)
303 self.count = struct.unpack(FOOTER_SIG,
304 str(buffer(self.m, st.st_size-FOOTLEN, FOOTLEN)))[0]
310 return int(self.count)
312 def forward_iter(self):
314 while ofs+ENTLEN <= len(self.m)-FOOTLEN:
315 eon = self.m.find('\0', ofs)
319 basename = str(buffer(self.m, ofs, eon-ofs))
320 yield ExistingEntry(None, basename, basename, self.m, eon+1)
321 ofs = eon + 1 + ENTLEN
323 def iter(self, name=None, wantrecurse=None):
324 if len(self.m) > len(INDEX_HDR)+ENTLEN:
326 if dname and not dname.endswith('/'):
328 root = ExistingEntry(None, '/', '/',
329 self.m, len(self.m)-FOOTLEN-ENTLEN)
330 for sub in root.iter(name=name, wantrecurse=wantrecurse):
332 if not dname or dname == root.name:
342 if self.writable and self.m:
347 if self.writable and self.m:
350 self.writable = False
352 def filter(self, prefixes, wantrecurse=None):
353 for (rp, path) in reduce_paths(prefixes):
354 for e in self.iter(rp, wantrecurse=wantrecurse):
355 assert(e.name.startswith(rp))
356 name = path + e.name[len(rp):]
360 # FIXME: this function isn't very generic, because it splits the filename
361 # in an odd way and depends on a terminating '/' to indicate directories.
363 """Split a path into a list of elements of the file system hierarchy."""
365 l = [i+'/' for i in l[:-1]] + l[-1:]
367 l.pop() # extra blank caused by terminating '/'
372 def __init__(self, filename, tmax):
373 self.rootlevel = self.level = Level([], None)
378 self.filename = filename = realpath(filename)
380 (dir,name) = os.path.split(filename)
381 (ffd,self.tmpname) = tempfile.mkstemp('.tmp', filename, dir)
382 self.f = os.fdopen(ffd, 'wb', 65536)
383 self.f.write(INDEX_HDR)
393 os.unlink(self.tmpname)
397 self.level = _golevel(self.level, self.f, [], None, self.tmax)
398 self.count = self.rootlevel.count
401 self.f.write(struct.pack(FOOTER_SIG, self.count))
403 assert(self.level == None)
411 os.rename(self.tmpname, self.filename)
413 def _add(self, ename, entry):
414 if self.lastfile and self.lastfile <= ename:
415 raise Error('%r must come before %r'
416 % (''.join(e.name), ''.join(self.lastfile)))
417 self.lastfile = e.name
418 self.level = _golevel(self.level, self.f, ename, entry, self.tmax)
420 def add(self, name, st, hashgen = None):
421 endswith = name.endswith('/')
422 ename = pathsplit(name)
424 #log('add: %r %r\n' % (basename, name))
428 (gitmode, sha) = hashgen(name)
429 flags |= IX_HASHVALID
431 (gitmode, sha) = (0, EMPTY_SHA)
433 isdir = stat.S_ISDIR(st.st_mode)
434 assert(isdir == endswith)
435 e = NewEntry(basename, name, self.tmax,
436 st.st_dev, st.st_ino, st.st_nlink,
437 st.st_ctime, st.st_mtime, st.st_atime,
438 st.st_uid, st.st_gid,
439 st.st_size, st.st_mode, gitmode, sha, flags,
443 e = BlankNewEntry(basename, tmax)
449 def add_ixentry(self, e):
450 e.children_ofs = e.children_n = 0
451 self._add(pathsplit(e.name), e)
453 def new_reader(self):
455 return Reader(self.tmpname)
458 def reduce_paths(paths):
464 if stat.S_ISDIR(st.st_mode):
467 xpaths.append((rp, p))
469 add_error('reduce_paths: %s' % e)
474 for (rp, p) in xpaths:
475 if prev and (prev == rp
476 or (prev.endswith('/') and rp.startswith(prev))):
477 continue # already superceded by previous path
478 paths.append((rp, p))
480 paths.sort(reverse=True)
484 def pfunc(count, total):
485 qprogress('bup: merging indexes (%d/%d)\r' % (count, total))
486 def pfinal(count, total):
487 progress('bup: merging indexes (%d/%d), done.\n' % (count, total))
488 return merge_iter(iters, 1024, pfunc, pfinal, key='name')