##// END OF EJS Templates
wireproto: implement batching on peer executor interface...
Gregory Szorc -
r37649:2f626233 default
parent child Browse files
Show More
@@ -1,267 +1,270 b''
1 # setdiscovery.py - improved discovery of common nodeset for mercurial
1 # setdiscovery.py - improved discovery of common nodeset for mercurial
2 #
2 #
3 # Copyright 2010 Benoit Boissinot <bboissin@gmail.com>
3 # Copyright 2010 Benoit Boissinot <bboissin@gmail.com>
4 # and Peter Arrenbrecht <peter@arrenbrecht.ch>
4 # and Peter Arrenbrecht <peter@arrenbrecht.ch>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8 """
8 """
9 Algorithm works in the following way. You have two repository: local and
9 Algorithm works in the following way. You have two repository: local and
10 remote. They both contains a DAG of changelists.
10 remote. They both contains a DAG of changelists.
11
11
12 The goal of the discovery protocol is to find one set of node *common*,
12 The goal of the discovery protocol is to find one set of node *common*,
13 the set of nodes shared by local and remote.
13 the set of nodes shared by local and remote.
14
14
15 One of the issue with the original protocol was latency, it could
15 One of the issue with the original protocol was latency, it could
16 potentially require lots of roundtrips to discover that the local repo was a
16 potentially require lots of roundtrips to discover that the local repo was a
17 subset of remote (which is a very common case, you usually have few changes
17 subset of remote (which is a very common case, you usually have few changes
18 compared to upstream, while upstream probably had lots of development).
18 compared to upstream, while upstream probably had lots of development).
19
19
20 The new protocol only requires one interface for the remote repo: `known()`,
20 The new protocol only requires one interface for the remote repo: `known()`,
21 which given a set of changelists tells you if they are present in the DAG.
21 which given a set of changelists tells you if they are present in the DAG.
22
22
23 The algorithm then works as follow:
23 The algorithm then works as follow:
24
24
25 - We will be using three sets, `common`, `missing`, `unknown`. Originally
25 - We will be using three sets, `common`, `missing`, `unknown`. Originally
26 all nodes are in `unknown`.
26 all nodes are in `unknown`.
27 - Take a sample from `unknown`, call `remote.known(sample)`
27 - Take a sample from `unknown`, call `remote.known(sample)`
28 - For each node that remote knows, move it and all its ancestors to `common`
28 - For each node that remote knows, move it and all its ancestors to `common`
29 - For each node that remote doesn't know, move it and all its descendants
29 - For each node that remote doesn't know, move it and all its descendants
30 to `missing`
30 to `missing`
31 - Iterate until `unknown` is empty
31 - Iterate until `unknown` is empty
32
32
33 There are a couple optimizations, first is instead of starting with a random
33 There are a couple optimizations, first is instead of starting with a random
34 sample of missing, start by sending all heads, in the case where the local
34 sample of missing, start by sending all heads, in the case where the local
35 repo is a subset, you computed the answer in one round trip.
35 repo is a subset, you computed the answer in one round trip.
36
36
37 Then you can do something similar to the bisecting strategy used when
37 Then you can do something similar to the bisecting strategy used when
38 finding faulty changesets. Instead of random samples, you can try picking
38 finding faulty changesets. Instead of random samples, you can try picking
39 nodes that will maximize the number of nodes that will be
39 nodes that will maximize the number of nodes that will be
40 classified with it (since all ancestors or descendants will be marked as well).
40 classified with it (since all ancestors or descendants will be marked as well).
41 """
41 """
42
42
43 from __future__ import absolute_import
43 from __future__ import absolute_import
44
44
45 import collections
45 import collections
46 import random
46 import random
47
47
48 from .i18n import _
48 from .i18n import _
49 from .node import (
49 from .node import (
50 nullid,
50 nullid,
51 nullrev,
51 nullrev,
52 )
52 )
53 from . import (
53 from . import (
54 dagutil,
54 dagutil,
55 error,
55 error,
56 util,
56 util,
57 )
57 )
58
58
59 def _updatesample(dag, nodes, sample, quicksamplesize=0):
59 def _updatesample(dag, nodes, sample, quicksamplesize=0):
60 """update an existing sample to match the expected size
60 """update an existing sample to match the expected size
61
61
62 The sample is updated with nodes exponentially distant from each head of the
62 The sample is updated with nodes exponentially distant from each head of the
63 <nodes> set. (H~1, H~2, H~4, H~8, etc).
63 <nodes> set. (H~1, H~2, H~4, H~8, etc).
64
64
65 If a target size is specified, the sampling will stop once this size is
65 If a target size is specified, the sampling will stop once this size is
66 reached. Otherwise sampling will happen until roots of the <nodes> set are
66 reached. Otherwise sampling will happen until roots of the <nodes> set are
67 reached.
67 reached.
68
68
69 :dag: a dag object from dagutil
69 :dag: a dag object from dagutil
70 :nodes: set of nodes we want to discover (if None, assume the whole dag)
70 :nodes: set of nodes we want to discover (if None, assume the whole dag)
71 :sample: a sample to update
71 :sample: a sample to update
72 :quicksamplesize: optional target size of the sample"""
72 :quicksamplesize: optional target size of the sample"""
73 # if nodes is empty we scan the entire graph
73 # if nodes is empty we scan the entire graph
74 if nodes:
74 if nodes:
75 heads = dag.headsetofconnecteds(nodes)
75 heads = dag.headsetofconnecteds(nodes)
76 else:
76 else:
77 heads = dag.heads()
77 heads = dag.heads()
78 dist = {}
78 dist = {}
79 visit = collections.deque(heads)
79 visit = collections.deque(heads)
80 seen = set()
80 seen = set()
81 factor = 1
81 factor = 1
82 while visit:
82 while visit:
83 curr = visit.popleft()
83 curr = visit.popleft()
84 if curr in seen:
84 if curr in seen:
85 continue
85 continue
86 d = dist.setdefault(curr, 1)
86 d = dist.setdefault(curr, 1)
87 if d > factor:
87 if d > factor:
88 factor *= 2
88 factor *= 2
89 if d == factor:
89 if d == factor:
90 sample.add(curr)
90 sample.add(curr)
91 if quicksamplesize and (len(sample) >= quicksamplesize):
91 if quicksamplesize and (len(sample) >= quicksamplesize):
92 return
92 return
93 seen.add(curr)
93 seen.add(curr)
94 for p in dag.parents(curr):
94 for p in dag.parents(curr):
95 if not nodes or p in nodes:
95 if not nodes or p in nodes:
96 dist.setdefault(p, d + 1)
96 dist.setdefault(p, d + 1)
97 visit.append(p)
97 visit.append(p)
98
98
99 def _takequicksample(dag, nodes, size):
99 def _takequicksample(dag, nodes, size):
100 """takes a quick sample of size <size>
100 """takes a quick sample of size <size>
101
101
102 It is meant for initial sampling and focuses on querying heads and close
102 It is meant for initial sampling and focuses on querying heads and close
103 ancestors of heads.
103 ancestors of heads.
104
104
105 :dag: a dag object
105 :dag: a dag object
106 :nodes: set of nodes to discover
106 :nodes: set of nodes to discover
107 :size: the maximum size of the sample"""
107 :size: the maximum size of the sample"""
108 sample = dag.headsetofconnecteds(nodes)
108 sample = dag.headsetofconnecteds(nodes)
109 if len(sample) >= size:
109 if len(sample) >= size:
110 return _limitsample(sample, size)
110 return _limitsample(sample, size)
111 _updatesample(dag, None, sample, quicksamplesize=size)
111 _updatesample(dag, None, sample, quicksamplesize=size)
112 return sample
112 return sample
113
113
114 def _takefullsample(dag, nodes, size):
114 def _takefullsample(dag, nodes, size):
115 sample = dag.headsetofconnecteds(nodes)
115 sample = dag.headsetofconnecteds(nodes)
116 # update from heads
116 # update from heads
117 _updatesample(dag, nodes, sample)
117 _updatesample(dag, nodes, sample)
118 # update from roots
118 # update from roots
119 _updatesample(dag.inverse(), nodes, sample)
119 _updatesample(dag.inverse(), nodes, sample)
120 assert sample
120 assert sample
121 sample = _limitsample(sample, size)
121 sample = _limitsample(sample, size)
122 if len(sample) < size:
122 if len(sample) < size:
123 more = size - len(sample)
123 more = size - len(sample)
124 sample.update(random.sample(list(nodes - sample), more))
124 sample.update(random.sample(list(nodes - sample), more))
125 return sample
125 return sample
126
126
127 def _limitsample(sample, desiredlen):
127 def _limitsample(sample, desiredlen):
128 """return a random subset of sample of at most desiredlen item"""
128 """return a random subset of sample of at most desiredlen item"""
129 if len(sample) > desiredlen:
129 if len(sample) > desiredlen:
130 sample = set(random.sample(sample, desiredlen))
130 sample = set(random.sample(sample, desiredlen))
131 return sample
131 return sample
132
132
133 def findcommonheads(ui, local, remote,
133 def findcommonheads(ui, local, remote,
134 initialsamplesize=100,
134 initialsamplesize=100,
135 fullsamplesize=200,
135 fullsamplesize=200,
136 abortwhenunrelated=True,
136 abortwhenunrelated=True,
137 ancestorsof=None):
137 ancestorsof=None):
138 '''Return a tuple (common, anyincoming, remoteheads) used to identify
138 '''Return a tuple (common, anyincoming, remoteheads) used to identify
139 missing nodes from or in remote.
139 missing nodes from or in remote.
140 '''
140 '''
141 start = util.timer()
141 start = util.timer()
142
142
143 roundtrips = 0
143 roundtrips = 0
144 cl = local.changelog
144 cl = local.changelog
145 localsubset = None
145 localsubset = None
146 if ancestorsof is not None:
146 if ancestorsof is not None:
147 rev = local.changelog.rev
147 rev = local.changelog.rev
148 localsubset = [rev(n) for n in ancestorsof]
148 localsubset = [rev(n) for n in ancestorsof]
149 dag = dagutil.revlogdag(cl, localsubset=localsubset)
149 dag = dagutil.revlogdag(cl, localsubset=localsubset)
150
150
151 # early exit if we know all the specified remote heads already
151 # early exit if we know all the specified remote heads already
152 ui.debug("query 1; heads\n")
152 ui.debug("query 1; heads\n")
153 roundtrips += 1
153 roundtrips += 1
154 ownheads = dag.heads()
154 ownheads = dag.heads()
155 sample = _limitsample(ownheads, initialsamplesize)
155 sample = _limitsample(ownheads, initialsamplesize)
156 # indices between sample and externalized version must match
156 # indices between sample and externalized version must match
157 sample = list(sample)
157 sample = list(sample)
158 batch = remote.iterbatch()
158
159 batch.heads()
159 with remote.commandexecutor() as e:
160 batch.known(dag.externalizeall(sample))
160 fheads = e.callcommand('heads', {})
161 batch.submit()
161 fknown = e.callcommand('known', {
162 srvheadhashes, yesno = batch.results()
162 'nodes': dag.externalizeall(sample),
163 })
164
165 srvheadhashes, yesno = fheads.result(), fknown.result()
163
166
164 if cl.tip() == nullid:
167 if cl.tip() == nullid:
165 if srvheadhashes != [nullid]:
168 if srvheadhashes != [nullid]:
166 return [nullid], True, srvheadhashes
169 return [nullid], True, srvheadhashes
167 return [nullid], False, []
170 return [nullid], False, []
168
171
169 # start actual discovery (we note this before the next "if" for
172 # start actual discovery (we note this before the next "if" for
170 # compatibility reasons)
173 # compatibility reasons)
171 ui.status(_("searching for changes\n"))
174 ui.status(_("searching for changes\n"))
172
175
173 srvheads = dag.internalizeall(srvheadhashes, filterunknown=True)
176 srvheads = dag.internalizeall(srvheadhashes, filterunknown=True)
174 if len(srvheads) == len(srvheadhashes):
177 if len(srvheads) == len(srvheadhashes):
175 ui.debug("all remote heads known locally\n")
178 ui.debug("all remote heads known locally\n")
176 return (srvheadhashes, False, srvheadhashes,)
179 return (srvheadhashes, False, srvheadhashes,)
177
180
178 if len(sample) == len(ownheads) and all(yesno):
181 if len(sample) == len(ownheads) and all(yesno):
179 ui.note(_("all local heads known remotely\n"))
182 ui.note(_("all local heads known remotely\n"))
180 ownheadhashes = dag.externalizeall(ownheads)
183 ownheadhashes = dag.externalizeall(ownheads)
181 return (ownheadhashes, True, srvheadhashes,)
184 return (ownheadhashes, True, srvheadhashes,)
182
185
183 # full blown discovery
186 # full blown discovery
184
187
185 # own nodes I know we both know
188 # own nodes I know we both know
186 # treat remote heads (and maybe own heads) as a first implicit sample
189 # treat remote heads (and maybe own heads) as a first implicit sample
187 # response
190 # response
188 common = cl.incrementalmissingrevs(srvheads)
191 common = cl.incrementalmissingrevs(srvheads)
189 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
192 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
190 common.addbases(commoninsample)
193 common.addbases(commoninsample)
191 # own nodes where I don't know if remote knows them
194 # own nodes where I don't know if remote knows them
192 undecided = set(common.missingancestors(ownheads))
195 undecided = set(common.missingancestors(ownheads))
193 # own nodes I know remote lacks
196 # own nodes I know remote lacks
194 missing = set()
197 missing = set()
195
198
196 full = False
199 full = False
197 while undecided:
200 while undecided:
198
201
199 if sample:
202 if sample:
200 missinginsample = [n for i, n in enumerate(sample) if not yesno[i]]
203 missinginsample = [n for i, n in enumerate(sample) if not yesno[i]]
201 missing.update(dag.descendantset(missinginsample, missing))
204 missing.update(dag.descendantset(missinginsample, missing))
202
205
203 undecided.difference_update(missing)
206 undecided.difference_update(missing)
204
207
205 if not undecided:
208 if not undecided:
206 break
209 break
207
210
208 if full or common.hasbases():
211 if full or common.hasbases():
209 if full:
212 if full:
210 ui.note(_("sampling from both directions\n"))
213 ui.note(_("sampling from both directions\n"))
211 else:
214 else:
212 ui.debug("taking initial sample\n")
215 ui.debug("taking initial sample\n")
213 samplefunc = _takefullsample
216 samplefunc = _takefullsample
214 targetsize = fullsamplesize
217 targetsize = fullsamplesize
215 else:
218 else:
216 # use even cheaper initial sample
219 # use even cheaper initial sample
217 ui.debug("taking quick initial sample\n")
220 ui.debug("taking quick initial sample\n")
218 samplefunc = _takequicksample
221 samplefunc = _takequicksample
219 targetsize = initialsamplesize
222 targetsize = initialsamplesize
220 if len(undecided) < targetsize:
223 if len(undecided) < targetsize:
221 sample = list(undecided)
224 sample = list(undecided)
222 else:
225 else:
223 sample = samplefunc(dag, undecided, targetsize)
226 sample = samplefunc(dag, undecided, targetsize)
224
227
225 roundtrips += 1
228 roundtrips += 1
226 ui.progress(_('searching'), roundtrips, unit=_('queries'))
229 ui.progress(_('searching'), roundtrips, unit=_('queries'))
227 ui.debug("query %i; still undecided: %i, sample size is: %i\n"
230 ui.debug("query %i; still undecided: %i, sample size is: %i\n"
228 % (roundtrips, len(undecided), len(sample)))
231 % (roundtrips, len(undecided), len(sample)))
229 # indices between sample and externalized version must match
232 # indices between sample and externalized version must match
230 sample = list(sample)
233 sample = list(sample)
231
234
232 with remote.commandexecutor() as e:
235 with remote.commandexecutor() as e:
233 yesno = e.callcommand('known', {
236 yesno = e.callcommand('known', {
234 'nodes': dag.externalizeall(sample),
237 'nodes': dag.externalizeall(sample),
235 }).result()
238 }).result()
236
239
237 full = True
240 full = True
238
241
239 if sample:
242 if sample:
240 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
243 commoninsample = set(n for i, n in enumerate(sample) if yesno[i])
241 common.addbases(commoninsample)
244 common.addbases(commoninsample)
242 common.removeancestorsfrom(undecided)
245 common.removeancestorsfrom(undecided)
243
246
244 # heads(common) == heads(common.bases) since common represents common.bases
247 # heads(common) == heads(common.bases) since common represents common.bases
245 # and all its ancestors
248 # and all its ancestors
246 result = dag.headsetofconnecteds(common.bases)
249 result = dag.headsetofconnecteds(common.bases)
247 # common.bases can include nullrev, but our contract requires us to not
250 # common.bases can include nullrev, but our contract requires us to not
248 # return any heads in that case, so discard that
251 # return any heads in that case, so discard that
249 result.discard(nullrev)
252 result.discard(nullrev)
250 elapsed = util.timer() - start
253 elapsed = util.timer() - start
251 ui.progress(_('searching'), None)
254 ui.progress(_('searching'), None)
252 ui.debug("%d total queries in %.4fs\n" % (roundtrips, elapsed))
255 ui.debug("%d total queries in %.4fs\n" % (roundtrips, elapsed))
253 msg = ('found %d common and %d unknown server heads,'
256 msg = ('found %d common and %d unknown server heads,'
254 ' %d roundtrips in %.4fs\n')
257 ' %d roundtrips in %.4fs\n')
255 missing = set(result) - set(srvheads)
258 missing = set(result) - set(srvheads)
256 ui.log('discovery', msg, len(result), len(missing), roundtrips,
259 ui.log('discovery', msg, len(result), len(missing), roundtrips,
257 elapsed)
260 elapsed)
258
261
259 if not result and srvheadhashes != [nullid]:
262 if not result and srvheadhashes != [nullid]:
260 if abortwhenunrelated:
263 if abortwhenunrelated:
261 raise error.Abort(_("repository is unrelated"))
264 raise error.Abort(_("repository is unrelated"))
262 else:
265 else:
263 ui.warn(_("warning: repository is unrelated\n"))
266 ui.warn(_("warning: repository is unrelated\n"))
264 return ({nullid}, True, srvheadhashes,)
267 return ({nullid}, True, srvheadhashes,)
265
268
266 anyincoming = (srvheadhashes != [nullid])
269 anyincoming = (srvheadhashes != [nullid])
267 return dag.externalizeall(result), anyincoming, srvheadhashes
270 return dag.externalizeall(result), anyincoming, srvheadhashes
@@ -1,576 +1,708 b''
1 # wireprotov1peer.py - Client-side functionality for wire protocol version 1.
1 # wireprotov1peer.py - Client-side functionality for wire protocol version 1.
2 #
2 #
3 # Copyright 2005-2010 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2010 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import hashlib
10 import hashlib
11 import sys
11 import sys
12 import weakref
12
13
13 from .i18n import _
14 from .i18n import _
14 from .node import (
15 from .node import (
15 bin,
16 bin,
16 )
17 )
17 from .thirdparty.zope import (
18 from .thirdparty.zope import (
18 interface as zi,
19 interface as zi,
19 )
20 )
20 from . import (
21 from . import (
21 bundle2,
22 bundle2,
22 changegroup as changegroupmod,
23 changegroup as changegroupmod,
23 encoding,
24 encoding,
24 error,
25 error,
25 pushkey as pushkeymod,
26 pushkey as pushkeymod,
26 pycompat,
27 pycompat,
27 repository,
28 repository,
28 util,
29 util,
29 wireprototypes,
30 wireprototypes,
30 )
31 )
31
32
32 urlreq = util.urlreq
33 urlreq = util.urlreq
33
34
34 def batchable(f):
35 def batchable(f):
35 '''annotation for batchable methods
36 '''annotation for batchable methods
36
37
37 Such methods must implement a coroutine as follows:
38 Such methods must implement a coroutine as follows:
38
39
39 @batchable
40 @batchable
40 def sample(self, one, two=None):
41 def sample(self, one, two=None):
41 # Build list of encoded arguments suitable for your wire protocol:
42 # Build list of encoded arguments suitable for your wire protocol:
42 encargs = [('one', encode(one),), ('two', encode(two),)]
43 encargs = [('one', encode(one),), ('two', encode(two),)]
43 # Create future for injection of encoded result:
44 # Create future for injection of encoded result:
44 encresref = future()
45 encresref = future()
45 # Return encoded arguments and future:
46 # Return encoded arguments and future:
46 yield encargs, encresref
47 yield encargs, encresref
47 # Assuming the future to be filled with the result from the batched
48 # Assuming the future to be filled with the result from the batched
48 # request now. Decode it:
49 # request now. Decode it:
49 yield decode(encresref.value)
50 yield decode(encresref.value)
50
51
51 The decorator returns a function which wraps this coroutine as a plain
52 The decorator returns a function which wraps this coroutine as a plain
52 method, but adds the original method as an attribute called "batchable",
53 method, but adds the original method as an attribute called "batchable",
53 which is used by remotebatch to split the call into separate encoding and
54 which is used by remotebatch to split the call into separate encoding and
54 decoding phases.
55 decoding phases.
55 '''
56 '''
56 def plain(*args, **opts):
57 def plain(*args, **opts):
57 batchable = f(*args, **opts)
58 batchable = f(*args, **opts)
58 encargsorres, encresref = next(batchable)
59 encargsorres, encresref = next(batchable)
59 if not encresref:
60 if not encresref:
60 return encargsorres # a local result in this case
61 return encargsorres # a local result in this case
61 self = args[0]
62 self = args[0]
62 cmd = pycompat.bytesurl(f.__name__) # ensure cmd is ascii bytestr
63 cmd = pycompat.bytesurl(f.__name__) # ensure cmd is ascii bytestr
63 encresref.set(self._submitone(cmd, encargsorres))
64 encresref.set(self._submitone(cmd, encargsorres))
64 return next(batchable)
65 return next(batchable)
65 setattr(plain, 'batchable', f)
66 setattr(plain, 'batchable', f)
66 return plain
67 return plain
67
68
68 class future(object):
69 class future(object):
69 '''placeholder for a value to be set later'''
70 '''placeholder for a value to be set later'''
70 def set(self, value):
71 def set(self, value):
71 if util.safehasattr(self, 'value'):
72 if util.safehasattr(self, 'value'):
72 raise error.RepoError("future is already set")
73 raise error.RepoError("future is already set")
73 self.value = value
74 self.value = value
74
75
75 class batcher(object):
76 class batcher(object):
76 '''base class for batches of commands submittable in a single request
77 '''base class for batches of commands submittable in a single request
77
78
78 All methods invoked on instances of this class are simply queued and
79 All methods invoked on instances of this class are simply queued and
79 return a a future for the result. Once you call submit(), all the queued
80 return a a future for the result. Once you call submit(), all the queued
80 calls are performed and the results set in their respective futures.
81 calls are performed and the results set in their respective futures.
81 '''
82 '''
82 def __init__(self):
83 def __init__(self):
83 self.calls = []
84 self.calls = []
84 def __getattr__(self, name):
85 def __getattr__(self, name):
85 def call(*args, **opts):
86 def call(*args, **opts):
86 resref = future()
87 resref = future()
87 # Please don't invent non-ascii method names, or you will
88 # Please don't invent non-ascii method names, or you will
88 # give core hg a very sad time.
89 # give core hg a very sad time.
89 self.calls.append((name.encode('ascii'), args, opts, resref,))
90 self.calls.append((name.encode('ascii'), args, opts, resref,))
90 return resref
91 return resref
91 return call
92 return call
92 def submit(self):
93 def submit(self):
93 raise NotImplementedError()
94 raise NotImplementedError()
94
95
95 class iterbatcher(batcher):
96 class iterbatcher(batcher):
96
97
97 def submit(self):
98 def submit(self):
98 raise NotImplementedError()
99 raise NotImplementedError()
99
100
100 def results(self):
101 def results(self):
101 raise NotImplementedError()
102 raise NotImplementedError()
102
103
103 class remoteiterbatcher(iterbatcher):
104 class remoteiterbatcher(iterbatcher):
104 def __init__(self, remote):
105 def __init__(self, remote):
105 super(remoteiterbatcher, self).__init__()
106 super(remoteiterbatcher, self).__init__()
106 self._remote = remote
107 self._remote = remote
107
108
108 def __getattr__(self, name):
109 def __getattr__(self, name):
109 # Validate this method is batchable, since submit() only supports
110 # Validate this method is batchable, since submit() only supports
110 # batchable methods.
111 # batchable methods.
111 fn = getattr(self._remote, name)
112 fn = getattr(self._remote, name)
112 if not getattr(fn, 'batchable', None):
113 if not getattr(fn, 'batchable', None):
113 raise error.ProgrammingError('Attempted to batch a non-batchable '
114 raise error.ProgrammingError('Attempted to batch a non-batchable '
114 'call to %r' % name)
115 'call to %r' % name)
115
116
116 return super(remoteiterbatcher, self).__getattr__(name)
117 return super(remoteiterbatcher, self).__getattr__(name)
117
118
118 def submit(self):
119 def submit(self):
119 """Break the batch request into many patch calls and pipeline them.
120 """Break the batch request into many patch calls and pipeline them.
120
121
121 This is mostly valuable over http where request sizes can be
122 This is mostly valuable over http where request sizes can be
122 limited, but can be used in other places as well.
123 limited, but can be used in other places as well.
123 """
124 """
124 # 2-tuple of (command, arguments) that represents what will be
125 # 2-tuple of (command, arguments) that represents what will be
125 # sent over the wire.
126 # sent over the wire.
126 requests = []
127 requests = []
127
128
128 # 4-tuple of (command, final future, @batchable generator, remote
129 # 4-tuple of (command, final future, @batchable generator, remote
129 # future).
130 # future).
130 results = []
131 results = []
131
132
132 for command, args, opts, finalfuture in self.calls:
133 for command, args, opts, finalfuture in self.calls:
133 mtd = getattr(self._remote, command)
134 mtd = getattr(self._remote, command)
134 batchable = mtd.batchable(mtd.__self__, *args, **opts)
135 batchable = mtd.batchable(mtd.__self__, *args, **opts)
135
136
136 commandargs, fremote = next(batchable)
137 commandargs, fremote = next(batchable)
137 assert fremote
138 assert fremote
138 requests.append((command, commandargs))
139 requests.append((command, commandargs))
139 results.append((command, finalfuture, batchable, fremote))
140 results.append((command, finalfuture, batchable, fremote))
140
141
141 if requests:
142 if requests:
142 self._resultiter = self._remote._submitbatch(requests)
143 self._resultiter = self._remote._submitbatch(requests)
143
144
144 self._results = results
145 self._results = results
145
146
146 def results(self):
147 def results(self):
147 for command, finalfuture, batchable, remotefuture in self._results:
148 for command, finalfuture, batchable, remotefuture in self._results:
148 # Get the raw result, set it in the remote future, feed it
149 # Get the raw result, set it in the remote future, feed it
149 # back into the @batchable generator so it can be decoded, and
150 # back into the @batchable generator so it can be decoded, and
150 # set the result on the final future to this value.
151 # set the result on the final future to this value.
151 remoteresult = next(self._resultiter)
152 remoteresult = next(self._resultiter)
152 remotefuture.set(remoteresult)
153 remotefuture.set(remoteresult)
153 finalfuture.set(next(batchable))
154 finalfuture.set(next(batchable))
154
155
155 # Verify our @batchable generators only emit 2 values.
156 # Verify our @batchable generators only emit 2 values.
156 try:
157 try:
157 next(batchable)
158 next(batchable)
158 except StopIteration:
159 except StopIteration:
159 pass
160 pass
160 else:
161 else:
161 raise error.ProgrammingError('%s @batchable generator emitted '
162 raise error.ProgrammingError('%s @batchable generator emitted '
162 'unexpected value count' % command)
163 'unexpected value count' % command)
163
164
164 yield finalfuture.value
165 yield finalfuture.value
165
166
166 def encodebatchcmds(req):
167 def encodebatchcmds(req):
167 """Return a ``cmds`` argument value for the ``batch`` command."""
168 """Return a ``cmds`` argument value for the ``batch`` command."""
168 escapearg = wireprototypes.escapebatcharg
169 escapearg = wireprototypes.escapebatcharg
169
170
170 cmds = []
171 cmds = []
171 for op, argsdict in req:
172 for op, argsdict in req:
172 # Old servers didn't properly unescape argument names. So prevent
173 # Old servers didn't properly unescape argument names. So prevent
173 # the sending of argument names that may not be decoded properly by
174 # the sending of argument names that may not be decoded properly by
174 # servers.
175 # servers.
175 assert all(escapearg(k) == k for k in argsdict)
176 assert all(escapearg(k) == k for k in argsdict)
176
177
177 args = ','.join('%s=%s' % (escapearg(k), escapearg(v))
178 args = ','.join('%s=%s' % (escapearg(k), escapearg(v))
178 for k, v in argsdict.iteritems())
179 for k, v in argsdict.iteritems())
179 cmds.append('%s %s' % (op, args))
180 cmds.append('%s %s' % (op, args))
180
181
181 return ';'.join(cmds)
182 return ';'.join(cmds)
182
183
184 class unsentfuture(pycompat.futures.Future):
185 """A Future variation to represent an unsent command.
186
187 Because we buffer commands and don't submit them immediately, calling
188 ``result()`` on an unsent future could deadlock. Futures for buffered
189 commands are represented by this type, which wraps ``result()`` to
190 call ``sendcommands()``.
191 """
192
193 def result(self, timeout=None):
194 if self.done():
195 return pycompat.futures.Future.result(self, timeout)
196
197 self._peerexecutor.sendcommands()
198
199 # This looks like it will infinitely recurse. However,
200 # sendcommands() should modify __class__. This call serves as a check
201 # on that.
202 return self.result(timeout)
203
183 @zi.implementer(repository.ipeercommandexecutor)
204 @zi.implementer(repository.ipeercommandexecutor)
184 class peerexecutor(object):
205 class peerexecutor(object):
185 def __init__(self, peer):
206 def __init__(self, peer):
186 self._peer = peer
207 self._peer = peer
187 self._sent = False
208 self._sent = False
188 self._closed = False
209 self._closed = False
189 self._calls = []
210 self._calls = []
211 self._futures = weakref.WeakSet()
212 self._responseexecutor = None
213 self._responsef = None
190
214
191 def __enter__(self):
215 def __enter__(self):
192 return self
216 return self
193
217
194 def __exit__(self, exctype, excvalee, exctb):
218 def __exit__(self, exctype, excvalee, exctb):
195 self.close()
219 self.close()
196
220
197 def callcommand(self, command, args):
221 def callcommand(self, command, args):
198 if self._sent:
222 if self._sent:
199 raise error.ProgrammingError('callcommand() cannot be used '
223 raise error.ProgrammingError('callcommand() cannot be used '
200 'after commands are sent')
224 'after commands are sent')
201
225
202 if self._closed:
226 if self._closed:
203 raise error.ProgrammingError('callcommand() cannot be used '
227 raise error.ProgrammingError('callcommand() cannot be used '
204 'after close()')
228 'after close()')
205
229
206 # Commands are dispatched through methods on the peer.
230 # Commands are dispatched through methods on the peer.
207 fn = getattr(self._peer, pycompat.sysstr(command), None)
231 fn = getattr(self._peer, pycompat.sysstr(command), None)
208
232
209 if not fn:
233 if not fn:
210 raise error.ProgrammingError(
234 raise error.ProgrammingError(
211 'cannot call command %s: method of same name not available '
235 'cannot call command %s: method of same name not available '
212 'on peer' % command)
236 'on peer' % command)
213
237
214 # Commands are either batchable or they aren't. If a command
238 # Commands are either batchable or they aren't. If a command
215 # isn't batchable, we send it immediately because the executor
239 # isn't batchable, we send it immediately because the executor
216 # can no longer accept new commands after a non-batchable command.
240 # can no longer accept new commands after a non-batchable command.
217 # If a command is batchable, we queue it for later.
241 # If a command is batchable, we queue it for later. But we have
242 # to account for the case of a non-batchable command arriving after
243 # a batchable one and refuse to service it.
244
245 def addcall():
246 f = pycompat.futures.Future()
247 self._futures.add(f)
248 self._calls.append((command, args, fn, f))
249 return f
218
250
219 if getattr(fn, 'batchable', False):
251 if getattr(fn, 'batchable', False):
220 pass
252 f = addcall()
253
254 # But since we don't issue it immediately, we wrap its result()
255 # to trigger sending so we avoid deadlocks.
256 f.__class__ = unsentfuture
257 f._peerexecutor = self
221 else:
258 else:
222 if self._calls:
259 if self._calls:
223 raise error.ProgrammingError(
260 raise error.ProgrammingError(
224 '%s is not batchable and cannot be called on a command '
261 '%s is not batchable and cannot be called on a command '
225 'executor along with other commands' % command)
262 'executor along with other commands' % command)
226
263
227 # We don't support batching yet. So resolve it immediately.
264 f = addcall()
228 f = pycompat.futures.Future()
265
229 self._calls.append((command, args, fn, f))
266 # Non-batchable commands can never coexist with another command
230 self.sendcommands()
267 # in this executor. So send the command immediately.
268 self.sendcommands()
269
231 return f
270 return f
232
271
233 def sendcommands(self):
272 def sendcommands(self):
234 if self._sent:
273 if self._sent:
235 return
274 return
236
275
237 if not self._calls:
276 if not self._calls:
238 return
277 return
239
278
240 self._sent = True
279 self._sent = True
241
280
281 # Unhack any future types so caller seens a clean type and to break
282 # cycle between us and futures.
283 for f in self._futures:
284 if isinstance(f, unsentfuture):
285 f.__class__ = pycompat.futures.Future
286 f._peerexecutor = None
287
242 calls = self._calls
288 calls = self._calls
243 # Mainly to destroy references to futures.
289 # Mainly to destroy references to futures.
244 self._calls = None
290 self._calls = None
245
291
292 # Simple case of a single command. We call it synchronously.
246 if len(calls) == 1:
293 if len(calls) == 1:
247 command, args, fn, f = calls[0]
294 command, args, fn, f = calls[0]
248
295
249 # Future was cancelled. Ignore it.
296 # Future was cancelled. Ignore it.
250 if not f.set_running_or_notify_cancel():
297 if not f.set_running_or_notify_cancel():
251 return
298 return
252
299
253 try:
300 try:
254 result = fn(**pycompat.strkwargs(args))
301 result = fn(**pycompat.strkwargs(args))
255 except Exception:
302 except Exception:
256 f.set_exception_info(*sys.exc_info()[1:])
303 f.set_exception_info(*sys.exc_info()[1:])
257 else:
304 else:
258 f.set_result(result)
305 f.set_result(result)
259
306
260 return
307 return
261
308
262 raise error.ProgrammingError('support for multiple commands not '
309 # Batch commands are a bit harder. First, we have to deal with the
263 'yet implemented')
310 # @batchable coroutine. That's a bit annoying. Furthermore, we also
311 # need to preserve streaming. i.e. it should be possible for the
312 # futures to resolve as data is coming in off the wire without having
313 # to wait for the final byte of the final response. We do this by
314 # spinning up a thread to read the responses.
315
316 requests = []
317 states = []
318
319 for command, args, fn, f in calls:
320 # Future was cancelled. Ignore it.
321 if not f.set_running_or_notify_cancel():
322 continue
323
324 try:
325 batchable = fn.batchable(fn.__self__,
326 **pycompat.strkwargs(args))
327 except Exception:
328 f.set_exception_info(*sys.exc_info()[1:])
329 return
330
331 # Encoded arguments and future holding remote result.
332 try:
333 encodedargs, fremote = next(batchable)
334 except Exception:
335 f.set_exception_info(*sys.exc_info()[1:])
336 return
337
338 requests.append((command, encodedargs))
339 states.append((command, f, batchable, fremote))
340
341 if not requests:
342 return
343
344 # This will emit responses in order they were executed.
345 wireresults = self._peer._submitbatch(requests)
346
347 # The use of a thread pool executor here is a bit weird for something
348 # that only spins up a single thread. However, thread management is
349 # hard and it is easy to encounter race conditions, deadlocks, etc.
350 # concurrent.futures already solves these problems and its thread pool
351 # executor has minimal overhead. So we use it.
352 self._responseexecutor = pycompat.futures.ThreadPoolExecutor(1)
353 self._responsef = self._responseexecutor.submit(self._readbatchresponse,
354 states, wireresults)
264
355
265 def close(self):
356 def close(self):
266 self.sendcommands()
357 self.sendcommands()
267
358
359 if self._closed:
360 return
361
268 self._closed = True
362 self._closed = True
269
363
364 if not self._responsef:
365 return
366
367 # We need to wait on our in-flight response and then shut down the
368 # executor once we have a result.
369 try:
370 self._responsef.result()
371 finally:
372 self._responseexecutor.shutdown(wait=True)
373 self._responsef = None
374 self._responseexecutor = None
375
376 # If any of our futures are still in progress, mark them as
377 # errored. Otherwise a result() could wait indefinitely.
378 for f in self._futures:
379 if not f.done():
380 f.set_exception(error.ResponseError(
381 _('unfulfilled batch command response')))
382
383 self._futures = None
384
385 def _readbatchresponse(self, states, wireresults):
386 # Executes in a thread to read data off the wire.
387
388 for command, f, batchable, fremote in states:
389 # Grab raw result off the wire and teach the internal future
390 # about it.
391 remoteresult = next(wireresults)
392 fremote.set(remoteresult)
393
394 # And ask the coroutine to decode that value.
395 try:
396 result = next(batchable)
397 except Exception:
398 f.set_exception_info(*sys.exc_info()[1:])
399 else:
400 f.set_result(result)
401
270 class wirepeer(repository.legacypeer):
402 class wirepeer(repository.legacypeer):
271 """Client-side interface for communicating with a peer repository.
403 """Client-side interface for communicating with a peer repository.
272
404
273 Methods commonly call wire protocol commands of the same name.
405 Methods commonly call wire protocol commands of the same name.
274
406
275 See also httppeer.py and sshpeer.py for protocol-specific
407 See also httppeer.py and sshpeer.py for protocol-specific
276 implementations of this interface.
408 implementations of this interface.
277 """
409 """
278 def commandexecutor(self):
410 def commandexecutor(self):
279 return peerexecutor(self)
411 return peerexecutor(self)
280
412
281 # Begin of ipeercommands interface.
413 # Begin of ipeercommands interface.
282
414
283 def iterbatch(self):
415 def iterbatch(self):
284 return remoteiterbatcher(self)
416 return remoteiterbatcher(self)
285
417
286 @batchable
418 @batchable
287 def lookup(self, key):
419 def lookup(self, key):
288 self.requirecap('lookup', _('look up remote revision'))
420 self.requirecap('lookup', _('look up remote revision'))
289 f = future()
421 f = future()
290 yield {'key': encoding.fromlocal(key)}, f
422 yield {'key': encoding.fromlocal(key)}, f
291 d = f.value
423 d = f.value
292 success, data = d[:-1].split(" ", 1)
424 success, data = d[:-1].split(" ", 1)
293 if int(success):
425 if int(success):
294 yield bin(data)
426 yield bin(data)
295 else:
427 else:
296 self._abort(error.RepoError(data))
428 self._abort(error.RepoError(data))
297
429
298 @batchable
430 @batchable
299 def heads(self):
431 def heads(self):
300 f = future()
432 f = future()
301 yield {}, f
433 yield {}, f
302 d = f.value
434 d = f.value
303 try:
435 try:
304 yield wireprototypes.decodelist(d[:-1])
436 yield wireprototypes.decodelist(d[:-1])
305 except ValueError:
437 except ValueError:
306 self._abort(error.ResponseError(_("unexpected response:"), d))
438 self._abort(error.ResponseError(_("unexpected response:"), d))
307
439
308 @batchable
440 @batchable
309 def known(self, nodes):
441 def known(self, nodes):
310 f = future()
442 f = future()
311 yield {'nodes': wireprototypes.encodelist(nodes)}, f
443 yield {'nodes': wireprototypes.encodelist(nodes)}, f
312 d = f.value
444 d = f.value
313 try:
445 try:
314 yield [bool(int(b)) for b in d]
446 yield [bool(int(b)) for b in d]
315 except ValueError:
447 except ValueError:
316 self._abort(error.ResponseError(_("unexpected response:"), d))
448 self._abort(error.ResponseError(_("unexpected response:"), d))
317
449
318 @batchable
450 @batchable
319 def branchmap(self):
451 def branchmap(self):
320 f = future()
452 f = future()
321 yield {}, f
453 yield {}, f
322 d = f.value
454 d = f.value
323 try:
455 try:
324 branchmap = {}
456 branchmap = {}
325 for branchpart in d.splitlines():
457 for branchpart in d.splitlines():
326 branchname, branchheads = branchpart.split(' ', 1)
458 branchname, branchheads = branchpart.split(' ', 1)
327 branchname = encoding.tolocal(urlreq.unquote(branchname))
459 branchname = encoding.tolocal(urlreq.unquote(branchname))
328 branchheads = wireprototypes.decodelist(branchheads)
460 branchheads = wireprototypes.decodelist(branchheads)
329 branchmap[branchname] = branchheads
461 branchmap[branchname] = branchheads
330 yield branchmap
462 yield branchmap
331 except TypeError:
463 except TypeError:
332 self._abort(error.ResponseError(_("unexpected response:"), d))
464 self._abort(error.ResponseError(_("unexpected response:"), d))
333
465
334 @batchable
466 @batchable
335 def listkeys(self, namespace):
467 def listkeys(self, namespace):
336 if not self.capable('pushkey'):
468 if not self.capable('pushkey'):
337 yield {}, None
469 yield {}, None
338 f = future()
470 f = future()
339 self.ui.debug('preparing listkeys for "%s"\n' % namespace)
471 self.ui.debug('preparing listkeys for "%s"\n' % namespace)
340 yield {'namespace': encoding.fromlocal(namespace)}, f
472 yield {'namespace': encoding.fromlocal(namespace)}, f
341 d = f.value
473 d = f.value
342 self.ui.debug('received listkey for "%s": %i bytes\n'
474 self.ui.debug('received listkey for "%s": %i bytes\n'
343 % (namespace, len(d)))
475 % (namespace, len(d)))
344 yield pushkeymod.decodekeys(d)
476 yield pushkeymod.decodekeys(d)
345
477
346 @batchable
478 @batchable
347 def pushkey(self, namespace, key, old, new):
479 def pushkey(self, namespace, key, old, new):
348 if not self.capable('pushkey'):
480 if not self.capable('pushkey'):
349 yield False, None
481 yield False, None
350 f = future()
482 f = future()
351 self.ui.debug('preparing pushkey for "%s:%s"\n' % (namespace, key))
483 self.ui.debug('preparing pushkey for "%s:%s"\n' % (namespace, key))
352 yield {'namespace': encoding.fromlocal(namespace),
484 yield {'namespace': encoding.fromlocal(namespace),
353 'key': encoding.fromlocal(key),
485 'key': encoding.fromlocal(key),
354 'old': encoding.fromlocal(old),
486 'old': encoding.fromlocal(old),
355 'new': encoding.fromlocal(new)}, f
487 'new': encoding.fromlocal(new)}, f
356 d = f.value
488 d = f.value
357 d, output = d.split('\n', 1)
489 d, output = d.split('\n', 1)
358 try:
490 try:
359 d = bool(int(d))
491 d = bool(int(d))
360 except ValueError:
492 except ValueError:
361 raise error.ResponseError(
493 raise error.ResponseError(
362 _('push failed (unexpected response):'), d)
494 _('push failed (unexpected response):'), d)
363 for l in output.splitlines(True):
495 for l in output.splitlines(True):
364 self.ui.status(_('remote: '), l)
496 self.ui.status(_('remote: '), l)
365 yield d
497 yield d
366
498
367 def stream_out(self):
499 def stream_out(self):
368 return self._callstream('stream_out')
500 return self._callstream('stream_out')
369
501
370 def getbundle(self, source, **kwargs):
502 def getbundle(self, source, **kwargs):
371 kwargs = pycompat.byteskwargs(kwargs)
503 kwargs = pycompat.byteskwargs(kwargs)
372 self.requirecap('getbundle', _('look up remote changes'))
504 self.requirecap('getbundle', _('look up remote changes'))
373 opts = {}
505 opts = {}
374 bundlecaps = kwargs.get('bundlecaps') or set()
506 bundlecaps = kwargs.get('bundlecaps') or set()
375 for key, value in kwargs.iteritems():
507 for key, value in kwargs.iteritems():
376 if value is None:
508 if value is None:
377 continue
509 continue
378 keytype = wireprototypes.GETBUNDLE_ARGUMENTS.get(key)
510 keytype = wireprototypes.GETBUNDLE_ARGUMENTS.get(key)
379 if keytype is None:
511 if keytype is None:
380 raise error.ProgrammingError(
512 raise error.ProgrammingError(
381 'Unexpectedly None keytype for key %s' % key)
513 'Unexpectedly None keytype for key %s' % key)
382 elif keytype == 'nodes':
514 elif keytype == 'nodes':
383 value = wireprototypes.encodelist(value)
515 value = wireprototypes.encodelist(value)
384 elif keytype == 'csv':
516 elif keytype == 'csv':
385 value = ','.join(value)
517 value = ','.join(value)
386 elif keytype == 'scsv':
518 elif keytype == 'scsv':
387 value = ','.join(sorted(value))
519 value = ','.join(sorted(value))
388 elif keytype == 'boolean':
520 elif keytype == 'boolean':
389 value = '%i' % bool(value)
521 value = '%i' % bool(value)
390 elif keytype != 'plain':
522 elif keytype != 'plain':
391 raise KeyError('unknown getbundle option type %s'
523 raise KeyError('unknown getbundle option type %s'
392 % keytype)
524 % keytype)
393 opts[key] = value
525 opts[key] = value
394 f = self._callcompressable("getbundle", **pycompat.strkwargs(opts))
526 f = self._callcompressable("getbundle", **pycompat.strkwargs(opts))
395 if any((cap.startswith('HG2') for cap in bundlecaps)):
527 if any((cap.startswith('HG2') for cap in bundlecaps)):
396 return bundle2.getunbundler(self.ui, f)
528 return bundle2.getunbundler(self.ui, f)
397 else:
529 else:
398 return changegroupmod.cg1unpacker(f, 'UN')
530 return changegroupmod.cg1unpacker(f, 'UN')
399
531
400 def unbundle(self, cg, heads, url):
532 def unbundle(self, cg, heads, url):
401 '''Send cg (a readable file-like object representing the
533 '''Send cg (a readable file-like object representing the
402 changegroup to push, typically a chunkbuffer object) to the
534 changegroup to push, typically a chunkbuffer object) to the
403 remote server as a bundle.
535 remote server as a bundle.
404
536
405 When pushing a bundle10 stream, return an integer indicating the
537 When pushing a bundle10 stream, return an integer indicating the
406 result of the push (see changegroup.apply()).
538 result of the push (see changegroup.apply()).
407
539
408 When pushing a bundle20 stream, return a bundle20 stream.
540 When pushing a bundle20 stream, return a bundle20 stream.
409
541
410 `url` is the url the client thinks it's pushing to, which is
542 `url` is the url the client thinks it's pushing to, which is
411 visible to hooks.
543 visible to hooks.
412 '''
544 '''
413
545
414 if heads != ['force'] and self.capable('unbundlehash'):
546 if heads != ['force'] and self.capable('unbundlehash'):
415 heads = wireprototypes.encodelist(
547 heads = wireprototypes.encodelist(
416 ['hashed', hashlib.sha1(''.join(sorted(heads))).digest()])
548 ['hashed', hashlib.sha1(''.join(sorted(heads))).digest()])
417 else:
549 else:
418 heads = wireprototypes.encodelist(heads)
550 heads = wireprototypes.encodelist(heads)
419
551
420 if util.safehasattr(cg, 'deltaheader'):
552 if util.safehasattr(cg, 'deltaheader'):
421 # this a bundle10, do the old style call sequence
553 # this a bundle10, do the old style call sequence
422 ret, output = self._callpush("unbundle", cg, heads=heads)
554 ret, output = self._callpush("unbundle", cg, heads=heads)
423 if ret == "":
555 if ret == "":
424 raise error.ResponseError(
556 raise error.ResponseError(
425 _('push failed:'), output)
557 _('push failed:'), output)
426 try:
558 try:
427 ret = int(ret)
559 ret = int(ret)
428 except ValueError:
560 except ValueError:
429 raise error.ResponseError(
561 raise error.ResponseError(
430 _('push failed (unexpected response):'), ret)
562 _('push failed (unexpected response):'), ret)
431
563
432 for l in output.splitlines(True):
564 for l in output.splitlines(True):
433 self.ui.status(_('remote: '), l)
565 self.ui.status(_('remote: '), l)
434 else:
566 else:
435 # bundle2 push. Send a stream, fetch a stream.
567 # bundle2 push. Send a stream, fetch a stream.
436 stream = self._calltwowaystream('unbundle', cg, heads=heads)
568 stream = self._calltwowaystream('unbundle', cg, heads=heads)
437 ret = bundle2.getunbundler(self.ui, stream)
569 ret = bundle2.getunbundler(self.ui, stream)
438 return ret
570 return ret
439
571
440 # End of ipeercommands interface.
572 # End of ipeercommands interface.
441
573
442 # Begin of ipeerlegacycommands interface.
574 # Begin of ipeerlegacycommands interface.
443
575
444 def branches(self, nodes):
576 def branches(self, nodes):
445 n = wireprototypes.encodelist(nodes)
577 n = wireprototypes.encodelist(nodes)
446 d = self._call("branches", nodes=n)
578 d = self._call("branches", nodes=n)
447 try:
579 try:
448 br = [tuple(wireprototypes.decodelist(b)) for b in d.splitlines()]
580 br = [tuple(wireprototypes.decodelist(b)) for b in d.splitlines()]
449 return br
581 return br
450 except ValueError:
582 except ValueError:
451 self._abort(error.ResponseError(_("unexpected response:"), d))
583 self._abort(error.ResponseError(_("unexpected response:"), d))
452
584
453 def between(self, pairs):
585 def between(self, pairs):
454 batch = 8 # avoid giant requests
586 batch = 8 # avoid giant requests
455 r = []
587 r = []
456 for i in xrange(0, len(pairs), batch):
588 for i in xrange(0, len(pairs), batch):
457 n = " ".join([wireprototypes.encodelist(p, '-')
589 n = " ".join([wireprototypes.encodelist(p, '-')
458 for p in pairs[i:i + batch]])
590 for p in pairs[i:i + batch]])
459 d = self._call("between", pairs=n)
591 d = self._call("between", pairs=n)
460 try:
592 try:
461 r.extend(l and wireprototypes.decodelist(l) or []
593 r.extend(l and wireprototypes.decodelist(l) or []
462 for l in d.splitlines())
594 for l in d.splitlines())
463 except ValueError:
595 except ValueError:
464 self._abort(error.ResponseError(_("unexpected response:"), d))
596 self._abort(error.ResponseError(_("unexpected response:"), d))
465 return r
597 return r
466
598
467 def changegroup(self, nodes, kind):
599 def changegroup(self, nodes, kind):
468 n = wireprototypes.encodelist(nodes)
600 n = wireprototypes.encodelist(nodes)
469 f = self._callcompressable("changegroup", roots=n)
601 f = self._callcompressable("changegroup", roots=n)
470 return changegroupmod.cg1unpacker(f, 'UN')
602 return changegroupmod.cg1unpacker(f, 'UN')
471
603
472 def changegroupsubset(self, bases, heads, kind):
604 def changegroupsubset(self, bases, heads, kind):
473 self.requirecap('changegroupsubset', _('look up remote changes'))
605 self.requirecap('changegroupsubset', _('look up remote changes'))
474 bases = wireprototypes.encodelist(bases)
606 bases = wireprototypes.encodelist(bases)
475 heads = wireprototypes.encodelist(heads)
607 heads = wireprototypes.encodelist(heads)
476 f = self._callcompressable("changegroupsubset",
608 f = self._callcompressable("changegroupsubset",
477 bases=bases, heads=heads)
609 bases=bases, heads=heads)
478 return changegroupmod.cg1unpacker(f, 'UN')
610 return changegroupmod.cg1unpacker(f, 'UN')
479
611
480 # End of ipeerlegacycommands interface.
612 # End of ipeerlegacycommands interface.
481
613
482 def _submitbatch(self, req):
614 def _submitbatch(self, req):
483 """run batch request <req> on the server
615 """run batch request <req> on the server
484
616
485 Returns an iterator of the raw responses from the server.
617 Returns an iterator of the raw responses from the server.
486 """
618 """
487 ui = self.ui
619 ui = self.ui
488 if ui.debugflag and ui.configbool('devel', 'debug.peer-request'):
620 if ui.debugflag and ui.configbool('devel', 'debug.peer-request'):
489 ui.debug('devel-peer-request: batched-content\n')
621 ui.debug('devel-peer-request: batched-content\n')
490 for op, args in req:
622 for op, args in req:
491 msg = 'devel-peer-request: - %s (%d arguments)\n'
623 msg = 'devel-peer-request: - %s (%d arguments)\n'
492 ui.debug(msg % (op, len(args)))
624 ui.debug(msg % (op, len(args)))
493
625
494 unescapearg = wireprototypes.unescapebatcharg
626 unescapearg = wireprototypes.unescapebatcharg
495
627
496 rsp = self._callstream("batch", cmds=encodebatchcmds(req))
628 rsp = self._callstream("batch", cmds=encodebatchcmds(req))
497 chunk = rsp.read(1024)
629 chunk = rsp.read(1024)
498 work = [chunk]
630 work = [chunk]
499 while chunk:
631 while chunk:
500 while ';' not in chunk and chunk:
632 while ';' not in chunk and chunk:
501 chunk = rsp.read(1024)
633 chunk = rsp.read(1024)
502 work.append(chunk)
634 work.append(chunk)
503 merged = ''.join(work)
635 merged = ''.join(work)
504 while ';' in merged:
636 while ';' in merged:
505 one, merged = merged.split(';', 1)
637 one, merged = merged.split(';', 1)
506 yield unescapearg(one)
638 yield unescapearg(one)
507 chunk = rsp.read(1024)
639 chunk = rsp.read(1024)
508 work = [merged, chunk]
640 work = [merged, chunk]
509 yield unescapearg(''.join(work))
641 yield unescapearg(''.join(work))
510
642
511 def _submitone(self, op, args):
643 def _submitone(self, op, args):
512 return self._call(op, **pycompat.strkwargs(args))
644 return self._call(op, **pycompat.strkwargs(args))
513
645
514 def debugwireargs(self, one, two, three=None, four=None, five=None):
646 def debugwireargs(self, one, two, three=None, four=None, five=None):
515 # don't pass optional arguments left at their default value
647 # don't pass optional arguments left at their default value
516 opts = {}
648 opts = {}
517 if three is not None:
649 if three is not None:
518 opts[r'three'] = three
650 opts[r'three'] = three
519 if four is not None:
651 if four is not None:
520 opts[r'four'] = four
652 opts[r'four'] = four
521 return self._call('debugwireargs', one=one, two=two, **opts)
653 return self._call('debugwireargs', one=one, two=two, **opts)
522
654
523 def _call(self, cmd, **args):
655 def _call(self, cmd, **args):
524 """execute <cmd> on the server
656 """execute <cmd> on the server
525
657
526 The command is expected to return a simple string.
658 The command is expected to return a simple string.
527
659
528 returns the server reply as a string."""
660 returns the server reply as a string."""
529 raise NotImplementedError()
661 raise NotImplementedError()
530
662
531 def _callstream(self, cmd, **args):
663 def _callstream(self, cmd, **args):
532 """execute <cmd> on the server
664 """execute <cmd> on the server
533
665
534 The command is expected to return a stream. Note that if the
666 The command is expected to return a stream. Note that if the
535 command doesn't return a stream, _callstream behaves
667 command doesn't return a stream, _callstream behaves
536 differently for ssh and http peers.
668 differently for ssh and http peers.
537
669
538 returns the server reply as a file like object.
670 returns the server reply as a file like object.
539 """
671 """
540 raise NotImplementedError()
672 raise NotImplementedError()
541
673
542 def _callcompressable(self, cmd, **args):
674 def _callcompressable(self, cmd, **args):
543 """execute <cmd> on the server
675 """execute <cmd> on the server
544
676
545 The command is expected to return a stream.
677 The command is expected to return a stream.
546
678
547 The stream may have been compressed in some implementations. This
679 The stream may have been compressed in some implementations. This
548 function takes care of the decompression. This is the only difference
680 function takes care of the decompression. This is the only difference
549 with _callstream.
681 with _callstream.
550
682
551 returns the server reply as a file like object.
683 returns the server reply as a file like object.
552 """
684 """
553 raise NotImplementedError()
685 raise NotImplementedError()
554
686
555 def _callpush(self, cmd, fp, **args):
687 def _callpush(self, cmd, fp, **args):
556 """execute a <cmd> on server
688 """execute a <cmd> on server
557
689
558 The command is expected to be related to a push. Push has a special
690 The command is expected to be related to a push. Push has a special
559 return method.
691 return method.
560
692
561 returns the server reply as a (ret, output) tuple. ret is either
693 returns the server reply as a (ret, output) tuple. ret is either
562 empty (error) or a stringified int.
694 empty (error) or a stringified int.
563 """
695 """
564 raise NotImplementedError()
696 raise NotImplementedError()
565
697
566 def _calltwowaystream(self, cmd, fp, **args):
698 def _calltwowaystream(self, cmd, fp, **args):
567 """execute <cmd> on server
699 """execute <cmd> on server
568
700
569 The command will send a stream to the server and get a stream in reply.
701 The command will send a stream to the server and get a stream in reply.
570 """
702 """
571 raise NotImplementedError()
703 raise NotImplementedError()
572
704
573 def _abort(self, exception):
705 def _abort(self, exception):
574 """clearly abort the wire protocol connection and raise the exception
706 """clearly abort the wire protocol connection and raise the exception
575 """
707 """
576 raise NotImplementedError()
708 raise NotImplementedError()
General Comments 0
You need to be logged in to leave comments. Login now