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