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