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