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
28 DEFAULT_MAX_SEGMENT_SIZE = 128*KiB
30 class RIStubClient(RemoteInterface):
31 """Each client publishes a service announcement for a dummy object called
32 the StubClient. This object doesn't actually offer any services, but the
33 announcement helps the Introducer keep track of which clients are
34 subscribed (so the grid admin can keep track of things like the size of
35 the grid and the client versions in use. This is the (empty)
36 RemoteInterface for the StubClient."""
38 class RIBucketWriter(RemoteInterface):
39 """ Objects of this kind live on the server side. """
40 def write(offset=Offset, data=ShareData):
45 If the data that has been written is incomplete or inconsistent then
46 the server will throw the data away, else it will store it for future
52 """Abandon all the data that has been written.
56 class RIBucketReader(RemoteInterface):
57 def read(offset=Offset, length=ReadSize):
60 def advise_corrupt_share(reason=str):
61 """Clients who discover hash failures in shares that they have
62 downloaded from me will use this method to inform me about the
63 failures. I will record their concern so that my operator can
64 manually inspect the shares in question. I return None.
66 This is a wrapper around RIStorageServer.advise_corrupt_share(),
67 which is tied to a specific share, and therefore does not need the
68 extra share-identifying arguments. Please see that method for full
72 TestVector = ListOf(TupleOf(Offset, ReadSize, str, str))
73 # elements are (offset, length, operator, specimen)
74 # operator is one of "lt, le, eq, ne, ge, gt"
75 # nop always passes and is used to fetch data while writing.
76 # you should use length==len(specimen) for everything except nop
77 DataVector = ListOf(TupleOf(Offset, ShareData))
78 # (offset, data). This limits us to 30 writes of 1MiB each per call
79 TestAndWriteVectorsForShares = DictOf(int,
82 ChoiceOf(None, Offset), # new_length
84 ReadVector = ListOf(TupleOf(Offset, ReadSize))
85 ReadData = ListOf(ShareData)
86 # returns data[offset:offset+length] for each element of TestVector
88 class RIStorageServer(RemoteInterface):
89 __remote_name__ = "RIStorageServer.tahoe.allmydata.com"
93 Return a dictionary of version information.
95 return DictOf(str, Any())
97 def allocate_buckets(storage_index=StorageIndex,
98 renew_secret=LeaseRenewSecret,
99 cancel_secret=LeaseCancelSecret,
100 sharenums=SetOf(int, maxLength=MAX_BUCKETS),
101 allocated_size=Offset, canary=Referenceable):
103 @param storage_index: the index of the bucket to be created or
105 @param sharenums: these are the share numbers (probably between 0 and
106 99) that the sender is proposing to store on this
108 @param renew_secret: This is the secret used to protect bucket refresh
109 This secret is generated by the client and
110 stored for later comparison by the server. Each
111 server is given a different secret.
112 @param cancel_secret: Like renew_secret, but protects bucket decref.
113 @param canary: If the canary is lost before close(), the bucket is
115 @return: tuple of (alreadygot, allocated), where alreadygot is what we
116 already have and allocated is what we hereby agree to accept.
117 New leases are added for shares in both lists.
119 return TupleOf(SetOf(int, maxLength=MAX_BUCKETS),
120 DictOf(int, RIBucketWriter, maxKeys=MAX_BUCKETS))
122 def add_lease(storage_index=StorageIndex,
123 renew_secret=LeaseRenewSecret,
124 cancel_secret=LeaseCancelSecret):
126 Add a new lease on the given bucket. If the renew_secret matches an
127 existing lease, that lease will be renewed instead. If there is no
128 bucket for the given storage_index, return silently. (note that in
129 tahoe-1.3.0 and earlier, IndexError was raised if there was no
132 return Any() # returns None now, but future versions might change
134 def renew_lease(storage_index=StorageIndex, renew_secret=LeaseRenewSecret):
136 Renew the lease on a given bucket, resetting the timer to 31 days.
137 Some networks will use this, some will not. If there is no bucket for
138 the given storage_index, IndexError will be raised.
140 For mutable shares, if the given renew_secret does not match an
141 existing lease, IndexError will be raised with a note listing the
142 server-nodeids on the existing leases, so leases on migrated shares
143 can be renewed or cancelled. For immutable shares, IndexError
144 (without the note) will be raised.
148 def cancel_lease(storage_index=StorageIndex,
149 cancel_secret=LeaseCancelSecret):
151 Cancel the lease on a given bucket. If this was the last lease on the
152 bucket, the bucket will be deleted. If there is no bucket for the
153 given storage_index, IndexError will be raised.
155 For mutable shares, if the given cancel_secret does not match an
156 existing lease, IndexError will be raised with a note listing the
157 server-nodeids on the existing leases, so leases on migrated shares
158 can be renewed or cancelled. For immutable shares, IndexError
159 (without the note) will be raised.
163 def get_buckets(storage_index=StorageIndex):
164 return DictOf(int, RIBucketReader, maxKeys=MAX_BUCKETS)
168 def slot_readv(storage_index=StorageIndex,
169 shares=ListOf(int), readv=ReadVector):
170 """Read a vector from the numbered shares associated with the given
171 storage index. An empty shares list means to return data from all
172 known shares. Returns a dictionary with one key per share."""
173 return DictOf(int, ReadData) # shnum -> results
175 def slot_testv_and_readv_and_writev(storage_index=StorageIndex,
176 secrets=TupleOf(WriteEnablerSecret,
179 tw_vectors=TestAndWriteVectorsForShares,
182 """General-purpose test-and-set operation for mutable slots. Perform
183 a bunch of comparisons against the existing shares. If they all pass,
184 then apply a bunch of write vectors to those shares. Then use the
185 read vectors to extract data from all the shares and return the data.
187 This method is, um, large. The goal is to allow clients to update all
188 the shares associated with a mutable file in a single round trip.
190 @param storage_index: the index of the bucket to be created or
192 @param write_enabler: a secret that is stored along with the slot.
193 Writes are accepted from any caller who can
194 present the matching secret. A different secret
195 should be used for each slot*server pair.
196 @param renew_secret: This is the secret used to protect bucket refresh
197 This secret is generated by the client and
198 stored for later comparison by the server. Each
199 server is given a different secret.
200 @param cancel_secret: Like renew_secret, but protects bucket decref.
202 The 'secrets' argument is a tuple of (write_enabler, renew_secret,
203 cancel_secret). The first is required to perform any write. The
204 latter two are used when allocating new shares. To simply acquire a
205 new lease on existing shares, use an empty testv and an empty writev.
207 Each share can have a separate test vector (i.e. a list of
208 comparisons to perform). If all vectors for all shares pass, then all
209 writes for all shares are recorded. Each comparison is a 4-tuple of
210 (offset, length, operator, specimen), which effectively does a bool(
211 (read(offset, length)) OPERATOR specimen ) and only performs the
212 write if all these evaluate to True. Basic test-and-set uses 'eq'.
213 Write-if-newer uses a seqnum and (offset, length, 'lt', specimen).
214 Write-if-same-or-newer uses 'le'.
216 Reads from the end of the container are truncated, and missing shares
217 behave like empty ones, so to assert that a share doesn't exist (for
218 use when creating a new share), use (0, 1, 'eq', '').
220 The write vector will be applied to the given share, expanding it if
221 necessary. A write vector applied to a share number that did not
222 exist previously will cause that share to be created.
224 Each write vector is accompanied by a 'new_length' argument. If
225 new_length is not None, use it to set the size of the container. This
226 can be used to pre-allocate space for a series of upcoming writes, or
227 truncate existing data. If the container is growing, new_length will
228 be applied before datav. If the container is shrinking, it will be
229 applied afterwards. If new_length==0, the share will be deleted.
231 The read vector is used to extract data from all known shares,
232 *before* any writes have been applied. The same vector is used for
233 all shares. This captures the state that was tested by the test
236 This method returns two values: a boolean and a dict. The boolean is
237 True if the write vectors were applied, False if not. The dict is
238 keyed by share number, and each value contains a list of strings, one
239 for each element of the read vector.
241 If the write_enabler is wrong, this will raise BadWriteEnablerError.
242 To enable share migration (using update_write_enabler), the exception
243 will have the nodeid used for the old write enabler embedded in it,
244 in the following string::
246 The write enabler was recorded by nodeid '%s'.
248 Note that the nodeid here is encoded using the same base32 encoding
249 used by Foolscap and allmydata.util.idlib.nodeid_b2a().
252 return TupleOf(bool, DictOf(int, ReadData))
254 def advise_corrupt_share(share_type=str, storage_index=StorageIndex,
255 shnum=int, reason=str):
256 """Clients who discover hash failures in shares that they have
257 downloaded from me will use this method to inform me about the
258 failures. I will record their concern so that my operator can
259 manually inspect the shares in question. I return None.
261 'share_type' is either 'mutable' or 'immutable'. 'storage_index' is a
262 (binary) storage index string, and 'shnum' is the integer share
263 number. 'reason' is a human-readable explanation of the problem,
264 probably including some expected hash values and the computed ones
265 which did not match. Corruption advisories for mutable shares should
266 include a hash of the public key (the same value that appears in the
267 mutable-file verify-cap), since the current share format does not
271 class IStorageBucketWriter(Interface):
273 Objects of this kind live on the client side.
275 def put_block(segmentnum=int, data=ShareData):
276 """@param data: For most segments, this data will be 'blocksize'
277 bytes in length. The last segment might be shorter.
278 @return: a Deferred that fires (with None) when the operation completes
281 def put_plaintext_hashes(hashes=ListOf(Hash)):
283 @return: a Deferred that fires (with None) when the operation completes
286 def put_crypttext_hashes(hashes=ListOf(Hash)):
288 @return: a Deferred that fires (with None) when the operation completes
291 def put_block_hashes(blockhashes=ListOf(Hash)):
293 @return: a Deferred that fires (with None) when the operation completes
296 def put_share_hashes(sharehashes=ListOf(TupleOf(int, Hash))):
298 @return: a Deferred that fires (with None) when the operation completes
301 def put_uri_extension(data=URIExtensionData):
302 """This block of data contains integrity-checking information (hashes
303 of plaintext, crypttext, and shares), as well as encoding parameters
304 that are necessary to recover the data. This is a serialized dict
305 mapping strings to other strings. The hash of this data is kept in
306 the URI and verified before any of the data is used. All buckets for
307 a given file contain identical copies of this data.
309 The serialization format is specified with the following pseudocode:
310 for k in sorted(dict.keys()):
311 assert re.match(r'^[a-zA-Z_\-]+$', k)
312 write(k + ':' + netstring(dict[k]))
314 @return: a Deferred that fires (with None) when the operation completes
318 """Finish writing and close the bucket. The share is not finalized
319 until this method is called: if the uploading client disconnects
320 before calling close(), the partially-written share will be
323 @return: a Deferred that fires (with None) when the operation completes
326 class IStorageBucketReader(Interface):
328 def get_block_data(blocknum=int, blocksize=int, size=int):
329 """Most blocks will be the same size. The last block might be shorter
335 def get_crypttext_hashes():
337 @return: ListOf(Hash)
340 def get_block_hashes(at_least_these=SetOf(int)):
342 @return: ListOf(Hash)
345 def get_share_hashes(at_least_these=SetOf(int)):
347 @return: ListOf(TupleOf(int, Hash))
350 def get_uri_extension():
352 @return: URIExtensionData
355 class IStorageBroker(Interface):
356 def get_servers_for_index(peer_selection_index):
358 @return: list of (peerid, versioned-rref) tuples
360 def get_all_servers():
362 @return: frozenset of (peerid, versioned-rref) tuples
364 def get_all_serverids():
366 @return: frozenset of serverid strings
368 def get_nickname_for_serverid(serverid):
370 @return: unicode nickname, or None
373 # methods moved from IntroducerClient, need review
374 def get_all_connections():
375 """Return a frozenset of (nodeid, service_name, rref) tuples, one for
376 each active connection we've established to a remote service. This is
377 mostly useful for unit tests that need to wait until a certain number
378 of connections have been made."""
380 def get_all_connectors():
381 """Return a dict that maps from (nodeid, service_name) to a
382 RemoteServiceConnector instance for all services that we are actively
383 trying to connect to. Each RemoteServiceConnector has the following
386 service_name: the type of service provided, like 'storage'
387 announcement_time: when we first heard about this service
388 last_connect_time: when we last established a connection
389 last_loss_time: when we last lost a connection
391 version: the peer's version, from the most recent connection
392 oldest_supported: the peer's oldest supported version, same
394 rref: the RemoteReference, if connected, otherwise None
395 remote_host: the IAddress, if connected, otherwise None
397 This method is intended for monitoring interfaces, such as a web page
398 which describes connecting and connected peers.
401 def get_all_peerids():
402 """Return a frozenset of all peerids to whom we have a connection (to
403 one or more services) established. Mostly useful for unit tests."""
405 def get_all_connections_for(service_name):
406 """Return a frozenset of (nodeid, service_name, rref) tuples, one
407 for each active connection that provides the given SERVICE_NAME."""
409 def get_permuted_peers(service_name, key):
410 """Returns an ordered list of (peerid, rref) tuples, selecting from
411 the connections that provide SERVICE_NAME, using a hash-based
412 permutation keyed by KEY. This randomizes the service list in a
413 repeatable way, to distribute load over many peers.
417 class IURI(Interface):
418 def init_from_string(uri):
419 """Accept a string (as created by my to_string() method) and populate
420 this instance with its data. I am not normally called directly,
421 please use the module-level uri.from_string() function to convert
422 arbitrary URI strings into IURI-providing instances."""
425 """Return False if this URI be used to modify the data. Return True
426 if this URI cannot be used to modify the data."""
429 """Return True if the data can be modified by *somebody* (perhaps
430 someone who has a more powerful URI than this one)."""
432 # TODO: rename to get_read_cap()
434 """Return another IURI instance, which represents a read-only form of
435 this one. If is_readonly() is True, this returns self."""
437 def get_verify_cap():
438 """Return an instance that provides IVerifierURI, which can be used
439 to check on the availability of the file or directory, without
440 providing enough capabilities to actually read or modify the
441 contents. This may return None if the file does not need checking or
442 verification (e.g. LIT URIs).
446 """Return a string of printable ASCII characters, suitable for
447 passing into init_from_string."""
449 class IVerifierURI(Interface, IURI):
450 def init_from_string(uri):
451 """Accept a string (as created by my to_string() method) and populate
452 this instance with its data. I am not normally called directly,
453 please use the module-level uri.from_string() function to convert
454 arbitrary URI strings into IURI-providing instances."""
457 """Return a string of printable ASCII characters, suitable for
458 passing into init_from_string."""
460 class IDirnodeURI(Interface):
461 """I am a URI which represents a dirnode."""
463 class IFileURI(Interface):
464 """I am a URI which represents a filenode."""
466 """Return the length (in bytes) of the file that I represent."""
468 class IImmutableFileURI(IFileURI):
471 class IMutableFileURI(Interface):
472 """I am a URI which represents a mutable filenode."""
474 class IDirectoryURI(Interface):
477 class IReadonlyDirectoryURI(Interface):
480 class CapConstraintError(Exception):
481 """A constraint on a cap was violated."""
483 class MustBeDeepImmutableError(CapConstraintError):
484 """Mutable children cannot be added to an immutable directory.
485 Also, caps obtained from an immutable directory can trigger this error
486 if they are later found to refer to a mutable object and then used."""
488 class MustBeReadonlyError(CapConstraintError):
489 """Known write caps cannot be specified in a ro_uri field. Also,
490 caps obtained from a ro_uri field can trigger this error if they
491 are later found to be write caps and then used."""
493 class MustNotBeUnknownRWError(CapConstraintError):
494 """Cannot add an unknown child cap specified in a rw_uri field."""
496 # The hierarchy looks like this:
503 class IFilesystemNode(Interface):
505 """Return the strongest 'cap instance' associated with this node.
506 (writecap for writeable-mutable files/directories, readcap for
507 immutable or readonly-mutable files/directories). To convert this
508 into a string, call .to_string() on the result."""
511 """Return a readonly cap instance for this node. For immutable or
512 readonly nodes, get_cap() and get_readcap() return the same thing."""
514 def get_repair_cap():
515 """Return an IURI instance that can be used to repair the file, or
516 None if this node cannot be repaired (either because it is not
517 distributed, like a LIT file, or because the node does not represent
518 sufficient authority to create a repair-cap, like a read-only RSA
519 mutable file node [which cannot create the correct write-enablers]).
522 def get_verify_cap():
523 """Return an IVerifierURI instance that represents the
524 'verifiy/refresh capability' for this node. The holder of this
525 capability will be able to renew the lease for this node, protecting
526 it from garbage-collection. They will also be able to ask a server if
527 it holds a share for the file or directory.
531 """Return the URI string corresponding to the strongest cap associated
532 with this node. If this node is read-only, the URI will only offer
533 read-only access. If this node is read-write, the URI will offer
536 If you have read-write access to a node and wish to share merely
537 read-only access with others, use get_readonly_uri().
540 def get_write_uri(n):
541 """Return the URI string that can be used by others to get write
542 access to this node, if it is writeable. If this is a read-only node,
545 def get_readonly_uri():
546 """Return the URI string that can be used by others to get read-only
547 access to this node. The result is a read-only URI, regardless of
548 whether this node is read-only or read-write.
550 If you have merely read-only access to this node, get_readonly_uri()
551 will return the same thing as get_uri().
554 def get_storage_index():
555 """Return a string with the (binary) storage index in use on this
556 download. This may be None if there is no storage index (i.e. LIT
557 files and directories)."""
560 """Return True if this reference provides mutable access to the given
561 file or directory (i.e. if you can modify it), or False if not. Note
562 that even if this reference is read-only, someone else may hold a
563 read-write reference to it."""
566 """Return True if this file or directory is mutable (by *somebody*,
567 not necessarily you), False if it is is immutable. Note that a file
568 might be mutable overall, but your reference to it might be
569 read-only. On the other hand, all references to an immutable file
570 will be read-only; there are no read-write references to an immutable
575 """Return True if this is an unknown node."""
577 def is_allowed_in_immutable_directory():
578 """Return True if this node is allowed as a child of a deep-immutable
579 directory. This is true if either the node is of a known-immutable type,
580 or it is unknown and read-only.
584 """Raise any error associated with this node."""
587 """Return the length (in bytes) of the data this node represents. For
588 directory nodes, I return the size of the backing store. I return
589 synchronously and do not consult the network, so for mutable objects,
590 I will return the most recently observed size for the object, or None
591 if I don't remember a size. Use get_current_size, which returns a
592 Deferred, if you want more up-to-date information."""
594 def get_current_size():
595 """I return a Deferred that fires with the length (in bytes) of the
596 data this node represents.
599 class IFileNode(IFilesystemNode):
600 """I am a node which represents a file: a sequence of bytes. I am not a
601 container, like IDirectoryNode."""
603 class IImmutableFileNode(IFileNode):
604 def read(consumer, offset=0, size=None):
605 """Download a portion (possibly all) of the file's contents, making
606 them available to the given IConsumer. Return a Deferred that fires
607 (with the consumer) when the consumer is unregistered (either because
608 the last byte has been given to it, or because the consumer threw an
609 exception during write(), possibly because it no longer wants to
610 receive data). The portion downloaded will start at 'offset' and
611 contain 'size' bytes (or the remainder of the file if size==None).
613 The consumer will be used in non-streaming mode: an IPullProducer
614 will be attached to it.
616 The consumer will not receive data right away: several network trips
617 must occur first. The order of events will be::
619 consumer.registerProducer(p, streaming)
620 (if streaming == False)::
621 consumer does p.resumeProducing()
623 consumer does p.resumeProducing()
624 consumer.write(data).. (repeat until all data is written)
625 consumer.unregisterProducer()
626 deferred.callback(consumer)
628 If a download error occurs, or an exception is raised by
629 consumer.registerProducer() or consumer.write(), I will call
630 consumer.unregisterProducer() and then deliver the exception via
631 deferred.errback(). To cancel the download, the consumer should call
632 p.stopProducing(), which will result in an exception being delivered
633 via deferred.errback().
635 See src/allmydata/util/consumer.py for an example of a simple
636 download-to-memory consumer.
639 class IMutableFileNode(IFileNode):
640 """I provide access to a 'mutable file', which retains its identity
641 regardless of what contents are put in it.
643 The consistency-vs-availability problem means that there might be
644 multiple versions of a file present in the grid, some of which might be
645 unrecoverable (i.e. have fewer than 'k' shares). These versions are
646 loosely ordered: each has a sequence number and a hash, and any version
647 with seqnum=N was uploaded by a node which has seen at least one version
650 The 'servermap' (an instance of IMutableFileServerMap) is used to
651 describe the versions that are known to be present in the grid, and which
652 servers are hosting their shares. It is used to represent the 'state of
653 the world', and is used for this purpose by my test-and-set operations.
654 Downloading the contents of the mutable file will also return a
655 servermap. Uploading a new version into the mutable file requires a
656 servermap as input, and the semantics of the replace operation is
657 'replace the file with my new version if it looks like nobody else has
658 changed the file since my previous download'. Because the file is
659 distributed, this is not a perfect test-and-set operation, but it will do
660 its best. If the replace process sees evidence of a simultaneous write,
661 it will signal an UncoordinatedWriteError, so that the caller can take
665 Most readers will want to use the 'best' current version of the file, and
666 should use my 'download_best_version()' method.
668 To unconditionally replace the file, callers should use overwrite(). This
669 is the mode that user-visible mutable files will probably use.
671 To apply some delta to the file, call modify() with a callable modifier
672 function that can apply the modification that you want to make. This is
673 the mode that dirnodes will use, since most directory modification
674 operations can be expressed in terms of deltas to the directory state.
677 Three methods are available for users who need to perform more complex
678 operations. The first is get_servermap(), which returns an up-to-date
679 servermap using a specified mode. The second is download_version(), which
680 downloads a specific version (not necessarily the 'best' one). The third
681 is 'upload', which accepts new contents and a servermap (which must have
682 been updated with MODE_WRITE). The upload method will attempt to apply
683 the new contents as long as no other node has modified the file since the
684 servermap was updated. This might be useful to a caller who wants to
685 merge multiple versions into a single new one.
687 Note that each time the servermap is updated, a specific 'mode' is used,
688 which determines how many peers are queried. To use a servermap for my
689 replace() method, that servermap must have been updated in MODE_WRITE.
690 These modes are defined in allmydata.mutable.common, and consist of
691 MODE_READ, MODE_WRITE, MODE_ANYTHING, and MODE_CHECK. Please look in
692 allmydata/mutable/servermap.py for details about the differences.
694 Mutable files are currently limited in size (about 3.5MB max) and can
695 only be retrieved and updated all-at-once, as a single big string. Future
696 versions of our mutable files will remove this restriction.
699 def download_best_version():
700 """Download the 'best' available version of the file, meaning one of
701 the recoverable versions with the highest sequence number. If no
702 uncoordinated writes have occurred, and if enough shares are
703 available, then this will be the most recent version that has been
706 I update an internal servermap with MODE_READ, determine which
707 version of the file is indicated by
708 servermap.best_recoverable_version(), and return a Deferred that
709 fires with its contents. If no version is recoverable, the Deferred
710 will errback with UnrecoverableFileError.
713 def get_size_of_best_version():
714 """Find the size of the version that would be downloaded with
715 download_best_version(), without actually downloading the whole file.
717 I return a Deferred that fires with an integer.
720 def overwrite(new_contents):
721 """Unconditionally replace the contents of the mutable file with new
722 ones. This simply chains get_servermap(MODE_WRITE) and upload(). This
723 is only appropriate to use when the new contents of the file are
724 completely unrelated to the old ones, and you do not care about other
727 I return a Deferred that fires (with a PublishStatus object) when the
728 update has completed.
731 def modify(modifier_cb):
732 """Modify the contents of the file, by downloading the current
733 version, applying the modifier function (or bound method), then
734 uploading the new version. I return a Deferred that fires (with a
735 PublishStatus object) when the update is complete.
737 The modifier callable will be given three arguments: a string (with
738 the old contents), a 'first_time' boolean, and a servermap. As with
739 download_best_version(), the old contents will be from the best
740 recoverable version, but the modifier can use the servermap to make
741 other decisions (such as refusing to apply the delta if there are
742 multiple parallel versions, or if there is evidence of a newer
743 unrecoverable version). 'first_time' will be True the first time the
744 modifier is called, and False on any subsequent calls.
746 The callable should return a string with the new contents. The
747 callable must be prepared to be called multiple times, and must
748 examine the input string to see if the change that it wants to make
749 is already present in the old version. If it does not need to make
750 any changes, it can either return None, or return its input string.
752 If the modifier raises an exception, it will be returned in the
757 def get_servermap(mode):
758 """Return a Deferred that fires with an IMutableFileServerMap
759 instance, updated using the given mode.
762 def download_version(servermap, version):
763 """Download a specific version of the file, using the servermap
764 as a guide to where the shares are located.
766 I return a Deferred that fires with the requested contents, or
767 errbacks with UnrecoverableFileError. Note that a servermap which was
768 updated with MODE_ANYTHING or MODE_READ may not know about shares for
769 all versions (those modes stop querying servers as soon as they can
770 fulfil their goals), so you may want to use MODE_CHECK (which checks
771 everything) to get increased visibility.
774 def upload(new_contents, servermap):
775 """Replace the contents of the file with new ones. This requires a
776 servermap that was previously updated with MODE_WRITE.
778 I attempt to provide test-and-set semantics, in that I will avoid
779 modifying any share that is different than the version I saw in the
780 servermap. However, if another node is writing to the file at the
781 same time as me, I may manage to update some shares while they update
782 others. If I see any evidence of this, I will signal
783 UncoordinatedWriteError, and the file will be left in an inconsistent
784 state (possibly the version you provided, possibly the old version,
785 possibly somebody else's version, and possibly a mix of shares from
788 The recommended response to UncoordinatedWriteError is to either
789 return it to the caller (since they failed to coordinate their
790 writes), or to attempt some sort of recovery. It may be sufficient to
791 wait a random interval (with exponential backoff) and repeat your
792 operation. If I do not signal UncoordinatedWriteError, then I was
793 able to write the new version without incident.
795 I return a Deferred that fires (with a PublishStatus object) when the
796 publish has completed. I will update the servermap in-place with the
797 location of all new shares.
801 """Return this filenode's writekey, or None if the node does not have
802 write-capability. This may be used to assist with data structures
803 that need to make certain data available only to writers, such as the
804 read-write child caps in dirnodes. The recommended process is to have
805 reader-visible data be submitted to the filenode in the clear (where
806 it will be encrypted by the filenode using the readkey), but encrypt
807 writer-visible data using this writekey.
810 class NotEnoughSharesError(Exception):
811 """Download was unable to get enough shares"""
813 class NoSharesError(Exception):
814 """Download was unable to get any shares at all."""
816 class UploadUnhappinessError(Exception):
817 """Upload was unable to satisfy 'servers_of_happiness'"""
819 class UnableToFetchCriticalDownloadDataError(Exception):
820 """I was unable to fetch some piece of critical data which is supposed to
821 be identically present in all shares."""
823 class NoServersError(Exception):
824 """Upload wasn't given any servers to work with, usually indicating a
825 network or Introducer problem."""
827 class ExistingChildError(Exception):
828 """A directory node was asked to add or replace a child that already
829 exists, and overwrite= was set to False."""
831 class NoSuchChildError(Exception):
832 """A directory node was asked to fetch a child which does not exist."""
834 class ChildOfWrongTypeError(Exception):
835 """An operation was attempted on a child of the wrong type (file or directory)."""
837 class IDirectoryNode(IFilesystemNode):
838 """I represent a filesystem node that is a container, with a
839 name-to-child mapping, holding the tahoe equivalent of a directory. All
840 child names are unicode strings, and all children are some sort of
841 IFilesystemNode (a file, subdirectory, or unknown node).
846 The dirnode ('1') URI returned by this method can be used in
847 set_uri() on a different directory ('2') to 'mount' a reference to
848 this directory ('1') under the other ('2'). This URI is just a
849 string, so it can be passed around through email or other out-of-band
853 def get_readonly_uri():
855 The dirnode ('1') URI returned by this method can be used in
856 set_uri() on a different directory ('2') to 'mount' a reference to
857 this directory ('1') under the other ('2'). This URI is just a
858 string, so it can be passed around through email or other out-of-band
863 """I return a Deferred that fires with a dictionary mapping child
864 name (a unicode string) to (node, metadata_dict) tuples, in which
865 'node' is an IFilesystemNode and 'metadata_dict' is a dictionary of
869 """I return a Deferred that fires with a boolean, True if there
870 exists a child of the given name, False if not. The child name must
871 be a unicode string."""
874 """I return a Deferred that fires with a specific named child node,
875 which is an IFilesystemNode. The child name must be a unicode string.
876 I raise NoSuchChildError if I do not have a child by that name."""
878 def get_metadata_for(name):
879 """I return a Deferred that fires with the metadata dictionary for
880 a specific named child node. The child name must be a unicode string.
881 This metadata is stored in the *edge*, not in the child, so it is
882 attached to the parent dirnode rather than the child node.
883 I raise NoSuchChildError if I do not have a child by that name."""
885 def set_metadata_for(name, metadata):
886 """I replace any existing metadata for the named child with the new
887 metadata. The child name must be a unicode string. This metadata is
888 stored in the *edge*, not in the child, so it is attached to the
889 parent dirnode rather than the child node. I return a Deferred
890 (that fires with this dirnode) when the operation is complete.
891 I raise NoSuchChildError if I do not have a child by that name."""
893 def get_child_at_path(path):
894 """Transform a child path into an IFilesystemNode.
896 I perform a recursive series of 'get' operations to find the named
897 descendant node. I return a Deferred that fires with the node, or
898 errbacks with NoSuchChildError if the node could not be found.
900 The path can be either a single string (slash-separated) or a list of
901 path-name elements. All elements must be unicode strings.
904 def get_child_and_metadata_at_path(path):
905 """Transform a child path into an IFilesystemNode and metadata.
907 I am like get_child_at_path(), but my Deferred fires with a tuple of
908 (node, metadata). The metadata comes from the last edge. If the path
909 is empty, the metadata will be an empty dictionary.
912 def set_uri(name, writecap, readcap=None, metadata=None, overwrite=True):
913 """I add a child (by writecap+readcap) at the specific name. I return
914 a Deferred that fires when the operation finishes. If overwrite= is
915 True, I will replace any existing child of the same name, otherwise
916 an existing child will cause me to return ExistingChildError. The
917 child name must be a unicode string.
919 The child caps could be for a file, or for a directory. If you have
920 both the writecap and readcap, you should provide both arguments.
921 If you have only one cap and don't know whether it is read-only,
922 provide it as the writecap argument and leave the readcap as None.
923 If you have only one cap that is known to be read-only, provide it
924 as the readcap argument and leave the writecap as None.
925 The filecaps are typically obtained from an IFilesystemNode with
926 get_uri() and get_readonly_uri().
928 If metadata= is provided, I will use it as the metadata for the named
929 edge. This will replace any existing metadata. If metadata= is left
930 as the default value of None, I will set ['mtime'] to the current
931 time, and I will set ['ctime'] to the current time if there was not
932 already a child by this name present. This roughly matches the
933 ctime/mtime semantics of traditional filesystems. See the
934 "About the metadata" section of webapi.txt for futher information.
936 If this directory node is read-only, the Deferred will errback with a
937 NotWriteableError."""
939 def set_children(entries, overwrite=True):
940 """Add multiple children (by writecap+readcap) to a directory node.
941 Takes a dictionary, with childname as keys and (writecap, readcap)
942 tuples (or (writecap, readcap, metadata) triples) as values. Returns
943 a Deferred that fires (with this dirnode) when the operation
944 finishes. This is equivalent to calling set_uri() multiple times, but
945 is much more efficient. All child names must be unicode strings.
948 def set_node(name, child, metadata=None, overwrite=True):
949 """I add a child at the specific name. I return a Deferred that fires
950 when the operation finishes. This Deferred will fire with the child
951 node that was just added. I will replace any existing child of the
952 same name. The child name must be a unicode string. The 'child'
953 instance must be an instance providing IFilesystemNode.
955 If metadata= is provided, I will use it as the metadata for the named
956 edge. This will replace any existing metadata. If metadata= is left
957 as the default value of None, I will set ['mtime'] to the current
958 time, and I will set ['ctime'] to the current time if there was not
959 already a child by this name present. This roughly matches the
960 ctime/mtime semantics of traditional filesystems. See the
961 "About the metadata" section of webapi.txt for futher information.
963 If this directory node is read-only, the Deferred will errback with a
964 NotWriteableError."""
966 def set_nodes(entries, overwrite=True):
967 """Add multiple children to a directory node. Takes a dict mapping
968 unicode childname to (child_node, metdata) tuples. If metdata=None,
969 the original metadata is left unmodified. Returns a Deferred that
970 fires (with this dirnode) when the operation finishes. This is
971 equivalent to calling set_node() multiple times, but is much more
974 def add_file(name, uploadable, metadata=None, overwrite=True):
975 """I upload a file (using the given IUploadable), then attach the
976 resulting ImmutableFileNode to the directory at the given name. I set
977 metadata the same way as set_uri and set_node. The child name must be
980 I return a Deferred that fires (with the IFileNode of the uploaded
981 file) when the operation completes."""
983 def delete(name, must_exist=True, must_be_directory=False, must_be_file=False):
984 """I remove the child at the specific name. I return a Deferred that
985 fires when the operation finishes. The child name must be a unicode
986 string. If must_exist is True and I do not have a child by that name,
987 I raise NoSuchChildError. If must_be_directory is True and the child
988 is a file, or if must_be_file is True and the child is a directory,
989 I raise ChildOfWrongTypeError."""
991 def create_subdirectory(name, initial_children={}, overwrite=True, metadata=None):
992 """I create and attach a directory at the given name. The new
993 directory can be empty, or it can be populated with children
994 according to 'initial_children', which takes a dictionary in the same
995 format as set_nodes (i.e. mapping unicode child name to (childnode,
996 metadata) tuples). The child name must be a unicode string. I return
997 a Deferred that fires (with the new directory node) when the
998 operation finishes."""
1000 def move_child_to(current_child_name, new_parent, new_child_name=None,
1002 """I take one of my children and move them to a new parent. The child
1003 is referenced by name. On the new parent, the child will live under
1004 'new_child_name', which defaults to 'current_child_name'. TODO: what
1005 should we do about metadata? I return a Deferred that fires when the
1006 operation finishes. The child name must be a unicode string. I raise
1007 NoSuchChildError if I do not have a child by that name."""
1009 def build_manifest():
1010 """I generate a table of everything reachable from this directory.
1011 I also compute deep-stats as described below.
1013 I return a Monitor. The Monitor's results will be a dictionary with
1016 res['manifest']: a list of (path, cap) tuples for all nodes
1017 (directories and files) reachable from this one.
1018 'path' will be a tuple of unicode strings. The
1019 origin dirnode will be represented by an empty path
1021 res['verifycaps']: a list of (printable) verifycap strings, one for
1022 each reachable non-LIT node. This is a set:
1023 it will contain no duplicates.
1024 res['storage-index']: a list of (base32) storage index strings,
1025 one for each reachable non-LIT node. This is
1026 a set: it will contain no duplicates.
1027 res['stats']: a dictionary, the same that is generated by
1028 start_deep_stats() below.
1030 The Monitor will also have an .origin_si attribute with the (binary)
1031 storage index of the starting point.
1034 def start_deep_stats():
1035 """Return a Monitor, examining all nodes (directories and files)
1036 reachable from this one. The Monitor's results will be a dictionary
1037 with the following keys::
1039 count-immutable-files: count of how many CHK files are in the set
1040 count-mutable-files: same, for mutable files (does not include
1042 count-literal-files: same, for LIT files
1043 count-files: sum of the above three
1045 count-directories: count of directories
1047 size-immutable-files: total bytes for all CHK files in the set
1048 size-mutable-files (TODO): same, for current version of all mutable
1049 files, does not include directories
1050 size-literal-files: same, for LIT files
1051 size-directories: size of mutable files used by directories
1053 largest-directory: number of bytes in the largest directory
1054 largest-directory-children: number of children in the largest
1056 largest-immutable-file: number of bytes in the largest CHK file
1058 size-mutable-files is not yet implemented, because it would involve
1059 even more queries than deep_stats does.
1061 The Monitor will also have an .origin_si attribute with the (binary)
1062 storage index of the starting point.
1064 This operation will visit every directory node underneath this one,
1065 and can take a long time to run. On a typical workstation with good
1066 bandwidth, this can examine roughly 15 directories per second (and
1067 takes several minutes of 100% CPU for ~1700 directories).
1070 class ICodecEncoder(Interface):
1071 def set_params(data_size, required_shares, max_shares):
1072 """Set up the parameters of this encoder.
1074 This prepares the encoder to perform an operation that converts a
1075 single block of data into a number of shares, such that a future
1076 ICodecDecoder can use a subset of these shares to recover the
1077 original data. This operation is invoked by calling encode(). Once
1078 the encoding parameters are set up, the encode operation can be
1079 invoked multiple times.
1081 set_params() prepares the encoder to accept blocks of input data that
1082 are exactly 'data_size' bytes in length. The encoder will be prepared
1083 to produce 'max_shares' shares for each encode() operation (although
1084 see the 'desired_share_ids' to use less CPU). The encoding math will
1085 be chosen such that the decoder can get by with as few as
1086 'required_shares' of these shares and still reproduce the original
1087 data. For example, set_params(1000, 5, 5) offers no redundancy at
1088 all, whereas set_params(1000, 1, 10) provides 10x redundancy.
1090 Numerical Restrictions: 'data_size' is required to be an integral
1091 multiple of 'required_shares'. In general, the caller should choose
1092 required_shares and max_shares based upon their reliability
1093 requirements and the number of peers available (the total storage
1094 space used is roughly equal to max_shares*data_size/required_shares),
1095 then choose data_size to achieve the memory footprint desired (larger
1096 data_size means more efficient operation, smaller data_size means
1097 smaller memory footprint).
1099 In addition, 'max_shares' must be equal to or greater than
1100 'required_shares'. Of course, setting them to be equal causes
1101 encode() to degenerate into a particularly slow form of the 'split'
1104 See encode() for more details about how these parameters are used.
1106 set_params() must be called before any other ICodecEncoder methods
1111 """Return the 3-tuple of data_size, required_shares, max_shares"""
1113 def get_encoder_type():
1114 """Return a short string that describes the type of this encoder.
1116 There is required to be a global table of encoder classes. This method
1117 returns an index into this table; the value at this index is an
1118 encoder class, and this encoder is an instance of that class.
1121 def get_block_size():
1122 """Return the length of the shares that encode() will produce.
1125 def encode_proposal(data, desired_share_ids=None):
1126 """Encode some data.
1128 'data' must be a string (or other buffer object), and len(data) must
1129 be equal to the 'data_size' value passed earlier to set_params().
1131 This will return a Deferred that will fire with two lists. The first
1132 is a list of shares, each of which is a string (or other buffer
1133 object) such that len(share) is the same as what get_share_size()
1134 returned earlier. The second is a list of shareids, in which each is
1135 an integer. The lengths of the two lists will always be equal to each
1136 other. The user should take care to keep each share closely
1137 associated with its shareid, as one is useless without the other.
1139 The length of this output list will normally be the same as the value
1140 provided to the 'max_shares' parameter of set_params(). This may be
1141 different if 'desired_share_ids' is provided.
1143 'desired_share_ids', if provided, is required to be a sequence of
1144 ints, each of which is required to be >= 0 and < max_shares. If not
1145 provided, encode() will produce 'max_shares' shares, as if
1146 'desired_share_ids' were set to range(max_shares). You might use this
1147 if you initially thought you were going to use 10 peers, started
1148 encoding, and then two of the peers dropped out: you could use
1149 desired_share_ids= to skip the work (both memory and CPU) of
1150 producing shares for the peers which are no longer available.
1154 def encode(inshares, desired_share_ids=None):
1155 """Encode some data. This may be called multiple times. Each call is
1158 inshares is a sequence of length required_shares, containing buffers
1159 (i.e. strings), where each buffer contains the next contiguous
1160 non-overlapping segment of the input data. Each buffer is required to
1161 be the same length, and the sum of the lengths of the buffers is
1162 required to be exactly the data_size promised by set_params(). (This
1163 implies that the data has to be padded before being passed to
1164 encode(), unless of course it already happens to be an even multiple
1165 of required_shares in length.)
1167 ALSO: the requirement to break up your data into 'required_shares'
1168 chunks before calling encode() feels a bit surprising, at least from
1169 the point of view of a user who doesn't know how FEC works. It feels
1170 like an implementation detail that has leaked outside the
1171 abstraction barrier. Can you imagine a use case in which the data to
1172 be encoded might already be available in pre-segmented chunks, such
1173 that it is faster or less work to make encode() take a list rather
1174 than splitting a single string?
1176 ALSO ALSO: I think 'inshares' is a misleading term, since encode()
1177 is supposed to *produce* shares, so what it *accepts* should be
1178 something other than shares. Other places in this interface use the
1179 word 'data' for that-which-is-not-shares.. maybe we should use that
1182 'desired_share_ids', if provided, is required to be a sequence of
1183 ints, each of which is required to be >= 0 and < max_shares. If not
1184 provided, encode() will produce 'max_shares' shares, as if
1185 'desired_share_ids' were set to range(max_shares). You might use this
1186 if you initially thought you were going to use 10 peers, started
1187 encoding, and then two of the peers dropped out: you could use
1188 desired_share_ids= to skip the work (both memory and CPU) of
1189 producing shares for the peers which are no longer available.
1191 For each call, encode() will return a Deferred that fires with two
1192 lists, one containing shares and the other containing the shareids.
1193 The get_share_size() method can be used to determine the length of
1194 the share strings returned by encode(). Each shareid is a small
1195 integer, exactly as passed into 'desired_share_ids' (or
1196 range(max_shares), if desired_share_ids was not provided).
1198 The shares and their corresponding shareids are required to be kept
1199 together during storage and retrieval. Specifically, the share data is
1200 useless by itself: the decoder needs to be told which share is which
1201 by providing it with both the shareid and the actual share data.
1203 This function will allocate an amount of memory roughly equal to::
1205 (max_shares - required_shares) * get_share_size()
1207 When combined with the memory that the caller must allocate to
1208 provide the input data, this leads to a memory footprint roughly
1209 equal to the size of the resulting encoded shares (i.e. the expansion
1210 factor times the size of the input segment).
1215 # returning a list of (shareidN,shareN) tuples instead of a pair of
1216 # lists (shareids..,shares..). Brian thought the tuples would
1217 # encourage users to keep the share and shareid together throughout
1218 # later processing, Zooko pointed out that the code to iterate
1219 # through two lists is not really more complicated than using a list
1220 # of tuples and there's also a performance improvement
1222 # having 'data_size' not required to be an integral multiple of
1223 # 'required_shares'. Doing this would require encode() to perform
1224 # padding internally, and we'd prefer to have any padding be done
1225 # explicitly by the caller. Yes, it is an abstraction leak, but
1226 # hopefully not an onerous one.
1229 class ICodecDecoder(Interface):
1230 def set_params(data_size, required_shares, max_shares):
1231 """Set the params. They have to be exactly the same ones that were
1232 used for encoding."""
1234 def get_needed_shares():
1235 """Return the number of shares needed to reconstruct the data.
1236 set_params() is required to be called before this."""
1238 def decode(some_shares, their_shareids):
1239 """Decode a partial list of shares into data.
1241 'some_shares' is required to be a sequence of buffers of sharedata, a
1242 subset of the shares returned by ICodecEncode.encode(). Each share is
1243 required to be of the same length. The i'th element of their_shareids
1244 is required to be the shareid of the i'th buffer in some_shares.
1246 This returns a Deferred which fires with a sequence of buffers. This
1247 sequence will contain all of the segments of the original data, in
1248 order. The sum of the lengths of all of the buffers will be the
1249 'data_size' value passed into the original ICodecEncode.set_params()
1250 call. To get back the single original input block of data, use
1251 ''.join(output_buffers), or you may wish to simply write them in
1252 order to an output file.
1254 Note that some of the elements in the result sequence may be
1255 references to the elements of the some_shares input sequence. In
1256 particular, this means that if those share objects are mutable (e.g.
1257 arrays) and if they are changed, then both the input (the
1258 'some_shares' parameter) and the output (the value given when the
1259 deferred is triggered) will change.
1261 The length of 'some_shares' is required to be exactly the value of
1262 'required_shares' passed into the original ICodecEncode.set_params()
1266 class IEncoder(Interface):
1267 """I take an object that provides IEncryptedUploadable, which provides
1268 encrypted data, and a list of shareholders. I then encode, hash, and
1269 deliver shares to those shareholders. I will compute all the necessary
1270 Merkle hash trees that are necessary to validate the crypttext that
1271 eventually comes back from the shareholders. I provide the URI Extension
1272 Block Hash, and the encoding parameters, both of which must be included
1275 I do not choose shareholders, that is left to the IUploader. I must be
1276 given a dict of RemoteReferences to storage buckets that are ready and
1277 willing to receive data.
1281 """Specify the number of bytes that will be encoded. This must be
1282 peformed before get_serialized_params() can be called.
1284 def set_params(params):
1285 """Override the default encoding parameters. 'params' is a tuple of
1286 (k,d,n), where 'k' is the number of required shares, 'd' is the
1287 servers_of_happiness, and 'n' is the total number of shares that will
1290 Encoding parameters can be set in three ways. 1: The Encoder class
1291 provides defaults (3/7/10). 2: the Encoder can be constructed with
1292 an 'options' dictionary, in which the
1293 needed_and_happy_and_total_shares' key can be a (k,d,n) tuple. 3:
1294 set_params((k,d,n)) can be called.
1296 If you intend to use set_params(), you must call it before
1297 get_share_size or get_param are called.
1300 def set_encrypted_uploadable(u):
1301 """Provide a source of encrypted upload data. 'u' must implement
1302 IEncryptedUploadable.
1304 When this is called, the IEncryptedUploadable will be queried for its
1305 length and the storage_index that should be used.
1307 This returns a Deferred that fires with this Encoder instance.
1309 This must be performed before start() can be called.
1312 def get_param(name):
1313 """Return an encoding parameter, by name.
1315 'storage_index': return a string with the (16-byte truncated SHA-256
1316 hash) storage index to which these shares should be
1319 'share_counts': return a tuple describing how many shares are used:
1320 (needed_shares, servers_of_happiness, total_shares)
1322 'num_segments': return an int with the number of segments that
1325 'segment_size': return an int with the size of each segment.
1327 'block_size': return the size of the individual blocks that will
1328 be delivered to a shareholder's put_block() method. By
1329 knowing this, the shareholder will be able to keep all
1330 blocks in a single file and still provide random access
1331 when reading them. # TODO: can we avoid exposing this?
1333 'share_size': an int with the size of the data that will be stored
1334 on each shareholder. This is aggregate amount of data
1335 that will be sent to the shareholder, summed over all
1336 the put_block() calls I will ever make. It is useful to
1337 determine this size before asking potential
1338 shareholders whether they will grant a lease or not,
1339 since their answers will depend upon how much space we
1340 need. TODO: this might also include some amount of
1341 overhead, like the size of all the hashes. We need to
1342 decide whether this is useful or not.
1344 'serialized_params': a string with a concise description of the
1345 codec name and its parameters. This may be passed
1346 into the IUploadable to let it make sure that
1347 the same file encoded with different parameters
1348 will result in different storage indexes.
1350 Once this is called, set_size() and set_params() may not be called.
1353 def set_shareholders(shareholders, servermap):
1354 """Tell the encoder where to put the encoded shares. 'shareholders'
1355 must be a dictionary that maps share number (an integer ranging from
1356 0 to n-1) to an instance that provides IStorageBucketWriter.
1357 'servermap' is a dictionary that maps share number (as defined above)
1358 to a set of peerids. This must be performed before start() can be
1362 """Begin the encode/upload process. This involves reading encrypted
1363 data from the IEncryptedUploadable, encoding it, uploading the shares
1364 to the shareholders, then sending the hash trees.
1366 set_encrypted_uploadable() and set_shareholders() must be called
1367 before this can be invoked.
1369 This returns a Deferred that fires with a verify cap when the upload
1370 process is complete. The verifycap, plus the encryption key, is
1371 sufficient to construct the read cap.
1374 class IDecoder(Interface):
1375 """I take a list of shareholders and some setup information, then
1376 download, validate, decode, and decrypt data from them, writing the
1377 results to an output file.
1379 I do not locate the shareholders, that is left to the IDownloader. I must
1380 be given a dict of RemoteReferences to storage buckets that are ready to
1385 """I take a file-like object (providing write and close) to which all
1386 the plaintext data will be written.
1388 TODO: producer/consumer . Maybe write() should return a Deferred that
1389 indicates when it will accept more data? But probably having the
1390 IDecoder be a producer is easier to glue to IConsumer pieces.
1393 def set_shareholders(shareholders):
1394 """I take a dictionary that maps share identifiers (small integers)
1395 to RemoteReferences that provide RIBucketReader. This must be called
1399 """I start the download. This process involves retrieving data and
1400 hash chains from the shareholders, using the hashes to validate the
1401 data, decoding the shares into segments, decrypting the segments,
1402 then writing the resulting plaintext to the output file.
1404 I return a Deferred that will fire (with self) when the download is
1408 class IDownloadTarget(Interface):
1409 # Note that if the IDownloadTarget is also an IConsumer, the downloader
1410 # will register itself as a producer. This allows the target to invoke
1411 # downloader.pauseProducing, resumeProducing, and stopProducing.
1413 """Called before any calls to write() or close(). If an error
1414 occurs before any data is available, fail() may be called without
1415 a previous call to open().
1417 'size' is the length of the file being downloaded, in bytes."""
1420 """Output some data to the target."""
1422 """Inform the target that there is no more data to be written."""
1424 """fail() is called to indicate that the download has failed. 'why'
1425 is a Failure object indicating what went wrong. No further methods
1426 will be invoked on the IDownloadTarget after fail()."""
1427 def register_canceller(cb):
1428 """The CiphertextDownloader uses this to register a no-argument function
1429 that the target can call to cancel the download. Once this canceller
1430 is invoked, no further calls to write() or close() will be made."""
1432 """When the CiphertextDownloader is done, this finish() function will be
1433 called. Whatever it returns will be returned to the invoker of
1434 Downloader.download.
1436 # The following methods are just because that target might be a
1437 # repairer.DownUpConnector, and just because the current CHKUpload object
1438 # expects to find the storage index and encoding parameters in its
1440 def set_storageindex(storageindex):
1441 """ Set the storage index. """
1442 def set_encodingparams(encodingparams):
1443 """ Set the encoding parameters. """
1445 class IDownloader(Interface):
1446 def download(uri, target):
1447 """Perform a CHK download, sending the data to the given target.
1448 'target' must provide IDownloadTarget.
1450 Returns a Deferred that fires (with the results of target.finish)
1451 when the download is finished, or errbacks if something went wrong."""
1453 class IEncryptedUploadable(Interface):
1454 def set_upload_status(upload_status):
1455 """Provide an IUploadStatus object that should be filled with status
1456 information. The IEncryptedUploadable is responsible for setting
1457 key-determination progress ('chk'), size, storage_index, and
1458 ciphertext-fetch progress. It may delegate some of this
1459 responsibility to others, in particular to the IUploadable."""
1462 """This behaves just like IUploadable.get_size()."""
1464 def get_all_encoding_parameters():
1465 """Return a Deferred that fires with a tuple of
1466 (k,happy,n,segment_size). The segment_size will be used as-is, and
1467 must match the following constraints: it must be a multiple of k, and
1468 it shouldn't be unreasonably larger than the file size (if
1469 segment_size is larger than filesize, the difference must be stored
1472 This usually passes through to the IUploadable method of the same
1475 The encoder strictly obeys the values returned by this method. To
1476 make an upload use non-default encoding parameters, you must arrange
1477 to control the values that this method returns.
1480 def get_storage_index():
1481 """Return a Deferred that fires with a 16-byte storage index.
1484 def read_encrypted(length, hash_only):
1485 """This behaves just like IUploadable.read(), but returns crypttext
1486 instead of plaintext. If hash_only is True, then this discards the
1487 data (and returns an empty list); this improves efficiency when
1488 resuming an interrupted upload (where we need to compute the
1489 plaintext hashes, but don't need the redundant encrypted data)."""
1491 def get_plaintext_hashtree_leaves(first, last, num_segments):
1492 """OBSOLETE; Get the leaf nodes of a merkle hash tree over the
1493 plaintext segments, i.e. get the tagged hashes of the given segments.
1494 The segment size is expected to be generated by the
1495 IEncryptedUploadable before any plaintext is read or ciphertext
1496 produced, so that the segment hashes can be generated with only a
1499 This returns a Deferred which fires with a sequence of hashes, using:
1501 tuple(segment_hashes[first:last])
1503 'num_segments' is used to assert that the number of segments that the
1504 IEncryptedUploadable handled matches the number of segments that the
1505 encoder was expecting.
1507 This method must not be called until the final byte has been read
1508 from read_encrypted(). Once this method is called, read_encrypted()
1509 can never be called again.
1512 def get_plaintext_hash():
1513 """OBSOLETE; Get the hash of the whole plaintext.
1515 This returns a Deferred which fires with a tagged SHA-256 hash of the
1516 whole plaintext, obtained from hashutil.plaintext_hash(data).
1520 """Just like IUploadable.close()."""
1522 class IUploadable(Interface):
1523 def set_upload_status(upload_status):
1524 """Provide an IUploadStatus object that should be filled with status
1525 information. The IUploadable is responsible for setting
1526 key-determination progress ('chk')."""
1528 def set_default_encoding_parameters(params):
1529 """Set the default encoding parameters, which must be a dict mapping
1530 strings to ints. The meaningful keys are 'k', 'happy', 'n', and
1531 'max_segment_size'. These might have an influence on the final
1532 encoding parameters returned by get_all_encoding_parameters(), if the
1533 Uploadable doesn't have more specific preferences.
1535 This call is optional: if it is not used, the Uploadable will use
1536 some built-in defaults. If used, this method must be called before
1537 any other IUploadable methods to have any effect.
1541 """Return a Deferred that will fire with the length of the data to be
1542 uploaded, in bytes. This will be called before the data is actually
1543 used, to compute encoding parameters.
1546 def get_all_encoding_parameters():
1547 """Return a Deferred that fires with a tuple of
1548 (k,happy,n,segment_size). The segment_size will be used as-is, and
1549 must match the following constraints: it must be a multiple of k, and
1550 it shouldn't be unreasonably larger than the file size (if
1551 segment_size is larger than filesize, the difference must be stored
1554 The relative values of k and n allow some IUploadables to request
1555 better redundancy than others (in exchange for consuming more space
1558 Larger values of segment_size reduce hash overhead, while smaller
1559 values reduce memory footprint and cause data to be delivered in
1560 smaller pieces (which may provide a smoother and more predictable
1561 download experience).
1563 The encoder strictly obeys the values returned by this method. To
1564 make an upload use non-default encoding parameters, you must arrange
1565 to control the values that this method returns. One way to influence
1566 them may be to call set_encoding_parameters() before calling
1567 get_all_encoding_parameters().
1570 def get_encryption_key():
1571 """Return a Deferred that fires with a 16-byte AES key. This key will
1572 be used to encrypt the data. The key will also be hashed to derive
1575 Uploadables which want to achieve convergence should hash their file
1576 contents and the serialized_encoding_parameters to form the key
1577 (which of course requires a full pass over the data). Uploadables can
1578 use the upload.ConvergentUploadMixin class to achieve this
1581 Uploadables which do not care about convergence (or do not wish to
1582 make multiple passes over the data) can simply return a
1583 strongly-random 16 byte string.
1585 get_encryption_key() may be called multiple times: the IUploadable is
1586 required to return the same value each time.
1590 """Return a Deferred that fires with a list of strings (perhaps with
1591 only a single element) which, when concatenated together, contain the
1592 next 'length' bytes of data. If EOF is near, this may provide fewer
1593 than 'length' bytes. The total number of bytes provided by read()
1594 before it signals EOF must equal the size provided by get_size().
1596 If the data must be acquired through multiple internal read
1597 operations, returning a list instead of a single string may help to
1598 reduce string copies.
1600 'length' will typically be equal to (min(get_size(),1MB)/req_shares),
1601 so a 10kB file means length=3kB, 100kB file means length=30kB,
1602 and >=1MB file means length=300kB.
1604 This method provides for a single full pass through the data. Later
1605 use cases may desire multiple passes or access to only parts of the
1606 data (such as a mutable file making small edits-in-place). This API
1607 will be expanded once those use cases are better understood.
1611 """The upload is finished, and whatever filehandle was in use may be
1614 class IUploadResults(Interface):
1615 """I am returned by upload() methods. I contain a number of public
1616 attributes which can be read to determine the results of the upload. Some
1617 of these are functional, some are timing information. All of these may be
1620 .file_size : the size of the file, in bytes
1621 .uri : the CHK read-cap for the file
1622 .ciphertext_fetched : how many bytes were fetched by the helper
1623 .sharemap: dict mapping share identifier to set of serverids
1624 (binary strings). This indicates which servers were given
1625 which shares. For immutable files, the shareid is an
1626 integer (the share number, from 0 to N-1). For mutable
1627 files, it is a string of the form 'seq%d-%s-sh%d',
1628 containing the sequence number, the roothash, and the
1630 .servermap : dict mapping server peerid to a set of share numbers
1631 .timings : dict of timing information, mapping name to seconds (float)
1632 total : total upload time, start to finish
1633 storage_index : time to compute the storage index
1634 peer_selection : time to decide which peers will be used
1635 contacting_helper : initial helper query to upload/no-upload decision
1636 existence_check : helper pre-upload existence check
1637 helper_total : initial helper query to helper finished pushing
1638 cumulative_fetch : helper waiting for ciphertext requests
1639 total_fetch : helper start to last ciphertext response
1640 cumulative_encoding : just time spent in zfec
1641 cumulative_sending : just time spent waiting for storage servers
1642 hashes_and_close : last segment push to shareholder close
1643 total_encode_and_push : first encode to shareholder close
1647 class IDownloadResults(Interface):
1648 """I am created internally by download() methods. I contain a number of
1649 public attributes which contain details about the download process.::
1651 .file_size : the size of the file, in bytes
1652 .servers_used : set of server peerids that were used during download
1653 .server_problems : dict mapping server peerid to a problem string. Only
1654 servers that had problems (bad hashes, disconnects)
1656 .servermap : dict mapping server peerid to a set of share numbers. Only
1657 servers that had any shares are listed here.
1658 .timings : dict of timing information, mapping name to seconds (float)
1659 peer_selection : time to ask servers about shares
1660 servers_peer_selection : dict of peerid to DYHB-query time
1661 uri_extension : time to fetch a copy of the URI extension block
1662 hashtrees : time to fetch the hash trees
1663 segments : time to fetch, decode, and deliver segments
1664 cumulative_fetch : time spent waiting for storage servers
1665 cumulative_decode : just time spent in zfec
1666 cumulative_decrypt : just time spent in decryption
1667 total : total download time, start to finish
1668 fetch_per_server : dict of peerid to list of per-segment fetch times
1672 class IUploader(Interface):
1673 def upload(uploadable):
1674 """Upload the file. 'uploadable' must impement IUploadable. This
1675 returns a Deferred which fires with an IUploadResults instance, from
1676 which the URI of the file can be obtained as results.uri ."""
1678 def upload_ssk(write_capability, new_version, uploadable):
1679 """TODO: how should this work?"""
1681 class ICheckable(Interface):
1682 def check(monitor, verify=False, add_lease=False):
1683 """Check upon my health, optionally repairing any problems.
1685 This returns a Deferred that fires with an instance that provides
1686 ICheckResults, or None if the object is non-distributed (i.e. LIT
1689 The monitor will be checked periodically to see if the operation has
1690 been cancelled. If so, no new queries will be sent, and the Deferred
1691 will fire (with a OperationCancelledError) immediately.
1693 Filenodes and dirnodes (which provide IFilesystemNode) are also
1694 checkable. Instances that represent verifier-caps will be checkable
1695 but not downloadable. Some objects (like LIT files) do not actually
1696 live in the grid, and their checkers return None (non-distributed
1697 files are always healthy).
1699 If verify=False, a relatively lightweight check will be performed: I
1700 will ask all servers if they have a share for me, and I will believe
1701 whatever they say. If there are at least N distinct shares on the
1702 grid, my results will indicate r.is_healthy()==True. This requires a
1703 roundtrip to each server, but does not transfer very much data, so
1704 the network bandwidth is fairly low.
1706 If verify=True, a more resource-intensive check will be performed:
1707 every share will be downloaded, and the hashes will be validated on
1708 every bit. I will ignore any shares that failed their hash checks. If
1709 there are at least N distinct valid shares on the grid, my results
1710 will indicate r.is_healthy()==True. This requires N/k times as much
1711 download bandwidth (and server disk IO) as a regular download. If a
1712 storage server is holding a corrupt share, or is experiencing memory
1713 failures during retrieval, or is malicious or buggy, then
1714 verification will detect the problem, but checking will not.
1716 If add_lease=True, I will ensure that an up-to-date lease is present
1717 on each share. The lease secrets will be derived from by node secret
1718 (in BASEDIR/private/secret), so either I will add a new lease to the
1719 share, or I will merely renew the lease that I already had. In a
1720 future version of the storage-server protocol (once Accounting has
1721 been implemented), there may be additional options here to define the
1722 kind of lease that is obtained (which account number to claim, etc).
1724 TODO: any problems seen during checking will be reported to the
1725 health-manager.furl, a centralized object which is responsible for
1726 figuring out why files are unhealthy so corrective action can be
1730 def check_and_repair(monitor, verify=False, add_lease=False):
1731 """Like check(), but if the file/directory is not healthy, attempt to
1734 Any non-healthy result will cause an immediate repair operation, to
1735 generate and upload new shares. After repair, the file will be as
1736 healthy as we can make it. Details about what sort of repair is done
1737 will be put in the check-and-repair results. The Deferred will not
1738 fire until the repair is complete.
1740 This returns a Deferred which fires with an instance of
1741 ICheckAndRepairResults."""
1743 class IDeepCheckable(Interface):
1744 def start_deep_check(verify=False, add_lease=False):
1745 """Check upon the health of me and everything I can reach.
1747 This is a recursive form of check(), useable only on dirnodes.
1749 I return a Monitor, with results that are an IDeepCheckResults
1752 TODO: If any of the directories I traverse are unrecoverable, the
1753 Monitor will report failure. If any of the files I check upon are
1754 unrecoverable, those problems will be reported in the
1755 IDeepCheckResults as usual, and the Monitor will not report a
1759 def start_deep_check_and_repair(verify=False, add_lease=False):
1760 """Check upon the health of me and everything I can reach. Repair
1761 anything that isn't healthy.
1763 This is a recursive form of check_and_repair(), useable only on
1766 I return a Monitor, with results that are an
1767 IDeepCheckAndRepairResults object.
1769 TODO: If any of the directories I traverse are unrecoverable, the
1770 Monitor will report failure. If any of the files I check upon are
1771 unrecoverable, those problems will be reported in the
1772 IDeepCheckResults as usual, and the Monitor will not report a
1776 class ICheckResults(Interface):
1777 """I contain the detailed results of a check/verify operation.
1780 def get_storage_index():
1781 """Return a string with the (binary) storage index."""
1782 def get_storage_index_string():
1783 """Return a string with the (printable) abbreviated storage index."""
1785 """Return the (string) URI of the object that was checked."""
1788 """Return a boolean, True if the file/dir is fully healthy, False if
1789 it is damaged in any way. Non-distributed LIT files always return
1792 def is_recoverable():
1793 """Return a boolean, True if the file/dir can be recovered, False if
1794 not. Unrecoverable files are obviously unhealthy. Non-distributed LIT
1795 files always return True."""
1797 def needs_rebalancing():
1798 """Return a boolean, True if the file/dir's reliability could be
1799 improved by moving shares to new servers. Non-distributed LIT files
1800 always return False."""
1804 """Return a dictionary that describes the state of the file/dir. LIT
1805 files always return an empty dictionary. Normal files and directories
1806 return a dictionary with the following keys (note that these use
1807 binary strings rather than base32-encoded ones) (also note that for
1808 mutable files, these counts are for the 'best' version):
1810 count-shares-good: the number of distinct good shares that were found
1811 count-shares-needed: 'k', the number of shares required for recovery
1812 count-shares-expected: 'N', the number of total shares generated
1813 count-good-share-hosts: the number of distinct storage servers with
1814 good shares. If this number is less than
1815 count-shares-good, then some shares are
1816 doubled up, increasing the correlation of
1817 failures. This indicates that one or more
1818 shares should be moved to an otherwise unused
1819 server, if one is available.
1820 count-corrupt-shares: the number of shares with integrity failures
1821 list-corrupt-shares: a list of 'share locators', one for each share
1822 that was found to be corrupt. Each share
1823 locator is a list of (serverid, storage_index,
1825 count-incompatible-shares: the number of shares which are of a share
1826 format unknown to this checker
1827 list-incompatible-shares: a list of 'share locators', one for each
1828 share that was found to be of an unknown
1829 format. Each share locator is a list of
1830 (serverid, storage_index, sharenum).
1831 servers-responding: list of (binary) storage server identifiers,
1832 one for each server which responded to the share
1833 query (even if they said they didn't have
1834 shares, and even if they said they did have
1835 shares but then didn't send them when asked, or
1836 dropped the connection, or returned a Failure,
1837 and even if they said they did have shares and
1838 sent incorrect ones when asked)
1839 sharemap: dict mapping share identifier to list of serverids
1840 (binary strings). This indicates which servers are holding
1841 which shares. For immutable files, the shareid is an
1842 integer (the share number, from 0 to N-1). For mutable
1843 files, it is a string of the form 'seq%d-%s-sh%d',
1844 containing the sequence number, the roothash, and the
1847 The following keys are most relevant for mutable files, but immutable
1848 files will provide sensible values too::
1850 count-wrong-shares: the number of shares for versions other than the
1851 'best' one (which is defined as being the
1852 recoverable version with the highest sequence
1853 number, then the highest roothash). These are
1854 either leftover shares from an older version
1855 (perhaps on a server that was offline when an
1856 update occurred), shares from an unrecoverable
1857 newer version, or shares from an alternate
1858 current version that results from an
1859 uncoordinated write collision. For a healthy
1860 file, this will equal 0.
1862 count-recoverable-versions: the number of recoverable versions of
1863 the file. For a healthy file, this will
1866 count-unrecoverable-versions: the number of unrecoverable versions
1867 of the file. For a healthy file, this
1873 """Return a string with a brief (one-line) summary of the results."""
1876 """Return a list of strings with more detailed results."""
1878 class ICheckAndRepairResults(Interface):
1879 """I contain the detailed results of a check/verify/repair operation.
1881 The IFilesystemNode.check()/verify()/repair() methods all return
1882 instances that provide ICheckAndRepairResults.
1885 def get_storage_index():
1886 """Return a string with the (binary) storage index."""
1887 def get_storage_index_string():
1888 """Return a string with the (printable) abbreviated storage index."""
1889 def get_repair_attempted():
1890 """Return a boolean, True if a repair was attempted. We might not
1891 attempt to repair the file because it was healthy, or healthy enough
1892 (i.e. some shares were missing but not enough to exceed some
1893 threshold), or because we don't know how to repair this object."""
1894 def get_repair_successful():
1895 """Return a boolean, True if repair was attempted and the file/dir
1896 was fully healthy afterwards. False if no repair was attempted or if
1897 a repair attempt failed."""
1898 def get_pre_repair_results():
1899 """Return an ICheckResults instance that describes the state of the
1900 file/dir before any repair was attempted."""
1901 def get_post_repair_results():
1902 """Return an ICheckResults instance that describes the state of the
1903 file/dir after any repair was attempted. If no repair was attempted,
1904 the pre-repair and post-repair results will be identical."""
1907 class IDeepCheckResults(Interface):
1908 """I contain the results of a deep-check operation.
1910 This is returned by a call to ICheckable.deep_check().
1913 def get_root_storage_index_string():
1914 """Return the storage index (abbreviated human-readable string) of
1915 the first object checked."""
1917 """Return a dictionary with the following keys::
1919 count-objects-checked: count of how many objects were checked
1920 count-objects-healthy: how many of those objects were completely
1922 count-objects-unhealthy: how many were damaged in some way
1923 count-objects-unrecoverable: how many were unrecoverable
1924 count-corrupt-shares: how many shares were found to have
1925 corruption, summed over all objects
1929 def get_corrupt_shares():
1930 """Return a set of (serverid, storage_index, sharenum) for all shares
1931 that were found to be corrupt. Both serverid and storage_index are
1934 def get_all_results():
1935 """Return a dictionary mapping pathname (a tuple of strings, ready to
1936 be slash-joined) to an ICheckResults instance, one for each object
1937 that was checked."""
1939 def get_results_for_storage_index(storage_index):
1940 """Retrive the ICheckResults instance for the given (binary)
1941 storage index. Raises KeyError if there are no results for that
1945 """Return a dictionary with the same keys as
1946 IDirectoryNode.deep_stats()."""
1948 class IDeepCheckAndRepairResults(Interface):
1949 """I contain the results of a deep-check-and-repair operation.
1951 This is returned by a call to ICheckable.deep_check_and_repair().
1954 def get_root_storage_index_string():
1955 """Return the storage index (abbreviated human-readable string) of
1956 the first object checked."""
1958 """Return a dictionary with the following keys::
1960 count-objects-checked: count of how many objects were checked
1961 count-objects-healthy-pre-repair: how many of those objects were
1962 completely healthy (before any
1964 count-objects-unhealthy-pre-repair: how many were damaged in
1966 count-objects-unrecoverable-pre-repair: how many were unrecoverable
1967 count-objects-healthy-post-repair: how many of those objects were
1968 completely healthy (after any
1970 count-objects-unhealthy-post-repair: how many were damaged in
1972 count-objects-unrecoverable-post-repair: how many were
1974 count-repairs-attempted: repairs were attempted on this many
1975 objects. The count-repairs- keys will
1976 always be provided, however unless
1977 repair=true is present, they will all
1979 count-repairs-successful: how many repairs resulted in healthy
1981 count-repairs-unsuccessful: how many repairs resulted did not
1982 results in completely healthy objects
1983 count-corrupt-shares-pre-repair: how many shares were found to
1984 have corruption, summed over all
1985 objects examined (before any
1987 count-corrupt-shares-post-repair: how many shares were found to
1988 have corruption, summed over all
1989 objects examined (after any
1994 """Return a dictionary with the same keys as
1995 IDirectoryNode.deep_stats()."""
1997 def get_corrupt_shares():
1998 """Return a set of (serverid, storage_index, sharenum) for all shares
1999 that were found to be corrupt before any repair was attempted. Both
2000 serverid and storage_index are binary.
2002 def get_remaining_corrupt_shares():
2003 """Return a set of (serverid, storage_index, sharenum) for all shares
2004 that were found to be corrupt after any repair was completed. Both
2005 serverid and storage_index are binary. These are shares that need
2006 manual inspection and probably deletion.
2008 def get_all_results():
2009 """Return a dictionary mapping pathname (a tuple of strings, ready to
2010 be slash-joined) to an ICheckAndRepairResults instance, one for each
2011 object that was checked."""
2013 def get_results_for_storage_index(storage_index):
2014 """Retrive the ICheckAndRepairResults instance for the given (binary)
2015 storage index. Raises KeyError if there are no results for that
2019 class IRepairable(Interface):
2020 def repair(check_results):
2021 """Attempt to repair the given object. Returns a Deferred that fires
2022 with a IRepairResults object.
2024 I must be called with an object that implements ICheckResults, as
2025 proof that you have actually discovered a problem with this file. I
2026 will use the data in the checker results to guide the repair process,
2027 such as which servers provided bad data and should therefore be
2028 avoided. The ICheckResults object is inside the
2029 ICheckAndRepairResults object, which is returned by the
2030 ICheckable.check() method::
2032 d = filenode.check(repair=False)
2033 def _got_results(check_and_repair_results):
2034 check_results = check_and_repair_results.get_pre_repair_results()
2035 return filenode.repair(check_results)
2036 d.addCallback(_got_results)
2040 class IRepairResults(Interface):
2041 """I contain the results of a repair operation."""
2042 def get_successful(self):
2043 """Returns a boolean: True if the repair made the file healthy, False
2044 if not. Repair failure generally indicates a file that has been
2045 damaged beyond repair."""
2048 class IClient(Interface):
2049 def upload(uploadable):
2050 """Upload some data into a CHK, get back the UploadResults for it.
2051 @param uploadable: something that implements IUploadable
2052 @return: a Deferred that fires with the UploadResults instance.
2053 To get the URI for this file, use results.uri .
2056 def create_mutable_file(contents=""):
2057 """Create a new mutable file (with initial) contents, get back the
2060 @param contents: (bytestring, callable, or None): this provides the
2061 initial contents of the mutable file. If 'contents' is a bytestring,
2062 it will be used as-is. If 'contents' is a callable, it will be
2063 invoked with the new MutableFileNode instance and is expected to
2064 return a bytestring with the initial contents of the file (the
2065 callable can use node.get_writekey() to decide how to encrypt the
2066 initial contents, e.g. for a brand new dirnode with initial
2067 children). contents=None is equivalent to an empty string. Using
2068 content_maker= is more efficient than creating a mutable file and
2069 setting its contents in two separate operations.
2071 @return: a Deferred that fires with an IMutableFileNode instance.
2074 def create_dirnode(initial_children={}):
2075 """Create a new unattached dirnode, possibly with initial children.
2077 @param initial_children: dict with keys that are unicode child names,
2078 and values that are (childnode, metadata) tuples.
2080 @return: a Deferred that fires with the new IDirectoryNode instance.
2083 def create_node_from_uri(uri, rouri):
2084 """Create a new IFilesystemNode instance from the uri, synchronously.
2085 @param uri: a string or IURI-providing instance, or None. This could
2086 be for a LiteralFileNode, a CHK file node, a mutable file
2087 node, or a directory node
2088 @param rouri: a string or IURI-providing instance, or None. If the
2089 main uri is None, I will use the rouri instead. If I
2090 recognize the format of the main uri, I will ignore the
2091 rouri (because it can be derived from the writecap).
2093 @return: an instance that provides IFilesystemNode (or more usefully
2094 one of its subclasses). File-specifying URIs will result in
2095 IFileNode-providing instances, like ImmutableFileNode,
2096 LiteralFileNode, or MutableFileNode. Directory-specifying
2097 URIs will result in IDirectoryNode-providing instances, like
2101 class INodeMaker(Interface):
2102 """The NodeMaker is used to create IFilesystemNode instances. It can
2103 accept a filecap/dircap string and return the node right away. It can
2104 also create new nodes (i.e. upload a file, or create a mutable file)
2105 asynchronously. Once you have one of these nodes, you can use other
2106 methods to determine whether it is a file or directory, and to download
2107 or modify its contents.
2109 The NodeMaker encapsulates all the authorities that these
2110 IFilesystemNodes require (like references to the StorageFarmBroker). Each
2111 Tahoe process will typically have a single NodeMaker, but unit tests may
2112 create simplified/mocked forms for testing purposes.
2114 def create_from_cap(writecap, readcap=None, **kwargs):
2115 """I create an IFilesystemNode from the given writecap/readcap. I can
2116 only provide nodes for existing file/directory objects: use my other
2117 methods to create new objects. I return synchronously."""
2119 def create_mutable_file(contents=None, keysize=None):
2120 """I create a new mutable file, and return a Deferred which will fire
2121 with the IMutableFileNode instance when it is ready. If contents= is
2122 provided (a bytestring), it will be used as the initial contents of
2123 the new file, otherwise the file will contain zero bytes. keysize= is
2124 for use by unit tests, to create mutable files that are smaller than
2127 def create_new_mutable_directory(initial_children={}):
2128 """I create a new mutable directory, and return a Deferred which will
2129 fire with the IDirectoryNode instance when it is ready. If
2130 initial_children= is provided (a dict mapping unicode child name to
2131 (childnode, metadata_dict) tuples), the directory will be populated
2132 with those children, otherwise it will be empty."""
2134 class IClientStatus(Interface):
2135 def list_all_uploads():
2136 """Return a list of uploader objects, one for each upload which
2137 currently has an object available (tracked with weakrefs). This is
2138 intended for debugging purposes."""
2139 def list_active_uploads():
2140 """Return a list of active IUploadStatus objects."""
2141 def list_recent_uploads():
2142 """Return a list of IUploadStatus objects for the most recently
2145 def list_all_downloads():
2146 """Return a list of downloader objects, one for each download which
2147 currently has an object available (tracked with weakrefs). This is
2148 intended for debugging purposes."""
2149 def list_active_downloads():
2150 """Return a list of active IDownloadStatus objects."""
2151 def list_recent_downloads():
2152 """Return a list of IDownloadStatus objects for the most recently
2153 started downloads."""
2155 class IUploadStatus(Interface):
2157 """Return a timestamp (float with seconds since epoch) indicating
2158 when the operation was started."""
2159 def get_storage_index():
2160 """Return a string with the (binary) storage index in use on this
2161 upload. Returns None if the storage index has not yet been
2164 """Return an integer with the number of bytes that will eventually
2165 be uploaded for this file. Returns None if the size is not yet known.
2168 """Return True if this upload is using a Helper, False if not."""
2170 """Return a string describing the current state of the upload
2173 """Returns a tuple of floats, (chk, ciphertext, encode_and_push),
2174 each from 0.0 to 1.0 . 'chk' describes how much progress has been
2175 made towards hashing the file to determine a CHK encryption key: if
2176 non-convergent encryption is in use, this will be trivial, otherwise
2177 the whole file must be hashed. 'ciphertext' describes how much of the
2178 ciphertext has been pushed to the helper, and is '1.0' for non-helper
2179 uploads. 'encode_and_push' describes how much of the encode-and-push
2180 process has finished: for helper uploads this is dependent upon the
2181 helper providing progress reports. It might be reasonable to add all
2182 three numbers and report the sum to the user."""
2184 """Return True if the upload is currently active, False if not."""
2186 """Return an instance of UploadResults (which contains timing and
2187 sharemap information). Might return None if the upload is not yet
2190 """Each upload status gets a unique number: this method returns that
2191 number. This provides a handle to this particular upload, so a web
2192 page can generate a suitable hyperlink."""
2194 class IDownloadStatus(Interface):
2196 """Return a timestamp (float with seconds since epoch) indicating
2197 when the operation was started."""
2198 def get_storage_index():
2199 """Return a string with the (binary) storage index in use on this
2200 download. This may be None if there is no storage index (i.e. LIT
2203 """Return an integer with the number of bytes that will eventually be
2204 retrieved for this file. Returns None if the size is not yet known.
2207 """Return True if this download is using a Helper, False if not."""
2209 """Return a string describing the current state of the download
2212 """Returns a float (from 0.0 to 1.0) describing the amount of the
2213 download that has completed. This value will remain at 0.0 until the
2214 first byte of plaintext is pushed to the download target."""
2216 """Return True if the download is currently active, False if not."""
2218 """Each download status gets a unique number: this method returns
2219 that number. This provides a handle to this particular download, so a
2220 web page can generate a suitable hyperlink."""
2222 class IServermapUpdaterStatus(Interface):
2224 class IPublishStatus(Interface):
2226 class IRetrieveStatus(Interface):
2229 class NotCapableError(Exception):
2230 """You have tried to write to a read-only node."""
2232 class BadWriteEnablerError(Exception):
2235 class RIControlClient(RemoteInterface):
2237 def wait_for_client_connections(num_clients=int):
2238 """Do not return until we have connections to at least NUM_CLIENTS
2242 def upload_from_file_to_uri(filename=str,
2243 convergence=ChoiceOf(None,
2244 StringConstraint(2**20))):
2245 """Upload a file to the grid. This accepts a filename (which must be
2246 absolute) that points to a file on the node's local disk. The node will
2247 read the contents of this file, upload it to the grid, then return the
2248 URI at which it was uploaded. If convergence is None then a random
2249 encryption key will be used, else the plaintext will be hashed, then
2250 that hash will be mixed together with the "convergence" string to form
2255 def download_from_uri_to_file(uri=URI, filename=str):
2256 """Download a file from the grid, placing it on the node's local disk
2257 at the given filename (which must be absolute[?]). Returns the
2258 absolute filename where the file was written."""
2263 def get_memory_usage():
2264 """Return a dict describes the amount of memory currently in use. The
2265 keys are 'VmPeak', 'VmSize', and 'VmData'. The values are integers,
2266 measuring memory consupmtion in bytes."""
2267 return DictOf(str, int)
2269 def speed_test(count=int, size=int, mutable=Any()):
2270 """Write 'count' tempfiles to disk, all of the given size. Measure
2271 how long (in seconds) it takes to upload them all to the servers.
2272 Then measure how long it takes to download all of them. If 'mutable'
2273 is 'create', time creation of mutable files. If 'mutable' is
2274 'upload', then time access to the same mutable file instead of
2277 Returns a tuple of (upload_time, download_time).
2279 return (float, float)
2281 def measure_peer_response_time():
2282 """Send a short message to each connected peer, and measure the time
2283 it takes for them to respond to it. This is a rough measure of the
2284 application-level round trip time.
2286 @return: a dictionary mapping peerid to a float (RTT time in seconds)
2289 return DictOf(Nodeid, float)
2291 UploadResults = Any() #DictOf(str, str)
2293 class RIEncryptedUploadable(RemoteInterface):
2294 __remote_name__ = "RIEncryptedUploadable.tahoe.allmydata.com"
2299 def get_all_encoding_parameters():
2300 return (int, int, int, long)
2302 def read_encrypted(offset=Offset, length=ReadSize):
2309 class RICHKUploadHelper(RemoteInterface):
2310 __remote_name__ = "RIUploadHelper.tahoe.allmydata.com"
2314 Return a dictionary of version information.
2316 return DictOf(str, Any())
2318 def upload(reader=RIEncryptedUploadable):
2319 return UploadResults
2322 class RIHelper(RemoteInterface):
2323 __remote_name__ = "RIHelper.tahoe.allmydata.com"
2327 Return a dictionary of version information.
2329 return DictOf(str, Any())
2331 def upload_chk(si=StorageIndex):
2332 """See if a file with a given storage index needs uploading. The
2333 helper will ask the appropriate storage servers to see if the file
2334 has already been uploaded. If so, the helper will return a set of
2335 'upload results' that includes whatever hashes are needed to build
2336 the read-cap, and perhaps a truncated sharemap.
2338 If the file has not yet been uploaded (or if it was only partially
2339 uploaded), the helper will return an empty upload-results dictionary
2340 and also an RICHKUploadHelper object that will take care of the
2341 upload process. The client should call upload() on this object and
2342 pass it a reference to an RIEncryptedUploadable object that will
2343 provide ciphertext. When the upload is finished, the upload() method
2344 will finish and return the upload results.
2346 return (UploadResults, ChoiceOf(RICHKUploadHelper, None))
2349 class RIStatsProvider(RemoteInterface):
2350 __remote_name__ = "RIStatsProvider.tahoe.allmydata.com"
2352 Provides access to statistics and monitoring information.
2357 returns a dictionary containing 'counters' and 'stats', each a
2358 dictionary with string counter/stat name keys, and numeric values.
2359 counters are monotonically increasing measures of work done, and
2360 stats are instantaneous measures (potentially time averaged
2363 return DictOf(str, DictOf(str, ChoiceOf(float, int, long)))
2365 class RIStatsGatherer(RemoteInterface):
2366 __remote_name__ = "RIStatsGatherer.tahoe.allmydata.com"
2368 Provides a monitoring service for centralised collection of stats
2371 def provide(provider=RIStatsProvider, nickname=str):
2373 @param provider: a stats collector instance which should be polled
2374 periodically by the gatherer to collect stats.
2375 @param nickname: a name useful to identify the provided client
2380 class IStatsProducer(Interface):
2383 returns a dictionary, with str keys representing the names of stats
2384 to be monitored, and numeric values.
2387 class RIKeyGenerator(RemoteInterface):
2388 __remote_name__ = "RIKeyGenerator.tahoe.allmydata.com"
2390 Provides a service offering to make RSA key pairs.
2393 def get_rsa_key_pair(key_size=int):
2395 @param key_size: the size of the signature key.
2396 @return: tuple(verifying_key, signing_key)
2398 return TupleOf(str, str)
2401 class FileTooLargeError(Exception):
2404 class IValidatedThingProxy(Interface):
2406 """ Acquire a thing and validate it. Return a deferred which is
2407 eventually fired with self if the thing is valid or errbacked if it
2408 can't be acquired or validated."""
2410 class InsufficientVersionError(Exception):
2411 def __init__(self, needed, got):
2412 self.needed = needed
2415 return "InsufficientVersionError(need '%s', got %s)" % (self.needed,
2418 class EmptyPathnameComponentError(Exception):
2419 """The webapi disallows empty pathname components."""