]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/mutable/publish.py
start to factor server-connection-management into a distinct 'StorageServerFarmBroker...
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / mutable / publish.py
1
2
3 import os, struct, time
4 from itertools import count
5 from zope.interface import implements
6 from twisted.internet import defer
7 from twisted.python import failure
8 from allmydata.interfaces import IPublishStatus, FileTooLargeError
9 from allmydata.util import base32, hashutil, mathutil, idlib, log
10 from allmydata import hashtree, codec
11 from allmydata.storage.server import si_b2a
12 from pycryptopp.cipher.aes import AES
13 from foolscap.api import eventually
14
15 from common import MODE_WRITE, MODE_CHECK, DictOfSets, \
16      UncoordinatedWriteError, NotEnoughServersError
17 from servermap import ServerMap
18 from layout import pack_prefix, pack_share, unpack_header, pack_checkstring, \
19      unpack_checkstring, SIGNED_PREFIX
20
21 class PublishStatus:
22     implements(IPublishStatus)
23     statusid_counter = count(0)
24     def __init__(self):
25         self.timings = {}
26         self.timings["send_per_server"] = {}
27         self.servermap = None
28         self.problems = {}
29         self.active = True
30         self.storage_index = None
31         self.helper = False
32         self.encoding = ("?", "?")
33         self.size = None
34         self.status = "Not started"
35         self.progress = 0.0
36         self.counter = self.statusid_counter.next()
37         self.started = time.time()
38
39     def add_per_server_time(self, peerid, elapsed):
40         if peerid not in self.timings["send_per_server"]:
41             self.timings["send_per_server"][peerid] = []
42         self.timings["send_per_server"][peerid].append(elapsed)
43
44     def get_started(self):
45         return self.started
46     def get_storage_index(self):
47         return self.storage_index
48     def get_encoding(self):
49         return self.encoding
50     def using_helper(self):
51         return self.helper
52     def get_servermap(self):
53         return self.servermap
54     def get_size(self):
55         return self.size
56     def get_status(self):
57         return self.status
58     def get_progress(self):
59         return self.progress
60     def get_active(self):
61         return self.active
62     def get_counter(self):
63         return self.counter
64
65     def set_storage_index(self, si):
66         self.storage_index = si
67     def set_helper(self, helper):
68         self.helper = helper
69     def set_servermap(self, servermap):
70         self.servermap = servermap
71     def set_encoding(self, k, n):
72         self.encoding = (k, n)
73     def set_size(self, size):
74         self.size = size
75     def set_status(self, status):
76         self.status = status
77     def set_progress(self, value):
78         self.progress = value
79     def set_active(self, value):
80         self.active = value
81
82 class LoopLimitExceededError(Exception):
83     pass
84
85 class Publish:
86     """I represent a single act of publishing the mutable file to the grid. I
87     will only publish my data if the servermap I am using still represents
88     the current state of the world.
89
90     To make the initial publish, set servermap to None.
91     """
92
93     # we limit the segment size as usual to constrain our memory footprint.
94     # The max segsize is higher for mutable files, because we want to support
95     # dirnodes with up to 10k children, and each child uses about 330 bytes.
96     # If you actually put that much into a directory you'll be using a
97     # footprint of around 14MB, which is higher than we'd like, but it is
98     # more important right now to support large directories than to make
99     # memory usage small when you use them. Once we implement MDMF (with
100     # multiple segments), we will drop this back down, probably to 128KiB.
101     MAX_SEGMENT_SIZE = 3500000
102
103     def __init__(self, filenode, servermap):
104         self._node = filenode
105         self._servermap = servermap
106         self._storage_index = self._node.get_storage_index()
107         self._log_prefix = prefix = si_b2a(self._storage_index)[:5]
108         num = self._node._client.log("Publish(%s): starting" % prefix)
109         self._log_number = num
110         self._running = True
111         self._first_write_error = None
112
113         self._status = PublishStatus()
114         self._status.set_storage_index(self._storage_index)
115         self._status.set_helper(False)
116         self._status.set_progress(0.0)
117         self._status.set_active(True)
118
119     def get_status(self):
120         return self._status
121
122     def log(self, *args, **kwargs):
123         if 'parent' not in kwargs:
124             kwargs['parent'] = self._log_number
125         if "facility" not in kwargs:
126             kwargs["facility"] = "tahoe.mutable.publish"
127         return log.msg(*args, **kwargs)
128
129     def publish(self, newdata):
130         """Publish the filenode's current contents.  Returns a Deferred that
131         fires (with None) when the publish has done as much work as it's ever
132         going to do, or errbacks with ConsistencyError if it detects a
133         simultaneous write.
134         """
135
136         # 1: generate shares (SDMF: files are small, so we can do it in RAM)
137         # 2: perform peer selection, get candidate servers
138         #  2a: send queries to n+epsilon servers, to determine current shares
139         #  2b: based upon responses, create target map
140         # 3: send slot_testv_and_readv_and_writev messages
141         # 4: as responses return, update share-dispatch table
142         # 4a: may need to run recovery algorithm
143         # 5: when enough responses are back, we're done
144
145         self.log("starting publish, datalen is %s" % len(newdata))
146         if len(newdata) > self.MAX_SEGMENT_SIZE:
147             raise FileTooLargeError("SDMF is limited to one segment, and "
148                                     "%d > %d" % (len(newdata),
149                                                  self.MAX_SEGMENT_SIZE))
150         self._status.set_size(len(newdata))
151         self._status.set_status("Started")
152         self._started = time.time()
153
154         self.done_deferred = defer.Deferred()
155
156         self._writekey = self._node.get_writekey()
157         assert self._writekey, "need write capability to publish"
158
159         # first, which servers will we publish to? We require that the
160         # servermap was updated in MODE_WRITE, so we can depend upon the
161         # peerlist computed by that process instead of computing our own.
162         if self._servermap:
163             assert self._servermap.last_update_mode in (MODE_WRITE, MODE_CHECK)
164             # we will push a version that is one larger than anything present
165             # in the grid, according to the servermap.
166             self._new_seqnum = self._servermap.highest_seqnum() + 1
167         else:
168             # If we don't have a servermap, that's because we're doing the
169             # initial publish
170             self._new_seqnum = 1
171             self._servermap = ServerMap()
172         self._status.set_servermap(self._servermap)
173
174         self.log(format="new seqnum will be %(seqnum)d",
175                  seqnum=self._new_seqnum, level=log.NOISY)
176
177         # having an up-to-date servermap (or using a filenode that was just
178         # created for the first time) also guarantees that the following
179         # fields are available
180         self.readkey = self._node.get_readkey()
181         self.required_shares = self._node.get_required_shares()
182         assert self.required_shares is not None
183         self.total_shares = self._node.get_total_shares()
184         assert self.total_shares is not None
185         self._status.set_encoding(self.required_shares, self.total_shares)
186
187         self._pubkey = self._node.get_pubkey()
188         assert self._pubkey
189         self._privkey = self._node.get_privkey()
190         assert self._privkey
191         self._encprivkey = self._node.get_encprivkey()
192
193         sb = self._node._client.storage_broker
194         full_peerlist = sb.get_servers(self._storage_index)
195         self.full_peerlist = full_peerlist # for use later, immutable
196         self.bad_peers = set() # peerids who have errbacked/refused requests
197
198         self.newdata = newdata
199         self.salt = os.urandom(16)
200
201         self.setup_encoding_parameters()
202
203         # if we experience any surprises (writes which were rejected because
204         # our test vector did not match, or shares which we didn't expect to
205         # see), we set this flag and report an UncoordinatedWriteError at the
206         # end of the publish process.
207         self.surprised = False
208
209         # as a failsafe, refuse to iterate through self.loop more than a
210         # thousand times.
211         self.looplimit = 1000
212
213         # we keep track of three tables. The first is our goal: which share
214         # we want to see on which servers. This is initially populated by the
215         # existing servermap.
216         self.goal = set() # pairs of (peerid, shnum) tuples
217
218         # the second table is our list of outstanding queries: those which
219         # are in flight and may or may not be delivered, accepted, or
220         # acknowledged. Items are added to this table when the request is
221         # sent, and removed when the response returns (or errbacks).
222         self.outstanding = set() # (peerid, shnum) tuples
223
224         # the third is a table of successes: share which have actually been
225         # placed. These are populated when responses come back with success.
226         # When self.placed == self.goal, we're done.
227         self.placed = set() # (peerid, shnum) tuples
228
229         # we also keep a mapping from peerid to RemoteReference. Each time we
230         # pull a connection out of the full peerlist, we add it to this for
231         # use later.
232         self.connections = {}
233
234         self.bad_share_checkstrings = {}
235
236         # we use the servermap to populate the initial goal: this way we will
237         # try to update each existing share in place.
238         for (peerid, shnum) in self._servermap.servermap:
239             self.goal.add( (peerid, shnum) )
240             self.connections[peerid] = self._servermap.connections[peerid]
241         # then we add in all the shares that were bad (corrupted, bad
242         # signatures, etc). We want to replace these.
243         for key, old_checkstring in self._servermap.bad_shares.items():
244             (peerid, shnum) = key
245             self.goal.add(key)
246             self.bad_share_checkstrings[key] = old_checkstring
247             self.connections[peerid] = self._servermap.connections[peerid]
248
249         # create the shares. We'll discard these as they are delivered. SDMF:
250         # we're allowed to hold everything in memory.
251
252         self._status.timings["setup"] = time.time() - self._started
253         d = self._encrypt_and_encode()
254         d.addCallback(self._generate_shares)
255         def _start_pushing(res):
256             self._started_pushing = time.time()
257             return res
258         d.addCallback(_start_pushing)
259         d.addCallback(self.loop) # trigger delivery
260         d.addErrback(self._fatal_error)
261
262         return self.done_deferred
263
264     def setup_encoding_parameters(self):
265         segment_size = min(self.MAX_SEGMENT_SIZE, len(self.newdata))
266         # this must be a multiple of self.required_shares
267         segment_size = mathutil.next_multiple(segment_size,
268                                               self.required_shares)
269         self.segment_size = segment_size
270         if segment_size:
271             self.num_segments = mathutil.div_ceil(len(self.newdata),
272                                                   segment_size)
273         else:
274             self.num_segments = 0
275         assert self.num_segments in [0, 1,] # SDMF restrictions
276
277     def _fatal_error(self, f):
278         self.log("error during loop", failure=f, level=log.UNUSUAL)
279         self._done(f)
280
281     def _update_status(self):
282         self._status.set_status("Sending Shares: %d placed out of %d, "
283                                 "%d messages outstanding" %
284                                 (len(self.placed),
285                                  len(self.goal),
286                                  len(self.outstanding)))
287         self._status.set_progress(1.0 * len(self.placed) / len(self.goal))
288
289     def loop(self, ignored=None):
290         self.log("entering loop", level=log.NOISY)
291         if not self._running:
292             return
293
294         self.looplimit -= 1
295         if self.looplimit <= 0:
296             raise LoopLimitExceededError("loop limit exceeded")
297
298         if self.surprised:
299             # don't send out any new shares, just wait for the outstanding
300             # ones to be retired.
301             self.log("currently surprised, so don't send any new shares",
302                      level=log.NOISY)
303         else:
304             self.update_goal()
305             # how far are we from our goal?
306             needed = self.goal - self.placed - self.outstanding
307             self._update_status()
308
309             if needed:
310                 # we need to send out new shares
311                 self.log(format="need to send %(needed)d new shares",
312                          needed=len(needed), level=log.NOISY)
313                 self._send_shares(needed)
314                 return
315
316         if self.outstanding:
317             # queries are still pending, keep waiting
318             self.log(format="%(outstanding)d queries still outstanding",
319                      outstanding=len(self.outstanding),
320                      level=log.NOISY)
321             return
322
323         # no queries outstanding, no placements needed: we're done
324         self.log("no queries outstanding, no placements needed: done",
325                  level=log.OPERATIONAL)
326         now = time.time()
327         elapsed = now - self._started_pushing
328         self._status.timings["push"] = elapsed
329         return self._done(None)
330
331     def log_goal(self, goal, message=""):
332         logmsg = [message]
333         for (shnum, peerid) in sorted([(s,p) for (p,s) in goal]):
334             logmsg.append("sh%d to [%s]" % (shnum,
335                                             idlib.shortnodeid_b2a(peerid)))
336         self.log("current goal: %s" % (", ".join(logmsg)), level=log.NOISY)
337         self.log("we are planning to push new seqnum=#%d" % self._new_seqnum,
338                  level=log.NOISY)
339
340     def update_goal(self):
341         # if log.recording_noisy
342         if True:
343             self.log_goal(self.goal, "before update: ")
344
345         # first, remove any bad peers from our goal
346         self.goal = set([ (peerid, shnum)
347                           for (peerid, shnum) in self.goal
348                           if peerid not in self.bad_peers ])
349
350         # find the homeless shares:
351         homefull_shares = set([shnum for (peerid, shnum) in self.goal])
352         homeless_shares = set(range(self.total_shares)) - homefull_shares
353         homeless_shares = sorted(list(homeless_shares))
354         # place them somewhere. We prefer unused servers at the beginning of
355         # the available peer list.
356
357         if not homeless_shares:
358             return
359
360         # if an old share X is on a node, put the new share X there too.
361         # TODO: 1: redistribute shares to achieve one-per-peer, by copying
362         #       shares from existing peers to new (less-crowded) ones. The
363         #       old shares must still be updated.
364         # TODO: 2: move those shares instead of copying them, to reduce future
365         #       update work
366
367         # this is a bit CPU intensive but easy to analyze. We create a sort
368         # order for each peerid. If the peerid is marked as bad, we don't
369         # even put them in the list. Then we care about the number of shares
370         # which have already been assigned to them. After that we care about
371         # their permutation order.
372         old_assignments = DictOfSets()
373         for (peerid, shnum) in self.goal:
374             old_assignments.add(peerid, shnum)
375
376         peerlist = []
377         for i, (peerid, ss) in enumerate(self.full_peerlist):
378             if peerid in self.bad_peers:
379                 continue
380             entry = (len(old_assignments.get(peerid, [])), i, peerid, ss)
381             peerlist.append(entry)
382         peerlist.sort()
383
384         if not peerlist:
385             raise NotEnoughServersError("Ran out of non-bad servers, "
386                                         "first_error=%s" %
387                                         str(self._first_write_error),
388                                         self._first_write_error)
389
390         new_assignments = []
391         # we then index this peerlist with an integer, because we may have to
392         # wrap. We update the goal as we go.
393         i = 0
394         for shnum in homeless_shares:
395             (ignored1, ignored2, peerid, ss) = peerlist[i]
396             # if we are forced to send a share to a server that already has
397             # one, we may have two write requests in flight, and the
398             # servermap (which was computed before either request was sent)
399             # won't reflect the new shares, so the second response will be
400             # surprising. There is code in _got_write_answer() to tolerate
401             # this, otherwise it would cause the publish to fail with an
402             # UncoordinatedWriteError. See #546 for details of the trouble
403             # this used to cause.
404             self.goal.add( (peerid, shnum) )
405             self.connections[peerid] = ss
406             i += 1
407             if i >= len(peerlist):
408                 i = 0
409         if True:
410             self.log_goal(self.goal, "after update: ")
411
412
413
414     def _encrypt_and_encode(self):
415         # this returns a Deferred that fires with a list of (sharedata,
416         # sharenum) tuples. TODO: cache the ciphertext, only produce the
417         # shares that we care about.
418         self.log("_encrypt_and_encode")
419
420         self._status.set_status("Encrypting")
421         started = time.time()
422
423         key = hashutil.ssk_readkey_data_hash(self.salt, self.readkey)
424         enc = AES(key)
425         crypttext = enc.process(self.newdata)
426         assert len(crypttext) == len(self.newdata)
427
428         now = time.time()
429         self._status.timings["encrypt"] = now - started
430         started = now
431
432         # now apply FEC
433
434         self._status.set_status("Encoding")
435         fec = codec.CRSEncoder()
436         fec.set_params(self.segment_size,
437                        self.required_shares, self.total_shares)
438         piece_size = fec.get_block_size()
439         crypttext_pieces = [None] * self.required_shares
440         for i in range(len(crypttext_pieces)):
441             offset = i * piece_size
442             piece = crypttext[offset:offset+piece_size]
443             piece = piece + "\x00"*(piece_size - len(piece)) # padding
444             crypttext_pieces[i] = piece
445             assert len(piece) == piece_size
446
447         d = fec.encode(crypttext_pieces)
448         def _done_encoding(res):
449             elapsed = time.time() - started
450             self._status.timings["encode"] = elapsed
451             return res
452         d.addCallback(_done_encoding)
453         return d
454
455     def _generate_shares(self, shares_and_shareids):
456         # this sets self.shares and self.root_hash
457         self.log("_generate_shares")
458         self._status.set_status("Generating Shares")
459         started = time.time()
460
461         # we should know these by now
462         privkey = self._privkey
463         encprivkey = self._encprivkey
464         pubkey = self._pubkey
465
466         (shares, share_ids) = shares_and_shareids
467
468         assert len(shares) == len(share_ids)
469         assert len(shares) == self.total_shares
470         all_shares = {}
471         block_hash_trees = {}
472         share_hash_leaves = [None] * len(shares)
473         for i in range(len(shares)):
474             share_data = shares[i]
475             shnum = share_ids[i]
476             all_shares[shnum] = share_data
477
478             # build the block hash tree. SDMF has only one leaf.
479             leaves = [hashutil.block_hash(share_data)]
480             t = hashtree.HashTree(leaves)
481             block_hash_trees[shnum] = block_hash_tree = list(t)
482             share_hash_leaves[shnum] = t[0]
483         for leaf in share_hash_leaves:
484             assert leaf is not None
485         share_hash_tree = hashtree.HashTree(share_hash_leaves)
486         share_hash_chain = {}
487         for shnum in range(self.total_shares):
488             needed_hashes = share_hash_tree.needed_hashes(shnum)
489             share_hash_chain[shnum] = dict( [ (i, share_hash_tree[i])
490                                               for i in needed_hashes ] )
491         root_hash = share_hash_tree[0]
492         assert len(root_hash) == 32
493         self.log("my new root_hash is %s" % base32.b2a(root_hash))
494         self._new_version_info = (self._new_seqnum, root_hash, self.salt)
495
496         prefix = pack_prefix(self._new_seqnum, root_hash, self.salt,
497                              self.required_shares, self.total_shares,
498                              self.segment_size, len(self.newdata))
499
500         # now pack the beginning of the share. All shares are the same up
501         # to the signature, then they have divergent share hash chains,
502         # then completely different block hash trees + salt + share data,
503         # then they all share the same encprivkey at the end. The sizes
504         # of everything are the same for all shares.
505
506         sign_started = time.time()
507         signature = privkey.sign(prefix)
508         self._status.timings["sign"] = time.time() - sign_started
509
510         verification_key = pubkey.serialize()
511
512         final_shares = {}
513         for shnum in range(self.total_shares):
514             final_share = pack_share(prefix,
515                                      verification_key,
516                                      signature,
517                                      share_hash_chain[shnum],
518                                      block_hash_trees[shnum],
519                                      all_shares[shnum],
520                                      encprivkey)
521             final_shares[shnum] = final_share
522         elapsed = time.time() - started
523         self._status.timings["pack"] = elapsed
524         self.shares = final_shares
525         self.root_hash = root_hash
526
527         # we also need to build up the version identifier for what we're
528         # pushing. Extract the offsets from one of our shares.
529         assert final_shares
530         offsets = unpack_header(final_shares.values()[0])[-1]
531         offsets_tuple = tuple( [(key,value) for key,value in offsets.items()] )
532         verinfo = (self._new_seqnum, root_hash, self.salt,
533                    self.segment_size, len(self.newdata),
534                    self.required_shares, self.total_shares,
535                    prefix, offsets_tuple)
536         self.versioninfo = verinfo
537
538
539
540     def _send_shares(self, needed):
541         self.log("_send_shares")
542
543         # we're finally ready to send out our shares. If we encounter any
544         # surprises here, it's because somebody else is writing at the same
545         # time. (Note: in the future, when we remove the _query_peers() step
546         # and instead speculate about [or remember] which shares are where,
547         # surprises here are *not* indications of UncoordinatedWriteError,
548         # and we'll need to respond to them more gracefully.)
549
550         # needed is a set of (peerid, shnum) tuples. The first thing we do is
551         # organize it by peerid.
552
553         peermap = DictOfSets()
554         for (peerid, shnum) in needed:
555             peermap.add(peerid, shnum)
556
557         # the next thing is to build up a bunch of test vectors. The
558         # semantics of Publish are that we perform the operation if the world
559         # hasn't changed since the ServerMap was constructed (more or less).
560         # For every share we're trying to place, we create a test vector that
561         # tests to see if the server*share still corresponds to the
562         # map.
563
564         all_tw_vectors = {} # maps peerid to tw_vectors
565         sm = self._servermap.servermap
566
567         for key in needed:
568             (peerid, shnum) = key
569
570             if key in sm:
571                 # an old version of that share already exists on the
572                 # server, according to our servermap. We will create a
573                 # request that attempts to replace it.
574                 old_versionid, old_timestamp = sm[key]
575                 (old_seqnum, old_root_hash, old_salt, old_segsize,
576                  old_datalength, old_k, old_N, old_prefix,
577                  old_offsets_tuple) = old_versionid
578                 old_checkstring = pack_checkstring(old_seqnum,
579                                                    old_root_hash,
580                                                    old_salt)
581                 testv = (0, len(old_checkstring), "eq", old_checkstring)
582
583             elif key in self.bad_share_checkstrings:
584                 old_checkstring = self.bad_share_checkstrings[key]
585                 testv = (0, len(old_checkstring), "eq", old_checkstring)
586
587             else:
588                 # add a testv that requires the share not exist
589
590                 # Unfortunately, foolscap-0.2.5 has a bug in the way inbound
591                 # constraints are handled. If the same object is referenced
592                 # multiple times inside the arguments, foolscap emits a
593                 # 'reference' token instead of a distinct copy of the
594                 # argument. The bug is that these 'reference' tokens are not
595                 # accepted by the inbound constraint code. To work around
596                 # this, we need to prevent python from interning the
597                 # (constant) tuple, by creating a new copy of this vector
598                 # each time.
599
600                 # This bug is fixed in foolscap-0.2.6, and even though this
601                 # version of Tahoe requires foolscap-0.3.1 or newer, we are
602                 # supposed to be able to interoperate with older versions of
603                 # Tahoe which are allowed to use older versions of foolscap,
604                 # including foolscap-0.2.5 . In addition, I've seen other
605                 # foolscap problems triggered by 'reference' tokens (see #541
606                 # for details). So we must keep this workaround in place.
607
608                 #testv = (0, 1, 'eq', "")
609                 testv = tuple([0, 1, 'eq', ""])
610
611             testvs = [testv]
612             # the write vector is simply the share
613             writev = [(0, self.shares[shnum])]
614
615             if peerid not in all_tw_vectors:
616                 all_tw_vectors[peerid] = {}
617                 # maps shnum to (testvs, writevs, new_length)
618             assert shnum not in all_tw_vectors[peerid]
619
620             all_tw_vectors[peerid][shnum] = (testvs, writev, None)
621
622         # we read the checkstring back from each share, however we only use
623         # it to detect whether there was a new share that we didn't know
624         # about. The success or failure of the write will tell us whether
625         # there was a collision or not. If there is a collision, the first
626         # thing we'll do is update the servermap, which will find out what
627         # happened. We could conceivably reduce a roundtrip by using the
628         # readv checkstring to populate the servermap, but really we'd have
629         # to read enough data to validate the signatures too, so it wouldn't
630         # be an overall win.
631         read_vector = [(0, struct.calcsize(SIGNED_PREFIX))]
632
633         # ok, send the messages!
634         self.log("sending %d shares" % len(all_tw_vectors), level=log.NOISY)
635         started = time.time()
636         for (peerid, tw_vectors) in all_tw_vectors.items():
637
638             write_enabler = self._node.get_write_enabler(peerid)
639             renew_secret = self._node.get_renewal_secret(peerid)
640             cancel_secret = self._node.get_cancel_secret(peerid)
641             secrets = (write_enabler, renew_secret, cancel_secret)
642             shnums = tw_vectors.keys()
643
644             for shnum in shnums:
645                 self.outstanding.add( (peerid, shnum) )
646
647             d = self._do_testreadwrite(peerid, secrets,
648                                        tw_vectors, read_vector)
649             d.addCallbacks(self._got_write_answer, self._got_write_error,
650                            callbackArgs=(peerid, shnums, started),
651                            errbackArgs=(peerid, shnums, started))
652             d.addCallback(self.loop)
653             d.addErrback(self._fatal_error)
654
655         self._update_status()
656         self.log("%d shares sent" % len(all_tw_vectors), level=log.NOISY)
657
658     def _do_testreadwrite(self, peerid, secrets,
659                           tw_vectors, read_vector):
660         storage_index = self._storage_index
661         ss = self.connections[peerid]
662
663         #print "SS[%s] is %s" % (idlib.shortnodeid_b2a(peerid), ss), ss.tracker.interfaceName
664         d = ss.callRemote("slot_testv_and_readv_and_writev",
665                           storage_index,
666                           secrets,
667                           tw_vectors,
668                           read_vector)
669         return d
670
671     def _got_write_answer(self, answer, peerid, shnums, started):
672         lp = self.log("_got_write_answer from %s" %
673                       idlib.shortnodeid_b2a(peerid))
674         for shnum in shnums:
675             self.outstanding.discard( (peerid, shnum) )
676
677         now = time.time()
678         elapsed = now - started
679         self._status.add_per_server_time(peerid, elapsed)
680
681         wrote, read_data = answer
682
683         surprise_shares = set(read_data.keys()) - set(shnums)
684
685         surprised = False
686         for shnum in surprise_shares:
687             # read_data is a dict mapping shnum to checkstring (SIGNED_PREFIX)
688             checkstring = read_data[shnum][0]
689             their_version_info = unpack_checkstring(checkstring)
690             if their_version_info == self._new_version_info:
691                 # they have the right share, somehow
692
693                 if (peerid,shnum) in self.goal:
694                     # and we want them to have it, so we probably sent them a
695                     # copy in an earlier write. This is ok, and avoids the
696                     # #546 problem.
697                     continue
698
699                 # They aren't in our goal, but they are still for the right
700                 # version. Somebody else wrote them, and it's a convergent
701                 # uncoordinated write. Pretend this is ok (don't be
702                 # surprised), since I suspect there's a decent chance that
703                 # we'll hit this in normal operation.
704                 continue
705
706             else:
707                 # the new shares are of a different version
708                 if peerid in self._servermap.reachable_peers:
709                     # we asked them about their shares, so we had knowledge
710                     # of what they used to have. Any surprising shares must
711                     # have come from someone else, so UCW.
712                     surprised = True
713                 else:
714                     # we didn't ask them, and now we've discovered that they
715                     # have a share we didn't know about. This indicates that
716                     # mapupdate should have wokred harder and asked more
717                     # servers before concluding that it knew about them all.
718
719                     # signal UCW, but make sure to ask this peer next time,
720                     # so we'll remember to update it if/when we retry.
721                     surprised = True
722                     # TODO: ask this peer next time. I don't yet have a good
723                     # way to do this. Two insufficient possibilities are:
724                     #
725                     # self._servermap.add_new_share(peerid, shnum, verinfo, now)
726                     #  but that requires fetching/validating/parsing the whole
727                     #  version string, and all we have is the checkstring
728                     # self._servermap.mark_bad_share(peerid, shnum, checkstring)
729                     #  that will make publish overwrite the share next time,
730                     #  but it won't re-query the server, and it won't make
731                     #  mapupdate search further
732
733                     # TODO later: when publish starts, do
734                     # servermap.get_best_version(), extract the seqnum,
735                     # subtract one, and store as highest-replaceable-seqnum.
736                     # Then, if this surprise-because-we-didn't-ask share is
737                     # of highest-replaceable-seqnum or lower, we're allowed
738                     # to replace it: send out a new writev (or rather add it
739                     # to self.goal and loop).
740                     pass
741
742                 surprised = True
743
744         if surprised:
745             self.log("they had shares %s that we didn't know about" %
746                      (list(surprise_shares),),
747                      parent=lp, level=log.WEIRD, umid="un9CSQ")
748             self.surprised = True
749
750         if not wrote:
751             # TODO: there are two possibilities. The first is that the server
752             # is full (or just doesn't want to give us any room), which means
753             # we shouldn't ask them again, but is *not* an indication of an
754             # uncoordinated write. The second is that our testv failed, which
755             # *does* indicate an uncoordinated write. We currently don't have
756             # a way to tell these two apart (in fact, the storage server code
757             # doesn't have the option of refusing our share).
758             #
759             # If the server is full, mark the peer as bad (so we don't ask
760             # them again), but don't set self.surprised. The loop() will find
761             # a new server.
762             #
763             # If the testv failed, log it, set self.surprised, but don't
764             # bother adding to self.bad_peers .
765
766             self.log("our testv failed, so the write did not happen",
767                      parent=lp, level=log.WEIRD, umid="8sc26g")
768             self.surprised = True
769             self.bad_peers.add(peerid) # don't ask them again
770             # use the checkstring to add information to the log message
771             for (shnum,readv) in read_data.items():
772                 checkstring = readv[0]
773                 (other_seqnum,
774                  other_roothash,
775                  other_salt) = unpack_checkstring(checkstring)
776                 expected_version = self._servermap.version_on_peer(peerid,
777                                                                    shnum)
778                 if expected_version:
779                     (seqnum, root_hash, IV, segsize, datalength, k, N, prefix,
780                      offsets_tuple) = expected_version
781                     self.log("somebody modified the share on us:"
782                              " shnum=%d: I thought they had #%d:R=%s,"
783                              " but testv reported #%d:R=%s" %
784                              (shnum,
785                               seqnum, base32.b2a(root_hash)[:4],
786                               other_seqnum, base32.b2a(other_roothash)[:4]),
787                              parent=lp, level=log.NOISY)
788                 # if expected_version==None, then we didn't expect to see a
789                 # share on that peer, and the 'surprise_shares' clause above
790                 # will have logged it.
791             # self.loop() will take care of finding new homes
792             return
793
794         for shnum in shnums:
795             self.placed.add( (peerid, shnum) )
796             # and update the servermap
797             self._servermap.add_new_share(peerid, shnum,
798                                           self.versioninfo, started)
799
800         # self.loop() will take care of checking to see if we're done
801         return
802
803     def _got_write_error(self, f, peerid, shnums, started):
804         for shnum in shnums:
805             self.outstanding.discard( (peerid, shnum) )
806         self.bad_peers.add(peerid)
807         if self._first_write_error is None:
808             self._first_write_error = f
809         self.log(format="error while writing shares %(shnums)s to peerid %(peerid)s",
810                  shnums=list(shnums), peerid=idlib.shortnodeid_b2a(peerid),
811                  failure=f,
812                  level=log.UNUSUAL)
813         # self.loop() will take care of checking to see if we're done
814         return
815
816
817     def _done(self, res):
818         if not self._running:
819             return
820         self._running = False
821         now = time.time()
822         self._status.timings["total"] = now - self._started
823         self._status.set_active(False)
824         if isinstance(res, failure.Failure):
825             self.log("Publish done, with failure", failure=res,
826                      level=log.WEIRD, umid="nRsR9Q")
827             self._status.set_status("Failed")
828         elif self.surprised:
829             self.log("Publish done, UncoordinatedWriteError", level=log.UNUSUAL)
830             self._status.set_status("UncoordinatedWriteError")
831             # deliver a failure
832             res = failure.Failure(UncoordinatedWriteError())
833             # TODO: recovery
834         else:
835             self.log("Publish done, success")
836             self._status.set_status("Done")
837             self._status.set_progress(1.0)
838         eventually(self.done_deferred.callback, res)
839
840