Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(126)

Side by Side Diff: third_party/twisted_8_1/twisted/internet/interfaces.py

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

Powered by Google App Engine
This is Rietveld 408576698