root/tags/releases/twisted-8.2.0/twisted/internet/interfaces.py

Revision 25371, 48.3 KB (checked in by thijs, 22 months ago)

Apply misleading-callFromThread-doc.patch: make docs for reactor.callFromThread() clear about when the callable must be threadsafe.

Author: thijs
Reviewer: therve
Fixes: #2449

Line 
1# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
2# See LICENSE for details.
3
4
5"""
6Interface documentation.
7
8Maintainer: Itamar Shtull-Trauring
9"""
10
11from zope.interface import Interface, Attribute
12
13
14class IAddress(Interface):
15    """
16    An address, e.g. a TCP C{(host, port)}.
17
18    Default implementations are in L{twisted.internet.address}.
19    """
20
21### Reactor Interfaces
22
23class IConnector(Interface):
24    """
25    Object used to interface between connections and protocols.
26
27    Each L{IConnector} manages one connection.
28    """
29
30    def stopConnecting():
31        """
32        Stop attempting to connect.
33        """
34
35    def disconnect():
36        """
37        Disconnect regardless of the connection state.
38
39        If we are connected, disconnect, if we are trying to connect,
40        stop trying.
41        """
42
43    def connect():
44        """
45        Try to connect to remote address.
46        """
47
48    def getDestination():
49        """
50        Return destination this will try to connect to.
51
52        @return: An object which provides L{IAddress}.
53        """
54
55
56class IResolverSimple(Interface):
57   
58    def getHostByName(name, timeout = (1, 3, 11, 45)):
59        """
60        Resolve the domain name C{name} into an IP address.
61
62        @type name: C{str}
63        @type timeout: C{tuple}
64        @rtype: L{twisted.internet.defer.Deferred}
65        @return: The callback of the Deferred that is returned will be
66        passed a string that represents the IP address of the specified
67        name, or the errback will be called if the lookup times out.  If
68        multiple types of address records are associated with the name,
69        A6 records will be returned in preference to AAAA records, which
70        will be returned in preference to A records.  If there are multiple
71        records of the type to be returned, one will be selected at random.
72
73        @raise twisted.internet.defer.TimeoutError: Raised (asynchronously)
74        if the name cannot be resolved within the specified timeout period.
75        """
76
77class IResolver(IResolverSimple):
78    def lookupRecord(name, cls, type, timeout = 10):
79        """
80        Lookup the records associated with the given name
81        that are of the given type and in the given class.
82        """
83
84    def query(query, timeout = 10):
85        """
86        Interpret and dispatch a query object to the appropriate
87        lookup* method.
88        """
89
90    def lookupAddress(name, timeout = 10):
91        """
92        Lookup the A records associated with C{name}.
93        """
94
95    def lookupAddress6(name, timeout = 10):
96        """
97        Lookup all the A6 records associated with C{name}.
98        """
99
100    def lookupIPV6Address(name, timeout = 10):
101        """
102        Lookup all the AAAA records associated with C{name}.
103        """
104
105    def lookupMailExchange(name, timeout = 10):
106        """
107        Lookup the MX records associated with C{name}.
108        """
109
110    def lookupNameservers(name, timeout = 10):
111        """
112        Lookup the the NS records associated with C{name}.
113        """
114
115    def lookupCanonicalName(name, timeout = 10):
116        """
117        Lookup the CNAME records associated with C{name}.
118        """
119
120    def lookupMailBox(name, timeout = 10):
121        """
122        Lookup the MB records associated with C{name}.
123        """
124
125    def lookupMailGroup(name, timeout = 10):
126        """
127        Lookup the MG records associated with C{name}.
128        """
129
130    def lookupMailRename(name, timeout = 10):
131        """
132        Lookup the MR records associated with C{name}.
133        """
134
135    def lookupPointer(name, timeout = 10):
136        """
137        Lookup the PTR records associated with C{name}.
138        """
139
140    def lookupAuthority(name, timeout = 10):
141        """
142        Lookup the SOA records associated with C{name}.
143        """
144
145    def lookupNull(name, timeout = 10):
146        """
147        Lookup the NULL records associated with C{name}.
148        """
149
150    def lookupWellKnownServices(name, timeout = 10):
151        """
152        Lookup the WKS records associated with C{name}.
153        """
154
155    def lookupHostInfo(name, timeout = 10):
156        """
157        Lookup the HINFO records associated with C{name}.
158        """
159
160    def lookupMailboxInfo(name, timeout = 10):
161        """
162        Lookup the MINFO records associated with C{name}.
163        """
164
165    def lookupText(name, timeout = 10):
166        """
167        Lookup the TXT records associated with C{name}.
168        """
169
170    def lookupResponsibility(name, timeout = 10):
171        """
172        Lookup the RP records associated with C{name}.
173        """
174
175    def lookupAFSDatabase(name, timeout = 10):
176        """
177        Lookup the AFSDB records associated with C{name}.
178        """
179
180    def lookupService(name, timeout = 10):
181        """
182        Lookup the SRV records associated with C{name}.
183        """
184
185    def lookupAllRecords(name, timeout = 10):
186        """
187        Lookup all records associated with C{name}.
188        """
189
190    def lookupZone(name, timeout = 10):
191        """
192        Perform a zone transfer for the given C{name}.
193        """
194
195
196class IReactorArbitrary(Interface):
197   
198    def listenWith(portType, *args, **kw):
199        """
200        Start an instance of the given C{portType} listening.
201
202        @type portType: type which implements L{IListeningPort}
203
204        @param portType: The object given by C{portType(*args, **kw)} will be
205                         started listening.
206
207        @return: an object which provides L{IListeningPort}.
208        """
209
210    def connectWith(connectorType, *args, **kw):
211        """
212        Start an instance of the given C{connectorType} connecting.
213
214        @type connectorType: type which implements L{IConnector}
215
216        @param connectorType: The object given by C{connectorType(*args, **kw)}
217                              will be started connecting.
218
219        @return:  An object which provides L{IConnector}.
220        """
221
222class IReactorTCP(Interface):
223
224    def listenTCP(port, factory, backlog=50, interface=''):
225        """
226        Connects a given protocol factory to the given numeric TCP/IP port.
227
228        @param port: a port number on which to listen
229
230        @param factory: a L{twisted.internet.protocol.ServerFactory} instance
231
232        @param backlog: size of the listen queue
233
234        @param interface: the hostname to bind to, defaults to '' (all)
235
236        @return: an object that provides L{IListeningPort}.
237
238        @raise CannotListenError: as defined here
239                                  L{twisted.internet.error.CannotListenError},
240                                  if it cannot listen on this port (e.g., it
241                                  cannot bind to the required port number)
242        """
243
244    def connectTCP(host, port, factory, timeout=30, bindAddress=None):
245        """
246        Connect a TCP client.
247
248        @param host: a host name
249
250        @param port: a port number
251
252        @param factory: a L{twisted.internet.protocol.ClientFactory} instance
253
254        @param timeout: number of seconds to wait before assuming the
255                        connection has failed.
256
257        @param bindAddress: a (host, port) tuple of local address to bind
258                            to, or None.
259
260        @return: An object which provides L{IConnector}. This connector will
261                 call various callbacks on the factory when a connection is
262                 made, failed, or lost - see
263                 L{ClientFactory<twisted.internet.protocol.ClientFactory>}
264                 docs for details.
265        """
266
267class IReactorSSL(Interface):
268
269    def connectSSL(host, port, factory, contextFactory, timeout=30, bindAddress=None):
270        """
271        Connect a client Protocol to a remote SSL socket.
272
273        @param host: a host name
274
275        @param port: a port number
276
277        @param factory: a L{twisted.internet.protocol.ClientFactory} instance
278
279        @param contextFactory: a L{twisted.internet.ssl.ClientContextFactory} object.
280
281        @param timeout: number of seconds to wait before assuming the
282                        connection has failed.
283
284        @param bindAddress: a (host, port) tuple of local address to bind to,
285                            or C{None}.
286
287        @return: An object which provides L{IConnector}.
288        """
289
290    def listenSSL(port, factory, contextFactory, backlog=50, interface=''):
291        """
292        Connects a given protocol factory to the given numeric TCP/IP port.
293        The connection is a SSL one, using contexts created by the context
294        factory.
295
296        @param port: a port number on which to listen
297
298        @param factory: a L{twisted.internet.protocol.ServerFactory} instance
299
300        @param contextFactory: a L{twisted.internet.ssl.ContextFactory} instance
301
302        @param backlog: size of the listen queue
303
304        @param interface: the hostname to bind to, defaults to '' (all)
305        """
306
307
308class IReactorUNIX(Interface):
309    """
310    UNIX socket methods.
311    """
312
313    def connectUNIX(address, factory, timeout=30, checkPID=0):
314        """
315        Connect a client protocol to a UNIX socket.
316
317        @param address: a path to a unix socket on the filesystem.
318
319        @param factory: a L{twisted.internet.protocol.ClientFactory} instance
320
321        @param timeout: number of seconds to wait before assuming the connection
322            has failed.
323
324        @param checkPID: if True, check for a pid file to verify that a server
325            is listening.
326
327        @return: An object which provides L{IConnector}.
328        """
329
330    def listenUNIX(address, factory, backlog=50, mode=0666, wantPID=0):
331        """
332        Listen on a UNIX socket.
333
334        @param address: a path to a unix socket on the filesystem.
335
336        @param factory: a L{twisted.internet.protocol.Factory} instance.
337
338        @param backlog: number of connections to allow in backlog.
339
340        @param mode: mode to set on the unix socket.  This parameter is
341            deprecated.  Permissions should be set on the directory which
342            contains the UNIX socket.
343
344        @param wantPID: if True, create a pidfile for the socket.
345
346        @return: An object which provides L{IListeningPort}.
347        """
348
349
350class IReactorUNIXDatagram(Interface):
351    """
352    Datagram UNIX socket methods.
353    """
354
355    def connectUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0666, bindAddress=None):
356        """
357        Connect a client protocol to a datagram UNIX socket.
358
359        @param address: a path to a unix socket on the filesystem.
360
361        @param protocol: a L{twisted.internet.protocol.ConnectedDatagramProtocol} instance
362
363        @param maxPacketSize: maximum packet size to accept
364
365        @param mode: mode to set on the unix socket.  This parameter is
366            deprecated.  Permissions should be set on the directory which
367            contains the UNIX socket.
368
369        @param bindAddress: address to bind to
370
371        @return: An object which provides L{IConnector}.
372        """
373
374    def listenUNIXDatagram(address, protocol, maxPacketSize=8192, mode=0666):
375        """
376        Listen on a datagram UNIX socket.
377
378        @param address: a path to a unix socket on the filesystem.
379
380        @param protocol: a L{twisted.internet.protocol.DatagramProtocol} instance.
381
382        @param maxPacketSize: maximum packet size to accept
383
384        @param mode: mode to set on the unix socket.  This parameter is
385            deprecated.  Permissions should be set on the directory which
386            contains the UNIX socket.
387
388        @return: An object which provides L{IListeningPort}.
389        """
390
391
392class IReactorUDP(Interface):
393    """
394    UDP socket methods.
395
396    IMPORTANT: This is an experimental new interface. It may change
397    without backwards compatability. Suggestions are welcome.
398    """
399
400    def listenUDP(port, protocol, interface='', maxPacketSize=8192):
401        """
402        Connects a given DatagramProtocol to the given numeric UDP port.
403
404        @return: object which provides L{IListeningPort}.
405        """
406
407    def connectUDP(remotehost, remoteport, protocol, localport=0,
408                  interface='', maxPacketSize=8192):
409        """
410        DEPRECATED.
411
412        Connects a L{twisted.internet.protocol.ConnectedDatagramProtocol}
413        instance to a UDP port.
414        """
415
416
417class IReactorMulticast(Interface):
418    """
419    UDP socket methods that support multicast.
420
421    IMPORTANT: This is an experimental new interface. It may change
422    without backwards compatability. Suggestions are welcome.
423    """
424
425    def listenMulticast(port, protocol, interface='', maxPacketSize=8192,
426                        listenMultiple=False):
427        """
428        Connects a given
429        L{DatagramProtocol<twisted.internet.protocol.DatagramProtocol>} to the
430        given numeric UDP port.
431
432        @param listenMultiple: boolean indicating whether multiple sockets can
433                               bind to same UDP port.
434
435        @returns: An object which provides L{IListeningPort}.
436        """
437
438
439class IReactorProcess(Interface):
440
441    def spawnProcess(processProtocol, executable, args=(), env={}, path=None,
442                     uid=None, gid=None, usePTY=0, childFDs=None):
443        """
444        Spawn a process, with a process protocol.
445
446        @type processProtocol: L{IProcessProtocol} provider
447        @param processProtocol: An object which will be notified of all
448            events related to the created process.
449
450        @param executable: the file name to spawn - the full path should be
451                           used.
452
453        @param args: the command line arguments to pass to the process; a
454                     sequence of strings. The first string should be the
455                     executable's name.
456
457        @param env: the environment variables to pass to the processs; a
458                    dictionary of strings. If 'None', use os.environ.
459
460        @param path: the path to run the subprocess in - defaults to the
461                     current directory.
462
463        @param uid: user ID to run the subprocess as. (Only available on
464                    POSIX systems.)
465
466        @param gid: group ID to run the subprocess as. (Only available on
467                    POSIX systems.)
468
469        @param usePTY: if true, run this process in a pseudo-terminal.
470                       optionally a tuple of C{(masterfd, slavefd, ttyname)},
471                       in which case use those file descriptors.
472                       (Not available on all systems.)
473
474        @param childFDs: A dictionary mapping file descriptors in the new child
475                         process to an integer or to the string 'r' or 'w'.
476
477                         If the value is an integer, it specifies a file
478                         descriptor in the parent process which will be mapped
479                         to a file descriptor (specified by the key) in the
480                         child process.  This is useful for things like inetd
481                         and shell-like file redirection.
482
483                         If it is the string 'r', a pipe will be created and
484                         attached to the child at that file descriptor: the
485                         child will be able to write to that file descriptor
486                         and the parent will receive read notification via the
487                         L{IProcessProtocol.childDataReceived} callback.  This
488                         is useful for the child's stdout and stderr.
489
490                         If it is the string 'w', similar setup to the previous
491                         case will occur, with the pipe being readable by the
492                         child instead of writeable.  The parent process can
493                         write to that file descriptor using
494                         L{IProcessTransport.writeToChild}.  This is useful for
495                         the child's stdin.
496
497                         If childFDs is not passed, the default behaviour is to
498                         use a mapping that opens the usual stdin/stdout/stderr
499                         pipes.
500
501        @see: L{twisted.internet.protocol.ProcessProtocol}
502
503        @return: An object which provides L{IProcessTransport}.
504
505        @raise OSError: Raised with errno C{EAGAIN} or C{ENOMEM} if there are
506                        insufficient system resources to create a new process.
507        """
508
509class IReactorTime(Interface):
510    """
511    Time methods that a Reactor should implement.
512    """
513
514    def seconds():
515        """
516        Get the current time in seconds.
517
518        @return: A number-like object of some sort.
519        """
520
521
522    def callLater(delay, callable, *args, **kw):
523        """
524        Call a function later.
525
526        @type delay:  C{float}
527        @param delay: the number of seconds to wait.
528
529        @param callable: the callable object to call later.
530
531        @param args: the arguments to call it with.
532
533        @param kw: the keyword arguments to call it with.
534
535        @return: An object which provides L{IDelayedCall} and can be used to
536                 cancel the scheduled call, by calling its C{cancel()} method.
537                 It also may be rescheduled by calling its C{delay()} or
538                 C{reset()} methods.
539        """
540
541    def cancelCallLater(callID):
542        """
543        This method is deprecated.
544
545        Cancel a call that would happen later.
546
547        @param callID: this is an opaque identifier returned from C{callLater}
548                       that will be used to cancel a specific call.
549
550        @raise ValueError: if the callID is not recognized.
551        """
552
553    def getDelayedCalls():
554        """
555        Retrieve all currently scheduled delayed calls.
556
557        @return: A tuple of all L{IDelayedCall} providers representing all
558                 currently scheduled calls. This is everything that has been
559                 returned by C{callLater} but not yet called or canceled.
560        """
561
562
563class IDelayedCall(Interface):
564    """
565    A scheduled call.
566
567    There are probably other useful methods we can add to this interface;
568    suggestions are welcome.
569    """
570
571    def getTime():
572        """
573        Get time when delayed call will happen.
574
575        @return: time in seconds since epoch (a float).
576        """
577
578    def cancel():
579        """
580        Cancel the scheduled call.
581
582        @raises twisted.internet.error.AlreadyCalled: if the call has already
583            happened.
584        @raises twisted.internet.error.AlreadyCancelled: if the call has already
585            been cancelled.
586        """
587
588    def delay(secondsLater):
589        """
590        Delay the scheduled call.
591
592        @param secondsLater: how many seconds from its current firing time to delay
593
594        @raises twisted.internet.error.AlreadyCalled: if the call has already
595            happened.
596        @raises twisted.internet.error.AlreadyCancelled: if the call has already
597            been cancelled.
598        """
599
600    def reset(secondsFromNow):
601        """
602        Reset the scheduled call's timer.
603
604        @param secondsFromNow: how many seconds from now it should fire,
605            equivalent to C{.cancel()} and then doing another
606            C{reactor.callLater(secondsLater, ...)}
607
608        @raises twisted.internet.error.AlreadyCalled: if the call has already
609            happened.
610        @raises twisted.internet.error.AlreadyCancelled: if the call has already
611            been cancelled.
612        """
613
614    def active():
615        """
616        @return: True if this call is still active, False if it has been
617                 called or cancelled.
618        """
619
620class IReactorThreads(Interface):
621    """
622    Dispatch methods to be run in threads.
623
624    Internally, this should use a thread pool and dispatch methods to them.
625    """
626
627    def callInThread(callable, *args, **kwargs):
628        """
629        Run the callable object in a separate thread.
630        """
631
632    def callFromThread(callable, *args, **kw):
633        """
634        Cause a function to be executed by the reactor thread.
635
636        Use this method when you want to run a function in the reactor's thread
637        from another thread.  Calling L{callFromThread} should wake up the main
638        thread (where L{reactor.run()<reactor.run>} is executing) and run the
639        given callable in that thread.
640
641        If you're writing a multi-threaded application the C{callable} may need
642        to be thread safe, but this method doesn't require it as such. If you
643        want to call a function in the next mainloop iteration, but you're in
644        the same thread, use L{callLater} with a delay of 0.
645        """
646
647    def suggestThreadPoolSize(size):
648        """
649        Suggest the size of the internal threadpool used to dispatch functions
650        passed to L{callInThread}.
651        """
652
653
654class IReactorCore(Interface):
655    """
656    Core methods that a Reactor must implement.
657    """
658
659    running = Attribute(
660        "A C{bool} which is C{True} from I{during startup} to "
661        "I{during shutdown} and C{False} the rest of the time.")
662
663
664    def resolve(name, timeout=10):
665        """
666        Return a L{twisted.internet.defer.Deferred} that will resolve a hostname.
667        """
668
669    def run():
670        """
671        Fire 'startup' System Events, move the reactor to the 'running'
672        state, then run the main loop until it is stopped with C{stop()} or
673        C{crash()}.
674        """
675
676    def stop():
677        """
678        Fire 'shutdown' System Events, which will move the reactor to the
679        'stopped' state and cause C{reactor.run()} to exit.
680        """
681
682    def crash():
683        """
684        Stop the main loop *immediately*, without firing any system events.
685
686        This is named as it is because this is an extremely "rude" thing to do;
687        it is possible to lose data and put your system in an inconsistent
688        state by calling this.  However, it is necessary, as sometimes a system
689        can become wedged in a pre-shutdown call.
690        """
691
692    def iterate(delay=0):
693        """
694        Run the main loop's I/O polling function for a period of time.
695
696        This is most useful in applications where the UI is being drawn "as
697        fast as possible", such as games. All pending L{IDelayedCall}s will
698        be called.
699
700        The reactor must have been started (via the C{run()} method) prior to
701        any invocations of this method.  It must also be stopped manually
702        after the last call to this method (via the C{stop()} method).  This
703        method is not re-entrant: you must not call it recursively; in
704        particular, you must not call it while the reactor is running.
705        """
706
707    def fireSystemEvent(eventType):
708        """
709        Fire a system-wide event.
710
711        System-wide events are things like 'startup', 'shutdown', and
712        'persist'.
713        """
714
715    def addSystemEventTrigger(phase, eventType, callable, *args, **kw):
716        """
717        Add a function to be called when a system event occurs.
718
719        Each "system event" in Twisted, such as 'startup', 'shutdown', and
720        'persist', has 3 phases: 'before', 'during', and 'after' (in that
721        order, of course).  These events will be fired internally by the
722        Reactor.
723
724        An implementor of this interface must only implement those events
725        described here.
726
727        Callbacks registered for the "before" phase may return either None or a
728        Deferred.  The "during" phase will not execute until all of the
729        Deferreds from the "before" phase have fired.
730
731        Once the "during" phase is running, all of the remaining triggers must
732        execute; their return values must be ignored.
733
734        @param phase: a time to call the event -- either the string 'before',
735                      'after', or 'during', describing when to call it
736                      relative to the event's execution.
737
738        @param eventType: this is a string describing the type of event.
739
740        @param callable: the object to call before shutdown.
741
742        @param args: the arguments to call it with.
743
744        @param kw: the keyword arguments to call it with.
745
746        @return: an ID that can be used to remove this call with
747                 removeSystemEventTrigger.
748        """
749
750    def removeSystemEventTrigger(triggerID):
751        """
752        Removes a trigger added with addSystemEventTrigger.
753
754        @param triggerID: a value returned from addSystemEventTrigger.
755
756        @raise KeyError: If there is no system event trigger for the given
757            C{triggerID}.
758
759        @raise ValueError: If there is no system event trigger for the given
760            C{triggerID}.
761
762        @raise TypeError: If there is no system event trigger for the given
763            C{triggerID}.
764        """
765
766    def callWhenRunning(callable, *args, **kw):
767        """
768        Call a function when the reactor is running.
769
770        If the reactor has not started, the callable will be scheduled
771        to run when it does start. Otherwise, the callable will be invoked
772        immediately.
773
774        @param callable: the callable object to call later.
775
776        @param args: the arguments to call it with.
777
778        @param kw: the keyword arguments to call it with.
779
780        @return: None if the callable was invoked, otherwise a system
781                 event id for the scheduled call.
782        """
783
784
785class IReactorPluggableResolver(Interface):
786    """
787    A reactor with a pluggable name resolver interface.
788    """
789   
790    def installResolver(resolver):
791        """
792        Set the internal resolver to use to for name lookups.
793
794        @type resolver: An object implementing the L{IResolverSimple} interface
795        @param resolver: The new resolver to use.
796
797        @return: The previously installed resolver.
798        """
799
800
801class IReactorFDSet(Interface):
802    """
803    Implement me to be able to use
804    L{FileDescriptor<twisted.internet.abstract.FileDescriptor>} type resources.
805
806    This assumes that your main-loop uses UNIX-style numeric file descriptors
807    (or at least similarly opaque IDs returned from a .fileno() method)
808    """
809
810    def addReader(reader):
811        """
812        I add reader to the set of file descriptors to get read events for.
813
814        @param reader: An L{IReadDescriptor} provider that will be checked for
815                       read events until it is removed from the reactor with
816                       L{removeReader}.
817
818        @return: C{None}.
819        """
820
821    def addWriter(writer):
822        """
823        I add writer to the set of file descriptors to get write events for.
824
825        @param writer: An L{IWriteDescriptor} provider that will be checked for
826                       read events until it is removed from the reactor with
827                       L{removeWriter}.
828
829        @return: C{None}.
830        """
831
832    def removeReader(reader):
833        """
834        Removes an object previously added with L{addReader}.
835
836        @return: C{None}.
837        """
838
839    def removeWriter(writer):
840        """
841        Removes an object previously added with L{addWriter}.
842
843        @return: C{None}.
844        """
845
846    def removeAll():
847        """
848        Remove all readers and writers.
849
850        Should not remove reactor internal reactor connections (like a waker).
851
852        @return: A list of L{IReadDescriptor} and L{IWriteDescriptor} providers
853                 which were removed.
854        """
855
856    def getReaders():
857        """
858        Return the list of file descriptors currently monitored for input
859        events by the reactor.
860
861        @return: the list of file descriptors monitored for input events.
862        @rtype: C{list} of C{IReadDescriptor}
863        """
864
865    def getWriters():
866        """
867        Return the list file descriptors currently monitored for output events
868        by the reactor.
869
870        @return: the list of file descriptors monitored for output events.
871        @rtype: C{list} of C{IWriteDescriptor}
872        """
873
874
875class IListeningPort(Interface):
876    """
877    A listening port.
878    """
879
880    def startListening():
881        """
882        Start listening on this port.
883
884        @raise CannotListenError: If it cannot listen on this port (e.g., it is
885                                  a TCP port and it cannot bind to the required
886                                  port number).
887        """
888
889    def stopListening():
890        """
891        Stop listening on this port.
892
893        If it does not complete immediately, will return Deferred that fires
894        upon completion.
895        """
896
897    def getHost():
898        """
899        Get the host that this port is listening for.
900
901        @return: An L{IAddress} provider.
902        """
903
904
905class ILoggingContext(Interface):
906    """
907    Give context information that will be used to log events generated by
908    this item.
909    """
910   
911    def logPrefix():
912        """
913        @return: Prefix used during log formatting to indicate context.
914        @rtype: C{str}
915        """
916
917
918class IFileDescriptor(ILoggingContext):
919    """
920    A file descriptor.
921    """
922
923    def fileno():
924        """
925        @return: The platform-specified representation of a file-descriptor
926                 number.
927        """
928
929    def connectionLost(reason):
930        """
931        Called when the connection was lost.
932
933        This is called when the connection on a selectable object has been
934        lost.  It will be called whether the connection was closed explicitly,
935        an exception occurred in an event handler, or the other end of the
936        connection closed it first.
937
938        See also L{IHalfCloseableDescriptor} if your descriptor wants to be
939        notified separately of the two halves of the connection being closed.
940
941        @param reason: A failure instance indicating the reason why the
942                       connection was lost.  L{error.ConnectionLost} and
943                       L{error.ConnectionDone} are of special note, but the
944                       failure may be of other classes as well.
945        """
946
947class IReadDescriptor(IFileDescriptor):
948
949    def doRead():
950        """
951        Some data is available for reading on your descriptor.
952        """
953
954
955class IWriteDescriptor(IFileDescriptor):
956
957    def doWrite():
958        """
959        Some data can be written to your descriptor.
960        """
961
962
963class IReadWriteDescriptor(IReadDescriptor, IWriteDescriptor):
964    """
965    I am a L{FileDescriptor<twisted.internet.abstract.FileDescriptor>} that
966    can both read and write.
967    """
968
969
970class IHalfCloseableDescriptor(Interface):
971    """
972    A descriptor that can be half-closed.
973    """
974
975    def writeConnectionLost(reason):
976        """
977        Indicates write connection was lost.
978        """
979
980    def readConnectionLost(reason):
981        """
982        Indicates read connection was lost.
983        """
984
985
986class ISystemHandle(Interface):
987    """
988    An object that wraps a networking OS-specific handle.
989    """
990
991    def getHandle():
992        """
993        Return a system- and reactor-specific handle.
994
995        This might be a socket.socket() object, or some other type of
996        object, depending on which reactor is being used. Use and
997        manipulate at your own risk.
998
999        This might be used in cases where you want to set specific
1000        options not exposed by the Twisted APIs.
1001        """
1002
1003
1004class IConsumer(Interface):
1005    """
1006    A consumer consumes data from a producer.
1007    """
1008
1009    def registerProducer(producer, streaming):
1010        """
1011        Register to receive data from a producer.
1012
1013        This sets self to be a consumer for a producer.  When this object runs
1014        out of data (as when a send(2) call on a socket succeeds in moving the
1015        last data from a userspace buffer into a kernelspace buffer), it will
1016        ask the producer to resumeProducing().
1017
1018        For L{IPullProducer} providers, C{resumeProducing} will be called once
1019        each time data is required.
1020
1021        For L{IPushProducer} providers, C{pauseProducing} will be called
1022        whenever the write buffer fills up and C{resumeProducing} will only be
1023        called when it empties.
1024
1025        @type producer: L{IProducer} provider
1026
1027        @type streaming: C{bool}
1028        @param streaming: C{True} if C{producer} provides L{IPushProducer},
1029        C{False} if C{producer} provides L{IPullProducer}.
1030
1031        @return: C{None}
1032        """
1033
1034    def unregisterProducer():
1035        """
1036        Stop consuming data from a producer, without disconnecting.
1037        """
1038
1039    def write(data):
1040        """
1041        The producer will write data by calling this method.
1042        """
1043
1044class IFinishableConsumer(IConsumer):
1045    """
1046    A Consumer for producers that finish.
1047    """
1048   
1049    def finish():
1050        """
1051        The producer has finished producing.
1052        """
1053
1054class IProducer(Interface):
1055    """
1056    A producer produces data for a consumer.
1057
1058    Typically producing is done by calling the write method of an class
1059    implementing L{IConsumer}.
1060    """
1061
1062    def stopProducing():
1063        """
1064        Stop producing data.
1065
1066        This tells a producer that its consumer has died, so it must stop
1067        producing data for good.
1068        """
1069
1070
1071class IPushProducer(IProducer):
1072    """
1073    A push producer, also known as a streaming producer is expected to
1074    produce (write to this consumer) data on a continous basis, unless
1075    it has been paused. A paused push producer will resume producing
1076    after its resumeProducing() method is called.   For a push producer
1077    which is not pauseable, these functions may be noops.
1078    """
1079
1080    def pauseProducing():
1081        """
1082        Pause producing data.
1083
1084        Tells a producer that it has produced too much data to process for
1085        the time being, and to stop until resumeProducing() is called.
1086        """
1087    def resumeProducing():
1088        """
1089        Resume producing data.
1090
1091        This tells a producer to re-add itself to the main loop and produce
1092        more data for its consumer.
1093        """
1094
1095class IPullProducer(IProducer):
1096    """
1097    A pull producer, also known as a non-streaming producer, is
1098    expected to produce data each time resumeProducing() is called.
1099    """
1100
1101    def resumeProducing():
1102        """
1103        Produce data for the consumer a single time.
1104
1105        This tells a producer to produce data for the consumer once
1106        (not repeatedly, once only). Typically this will be done
1107        by calling the consumer's write() method a single time with
1108        produced data.
1109        """
1110
1111class IProtocol(Interface):
1112
1113    def dataReceived(data):
1114        """
1115        Called whenever data is received.
1116
1117        Use this method to translate to a higher-level message.  Usually, some
1118        callback will be made upon the receipt of each complete protocol
1119        message.
1120
1121        @param data: a string of indeterminate length.  Please keep in mind
1122            that you will probably need to buffer some data, as partial
1123            (or multiple) protocol messages may be received!  I recommend
1124            that unit tests for protocols call through to this method with
1125            differing chunk sizes, down to one byte at a time.
1126        """
1127
1128    def connectionLost(reason):
1129        """
1130        Called when the connection is shut down.
1131
1132        Clear any circular references here, and any external references
1133        to this Protocol.  The connection has been closed. The C{reason}
1134        Failure wraps a L{twisted.internet.error.ConnectionDone} or
1135        L{twisted.internet.error.ConnectionLost} instance (or a subclass
1136        of one of those).
1137
1138        @type reason: L{twisted.python.failure.Failure}
1139        """
1140
1141    def makeConnection(transport):
1142        """
1143        Make a connection to a transport and a server.
1144        """
1145
1146    def connectionMade():
1147        """
1148        Called when a connection is made.
1149
1150        This may be considered the initializer of the protocol, because
1151        it is called when the connection is completed.  For clients,
1152        this is called once the connection to the server has been
1153        established; for servers, this is called after an accept() call
1154        stops blocking and a socket has been received.  If you need to
1155        send any greeting or initial message, do it here.
1156        """
1157
1158
1159class IProcessProtocol(Interface):
1160    """
1161    Interface for process-related event handlers.
1162    """
1163
1164    def makeConnection(process):
1165        """
1166        Called when the process has been created.
1167
1168        @type process: L{IProcessTransport} provider
1169        @param process: An object representing the process which has been
1170            created and associated with this protocol.
1171        """
1172
1173
1174    def childDataReceived(childFD, data):
1175        """
1176        Called when data arrives from the child process.
1177
1178        @type childFD: C{int}
1179        @param childFD: The file descriptor from which the data was
1180            received.
1181
1182        @type data: C{str}
1183        @param data: The data read from the child's file descriptor.
1184        """
1185
1186
1187    def childConnectionLost(childFD):
1188        """
1189        Called when a file descriptor associated with the child process is
1190        closed.
1191
1192        @type childFD: C{int}
1193        @param childFD: The file descriptor which was closed.
1194        """
1195
1196
1197    def processExited(reason):
1198        """
1199        Called when the child process exits.
1200
1201        @type reason: L{twisted.python.failure.Failure}
1202        @param reason: A failure giving the reason the child process
1203            terminated.  The type of exception for this failure is either
1204            L{twisted.internet.error.ProcessDone} or
1205            L{twisted.internet.error.ProcessTerminated}.
1206
1207        @since: 8.2
1208        """
1209
1210
1211    def processEnded(reason):
1212        """
1213        Called when the child process exits and all file descriptors associated
1214        with it have been closed.
1215
1216        @type reason: L{twisted.python.failure.Failure}
1217        @param reason: A failure giving the reason the child process
1218            terminated.  The type of exception for this failure is either
1219            L{twisted.internet.error.ProcessDone} or
1220            L{twisted.internet.error.ProcessTerminated}.
1221        """
1222
1223
1224
1225class IHalfCloseableProtocol(Interface):
1226    """
1227    Implemented to indicate they want notification of half-closes.
1228
1229    TCP supports the notion of half-closing the connection, e.g.
1230    closing the write side but still not stopping reading. A protocol
1231    that implements this interface will be notified of such events,
1232    instead of having connectionLost called.
1233    """
1234
1235    def readConnectionLost():
1236        """
1237        Notification of the read connection being closed.
1238
1239        This indicates peer did half-close of write side. It is now
1240        the responsiblity of the this protocol to call
1241        loseConnection().  In addition, the protocol MUST make sure a
1242        reference to it still exists (i.e. by doing a callLater with
1243        one of its methods, etc.)  as the reactor will only have a
1244        reference to it if it is writing.
1245
1246        If the protocol does not do so, it might get garbage collected
1247        without the connectionLost method ever being called.
1248        """
1249
1250    def writeConnectionLost():
1251        """
1252        Notification of the write connection being closed.
1253
1254        This will never be called for TCP connections as TCP does not
1255        support notification of this type of half-close.
1256        """
1257
1258
1259class IProtocolFactory(Interface):
1260    """
1261    Interface for protocol factories.
1262    """
1263
1264    def buildProtocol(addr):
1265        """
1266        Called when a connection has been established to addr.
1267
1268        If None is returned, the connection is assumed to have been refused,
1269        and the Port will close the connection.
1270
1271        @type addr: (host, port)
1272        @param addr: The address of the newly-established connection
1273
1274        @return: None if the connection was refused, otherwise an object
1275                 providing L{IProtocol}.
1276        """
1277
1278    def doStart():
1279        """
1280        Called every time this is connected to a Port or Connector.
1281        """
1282
1283    def doStop():
1284        """
1285        Called every time this is unconnected from a Port or Connector.
1286        """
1287
1288
1289class ITransport(Interface):
1290    """
1291    I am a transport for bytes.
1292
1293    I represent (and wrap) the physical connection and synchronicity
1294    of the framework which is talking to the network.  I make no
1295    representations about whether calls to me will happen immediately
1296    or require returning to a control loop, or whether they will happen
1297    in the same or another thread.  Consider methods of this class
1298    (aside from getPeer) to be 'thrown over the wall', to happen at some
1299    indeterminate time.
1300    """
1301
1302    def write(data):
1303        """
1304        Write some data to the physical connection, in sequence, in a
1305        non-blocking fashion.
1306
1307        If possible, make sure that it is all written.  No data will
1308        ever be lost, although (obviously) the connection may be closed
1309        before it all gets through.
1310        """
1311
1312    def writeSequence(data):
1313        """
1314        Write a list of strings to the physical connection.
1315
1316        If possible, make sure that all of the data is written to
1317        the socket at once, without first copying it all into a
1318        single string.
1319        """
1320
1321    def loseConnection():
1322        """
1323        Close my connection, after writing all pending data.
1324
1325        Note that if there is a registered producer on a transport it
1326        will not be closed until the producer has been unregistered.
1327        """
1328
1329    def getPeer():
1330        """
1331        Get the remote address of this connection.
1332
1333        Treat this method with caution.  It is the unfortunate result of the
1334        CGI and Jabber standards, but should not be considered reliable for
1335        the usual host of reasons; port forwarding, proxying, firewalls, IP
1336        masquerading, etc.
1337
1338        @return: An L{IAddress} provider.
1339        """
1340
1341    def getHost():
1342        """
1343        Similar to getPeer, but returns an address describing this side of the
1344        connection.
1345
1346        @return: An L{IAddress} provider.
1347        """
1348
1349
1350class ITCPTransport(ITransport):
1351    """
1352    A TCP based transport.
1353    """
1354
1355    def loseWriteConnection():
1356        """
1357        Half-close the write side of a TCP connection.
1358
1359        If the protocol instance this is attached to provides
1360        IHalfCloseableProtocol, it will get notified when the operation is
1361        done. When closing write connection, as with loseConnection this will
1362        only happen when buffer has emptied and there is no registered
1363        producer.
1364        """
1365
1366    def getTcpNoDelay():
1367        """
1368        Return if C{TCP_NODELAY} is enabled.
1369        """
1370
1371    def setTcpNoDelay(enabled):
1372        """
1373        Enable/disable C{TCP_NODELAY}.
1374
1375        Enabling C{TCP_NODELAY} turns off Nagle's algorithm. Small packets are
1376        sent sooner, possibly at the expense of overall throughput.
1377        """
1378
1379    def getTcpKeepAlive():
1380        """
1381        Return if C{SO_KEEPALIVE} is enabled.
1382        """
1383
1384    def setTcpKeepAlive(enabled):
1385        """
1386        Enable/disable C{SO_KEEPALIVE}.
1387
1388        Enabling C{SO_KEEPALIVE} sends packets periodically when the connection
1389        is otherwise idle, usually once every two hours. They are intended
1390        to allow detection of lost peers in a non-infinite amount of time.
1391        """
1392
1393    def getHost():
1394        """
1395        Returns L{IPv4Address}.
1396        """
1397
1398    def getPeer():
1399        """
1400        Returns L{IPv4Address}.
1401        """
1402
1403
1404class ITLSTransport(ITCPTransport):
1405    """
1406    A TCP transport that supports switching to TLS midstream.
1407
1408    Once TLS mode is started the transport will implement L{ISSLTransport}.
1409    """
1410
1411    def startTLS(contextFactory):
1412        """
1413        Initiate TLS negotiation.
1414
1415        @param contextFactory: A context factory (see L{ssl.py<twisted.internet.ssl>})
1416        """
1417
1418class ISSLTransport(ITCPTransport):
1419    """
1420    A SSL/TLS based transport.
1421    """
1422
1423    def getPeerCertificate():
1424        """
1425        Return an object with the peer's certificate info.
1426        """
1427
1428
1429class IProcessTransport(ITransport):
1430    """
1431    A process transport.
1432    """
1433
1434    pid = Attribute(
1435        "From before L{IProcessProtocol.makeConnection} is called to before "
1436        "L{IProcessProtocol.processEnded} is called, C{pid} is an L{int} "
1437        "giving the platform process ID of this process.  C{pid} is L{None} "
1438        "at all other times.")
1439
1440    def closeStdin():
1441        """
1442        Close stdin after all data has been written out.
1443        """
1444
1445    def closeStdout():
1446        """
1447        Close stdout.
1448        """
1449
1450    def closeStderr():
1451        """
1452        Close stderr.
1453        """
1454
1455    def closeChildFD(descriptor):
1456        """
1457        Close a file descriptor which is connected to the child process, identified
1458        by its FD in the child process.
1459        """
1460
1461    def writeToChild(childFD, data):
1462        """
1463        Similar to L{ITransport.write} but also allows the file descriptor in
1464        the child process which will receive the bytes to be specified.
1465
1466        This is not available on all platforms.
1467
1468        @type childFD: C{int}
1469        @param childFD: The file descriptor to which to write.
1470
1471        @type data: C{str}
1472        @param data: The bytes to write.
1473
1474        @return: C{None}
1475        """
1476
1477    def loseConnection():
1478        """
1479        Close stdin, stderr and stdout.
1480        """
1481
1482    def signalProcess(signalID):
1483        """
1484        Send a signal to the process.
1485
1486        @param signalID: can be
1487          - one of C{\"HUP\"}, C{\"KILL\"}, C{\"STOP\"}, or C{\"INT\"}.
1488              These will be implemented in a
1489              cross-platform manner, and so should be used
1490              if possible.
1491          - an integer, where it represents a POSIX
1492              signal ID.
1493
1494        @raise twisted.internet.error.ProcessExitedAlready: The process has
1495        already exited.
1496        """
1497
1498
1499class IServiceCollection(Interface):
1500    """
1501    An object which provides access to a collection of services.
1502    """
1503
1504    def getServiceNamed(serviceName):
1505        """
1506        Retrieve the named service from this application.
1507
1508        Raise a C{KeyError} if there is no such service name.
1509        """
1510
1511    def addService(service):
1512        """
1513        Add a service to this collection.
1514        """
1515
1516    def removeService(service):
1517        """
1518        Remove a service from this collection.
1519        """
1520
1521
1522class IUDPTransport(Interface):
1523    """
1524    Transport for UDP DatagramProtocols.
1525    """
1526
1527    def write(packet, addr=None):
1528        """
1529        Write packet to given address.
1530
1531        @param addr: a tuple of (ip, port). For connected transports must
1532                     be the address the transport is connected to, or None.
1533                     In non-connected mode this is mandatory.
1534
1535        @raise twisted.internet.error.MessageLengthError: C{packet} was too
1536        long.
1537        """
1538
1539    def connect(host, port):
1540        """
1541        Connect the transport to an address.
1542
1543        This changes it to connected mode. Datagrams can only be sent to
1544        this address, and will only be received from this address. In addition
1545        the protocol's connectionRefused method might get called if destination
1546        is not receiving datagrams.
1547
1548        @param host: an IP address, not a domain name ('127.0.0.1', not 'localhost')
1549        @param port: port to connect to.
1550        """
1551
1552    def getHost():
1553        """
1554        Returns L{IPv4Address}.
1555        """
1556
1557    def stopListening():
1558        """
1559        Stop listening on this port.
1560
1561        If it does not complete immediately, will return L{Deferred} that fires
1562        upon completion.
1563        """
1564
1565
1566class IUDPConnectedTransport(Interface):
1567    """
1568    DEPRECATED. Transport for UDP ConnectedPacketProtocols.
1569    """
1570
1571    def write(packet):
1572        """
1573        Write packet to address we are connected to.
1574        """
1575
1576    def getHost():
1577        """
1578        Returns L{UNIXAddress}.
1579        """
1580
1581
1582class IUNIXDatagramTransport(Interface):
1583    """
1584    Transport for UDP PacketProtocols.
1585    """
1586
1587    def write(packet, address):
1588        """
1589        Write packet to given address.
1590        """
1591
1592    def getHost():
1593        """
1594        Returns L{UNIXAddress}.
1595        """
1596
1597
1598class IUNIXDatagramConnectedTransport(Interface):
1599    """
1600    Transport for UDP ConnectedPacketProtocols.
1601    """
1602
1603    def write(packet):
1604        """
1605        Write packet to address we are connected to.
1606        """
1607
1608    def getHost():
1609        """
1610        Returns L{UNIXAddress}.
1611        """
1612
1613    def getPeer():
1614        """
1615        Returns L{UNIXAddress}.
1616        """
1617
1618
1619class IMulticastTransport(Interface):
1620    """
1621    Additional functionality for multicast UDP.
1622    """
1623
1624    def getOutgoingInterface():
1625        """
1626        Return interface of outgoing multicast packets.
1627        """
1628
1629    def setOutgoingInterface(addr):
1630        """
1631        Set interface for outgoing multicast packets.
1632
1633        Returns Deferred of success.
1634        """
1635
1636    def getLoopbackMode():
1637        """
1638        Return if loopback mode is enabled.
1639        """
1640
1641    def setLoopbackMode(mode):
1642        """
1643        Set if loopback mode is enabled.
1644        """
1645
1646    def getTTL():
1647        """
1648        Get time to live for multicast packets.
1649        """
1650
1651    def setTTL(ttl):
1652        """
1653        Set time to live on multicast packets.
1654        """
1655
1656    def joinGroup(addr, interface=""):
1657        """
1658        Join a multicast group. Returns L{Deferred} of success or failure.
1659
1660        If an error occurs, the returned L{Deferred} will fail with
1661        L{error.MulticastJoinError}.
1662        """
1663
1664    def leaveGroup(addr, interface=""):
1665        """
1666        Leave multicast group, return L{Deferred} of success.
1667        """
Note: See TracBrowser for help on using the browser.