source file: /home/buildslave/tahoe/edgy/build/src/allmydata/immutable/encode.py
file stats: 468 lines, 428 executed: 91.5% covered
   1. # -*- test-case-name: allmydata.test.test_encode -*-
   2. 
   3. import time
   4. from zope.interface import implements
   5. from twisted.internet import defer
   6. from foolscap import eventual
   7. from allmydata import storage, uri
   8. from allmydata.hashtree import HashTree
   9. from allmydata.util import mathutil, hashutil, base32, log
  10. from allmydata.util.assertutil import _assert, precondition
  11. from allmydata.codec import CRSEncoder
  12. from allmydata.interfaces import IEncoder, IStorageBucketWriter, \
  13.      IEncryptedUploadable, IUploadStatus
  14. 
  15. """
  16. The goal of the encoder is to turn the original file into a series of
  17. 'shares'. Each share is going to a 'shareholder' (nominally each shareholder
  18. is a different host, but for small grids there may be overlap). The number
  19. of shares is chosen to hit our reliability goals (more shares on more
  20. machines means more reliability), and is limited by overhead (proportional to
  21. numshares or log(numshares)) and the encoding technology in use (zfec permits
  22. only 256 shares total). It is also constrained by the amount of data
  23. we want to send to each host. For estimating purposes, think of 10 shares
  24. out of which we need 3 to reconstruct the file.
  25. 
  26. The encoder starts by cutting the original file into segments. All segments
  27. except the last are of equal size. The segment size is chosen to constrain
  28. the memory footprint (which will probably vary between 1x and 4x segment
  29. size) and to constrain the overhead (which will be proportional to
  30. log(number of segments)).
  31. 
  32. 
  33. Each segment (A,B,C) is read into memory, encrypted, and encoded into
  34. blocks. The 'share' (say, share #1) that makes it out to a host is a
  35. collection of these blocks (block A1, B1, C1), plus some hash-tree
  36. information necessary to validate the data upon retrieval. Only one segment
  37. is handled at a time: all blocks for segment A are delivered before any
  38. work is begun on segment B.
  39. 
  40. As blocks are created, we retain the hash of each one. The list of block hashes
  41. for a single share (say, hash(A1), hash(B1), hash(C1)) is used to form the base
  42. of a Merkle hash tree for that share, called the block hash tree.
  43. 
  44. This hash tree has one terminal leaf per block. The complete block hash
  45. tree is sent to the shareholder after all the data has been sent. At
  46. retrieval time, the decoder will ask for specific pieces of this tree before
  47. asking for blocks, whichever it needs to validate those blocks.
  48. 
  49. (Note: we don't really need to generate this whole block hash tree
  50. ourselves. It would be sufficient to have the shareholder generate it and
  51. just tell us the root. This gives us an extra level of validation on the
  52. transfer, though, and it is relatively cheap to compute.)
  53. 
  54. Each of these block hash trees has a root hash. The collection of these
  55. root hashes for all shares are collected into the 'share hash tree', which
  56. has one terminal leaf per share. After sending the blocks and the complete
  57. block hash tree to each shareholder, we send them the portion of the share
  58. hash tree that is necessary to validate their share. The root of the share
  59. hash tree is put into the URI.
  60. 
  61. """
  62. 
  63. class NotEnoughSharesError(Exception):
  64.     servermap = None
  65.     pass
  66. 
  67. class UploadAborted(Exception):
  68.     pass
  69. 
  70. KiB=1024
  71. MiB=1024*KiB
  72. GiB=1024*MiB
  73. TiB=1024*GiB
  74. PiB=1024*TiB
  75. 
  76. class Encoder(object):
  77.     implements(IEncoder)
  78.     USE_PLAINTEXT_HASHES = False
  79. 
  80.     def __init__(self, log_parent=None, upload_status=None):
  81.         object.__init__(self)
  82.         self.uri_extension_data = {}
  83.         self._codec = None
  84.         self._status = None
  85.         if upload_status:
  86.             self._status = IUploadStatus(upload_status)
  87.         precondition(log_parent is None or isinstance(log_parent, int),
  88.                      log_parent)
  89.         self._log_number = log.msg("creating Encoder %s" % self,
  90.                                    facility="tahoe.encoder", parent=log_parent)
  91.         self._aborted = False
  92. 
  93.     def __repr__(self):
  94.         if hasattr(self, "_storage_index"):
  95.             return "<Encoder for %s>" % storage.si_b2a(self._storage_index)[:5]
  96.         return "<Encoder for unknown storage index>"
  97. 
  98.     def log(self, *args, **kwargs):
  99.         if "parent" not in kwargs:
 100.             kwargs["parent"] = self._log_number
 101.         if "facility" not in kwargs:
 102.             kwargs["facility"] = "tahoe.encoder"
 103.         return log.msg(*args, **kwargs)
 104. 
 105.     def set_encrypted_uploadable(self, uploadable):
 106.         eu = self._uploadable = IEncryptedUploadable(uploadable)
 107.         d = eu.get_size()
 108.         def _got_size(size):
 109.             self.log(format="file size: %(size)d", size=size)
 110.             self.file_size = size
 111.         d.addCallback(_got_size)
 112.         d.addCallback(lambda res: eu.get_all_encoding_parameters())
 113.         d.addCallback(self._got_all_encoding_parameters)
 114.         d.addCallback(lambda res: eu.get_storage_index())
 115.         def _done(storage_index):
 116.             self._storage_index = storage_index
 117.             return self
 118.         d.addCallback(_done)
 119.         return d
 120. 
 121.     def _got_all_encoding_parameters(self, params):
 122.         assert not self._codec
 123.         k, happy, n, segsize = params
 124.         self.required_shares = k
 125.         self.shares_of_happiness = happy
 126.         self.num_shares = n
 127.         self.segment_size = segsize
 128.         self.log("got encoding parameters: %d/%d/%d %d" % (k,happy,n, segsize))
 129.         self.log("now setting up codec")
 130. 
 131.         assert self.segment_size % self.required_shares == 0
 132. 
 133.         self.num_segments = mathutil.div_ceil(self.file_size,
 134.                                               self.segment_size)
 135. 
 136.         self._codec = CRSEncoder()
 137.         self._codec.set_params(self.segment_size,
 138.                                self.required_shares, self.num_shares)
 139. 
 140.         data = self.uri_extension_data
 141.         data['codec_name'] = self._codec.get_encoder_type()
 142.         data['codec_params'] = self._codec.get_serialized_params()
 143. 
 144.         data['size'] = self.file_size
 145.         data['segment_size'] = self.segment_size
 146.         self.share_size = mathutil.div_ceil(self.file_size,
 147.                                             self.required_shares)
 148.         data['num_segments'] = self.num_segments
 149.         data['needed_shares'] = self.required_shares
 150.         data['total_shares'] = self.num_shares
 151. 
 152.         # the "tail" is the last segment. This segment may or may not be
 153.         # shorter than all other segments. We use the "tail codec" to handle
 154.         # it. If the tail is short, we use a different codec instance. In
 155.         # addition, the tail codec must be fed data which has been padded out
 156.         # to the right size.
 157.         self.tail_size = self.file_size % self.segment_size
 158.         if not self.tail_size:
 159.             self.tail_size = self.segment_size
 160. 
 161.         # the tail codec is responsible for encoding tail_size bytes
 162.         padded_tail_size = mathutil.next_multiple(self.tail_size,
 163.                                                   self.required_shares)
 164.         self._tail_codec = CRSEncoder()
 165.         self._tail_codec.set_params(padded_tail_size,
 166.                                     self.required_shares, self.num_shares)
 167.         data['tail_codec_params'] = self._tail_codec.get_serialized_params()
 168. 
 169.     def _get_share_size(self):
 170.         share_size = mathutil.div_ceil(self.file_size, self.required_shares)
 171.         overhead = self._compute_overhead()
 172.         return share_size + overhead
 173. 
 174.     def _compute_overhead(self):
 175.         return 0
 176. 
 177.     def get_param(self, name):
 178.         assert self._codec
 179. 
 180.         if name == "storage_index":
 181.             return self._storage_index
 182.         elif name == "share_counts":
 183.             return (self.required_shares, self.shares_of_happiness,
 184.                     self.num_shares)
 185.         elif name == "num_segments":
 186.             return self.num_segments
 187.         elif name == "segment_size":
 188.             return self.segment_size
 189.         elif name == "block_size":
 190.             return self._codec.get_block_size()
 191.         elif name == "share_size":
 192.             return self._get_share_size()
 193.         elif name == "serialized_params":
 194.             return self._codec.get_serialized_params()
 195.         else:
 196.             raise KeyError("unknown parameter name '%s'" % name)
 197. 
 198.     def set_shareholders(self, landlords):
 199.         assert isinstance(landlords, dict)
 200.         for k in landlords:
 201.             assert IStorageBucketWriter.providedBy(landlords[k])
 202.         self.landlords = landlords.copy()
 203. 
 204.     def start(self):
 205.         self.log("%s starting" % (self,))
 206.         #paddedsize = self._size + mathutil.pad_size(self._size, self.needed_shares)
 207.         assert self._codec
 208.         self._crypttext_hasher = hashutil.crypttext_hasher()
 209.         self._crypttext_hashes = []
 210.         self.segment_num = 0
 211.         self.subshare_hashes = [[] for x in range(self.num_shares)]
 212.         # subshare_hashes[i] is a list that will be accumulated and then send
 213.         # to landlord[i]. This list contains a hash of each segment_share
 214.         # that we sent to that landlord.
 215.         self.share_root_hashes = [None] * self.num_shares
 216. 
 217.         self._times = {
 218.             "cumulative_encoding": 0.0,
 219.             "cumulative_sending": 0.0,
 220.             "hashes_and_close": 0.0,
 221.             "total_encode_and_push": 0.0,
 222.             }
 223.         self._start_total_timestamp = time.time()
 224. 
 225.         d = eventual.fireEventually()
 226. 
 227.         d.addCallback(lambda res: self.start_all_shareholders())
 228. 
 229.         for i in range(self.num_segments-1):
 230.             # note to self: this form doesn't work, because lambda only
 231.             # captures the slot, not the value
 232.             #d.addCallback(lambda res: self.do_segment(i))
 233.             # use this form instead:
 234.             d.addCallback(lambda res, i=i: self._encode_segment(i))
 235.             d.addCallback(self._send_segment, i)
 236.             d.addCallback(self._turn_barrier)
 237.         last_segnum = self.num_segments - 1
 238.         d.addCallback(lambda res: self._encode_tail_segment(last_segnum))
 239.         d.addCallback(self._send_segment, last_segnum)
 240.         d.addCallback(self._turn_barrier)
 241. 
 242.         d.addCallback(lambda res: self.finish_hashing())
 243. 
 244.         if self.USE_PLAINTEXT_HASHES:
 245.             d.addCallback(lambda res:
 246.                           self.send_plaintext_hash_tree_to_all_shareholders())
 247.         d.addCallback(lambda res:
 248.                       self.send_crypttext_hash_tree_to_all_shareholders())
 249.         d.addCallback(lambda res: self.send_all_subshare_hash_trees())
 250.         d.addCallback(lambda res: self.send_all_share_hash_trees())
 251.         d.addCallback(lambda res: self.send_uri_extension_to_all_shareholders())
 252. 
 253.         d.addCallback(lambda res: self.close_all_shareholders())
 254.         d.addCallbacks(self.done, self.err)
 255.         return d
 256. 
 257.     def set_status(self, status):
 258.         if self._status:
 259.             self._status.set_status(status)
 260. 
 261.     def set_encode_and_push_progress(self, sent_segments=None, extra=0.0):
 262.         if self._status:
 263.             # we treat the final hash+close as an extra segment
 264.             if sent_segments is None:
 265.                 sent_segments = self.num_segments
 266.             progress = float(sent_segments + extra) / (self.num_segments + 1)
 267.             self._status.set_progress(2, progress)
 268. 
 269.     def abort(self):
 270.         self.log("aborting upload", level=log.UNUSUAL)
 271.         assert self._codec, "don't call abort before start"
 272.         self._aborted = True
 273.         # the next segment read (in _gather_data inside _encode_segment) will
 274.         # raise UploadAborted(), which will bypass the rest of the upload
 275.         # chain. If we've sent the final segment's shares, it's too late to
 276.         # abort. TODO: allow abort any time up to close_all_shareholders.
 277. 
 278.     def _turn_barrier(self, res):
 279.         # putting this method in a Deferred chain imposes a guaranteed
 280.         # reactor turn between the pre- and post- portions of that chain.
 281.         # This can be useful to limit memory consumption: since Deferreds do
 282.         # not do tail recursion, code which uses defer.succeed(result) for
 283.         # consistency will cause objects to live for longer than you might
 284.         # normally expect.
 285. 
 286.         return eventual.fireEventually(res)
 287. 
 288. 
 289.     def start_all_shareholders(self):
 290.         self.log("starting shareholders", level=log.NOISY)
 291.         self.set_status("Starting shareholders")
 292.         dl = []
 293.         for shareid in self.landlords:
 294.             d = self.landlords[shareid].start()
 295.             d.addErrback(self._remove_shareholder, shareid, "start")
 296.             dl.append(d)
 297.         return self._gather_responses(dl)
 298. 
 299.     def _encode_segment(self, segnum):
 300.         codec = self._codec
 301.         start = time.time()
 302. 
 303.         # the ICodecEncoder API wants to receive a total of self.segment_size
 304.         # bytes on each encode() call, broken up into a number of
 305.         # identically-sized pieces. Due to the way the codec algorithm works,
 306.         # these pieces need to be the same size as the share which the codec
 307.         # will generate. Therefore we must feed it with input_piece_size that
 308.         # equals the output share size.
 309.         input_piece_size = codec.get_block_size()
 310. 
 311.         # as a result, the number of input pieces per encode() call will be
 312.         # equal to the number of required shares with which the codec was
 313.         # constructed. You can think of the codec as chopping up a
 314.         # 'segment_size' of data into 'required_shares' shares (not doing any
 315.         # fancy math at all, just doing a split), then creating some number
 316.         # of additional shares which can be substituted if the primary ones
 317.         # are unavailable
 318. 
 319.         crypttext_segment_hasher = hashutil.crypttext_segment_hasher()
 320. 
 321.         # memory footprint: we only hold a tiny piece of the plaintext at any
 322.         # given time. We build up a segment's worth of cryptttext, then hand
 323.         # it to the encoder. Assuming 3-of-10 encoding (3.3x expansion) and
 324.         # 1MiB max_segment_size, we get a peak memory footprint of 4.3*1MiB =
 325.         # 4.3MiB. Lowering max_segment_size to, say, 100KiB would drop the
 326.         # footprint to 430KiB at the expense of more hash-tree overhead.
 327. 
 328.         d = self._gather_data(self.required_shares, input_piece_size,
 329.                               crypttext_segment_hasher)
 330.         def _done_gathering(chunks):
 331.             for c in chunks:
 332.                 assert len(c) == input_piece_size
 333.             self._crypttext_hashes.append(crypttext_segment_hasher.digest())
 334.             # during this call, we hit 5*segsize memory
 335.             return codec.encode(chunks)
 336.         d.addCallback(_done_gathering)
 337.         def _done(res):
 338.             elapsed = time.time() - start
 339.             self._times["cumulative_encoding"] += elapsed
 340.             return res
 341.         d.addCallback(_done)
 342.         return d
 343. 
 344.     def _encode_tail_segment(self, segnum):
 345. 
 346.         start = time.time()
 347.         codec = self._tail_codec
 348.         input_piece_size = codec.get_block_size()
 349. 
 350.         crypttext_segment_hasher = hashutil.crypttext_segment_hasher()
 351. 
 352.         d = self._gather_data(self.required_shares, input_piece_size,
 353.                               crypttext_segment_hasher,
 354.                               allow_short=True)
 355.         def _done_gathering(chunks):
 356.             for c in chunks:
 357.                 # a short trailing chunk will have been padded by
 358.                 # _gather_data
 359.                 assert len(c) == input_piece_size
 360.             self._crypttext_hashes.append(crypttext_segment_hasher.digest())
 361.             return codec.encode(chunks)
 362.         d.addCallback(_done_gathering)
 363.         def _done(res):
 364.             elapsed = time.time() - start
 365.             self._times["cumulative_encoding"] += elapsed
 366.             return res
 367.         d.addCallback(_done)
 368.         return d
 369. 
 370.     def _gather_data(self, num_chunks, input_chunk_size,
 371.                      crypttext_segment_hasher,
 372.                      allow_short=False,
 373.                      previous_chunks=[]):
 374.         """Return a Deferred that will fire when the required number of
 375.         chunks have been read (and hashed and encrypted). The Deferred fires
 376.         with the combination of any 'previous_chunks' and the new chunks
 377.         which were gathered."""
 378. 
 379.         if self._aborted:
 380.             raise UploadAborted()
 381. 
 382.         if not num_chunks:
 383.             return defer.succeed(previous_chunks)
 384. 
 385.         d = self._uploadable.read_encrypted(input_chunk_size, False)
 386.         def _got(data):
 387.             if self._aborted:
 388.                 raise UploadAborted()
 389.             encrypted_pieces = []
 390.             length = 0
 391.             while data:
 392.                 encrypted_piece = data.pop(0)
 393.                 length += len(encrypted_piece)
 394.                 crypttext_segment_hasher.update(encrypted_piece)
 395.                 self._crypttext_hasher.update(encrypted_piece)
 396.                 encrypted_pieces.append(encrypted_piece)
 397. 
 398.             if allow_short:
 399.                 if length < input_chunk_size:
 400.                     # padding
 401.                     pad_size = input_chunk_size - length
 402.                     encrypted_pieces.append('\x00' * pad_size)
 403.             else:
 404.                 # non-tail segments should be the full segment size
 405.                 if length != input_chunk_size:
 406.                     log.msg("non-tail segment should be full segment size: %d!=%d"
 407.                             % (length, input_chunk_size),
 408.                             level=log.BAD, umid="jNk5Yw")
 409.                 precondition(length == input_chunk_size,
 410.                              "length=%d != input_chunk_size=%d" %
 411.                              (length, input_chunk_size))
 412. 
 413.             encrypted_piece = "".join(encrypted_pieces)
 414.             return previous_chunks + [encrypted_piece]
 415. 
 416.         d.addCallback(_got)
 417.         d.addCallback(lambda chunks:
 418.                       self._gather_data(num_chunks-1, input_chunk_size,
 419.                                         crypttext_segment_hasher,
 420.                                         allow_short, chunks))
 421.         return d
 422. 
 423.     def _send_segment(self, (shares, shareids), segnum):
 424.         # To generate the URI, we must generate the roothash, so we must
 425.         # generate all shares, even if we aren't actually giving them to
 426.         # anybody. This means that the set of shares we create will be equal
 427.         # to or larger than the set of landlords. If we have any landlord who
 428.         # *doesn't* have a share, that's an error.
 429.         _assert(set(self.landlords.keys()).issubset(set(shareids)),
 430.                 shareids=shareids, landlords=self.landlords)
 431.         start = time.time()
 432.         dl = []
 433.         self.set_status("Sending segment %d of %d" % (segnum+1,
 434.                                                       self.num_segments))
 435.         self.set_encode_and_push_progress(segnum)
 436.         lognum = self.log("send_segment(%d)" % segnum, level=log.NOISY)
 437.         for i in range(len(shares)):
 438.             subshare = shares[i]
 439.             shareid = shareids[i]
 440.             d = self.send_subshare(shareid, segnum, subshare, lognum)
 441.             dl.append(d)
 442.             subshare_hash = hashutil.block_hash(subshare)
 443.             #from allmydata.util import base32
 444.             #log.msg("creating block (shareid=%d, blocknum=%d) "
 445.             #        "len=%d %r .. %r: %s" %
 446.             #        (shareid, segnum, len(subshare),
 447.             #         subshare[:50], subshare[-50:], base32.b2a(subshare_hash)))
 448.             self.subshare_hashes[shareid].append(subshare_hash)
 449. 
 450.         dl = self._gather_responses(dl)
 451.         def _logit(res):
 452.             self.log("%s uploaded %s / %s bytes (%d%%) of your file." %
 453.                      (self,
 454.                       self.segment_size*(segnum+1),
 455.                       self.segment_size*self.num_segments,
 456.                       100 * (segnum+1) / self.num_segments,
 457.                       ),
 458.                      level=log.OPERATIONAL)
 459.             elapsed = time.time() - start
 460.             self._times["cumulative_sending"] += elapsed
 461.             return res
 462.         dl.addCallback(_logit)
 463.         return dl
 464. 
 465.     def send_subshare(self, shareid, segment_num, subshare, lognum):
 466.         if shareid not in self.landlords:
 467.             return defer.succeed(None)
 468.         sh = self.landlords[shareid]
 469.         lognum2 = self.log("put_block to %s" % self.landlords[shareid],
 470.                            parent=lognum, level=log.NOISY)
 471.         d = sh.put_block(segment_num, subshare)
 472.         def _done(res):
 473.             self.log("put_block done", parent=lognum2, level=log.NOISY)
 474.             return res
 475.         d.addCallback(_done)
 476.         d.addErrback(self._remove_shareholder, shareid,
 477.                      "segnum=%d" % segment_num)
 478.         return d
 479. 
 480.     def _remove_shareholder(self, why, shareid, where):
 481.         ln = self.log(format="error while sending %(method)s to shareholder=%(shnum)d",
 482.                       method=where, shnum=shareid,
 483.                       level=log.UNUSUAL, failure=why)
 484.         if shareid in self.landlords:
 485.             self.landlords[shareid].abort()
 486.             del self.landlords[shareid]
 487.         else:
 488.             # even more UNUSUAL
 489.             self.log("they weren't in our list of landlords", parent=ln,
 490.                      level=log.WEIRD, umid="TQGFRw")
 491.         if len(self.landlords) < self.shares_of_happiness:
 492.             msg = "lost too many shareholders during upload: %s" % why
 493.             raise NotEnoughSharesError(msg)
 494.         self.log("but we can still continue with %s shares, we'll be happy "
 495.                  "with at least %s" % (len(self.landlords),
 496.                                        self.shares_of_happiness),
 497.                  parent=ln)
 498. 
 499.     def _gather_responses(self, dl):
 500.         d = defer.DeferredList(dl, fireOnOneErrback=True)
 501.         def _eatNotEnoughSharesError(f):
 502.             # all exceptions that occur while talking to a peer are handled
 503.             # in _remove_shareholder. That might raise NotEnoughSharesError,
 504.             # which will cause the DeferredList to errback but which should
 505.             # otherwise be consumed. Allow non-NotEnoughSharesError exceptions
 506.             # to pass through as an unhandled errback. We use this in lieu of
 507.             # consumeErrors=True to allow coding errors to be logged.
 508.             f.trap(NotEnoughSharesError)
 509.             return None
 510.         for d0 in dl:
 511.             d0.addErrback(_eatNotEnoughSharesError)
 512.         return d
 513. 
 514.     def finish_hashing(self):
 515.         self._start_hashing_and_close_timestamp = time.time()
 516.         self.set_status("Finishing hashes")
 517.         self.set_encode_and_push_progress(extra=0.0)
 518.         crypttext_hash = self._crypttext_hasher.digest()
 519.         self.uri_extension_data["crypttext_hash"] = crypttext_hash
 520.         d = self._uploadable.get_plaintext_hash()
 521.         def _got(plaintext_hash):
 522.             self.log(format="plaintext_hash=%(plaintext_hash)s, SI=%(SI)s, size=%(size)d",
 523.                      plaintext_hash=base32.b2a(plaintext_hash),
 524.                      SI=storage.si_b2a(self._storage_index),
 525.                      size=self.file_size)
 526.             return plaintext_hash
 527.         d.addCallback(_got)
 528.         if self.USE_PLAINTEXT_HASHES:
 529.             def _use_plaintext_hash(plaintext_hash):
 530.                 self.uri_extension_data["plaintext_hash"] = plaintext_hash
 531.                 return self._uploadable.get_plaintext_hashtree_leaves(0, self.num_segments, self.num_segments)
 532.             d.addCallback(_use_plaintext_hash)
 533.             def _got_hashtree_leaves(leaves):
 534.                 self.log("Encoder: got plaintext_hashtree_leaves: %s" %
 535.                          (",".join([base32.b2a(h) for h in leaves]),),
 536.                          level=log.NOISY)
 537.                 ht = list(HashTree(list(leaves)))
 538.                 self.uri_extension_data["plaintext_root_hash"] = ht[0]
 539.                 self._plaintext_hashtree_nodes = ht
 540.             d.addCallback(_got_hashtree_leaves)
 541. 
 542.         d.addCallback(lambda res: self._uploadable.close())
 543.         return d
 544. 
 545.     def send_plaintext_hash_tree_to_all_shareholders(self):
 546.         self.log("sending plaintext hash tree", level=log.NOISY)
 547.         self.set_status("Sending Plaintext Hash Tree")
 548.         self.set_encode_and_push_progress(extra=0.2)
 549.         dl = []
 550.         for shareid in self.landlords.keys():
 551.             d = self.send_plaintext_hash_tree(shareid,
 552.                                               self._plaintext_hashtree_nodes)
 553.             dl.append(d)
 554.         return self._gather_responses(dl)
 555. 
 556.     def send_plaintext_hash_tree(self, shareid, all_hashes):
 557.         if shareid not in self.landlords:
 558.             return defer.succeed(None)
 559.         sh = self.landlords[shareid]
 560.         d = sh.put_plaintext_hashes(all_hashes)
 561.         d.addErrback(self._remove_shareholder, shareid, "put_plaintext_hashes")
 562.         return d
 563. 
 564.     def send_crypttext_hash_tree_to_all_shareholders(self):
 565.         self.log("sending crypttext hash tree", level=log.NOISY)
 566.         self.set_status("Sending Crypttext Hash Tree")
 567.         self.set_encode_and_push_progress(extra=0.3)
 568.         t = HashTree(self._crypttext_hashes)
 569.         all_hashes = list(t)
 570.         self.uri_extension_data["crypttext_root_hash"] = t[0]
 571.         dl = []
 572.         for shareid in self.landlords.keys():
 573.             dl.append(self.send_crypttext_hash_tree(shareid, all_hashes))
 574.         return self._gather_responses(dl)
 575. 
 576.     def send_crypttext_hash_tree(self, shareid, all_hashes):
 577.         if shareid not in self.landlords:
 578.             return defer.succeed(None)
 579.         sh = self.landlords[shareid]
 580.         d = sh.put_crypttext_hashes(all_hashes)
 581.         d.addErrback(self._remove_shareholder, shareid, "put_crypttext_hashes")
 582.         return d
 583. 
 584.     def send_all_subshare_hash_trees(self):
 585.         self.log("sending subshare hash trees", level=log.NOISY)
 586.         self.set_status("Sending Subshare Hash Trees")
 587.         self.set_encode_and_push_progress(extra=0.4)
 588.         dl = []
 589.         for shareid,hashes in enumerate(self.subshare_hashes):
 590.             # hashes is a list of the hashes of all subshares that were sent
 591.             # to shareholder[shareid].
 592.             dl.append(self.send_one_subshare_hash_tree(shareid, hashes))
 593.         return self._gather_responses(dl)
 594. 
 595.     def send_one_subshare_hash_tree(self, shareid, subshare_hashes):
 596.         t = HashTree(subshare_hashes)
 597.         all_hashes = list(t)
 598.         # all_hashes[0] is the root hash, == hash(ah[1]+ah[2])
 599.         # all_hashes[1] is the left child, == hash(ah[3]+ah[4])
 600.         # all_hashes[n] == hash(all_hashes[2*n+1] + all_hashes[2*n+2])
 601.         self.share_root_hashes[shareid] = t[0]
 602.         if shareid not in self.landlords:
 603.             return defer.succeed(None)
 604.         sh = self.landlords[shareid]
 605.         d = sh.put_block_hashes(all_hashes)
 606.         d.addErrback(self._remove_shareholder, shareid, "put_block_hashes")
 607.         return d
 608. 
 609.     def send_all_share_hash_trees(self):
 610.         # each bucket gets a set of share hash tree nodes that are needed to
 611.         # validate their share. This includes the share hash itself, but does
 612.         # not include the top-level hash root (which is stored securely in
 613.         # the URI instead).
 614.         self.log("sending all share hash trees", level=log.NOISY)
 615.         self.set_status("Sending Share Hash Trees")
 616.         self.set_encode_and_push_progress(extra=0.6)
 617.         dl = []
 618.         for h in self.share_root_hashes:
 619.             assert h
 620.         # create the share hash tree
 621.         t = HashTree(self.share_root_hashes)
 622.         # the root of this hash tree goes into our URI
 623.         self.uri_extension_data['share_root_hash'] = t[0]
 624.         # now send just the necessary pieces out to each shareholder
 625.         for i in range(self.num_shares):
 626.             # the HashTree is given a list of leaves: 0,1,2,3..n .
 627.             # These become nodes A+0,A+1,A+2.. of the tree, where A=n-1
 628.             needed_hash_indices = t.needed_hashes(i, include_leaf=True)
 629.             hashes = [(hi, t[hi]) for hi in needed_hash_indices]
 630.             dl.append(self.send_one_share_hash_tree(i, hashes))
 631.         return self._gather_responses(dl)
 632. 
 633.     def send_one_share_hash_tree(self, shareid, needed_hashes):
 634.         if shareid not in self.landlords:
 635.             return defer.succeed(None)
 636.         sh = self.landlords[shareid]
 637.         d = sh.put_share_hashes(needed_hashes)
 638.         d.addErrback(self._remove_shareholder, shareid, "put_share_hashes")
 639.         return d
 640. 
 641.     def send_uri_extension_to_all_shareholders(self):
 642.         lp = self.log("sending uri_extension", level=log.NOISY)
 643.         self.set_status("Sending URI Extensions")
 644.         self.set_encode_and_push_progress(extra=0.8)
 645.         for k in ('crypttext_root_hash', 'crypttext_hash',
 646.                   ):
 647.             assert k in self.uri_extension_data
 648.         if self.USE_PLAINTEXT_HASHES:
 649.             for k in ('plaintext_root_hash', 'plaintext_hash',
 650.                       ):
 651.                 assert k in self.uri_extension_data
 652.         uri_extension = uri.pack_extension(self.uri_extension_data)
 653.         ed = {}
 654.         for k,v in self.uri_extension_data.items():
 655.             if k.endswith("hash"):
 656.                 ed[k] = base32.b2a(v)
 657.             else:
 658.                 ed[k] = v
 659.         self.log("uri_extension_data is %s" % (ed,), level=log.NOISY, parent=lp)
 660.         self.uri_extension_hash = hashutil.uri_extension_hash(uri_extension)
 661.         dl = []
 662.         for shareid in self.landlords.keys():
 663.             dl.append(self.send_uri_extension(shareid, uri_extension))
 664.         return self._gather_responses(dl)
 665. 
 666.     def send_uri_extension(self, shareid, uri_extension):
 667.         sh = self.landlords[shareid]
 668.         d = sh.put_uri_extension(uri_extension)
 669.         d.addErrback(self._remove_shareholder, shareid, "put_uri_extension")
 670.         return d
 671. 
 672.     def close_all_shareholders(self):
 673.         self.log("closing shareholders", level=log.NOISY)
 674.         self.set_status("Closing Shareholders")
 675.         self.set_encode_and_push_progress(extra=0.9)
 676.         dl = []
 677.         for shareid in self.landlords:
 678.             d = self.landlords[shareid].close()
 679.             d.addErrback(self._remove_shareholder, shareid, "close")
 680.             dl.append(d)
 681.         return self._gather_responses(dl)
 682. 
 683.     def done(self, res):
 684.         self.log("upload done", level=log.OPERATIONAL)
 685.         self.set_status("Done")
 686.         self.set_encode_and_push_progress(extra=1.0) # done
 687.         now = time.time()
 688.         h_and_c_elapsed = now - self._start_hashing_and_close_timestamp
 689.         self._times["hashes_and_close"] = h_and_c_elapsed
 690.         total_elapsed = now - self._start_total_timestamp
 691.         self._times["total_encode_and_push"] = total_elapsed
 692. 
 693.         # update our sharemap
 694.         self._shares_placed = set(self.landlords.keys())
 695.         return (self.uri_extension_hash, self.required_shares,
 696.                 self.num_shares, self.file_size)
 697. 
 698.     def err(self, f):
 699.         self.log("upload failed", failure=f, level=log.UNUSUAL)
 700.         self.set_status("Failed")
 701.         # we need to abort any remaining shareholders, so they'll delete the
 702.         # partial share, allowing someone else to upload it again.
 703.         self.log("aborting shareholders", level=log.UNUSUAL)
 704.         for shareid in list(self.landlords.keys()):
 705.             self.landlords[shareid].abort()
 706.         if f.check(defer.FirstError):
 707.             return f.value.subFailure
 708.         return f
 709. 
 710.     def get_shares_placed(self):
 711.         # return a set of share numbers that were successfully placed.
 712.         return self._shares_placed
 713. 
 714.     def get_times(self):
 715.         # return a dictionary of encode+push timings
 716.         return self._times
 717. 
 718.     def get_uri_extension_data(self):
 719.         return self.uri_extension_data