2 from zope.interface import Interface
3 from foolscap.api import StringConstraint, ListOf, TupleOf, SetOf, DictOf, \
4 ChoiceOf, IntegerConstraint, Any, RemoteInterface, Referenceable
8 Hash = StringConstraint(maxLength=HASH_SIZE,
9 minLength=HASH_SIZE)# binary format 32-byte SHA256 hash
10 Nodeid = StringConstraint(maxLength=20,
11 minLength=20) # binary format 20-byte SHA1 hash
12 FURL = StringConstraint(1000)
13 StorageIndex = StringConstraint(16)
14 URI = StringConstraint(300) # kind of arbitrary
16 MAX_BUCKETS = 256 # per peer -- zfec offers at most 256 shares per file
18 ShareData = StringConstraint(None)
19 URIExtensionData = StringConstraint(1000)
20 Number = IntegerConstraint(8) # 2**(8*8) == 16EiB ~= 18e18 ~= 18 exabytes
22 ReadSize = int # the 'int' constraint is 2**31 == 2Gib -- large files are processed in not-so-large increments
23 WriteEnablerSecret = Hash # used to protect mutable bucket modifications
24 LeaseRenewSecret = Hash # used to protect bucket lease renewal requests
25 LeaseCancelSecret = Hash # used to protect bucket lease cancellation requests
27 class RIStubClient(RemoteInterface):
28 """Each client publishes a service announcement for a dummy object called
29 the StubClient. This object doesn't actually offer any services, but the
30 announcement helps the Introducer keep track of which clients are
31 subscribed (so the grid admin can keep track of things like the size of
32 the grid and the client versions in use. This is the (empty)
33 RemoteInterface for the StubClient."""
35 class RIBucketWriter(RemoteInterface):
36 """ Objects of this kind live on the server side. """
37 def write(offset=Offset, data=ShareData):
42 If the data that has been written is incomplete or inconsistent then
43 the server will throw the data away, else it will store it for future
49 """Abandon all the data that has been written.
53 class RIBucketReader(RemoteInterface):
54 def read(offset=Offset, length=ReadSize):
57 def advise_corrupt_share(reason=str):
58 """Clients who discover hash failures in shares that they have
59 downloaded from me will use this method to inform me about the
60 failures. I will record their concern so that my operator can
61 manually inspect the shares in question. I return None.
63 This is a wrapper around RIStorageServer.advise_corrupt_share(),
64 which is tied to a specific share, and therefore does not need the
65 extra share-identifying arguments. Please see that method for full
69 TestVector = ListOf(TupleOf(Offset, ReadSize, str, str))
70 # elements are (offset, length, operator, specimen)
71 # operator is one of "lt, le, eq, ne, ge, gt"
72 # nop always passes and is used to fetch data while writing.
73 # you should use length==len(specimen) for everything except nop
74 DataVector = ListOf(TupleOf(Offset, ShareData))
75 # (offset, data). This limits us to 30 writes of 1MiB each per call
76 TestAndWriteVectorsForShares = DictOf(int,
79 ChoiceOf(None, Offset), # new_length
81 ReadVector = ListOf(TupleOf(Offset, ReadSize))
82 ReadData = ListOf(ShareData)
83 # returns data[offset:offset+length] for each element of TestVector
85 class RIStorageServer(RemoteInterface):
86 __remote_name__ = "RIStorageServer.tahoe.allmydata.com"
90 Return a dictionary of version information.
92 return DictOf(str, Any())
94 def allocate_buckets(storage_index=StorageIndex,
95 renew_secret=LeaseRenewSecret,
96 cancel_secret=LeaseCancelSecret,
97 sharenums=SetOf(int, maxLength=MAX_BUCKETS),
98 allocated_size=Offset, canary=Referenceable):
100 @param storage_index: the index of the bucket to be created or
102 @param sharenums: these are the share numbers (probably between 0 and
103 99) that the sender is proposing to store on this
105 @param renew_secret: This is the secret used to protect bucket refresh
106 This secret is generated by the client and
107 stored for later comparison by the server. Each
108 server is given a different secret.
109 @param cancel_secret: Like renew_secret, but protects bucket decref.
110 @param canary: If the canary is lost before close(), the bucket is
112 @return: tuple of (alreadygot, allocated), where alreadygot is what we
113 already have and allocated is what we hereby agree to accept.
114 New leases are added for shares in both lists.
116 return TupleOf(SetOf(int, maxLength=MAX_BUCKETS),
117 DictOf(int, RIBucketWriter, maxKeys=MAX_BUCKETS))
119 def add_lease(storage_index=StorageIndex,
120 renew_secret=LeaseRenewSecret,
121 cancel_secret=LeaseCancelSecret):
123 Add a new lease on the given bucket. If the renew_secret matches an
124 existing lease, that lease will be renewed instead. If there is no
125 bucket for the given storage_index, return silently. (note that in
126 tahoe-1.3.0 and earlier, IndexError was raised if there was no
129 return Any() # returns None now, but future versions might change
131 def renew_lease(storage_index=StorageIndex, renew_secret=LeaseRenewSecret):
133 Renew the lease on a given bucket, resetting the timer to 31 days.
134 Some networks will use this, some will not. If there is no bucket for
135 the given storage_index, IndexError will be raised.
137 For mutable shares, if the given renew_secret does not match an
138 existing lease, IndexError will be raised with a note listing the
139 server-nodeids on the existing leases, so leases on migrated shares
140 can be renewed or cancelled. For immutable shares, IndexError
141 (without the note) will be raised.
145 def cancel_lease(storage_index=StorageIndex,
146 cancel_secret=LeaseCancelSecret):
148 Cancel the lease on a given bucket. If this was the last lease on the
149 bucket, the bucket will be deleted. If there is no bucket for the
150 given storage_index, IndexError will be raised.
152 For mutable shares, if the given cancel_secret does not match an
153 existing lease, IndexError will be raised with a note listing the
154 server-nodeids on the existing leases, so leases on migrated shares
155 can be renewed or cancelled. For immutable shares, IndexError
156 (without the note) will be raised.
160 def get_buckets(storage_index=StorageIndex):
161 return DictOf(int, RIBucketReader, maxKeys=MAX_BUCKETS)
165 def slot_readv(storage_index=StorageIndex,
166 shares=ListOf(int), readv=ReadVector):
167 """Read a vector from the numbered shares associated with the given
168 storage index. An empty shares list means to return data from all
169 known shares. Returns a dictionary with one key per share."""
170 return DictOf(int, ReadData) # shnum -> results
172 def slot_testv_and_readv_and_writev(storage_index=StorageIndex,
173 secrets=TupleOf(WriteEnablerSecret,
176 tw_vectors=TestAndWriteVectorsForShares,
179 """General-purpose test-and-set operation for mutable slots. Perform
180 a bunch of comparisons against the existing shares. If they all pass,
181 then apply a bunch of write vectors to those shares. Then use the
182 read vectors to extract data from all the shares and return the data.
184 This method is, um, large. The goal is to allow clients to update all
185 the shares associated with a mutable file in a single round trip.
187 @param storage_index: the index of the bucket to be created or
189 @param write_enabler: a secret that is stored along with the slot.
190 Writes are accepted from any caller who can
191 present the matching secret. A different secret
192 should be used for each slot*server pair.
193 @param renew_secret: This is the secret used to protect bucket refresh
194 This secret is generated by the client and
195 stored for later comparison by the server. Each
196 server is given a different secret.
197 @param cancel_secret: Like renew_secret, but protects bucket decref.
199 The 'secrets' argument is a tuple of (write_enabler, renew_secret,
200 cancel_secret). The first is required to perform any write. The
201 latter two are used when allocating new shares. To simply acquire a
202 new lease on existing shares, use an empty testv and an empty writev.
204 Each share can have a separate test vector (i.e. a list of
205 comparisons to perform). If all vectors for all shares pass, then all
206 writes for all shares are recorded. Each comparison is a 4-tuple of
207 (offset, length, operator, specimen), which effectively does a bool(
208 (read(offset, length)) OPERATOR specimen ) and only performs the
209 write if all these evaluate to True. Basic test-and-set uses 'eq'.
210 Write-if-newer uses a seqnum and (offset, length, 'lt', specimen).
211 Write-if-same-or-newer uses 'le'.
213 Reads from the end of the container are truncated, and missing shares
214 behave like empty ones, so to assert that a share doesn't exist (for
215 use when creating a new share), use (0, 1, 'eq', '').
217 The write vector will be applied to the given share, expanding it if
218 necessary. A write vector applied to a share number that did not
219 exist previously will cause that share to be created.
221 Each write vector is accompanied by a 'new_length' argument. If
222 new_length is not None, use it to set the size of the container. This
223 can be used to pre-allocate space for a series of upcoming writes, or
224 truncate existing data. If the container is growing, new_length will
225 be applied before datav. If the container is shrinking, it will be
226 applied afterwards. If new_length==0, the share will be deleted.
228 The read vector is used to extract data from all known shares,
229 *before* any writes have been applied. The same vector is used for
230 all shares. This captures the state that was tested by the test
233 This method returns two values: a boolean and a dict. The boolean is
234 True if the write vectors were applied, False if not. The dict is
235 keyed by share number, and each value contains a list of strings, one
236 for each element of the read vector.
238 If the write_enabler is wrong, this will raise BadWriteEnablerError.
239 To enable share migration (using update_write_enabler), the exception
240 will have the nodeid used for the old write enabler embedded in it,
241 in the following string::
243 The write enabler was recorded by nodeid '%s'.
245 Note that the nodeid here is encoded using the same base32 encoding
246 used by Foolscap and allmydata.util.idlib.nodeid_b2a().
249 return TupleOf(bool, DictOf(int, ReadData))
251 def advise_corrupt_share(share_type=str, storage_index=StorageIndex,
252 shnum=int, reason=str):
253 """Clients who discover hash failures in shares that they have
254 downloaded from me will use this method to inform me about the
255 failures. I will record their concern so that my operator can
256 manually inspect the shares in question. I return None.
258 'share_type' is either 'mutable' or 'immutable'. 'storage_index' is a
259 (binary) storage index string, and 'shnum' is the integer share
260 number. 'reason' is a human-readable explanation of the problem,
261 probably including some expected hash values and the computed ones
262 which did not match. Corruption advisories for mutable shares should
263 include a hash of the public key (the same value that appears in the
264 mutable-file verify-cap), since the current share format does not
268 class IStorageBucketWriter(Interface):
270 Objects of this kind live on the client side.
272 def put_block(segmentnum=int, data=ShareData):
273 """@param data: For most segments, this data will be 'blocksize'
274 bytes in length. The last segment might be shorter.
275 @return: a Deferred that fires (with None) when the operation completes
278 def put_plaintext_hashes(hashes=ListOf(Hash)):
280 @return: a Deferred that fires (with None) when the operation completes
283 def put_crypttext_hashes(hashes=ListOf(Hash)):
285 @return: a Deferred that fires (with None) when the operation completes
288 def put_block_hashes(blockhashes=ListOf(Hash)):
290 @return: a Deferred that fires (with None) when the operation completes
293 def put_share_hashes(sharehashes=ListOf(TupleOf(int, Hash))):
295 @return: a Deferred that fires (with None) when the operation completes
298 def put_uri_extension(data=URIExtensionData):
299 """This block of data contains integrity-checking information (hashes
300 of plaintext, crypttext, and shares), as well as encoding parameters
301 that are necessary to recover the data. This is a serialized dict
302 mapping strings to other strings. The hash of this data is kept in
303 the URI and verified before any of the data is used. All buckets for
304 a given file contain identical copies of this data.
306 The serialization format is specified with the following pseudocode:
307 for k in sorted(dict.keys()):
308 assert re.match(r'^[a-zA-Z_\-]+$', k)
309 write(k + ':' + netstring(dict[k]))
311 @return: a Deferred that fires (with None) when the operation completes
315 """Finish writing and close the bucket. The share is not finalized
316 until this method is called: if the uploading client disconnects
317 before calling close(), the partially-written share will be
320 @return: a Deferred that fires (with None) when the operation completes
323 class IStorageBucketReader(Interface):
325 def get_block_data(blocknum=int, blocksize=int, size=int):
326 """Most blocks will be the same size. The last block might be shorter
332 def get_crypttext_hashes():
334 @return: ListOf(Hash)
337 def get_block_hashes(at_least_these=SetOf(int)):
339 @return: ListOf(Hash)
342 def get_share_hashes(at_least_these=SetOf(int)):
344 @return: ListOf(TupleOf(int, Hash))
347 def get_uri_extension():
349 @return: URIExtensionData
352 class IStorageBroker(Interface):
353 def get_servers_for_index(peer_selection_index):
355 @return: list of (peerid, versioned-rref) tuples
357 def get_all_servers():
359 @return: frozenset of (peerid, versioned-rref) tuples
361 def get_all_serverids():
363 @return: frozenset of serverid strings
365 def get_nickname_for_serverid(serverid):
367 @return: unicode nickname, or None
370 # methods moved from IntroducerClient, need review
371 def get_all_connections():
372 """Return a frozenset of (nodeid, service_name, rref) tuples, one for
373 each active connection we've established to a remote service. This is
374 mostly useful for unit tests that need to wait until a certain number
375 of connections have been made."""
377 def get_all_connectors():
378 """Return a dict that maps from (nodeid, service_name) to a
379 RemoteServiceConnector instance for all services that we are actively
380 trying to connect to. Each RemoteServiceConnector has the following
383 service_name: the type of service provided, like 'storage'
384 announcement_time: when we first heard about this service
385 last_connect_time: when we last established a connection
386 last_loss_time: when we last lost a connection
388 version: the peer's version, from the most recent connection
389 oldest_supported: the peer's oldest supported version, same
391 rref: the RemoteReference, if connected, otherwise None
392 remote_host: the IAddress, if connected, otherwise None
394 This method is intended for monitoring interfaces, such as a web page
395 which describes connecting and connected peers.
398 def get_all_peerids():
399 """Return a frozenset of all peerids to whom we have a connection (to
400 one or more services) established. Mostly useful for unit tests."""
402 def get_all_connections_for(service_name):
403 """Return a frozenset of (nodeid, service_name, rref) tuples, one
404 for each active connection that provides the given SERVICE_NAME."""
406 def get_permuted_peers(service_name, key):
407 """Returns an ordered list of (peerid, rref) tuples, selecting from
408 the connections that provide SERVICE_NAME, using a hash-based
409 permutation keyed by KEY. This randomizes the service list in a
410 repeatable way, to distribute load over many peers.
414 # hm, we need a solution for forward references in schemas
415 FileNode_ = Any() # TODO: foolscap needs constraints on copyables
416 DirectoryNode_ = Any() # TODO: same
417 AnyNode_ = ChoiceOf(FileNode_, DirectoryNode_)
420 class IURI(Interface):
421 def init_from_string(uri):
422 """Accept a string (as created by my to_string() method) and populate
423 this instance with its data. I am not normally called directly,
424 please use the module-level uri.from_string() function to convert
425 arbitrary URI strings into IURI-providing instances."""
428 """Return False if this URI be used to modify the data. Return True
429 if this URI cannot be used to modify the data."""
432 """Return True if the data can be modified by *somebody* (perhaps
433 someone who has a more powerful URI than this one)."""
436 """Return another IURI instance, which represents a read-only form of
437 this one. If is_readonly() is True, this returns self."""
439 def get_verify_cap():
440 """Return an instance that provides IVerifierURI, which can be used
441 to check on the availability of the file or directory, without
442 providing enough capabilities to actually read or modify the
443 contents. This may return None if the file does not need checking or
444 verification (e.g. LIT URIs).
448 """Return a string of printable ASCII characters, suitable for
449 passing into init_from_string."""
451 class IVerifierURI(Interface, IURI):
452 def init_from_string(uri):
453 """Accept a string (as created by my to_string() method) and populate
454 this instance with its data. I am not normally called directly,
455 please use the module-level uri.from_string() function to convert
456 arbitrary URI strings into IURI-providing instances."""
459 """Return a string of printable ASCII characters, suitable for
460 passing into init_from_string."""
462 class IDirnodeURI(Interface):
463 """I am a URI which represents a dirnode."""
466 class IFileURI(Interface):
467 """I am a URI which represents a filenode."""
469 """Return the length (in bytes) of the file that I represent."""
471 class IImmutableFileURI(IFileURI):
474 class IMutableFileURI(Interface):
475 """I am a URI which represents a mutable filenode."""
476 class INewDirectoryURI(Interface):
478 class IReadonlyNewDirectoryURI(Interface):
482 class IFilesystemNode(Interface):
485 Return the URI that can be used by others to get access to this
486 node. If this node is read-only, the URI will only offer read-only
487 access. If this node is read-write, the URI will offer read-write
490 If you have read-write access to a node and wish to share merely
491 read-only access with others, use get_readonly_uri().
494 def get_readonly_uri():
495 """Return the directory URI that can be used by others to get
496 read-only access to this directory node. The result is a read-only
497 URI, regardless of whether this dirnode is read-only or read-write.
499 If you have merely read-only access to this dirnode,
500 get_readonly_uri() will return the same thing as get_uri().
503 def get_repair_cap():
504 """Return an IURI instance that can be used to repair the file, or
505 None if this node cannot be repaired (either because it is not
506 distributed, like a LIT file, or because the node does not represent
507 sufficient authority to create a repair-cap, like a read-only RSA
508 mutable file node [which cannot create the correct write-enablers]).
511 def get_verify_cap():
512 """Return an IVerifierURI instance that represents the
513 'verifiy/refresh capability' for this node. The holder of this
514 capability will be able to renew the lease for this node, protecting
515 it from garbage-collection. They will also be able to ask a server if
516 it holds a share for the file or directory.
519 def get_storage_index():
520 """Return a string with the (binary) storage index in use on this
521 download. This may be None if there is no storage index (i.e. LIT
525 """Return True if this reference provides mutable access to the given
526 file or directory (i.e. if you can modify it), or False if not. Note
527 that even if this reference is read-only, someone else may hold a
528 read-write reference to it."""
531 """Return True if this file or directory is mutable (by *somebody*,
532 not necessarily you), False if it is is immutable. Note that a file
533 might be mutable overall, but your reference to it might be
534 read-only. On the other hand, all references to an immutable file
535 will be read-only; there are no read-write references to an immutable
539 class IMutableFilesystemNode(IFilesystemNode):
542 class IFileNode(IFilesystemNode):
543 def download(target):
544 """Download the file's contents to a given IDownloadTarget"""
546 def download_to_data():
547 """Download the file's contents. Return a Deferred that fires
548 with those contents."""
551 """Return the length (in bytes) of the data this node represents."""
553 def read(consumer, offset=0, size=None):
554 """Download a portion (possibly all) of the file's contents, making
555 them available to the given IConsumer. Return a Deferred that fires
556 (with the consumer) when the consumer is unregistered (either because
557 the last byte has been given to it, or because the consumer threw an
558 exception during write(), possibly because it no longer wants to
559 receive data). The portion downloaded will start at 'offset' and
560 contain 'size' bytes (or the remainder of the file if size==None).
562 The consumer will be used in non-streaming mode: an IPullProducer
563 will be attached to it.
565 The consumer will not receive data right away: several network trips
566 must occur first. The order of events will be::
568 consumer.registerProducer(p, streaming)
569 (if streaming == False)::
570 consumer does p.resumeProducing()
572 consumer does p.resumeProducing()
573 consumer.write(data).. (repeat until all data is written)
574 consumer.unregisterProducer()
575 deferred.callback(consumer)
577 If a download error occurs, or an exception is raised by
578 consumer.registerProducer() or consumer.write(), I will call
579 consumer.unregisterProducer() and then deliver the exception via
580 deferred.errback(). To cancel the download, the consumer should call
581 p.stopProducing(), which will result in an exception being delivered
582 via deferred.errback().
584 A simple download-to-memory consumer example would look like this::
586 class MemoryConsumer:
587 implements(IConsumer)
591 def registerProducer(self, p, streaming):
592 assert streaming == False
595 def write(self, data):
596 self.chunks.append(data)
597 def unregisterProducer(self):
599 d = filenode.read(MemoryConsumer())
600 d.addCallback(lambda mc: "".join(mc.chunks))
605 class IMutableFileNode(IFileNode, IMutableFilesystemNode):
606 """I provide access to a 'mutable file', which retains its identity
607 regardless of what contents are put in it.
609 The consistency-vs-availability problem means that there might be
610 multiple versions of a file present in the grid, some of which might be
611 unrecoverable (i.e. have fewer than 'k' shares). These versions are
612 loosely ordered: each has a sequence number and a hash, and any version
613 with seqnum=N was uploaded by a node which has seen at least one version
616 The 'servermap' (an instance of IMutableFileServerMap) is used to
617 describe the versions that are known to be present in the grid, and which
618 servers are hosting their shares. It is used to represent the 'state of
619 the world', and is used for this purpose by my test-and-set operations.
620 Downloading the contents of the mutable file will also return a
621 servermap. Uploading a new version into the mutable file requires a
622 servermap as input, and the semantics of the replace operation is
623 'replace the file with my new version if it looks like nobody else has
624 changed the file since my previous download'. Because the file is
625 distributed, this is not a perfect test-and-set operation, but it will do
626 its best. If the replace process sees evidence of a simultaneous write,
627 it will signal an UncoordinatedWriteError, so that the caller can take
631 Most readers will want to use the 'best' current version of the file, and
632 should use my 'download_best_version()' method.
634 To unconditionally replace the file, callers should use overwrite(). This
635 is the mode that user-visible mutable files will probably use.
637 To apply some delta to the file, call modify() with a callable modifier
638 function that can apply the modification that you want to make. This is
639 the mode that dirnodes will use, since most directory modification
640 operations can be expressed in terms of deltas to the directory state.
643 Three methods are available for users who need to perform more complex
644 operations. The first is get_servermap(), which returns an up-to-date
645 servermap using a specified mode. The second is download_version(), which
646 downloads a specific version (not necessarily the 'best' one). The third
647 is 'upload', which accepts new contents and a servermap (which must have
648 been updated with MODE_WRITE). The upload method will attempt to apply
649 the new contents as long as no other node has modified the file since the
650 servermap was updated. This might be useful to a caller who wants to
651 merge multiple versions into a single new one.
653 Note that each time the servermap is updated, a specific 'mode' is used,
654 which determines how many peers are queried. To use a servermap for my
655 replace() method, that servermap must have been updated in MODE_WRITE.
656 These modes are defined in allmydata.mutable.common, and consist of
657 MODE_READ, MODE_WRITE, MODE_ANYTHING, and MODE_CHECK. Please look in
658 allmydata/mutable/servermap.py for details about the differences.
660 Mutable files are currently limited in size (about 3.5MB max) and can
661 only be retrieved and updated all-at-once, as a single big string. Future
662 versions of our mutable files will remove this restriction.
665 def download_best_version():
666 """Download the 'best' available version of the file, meaning one of
667 the recoverable versions with the highest sequence number. If no
668 uncoordinated writes have occurred, and if enough shares are
669 available, then this will be the most recent version that has been
672 I update an internal servermap with MODE_READ, determine which
673 version of the file is indicated by
674 servermap.best_recoverable_version(), and return a Deferred that
675 fires with its contents. If no version is recoverable, the Deferred
676 will errback with UnrecoverableFileError.
679 def get_size_of_best_version():
680 """Find the size of the version that would be downloaded with
681 download_best_version(), without actually downloading the whole file.
683 I return a Deferred that fires with an integer.
686 def overwrite(new_contents):
687 """Unconditionally replace the contents of the mutable file with new
688 ones. This simply chains get_servermap(MODE_WRITE) and upload(). This
689 is only appropriate to use when the new contents of the file are
690 completely unrelated to the old ones, and you do not care about other
693 I return a Deferred that fires (with a PublishStatus object) when the
694 update has completed.
697 def modify(modifier_cb):
698 """Modify the contents of the file, by downloading the current
699 version, applying the modifier function (or bound method), then
700 uploading the new version. I return a Deferred that fires (with a
701 PublishStatus object) when the update is complete.
703 The modifier callable will be given three arguments: a string (with
704 the old contents), a 'first_time' boolean, and a servermap. As with
705 download_best_version(), the old contents will be from the best
706 recoverable version, but the modifier can use the servermap to make
707 other decisions (such as refusing to apply the delta if there are
708 multiple parallel versions, or if there is evidence of a newer
709 unrecoverable version). 'first_time' will be True the first time the
710 modifier is called, and False on any subsequent calls.
712 The callable should return a string with the new contents. The
713 callable must be prepared to be called multiple times, and must
714 examine the input string to see if the change that it wants to make
715 is already present in the old version. If it does not need to make
716 any changes, it can either return None, or return its input string.
718 If the modifier raises an exception, it will be returned in the
723 def get_servermap(mode):
724 """Return a Deferred that fires with an IMutableFileServerMap
725 instance, updated using the given mode.
728 def download_version(servermap, version):
729 """Download a specific version of the file, using the servermap
730 as a guide to where the shares are located.
732 I return a Deferred that fires with the requested contents, or
733 errbacks with UnrecoverableFileError. Note that a servermap which was
734 updated with MODE_ANYTHING or MODE_READ may not know about shares for
735 all versions (those modes stop querying servers as soon as they can
736 fulfil their goals), so you may want to use MODE_CHECK (which checks
737 everything) to get increased visibility.
740 def upload(new_contents, servermap):
741 """Replace the contents of the file with new ones. This requires a
742 servermap that was previously updated with MODE_WRITE.
744 I attempt to provide test-and-set semantics, in that I will avoid
745 modifying any share that is different than the version I saw in the
746 servermap. However, if another node is writing to the file at the
747 same time as me, I may manage to update some shares while they update
748 others. If I see any evidence of this, I will signal
749 UncoordinatedWriteError, and the file will be left in an inconsistent
750 state (possibly the version you provided, possibly the old version,
751 possibly somebody else's version, and possibly a mix of shares from
754 The recommended response to UncoordinatedWriteError is to either
755 return it to the caller (since they failed to coordinate their
756 writes), or to attempt some sort of recovery. It may be sufficient to
757 wait a random interval (with exponential backoff) and repeat your
758 operation. If I do not signal UncoordinatedWriteError, then I was
759 able to write the new version without incident.
761 I return a Deferred that fires (with a PublishStatus object) when the
762 publish has completed. I will update the servermap in-place with the
763 location of all new shares.
767 """Return this filenode's writekey, or None if the node does not have
768 write-capability. This may be used to assist with data structures
769 that need to make certain data available only to writers, such as the
770 read-write child caps in dirnodes. The recommended process is to have
771 reader-visible data be submitted to the filenode in the clear (where
772 it will be encrypted by the filenode using the readkey), but encrypt
773 writer-visible data using this writekey.
776 class NotEnoughSharesError(Exception):
777 """Download was unable to get enough shares, or upload was unable to
778 place 'shares_of_happiness' shares."""
780 class NoSharesError(Exception):
781 """Upload or Download was unable to get any shares at all."""
783 class UnableToFetchCriticalDownloadDataError(Exception):
784 """I was unable to fetch some piece of critical data which is supposed to
785 be identically present in all shares."""
787 class NoServersError(Exception):
788 """Upload wasn't given any servers to work with, usually indicating a
789 network or Introducer problem."""
791 class ExistingChildError(Exception):
792 """A directory node was asked to add or replace a child that already
793 exists, and overwrite= was set to False."""
795 class NoSuchChildError(Exception):
796 """A directory node was asked to fetch a child which does not exist."""
798 class IDirectoryNode(IMutableFilesystemNode):
799 """I represent a name-to-child mapping, holding the tahoe equivalent of a
800 directory. All child names are unicode strings, and all children are some
801 sort of IFilesystemNode (either files or subdirectories).
806 The dirnode ('1') URI returned by this method can be used in
807 set_uri() on a different directory ('2') to 'mount' a reference to
808 this directory ('1') under the other ('2'). This URI is just a
809 string, so it can be passed around through email or other out-of-band
813 def get_readonly_uri():
815 The dirnode ('1') URI returned by this method can be used in
816 set_uri() on a different directory ('2') to 'mount' a reference to
817 this directory ('1') under the other ('2'). This URI is just a
818 string, so it can be passed around through email or other out-of-band
823 """I return a Deferred that fires with a dictionary mapping child
824 name (a unicode string) to (node, metadata_dict) tuples, in which
825 'node' is either an IFileNode or IDirectoryNode, and 'metadata_dict'
826 is a dictionary of metadata."""
829 """I return a Deferred that fires with a boolean, True if there
830 exists a child of the given name, False if not. The child name must
831 be a unicode string."""
834 """I return a Deferred that fires with a specific named child node,
835 either an IFileNode or an IDirectoryNode. The child name must be a
836 unicode string. I raise NoSuchChildError if I do not have a child by
839 def get_metadata_for(name):
840 """I return a Deferred that fires with the metadata dictionary for a
841 specific named child node. This metadata is stored in the *edge*, not
842 in the child, so it is attached to the parent dirnode rather than the
843 child dir-or-file-node. The child name must be a unicode string. I
844 raise NoSuchChildError if I do not have a child by that name."""
846 def set_metadata_for(name, metadata):
847 """I replace any existing metadata for the named child with the new
848 metadata. The child name must be a unicode string. This metadata is
849 stored in the *edge*, not in the child, so it is attached to the
850 parent dirnode rather than the child dir-or-file-node. I return a
851 Deferred (that fires with this dirnode) when the operation is
852 complete. I raise NoSuchChildError if I do not have a child by that
855 def get_child_at_path(path):
856 """Transform a child path into an IDirectoryNode or IFileNode.
858 I perform a recursive series of 'get' operations to find the named
859 descendant node. I return a Deferred that fires with the node, or
860 errbacks with NoSuchChildError if the node could not be found.
862 The path can be either a single string (slash-separated) or a list of
863 path-name elements. All elements must be unicode strings.
866 def get_child_and_metadata_at_path(path):
867 """Transform a child path into an IDirectoryNode/IFileNode and
870 I am like get_child_at_path(), but my Deferred fires with a tuple of
871 (node, metadata). The metadata comes from the last edge. If the path
872 is empty, the metadata will be an empty dictionary.
875 def set_uri(name, child_uri, metadata=None, overwrite=True):
876 """I add a child (by URI) at the specific name. I return a Deferred
877 that fires when the operation finishes. If overwrite= is True, I will
878 replace any existing child of the same name, otherwise an existing
879 child will cause me to return ExistingChildError. The child name must
882 The child_uri could be for a file, or for a directory (either
883 read-write or read-only, using a URI that came from get_uri() ).
885 If metadata= is provided, I will use it as the metadata for the named
886 edge. This will replace any existing metadata. If metadata= is left
887 as the default value of None, I will set ['mtime'] to the current
888 time, and I will set ['ctime'] to the current time if there was not
889 already a child by this name present. This roughly matches the
890 ctime/mtime semantics of traditional filesystems.
892 If this directory node is read-only, the Deferred will errback with a
895 def set_children(entries, overwrite=True):
896 """Add multiple (name, child_uri) pairs (or (name, child_uri,
897 metadata) triples) to a directory node. Returns a Deferred that fires
898 (with None) when the operation finishes. This is equivalent to
899 calling set_uri() multiple times, but is much more efficient. All
900 child names must be unicode strings.
903 def set_node(name, child, metadata=None, overwrite=True):
904 """I add a child at the specific name. I return a Deferred that fires
905 when the operation finishes. This Deferred will fire with the child
906 node that was just added. I will replace any existing child of the
907 same name. The child name must be a unicode string. The 'child'
908 instance must be an instance providing IDirectoryNode or IFileNode.
910 If metadata= is provided, I will use it as the metadata for the named
911 edge. This will replace any existing metadata. If metadata= is left
912 as the default value of None, I will set ['mtime'] to the current
913 time, and I will set ['ctime'] to the current time if there was not
914 already a child by this name present. This roughly matches the
915 ctime/mtime semantics of traditional filesystems.
917 If this directory node is read-only, the Deferred will errback with a
920 def set_nodes(entries, overwrite=True):
921 """Add multiple (name, child_node) pairs (or (name, child_node,
922 metadata) triples) to a directory node. Returns a Deferred that fires
923 (with None) when the operation finishes. This is equivalent to
924 calling set_node() multiple times, but is much more efficient. All
925 child names must be unicode strings."""
928 def add_file(name, uploadable, metadata=None, overwrite=True):
929 """I upload a file (using the given IUploadable), then attach the
930 resulting FileNode to the directory at the given name. I set metadata
931 the same way as set_uri and set_node. The child name must be a
934 I return a Deferred that fires (with the IFileNode of the uploaded
935 file) when the operation completes."""
938 """I remove the child at the specific name. I return a Deferred that
939 fires when the operation finishes. The child name must be a unicode
940 string. I raise NoSuchChildError if I do not have a child by that
943 def create_empty_directory(name, overwrite=True):
944 """I create and attach an empty directory at the given name. The
945 child name must be a unicode string. I return a Deferred that fires
946 when the operation finishes."""
948 def move_child_to(current_child_name, new_parent, new_child_name=None,
950 """I take one of my children and move them to a new parent. The child
951 is referenced by name. On the new parent, the child will live under
952 'new_child_name', which defaults to 'current_child_name'. TODO: what
953 should we do about metadata? I return a Deferred that fires when the
954 operation finishes. The child name must be a unicode string. I raise
955 NoSuchChildError if I do not have a child by that name."""
957 def build_manifest():
958 """I generate a table of everything reachable from this directory.
959 I also compute deep-stats as described below.
961 I return a Monitor. The Monitor's results will be a dictionary with
964 res['manifest']: a list of (path, cap) tuples for all nodes
965 (directories and files) reachable from this one.
966 'path' will be a tuple of unicode strings. The
967 origin dirnode will be represented by an empty path
969 res['verifycaps']: a list of (printable) verifycap strings, one for
970 each reachable non-LIT node. This is a set:
971 it will contain no duplicates.
972 res['storage-index']: a list of (base32) storage index strings,
973 one for each reachable non-LIT node. This is
974 a set: it will contain no duplicates.
975 res['stats']: a dictionary, the same that is generated by
976 start_deep_stats() below.
978 The Monitor will also have an .origin_si attribute with the (binary)
979 storage index of the starting point.
982 def start_deep_stats():
983 """Return a Monitor, examining all nodes (directories and files)
984 reachable from this one. The Monitor's results will be a dictionary
985 with the following keys::
987 count-immutable-files: count of how many CHK files are in the set
988 count-mutable-files: same, for mutable files (does not include
990 count-literal-files: same, for LIT files
991 count-files: sum of the above three
993 count-directories: count of directories
995 size-immutable-files: total bytes for all CHK files in the set
996 size-mutable-files (TODO): same, for current version of all mutable
997 files, does not include directories
998 size-literal-files: same, for LIT files
999 size-directories: size of mutable files used by directories
1001 largest-directory: number of bytes in the largest directory
1002 largest-directory-children: number of children in the largest
1004 largest-immutable-file: number of bytes in the largest CHK file
1006 size-mutable-files is not yet implemented, because it would involve
1007 even more queries than deep_stats does.
1009 The Monitor will also have an .origin_si attribute with the (binary)
1010 storage index of the starting point.
1012 This operation will visit every directory node underneath this one,
1013 and can take a long time to run. On a typical workstation with good
1014 bandwidth, this can examine roughly 15 directories per second (and
1015 takes several minutes of 100% CPU for ~1700 directories).
1018 class ICodecEncoder(Interface):
1019 def set_params(data_size, required_shares, max_shares):
1020 """Set up the parameters of this encoder.
1022 This prepares the encoder to perform an operation that converts a
1023 single block of data into a number of shares, such that a future
1024 ICodecDecoder can use a subset of these shares to recover the
1025 original data. This operation is invoked by calling encode(). Once
1026 the encoding parameters are set up, the encode operation can be
1027 invoked multiple times.
1029 set_params() prepares the encoder to accept blocks of input data that
1030 are exactly 'data_size' bytes in length. The encoder will be prepared
1031 to produce 'max_shares' shares for each encode() operation (although
1032 see the 'desired_share_ids' to use less CPU). The encoding math will
1033 be chosen such that the decoder can get by with as few as
1034 'required_shares' of these shares and still reproduce the original
1035 data. For example, set_params(1000, 5, 5) offers no redundancy at
1036 all, whereas set_params(1000, 1, 10) provides 10x redundancy.
1038 Numerical Restrictions: 'data_size' is required to be an integral
1039 multiple of 'required_shares'. In general, the caller should choose
1040 required_shares and max_shares based upon their reliability
1041 requirements and the number of peers available (the total storage
1042 space used is roughly equal to max_shares*data_size/required_shares),
1043 then choose data_size to achieve the memory footprint desired (larger
1044 data_size means more efficient operation, smaller data_size means
1045 smaller memory footprint).
1047 In addition, 'max_shares' must be equal to or greater than
1048 'required_shares'. Of course, setting them to be equal causes
1049 encode() to degenerate into a particularly slow form of the 'split'
1052 See encode() for more details about how these parameters are used.
1054 set_params() must be called before any other ICodecEncoder methods
1059 """Return the 3-tuple of data_size, required_shares, max_shares"""
1061 def get_encoder_type():
1062 """Return a short string that describes the type of this encoder.
1064 There is required to be a global table of encoder classes. This method
1065 returns an index into this table; the value at this index is an
1066 encoder class, and this encoder is an instance of that class.
1069 def get_block_size():
1070 """Return the length of the shares that encode() will produce.
1073 def encode_proposal(data, desired_share_ids=None):
1074 """Encode some data.
1076 'data' must be a string (or other buffer object), and len(data) must
1077 be equal to the 'data_size' value passed earlier to set_params().
1079 This will return a Deferred that will fire with two lists. The first
1080 is a list of shares, each of which is a string (or other buffer
1081 object) such that len(share) is the same as what get_share_size()
1082 returned earlier. The second is a list of shareids, in which each is
1083 an integer. The lengths of the two lists will always be equal to each
1084 other. The user should take care to keep each share closely
1085 associated with its shareid, as one is useless without the other.
1087 The length of this output list will normally be the same as the value
1088 provided to the 'max_shares' parameter of set_params(). This may be
1089 different if 'desired_share_ids' is provided.
1091 'desired_share_ids', if provided, is required to be a sequence of
1092 ints, each of which is required to be >= 0 and < max_shares. If not
1093 provided, encode() will produce 'max_shares' shares, as if
1094 'desired_share_ids' were set to range(max_shares). You might use this
1095 if you initially thought you were going to use 10 peers, started
1096 encoding, and then two of the peers dropped out: you could use
1097 desired_share_ids= to skip the work (both memory and CPU) of
1098 producing shares for the peers which are no longer available.
1102 def encode(inshares, desired_share_ids=None):
1103 """Encode some data. This may be called multiple times. Each call is
1106 inshares is a sequence of length required_shares, containing buffers
1107 (i.e. strings), where each buffer contains the next contiguous
1108 non-overlapping segment of the input data. Each buffer is required to
1109 be the same length, and the sum of the lengths of the buffers is
1110 required to be exactly the data_size promised by set_params(). (This
1111 implies that the data has to be padded before being passed to
1112 encode(), unless of course it already happens to be an even multiple
1113 of required_shares in length.)
1115 ALSO: the requirement to break up your data into 'required_shares'
1116 chunks before calling encode() feels a bit surprising, at least from
1117 the point of view of a user who doesn't know how FEC works. It feels
1118 like an implementation detail that has leaked outside the
1119 abstraction barrier. Can you imagine a use case in which the data to
1120 be encoded might already be available in pre-segmented chunks, such
1121 that it is faster or less work to make encode() take a list rather
1122 than splitting a single string?
1124 ALSO ALSO: I think 'inshares' is a misleading term, since encode()
1125 is supposed to *produce* shares, so what it *accepts* should be
1126 something other than shares. Other places in this interface use the
1127 word 'data' for that-which-is-not-shares.. maybe we should use that
1130 'desired_share_ids', if provided, is required to be a sequence of
1131 ints, each of which is required to be >= 0 and < max_shares. If not
1132 provided, encode() will produce 'max_shares' shares, as if
1133 'desired_share_ids' were set to range(max_shares). You might use this
1134 if you initially thought you were going to use 10 peers, started
1135 encoding, and then two of the peers dropped out: you could use
1136 desired_share_ids= to skip the work (both memory and CPU) of
1137 producing shares for the peers which are no longer available.
1139 For each call, encode() will return a Deferred that fires with two
1140 lists, one containing shares and the other containing the shareids.
1141 The get_share_size() method can be used to determine the length of
1142 the share strings returned by encode(). Each shareid is a small
1143 integer, exactly as passed into 'desired_share_ids' (or
1144 range(max_shares), if desired_share_ids was not provided).
1146 The shares and their corresponding shareids are required to be kept
1147 together during storage and retrieval. Specifically, the share data is
1148 useless by itself: the decoder needs to be told which share is which
1149 by providing it with both the shareid and the actual share data.
1151 This function will allocate an amount of memory roughly equal to::
1153 (max_shares - required_shares) * get_share_size()
1155 When combined with the memory that the caller must allocate to
1156 provide the input data, this leads to a memory footprint roughly
1157 equal to the size of the resulting encoded shares (i.e. the expansion
1158 factor times the size of the input segment).
1163 # returning a list of (shareidN,shareN) tuples instead of a pair of
1164 # lists (shareids..,shares..). Brian thought the tuples would
1165 # encourage users to keep the share and shareid together throughout
1166 # later processing, Zooko pointed out that the code to iterate
1167 # through two lists is not really more complicated than using a list
1168 # of tuples and there's also a performance improvement
1170 # having 'data_size' not required to be an integral multiple of
1171 # 'required_shares'. Doing this would require encode() to perform
1172 # padding internally, and we'd prefer to have any padding be done
1173 # explicitly by the caller. Yes, it is an abstraction leak, but
1174 # hopefully not an onerous one.
1177 class ICodecDecoder(Interface):
1178 def set_params(data_size, required_shares, max_shares):
1179 """Set the params. They have to be exactly the same ones that were used for encoding. """
1181 def get_needed_shares():
1182 """Return the number of shares needed to reconstruct the data.
1183 set_params() is required to be called before this."""
1185 def decode(some_shares, their_shareids):
1186 """Decode a partial list of shares into data.
1188 'some_shares' is required to be a sequence of buffers of sharedata, a
1189 subset of the shares returned by ICodecEncode.encode(). Each share is
1190 required to be of the same length. The i'th element of their_shareids
1191 is required to be the shareid of the i'th buffer in some_shares.
1193 This returns a Deferred which fires with a sequence of buffers. This
1194 sequence will contain all of the segments of the original data, in
1195 order. The sum of the lengths of all of the buffers will be the
1196 'data_size' value passed into the original ICodecEncode.set_params()
1197 call. To get back the single original input block of data, use
1198 ''.join(output_buffers), or you may wish to simply write them in
1199 order to an output file.
1201 Note that some of the elements in the result sequence may be
1202 references to the elements of the some_shares input sequence. In
1203 particular, this means that if those share objects are mutable (e.g.
1204 arrays) and if they are changed, then both the input (the
1205 'some_shares' parameter) and the output (the value given when the
1206 deferred is triggered) will change.
1208 The length of 'some_shares' is required to be exactly the value of
1209 'required_shares' passed into the original ICodecEncode.set_params()
1213 class IEncoder(Interface):
1214 """I take an object that provides IEncryptedUploadable, which provides
1215 encrypted data, and a list of shareholders. I then encode, hash, and
1216 deliver shares to those shareholders. I will compute all the necessary
1217 Merkle hash trees that are necessary to validate the crypttext that
1218 eventually comes back from the shareholders. I provide the URI Extension
1219 Block Hash, and the encoding parameters, both of which must be included
1222 I do not choose shareholders, that is left to the IUploader. I must be
1223 given a dict of RemoteReferences to storage buckets that are ready and
1224 willing to receive data.
1228 """Specify the number of bytes that will be encoded. This must be
1229 peformed before get_serialized_params() can be called.
1231 def set_params(params):
1232 """Override the default encoding parameters. 'params' is a tuple of
1233 (k,d,n), where 'k' is the number of required shares, 'd' is the
1234 shares_of_happiness, and 'n' is the total number of shares that will
1237 Encoding parameters can be set in three ways. 1: The Encoder class
1238 provides defaults (3/7/10). 2: the Encoder can be constructed with
1239 an 'options' dictionary, in which the
1240 needed_and_happy_and_total_shares' key can be a (k,d,n) tuple. 3:
1241 set_params((k,d,n)) can be called.
1243 If you intend to use set_params(), you must call it before
1244 get_share_size or get_param are called.
1247 def set_encrypted_uploadable(u):
1248 """Provide a source of encrypted upload data. 'u' must implement
1249 IEncryptedUploadable.
1251 When this is called, the IEncryptedUploadable will be queried for its
1252 length and the storage_index that should be used.
1254 This returns a Deferred that fires with this Encoder instance.
1256 This must be performed before start() can be called.
1259 def get_param(name):
1260 """Return an encoding parameter, by name.
1262 'storage_index': return a string with the (16-byte truncated SHA-256
1263 hash) storage index to which these shares should be
1266 'share_counts': return a tuple describing how many shares are used:
1267 (needed_shares, shares_of_happiness, total_shares)
1269 'num_segments': return an int with the number of segments that
1272 'segment_size': return an int with the size of each segment.
1274 'block_size': return the size of the individual blocks that will
1275 be delivered to a shareholder's put_block() method. By
1276 knowing this, the shareholder will be able to keep all
1277 blocks in a single file and still provide random access
1278 when reading them. # TODO: can we avoid exposing this?
1280 'share_size': an int with the size of the data that will be stored
1281 on each shareholder. This is aggregate amount of data
1282 that will be sent to the shareholder, summed over all
1283 the put_block() calls I will ever make. It is useful to
1284 determine this size before asking potential
1285 shareholders whether they will grant a lease or not,
1286 since their answers will depend upon how much space we
1287 need. TODO: this might also include some amount of
1288 overhead, like the size of all the hashes. We need to
1289 decide whether this is useful or not.
1291 'serialized_params': a string with a concise description of the
1292 codec name and its parameters. This may be passed
1293 into the IUploadable to let it make sure that
1294 the same file encoded with different parameters
1295 will result in different storage indexes.
1297 Once this is called, set_size() and set_params() may not be called.
1300 def set_shareholders(shareholders):
1301 """Tell the encoder where to put the encoded shares. 'shareholders'
1302 must be a dictionary that maps share number (an integer ranging from
1303 0 to n-1) to an instance that provides IStorageBucketWriter. This
1304 must be performed before start() can be called."""
1307 """Begin the encode/upload process. This involves reading encrypted
1308 data from the IEncryptedUploadable, encoding it, uploading the shares
1309 to the shareholders, then sending the hash trees.
1311 set_encrypted_uploadable() and set_shareholders() must be called
1312 before this can be invoked.
1314 This returns a Deferred that fires with a verify cap when the upload process is
1315 complete. The verifycap, plus the encryption key, is sufficient to construct the read
1319 class IDecoder(Interface):
1320 """I take a list of shareholders and some setup information, then
1321 download, validate, decode, and decrypt data from them, writing the
1322 results to an output file.
1324 I do not locate the shareholders, that is left to the IDownloader. I must
1325 be given a dict of RemoteReferences to storage buckets that are ready to
1330 """I take a file-like object (providing write and close) to which all
1331 the plaintext data will be written.
1333 TODO: producer/consumer . Maybe write() should return a Deferred that
1334 indicates when it will accept more data? But probably having the
1335 IDecoder be a producer is easier to glue to IConsumer pieces.
1338 def set_shareholders(shareholders):
1339 """I take a dictionary that maps share identifiers (small integers)
1340 to RemoteReferences that provide RIBucketReader. This must be called
1344 """I start the download. This process involves retrieving data and
1345 hash chains from the shareholders, using the hashes to validate the
1346 data, decoding the shares into segments, decrypting the segments,
1347 then writing the resulting plaintext to the output file.
1349 I return a Deferred that will fire (with self) when the download is
1353 class IDownloadTarget(Interface):
1354 # Note that if the IDownloadTarget is also an IConsumer, the downloader
1355 # will register itself as a producer. This allows the target to invoke
1356 # downloader.pauseProducing, resumeProducing, and stopProducing.
1358 """Called before any calls to write() or close(). If an error
1359 occurs before any data is available, fail() may be called without
1360 a previous call to open().
1362 'size' is the length of the file being downloaded, in bytes."""
1365 """Output some data to the target."""
1367 """Inform the target that there is no more data to be written."""
1369 """fail() is called to indicate that the download has failed. 'why'
1370 is a Failure object indicating what went wrong. No further methods
1371 will be invoked on the IDownloadTarget after fail()."""
1372 def register_canceller(cb):
1373 """The CiphertextDownloader uses this to register a no-argument function
1374 that the target can call to cancel the download. Once this canceller
1375 is invoked, no further calls to write() or close() will be made."""
1377 """When the CiphertextDownloader is done, this finish() function will be
1378 called. Whatever it returns will be returned to the invoker of
1379 Downloader.download.
1381 # The following methods are just because that target might be a repairer.DownUpConnector,
1382 # and just because the current CHKUpload object expects to find the storage index and
1383 # encoding parameters in its Uploadable.
1384 def set_storageindex(storageindex):
1385 """ Set the storage index. """
1386 def set_encodingparams(encodingparams):
1387 """ Set the encoding parameters. """
1389 class IDownloader(Interface):
1390 def download(uri, target):
1391 """Perform a CHK download, sending the data to the given target.
1392 'target' must provide IDownloadTarget.
1394 Returns a Deferred that fires (with the results of target.finish)
1395 when the download is finished, or errbacks if something went wrong."""
1397 class IEncryptedUploadable(Interface):
1398 def set_upload_status(upload_status):
1399 """Provide an IUploadStatus object that should be filled with status
1400 information. The IEncryptedUploadable is responsible for setting
1401 key-determination progress ('chk'), size, storage_index, and
1402 ciphertext-fetch progress. It may delegate some of this
1403 responsibility to others, in particular to the IUploadable."""
1406 """This behaves just like IUploadable.get_size()."""
1408 def get_all_encoding_parameters():
1409 """Return a Deferred that fires with a tuple of
1410 (k,happy,n,segment_size). The segment_size will be used as-is, and
1411 must match the following constraints: it must be a multiple of k, and
1412 it shouldn't be unreasonably larger than the file size (if
1413 segment_size is larger than filesize, the difference must be stored
1416 This usually passes through to the IUploadable method of the same
1419 The encoder strictly obeys the values returned by this method. To
1420 make an upload use non-default encoding parameters, you must arrange
1421 to control the values that this method returns.
1424 def get_storage_index():
1425 """Return a Deferred that fires with a 16-byte storage index.
1428 def read_encrypted(length, hash_only):
1429 """This behaves just like IUploadable.read(), but returns crypttext
1430 instead of plaintext. If hash_only is True, then this discards the
1431 data (and returns an empty list); this improves efficiency when
1432 resuming an interrupted upload (where we need to compute the
1433 plaintext hashes, but don't need the redundant encrypted data)."""
1435 def get_plaintext_hashtree_leaves(first, last, num_segments):
1436 """OBSOLETE; Get the leaf nodes of a merkle hash tree over the plaintext
1437 segments, i.e. get the tagged hashes of the given segments. The
1438 segment size is expected to be generated by the IEncryptedUploadable
1439 before any plaintext is read or ciphertext produced, so that the
1440 segment hashes can be generated with only a single pass.
1442 This returns a Deferred which fires with a sequence of hashes, using:
1444 tuple(segment_hashes[first:last])
1446 'num_segments' is used to assert that the number of segments that the
1447 IEncryptedUploadable handled matches the number of segments that the
1448 encoder was expecting.
1450 This method must not be called until the final byte has been read
1451 from read_encrypted(). Once this method is called, read_encrypted()
1452 can never be called again.
1455 def get_plaintext_hash():
1456 """OBSOLETE; Get the hash of the whole plaintext.
1458 This returns a Deferred which fires with a tagged SHA-256 hash of the
1459 whole plaintext, obtained from hashutil.plaintext_hash(data).
1463 """Just like IUploadable.close()."""
1465 class IUploadable(Interface):
1466 def set_upload_status(upload_status):
1467 """Provide an IUploadStatus object that should be filled with status
1468 information. The IUploadable is responsible for setting
1469 key-determination progress ('chk')."""
1471 def set_default_encoding_parameters(params):
1472 """Set the default encoding parameters, which must be a dict mapping
1473 strings to ints. The meaningful keys are 'k', 'happy', 'n', and
1474 'max_segment_size'. These might have an influence on the final
1475 encoding parameters returned by get_all_encoding_parameters(), if the
1476 Uploadable doesn't have more specific preferences.
1478 This call is optional: if it is not used, the Uploadable will use
1479 some built-in defaults. If used, this method must be called before
1480 any other IUploadable methods to have any effect.
1484 """Return a Deferred that will fire with the length of the data to be
1485 uploaded, in bytes. This will be called before the data is actually
1486 used, to compute encoding parameters.
1489 def get_all_encoding_parameters():
1490 """Return a Deferred that fires with a tuple of
1491 (k,happy,n,segment_size). The segment_size will be used as-is, and
1492 must match the following constraints: it must be a multiple of k, and
1493 it shouldn't be unreasonably larger than the file size (if
1494 segment_size is larger than filesize, the difference must be stored
1497 The relative values of k and n allow some IUploadables to request
1498 better redundancy than others (in exchange for consuming more space
1501 Larger values of segment_size reduce hash overhead, while smaller
1502 values reduce memory footprint and cause data to be delivered in
1503 smaller pieces (which may provide a smoother and more predictable
1504 download experience).
1506 The encoder strictly obeys the values returned by this method. To
1507 make an upload use non-default encoding parameters, you must arrange
1508 to control the values that this method returns. One way to influence
1509 them may be to call set_encoding_parameters() before calling
1510 get_all_encoding_parameters().
1513 def get_encryption_key():
1514 """Return a Deferred that fires with a 16-byte AES key. This key will
1515 be used to encrypt the data. The key will also be hashed to derive
1518 Uploadables which want to achieve convergence should hash their file
1519 contents and the serialized_encoding_parameters to form the key
1520 (which of course requires a full pass over the data). Uploadables can
1521 use the upload.ConvergentUploadMixin class to achieve this
1524 Uploadables which do not care about convergence (or do not wish to
1525 make multiple passes over the data) can simply return a
1526 strongly-random 16 byte string.
1528 get_encryption_key() may be called multiple times: the IUploadable is
1529 required to return the same value each time.
1533 """Return a Deferred that fires with a list of strings (perhaps with
1534 only a single element) which, when concatenated together, contain the
1535 next 'length' bytes of data. If EOF is near, this may provide fewer
1536 than 'length' bytes. The total number of bytes provided by read()
1537 before it signals EOF must equal the size provided by get_size().
1539 If the data must be acquired through multiple internal read
1540 operations, returning a list instead of a single string may help to
1541 reduce string copies.
1543 'length' will typically be equal to (min(get_size(),1MB)/req_shares),
1544 so a 10kB file means length=3kB, 100kB file means length=30kB,
1545 and >=1MB file means length=300kB.
1547 This method provides for a single full pass through the data. Later
1548 use cases may desire multiple passes or access to only parts of the
1549 data (such as a mutable file making small edits-in-place). This API
1550 will be expanded once those use cases are better understood.
1554 """The upload is finished, and whatever filehandle was in use may be
1557 class IUploadResults(Interface):
1558 """I am returned by upload() methods. I contain a number of public
1559 attributes which can be read to determine the results of the upload. Some
1560 of these are functional, some are timing information. All of these may be
1563 .file_size : the size of the file, in bytes
1564 .uri : the CHK read-cap for the file
1565 .ciphertext_fetched : how many bytes were fetched by the helper
1566 .sharemap: dict mapping share identifier to set of serverids
1567 (binary strings). This indicates which servers were given
1568 which shares. For immutable files, the shareid is an
1569 integer (the share number, from 0 to N-1). For mutable
1570 files, it is a string of the form 'seq%d-%s-sh%d',
1571 containing the sequence number, the roothash, and the
1573 .servermap : dict mapping server peerid to a set of share numbers
1574 .timings : dict of timing information, mapping name to seconds (float)
1575 total : total upload time, start to finish
1576 storage_index : time to compute the storage index
1577 peer_selection : time to decide which peers will be used
1578 contacting_helper : initial helper query to upload/no-upload decision
1579 existence_check : helper pre-upload existence check
1580 helper_total : initial helper query to helper finished pushing
1581 cumulative_fetch : helper waiting for ciphertext requests
1582 total_fetch : helper start to last ciphertext response
1583 cumulative_encoding : just time spent in zfec
1584 cumulative_sending : just time spent waiting for storage servers
1585 hashes_and_close : last segment push to shareholder close
1586 total_encode_and_push : first encode to shareholder close
1590 class IDownloadResults(Interface):
1591 """I am created internally by download() methods. I contain a number of
1592 public attributes which contain details about the download process.::
1594 .file_size : the size of the file, in bytes
1595 .servers_used : set of server peerids that were used during download
1596 .server_problems : dict mapping server peerid to a problem string. Only
1597 servers that had problems (bad hashes, disconnects) are
1599 .servermap : dict mapping server peerid to a set of share numbers. Only
1600 servers that had any shares are listed here.
1601 .timings : dict of timing information, mapping name to seconds (float)
1602 peer_selection : time to ask servers about shares
1603 servers_peer_selection : dict of peerid to DYHB-query time
1604 uri_extension : time to fetch a copy of the URI extension block
1605 hashtrees : time to fetch the hash trees
1606 segments : time to fetch, decode, and deliver segments
1607 cumulative_fetch : time spent waiting for storage servers
1608 cumulative_decode : just time spent in zfec
1609 cumulative_decrypt : just time spent in decryption
1610 total : total download time, start to finish
1611 fetch_per_server : dict of peerid to list of per-segment fetch times
1615 class IUploader(Interface):
1616 def upload(uploadable):
1617 """Upload the file. 'uploadable' must impement IUploadable. This
1618 returns a Deferred which fires with an UploadResults instance, from
1619 which the URI of the file can be obtained as results.uri ."""
1621 def upload_ssk(write_capability, new_version, uploadable):
1622 """TODO: how should this work?"""
1624 class ICheckable(Interface):
1625 def check(monitor, verify=False, add_lease=False):
1626 """Check upon my health, optionally repairing any problems.
1628 This returns a Deferred that fires with an instance that provides
1629 ICheckResults, or None if the object is non-distributed (i.e. LIT
1632 The monitor will be checked periodically to see if the operation has
1633 been cancelled. If so, no new queries will be sent, and the Deferred
1634 will fire (with a OperationCancelledError) immediately.
1636 Filenodes and dirnodes (which provide IFilesystemNode) are also
1637 checkable. Instances that represent verifier-caps will be checkable
1638 but not downloadable. Some objects (like LIT files) do not actually
1639 live in the grid, and their checkers return None (non-distributed
1640 files are always healthy).
1642 If verify=False, a relatively lightweight check will be performed: I
1643 will ask all servers if they have a share for me, and I will believe
1644 whatever they say. If there are at least N distinct shares on the
1645 grid, my results will indicate r.is_healthy()==True. This requires a
1646 roundtrip to each server, but does not transfer very much data, so
1647 the network bandwidth is fairly low.
1649 If verify=True, a more resource-intensive check will be performed:
1650 every share will be downloaded, and the hashes will be validated on
1651 every bit. I will ignore any shares that failed their hash checks. If
1652 there are at least N distinct valid shares on the grid, my results
1653 will indicate r.is_healthy()==True. This requires N/k times as much
1654 download bandwidth (and server disk IO) as a regular download. If a
1655 storage server is holding a corrupt share, or is experiencing memory
1656 failures during retrieval, or is malicious or buggy, then
1657 verification will detect the problem, but checking will not.
1659 If add_lease=True, I will ensure that an up-to-date lease is present
1660 on each share. The lease secrets will be derived from by node secret
1661 (in BASEDIR/private/secret), so either I will add a new lease to the
1662 share, or I will merely renew the lease that I already had. In a
1663 future version of the storage-server protocol (once Accounting has
1664 been implemented), there may be additional options here to define the
1665 kind of lease that is obtained (which account number to claim, etc).
1667 TODO: any problems seen during checking will be reported to the
1668 health-manager.furl, a centralized object which is responsible for
1669 figuring out why files are unhealthy so corrective action can be
1673 def check_and_repair(monitor, verify=False, add_lease=False):
1674 """Like check(), but if the file/directory is not healthy, attempt to
1677 Any non-healthy result will cause an immediate repair operation, to
1678 generate and upload new shares. After repair, the file will be as
1679 healthy as we can make it. Details about what sort of repair is done
1680 will be put in the check-and-repair results. The Deferred will not
1681 fire until the repair is complete.
1683 This returns a Deferred which fires with an instance of
1684 ICheckAndRepairResults."""
1686 class IDeepCheckable(Interface):
1687 def start_deep_check(verify=False, add_lease=False):
1688 """Check upon the health of me and everything I can reach.
1690 This is a recursive form of check(), useable only on dirnodes.
1692 I return a Monitor, with results that are an IDeepCheckResults
1695 TODO: If any of the directories I traverse are unrecoverable, the
1696 Monitor will report failure. If any of the files I check upon are
1697 unrecoverable, those problems will be reported in the
1698 IDeepCheckResults as usual, and the Monitor will not report a
1702 def start_deep_check_and_repair(verify=False, add_lease=False):
1703 """Check upon the health of me and everything I can reach. Repair
1704 anything that isn't healthy.
1706 This is a recursive form of check_and_repair(), useable only on
1709 I return a Monitor, with results that are an
1710 IDeepCheckAndRepairResults object.
1712 TODO: If any of the directories I traverse are unrecoverable, the
1713 Monitor will report failure. If any of the files I check upon are
1714 unrecoverable, those problems will be reported in the
1715 IDeepCheckResults as usual, and the Monitor will not report a
1719 class ICheckResults(Interface):
1720 """I contain the detailed results of a check/verify operation.
1723 def get_storage_index():
1724 """Return a string with the (binary) storage index."""
1725 def get_storage_index_string():
1726 """Return a string with the (printable) abbreviated storage index."""
1728 """Return the (string) URI of the object that was checked."""
1731 """Return a boolean, True if the file/dir is fully healthy, False if
1732 it is damaged in any way. Non-distributed LIT files always return
1735 def is_recoverable():
1736 """Return a boolean, True if the file/dir can be recovered, False if
1737 not. Unrecoverable files are obviously unhealthy. Non-distributed LIT
1738 files always return True."""
1740 def needs_rebalancing():
1741 """Return a boolean, True if the file/dir's reliability could be
1742 improved by moving shares to new servers. Non-distributed LIT files
1743 always return False."""
1747 """Return a dictionary that describes the state of the file/dir. LIT
1748 files always return an empty dictionary. Normal files and directories return a
1749 dictionary with the following keys (note that these use binary strings rather than
1750 base32-encoded ones) (also note that for mutable files, these counts are for the 'best'
1753 count-shares-good: the number of distinct good shares that were found
1754 count-shares-needed: 'k', the number of shares required for recovery
1755 count-shares-expected: 'N', the number of total shares generated
1756 count-good-share-hosts: the number of distinct storage servers with
1757 good shares. If this number is less than
1758 count-shares-good, then some shares are
1759 doubled up, increasing the correlation of
1760 failures. This indicates that one or more
1761 shares should be moved to an otherwise unused
1762 server, if one is available.
1763 count-corrupt-shares: the number of shares with integrity failures
1764 list-corrupt-shares: a list of 'share locators', one for each share
1765 that was found to be corrupt. Each share
1766 locator is a list of (serverid, storage_index,
1768 count-incompatible-shares: the number of shares which are of a share format unknown to
1770 list-incompatible-shares: a list of 'share locators', one for each share that was found
1771 to be of an unknown format. Each share locator is a list of
1772 (serverid, storage_index, sharenum).
1773 servers-responding: list of (binary) storage server identifiers,
1774 one for each server which responded to the share
1775 query (even if they said they didn't have shares,
1776 and even if they said they did have shares but then
1777 didn't send them when asked, or dropped the
1778 connection, or returned a Failure, and even if they
1779 said they did have shares and sent incorrect ones
1781 sharemap: dict mapping share identifier to list of serverids
1782 (binary strings). This indicates which servers are holding
1783 which shares. For immutable files, the shareid is an
1784 integer (the share number, from 0 to N-1). For mutable
1785 files, it is a string of the form 'seq%d-%s-sh%d',
1786 containing the sequence number, the roothash, and the
1789 The following keys are most relevant for mutable files, but immutable
1790 files will provide sensible values too::
1792 count-wrong-shares: the number of shares for versions other than the
1793 'best' one (which is defined as being the
1794 recoverable version with the highest sequence
1795 number, then the highest roothash). These are
1796 either leftover shares from an older version
1797 (perhaps on a server that was offline when an
1798 update occurred), shares from an unrecoverable
1799 newer version, or shares from an alternate
1800 current version that results from an
1801 uncoordinated write collision. For a healthy
1802 file, this will equal 0.
1804 count-recoverable-versions: the number of recoverable versions of
1805 the file. For a healthy file, this will
1808 count-unrecoverable-versions: the number of unrecoverable versions
1809 of the file. For a healthy file, this
1815 """Return a string with a brief (one-line) summary of the results."""
1818 """Return a list of strings with more detailed results."""
1820 class ICheckAndRepairResults(Interface):
1821 """I contain the detailed results of a check/verify/repair operation.
1823 The IFilesystemNode.check()/verify()/repair() methods all return
1824 instances that provide ICheckAndRepairResults.
1827 def get_storage_index():
1828 """Return a string with the (binary) storage index."""
1829 def get_storage_index_string():
1830 """Return a string with the (printable) abbreviated storage index."""
1831 def get_repair_attempted():
1832 """Return a boolean, True if a repair was attempted."""
1833 def get_repair_successful():
1834 """Return a boolean, True if repair was attempted and the file/dir
1835 was fully healthy afterwards. False if no repair was attempted or if
1836 a repair attempt failed."""
1837 def get_pre_repair_results():
1838 """Return an ICheckResults instance that describes the state of the
1839 file/dir before any repair was attempted."""
1840 def get_post_repair_results():
1841 """Return an ICheckResults instance that describes the state of the
1842 file/dir after any repair was attempted. If no repair was attempted,
1843 the pre-repair and post-repair results will be identical."""
1846 class IDeepCheckResults(Interface):
1847 """I contain the results of a deep-check operation.
1849 This is returned by a call to ICheckable.deep_check().
1852 def get_root_storage_index_string():
1853 """Return the storage index (abbreviated human-readable string) of
1854 the first object checked."""
1856 """Return a dictionary with the following keys::
1858 count-objects-checked: count of how many objects were checked
1859 count-objects-healthy: how many of those objects were completely
1861 count-objects-unhealthy: how many were damaged in some way
1862 count-objects-unrecoverable: how many were unrecoverable
1863 count-corrupt-shares: how many shares were found to have
1864 corruption, summed over all objects
1868 def get_corrupt_shares():
1869 """Return a set of (serverid, storage_index, sharenum) for all shares
1870 that were found to be corrupt. Both serverid and storage_index are
1873 def get_all_results():
1874 """Return a dictionary mapping pathname (a tuple of strings, ready to
1875 be slash-joined) to an ICheckResults instance, one for each object
1876 that was checked."""
1878 def get_results_for_storage_index(storage_index):
1879 """Retrive the ICheckResults instance for the given (binary)
1880 storage index. Raises KeyError if there are no results for that
1884 """Return a dictionary with the same keys as
1885 IDirectoryNode.deep_stats()."""
1887 class IDeepCheckAndRepairResults(Interface):
1888 """I contain the results of a deep-check-and-repair operation.
1890 This is returned by a call to ICheckable.deep_check_and_repair().
1893 def get_root_storage_index_string():
1894 """Return the storage index (abbreviated human-readable string) of
1895 the first object checked."""
1897 """Return a dictionary with the following keys::
1899 count-objects-checked: count of how many objects were checked
1900 count-objects-healthy-pre-repair: how many of those objects were
1901 completely healthy (before any
1903 count-objects-unhealthy-pre-repair: how many were damaged in
1905 count-objects-unrecoverable-pre-repair: how many were unrecoverable
1906 count-objects-healthy-post-repair: how many of those objects were
1907 completely healthy (after any
1909 count-objects-unhealthy-post-repair: how many were damaged in
1911 count-objects-unrecoverable-post-repair: how many were
1913 count-repairs-attempted: repairs were attempted on this many
1914 objects. The count-repairs- keys will
1915 always be provided, however unless
1916 repair=true is present, they will all
1918 count-repairs-successful: how many repairs resulted in healthy
1920 count-repairs-unsuccessful: how many repairs resulted did not
1921 results in completely healthy objects
1922 count-corrupt-shares-pre-repair: how many shares were found to
1923 have corruption, summed over all
1924 objects examined (before any
1926 count-corrupt-shares-post-repair: how many shares were found to
1927 have corruption, summed over all
1928 objects examined (after any
1933 """Return a dictionary with the same keys as
1934 IDirectoryNode.deep_stats()."""
1936 def get_corrupt_shares():
1937 """Return a set of (serverid, storage_index, sharenum) for all shares
1938 that were found to be corrupt before any repair was attempted. Both
1939 serverid and storage_index are binary.
1941 def get_remaining_corrupt_shares():
1942 """Return a set of (serverid, storage_index, sharenum) for all shares
1943 that were found to be corrupt after any repair was completed. Both
1944 serverid and storage_index are binary. These are shares that need
1945 manual inspection and probably deletion.
1947 def get_all_results():
1948 """Return a dictionary mapping pathname (a tuple of strings, ready to
1949 be slash-joined) to an ICheckAndRepairResults instance, one for each
1950 object that was checked."""
1952 def get_results_for_storage_index(storage_index):
1953 """Retrive the ICheckAndRepairResults instance for the given (binary)
1954 storage index. Raises KeyError if there are no results for that
1958 class IRepairable(Interface):
1959 def repair(check_results):
1960 """Attempt to repair the given object. Returns a Deferred that fires
1961 with a IRepairResults object.
1963 I must be called with an object that implements ICheckResults, as
1964 proof that you have actually discovered a problem with this file. I
1965 will use the data in the checker results to guide the repair process,
1966 such as which servers provided bad data and should therefore be
1967 avoided. The ICheckResults object is inside the
1968 ICheckAndRepairResults object, which is returned by the
1969 ICheckable.check() method::
1971 d = filenode.check(repair=False)
1972 def _got_results(check_and_repair_results):
1973 check_results = check_and_repair_results.get_pre_repair_results()
1974 return filenode.repair(check_results)
1975 d.addCallback(_got_results)
1979 class IRepairResults(Interface):
1980 """I contain the results of a repair operation."""
1983 class IClient(Interface):
1984 def upload(uploadable):
1985 """Upload some data into a CHK, get back the UploadResults for it.
1986 @param uploadable: something that implements IUploadable
1987 @return: a Deferred that fires with the UploadResults instance.
1988 To get the URI for this file, use results.uri .
1991 def create_mutable_file(contents=""):
1992 """Create a new mutable file with contents, get back the URI string.
1993 @param contents: the initial contents to place in the file.
1994 @return: a Deferred that fires with tne (string) SSK URI for the new
1998 def create_empty_dirnode():
1999 """Create a new dirnode, empty and unattached.
2000 @return: a Deferred that fires with the new IDirectoryNode instance.
2003 def create_node_from_uri(uri):
2004 """Create a new IFilesystemNode instance from the uri, synchronously.
2005 @param uri: a string or IURI-providing instance. This could be for a
2006 LiteralFileNode, a CHK file node, a mutable file node, or
2008 @return: an instance that provides IFilesystemNode (or more usefully one
2009 of its subclasses). File-specifying URIs will result in
2010 IFileNode or IMutableFileNode -providing instances, like
2011 FileNode, LiteralFileNode, or MutableFileNode.
2012 Directory-specifying URIs will result in
2013 IDirectoryNode-providing instances, like NewDirectoryNode.
2016 class IClientStatus(Interface):
2017 def list_all_uploads():
2018 """Return a list of uploader objects, one for each upload which
2019 currently has an object available (tracked with weakrefs). This is
2020 intended for debugging purposes."""
2021 def list_active_uploads():
2022 """Return a list of active IUploadStatus objects."""
2023 def list_recent_uploads():
2024 """Return a list of IUploadStatus objects for the most recently
2027 def list_all_downloads():
2028 """Return a list of downloader objects, one for each download which
2029 currently has an object available (tracked with weakrefs). This is
2030 intended for debugging purposes."""
2031 def list_active_downloads():
2032 """Return a list of active IDownloadStatus objects."""
2033 def list_recent_downloads():
2034 """Return a list of IDownloadStatus objects for the most recently
2035 started downloads."""
2037 class IUploadStatus(Interface):
2039 """Return a timestamp (float with seconds since epoch) indicating
2040 when the operation was started."""
2041 def get_storage_index():
2042 """Return a string with the (binary) storage index in use on this
2043 upload. Returns None if the storage index has not yet been
2046 """Return an integer with the number of bytes that will eventually
2047 be uploaded for this file. Returns None if the size is not yet known.
2050 """Return True if this upload is using a Helper, False if not."""
2052 """Return a string describing the current state of the upload
2055 """Returns a tuple of floats, (chk, ciphertext, encode_and_push),
2056 each from 0.0 to 1.0 . 'chk' describes how much progress has been
2057 made towards hashing the file to determine a CHK encryption key: if
2058 non-convergent encryption is in use, this will be trivial, otherwise
2059 the whole file must be hashed. 'ciphertext' describes how much of the
2060 ciphertext has been pushed to the helper, and is '1.0' for non-helper
2061 uploads. 'encode_and_push' describes how much of the encode-and-push
2062 process has finished: for helper uploads this is dependent upon the
2063 helper providing progress reports. It might be reasonable to add all
2064 three numbers and report the sum to the user."""
2066 """Return True if the upload is currently active, False if not."""
2068 """Return an instance of UploadResults (which contains timing and
2069 sharemap information). Might return None if the upload is not yet
2072 """Each upload status gets a unique number: this method returns that
2073 number. This provides a handle to this particular upload, so a web
2074 page can generate a suitable hyperlink."""
2076 class IDownloadStatus(Interface):
2078 """Return a timestamp (float with seconds since epoch) indicating
2079 when the operation was started."""
2080 def get_storage_index():
2081 """Return a string with the (binary) storage index in use on this
2082 download. This may be None if there is no storage index (i.e. LIT
2085 """Return an integer with the number of bytes that will eventually be
2086 retrieved for this file. Returns None if the size is not yet known.
2089 """Return True if this download is using a Helper, False if not."""
2091 """Return a string describing the current state of the download
2094 """Returns a float (from 0.0 to 1.0) describing the amount of the
2095 download that has completed. This value will remain at 0.0 until the
2096 first byte of plaintext is pushed to the download target."""
2098 """Return True if the download is currently active, False if not."""
2100 """Each download status gets a unique number: this method returns
2101 that number. This provides a handle to this particular download, so a
2102 web page can generate a suitable hyperlink."""
2104 class IServermapUpdaterStatus(Interface):
2106 class IPublishStatus(Interface):
2108 class IRetrieveStatus(Interface):
2111 class NotCapableError(Exception):
2112 """You have tried to write to a read-only node."""
2114 class BadWriteEnablerError(Exception):
2117 class RIControlClient(RemoteInterface):
2119 def wait_for_client_connections(num_clients=int):
2120 """Do not return until we have connections to at least NUM_CLIENTS
2124 def upload_from_file_to_uri(filename=str, convergence=ChoiceOf(None, StringConstraint(2**20))):
2125 """Upload a file to the grid. This accepts a filename (which must be
2126 absolute) that points to a file on the node's local disk. The node will
2127 read the contents of this file, upload it to the grid, then return the
2128 URI at which it was uploaded. If convergence is None then a random
2129 encryption key will be used, else the plaintext will be hashed, then
2130 that hash will be mixed together with the "convergence" string to form
2135 def download_from_uri_to_file(uri=URI, filename=str):
2136 """Download a file from the grid, placing it on the node's local disk
2137 at the given filename (which must be absolute[?]). Returns the
2138 absolute filename where the file was written."""
2143 def get_memory_usage():
2144 """Return a dict describes the amount of memory currently in use. The
2145 keys are 'VmPeak', 'VmSize', and 'VmData'. The values are integers,
2146 measuring memory consupmtion in bytes."""
2147 return DictOf(str, int)
2149 def speed_test(count=int, size=int, mutable=Any()):
2150 """Write 'count' tempfiles to disk, all of the given size. Measure
2151 how long (in seconds) it takes to upload them all to the servers.
2152 Then measure how long it takes to download all of them. If 'mutable'
2153 is 'create', time creation of mutable files. If 'mutable' is
2154 'upload', then time access to the same mutable file instead of
2157 Returns a tuple of (upload_time, download_time).
2159 return (float, float)
2161 def measure_peer_response_time():
2162 """Send a short message to each connected peer, and measure the time
2163 it takes for them to respond to it. This is a rough measure of the
2164 application-level round trip time.
2166 @return: a dictionary mapping peerid to a float (RTT time in seconds)
2169 return DictOf(Nodeid, float)
2171 UploadResults = Any() #DictOf(str, str)
2173 class RIEncryptedUploadable(RemoteInterface):
2174 __remote_name__ = "RIEncryptedUploadable.tahoe.allmydata.com"
2179 def get_all_encoding_parameters():
2180 return (int, int, int, long)
2182 def read_encrypted(offset=Offset, length=ReadSize):
2189 class RICHKUploadHelper(RemoteInterface):
2190 __remote_name__ = "RIUploadHelper.tahoe.allmydata.com"
2194 Return a dictionary of version information.
2196 return DictOf(str, Any())
2198 def upload(reader=RIEncryptedUploadable):
2199 return UploadResults
2202 class RIHelper(RemoteInterface):
2203 __remote_name__ = "RIHelper.tahoe.allmydata.com"
2207 Return a dictionary of version information.
2209 return DictOf(str, Any())
2211 def upload_chk(si=StorageIndex):
2212 """See if a file with a given storage index needs uploading. The
2213 helper will ask the appropriate storage servers to see if the file
2214 has already been uploaded. If so, the helper will return a set of
2215 'upload results' that includes whatever hashes are needed to build
2216 the read-cap, and perhaps a truncated sharemap.
2218 If the file has not yet been uploaded (or if it was only partially
2219 uploaded), the helper will return an empty upload-results dictionary
2220 and also an RICHKUploadHelper object that will take care of the
2221 upload process. The client should call upload() on this object and
2222 pass it a reference to an RIEncryptedUploadable object that will
2223 provide ciphertext. When the upload is finished, the upload() method
2224 will finish and return the upload results.
2226 return (UploadResults, ChoiceOf(RICHKUploadHelper, None))
2229 class RIStatsProvider(RemoteInterface):
2230 __remote_name__ = "RIStatsProvider.tahoe.allmydata.com"
2232 Provides access to statistics and monitoring information.
2237 returns a dictionary containing 'counters' and 'stats', each a dictionary
2238 with string counter/stat name keys, and numeric values. counters are
2239 monotonically increasing measures of work done, and stats are instantaneous
2240 measures (potentially time averaged internally)
2242 return DictOf(str, DictOf(str, ChoiceOf(float, int, long)))
2244 class RIStatsGatherer(RemoteInterface):
2245 __remote_name__ = "RIStatsGatherer.tahoe.allmydata.com"
2247 Provides a monitoring service for centralised collection of stats
2250 def provide(provider=RIStatsProvider, nickname=str):
2252 @param provider: a stats collector instance which should be polled
2253 periodically by the gatherer to collect stats.
2254 @param nickname: a name useful to identify the provided client
2259 class IStatsProducer(Interface):
2262 returns a dictionary, with str keys representing the names of stats
2263 to be monitored, and numeric values.
2266 class RIKeyGenerator(RemoteInterface):
2267 __remote_name__ = "RIKeyGenerator.tahoe.allmydata.com"
2269 Provides a service offering to make RSA key pairs.
2272 def get_rsa_key_pair(key_size=int):
2274 @param key_size: the size of the signature key.
2275 @return: tuple(verifying_key, signing_key)
2277 return TupleOf(str, str)
2280 class FileTooLargeError(Exception):
2283 class IValidatedThingProxy(Interface):
2285 """ Acquire a thing and validate it. Return a deferred which is eventually fired with
2286 self if the thing is valid or errbacked if it can't be acquired or validated. """
2288 class InsufficientVersionError(Exception):
2289 def __init__(self, needed, got):
2290 self.needed = needed
2293 return "InsufficientVersionError(need '%s', got %s)" % (self.needed,