]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/mutable/publish.py
Overhaul IFilesystemNode handling, to simplify tests and use POLA internally.
[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 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, storage_broker, servermap):
94         self._node = filenode
95         self._storage_broker = storage_broker
96         self._servermap = servermap
97         self._storage_index = self._node.get_storage_index()
98         self._log_prefix = prefix = si_b2a(self._storage_index)[:5]
99         num = self.log("Publish(%s): starting" % prefix, parent=None)
100         self._log_number = num
101         self._running = True
102         self._first_write_error = None
103
104         self._status = PublishStatus()
105         self._status.set_storage_index(self._storage_index)
106         self._status.set_helper(False)
107         self._status.set_progress(0.0)
108         self._status.set_active(True)
109
110     def get_status(self):
111         return self._status
112
113     def log(self, *args, **kwargs):
114         if 'parent' not in kwargs:
115             kwargs['parent'] = self._log_number
116         if "facility" not in kwargs:
117             kwargs["facility"] = "tahoe.mutable.publish"
118         return log.msg(*args, **kwargs)
119
120     def publish(self, newdata):
121         """Publish the filenode's current contents.  Returns a Deferred that
122         fires (with None) when the publish has done as much work as it's ever
123         going to do, or errbacks with ConsistencyError if it detects a
124         simultaneous write.
125         """
126
127         # 1: generate shares (SDMF: files are small, so we can do it in RAM)
128         # 2: perform peer selection, get candidate servers
129         #  2a: send queries to n+epsilon servers, to determine current shares
130         #  2b: based upon responses, create target map
131         # 3: send slot_testv_and_readv_and_writev messages
132         # 4: as responses return, update share-dispatch table
133         # 4a: may need to run recovery algorithm
134         # 5: when enough responses are back, we're done
135
136         self.log("starting publish, datalen is %s" % len(newdata))
137         self._status.set_size(len(newdata))
138         self._status.set_status("Started")
139         self._started = time.time()
140
141         self.done_deferred = defer.Deferred()
142
143         self._writekey = self._node.get_writekey()
144         assert self._writekey, "need write capability to publish"
145
146         # first, which servers will we publish to? We require that the
147         # servermap was updated in MODE_WRITE, so we can depend upon the
148         # peerlist computed by that process instead of computing our own.
149         if self._servermap:
150             assert self._servermap.last_update_mode in (MODE_WRITE, MODE_CHECK)
151             # we will push a version that is one larger than anything present
152             # in the grid, according to the servermap.
153             self._new_seqnum = self._servermap.highest_seqnum() + 1
154         else:
155             # If we don't have a servermap, that's because we're doing the
156             # initial publish
157             self._new_seqnum = 1
158             self._servermap = ServerMap()
159         self._status.set_servermap(self._servermap)
160
161         self.log(format="new seqnum will be %(seqnum)d",
162                  seqnum=self._new_seqnum, level=log.NOISY)
163
164         # having an up-to-date servermap (or using a filenode that was just
165         # created for the first time) also guarantees that the following
166         # fields are available
167         self.readkey = self._node.get_readkey()
168         self.required_shares = self._node.get_required_shares()
169         assert self.required_shares is not None
170         self.total_shares = self._node.get_total_shares()
171         assert self.total_shares is not None
172         self._status.set_encoding(self.required_shares, self.total_shares)
173
174         self._pubkey = self._node.get_pubkey()
175         assert self._pubkey
176         self._privkey = self._node.get_privkey()
177         assert self._privkey
178         self._encprivkey = self._node.get_encprivkey()
179
180         sb = self._storage_broker
181         full_peerlist = sb.get_servers_for_index(self._storage_index)
182         self.full_peerlist = full_peerlist # for use later, immutable
183         self.bad_peers = set() # peerids who have errbacked/refused requests
184
185         self.newdata = newdata
186         self.salt = os.urandom(16)
187
188         self.setup_encoding_parameters()
189
190         # if we experience any surprises (writes which were rejected because
191         # our test vector did not match, or shares which we didn't expect to
192         # see), we set this flag and report an UncoordinatedWriteError at the
193         # end of the publish process.
194         self.surprised = False
195
196         # as a failsafe, refuse to iterate through self.loop more than a
197         # thousand times.
198         self.looplimit = 1000
199
200         # we keep track of three tables. The first is our goal: which share
201         # we want to see on which servers. This is initially populated by the
202         # existing servermap.
203         self.goal = set() # pairs of (peerid, shnum) tuples
204
205         # the second table is our list of outstanding queries: those which
206         # are in flight and may or may not be delivered, accepted, or
207         # acknowledged. Items are added to this table when the request is
208         # sent, and removed when the response returns (or errbacks).
209         self.outstanding = set() # (peerid, shnum) tuples
210
211         # the third is a table of successes: share which have actually been
212         # placed. These are populated when responses come back with success.
213         # When self.placed == self.goal, we're done.
214         self.placed = set() # (peerid, shnum) tuples
215
216         # we also keep a mapping from peerid to RemoteReference. Each time we
217         # pull a connection out of the full peerlist, we add it to this for
218         # use later.
219         self.connections = {}
220
221         self.bad_share_checkstrings = {}
222
223         # we use the servermap to populate the initial goal: this way we will
224         # try to update each existing share in place.
225         for (peerid, shnum) in self._servermap.servermap:
226             self.goal.add( (peerid, shnum) )
227             self.connections[peerid] = self._servermap.connections[peerid]
228         # then we add in all the shares that were bad (corrupted, bad
229         # signatures, etc). We want to replace these.
230         for key, old_checkstring in self._servermap.bad_shares.items():
231             (peerid, shnum) = key
232             self.goal.add(key)
233             self.bad_share_checkstrings[key] = old_checkstring
234             self.connections[peerid] = self._servermap.connections[peerid]
235
236         # create the shares. We'll discard these as they are delivered. SDMF:
237         # we're allowed to hold everything in memory.
238
239         self._status.timings["setup"] = time.time() - self._started
240         d = self._encrypt_and_encode()
241         d.addCallback(self._generate_shares)
242         def _start_pushing(res):
243             self._started_pushing = time.time()
244             return res
245         d.addCallback(_start_pushing)
246         d.addCallback(self.loop) # trigger delivery
247         d.addErrback(self._fatal_error)
248
249         return self.done_deferred
250
251     def setup_encoding_parameters(self):
252         segment_size = len(self.newdata)
253         # this must be a multiple of self.required_shares
254         segment_size = mathutil.next_multiple(segment_size,
255                                               self.required_shares)
256         self.segment_size = segment_size
257         if segment_size:
258             self.num_segments = mathutil.div_ceil(len(self.newdata),
259                                                   segment_size)
260         else:
261             self.num_segments = 0
262         assert self.num_segments in [0, 1,] # SDMF restrictions
263
264     def _fatal_error(self, f):
265         self.log("error during loop", failure=f, level=log.UNUSUAL)
266         self._done(f)
267
268     def _update_status(self):
269         self._status.set_status("Sending Shares: %d placed out of %d, "
270                                 "%d messages outstanding" %
271                                 (len(self.placed),
272                                  len(self.goal),
273                                  len(self.outstanding)))
274         self._status.set_progress(1.0 * len(self.placed) / len(self.goal))
275
276     def loop(self, ignored=None):
277         self.log("entering loop", level=log.NOISY)
278         if not self._running:
279             return
280
281         self.looplimit -= 1
282         if self.looplimit <= 0:
283             raise LoopLimitExceededError("loop limit exceeded")
284
285         if self.surprised:
286             # don't send out any new shares, just wait for the outstanding
287             # ones to be retired.
288             self.log("currently surprised, so don't send any new shares",
289                      level=log.NOISY)
290         else:
291             self.update_goal()
292             # how far are we from our goal?
293             needed = self.goal - self.placed - self.outstanding
294             self._update_status()
295
296             if needed:
297                 # we need to send out new shares
298                 self.log(format="need to send %(needed)d new shares",
299                          needed=len(needed), level=log.NOISY)
300                 self._send_shares(needed)
301                 return
302
303         if self.outstanding:
304             # queries are still pending, keep waiting
305             self.log(format="%(outstanding)d queries still outstanding",
306                      outstanding=len(self.outstanding),
307                      level=log.NOISY)
308             return
309
310         # no queries outstanding, no placements needed: we're done
311         self.log("no queries outstanding, no placements needed: done",
312                  level=log.OPERATIONAL)
313         now = time.time()
314         elapsed = now - self._started_pushing
315         self._status.timings["push"] = elapsed
316         return self._done(None)
317
318     def log_goal(self, goal, message=""):
319         logmsg = [message]
320         for (shnum, peerid) in sorted([(s,p) for (p,s) in goal]):
321             logmsg.append("sh%d to [%s]" % (shnum,
322                                             idlib.shortnodeid_b2a(peerid)))
323         self.log("current goal: %s" % (", ".join(logmsg)), level=log.NOISY)
324         self.log("we are planning to push new seqnum=#%d" % self._new_seqnum,
325                  level=log.NOISY)
326
327     def update_goal(self):
328         # if log.recording_noisy
329         if True:
330             self.log_goal(self.goal, "before update: ")
331
332         # first, remove any bad peers from our goal
333         self.goal = set([ (peerid, shnum)
334                           for (peerid, shnum) in self.goal
335                           if peerid not in self.bad_peers ])
336
337         # find the homeless shares:
338         homefull_shares = set([shnum for (peerid, shnum) in self.goal])
339         homeless_shares = set(range(self.total_shares)) - homefull_shares
340         homeless_shares = sorted(list(homeless_shares))
341         # place them somewhere. We prefer unused servers at the beginning of
342         # the available peer list.
343
344         if not homeless_shares:
345             return
346
347         # if an old share X is on a node, put the new share X there too.
348         # TODO: 1: redistribute shares to achieve one-per-peer, by copying
349         #       shares from existing peers to new (less-crowded) ones. The
350         #       old shares must still be updated.
351         # TODO: 2: move those shares instead of copying them, to reduce future
352         #       update work
353
354         # this is a bit CPU intensive but easy to analyze. We create a sort
355         # order for each peerid. If the peerid is marked as bad, we don't
356         # even put them in the list. Then we care about the number of shares
357         # which have already been assigned to them. After that we care about
358         # their permutation order.
359         old_assignments = DictOfSets()
360         for (peerid, shnum) in self.goal:
361             old_assignments.add(peerid, shnum)
362
363         peerlist = []
364         for i, (peerid, ss) in enumerate(self.full_peerlist):
365             if peerid in self.bad_peers:
366                 continue
367             entry = (len(old_assignments.get(peerid, [])), i, peerid, ss)
368             peerlist.append(entry)
369         peerlist.sort()
370
371         if not peerlist:
372             raise NotEnoughServersError("Ran out of non-bad servers, "
373                                         "first_error=%s" %
374                                         str(self._first_write_error),
375                                         self._first_write_error)
376
377         new_assignments = []
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] = block_hash_tree = 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             d.addCallback(self.loop)
640             d.addErrback(self._fatal_error)
641
642         self._update_status()
643         self.log("%d shares sent" % len(all_tw_vectors), level=log.NOISY)
644
645     def _do_testreadwrite(self, peerid, secrets,
646                           tw_vectors, read_vector):
647         storage_index = self._storage_index
648         ss = self.connections[peerid]
649
650         #print "SS[%s] is %s" % (idlib.shortnodeid_b2a(peerid), ss), ss.tracker.interfaceName
651         d = ss.callRemote("slot_testv_and_readv_and_writev",
652                           storage_index,
653                           secrets,
654                           tw_vectors,
655                           read_vector)
656         return d
657
658     def _got_write_answer(self, answer, peerid, shnums, started):
659         lp = self.log("_got_write_answer from %s" %
660                       idlib.shortnodeid_b2a(peerid))
661         for shnum in shnums:
662             self.outstanding.discard( (peerid, shnum) )
663
664         now = time.time()
665         elapsed = now - started
666         self._status.add_per_server_time(peerid, elapsed)
667
668         wrote, read_data = answer
669
670         surprise_shares = set(read_data.keys()) - set(shnums)
671
672         surprised = False
673         for shnum in surprise_shares:
674             # read_data is a dict mapping shnum to checkstring (SIGNED_PREFIX)
675             checkstring = read_data[shnum][0]
676             their_version_info = unpack_checkstring(checkstring)
677             if their_version_info == self._new_version_info:
678                 # they have the right share, somehow
679
680                 if (peerid,shnum) in self.goal:
681                     # and we want them to have it, so we probably sent them a
682                     # copy in an earlier write. This is ok, and avoids the
683                     # #546 problem.
684                     continue
685
686                 # They aren't in our goal, but they are still for the right
687                 # version. Somebody else wrote them, and it's a convergent
688                 # uncoordinated write. Pretend this is ok (don't be
689                 # surprised), since I suspect there's a decent chance that
690                 # we'll hit this in normal operation.
691                 continue
692
693             else:
694                 # the new shares are of a different version
695                 if peerid in self._servermap.reachable_peers:
696                     # we asked them about their shares, so we had knowledge
697                     # of what they used to have. Any surprising shares must
698                     # have come from someone else, so UCW.
699                     surprised = True
700                 else:
701                     # we didn't ask them, and now we've discovered that they
702                     # have a share we didn't know about. This indicates that
703                     # mapupdate should have wokred harder and asked more
704                     # servers before concluding that it knew about them all.
705
706                     # signal UCW, but make sure to ask this peer next time,
707                     # so we'll remember to update it if/when we retry.
708                     surprised = True
709                     # TODO: ask this peer next time. I don't yet have a good
710                     # way to do this. Two insufficient possibilities are:
711                     #
712                     # self._servermap.add_new_share(peerid, shnum, verinfo, now)
713                     #  but that requires fetching/validating/parsing the whole
714                     #  version string, and all we have is the checkstring
715                     # self._servermap.mark_bad_share(peerid, shnum, checkstring)
716                     #  that will make publish overwrite the share next time,
717                     #  but it won't re-query the server, and it won't make
718                     #  mapupdate search further
719
720                     # TODO later: when publish starts, do
721                     # servermap.get_best_version(), extract the seqnum,
722                     # subtract one, and store as highest-replaceable-seqnum.
723                     # Then, if this surprise-because-we-didn't-ask share is
724                     # of highest-replaceable-seqnum or lower, we're allowed
725                     # to replace it: send out a new writev (or rather add it
726                     # to self.goal and loop).
727                     pass
728
729                 surprised = True
730
731         if surprised:
732             self.log("they had shares %s that we didn't know about" %
733                      (list(surprise_shares),),
734                      parent=lp, level=log.WEIRD, umid="un9CSQ")
735             self.surprised = True
736
737         if not wrote:
738             # TODO: there are two possibilities. The first is that the server
739             # is full (or just doesn't want to give us any room), which means
740             # we shouldn't ask them again, but is *not* an indication of an
741             # uncoordinated write. The second is that our testv failed, which
742             # *does* indicate an uncoordinated write. We currently don't have
743             # a way to tell these two apart (in fact, the storage server code
744             # doesn't have the option of refusing our share).
745             #
746             # If the server is full, mark the peer as bad (so we don't ask
747             # them again), but don't set self.surprised. The loop() will find
748             # a new server.
749             #
750             # If the testv failed, log it, set self.surprised, but don't
751             # bother adding to self.bad_peers .
752
753             self.log("our testv failed, so the write did not happen",
754                      parent=lp, level=log.WEIRD, umid="8sc26g")
755             self.surprised = True
756             self.bad_peers.add(peerid) # don't ask them again
757             # use the checkstring to add information to the log message
758             for (shnum,readv) in read_data.items():
759                 checkstring = readv[0]
760                 (other_seqnum,
761                  other_roothash,
762                  other_salt) = unpack_checkstring(checkstring)
763                 expected_version = self._servermap.version_on_peer(peerid,
764                                                                    shnum)
765                 if expected_version:
766                     (seqnum, root_hash, IV, segsize, datalength, k, N, prefix,
767                      offsets_tuple) = expected_version
768                     self.log("somebody modified the share on us:"
769                              " shnum=%d: I thought they had #%d:R=%s,"
770                              " but testv reported #%d:R=%s" %
771                              (shnum,
772                               seqnum, base32.b2a(root_hash)[:4],
773                               other_seqnum, base32.b2a(other_roothash)[:4]),
774                              parent=lp, level=log.NOISY)
775                 # if expected_version==None, then we didn't expect to see a
776                 # share on that peer, and the 'surprise_shares' clause above
777                 # will have logged it.
778             # self.loop() will take care of finding new homes
779             return
780
781         for shnum in shnums:
782             self.placed.add( (peerid, shnum) )
783             # and update the servermap
784             self._servermap.add_new_share(peerid, shnum,
785                                           self.versioninfo, started)
786
787         # self.loop() will take care of checking to see if we're done
788         return
789
790     def _got_write_error(self, f, peerid, shnums, started):
791         for shnum in shnums:
792             self.outstanding.discard( (peerid, shnum) )
793         self.bad_peers.add(peerid)
794         if self._first_write_error is None:
795             self._first_write_error = f
796         self.log(format="error while writing shares %(shnums)s to peerid %(peerid)s",
797                  shnums=list(shnums), peerid=idlib.shortnodeid_b2a(peerid),
798                  failure=f,
799                  level=log.UNUSUAL)
800         # self.loop() will take care of checking to see if we're done
801         return
802
803
804     def _done(self, res):
805         if not self._running:
806             return
807         self._running = False
808         now = time.time()
809         self._status.timings["total"] = now - self._started
810         self._status.set_active(False)
811         if isinstance(res, failure.Failure):
812             self.log("Publish done, with failure", failure=res,
813                      level=log.WEIRD, umid="nRsR9Q")
814             self._status.set_status("Failed")
815         elif self.surprised:
816             self.log("Publish done, UncoordinatedWriteError", level=log.UNUSUAL)
817             self._status.set_status("UncoordinatedWriteError")
818             # deliver a failure
819             res = failure.Failure(UncoordinatedWriteError())
820             # TODO: recovery
821         else:
822             self.log("Publish done, success")
823             self._status.set_status("Done")
824             self._status.set_progress(1.0)
825         eventually(self.done_deferred.callback, res)
826
827