Source

trac-ticketlinks / trac / versioncontrol / cache.py

jonas 26623b3 
cmlenz efff209 
jonas 7c60ab2 
cmlenz efff209 
cmlenz d6c17a5 
cmlenz efff209 
cmlenz d6c17a5 

cmlenz 47c3427 
cmlenz efff209 
cmlenz d6c17a5 

cmlenz 47c3427 
cmlenz efff209 


cboos cc00de2 
jonas 576c8e9 
rblank 5530e4d 
cboos 0242c59 
rblank c41794b 
jruigrok 4dc6905 
cboos 465033c 
cmlenz efff209 






cboos a33451d 




cmlenz efff209 


cboos 2618ae8 

rblank 86df883 

cboos 465033c 

cmlenz efff209 
rblank 22799a0 

rblank 5530e4d 
cboos 465033c 
cmlenz efff209 



cboos 465033c 


cboos 522f5d3 
cboos 465033c 



cboos 522f5d3 
cmlenz efff209 
rblank 138063d 
cboos 465033c 


cmlenz efff209 
cboos 7c4ecda 
cboos 465033c 
cboos 3b9cffd 
cboos 7c4ecda 
cboos 465033c 
cboos 1f2b282 
rblank c41794b 
cboos 7c4ecda 
cboos a33451d 
cboos 465033c 
cboos a33451d 

cboos 7c4ecda 
cboos 44fbb29 

rblank 138063d 
cboos 6a74248 

cboos c5fc48f 
cboos 6a74248 




rblank efa4205 
cboos 6a74248 

rblank c41794b 
cboos 262879f 


rblank c41794b 
rblank efa4205 
cboos 6a74248 
rblank 5530e4d 


cboos 465033c 
cboos 3b9cffd 
cboos 465033c 








cboos c5fc48f 
rblank 5530e4d 












cboos edca29a 
rblank 5530e4d 

cboos c5fc48f 
rblank 5530e4d 













rblank 91d4a68 




rblank 5530e4d 






















cboos edca29a 
rblank 5530e4d 

cboos 2f6e122 

cboos 465033c 

cboos edca29a 
cboos 465033c 


cboos edca29a 
cboos d5580b0 
cboos a33451d 
cboos edca29a 
cboos d5580b0 
cboos 465033c 
cboos a33451d 

cboos edca29a 
cboos 465033c 
cboos edca29a 

cboos 465033c 

cboos a33451d 


cboos f6c83c9 

rblank a74e304 



cboos a33451d 

cboos 465033c 

cboos a33451d 


rblank 138063d 
cboos a33451d 

cboos c5fc48f 
rblank 5530e4d 
cboos edca29a 

rblank efa4205 
cboos a33451d 


cboos 465033c 
cboos a33451d 




cmlenz efff209 

cboos a33451d 
cboos 465033c 
rblank 138063d 
rblank 5530e4d 
cboos 465033c 
cboos c5fc48f 
rblank 5530e4d 











































cboos edca29a 
rblank 5530e4d 




cboos 465033c 
rblank 5530e4d 

cboos edca29a 
cboos 465033c 
cboos a33451d 
cboos 465033c 


cmlenz efff209 

cboos 465033c 
cmlenz efff209 
rblank 51f54b5 


rblank 8ed0d32 
rblank 51f54b5 
rblank 138063d 
rblank efa4205 
cboos 465033c 
rblank 8ed0d32 
rblank 51f54b5 

rblank efa4205 

rblank 51f54b5 
rblank efa4205 

rblank 51f54b5 


rblank 138063d 
rblank 8ed0d32 
rblank efa4205 


cboos 465033c 
rblank 51f54b5 
rblank 8ed0d32 
cboos e3d3584 
cboos 465033c 
cboos 0482b1d 
cmlenz efff209 



rblank 5530e4d 
cmlenz efff209 
cboos 0e91efc 
cboos 853aa5c 


cboos 465033c 
cmlenz efff209 
cboos 35bbfbb 
cboos 853aa5c 


cboos 465033c 
cboos 2618ae8 
cboos 0e91efc 
rblank 138063d 
cboos 465033c 
cboos 2618ae8 
cboos 465033c 
rblank efa4205 

cboos 2618ae8 

