~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/hashcache.py

  • Committer: Aaron Bentley
  • Date: 2006-08-08 06:47:16 UTC
  • mto: (1910.2.43 format-bumps)
  • mto: This revision was merged to the branch mainline in revision 1922.
  • Revision ID: aaron.bentley@utoronto.ca-20060808064716-75bc465292c2708f
Ensure root entry always has a revision

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# (C) 2005 Canonical Ltd
2
 
 
 
1
# Copyright (C) 2005, 2006 by 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
206
            print >>outf, CACHE_HEADER,
198
207
 
204
213
                for fld in c[1]:
205
214
                    print >>outf, "%d" % fld,
206
215
                print >>outf
207
 
 
208
216
            outf.commit()
209
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,
 
220
            ##        self.stat_count,
 
221
            ##        self.danger_count, self.update_count)
210
222
        finally:
211
223
            if not outf.closed:
212
224
                outf.abort()
213
 
        
214
 
 
215
225
 
216
226
    def read(self):
217
227
        """Reinstate cache from file.
226
236
        try:
227
237
            inf = file(fn, 'rb', buffering=65000)
228
238
        except IOError, e:
229
 
            mutter("failed to open %s: %s" % (fn, e))
 
239
            mutter("failed to open %s: %s", fn, e)
230
240
            # better write it now so it is valid
231
241
            self.needs_write = True
232
242
            return
233
243
 
234
 
 
235
244
        hdr = inf.readline()
236
245
        if hdr != CACHE_HEADER:
237
 
            mutter('cache header marker not found at top of %s; discarding cache'
238
 
                   % fn)
 
246
            mutter('cache header marker not found at top of %s;'
 
247
                   ' discarding cache', fn)
239
248
            self.needs_write = True
240
249
            return
241
250
 
262
271
            self._cache[path] = (sha1, fp)
263
272
 
264
273
        self.needs_write = False
 
274
 
 
275
    def _cutoff_time(self):
 
276
        """Return cutoff time.
 
277
 
 
278
        Files modified more recently than this time are at risk of being
 
279
        undetectably modified and so can't be cached.
 
280
        """
 
281
        return int(time.time()) - 3
265
282
           
266
 
 
267
 
 
268
 
        
 
283
    def _fingerprint(self, abspath):
 
284
        try:
 
285
            fs = os.lstat(abspath)
 
286
        except OSError:
 
287
            # might be missing, etc
 
288
            return None
 
289
        if stat.S_ISDIR(fs.st_mode):
 
290
            return None
 
291
        # we discard any high precision because it's not reliable; perhaps we
 
292
        # could do better on some systems?
 
293
        return (fs.st_size, long(fs.st_mtime),
 
294
                long(fs.st_ctime), fs.st_ino, fs.st_dev, fs.st_mode)