1
# Copyright (C) 2006, 2007 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
"""Server-side repository related request implmentations."""
19
from cStringIO import StringIO
25
from bzrlib import errors
26
from bzrlib.bzrdir import BzrDir
27
from bzrlib.pack import ContainerSerialiser
28
from bzrlib.smart.request import (
29
FailedSmartServerResponse,
31
SuccessfulSmartServerResponse,
33
from bzrlib import revision as _mod_revision
36
class SmartServerRepositoryRequest(SmartServerRequest):
37
"""Common base class for Repository requests."""
39
def do(self, path, *args):
40
"""Execute a repository request.
42
The repository must be at the exact path - no searching is done.
44
The actual logic is delegated to self.do_repository_request.
46
:param path: The path for the repository.
47
:return: A smart server from self.do_repository_request().
49
transport = self._backing_transport.clone(path)
50
bzrdir = BzrDir.open_from_transport(transport)
51
# Save the repository for use with do_body.
52
self._repository = bzrdir.open_repository()
53
return self.do_repository_request(self._repository, *args)
55
def do_repository_request(self, repository, *args):
56
"""Override to provide an implementation for a verb."""
57
# No-op for verbs that take bodies (None as a result indicates a body
62
class SmartServerRepositoryGetParentMap(SmartServerRepositoryRequest):
64
def do_repository_request(self, repository, *revision_ids):
65
repository.lock_read()
67
return self._do_repository_request(repository, revision_ids)
71
def _do_repository_request(self, repository, revision_ids):
72
"""Get parent details for some revisions.
74
All the parents for revision_ids are returned. Additionally up to 64KB
75
of additional parent data found by performing a breadth first search
76
from revision_ids is returned.
78
:param repository: The repository to query in.
79
:param revision_ids: The utf8 encoded revision_id to answer for.
80
:return: A smart server response where the body contains an utf8
81
encoded flattened list of the parents of the revisions, (the same
82
format as Repository.get_revision_graph).
85
repo_graph = repository.get_graph()
89
next_revs = revision_ids
90
first_loop_done = False
92
queried_revs.update(next_revs)
93
parent_map = repo_graph.get_parent_map(next_revs)
95
for revision_id, parents in parent_map.iteritems():
97
if parents == (_mod_revision.NULL_REVISION,):
99
# add parents to the result
100
result[revision_id] = parents
101
# prepare the next query
102
next_revs.update(parents)
103
# Approximate the serialized cost of this revision_id.
104
size_so_far += 2 + len(revision_id) + sum(map(len, parents))
105
# get all the directly asked for parents, and then flesh out to
107
if first_loop_done and size_so_far > 65000:
110
# don't query things we've already queried
111
next_revs.difference_update(queried_revs)
112
first_loop_done = True
114
for revision, parents in result.items():
115
lines.append(' '.join((revision, ) + tuple(parents)))
117
return SuccessfulSmartServerResponse(('ok', ), '\n'.join(lines))
120
class SmartServerRepositoryGetRevisionGraph(SmartServerRepositoryRequest):
122
def do_repository_request(self, repository, revision_id):
123
"""Return the result of repository.get_revision_graph(revision_id).
125
:param repository: The repository to query in.
126
:param revision_id: The utf8 encoded revision_id to get a graph from.
127
:return: A smart server response where the body contains an utf8
128
encoded flattened list of the revision graph.
135
revision_graph = repository.get_revision_graph(revision_id)
136
except errors.NoSuchRevision:
137
# Note that we return an empty body, rather than omitting the body.
138
# This way the client knows that it can always expect to find a body
139
# in the response for this method, even in the error case.
140
return FailedSmartServerResponse(('nosuchrevision', revision_id), '')
142
for revision, parents in revision_graph.items():
143
lines.append(' '.join((revision, ) + tuple(parents)))
145
return SuccessfulSmartServerResponse(('ok', ), '\n'.join(lines))
148
class SmartServerRequestHasRevision(SmartServerRepositoryRequest):
150
def do_repository_request(self, repository, revision_id):
151
"""Return ok if a specific revision is in the repository at path.
153
:param repository: The repository to query in.
154
:param revision_id: The utf8 encoded revision_id to lookup.
155
:return: A smart server response of ('ok', ) if the revision is
158
if repository.has_revision(revision_id):
159
return SuccessfulSmartServerResponse(('yes', ))
161
return SuccessfulSmartServerResponse(('no', ))
164
class SmartServerRepositoryGatherStats(SmartServerRepositoryRequest):
166
def do_repository_request(self, repository, revid, committers):
167
"""Return the result of repository.gather_stats().
169
:param repository: The repository to query in.
170
:param revid: utf8 encoded rev id or an empty string to indicate None
171
:param committers: 'yes' or 'no'.
173
:return: A SmartServerResponse ('ok',), a encoded body looking like
176
latestrev: 345.700 3600
180
But containing only fields returned by the gather_stats() call
183
decoded_revision_id = None
185
decoded_revision_id = revid
186
if committers == 'yes':
187
decoded_committers = True
189
decoded_committers = None
190
stats = repository.gather_stats(decoded_revision_id, decoded_committers)
193
if stats.has_key('committers'):
194
body += 'committers: %d\n' % stats['committers']
195
if stats.has_key('firstrev'):
196
body += 'firstrev: %.3f %d\n' % stats['firstrev']
197
if stats.has_key('latestrev'):
198
body += 'latestrev: %.3f %d\n' % stats['latestrev']
199
if stats.has_key('revisions'):
200
body += 'revisions: %d\n' % stats['revisions']
201
if stats.has_key('size'):
202
body += 'size: %d\n' % stats['size']
204
return SuccessfulSmartServerResponse(('ok', ), body)
207
class SmartServerRepositoryIsShared(SmartServerRepositoryRequest):
209
def do_repository_request(self, repository):
210
"""Return the result of repository.is_shared().
212
:param repository: The repository to query in.
213
:return: A smart server response of ('yes', ) if the repository is
214
shared, and ('no', ) if it is not.
216
if repository.is_shared():
217
return SuccessfulSmartServerResponse(('yes', ))
219
return SuccessfulSmartServerResponse(('no', ))
222
class SmartServerRepositoryLockWrite(SmartServerRepositoryRequest):
224
def do_repository_request(self, repository, token=''):
225
# XXX: this probably should not have a token.
229
token = repository.lock_write(token=token)
230
except errors.LockContention, e:
231
return FailedSmartServerResponse(('LockContention',))
232
except errors.UnlockableTransport:
233
return FailedSmartServerResponse(('UnlockableTransport',))
234
except errors.LockFailed, e:
235
return FailedSmartServerResponse(('LockFailed',
236
str(e.lock), str(e.why)))
237
if token is not None:
238
repository.leave_lock_in_place()
242
return SuccessfulSmartServerResponse(('ok', token))
245
class SmartServerRepositoryUnlock(SmartServerRepositoryRequest):
247
def do_repository_request(self, repository, token):
249
repository.lock_write(token=token)
250
except errors.TokenMismatch, e:
251
return FailedSmartServerResponse(('TokenMismatch',))
252
repository.dont_leave_lock_in_place()
254
return SuccessfulSmartServerResponse(('ok',))
257
class SmartServerRepositoryTarball(SmartServerRepositoryRequest):
258
"""Get the raw repository files as a tarball.
260
The returned tarball contains a .bzr control directory which in turn
261
contains a repository.
263
This takes one parameter, compression, which currently must be
266
This is used to implement the Repository.copy_content_into operation.
269
def do_repository_request(self, repository, compression):
270
from bzrlib import osutils
271
repo_transport = repository.control_files._transport
272
tmp_dirname, tmp_repo = self._copy_to_tempdir(repository)
274
controldir_name = tmp_dirname + '/.bzr'
275
return self._tarfile_response(controldir_name, compression)
277
osutils.rmtree(tmp_dirname)
279
def _copy_to_tempdir(self, from_repo):
280
tmp_dirname = tempfile.mkdtemp(prefix='tmpbzrclone')
281
tmp_bzrdir = from_repo.bzrdir._format.initialize(tmp_dirname)
282
tmp_repo = from_repo._format.initialize(tmp_bzrdir)
283
from_repo.copy_content_into(tmp_repo)
284
return tmp_dirname, tmp_repo
286
def _tarfile_response(self, tmp_dirname, compression):
287
temp = tempfile.NamedTemporaryFile()
289
self._tarball_of_dir(tmp_dirname, compression, temp.file)
290
# all finished; write the tempfile out to the network
292
return SuccessfulSmartServerResponse(('ok',), temp.read())
293
# FIXME: Don't read the whole thing into memory here; rather stream it
294
# out from the file onto the network. mbp 20070411
298
def _tarball_of_dir(self, dirname, compression, ofile):
299
filename = os.path.basename(ofile.name)
300
tarball = tarfile.open(fileobj=ofile, name=filename,
301
mode='w|' + compression)
303
# The tarball module only accepts ascii names, and (i guess)
304
# packs them with their 8bit names. We know all the files
305
# within the repository have ASCII names so the should be safe
307
dirname = dirname.encode(sys.getfilesystemencoding())
308
# python's tarball module includes the whole path by default so
310
assert dirname.endswith('.bzr')
311
tarball.add(dirname, '.bzr') # recursive by default
316
class SmartServerRepositoryStreamKnitDataForRevisions(SmartServerRepositoryRequest):
317
"""Bzr <= 1.1 streaming pull, buffers all data on server."""
319
def do_repository_request(self, repository, *revision_ids):
320
repository.lock_read()
322
return self._do_repository_request(repository, revision_ids)
326
def _do_repository_request(self, repository, revision_ids):
327
stream = repository.get_data_stream_for_search(
328
repository.revision_ids_to_search_result(set(revision_ids)))
330
pack = ContainerSerialiser()
331
buffer.write(pack.begin())
333
for name_tuple, bytes in stream:
334
buffer.write(pack.bytes_record(bytes, [name_tuple]))
335
except errors.RevisionNotPresent, e:
336
return FailedSmartServerResponse(('NoSuchRevision', e.revision_id))
337
buffer.write(pack.end())
338
return SuccessfulSmartServerResponse(('ok',), buffer.getvalue())
341
class SmartServerRepositoryStreamRevisionsChunked(SmartServerRepositoryRequest):
342
"""Bzr 1.1+ streaming pull."""
344
def do_body(self, body_bytes):
345
lines = body_bytes.split('\n')
346
start_keys = set(lines[0].split(' '))
347
exclude_keys = set(lines[1].split(' '))
348
revision_count = int(lines[2])
349
repository = self._repository
350
repository.lock_read()
352
search = repository.get_graph()._make_breadth_first_searcher(
356
next_revs = search.next()
357
except StopIteration:
359
search.stop_searching_any(exclude_keys.intersection(next_revs))
360
search_result = search.get_result()
361
if search_result.get_recipe()[2] != revision_count:
362
# we got back a different amount of data than expected, this
363
# gets reported as NoSuchRevision, because less revisions
364
# indicates missing revisions, and more should never happen as
365
# the excludes list considers ghosts and ensures that ghost
366
# filling races are not a problem.
367
return FailedSmartServerResponse(('NoSuchRevision',))
368
stream = repository.get_data_stream_for_search(search_result)
372
return SuccessfulSmartServerResponse(('ok',),
373
body_stream=self.body_stream(stream, repository))
375
def body_stream(self, stream, repository):
376
pack = ContainerSerialiser()
379
for name_tuple, bytes in stream:
380
yield pack.bytes_record(bytes, [name_tuple])
381
except errors.RevisionNotPresent, e:
382
# This shouldn't be able to happen, but as we don't buffer
383
# everything it can in theory happen.
384
yield FailedSmartServerResponse(('NoSuchRevision', e.revision_id))