[Twisted-Python] sample tac that needs a critique

Don Smith donwsmith at gmail.com
Fri Mar 3 20:01:46 EST 2006


Okay, I've made some huge progress, I think with my Telnet connection stuff.
I'm curious what the Twisted pros think of this..syntax, if it is correct,
etc. Here is what I'm going for, I want to have this application running,
which provides an XML-RPC interface for 'controlling' it. The server, right
now, can start Telnet clients at the request of XML-RPC clients. This seems
to work, however, I'd also like to be able to stop said Telnet clients, or
see which ones are running, etc. I can't wrap my brain around how to
accomplish those bits of functionality. I've included the .tac file below
for reference.

Thanks so much for your assistance!

-Don


#Try to build a Twisted Connector Service the twisted way
from twisted.application import internet, service
from twisted.web import resource, server, static, xmlrpc
import re, time


from EventTypes import Event
connectiontypes = {'TelnetConnection':'A telnet client connection.',
'FileTailConnection':'Facilitates tailing a log file'}


class Connection:
    def __init__(self,name):
        # Constructor
        self.name=name
    #print "Connection name: %s" % self.name
    self.status=False

    def setStatus (self,status):
        self.status=status

####################
# TCP Client Stuff
####################
from twisted.internet.protocol import Protocol, ReconnectingClientFactory
from twisted.conch.telnet import Telnet


##########################
# Telnet Clients
##########################
class TelnetClient(Telnet):
    "TelnetClient class."
    def connectionMade(self):
        #print "connection made to %s" % self.factory.name
    #if the cmd variable was set in the calling factory, lets iterate over
it.
    if self.factory.cmd:
        for cmd in self.factory.cmd:
            if "sleep" in cmd:
                #print re.compile
('(?P<sleeptime>(\d+))').search(cmd).group('sleeptime')
                sleeptime = int(re.compile
('(?P<sleeptime>(\d+))').search(cmd).group('sleeptime'))
                time.sleep(sleeptime)
            else:
                self.write(cmd)


    def write(self, data):
    #print data
    Telnet._write(self, data+"\r\n")


    def dataReceived(self, data):
        print "received:", data
    #always send data to the eventQueue
    self.factory.eventQueue.insert(Event(data, self.factory.name))
    #check if we should send any commands based on data received
    if self.factory.expect:
        #check if any of the expect dictionary keys are in data
        for key in self.factory.expect.keys():
            if key in data:
                for cmd in self.factory.expect[key]:
                if "sleep" in cmd:
                        sleeptime = int(re.compile
('(?P<sleeptime>(\d+))').search(cmd).group('sleeptime'))
                        time.sleep(sleeptime)
                    else:
                        self.write(cmd)



class TelnetConnection(Connection, ReconnectingClientFactory):
    "Telnets to host:port and executes cmd. cmd"
    protocol = TelnetClient
    def  __init__(self, name, eventQueue, cmd=None, expect=None):
        Connection.__init__(self, name)
    self.cmd = cmd
    self.expect = expect
    self.eventQueue = eventQueue




    def clientConnectionFailed(self, connector, reason):
        print 'connection failed:', reason.getErrorMessage()


    def clientConnectionLost(self, connector, reason):
        print 'connection lost:', reason.getErrorMessage()


class ManagerService(service.Service):
    def __init__(self):
        pass

    # some XML-RPC function calls for twisted server
    def stop(self):
        return 'Shutdown initiated'

    def getConnectionTypes(self):
        """Return connection types"""
    return connectiontypes

    def xmlrpc_getActiveConnections(self):
        """Return all active connections"""

    def getConnectionStatus(self, connection):
        return "connection status"


    def getResource(self):
        """Return sum of arguments."""
    r = resource.Resource()
    x = xmlrpc.XMLRPC()
    x.xmlrpc_stop = self.stop
    x.xmlrpc_getConnectionStatus = self.getConnectionStatus
    x.xmlrpc_startTelnet = self.startTelnet

        r.putChild('RPC2', x)
        return r

    def startTelnet(self, host, port, name, queue, command, script):
        from twisted.internet import reactor
    from EventQueue import Queue
        #Create the Event Queue object
    self.queue = queue

        self.queue = Queue()

        reactor.connectTCP(host, int(port), TelnetConnection(name,self.queue
,command,script))
    return "%s started" % name


#create an application instance
application = service.Application('connectorservice', uid=1, gid=1)
m = ManagerService()
serviceCollection = service.IServiceCollection(application)
internet.TCPServer(7090, server.Site(m.getResource())
                   ).setServiceParent(serviceCollection)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://twistedmatrix.com/pipermail/twisted-python/attachments/20060303/52ce2635/attachment.htm 


More information about the Twisted-Python mailing list