1
# Copyright (C) 2005, 2006 Canonical Ltd
 
 
3
# This program is free software; you can redistribute it and/or modify
 
 
4
# it under the terms of the GNU General Public License as published by
 
 
5
# the Free Software Foundation; either version 2 of the License, or
 
 
6
# (at your option) any later version.
 
 
8
# This program is distributed in the hope that it will be useful,
 
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
11
# GNU General Public License for more details.
 
 
13
# You should have received a copy of the GNU General Public License
 
 
14
# along with this program; if not, write to the Free Software
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
17
# TODO: Up-front, stat all files in order and remove those which are deleted or 
 
 
18
# out-of-date.  Don't actually re-read them until they're needed.  That ought 
 
 
19
# to bring all the inodes into core so that future stats to them are fast, and 
 
 
20
# it preserves the nice property that any caller will always get up-to-date
 
 
21
# data except in unavoidable cases.
 
 
23
# TODO: Perhaps return more details on the file to avoid statting it
 
 
24
# again: nonexistent, file type, size, etc
 
 
26
# TODO: Perhaps use a Python pickle instead of a text file; might be faster.
 
 
30
CACHE_HEADER = "### bzr hashcache v5\n"
 
 
34
from bzrlib.osutils import sha_file, sha_string, pathjoin, safe_unicode
 
 
35
from bzrlib.trace import mutter, warning
 
 
36
from bzrlib.atomicfile import AtomicFile
 
 
37
from bzrlib.errors import BzrError
 
 
46
class HashCache(object):
 
 
47
    """Cache for looking up file SHA-1.
 
 
49
    Files are considered to match the cached value if the fingerprint
 
 
50
    of the file has not changed.  This includes its mtime, ctime,
 
 
51
    device number, inode number, and size.  This should catch
 
 
52
    modifications or replacement of the file by a new one.
 
 
54
    This may not catch modifications that do not change the file's
 
 
55
    size and that occur within the resolution window of the
 
 
56
    timestamps.  To handle this we specifically do not cache files
 
 
57
    which have changed since the start of the present second, since
 
 
58
    they could undetectably change again.
 
 
60
    This scheme may fail if the machine's clock steps backwards.
 
 
63
    This does not canonicalize the paths passed in; that should be
 
 
67
        Indexed by path, points to a two-tuple of the SHA-1 of the file.
 
 
71
        number of times files have been statted
 
 
74
        number of times files have been retrieved from the cache, avoiding a
 
 
78
        number of misses (times files have been completely re-read)
 
 
82
    def __init__(self, root, cache_file_name, mode=None):
 
 
83
        """Create a hash cache in base dir, and set the file mode to mode."""
 
 
84
        self.root = safe_unicode(root)
 
 
85
        self.root_utf8 = self.root.encode('utf8') # where is the filesystem encoding ?
 
 
90
        self.removed_count = 0
 
 
94
        self._cache_file_name = safe_unicode(cache_file_name)
 
 
96
    def cache_file_name(self):
 
 
97
        return self._cache_file_name
 
 
100
        """Discard all cached information.
 
 
102
        This does not reset the counters."""
 
 
104
            self.needs_write = True
 
 
108
        """Scan all files and remove entries where the cache entry is obsolete.
 
 
110
        Obsolete entries are those where the file has been modified or deleted
 
 
111
        since the entry was inserted.        
 
 
113
        # FIXME optimisation opportunity, on linux [and check other oses]:
 
 
114
        # rather than iteritems order, stat in inode order.
 
 
115
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
 
 
118
        for inum, path, cache_entry in prep:
 
 
119
            abspath = pathjoin(self.root, path)
 
 
120
            fp = self._fingerprint(abspath)
 
 
123
            cache_fp = cache_entry[1]
 
 
125
            if (not fp) or (cache_fp != fp):
 
 
126
                # not here or not a regular file anymore
 
 
127
                self.removed_count += 1
 
 
128
                self.needs_write = True
 
 
129
                del self._cache[path]
 
 
131
    def get_sha1(self, path, stat_value=None):
 
 