cboos 853aa5c 
rblank f47147f 
cboos 465033c 
rblank 8d3b639 
cboos 853aa5c 
cboos 2618ae8 
rblank f47147f 
cboos 465033c 
rblank f47147f 
cboos 2618ae8 

rblank efa4205 

cboos 2618ae8 
cboos 3b9cffd 
cboos 2618ae8 

rblank efa4205 
cmlenz efff209 
cboos 2e06040 
cboos 465033c 

cboos 2e06040 
cboos af49681 
cboos 465033c 

cboos 183d992 




cboos 465033c 

cboos d42320e 
cboos 465033c 







cboos 183d992 
rblank 138063d 



cboos d42320e 



cboos 1f2b282 
cboos 465033c 



cboos 35bbfbb 
cmlenz efff209 


cboos 465033c 


cboos 3b9cffd 
cmlenz efff209 
cboos 465033c 
rblank 138063d 
cboos 3bb6bad 

jonas 576c8e9 
rblank c41794b 
cboos d42320e 

cboos 3bb6bad 
cboos 4eb1dad 
cmlenz efff209 

cboos 465033c 
cboos 3b9cffd 
cmlenz 33bf728 
cboos 465033c 
rblank 138063d 

cboos a21bcd8 
cmlenz efff209 

cboos d42320e 
cboos fbf077e 

rblank 138063d 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2009 Edgewall Software
# Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Christopher Lenz <cmlenz@gmx.de>

import os

from trac.cache import cached
from trac.core import TracError
from trac.util.datefmt import from_utimestamp, to_utimestamp
from trac.util.translation import _
from trac.versioncontrol import Changeset, Node, Repository, NoSuchChangeset


_kindmap = {'D': Node.DIRECTORY, 'F': Node.FILE}
_actionmap = {'A': Changeset.ADD, 'C': Changeset.COPY,
              'D': Changeset.DELETE, 'E': Changeset.EDIT,
              'M': Changeset.MOVE}

CACHE_REPOSITORY_DIR = 'repository_dir'
CACHE_YOUNGEST_REV = 'youngest_rev'

CACHE_METADATA_KEYS = (CACHE_REPOSITORY_DIR, CACHE_YOUNGEST_REV)


