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