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)
11 EMPTY_SHA = b'\0' * 20
12 FAKE_SHA = b'\x01' * 20
14 INDEX_HDR = b'BUPI\0\0\0\7'
16 # Time values are handled as integer nanoseconds since the epoch in
17 # memory, but are written as xstat/metadata timespecs. This behavior
18 # matches the existing metadata/xstat/.bupm code.
20 # Record times (mtime, ctime, atime) as xstat/metadata timespecs, and
21 # store all of the times in the index so they won't interfere with the
22 # forthcoming metadata cache.
27 'qQ' # ctime_s, ctime_ns
28 'qQ' # mtime_s, mtime_ns
29 'qQ' # atime_s, atime_ns
39 ENTLEN = struct.calcsize(INDEX_SIG)
41 FOOTLEN = struct.calcsize(FOOTER_SIG)
43 IX_EXISTS = 0x8000 # file exists on filesystem
44 IX_HASHVALID = 0x4000 # the stored sha1 matches the filesystem
45 IX_SHAMISSING = 0x2000 # the stored sha1 object doesn't seem to exist
47 class Error(Exception):
51 class MetaStoreReader:
52 def __init__(self, filename):
54 self._file = open(filename, 'rb')
64 def metadata_at(self, ofs):
66 return metadata.Metadata.read(self._file)
69 class MetaStoreWriter:
70 # For now, we just append to the file, and try to handle any
71 # truncation or corruption somewhat sensibly.
73 def __init__(self, filename):
74 # Map metadata hashes to bupindex.meta offsets.
76 self._filename = filename
78 # FIXME: see how slow this is; does it matter?
79 m_file = open(filename, 'ab+')
84 m = metadata.Metadata.read(m_file)
86 m_encoded = m.encode()
87 self._offsets[m_encoded] = m_off
89 m = metadata.Metadata.read(m_file)
93 log('index metadata in %r appears to be corrupt' % filename)
97 self._file = open(filename, 'ab')
108 def store(self, metadata):
109 meta_encoded = metadata.encode(include_path=False)
110 ofs = self._offsets.get(meta_encoded)
113 ofs = self._file.tell()
114 self._file.write(meta_encoded)
115 self._offsets[meta_encoded] = ofs
120 def __init__(self, ename, parent):
127 (ofs,n) = (f.tell(), len(self.list))
129 count = len(self.list)
130 #log('popping %r with %d entries\n'
131 # % (''.join(self.ename), count))
135 self.parent.count += count + self.count
139 def _golevel(level, f, ename, newentry, metastore, tmax):
140 # close nodes back up the tree
142 default_meta_ofs = metastore.store(metadata.Metadata())
143 while ename[:len(level.ename)] != level.ename:
144 n = BlankNewEntry(level.ename[-1], default_meta_ofs, tmax)
146 (n.children_ofs,n.children_n) = level.write(f)
147 level.parent.list.append(n)
150 # create nodes down the tree
151 while len(level.ename) < len(ename):
152 level = Level(ename[:len(level.ename)+1], level)
154 # are we in precisely the right place?
155 assert(ename == level.ename)
157 BlankNewEntry(ename and level.ename[-1] or None, default_meta_ofs, tmax)
158 (n.children_ofs,n.children_n) = level.write(f)
160 level.parent.list.append(n)
167 def __init__(self, basename, name, meta_ofs, tmax):
168 assert basename is None or type(basename) == bytes
169 assert name is None or type(name) == bytes
170 self.basename = basename
172 self.meta_ofs = meta_ofs
174 self.children_ofs = 0
178 return ("(%r,0x%04x,%d,%d,%d,%d,%d,%d,%s/%s,0x%04x,%d,0x%08x/%d)"
179 % (self.name, self.dev, self.ino, self.nlink,
180 self.ctime, self.mtime, self.atime,
181 self.size, self.mode, self.gitmode,
182 self.flags, self.meta_ofs,
183 self.children_ofs, self.children_n))
187 ctime = xstat.nsecs_to_timespec(self.ctime)
188 mtime = xstat.nsecs_to_timespec(self.mtime)
189 atime = xstat.nsecs_to_timespec(self.atime)
190 return struct.pack(INDEX_SIG,
191 self.dev, self.ino, self.nlink,
195 self.size, self.mode,
196 self.gitmode, self.sha, self.flags,
197 self.children_ofs, self.children_n,
199 except (DeprecationWarning, struct.error) as e:
200 log('pack error: %s (%r)\n' % (e, self))
203 def stale(self, st, tstart, check_device=True):
204 if self.size != st.st_size:
206 if self.mtime != st.st_mtime:
208 if self.sha == EMPTY_SHA:
212 if self.ctime != st.st_ctime:
214 if self.ino != st.st_ino:
216 if self.nlink != st.st_nlink:
218 if not (self.flags & IX_EXISTS):
220 if check_device and (self.dev != st.st_dev):
222 # Check that the ctime's "second" is at or after tstart's.
223 ctime_sec_in_ns = xstat.fstime_floor_secs(st.st_ctime) * 10**9
224 if ctime_sec_in_ns >= tstart:
228 def update_from_stat(self, st, meta_ofs):
229 # Should only be called when the entry is stale(), and
230 # invalidate() should almost certainly be called afterward.
233 self.nlink = st.st_nlink
234 self.ctime = st.st_ctime
235 self.mtime = st.st_mtime
236 self.atime = st.st_atime
237 self.size = st.st_size
238 self.mode = st.st_mode
239 self.flags |= IX_EXISTS
240 self.meta_ofs = meta_ofs
244 self.mtime = self._fixup_time(self.mtime)
245 self.ctime = self._fixup_time(self.ctime)
247 def _fixup_time(self, t):
248 if self.tmax != None and t > self.tmax:
254 f = IX_HASHVALID|IX_EXISTS
255 return (self.flags & f) == f
257 def invalidate(self):
258 self.flags &= ~IX_HASHVALID
260 def validate(self, gitmode, sha):
263 assert(gitmode+0 == gitmode)
264 self.gitmode = gitmode
266 self.flags |= IX_HASHVALID|IX_EXISTS
269 return not self.is_deleted()
271 def sha_missing(self):
272 return (self.flags & IX_SHAMISSING) or not (self.flags & IX_HASHVALID)
274 def is_deleted(self):
275 return (self.flags & IX_EXISTS) == 0
277 def set_deleted(self):
278 if self.flags & IX_EXISTS:
279 self.flags &= ~(IX_EXISTS | IX_HASHVALID)
282 return not self.is_fake()
285 return not self.ctime
287 def _cmp(self, other):
288 # Note reversed name ordering
289 bc = bytescmp(other.name, self.name)
292 vc = self.is_valid() - other.is_valid()
295 fc = self.is_fake() - other.is_fake()
300 def __eq__(self, other):
301 return self._cmp(other) == 0
303 def __ne__(self, other):
304 return self._cmp(other) != 0
306 def __lt__(self, other):
307 return self._cmp(other) < 0
309 def __gt__(self, other):
310 return self._cmp(other) > 0
312 def __le__(self, other):
313 return self._cmp(other) <= 0
315 def __ge__(self, other):
316 return self._cmp(other) >= 0
319 f.write(self.basename + b'\0' + self.packed())
322 class NewEntry(Entry):
323 def __init__(self, basename, name, tmax, dev, ino, nlink,
325 size, mode, gitmode, sha, flags, meta_ofs,
326 children_ofs, children_n):
327 Entry.__init__(self, basename, name, meta_ofs, tmax)
328 (self.dev, self.ino, self.nlink, self.ctime, self.mtime, self.atime,
329 self.size, self.mode, self.gitmode, self.sha,
330 self.flags, self.children_ofs, self.children_n
331 ) = (dev, ino, nlink, ctime, mtime, atime,
332 size, mode, gitmode, sha, flags, children_ofs, children_n)
336 class BlankNewEntry(NewEntry):
337 def __init__(self, basename, meta_ofs, tmax):
338 NewEntry.__init__(self, basename, basename, tmax,
339 0, 0, 0, 0, 0, 0, 0, 0,
340 0, EMPTY_SHA, 0, meta_ofs, 0, 0)
343 class ExistingEntry(Entry):
344 def __init__(self, parent, basename, name, m, ofs):
345 Entry.__init__(self, basename, name, None, None)
349 (self.dev, self.ino, self.nlink,
350 self.ctime, ctime_ns, self.mtime, mtime_ns, self.atime, atime_ns,
351 self.size, self.mode, self.gitmode, self.sha,
352 self.flags, self.children_ofs, self.children_n, self.meta_ofs
353 ) = struct.unpack(INDEX_SIG, m[ofs : ofs + ENTLEN])
354 self.atime = xstat.timespec_to_nsecs((self.atime, atime_ns))
355 self.mtime = xstat.timespec_to_nsecs((self.mtime, mtime_ns))
356 self.ctime = xstat.timespec_to_nsecs((self.ctime, ctime_ns))
358 # effectively, we don't bother messing with IX_SHAMISSING if
359 # not IX_HASHVALID, since it's redundant, and repacking is more
360 # expensive than not repacking.
361 # This is implemented by having sha_missing() check IX_HASHVALID too.
362 def set_sha_missing(self, val):
364 oldval = self.sha_missing() and 1 or 0
366 flag = val and IX_SHAMISSING or 0
367 newflags = (self.flags & (~IX_SHAMISSING)) | flag
368 self.flags = newflags
371 def unset_sha_missing(self, flag):
372 if self.flags & IX_SHAMISSING:
373 self.flags &= ~IX_SHAMISSING
377 self._m[self._ofs:self._ofs+ENTLEN] = self.packed()
378 if self.parent and not self.is_valid():
379 self.parent.invalidate()
382 def iter(self, name=None, wantrecurse=None):
384 if dname and not dname.endswith(b'/'):
386 ofs = self.children_ofs
387 assert(ofs <= len(self._m))
388 assert(self.children_n <= UINT_MAX) # i.e. python struct 'I'
389 for i in range(self.children_n):
390 eon = self._m.find(b'\0', ofs)
394 basename = self._m[ofs : ofs + (eon - ofs)]
395 child = ExistingEntry(self, basename, self.name + basename,
398 or child.name.startswith(dname)
399 or child.name.endswith(b'/') and dname.startswith(child.name)):
400 if not wantrecurse or wantrecurse(child):
401 for e in child.iter(name=name, wantrecurse=wantrecurse):
403 if not name or child.name == name or child.name.startswith(dname):
405 ofs = eon + 1 + ENTLEN
412 def __init__(self, filename):
413 self.filename = filename
415 self.writable = False
419 f = open(filename, 'rb+')
421 if e.errno == errno.ENOENT:
426 b = f.read(len(INDEX_HDR))
428 log('warning: %s: header: expected %r, got %r\n'
429 % (filename, INDEX_HDR, b))
431 st = os.fstat(f.fileno())
433 self.m = mmap_readwrite(f)
435 self.count = struct.unpack(FOOTER_SIG,
436 self.m[st.st_size - FOOTLEN
443 return int(self.count)
445 def forward_iter(self):
447 while ofs+ENTLEN <= len(self.m)-FOOTLEN:
448 eon = self.m.find(b'\0', ofs)
452 basename = self.m[ofs : ofs + (eon - ofs)]
453 yield ExistingEntry(None, basename, basename, self.m, eon+1)
454 ofs = eon + 1 + ENTLEN
456 def iter(self, name=None, wantrecurse=None):
457 if len(self.m) > len(INDEX_HDR)+ENTLEN:
459 if dname and not dname.endswith(b'/'):
461 root = ExistingEntry(None, b'/', b'/',
462 self.m, len(self.m)-FOOTLEN-ENTLEN)
463 for sub in root.iter(name=name, wantrecurse=wantrecurse):
465 if not dname or dname == root.name:
471 def find(self, name):
472 return next((e for e in self.iter(name, wantrecurse=lambda x : True)
480 if self.writable and self.m:
485 if self.writable and self.m:
488 self.writable = False
490 def filter(self, prefixes, wantrecurse=None):
491 for (rp, path) in reduce_paths(prefixes):
493 for e in self.iter(rp, wantrecurse=wantrecurse):
495 assert(e.name.startswith(rp))
496 name = path + e.name[len(rp):]
499 # Always return at least the top for each prefix.
500 # Otherwise something like "save x/y" will produce
501 # nothing if x is up to date.
504 name = path + pe.name[len(rp):]
507 # FIXME: this function isn't very generic, because it splits the filename
508 # in an odd way and depends on a terminating '/' to indicate directories.
510 """Split a path into a list of elements of the file system hierarchy."""
512 l = [i + b'/' for i in l[:-1]] + l[-1:]
514 l.pop() # extra blank caused by terminating '/'
519 def __init__(self, filename, metastore, tmax):
520 self.rootlevel = self.level = Level([], None)
525 self.filename = filename = resolve_parent(filename)
526 self.metastore = metastore
528 (dir,name) = os.path.split(filename)
529 ffd, self.tmpname = tempfile.mkstemp(b'.tmp', filename, dir)
530 self.f = os.fdopen(ffd, 'wb', 65536)
531 self.f.write(INDEX_HDR)
541 os.unlink(self.tmpname)
545 self.level = _golevel(self.level, self.f, [], None,
546 self.metastore, self.tmax)
547 self.count = self.rootlevel.count
550 self.f.write(struct.pack(FOOTER_SIG, self.count))
552 assert(self.level == None)
560 os.rename(self.tmpname, self.filename)
562 def _add(self, ename, entry):
563 if self.lastfile and self.lastfile <= ename:
564 raise Error('%r must come before %r'
565 % (''.join(ename), ''.join(self.lastfile)))
566 self.lastfile = ename
567 self.level = _golevel(self.level, self.f, ename, entry,
568 self.metastore, self.tmax)
570 def add(self, name, st, meta_ofs, hashgen = None):
571 endswith = name.endswith(b'/')
572 ename = pathsplit(name)
574 #log('add: %r %r\n' % (basename, name))
578 (gitmode, sha) = hashgen(name)
579 flags |= IX_HASHVALID
581 (gitmode, sha) = (0, EMPTY_SHA)
583 isdir = stat.S_ISDIR(st.st_mode)
584 assert(isdir == endswith)
585 e = NewEntry(basename, name, self.tmax,
586 st.st_dev, st.st_ino, st.st_nlink,
587 st.st_ctime, st.st_mtime, st.st_atime,
588 st.st_size, st.st_mode, gitmode, sha, flags,
592 meta_ofs = self.metastore.store(metadata.Metadata())
593 e = BlankNewEntry(basename, meta_ofs, self.tmax)
599 def add_ixentry(self, e):
600 e.children_ofs = e.children_n = 0
601 self._add(pathsplit(e.name), e)
603 def new_reader(self):
605 return Reader(self.tmpname)
608 def _slashappend_or_add_error(p, caller):
609 """Return p, after ensuring it has a single trailing slash if it names
610 a directory, unless there's an OSError, in which case, call
611 add_error() and return None."""
615 add_error('%s: %s' % (caller, e))
618 if stat.S_ISDIR(st.st_mode):
619 return slashappend(p)
623 def unique_resolved_paths(paths):
624 "Return a collection of unique resolved paths."
625 rps = (_slashappend_or_add_error(resolve_parent(p), 'unique_resolved_paths')
627 return frozenset((x for x in rps if x is not None))
630 def reduce_paths(paths):
633 rp = _slashappend_or_add_error(resolve_parent(p), 'reduce_paths')
635 xpaths.append((rp, slashappend(p) if rp.endswith(b'/') else p))
640 for (rp, p) in xpaths:
641 if prev and (prev == rp
642 or (prev.endswith(b'/') and rp.startswith(prev))):
643 continue # already superceded by previous path
644 paths.append((rp, p))
646 paths.sort(reverse=True)
651 def pfunc(count, total):
652 qprogress('bup: merging indexes (%d/%d)\r' % (count, total))
653 def pfinal(count, total):
654 progress('bup: merging indexes (%d/%d), done.\n' % (count, total))
655 return merge_iter(iters, 1024, pfunc, pfinal, key='name')