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