class CachedRepository(Repository):

    has_linear_changesets = False

    scope = property(lambda self: self.repos.scope)
    
    def __init__(self, env, repos, log):
        self.env = env
        self.repos = repos
        self._metadata_id = (CachedRepository.__module__ + '.'
                             + CachedRepository.__name__ + '.metadata:'
                             + str(self.repos.id))
        Repository.__init__(self, repos.name, repos.params, log)

    def close(self):
        self.repos.close()

    def get_base(self):
        return self.repos.get_base()
        
    def get_quickjump_entries(self, rev):
        return self.repos.get_quickjump_entries(self.normalize_rev(rev))

    def get_path_url(self, path, rev):
        return self.repos.get_path_url(path, rev)

    def get_changeset(self, rev):
        return CachedChangeset(self, self.normalize_rev(rev), self.env)

    def get_changeset_uid(self, rev):
        return self.repos.get_changeset_uid(rev)

    def get_changesets(self, start, stop):
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute("SELECT rev FROM revision "
                       "WHERE repos=%s AND time >= %s AND time < %s "
                       "ORDER BY time DESC, rev DESC",
                       (self.id, to_utimestamp(start), to_utimestamp(stop)))
        for rev, in cursor:
            try:
                yield self.get_changeset(rev)
            except NoSuchChangeset:
                pass # skip changesets currently being resync'ed

    def sync_changeset(self, rev):
        cset = self.repos.get_changeset(rev)
        srev = self.db_rev(cset.rev)
        old_cset = [None]

        @self.env.with_transaction()
        def do_sync(db):
            cursor = db.cursor()
            cursor.execute("""
                SELECT time,author,message FROM revision
                WHERE repos=%s AND rev=%s
                """, (self.id, srev))
            for time, author, message in cursor:
                old_cset[0] = Changeset(self.repos, cset.rev, message, author,
                                        from_utimestamp(time))
            cursor.execute("""
                UPDATE revision SET time=%s, author=%s, message=%s
                WHERE repos=%s AND rev=%s
                """, (to_utimestamp(cset.date), cset.author, cset.message,
                      self.id, srev))
        return old_cset[0]

    @cached('_metadata_id')
    def metadata(self, db):
        """Retrieve data for the cached `metadata` attribute."""
        cursor = db.cursor()
        cursor.execute("SELECT name, value FROM repository "
                       "WHERE id=%%s AND name IN (%s)" % 
                       ','.join(['%s'] * len(CACHE_METADATA_KEYS)),
                       (self.id,) + CACHE_METADATA_KEYS)
        return dict(cursor)

    def sync(self, feedback=None, clean=False):
        if clean:
            self.log.info('Cleaning cache')
            @self.env.with_transaction()
            def do_clean(db):
                cursor = db.cursor()
                cursor.execute("DELETE FROM revision WHERE repos=%s",
                               (self.id,))
                cursor.execute("DELETE FROM node_change WHERE repos=%s",
                               (self.id,))
                cursor.executemany("""
                    DELETE FROM repository WHERE id=%s AND name=%s
                    """, [(self.id, k) for k in CACHE_METADATA_KEYS])
                cursor.executemany("""
                    INSERT INTO repository (id,name,value) VALUES (%s,%s,%s)
                    """, [(self.id, k, '') for k in CACHE_METADATA_KEYS])
                del self.metadata

        metadata = self.metadata
        
        @self.env.with_transaction()
        def do_transaction(db):
            cursor = db.cursor()
            invalidate = False
    
            # -- check that we're populating the cache for the correct
            #    repository
            repository_dir = metadata.get(CACHE_REPOSITORY_DIR)
            if repository_dir:
                # directory part of the repo name can vary on case insensitive
                # fs
                if os.path.normcase(repository_dir) \
                        != os.path.normcase(self.name):
                    self.log.info("'repository_dir' has changed from %r to %r",
                                  repository_dir, self.name)
                    raise TracError(_("The repository directory has changed, "
                                      "you should resynchronize the "
                                      "repository with: trac-admin $ENV "
                                      "repository resync '%(reponame)s'",
                                      reponame=self.reponame or '(default)'))
            elif repository_dir is None: # 
                self.log.info('Storing initial "repository_dir": %s',
                              self.name)
                cursor.execute("""
                    INSERT INTO repository (id,name,value) VALUES (%s,%s,%s)
                    """, (self.id, CACHE_REPOSITORY_DIR, self.name))
                invalidate = True
            else: # 'repository_dir' cleared by a resync
                self.log.info('Resetting "repository_dir": %s', self.name)
                cursor.execute("""
                    UPDATE repository SET value=%s WHERE id=%s AND name=%s
                    """, (self.name, self.id, CACHE_REPOSITORY_DIR))
                invalidate = True
    
            # -- insert a 'youngeset_rev' for the repository if necessary
            if metadata.get(CACHE_YOUNGEST_REV) is None:
                cursor.execute("""
                    INSERT INTO repository (id,name,value) VALUES (%s,%s,%s)
                    """, (self.id, CACHE_YOUNGEST_REV, ''))
                invalidate = True
    
            if invalidate:
                del self.metadata

        # -- retrieve the youngest revision in the repository and the youngest
        #    revision cached so far
        self.repos.clear()
        repos_youngest = self.repos.youngest_rev
        youngest = metadata.get(CACHE_YOUNGEST_REV)

        # -- verify and normalize youngest revision
        if youngest:
            youngest = self.repos.normalize_rev(youngest)
            if not youngest:
                self.log.debug('normalize_rev failed (youngest_rev=%r)',
                               self.youngest_rev)
        else:
            self.log.debug('cache metadata undefined (youngest_rev=%r)',
                           self.youngest_rev)
            youngest = None

        # -- compare them and try to resync if different
        next_youngest = None
        if youngest != repos_youngest:
            self.log.info("repos rev [%s] != cached rev [%s]",
                          repos_youngest, youngest)
            if youngest:
                next_youngest = self.repos.next_rev(youngest)
            else:
                try:
                    next_youngest = self.repos.oldest_rev
                    # Ugly hack needed because doing that everytime in 
                    # oldest_rev suffers from horrendeous performance (#5213)
                    if self.repos.scope != '/' and not \
                            self.repos.has_node('/', next_youngest):
                        next_youngest = self.repos.next_rev(next_youngest,
                                find_initial_rev=True)
                    next_youngest = self.repos.normalize_rev(next_youngest)
                except TracError:
                    # can't normalize oldest_rev: repository was empty
                    return

            if next_youngest is None: # nothing to cache yet
                return
            srev = self.db_rev(next_youngest)

            # 0. first check if there's no (obvious) resync in progress
            db = self.env.get_read_db()
            cursor = db.cursor()
            cursor.execute("""
               SELECT rev FROM revision WHERE repos=%s AND rev=%s
               """, (self.id, srev))
            for rev, in cursor:
                # already there, but in progress, so keep ''previous''
                # notion of 'youngest'
                self.repos.clear(youngest_rev=youngest)
                return

            # 1. prepare for resyncing
            #    (there still might be a race condition at this point)

            kindmap = dict(zip(_kindmap.values(), _kindmap.keys()))
            actionmap = dict(zip(_actionmap.values(), _actionmap.keys()))

            while next_youngest is not None:
                srev = self.db_rev(next_youngest)
                exit = [False]
                
                @self.env.with_transaction()
                def do_transaction(db):
                    cursor = db.cursor()
                    
                    # 1.1 Attempt to resync the 'revision' table
                    self.log.info("Trying to sync revision [%s]",
                                  next_youngest)
                    cset = self.repos.get_changeset(next_youngest)
                    try:
                        cursor.execute("""
                            INSERT INTO revision
                                (repos,rev,time,author,message)
                            VALUES (%s,%s,%s,%s,%s)
                            """, (self.id, srev, to_utimestamp(cset.date),
                                  cset.author, cset.message))
                    except Exception, e: # *another* 1.1. resync attempt won 
                        self.log.warning('Revision %s already cached: %r',
                                         next_youngest, e)
                        # also potentially in progress, so keep ''previous''
                        # notion of 'youngest'
                        self.repos.clear(youngest_rev=youngest)
                        # FIXME: This aborts a containing transaction
                        db.rollback()
                        exit[0] = True
                        return
    
                    # 1.2. now *only* one process was able to get there
                    #      (i.e. there *shouldn't* be any race condition here)
    
                    for path, kind, action, bpath, brev in cset.get_changes():
                        self.log.debug("Caching node change in [%s]: %r",
                                       next_youngest,
                                       (path, kind, action, bpath, brev))
                        kind = kindmap[kind]
                        action = actionmap[action]
                        cursor.execute("""
                            INSERT INTO node_change
                                (repos,rev,path,node_type,
                                 change_type,base_path,base_rev)
                            VALUES (%s,%s,%s,%s,%s,%s,%s)
                            """, (self.id, srev, path, kind, action, bpath,
                                  brev))
    
                    # 1.3. update 'youngest_rev' metadata 
                    #      (minimize possibility of failures at point 0.)
                    cursor.execute("""
                        UPDATE repository SET value=%s WHERE id=%s AND name=%s
                        """, (str(next_youngest), self.id, CACHE_YOUNGEST_REV))
                    del self.metadata

                if exit[0]:
                    return
                
                # 1.4. iterate (1.1 should always succeed now)
                youngest = next_youngest
                next_youngest = self.repos.next_rev(next_youngest)

                # 1.5. provide some feedback
                if feedback:
                    feedback(youngest)

    def get_node(self, path, rev=None):
        return self.repos.get_node(path, self.normalize_rev(rev))

    def _get_node_revs(self, path, last=None, first=None):
        """Return the revisions affecting `path` between `first` and `last`
        revisions.
        """
        last = self.normalize_rev(last)
        slast = self.db_rev(last)
        node = self.get_node(path, last)    # Check node existence
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        if first is None:
            cursor.execute("SELECT rev FROM node_change "
                           "WHERE repos=%s AND rev<=%s "
                           "  AND path=%s "
                           "  AND change_type IN ('A', 'C', 'M') "
                           "ORDER BY rev DESC LIMIT 1",
                           (self.id, slast, path))
            first = 0
            for row in cursor:
                first = int(row[0])
        sfirst = self.db_rev(first)
        cursor.execute("SELECT DISTINCT rev FROM node_change "
                       "WHERE repos=%%s AND rev>=%%s AND rev<=%%s "
                       " AND (path=%%s OR path %s)" % db.like(),
                       (self.id, sfirst, slast, path,
                        db.like_escape(path + '/') + '%'))
        return [int(row[0]) for row in cursor]

    def has_node(self, path, rev=None):
        return self.repos.has_node(path, self.normalize_rev(rev))

    def get_oldest_rev(self):
        return self.repos.oldest_rev

    def get_youngest_rev(self):
        return self.rev_db(self.metadata.get(CACHE_YOUNGEST_REV))

    def previous_rev(self, rev, path=''):
        if self.has_linear_changesets:
            return self._next_prev_rev('<', rev, path)
        else:
            return self.repos.previous_rev(self.normalize_rev(rev), path)

    def next_rev(self, rev, path=''):
        if self.has_linear_changesets:
            return self._next_prev_rev('>', rev, path)
        else:
            return self.repos.next_rev(self.normalize_rev(rev), path)

    def _next_prev_rev(self, direction, rev, path=''):
        srev = self.db_rev(rev)
        db = self.env.get_db_cnx()
        # the changeset revs are sequence of ints:
        sql = "SELECT rev FROM node_change WHERE repos=%s AND " + \
              "rev" + direction + "%s"
        args = [self.id, srev]

        if path:
            path = path.lstrip('/')
            # changes on path itself or its children
            sql += " AND (path=%s OR path " + db.like()
            args.extend((path, db.like_escape(path + '/') + '%'))
            # deletion of path ancestors
            components = path.lstrip('/').split('/')
            parents = ','.join(('%s',) * len(components))
            sql += " OR (path IN (" + parents + ") AND change_type='D'))"
            for i in range(1, len(components) + 1):
                args.append('/'.join(components[:i]))

        sql += " ORDER BY rev" + (direction == '<' and " DESC" or "") \
               + " LIMIT 1"
        
        cursor = db.cursor()
        cursor.execute(sql, args)
        for rev, in cursor:
            return int(rev)

    def rev_older_than(self, rev1, rev2):
        return self.repos.rev_older_than(self.normalize_rev(rev1),
                                         self.normalize_rev(rev2))

    def get_path_history(self, path, rev=None, limit=None):
        return self.repos.get_path_history(path, self.normalize_rev(rev),
                                           limit)

    def normalize_path(self, path):
        return self.repos.normalize_path(path)

    def normalize_rev(self, rev):
        if rev is None or isinstance(rev, basestring) and \
               rev.lower() in ('', 'head', 'latest', 'youngest'):
            return self.rev_db(self.youngest_rev or 0)
        else:
            try:
                rev = int(rev)
                if rev <= self.youngest_rev:
                    return rev
            except (ValueError, TypeError):
                pass
            raise NoSuchChangeset(rev)

    def db_rev(self, rev):
        """Convert a revision to its representation in the database."""
        return str(rev)

    def rev_db(self, rev):
        """Convert a revision from its representation in the database."""
        return rev

    def get_changes(self, old_path, old_rev, new_path, new_rev, 
                    ignore_ancestry=1):
        return self.repos.get_changes(old_path, self.normalize_rev(old_rev),
                                      new_path, self.normalize_rev(new_rev), 
                                      ignore_ancestry)


class CachedChangeset(Changeset):

    def __init__(self, repos, rev, env):
        self.env = env
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute("SELECT time,author,message FROM revision "
                       "WHERE repos=%s AND rev=%s",
                       (repos.id, repos.db_rev(rev)))
        row = cursor.fetchone()
        if row:
            _date, author, message = row
            date = from_utimestamp(_date)
            Changeset.__init__(self, repos, repos.rev_db(rev), message, author,
                               date)
        else:
            raise NoSuchChangeset(rev)

    def get_changes(self):
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute("SELECT path,node_type,change_type,base_path,base_rev "
                       "FROM node_change WHERE repos=%s AND rev=%s "
                       "ORDER BY path",
                       (self.repos.id, self.repos.db_rev(self.rev)))
        for path, kind, change, base_path, base_rev in sorted(cursor):
            kind = _kindmap[kind]
            change = _actionmap[change]
            yield path, kind, change, base_path, self.repos.rev_db(base_rev)

    def get_properties(self):
        return self.repos.repos.get_changeset(self.rev).get_properties()