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