2 from __future__ import absolute_import, print_function
3 import errno, os, stat, struct, tempfile
5 from bup import compat, metadata, xstat
6 from bup._helpers import UINT_MAX, bytescmp
7 from bup.compat import range
8 from bup.helpers import (add_error, log, merge_iter, mmap_readwrite,
9 progress, qprogress, resolve_parent, slashappend)
12 from bup.compat import buffer
16 EMPTY_SHA = b'\0' * 20
17 FAKE_SHA = b'\x01' * 20
19 INDEX_HDR = b'BUPI\0\0\0\7'
21 # Time values are handled as integer nanoseconds since the epoch in
22 # memory, but are written as xstat/metadata timespecs. This behavior
23 # matches the existing metadata/xstat/.bupm code.
25 # Record times (mtime, ctime, atime) as xstat/metadata timespecs, and
26 # store all of the times in the index so they won't interfere with the
27 # forthcoming metadata cache.
32 'qQ' # ctime_s, ctime_ns
33 'qQ' # mtime_s, mtime_ns
34 'qQ' # atime_s, atime_ns
44 ENTLEN = struct.calcsize(INDEX_SIG)
46 FOOTLEN = struct.calcsize(FOOTER_SIG)
48 IX_EXISTS = 0x8000 # file exists on filesystem
49 IX_HASHVALID = 0x4000 # the stored sha1 matches the filesystem
50 IX_SHAMISSING = 0x2000 # the stored sha1 object doesn't seem to exist
52 class Error(Exception):
56 class MetaStoreReader:
57 def __init__(self, filename):
59 self._file = open(filename, 'rb')
69 def metadata_at(self, ofs):
71 return metadata.Metadata.read(self._file)
74 class MetaStoreWriter:
75 # For now, we just append to the file, and try to handle any
76 # truncation or corruption somewhat sensibly.
78 def __init__(self, filename):
79 # Map metadata hashes to bupindex.meta offsets.
81 self._filename = filename
83 # FIXME: see how slow this is; does it matter?
84 m_file = open(filename, 'ab+')
89 m = metadata.Metadata.read(m_file)
91 m_encoded = m.encode()
92 self._offsets[m_encoded] = m_off
94 m = metadata.Metadata.read(m_file)
98 log('index metadata in %r appears to be corrupt' % filename)
102 self._file = open(filename, 'ab')
113 def store(self, metadata):
114 meta_encoded = metadata.encode(include_path=False)
115 ofs = self._offsets.get(meta_encoded)
118 ofs = self._file.tell()
119 self._file.write(meta_encoded)
120 self._offsets[meta_encoded] = ofs
125 def __init__(self, ename, parent):
132 (ofs,n) = (f.tell(), len(self.list))
134 count = len(self.list)
135 #log('popping %r with %d entries\n'
136 # % (''.join(self.ename), count))
140 self.parent.count += count + self.count
144 def _golevel(level, f, ename, newentry, metastore, tmax):
145 # close nodes back up the tree
147 default_meta_ofs = metastore.store(metadata.Metadata())
148 while ename[:len(level.ename)] != level.ename:
149 n = BlankNewEntry(level.ename[-1], default_meta_ofs, tmax)
151 (n.children_ofs,n.children_n) = level.write(f)
152 level.parent.list.append(n)
155 # create nodes down the tree
156 while len(level.ename) < len(ename):
157 level = Level(ename[:len(level.ename)+1], level)
159 # are we in precisely the right place?
160 assert(ename == level.ename)
162 BlankNewEntry(ename and level.ename[-1] or None, default_meta_ofs, tmax)
163 (n.children_ofs,n.children_n) = level.write(f)
165 level.parent.list.append(n)
172 def __init__(self, basename, name, meta_ofs, tmax):
173 assert basename is None or type(basename) == bytes
174 assert name is None or type(name) == bytes
175 self.basename = basename
177 self.meta_ofs = meta_ofs
179 self.children_ofs = 0
183 return ("(%r,0x%04x,%d,%d,%d,%d,%d,%d,%s/%s,0x%04x,%d,0x%08x/%d)"
184 % (self.name, self.dev, self.ino, self.nlink,
185 self.ctime, self.mtime, self.atime,
186 self.size, self.mode, self.gitmode,
187 self.flags, self.meta_ofs,
188 self.children_ofs, self.children_n))
192 ctime = xstat.nsecs_to_timespec(self.ctime)
193 mtime = xstat.nsecs_to_timespec(self.mtime)
194 atime = xstat.nsecs_to_timespec(self.atime)
195 return struct.pack(INDEX_SIG,
196 self.dev, self.ino, self.nlink,
200 self.size, self.mode,
201 self.gitmode, self.sha, self.flags,
202 self.children_ofs, self.children_n,
204 except (DeprecationWarning, struct.error) as e:
205 log('pack error: %s (%r)\n' % (e, self))
208 def stale(self, st, tstart, check_device=True):
209 if self.size != st.st_size:
211 if self.mtime != st.st_mtime:
213 if self.sha == EMPTY_SHA:
217 if self.ctime != st.st_ctime:
219 if self.ino != st.st_ino:
221 if self.nlink != st.st_nlink:
223 if not (self.flags & IX_EXISTS):
225 if check_device and (self.dev != st.st_dev):
227 # Check that the ctime's "second" is at or after tstart's.
228 ctime_sec_in_ns = xstat.fstime_floor_secs(st.st_ctime) * 10**9
229 if ctime_sec_in_ns >= tstart:
233 def update_from_stat(self, st, meta_ofs):
234 # Should only be called when the entry is stale(), and
235 # invalidate() should almost certainly be called afterward.
238 self.nlink = st.st_nlink
239 self.ctime = st.st_ctime
240 self.mtime = st.st_mtime
241 self.atime = st.st_atime
242 self.size = st.st_size
243 self.mode = st.st_mode
244 self.flags |= IX_EXISTS
245 self.meta_ofs = meta_ofs
249 self.mtime = self._fixup_time(self.mtime)
250 self.ctime = self._fixup_time(self.ctime)
252 def _fixup_time(self, t):
253 if self.tmax != None and t > self.tmax:
259 f = IX_HASHVALID|IX_EXISTS
260 return (self.flags & f) == f
262 def invalidate(self):
263 self.flags &= ~IX_HASHVALID
265 def validate(self, gitmode, sha):
268 assert(gitmode+0 == gitmode)
269 self.gitmode = gitmode
271 self.flags |= IX_HASHVALID|IX_EXISTS
274 return not self.is_deleted()
276 def sha_missing(self):
277 return (self.flags & IX_SHAMISSING) or not (self.flags & IX_HASHVALID)
279 def is_deleted(self):
280 return (self.flags & IX_EXISTS) == 0
282 def set_deleted(self):
283 if self.flags & IX_EXISTS:
284 self.flags &= ~(IX_EXISTS | IX_HASHVALID)
287 return not self.is_fake()
290 return not self.ctime
292 def _cmp(self, other):
293 # Note reversed name ordering
294 bc = bytescmp(other.name, self.name)
297 vc = self.is_valid() - other.is_valid()
300 fc = self.is_fake() - other.is_fake()
305 def __eq__(self, other):
306 return self._cmp(other) == 0
309 return self._cmp(other) != 0
311 def __lt__(self, other):
312 return self._cmp(other) < 0
314 def __gt__(self, other):
315 return self._cmp(other) > 0
318 return self._cmp(other) <= 0
321 return self._cmp(other) >= 0
324 f.write(self.basename + b'\0' + self.packed())
327 class NewEntry(Entry):
328 def __init__(self, basename, name, tmax, dev, ino, nlink,
330 size, mode, gitmode, sha, flags, meta_ofs,
331 children_ofs, children_n):
332 Entry.__init__(self, basename, name, meta_ofs, tmax)
333 (self.dev, self.ino, self.nlink, self.ctime, self.mtime, self.atime,
334 self.size, self.mode, self.gitmode, self.sha,
335 self.flags, self.children_ofs, self.children_n
336 ) = (dev, ino, nlink, ctime, mtime, atime,
337 size, mode, gitmode, sha, flags, children_ofs, children_n)
341 class BlankNewEntry(NewEntry):
342 def __init__(self, basename, meta_ofs, tmax):
343 NewEntry.__init__(self, basename, basename, tmax,
344 0, 0, 0, 0, 0, 0, 0, 0,
345 0, EMPTY_SHA, 0, meta_ofs, 0, 0)
348 class ExistingEntry(Entry):
349 def __init__(self, parent, basename, name, m, ofs):
350 Entry.__init__(self, basename, name, None, None)
354 (self.dev, self.ino, self.nlink,
355 self.ctime, ctime_ns, self.mtime, mtime_ns, self.atime, atime_ns,
356 self.size, self.mode, self.gitmode, self.sha,
357 self.flags, self.children_ofs, self.children_n, self.meta_ofs
358 ) = struct.unpack(INDEX_SIG, m[ofs : ofs + ENTLEN])
359 self.atime = xstat.timespec_to_nsecs((self.atime, atime_ns))
360 self.mtime = xstat.timespec_to_nsecs((self.mtime, mtime_ns))
361 self.ctime = xstat.timespec_to_nsecs((self.ctime, ctime_ns))
363 # effectively, we don't bother messing with IX_SHAMISSING if
364 # not IX_HASHVALID, since it's redundant, and repacking is more
365 # expensive than not repacking.
366 # This is implemented by having sha_missing() check IX_HASHVALID too.
367 def set_sha_missing(self, val):
369 oldval = self.sha_missing() and 1 or 0
371 flag = val and IX_SHAMISSING or 0
372 newflags = (self.flags & (~IX_SHAMISSING)) | flag
373 self.flags = newflags
376 def unset_sha_missing(self, flag):
377 if self.flags & IX_SHAMISSING:
378 self.flags &= ~IX_SHAMISSING
382 self._m[self._ofs:self._ofs+ENTLEN] = self.packed()
383 if self.parent and not self.is_valid():
384 self.parent.invalidate()
387 def iter(self, name=None, wantrecurse=None):
389 if dname and not dname.endswith(b'/'):
391 ofs = self.children_ofs
392 assert(ofs <= len(self._m))
393 assert(self.children_n <= UINT_MAX) # i.e. python struct 'I'
394 for i in range(self.children_n):
395 eon = self._m.find(b'\0', ofs)
399 basename = self._m[ofs : ofs + (eon - ofs)]
400 child = ExistingEntry(self, basename, self.name + basename,
403 or child.name.startswith(dname)
404 or child.name.endswith(b'/') and dname.startswith(child.name)):
405 if not wantrecurse or wantrecurse(child):
406 for e in child.iter(name=name, wantrecurse=wantrecurse):
408 if not name or child.name == name or child.name.startswith(dname):
410 ofs = eon + 1 + ENTLEN
417 def __init__(self, filename):
418 self.filename = filename
420 self.writable = False
424 f = open(filename, 'rb+')
426 if e.errno == errno.ENOENT:
431 b = f.read(len(INDEX_HDR))
433 log('warning: %s: header: expected %r, got %r\n'
434 % (filename, INDEX_HDR, b))
436 st = os.fstat(f.fileno())
438 self.m = mmap_readwrite(f)
440 self.count = struct.unpack(FOOTER_SIG,
441 self.m[st.st_size - FOOTLEN
448 return int(self.count)
450 def forward_iter(self):
452 while ofs+ENTLEN <= len(self.m)-FOOTLEN:
453 eon = self.m.find(b'\0', ofs)
457 basename = self.m[ofs : ofs + (eon - ofs)]
458 yield ExistingEntry(None, basename, basename, self.m, eon+1)
459 ofs = eon + 1 + ENTLEN
461 def iter(self, name=None, wantrecurse=None):
462 if len(self.m) > len(INDEX_HDR)+ENTLEN:
464 if dname and not dname.endswith(b'/'):
466 root = ExistingEntry(None, b'/', b'/',
467 self.m, len(self.m)-FOOTLEN-ENTLEN)
468 for sub in root.iter(name=name, wantrecurse=wantrecurse):
470 if not dname or dname == root.name:
476 def find(self, name):
477 return next((e for e in self.iter(name, wantrecurse=lambda x : True)
485 if self.writable and self.m:
490 if self.writable and self.m:
493 self.writable = False
495 def filter(self, prefixes, wantrecurse=None):
496 for (rp, path) in reduce_paths(prefixes):
498 for e in self.iter(rp, wantrecurse=wantrecurse):
500 assert(e.name.startswith(rp))
501 name = path + e.name[len(rp):]
504 # Always return at least the top for each prefix.
505 # Otherwise something like "save x/y" will produce
506 # nothing if x is up to date.
509 name = path + pe.name[len(rp):]
512 # FIXME: this function isn't very generic, because it splits the filename
513 # in an odd way and depends on a terminating '/' to indicate directories.
515 """Split a path into a list of elements of the file system hierarchy."""
517 l = [i + b'/' for i in l[:-1]] + l[-1:]
519 l.pop() # extra blank caused by terminating '/'
524 def __init__(self, filename, metastore, tmax):
525 self.rootlevel = self.level = Level([], None)
530 self.filename = filename = resolve_parent(filename)
531 self.metastore = metastore
533 (dir,name) = os.path.split(filename)
534 ffd, self.tmpname = tempfile.mkstemp(b'.tmp', filename, dir)
535 self.f = os.fdopen(ffd, 'wb', 65536)
536 self.f.write(INDEX_HDR)
546 os.unlink(self.tmpname)
550 self.level = _golevel(self.level, self.f, [], None,
551 self.metastore, self.tmax)
552 self.count = self.rootlevel.count
555 self.f.write(struct.pack(FOOTER_SIG, self.count))
557 assert(self.level == None)
565 os.rename(self.tmpname, self.filename)
567 def _add(self, ename, entry):
568 if self.lastfile and self.lastfile <= ename:
569 raise Error('%r must come before %r'
570 % (''.join(ename), ''.join(self.lastfile)))
571 self.lastfile = ename
572 self.level = _golevel(self.level, self.f, ename, entry,
573 self.metastore, self.tmax)
575 def add(self, name, st, meta_ofs, hashgen = None):
576 endswith = name.endswith(b'/')
577 ename = pathsplit(name)
579 #log('add: %r %r\n' % (basename, name))
583 (gitmode, sha) = hashgen(name)
584 flags |= IX_HASHVALID
586 (gitmode, sha) = (0, EMPTY_SHA)
588 isdir = stat.S_ISDIR(st.st_mode)
589 assert(isdir == endswith)
590 e = NewEntry(basename, name, self.tmax,
591 st.st_dev, st.st_ino, st.st_nlink,
592 st.st_ctime, st.st_mtime, st.st_atime,
593 st.st_size, st.st_mode, gitmode, sha, flags,
597 meta_ofs = self.metastore.store(metadata.Metadata())
598 e = BlankNewEntry(basename, meta_ofs, self.tmax)
604 def add_ixentry(self, e):
605 e.children_ofs = e.children_n = 0
606 self._add(pathsplit(e.name), e)
608 def new_reader(self):
610 return Reader(self.tmpname)
613 def _slashappend_or_add_error(p, caller):
614 """Return p, after ensuring it has a single trailing slash if it names
615 a directory, unless there's an OSError, in which case, call
616 add_error() and return None."""
620 add_error('%s: %s' % (caller, e))
623 if stat.S_ISDIR(st.st_mode):
624 return slashappend(p)
628 def unique_resolved_paths(paths):
629 "Return a collection of unique resolved paths."
630 rps = (_slashappend_or_add_error(resolve_parent(p), 'unique_resolved_paths')
632 return frozenset((x for x in rps if x is not None))
635 def reduce_paths(paths):
638 rp = _slashappend_or_add_error(resolve_parent(p), 'reduce_paths')
640 xpaths.append((rp, slashappend(p) if rp.endswith(b'/') else p))
645 for (rp, p) in xpaths:
646 if prev and (prev == rp
647 or (prev.endswith(b'/') and rp.startswith(prev))):
648 continue # already superceded by previous path
649 paths.append((rp, p))
651 paths.sort(reverse=True)
656 def pfunc(count, total):
657 qprogress('bup: merging indexes (%d/%d)\r' % (count, total))
658 def pfinal(count, total):
659 progress('bup: merging indexes (%d/%d), done.\n' % (count, total))
660 return merge_iter(iters, 1024, pfunc, pfinal, key='name')