/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Martin Pool
  • Date: 2005-07-08 02:40:22 UTC
  • Revision ID: mbp@sourcefrog.net-20050708024021-731a320c625619f6
- code to re-read hashcache from file

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 by Canonical Ltd
 
1
# (C) 2005 Canonical Ltd
2
2
 
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
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.
22
 
 
23
 
# TODO: Perhaps return more details on the file to avoid statting it
24
 
# again: nonexistent, file type, size, etc
25
 
 
26
 
# TODO: Perhaps use a Python pickle instead of a text file; might be faster.
27
 
 
28
 
 
29
 
 
30
 
CACHE_HEADER = "### bzr hashcache v5\n"
31
 
 
32
 
import os, stat, time
33
 
import sha
34
 
 
35
 
from bzrlib.osutils import sha_file, pathjoin, safe_unicode
36
 
from bzrlib.trace import mutter, warning
37
 
from bzrlib.atomicfile import AtomicFile
38
 
from bzrlib.errors import BzrError
39
 
 
40
 
 
41
 
FP_MTIME_COLUMN = 1
42
 
FP_CTIME_COLUMN = 2
43
 
FP_MODE_COLUMN = 5
 
17
 
 
18
 
 
19
 
 
20
CACHE_HEADER = "### bzr statcache v5\n"
 
21
 
44
22
 
45
23
def _fingerprint(abspath):
 
24
    import os, stat
 
25
 
46
26
    try:
47
27
        fs = os.lstat(abspath)
48
28
    except OSError:
52
32
    if stat.S_ISDIR(fs.st_mode):
53
33
        return None
54
34
 
55
 
    # we discard any high precision because it's not reliable; perhaps we
56
 
    # could do better on some systems?
57
 
    return (fs.st_size, long(fs.st_mtime),
58
 
            long(fs.st_ctime), fs.st_ino, fs.st_dev, fs.st_mode)
 
35
    return (fs.st_size, fs.st_mtime,
 
36
            fs.st_ctime, fs.st_ino, fs.st_dev)
59
37
 
60
38
 
61
39
class HashCache(object):
92
70
    miss_count
93
71
        number of misses (times files have been completely re-read)
94
72
    """
95
 
    needs_write = False
96
 
 
97
 
    def __init__(self, root, cache_file_name, mode=None):
98
 
        """Create a hash cache in base dir, and set the file mode to mode."""
99
 
        self.root = safe_unicode(root)
 
73
    def __init__(self, basedir):
 
74
        self.basedir = basedir
100
75
        self.hit_count = 0
101
76
        self.miss_count = 0
102
77
        self.stat_count = 0
103
78
        self.danger_count = 0
104
 
        self.removed_count = 0
105
 
        self.update_count = 0
 
79
 
106
80
        self._cache = {}
107
 
        self._mode = mode
108
 
        self._cache_file_name = safe_unicode(cache_file_name)
109
81
 
110
 
    def cache_file_name(self):
111
 
        return self._cache_file_name
112
82
 
113
83
    def clear(self):
114
84
        """Discard all cached information.
115
85
 
116
86
        This does not reset the counters."""
117
 
        if self._cache:
118
 
            self.needs_write = True
119
 
            self._cache = {}
120
 
 
121
 
    def scan(self):
122
 
        """Scan all files and remove entries where the cache entry is obsolete.
123
 
        
124
 
        Obsolete entries are those where the file has been modified or deleted
125
 
        since the entry was inserted.        
126
 
        """
127
 
        # FIXME optimisation opportunity, on linux [and check other oses]:
128
 
        # rather than iteritems order, stat in inode order.
129
 
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
130
 
        prep.sort()
131
 
        
132
 
        for inum, path, cache_entry in prep:
133
 
            abspath = pathjoin(self.root, path)
134
 
            fp = _fingerprint(abspath)
135
 
            self.stat_count += 1
136
 
            
137
 
            cache_fp = cache_entry[1]
138
 
    
139
 
            if (not fp) or (cache_fp != fp):
140
 
                # not here or not a regular file anymore
141
 
                self.removed_count += 1
142
 
                self.needs_write = True
143
 
                del self._cache[path]
 
87
        self._cache_sha1 = {}
144
88
 
145
89
 
146
90
    def get_sha1(self, path):
147
 
        """Return the sha1 of a file.
 
91
        """Return the hex SHA-1 of the contents of the file at path.
 
92
 
 
93
        XXX: If the file does not exist or is not a plain file???
148
94
        """
149
 
        abspath = pathjoin(self.root, path)
 
95
 
 
96
        import os, time
 
97
        from bzrlib.osutils import sha_file
 
98
        
 
99
        abspath = os.path.join(self.basedir, path)
 
100
        fp = _fingerprint(abspath)
 
101
        c = self._cache.get(path)
 
102
        if c:
 
103
            cache_sha1, cache_fp = c
 
104
        else:
 
105
            cache_sha1, cache_fp = None, None
 
106
 
150
107
        self.stat_count += 1
151
 
        file_fp = _fingerprint(abspath)
152
 
        
153
 
        if not file_fp:
154
 
            # not a regular file or not existing
155
 
            if path in self._cache:
156
 
                self.removed_count += 1
157
 
                self.needs_write = True
158
 
                del self._cache[path]
159
 
            return None        
