1 import errno, metadata, os, stat, struct, tempfile
4 from bup._helpers import UINT_MAX, bytescmp
5 from bup.helpers import (add_error, log, merge_iter, mmap_readwrite,
6 progress, qprogress, resolve_parent, slashappend)
11 INDEX_HDR = 'BUPI\0\0\0\7'
13 # Time values are handled as integer nanoseconds since the epoch in
14 # memory, but are written as xstat/metadata timespecs. This behavior
15 # matches the existing metadata/xstat/.bupm code.
17 # Record times (mtime, ctime, atime) as xstat/metadata timespecs, and
18 # store all of the times in the index so they won't interfere with the
19 # forthcoming metadata cache.
24 'qQ' # ctime_s, ctime_ns
25 'qQ' # mtime_s, mtime_ns
26 'qQ' # atime_s, atime_ns
36 ENTLEN = struct.calcsize(INDEX_SIG)
38 FOOTLEN = struct.calcsize(FOOTER_SIG)
40 IX_EXISTS = 0x8000 # file exists on filesystem
41 IX_HASHVALID = 0x4000 # the stored sha1 matches the filesystem
42 IX_SHAMISSING = 0x2000 # the stored sha1 object doesn't seem to exist
44 class Error(Exception):
48 class MetaStoreReader:
49 def __init__(self, filename):
51 self._file = open(filename, 'rb')
61 def metadata_at(self, ofs):
63 return metadata.Metadata.read(self._file)
66 class MetaStoreWriter:
67 # For now, we just append to the file, and try to handle any
68 # truncation or corruption somewhat sensibly.
70 def __init__(self, filename):
71 # Map metadata hashes to bupindex.meta offsets.
73 self._filename = filename
75 # FIXME: see how slow this is; does it matter?
76 m_file = open(filename, 'ab+')
81 m = metadata.Metadata.read(m_file)
83 m_encoded = m.encode()
84 self._offsets[m_encoded] = m_off
86 m = metadata.Metadata.read(m_file)
90 log('index metadata in %r appears to be corrupt' % filename)
94 self._file = open(filename, 'ab')
105 def store(self, metadata):
106 meta_encoded = metadata.encode(include_path=False)
107 ofs = self._offsets.get(meta_encoded)
110 ofs = self._file.tell()
111 self._file.write(meta_encoded)
112 self._offsets[meta_encoded] = ofs
117 def __init__(self, ename, parent):
124 (ofs,n) = (f.tell(), len(self.list))
126 count = len(self.list)
127 #log('popping %r with %d entries\n'
128 # % (''.join(self.ename), count))
132 self.parent.count += count + self.count
136 def _golevel(level, f, ename, newentry, metastore, tmax):
137 # close nodes back up the tree
139 default_meta_ofs = metastore.store(metadata.Metadata())
140 while ename[:len(level.ename)] != level.ename:
141 n = BlankNewEntry(level.ename[-1], default_meta_ofs, tmax)
143 (n.children_ofs,n.children_n) = level.write(f)
144 level.parent.list.append(n)
147 # create nodes down the tree
148 while len(level.ename) < len(ename):
149 level = Level(ename[:len(level.ename)+1], level)
151 # are we in precisely the right place?
152 assert(ename == level.ename)
154 BlankNewEntry(ename and level.ename[-1] or None, default_meta_ofs, tmax)
155 (n.children_ofs,n.children_n) = level.write(f)
157 level.parent.list.append(n)
164 def __init__(self, basename, name, meta_ofs, tmax):
165 self.basename = str(basename)
166 self.name = str(name)
167 self.meta_ofs = meta_ofs
169 self.children_ofs = 0
173 return ("(%s,0x%04x,%d,%d,%d,%d,%d,%d,%s/%s,0x%04x,%d,0x%08x/%d)"
174 % (self.name, self.dev, self.ino, self.nlink,
175 self.ctime, self.mtime, self.atime,
176 self.size, self.mode, self.gitmode,
177 self.flags, self.meta_ofs,
178 self.children_ofs, self.children_n))
182 ctime = xstat.nsecs_to_timespec(self.ctime)
183 mtime = xstat.nsecs_to_timespec(self.mtime)
184 atime = xstat.nsecs_to_timespec(self.atime)
185 return struct.pack(INDEX_SIG,
186 self.dev, self.ino, self.nlink,
190 self.size, self.mode,
191 self.gitmode, self.sha, self.flags,
192 self.children_ofs, self.children_n,
194 except (DeprecationWarning, struct.error) as e:
195 log('pack error: %s (%r)\n' % (e, self))
198 def stale(self, st, tstart, check_device=True):
199 if self.size != st.st_size:
201 if self.mtime != st.st_mtime:
203 if self.sha == EMPTY_SHA:
207 if self.ctime != st.st_ctime:
209 if self.ino != st.st_ino:
211 if self.nlink != st.st_nlink:
213 if not (self.flags & IX_EXISTS):
215 if check_device and (self.dev != st.st_dev):
217 # Check that the ctime's "second" is at or after tstart's.
218 ctime_sec_in_ns = xstat.fstime_floor_secs(st.st_ctime) * 10**9
219 if ctime_sec_in_ns >= tstart:
223 def update_from_stat(self, st, meta_ofs):
224 # Should only be called when the entry is stale(), and
225 # invalidate() should almost certainly be called afterward.
228 self.nlink = st.st_nlink
229 self.ctime = st.st_ctime
230 self.mtime = st.st_mtime
231 self.atime = st.st_atime
232 self.size = st.st_size
233 self.mode = st.st_mode
234 self.flags |= IX_EXISTS
235 self.meta_ofs = meta_ofs
239 self.mtime = self._fixup_time(self.mtime)
240 self.ctime = self._fixup_time(self.ctime)
242 def _fixup_time(self, t):
243 if self.tmax != None and t > self.tmax:
249 f = IX_HASHVALID|IX_EXISTS
250 return (self.flags & f) == f
252 def invalidate(self):
253 self.flags &= ~IX_HASHVALID
255 def validate(self, gitmode, sha):
258 assert(gitmode+0 == gitmode)
259 self.gitmode = gitmode
261 self.flags |= IX_HASHVALID|IX_EXISTS
264 return not self.is_deleted()
266 def sha_missing(self):
267 return (self.flags & IX_SHAMISSING) or not (self.flags & IX_HASHVALID)
269 def is_deleted(self):
270 return (self.flags & IX_EXISTS) == 0
272 def set_deleted(self):
273 if self.flags & IX_EXISTS:
274 self.flags &= ~(IX_EXISTS | IX_HASHVALID)
277 return not self.is_fake()
280 return not self.ctime
282 def _cmp(self, other):
283 # Note reversed name ordering
284 bc = bytescmp(other.name, self.name)
287 vc = self.is_valid() - other.is_valid()
290 fc = self.is_fake() - other.is_fake()
295 def __eq__(self, other):
296 return self._cmp(other) == 0
299 return self._cmp(other) != 0
301 def __lt__(self, other):
302 return self._cmp(other) < 0
304 def __gt__(self, other):
305 return self._cmp(other) > 0
308 return self._cmp(other) <= 0
311 return self._cmp(other) >= 0
314 f.write(self.basename + '\0' + self.packed())
317 class NewEntry(Entry):
318 def __init__(self, basename, name, tmax, dev, ino, nlink,
320 size, mode, gitmode, sha, flags, meta_ofs,
321 children_ofs, children_n):
322 Entry.__init__(self, basename, name, meta_ofs, tmax)
323 (self.dev, self.ino, self.nlink, self.ctime, self.mtime, self.atime,
324 self.size, self.mode, self.gitmode, self.sha,
325 self.flags, self.children_ofs, self.children_n
326 ) = (dev, ino, nlink, ctime, mtime, atime,
327 size, mode, gitmode, sha, flags, children_ofs, children_n)
331 class BlankNewEntry(NewEntry):
332 def __init__(self, basename, meta_ofs, tmax):
333 NewEntry.__init__(self, basename, basename, tmax,
334 0, 0, 0, 0, 0, 0, 0, 0,
335 0, EMPTY_SHA, 0, meta_ofs, 0, 0)
338 class ExistingEntry(Entry):
339 def __init__(self, parent, basename, name, m, ofs):
340 Entry.__init__(self, basename, name, None, None)
344 (self.dev, self.ino, self.nlink,
345 self.ctime, ctime_ns, self.mtime, mtime_ns, self.atime, atime_ns,
346 self.size, self.mode, self.gitmode, self.sha,
347 self.flags, self.children_ofs, self.children_n, self.meta_ofs
348 ) = struct.unpack(INDEX_SIG, str(buffer(m, ofs, ENTLEN)))
349 self.atime = xstat.timespec_to_nsecs((self.atime, atime_ns))
350 self.mtime = xstat.timespec_to_nsecs((self.mtime, mtime_ns))
351 self.ctime = xstat.timespec_to_nsecs((self.ctime, ctime_ns))
353 # effectively, we don't bother messing with IX_SHAMISSING if
354 # not IX_HASHVALID, since it's redundant, and repacking is more
355 # expensive than not repacking.
356 # This is implemented by having sha_missing() check IX_HASHVALID too.
357 def set_sha_missing(self, val):
359 oldval = self.sha_missing() and 1 or 0
361 flag = val and IX_SHAMISSING or 0
362 newflags = (self.flags & (~IX_SHAMISSING)) | flag
363 self.flags = newflags
366 def unset_sha_missing(self, flag):
367 if self.flags & IX_SHAMISSING:
368 self.flags &= ~IX_SHAMISSING
372 self._m[self._ofs:self._ofs+ENTLEN] = self.packed()
373 if self.parent and not self.is_valid():
374 self.parent.invalidate()
377 def iter(self, name=None, wantrecurse=None):
379 if dname and not dname.endswith('/'):
381 ofs = self.children_ofs
382 assert(ofs <= len(self._m))
383 assert(self.children_n <= UINT_MAX) # i.e. python struct 'I'
384 for i in xrange(self.children_n):
385 eon = self._m.find('\0', ofs)
389 basename = str(buffer(self._m, ofs, eon-ofs))
390 child = ExistingEntry(self, basename, self.name + basename,
393 or child.name.startswith(dname)
394 or child.name.endswith('/') and dname.startswith(child.name)):
395 if not wantrecurse or wantrecurse(child):
396 for e in child.iter(name=name, wantrecurse=wantrecurse):
398 if not name or child.name == name or child.name.startswith(dname):
400 ofs = eon + 1 + ENTLEN
407 def __init__(self, filename):
408 self.filename = filename
410 self.writable = False
414 f = open(filename, 'r+')
416 if e.errno == errno.ENOENT:
421 b = f.read(len(INDEX_HDR))
423 log('warning: %s: header: expected %r, got %r\n'
424 % (filename, INDEX_HDR, b))
426 st = os.fstat(f.fileno())
428 self.m = mmap_readwrite(f)
430 self.count = struct.unpack(FOOTER_SIG,
431 str(buffer(self.m, st.st_size-FOOTLEN, FOOTLEN)))[0]
437 return int(self.count)
439 def forward_iter(self):
441 while ofs+ENTLEN <= len(self.m)-FOOTLEN:
442 eon = self.m.find('\0', ofs)
446 basename = str(buffer(self.m, ofs, eon-ofs))
447 yield ExistingEntry(None, basename, basename, self.m, eon+1)
448 ofs = eon + 1 + ENTLEN
450 def iter(self, name=None, wantrecurse=None):
451 if len(self.m) > len(INDEX_HDR)+ENTLEN:
453 if dname and not dname.endswith('/'):
455 root = ExistingEntry(None, '/', '/',
456 self.m, len(self.m)-FOOTLEN-ENTLEN)
457 for sub in root.iter(name=name, wantrecurse=wantrecurse):
459 if not dname or dname == root.name:
465 def find(self, name):
466 return next((e for e in self.iter(name, wantrecurse=lambda x : True)
474 if self.writable and self.m:
479 if self.writable and self.m:
482 self.writable = False
484 def filter(self, prefixes, wantrecurse=None):
485 for (rp, path) in reduce_paths(prefixes):
487 for e in self.iter(rp, wantrecurse=wantrecurse):
489 assert(e.name.startswith(rp))
490 name = path + e.name[len(rp):]
493 # Always return at least the top for each prefix.
494 # Otherwise something like "save x/y" will produce
495 # nothing if x is up to date.
498 name = path + pe.name[len(rp):]
501 # FIXME: this function isn't very generic, because it splits the filename
502 # in an odd way and depends on a terminating '/' to indicate directories.
504 """Split a path into a list of elements of the file system hierarchy."""
506 l = [i+'/' for i in l[:-1]] + l[-1:]
508 l.pop() # extra blank caused by terminating '/'
513 def __init__(self, filename, metastore, tmax):
514 self.rootlevel = self.level = Level([], None)
519 self.filename = filename = resolve_parent(filename)
520 self.metastore = metastore
522 (dir,name) = os.path.split(filename)
523 (ffd,self.tmpname) = tempfile.mkstemp('.tmp', filename, dir)
524 self.f = os.fdopen(ffd, 'wb', 65536)
525 self.f.write(INDEX_HDR)
535 os.unlink(self.tmpname)
539 self.level = _golevel(self.level, self.f, [], None,
540 self.metastore, self.tmax)
541 self.count = self.rootlevel.count
544 self.f.write(struct.pack(FOOTER_SIG, self.count))
546 assert(self.level == None)
554 os.rename(self.tmpname, self.filename)
556 def _add(self, ename, entry):
557 if self.lastfile and self.lastfile <= ename:
558 raise Error('%r must come before %r'
559 % (''.join(ename), ''.join(self.lastfile)))
560 self.lastfile = ename
561 self.level = _golevel(self.level, self.f, ename, entry,
562 self.metastore, self.tmax)
564 def add(self, name, st, meta_ofs, hashgen = None):
565 endswith = name.endswith('/')
566 ename = pathsplit(name)
568 #log('add: %r %r\n' % (basename, name))
572 (gitmode, sha) = hashgen(name)
573 flags |= IX_HASHVALID
575 (gitmode, sha) = (0, EMPTY_SHA)
577 isdir = stat.S_ISDIR(st.st_mode)
578 assert(isdir == endswith)
579 e = NewEntry(basename, name, self.tmax,
580 st.st_dev, st.st_ino, st.st_nlink,
581 st.st_ctime, st.st_mtime, st.st_atime,
582 st.st_size, st.st_mode, gitmode, sha, flags,
586 meta_ofs = self.metastore.store(metadata.Metadata())
587 e = BlankNewEntry(basename, meta_ofs, self.tmax)
593 def add_ixentry(self, e):
594 e.children_ofs = e.children_n = 0
595 self._add(pathsplit(e.name), e)
597 def new_reader(self):
599 return Reader(self.tmpname)
602 def _slashappend_or_add_error(p, caller):
603 """Return p, after ensuring it has a single trailing slash if it names
604 a directory, unless there's an OSError, in which case, call
605 add_error() and return None."""
609 add_error('%s: %s' % (caller, e))
612 if stat.S_ISDIR(st.st_mode):
613 return slashappend(p)
617 def unique_resolved_paths(paths):
618 "Return a collection of unique resolved paths."
619 rps = (_slashappend_or_add_error(resolve_parent(p), 'unique_resolved_paths')
621 return frozenset((x for x in rps if x is not None))
624 def reduce_paths(paths):
627 rp = _slashappend_or_add_error(resolve_parent(p), 'reduce_paths')
629 xpaths.append((rp, slashappend(p) if rp.endswith('/') else p))
634 for (rp, p) in xpaths:
635 if prev and (prev == rp
636 or (prev.endswith('/') and rp.startswith(prev))):
637 continue # already superceded by previous path
638 paths.append((rp, p))
640 paths.sort(reverse=True)
645 def pfunc(count, total):
646 qprogress('bup: merging indexes (%d/%d)\r' % (count, total))
647 def pfinal(count, total):
648 progress('bup: merging indexes (%d/%d), done.\n' % (count, total))
649 return merge_iter(iters, 1024, pfunc, pfinal, key='name')