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