160
 
 
161
 
        if path in self._cache:
162
 
            cache_sha1, cache_fp = self._cache[path]
163
 
        else:
164
 
            cache_sha1, cache_fp = None, None
165
 
 
166
 
        if cache_fp == file_fp:
 
108
 
 
109
        if not fp:
 
110
            # not a regular file
 
111
            return None
 
112
        elif cache_fp and (cache_fp == fp):
167
113
            self.hit_count += 1
168
114
            return cache_sha1
169
 
        
170
 
        self.miss_count += 1
171
 
 
172
 
 
173
 
        mode = file_fp[FP_MODE_COLUMN]
174
 
        if stat.S_ISREG(mode):
175
 
            digest = sha_file(file(abspath, 'rb', buffering=65000))
176
 
        elif stat.S_ISLNK(mode):
177
 
            digest = sha.new(os.readlink(abspath)).hexdigest()
178
 
        else:
179
 
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
180
 
 
181
 
        now = int(time.time())
182
 
        if file_fp[FP_MTIME_COLUMN] >= now or file_fp[FP_CTIME_COLUMN] >= now:
183
 
            # changed too recently; can't be cached.  we can
184
 
            # return the result and it could possibly be cached
185
 
            # next time.
186
 
            #
187
 
            # the point is that we only want to cache when we are sure that any
188
 
            # subsequent modifications of the file can be detected.  If a
189
 
            # modification neither changes the inode, the device, the size, nor
190
 
            # the mode, then we can only distinguish it by time; therefore we
191
 
            # need to let sufficient time elapse before we may cache this entry
192
 
            # again.  If we didn't do this, then, for example, a very quick 1
193
 
            # byte replacement in the file might go undetected.
194
 
            self.danger_count += 1 
195
 
            if cache_fp:
196
 
                self.removed_count += 1
197
 
                self.needs_write = True
198
 
                del self._cache[path]
199
 
        else:
200
 
            self.update_count += 1
201
 
            self.needs_write = True
202
 
            self._cache[path] = (digest, file_fp)
203
 
        return digest
204
 
        
205
 
    def write(self):
 
115
        else:
 
116
            self.miss_count += 1
 
117
            digest = sha_file(file(abspath, 'rb'))
 
118
 
 
119
            now = int(time.time())
 
120
            if fp[1] >= now or fp[2] >= now:
 
121
                # changed too recently; can't be cached.  we can
 
122
                # return the result and it could possibly be cached
 
123
                # next time.
 
124
                self.danger_count += 1 
 
125
                if cache_fp:
 
126
                    del self._cache[path]
 
127
            else:
 
128
                self._cache[path] = (digest, fp)
 
129
 
 
130
            return digest
 
131
 
 
132
 
 
133
 
 
134
    def write(self, cachefn):
206
135
        """Write contents of cache to file."""
207
 
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
 
136
        from atomicfile import AtomicFile
 
137
 
 
138
        outf = AtomicFile(cachefn, 'wb')
208
139
        try:
209
140
            print >>outf, CACHE_HEADER,
210
141
 
216
147
                for fld in c[1]:
217
148
                    print >>outf, "%d" % fld,
218
149
                print >>outf
 
150
 
219
151
            outf.commit()
220
 
            self.needs_write = False
221
 
            mutter("write hash cache: %s hits=%d misses=%d stat=%d recent=%d updates=%d",
222
 
                   self.cache_file_name(), self.hit_count, self.miss_count,
223
 
                   self.stat_count,
224
 
                   self.danger_count, self.update_count)
225
152
        finally:
226
153
            if not outf.closed:
227
154
                outf.abort()
228
 
 
229
 
    def read(self):
 
155
        
 
156
 
 
157
 
 
158
    def read(self, cachefn):
230
159
        """Reinstate cache from file.
231
160
 
232
161
        Overwrites existing cache.
233
162
 
234
163
        If the cache file has the wrong version marker, this just clears 
235
164
        the cache."""
 
165
        from bzrlib.trace import mutter, warning
 
166
 
 
167
        inf = file(cachefn, 'rb')
236
168
        self._cache = {}
237
169
 
238
 
        fn = self.cache_file_name()
239
 
        try:
240
 
            inf = file(fn, 'rb', buffering=65000)
241
 
        except IOError, e:
242
 
            mutter("failed to open %s: %s", fn, e)
243
 
            # better write it now so it is valid
244
 
            self.needs_write = True
245
 
            return
246
 
 
247
 
 
248
170
        hdr = inf.readline()
249
171
        if hdr != CACHE_HEADER:
250
 
            mutter('cache header marker not found at top of %s;'
251
 
                   ' discarding cache', fn)
252
 
            self.needs_write = True
 
172
            mutter('cache header marker not found at top of %s; discarding cache'
 
173
                   % cachefn)
253
174
            return
254
175
 
255
176
        for l in inf:
261
182
 
262
183
            pos += 3
263
184
            fields = l[pos:].split(' ')
264
 
            if len(fields) != 7:
 
185
            if len(fields) != 6:
265
186
                warning("bad line in hashcache: %r" % l)
266
187
                continue
267
188
 
274
195
 
275
196
            self._cache[path] = (sha1, fp)
276
197
 
277
 
        self.needs_write = False
278
 
           
279
 
 
280
198
 
281
199