~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Aaron Bentley
  • Date: 2006-11-10 01:55:55 UTC
  • mto: This revision was merged to the branch mainline in revision 2127.
  • Revision ID: aaron.bentley@utoronto.ca-20061110015555-f48202744b630209
Ignore html docs (both kinds)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# (C) 2005 Canonical Ltd
2
 
 
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
 
 
7
#
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
12
 
 
 
12
#
13
13
# You should have received a copy of the GNU General Public License
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
32
32
import os, stat, time
33
33
import sha
34
34
 
35
 
from bzrlib.osutils import sha_file
 
35
from bzrlib.osutils import sha_file, pathjoin, safe_unicode
36
36
from bzrlib.trace import mutter, warning
37
37
from bzrlib.atomicfile import AtomicFile
38
 
 
39
 
 
 
38
from bzrlib.errors import BzrError
 
39
 
 
40
 
 
41
FP_MTIME_COLUMN = 1
 
42
FP_CTIME_COLUMN = 2
40
43
FP_MODE_COLUMN = 5
41
44
 
42
 
def _fingerprint(abspath):
43
 
    try:
44
 
        fs = os.lstat(abspath)
45
 
    except OSError:
46
 
        # might be missing, etc
47
 
        return None
48
 
 
49
 
    if stat.S_ISDIR(fs.st_mode):
50
 
        return None
51
 
 
52
 
    # we discard any high precision because it's not reliable; perhaps we
53
 
    # could do better on some systems?
54
 
    return (fs.st_size, long(fs.st_mtime),
55
 
            long(fs.st_ctime), fs.st_ino, fs.st_dev, fs.st_mode)
56
45
 
57
46
 
58
47
class HashCache(object):
91
80
    """
92
81
    needs_write = False
93
82
 
94
 
    def __init__(self, basedir):
95
 
        self.basedir = basedir
 
83
    def __init__(self, root, cache_file_name, mode=None):
 
84
        """Create a hash cache in base dir, and set the file mode to mode."""
 
85
        self.root = safe_unicode(root)
96
86
        self.hit_count = 0
97
87
        self.miss_count = 0
98
88
        self.stat_count = 0
100
90
        self.removed_count = 0
101
91
        self.update_count = 0
102
92
        self._cache = {}
 
93
        self._mode = mode
 
94
        self._cache_file_name = safe_unicode(cache_file_name)
103
95
 
104
96
    def cache_file_name(self):
105
 
        # FIXME: duplicate path logic here, this should be 
106
 
        # something like 'branch.controlfile'.
107
 
        return os.sep.join([self.basedir, '.bzr', 'stat-cache'])
 
97
        return self._cache_file_name
108
98
 
109
99
    def clear(self):
110
100
        """Discard all cached information.
114
104
            self.needs_write = True
115
105
            self._cache = {}
116
106
 
117
 
 
118
107
    def scan(self):
119
108
        """Scan all files and remove entries where the cache entry is obsolete.
120
109
        
121
110
        Obsolete entries are those where the file has been modified or deleted
122
111
        since the entry was inserted.        
123
112
        """
 
113
        # FIXME optimisation opportunity, on linux [and check other oses]:
 
114
        # rather than iteritems order, stat in inode order.
124
115
        prep = [(ce[1][3], path, ce) for (path, ce) in self._cache.iteritems()]
125
116
        prep.sort()
126
117
        
127
118
        for inum, path, cache_entry in prep:
128
 
            abspath = os.sep.join([self.basedir, path])
129
 
            fp = _fingerprint(abspath)
 
119
            abspath = pathjoin(self.root, path)
 
120
            fp = self._fingerprint(abspath)
130
121
            self.stat_count += 1
131
122
            
132
123
            cache_fp = cache_entry[1]
137
128
                self.needs_write = True
138
129
                del self._cache[path]
139
130
 
140
 
 
141
131
    def get_sha1(self, path):
142
132
        """Return the sha1 of a file.
143
133
        """
144
 
        abspath = os.sep.join([self.basedir, path])
 
134
        abspath = pathjoin(self.root, path)
145
135
        self.stat_count += 1
146
 
        file_fp = _fingerprint(abspath)
 
136
        file_fp = self._fingerprint(abspath)
147
137
        
148
138
        if not file_fp:
149
139
            # not a regular file or not existing
159
149
            cache_sha1, cache_fp = None, None
160
150
 
161
151
        if cache_fp == file_fp:
 
152
            ## mutter("hashcache hit for %s %r -> %s", path, file_fp, cache_sha1)
 
153
            ## mutter("now = %s", time.time())
162
154
            self.hit_count += 1
163
155
            return cache_sha1
164
156
        
165
157
        self.miss_count += 1
166
158
 
167
 
 
168
159
        mode = file_fp[FP_MODE_COLUMN]
169
160
        if stat.S_ISREG(mode):
170
 
            digest = sha_file(file(abspath, 'rb', buffering=65000))
 
161
            digest = self._really_sha1_file(abspath)
171
162
        elif stat.S_ISLNK(mode):
172
 
            link_target = os.readlink(abspath)
173
163
            digest = sha.new(os.readlink(abspath)).hexdigest()
174
164
        else:
175
165
            raise BzrError("file %r: unknown file stat mode: %o"%(abspath,mode))
176
166
 
177
 
        now = int(time.time())