132
        """Return the sha1 of a file.
 
 
134
        if path.__class__ is str:
 
 
135
            abspath = pathjoin(self.root_utf8, path)
 
 
137
            abspath = pathjoin(self.root, path)
 
 
139
        file_fp = self._fingerprint(abspath, stat_value)
 
 
142
            # not a regular file or not existing
 
 
143
            if path in self._cache:
 
 
144
                self.removed_count += 1
 
 
145
                self.needs_write = True
 
 
146
                del self._cache[path]
 
 
149
        if path in self._cache:
 
 
150
            cache_sha1, cache_fp = self._cache[path]
 
 
152
            cache_sha1, cache_fp = None, None
 
 
154
        if cache_fp == file_fp:
 
 
155
            ## mutter("hashcache hit for %s %r -> %s", path, file_fp, cache_sha1)
 
 
156
            ## mutter("now = %s", time.time())
 
 
162
        mode = file_fp[FP_MODE_COLUMN]
 
 
163
        if stat.S_ISREG(mode):
 
 
164
            digest = self._really_sha1_file(abspath)
 
 
165
        elif stat.S_ISLNK(mode):
 
 
166
            digest = sha_string(os.readlink(abspath))
 
 
168
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
 
 
170
        # window of 3 seconds to allow for 2s resolution on windows,
 
 
171
        # unsynchronized file servers, etc.
 
 
172
        cutoff = self._cutoff_time()
 
 
173
        if file_fp[FP_MTIME_COLUMN] >= cutoff \
 
 
174
                or file_fp[FP_CTIME_COLUMN] >= cutoff:
 
 
175
            # changed too recently; can't be cached.  we can
 
 
176
            # return the result and it could possibly be cached
 
 
179
            # the point is that we only want to cache when we are sure that any
 
 
180
            # subsequent modifications of the file can be detected.  If a
 
 
181
            # modification neither changes the inode, the device, the size, nor
 
 
182
            # the mode, then we can only distinguish it by time; therefore we
 
 
183
            # need to let sufficient time elapse before we may cache this entry
 
 
184
            # again.  If we didn't do this, then, for example, a very quick 1
 
 
185
            # byte replacement in the file might go undetected.
 
 
186
            ## mutter('%r modified too recently; not caching', path)
 
 
187
            self.danger_count += 1
 
 
189
                self.removed_count += 1
 
 
190
                self.needs_write = True
 
 
191
                del self._cache[path]
 
 
193
            ## mutter('%r added to cache: now=%f, mtime=%d, ctime=%d',
 
 
194
            ##        path, time.time(), file_fp[FP_MTIME_COLUMN],
 
 
195
            ##        file_fp[FP_CTIME_COLUMN])
 
 
196
            self.update_count += 1
 
 
197
            self.needs_write = True
 
 
198
            self._cache[path] = (digest, file_fp)
 
 
201
    def _really_sha1_file(self, abspath):
 
 
202
        """Calculate the SHA1 of a file by reading the full text"""
 
 
203
        return sha_file(file(abspath, 'rb', buffering=65000))
 
 
206
        """Write contents of cache to file."""
 
 
207
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
 
 
209
            outf.write(CACHE_HEADER)
 
 
211
            for path, c  in self._cache.iteritems():
 
 
212
                line_info = [path.encode('utf-8'), '// ', c[0], ' ']
 
 
213
                line_info.append(' '.join([str(fld) for fld in c[1]]))
 
 
214
                line_info.append('\n')
 
 
215
                outf.write(''.join(line_info))
 
 
217
            self.needs_write = False
 
 
218
            ## mutter("write hash cache: %s hits=%d misses=%d stat=%d recent=%d updates=%d",
 
 
219
            ##        self.cache_file_name(), self.hit_count, self.miss_count,
 
 
221
            ##        self.danger_count, self.update_count)
 
 
226
        """Reinstate cache from file.
 
 
228
        Overwrites existing cache.
 
 
230
        If the cache file has the wrong version marker, this just clears 
 
 
234
        fn = self.cache_file_name()
 
 
236
            inf = file(fn, 'rb', buffering=65000)
 
 
238
            mutter("failed to open %s: %s", fn, e)
 
 
239
            # better write it now so it is valid
 
 
240
            self.needs_write = True
 
 
244
        if hdr != CACHE_HEADER:
 
 
245
            mutter('cache header marker not found at top of %s;'
 
 
246
                   ' discarding cache', fn)
 
 
247
            self.needs_write = True
 
 
252
            path = l[:pos].decode('utf-8')
 
 
253
            if path in self._cache:
 
 
254
                warning('duplicated path %r in cache' % path)
 
 
258
            fields = l[pos:].split(' ')
 
 
260
                warning("bad line in hashcache: %r" % l)
 
 
265
                warning("bad sha1 in hashcache: %r" % sha1)
 
 
268
            fp = tuple(map(long, fields[1:]))
 
 
270
            self._cache[path] = (sha1, fp)
 
 
272
        self.needs_write = False
 
 
274
    def _cutoff_time(self):
 
 
275
        """Return cutoff time.
 
 
277
        Files modified more recently than this time are at risk of being
 
 
278
        undetectably modified and so can't be cached.
 
 
280
        return int(time.time()) - 3
 
 
282
    def _fingerprint(self, abspath, stat_value=None):
 
 
283
        if stat_value is None:
 
 
285
                stat_value = os.lstat(abspath)
 
 
287
                # might be missing, etc
 
 
289
        if stat.S_ISDIR(stat_value.st_mode):
 
 
291
        # we discard any high precision because it's not reliable; perhaps we
 
 
292
        # could do better on some systems?
 
 
293
        return (stat_value.st_size, long(stat_value.st_mtime),
 
 
294
                long(stat_value.st_ctime), stat_value.st_ino, 
 
 
295
                stat_value.st_dev, stat_value.st_mode)