178
 
        if file_fp[1] >= now or file_fp[2] >= now:
 
167
        # window of 3 seconds to allow for 2s resolution on windows,
 
168
        # unsynchronized file servers, etc.
 
169
        cutoff = self._cutoff_time()
 
170
        if file_fp[FP_MTIME_COLUMN] >= cutoff \
 
171
                or file_fp[FP_CTIME_COLUMN] >= cutoff:
179
172
            # changed too recently; can't be cached.  we can
180
173
            # return the result and it could possibly be cached
181
174
            # next time.
182
 
            self.danger_count += 1 
 
175
            #
 
176
            # the point is that we only want to cache when we are sure that any
 
177
            # subsequent modifications of the file can be detected.  If a
 
178
            # modification neither changes the inode, the device, the size, nor
 
179
            # the mode, then we can only distinguish it by time; therefore we
 
180
            # need to let sufficient time elapse before we may cache this entry
 
181
            # again.  If we didn't do this, then, for example, a very quick 1
 
182
            # byte replacement in the file might go undetected.
 
183
            ## mutter('%r modified too recently; not caching', path)
 
184
            self.danger_count += 1
183
185
            if cache_fp:
184
186
                self.removed_count += 1
185
187
                self.needs_write = True
186
188
                del self._cache[path]
187
189
        else:
 
190
            ## mutter('%r added to cache: now=%f, mtime=%d, ctime=%d',
 
191
            ##        path, time.time(), file_fp[FP_MTIME_COLUMN],
 
192
            ##        file_fp[FP_CTIME_COLUMN])
188
193
            self.update_count += 1
189
194
            self.needs_write = True
190
195
            self._cache[path] = (digest, file_fp)
191
196
        return digest
 
197
 
 
198
    def _really_sha1_file(self, abspath):
 
199
        """Calculate the SHA1 of a file by reading the full text"""
 
200
        return sha_file(file(abspath, 'rb', buffering=65000))
192
201
        
193
202
    def write(self):
194
203
        """Write contents of cache to file."""
195
 
        outf = AtomicFile(self.cache_file_name(), 'wb')
 
204
        outf = AtomicFile(self.cache_file_name(), 'wb', new_mode=self._mode)
196
205
        try:
197
 
            print >>outf, CACHE_HEADER,
 
206
            outf.write(CACHE_HEADER)
198
207
 
199
208
            for path, c  in self._cache.iteritems():
200
209
                assert '//' not in path, path
201
 
                outf.write(path.encode('utf-8'))
202
 
                outf.write('// ')
203
 
                print >>outf, c[0],     # hex sha1
204
 
                for fld in c[1]:
205
 
                    print >>outf, "%d" % fld,
206
 
                print >>outf
207
 
 
 
210
                line_info = [path.encode('utf-8'), '// ', c[0], ' ']
 
211
                line_info.append(' '.join([str(fld) for fld in c[1]]))
 
212
                line_info.append('\n')
 
213
                outf.write(''.join(line_info))
208
214
            outf.commit()
209
215
            self.needs_write = False
 
216
            ## mutter("write hash cache: %s hits=%d misses=%d stat=%d recent=%d updates=%d",
 
217
            ##        self.cache_file_name(), self.hit_count, self.miss_count,
 
218
            ##        self.stat_count,
 
219
            ##        self.danger_count, self.update_count)
210
220
        finally:
211
 
            if not outf.closed:
212
 
                outf.abort()
213
 
        
214
 
 
 
221
            outf.close()
215
222
 
216
223
    def read(self):
217
224
        """Reinstate cache from file.
226
233
        try:
227
234
            inf = file(fn, 'rb', buffering=65000)
228
235
        except IOError, e:
229
 
            mutter("failed to open %s: %s" % (fn, e))
 
236
            mutter("failed to open %s: %s", fn, e)
230
237
            # better write it now so it is valid
231
238
            self.needs_write = True
232
239
            return
233
240
 
234
 
 
235
241
        hdr = inf.readline()
236
242
        if hdr != CACHE_HEADER:
237
 
            mutter('cache header marker not found at top of %s; discarding cache'
238
 
                   % fn)
 
243
            mutter('cache header marker not found at top of %s;'
 
244
                   ' discarding cache', fn)
239
245
            self.needs_write = True
240
246
            return
241
247
 
262
268
            self._cache[path] = (sha1, fp)
263
269
 
264
270
        self.needs_write = False
 
271
 
 
272
    def _cutoff_time(self):
 
273
        """Return cutoff time.
 
274
 
 
275
        Files modified more recently than this time are at risk of being
 
276
        undetectably modified and so can't be cached.
 
277
        """
 
278
        return int(time.time()) - 3
265
279
           
266
 
 
267
 
 
268
 
        
 
280
    def _fingerprint(self, abspath):
 
281
        try:
 
282
            fs = os.lstat(abspath)
 
283
        except OSError:
 
284
            # might be missing, etc
 
285
            return None
 
286
        if stat.S_ISDIR(fs.st_mode):
 
287
            return None
 
288
        # we discard any high precision because it's not reliable; perhaps we
 
289
        # could do better on some systems?
 
290
        return (fs.st_size, long(fs.st_mtime),
 
291
                long(fs.st_ctime), fs.st_ino, fs.st_dev, fs.st_mode)