Beispiel #1
0
    def listen(self):
        assert self._port is None
        assert self.avatarClass is not None
        # FIXME: we should hand a username and password to log in with to
        # the job process instead of allowing anonymous
        checker = checkers.FlexibleCredentialsChecker()
        checker.allowPasswordless(True)
        p = portal.Portal(self, [checker])
        f = pb.PBServerFactory(p)
        try:
            os.unlink(self._socketPath)
        except OSError:
            pass

        # Rather than a listenUNIX(), we use listenWith so that we can specify
        # our particular Port, which creates Transports that we know how to
        # pass FDs over.
        self.debug("Listening for FD's on unix socket %s", self._socketPath)
        port = reactor.listenWith(fdserver.FDPort, self._socketPath, f)
        self._port = port
Beispiel #2
0
def main():
    """..."""
    from twisted.spread import pb
    from twisted.application import service
    from twisted.cred.authorizer import DefaultAuthorizer
    from twisted.internet import reactor, app

    evManager = EventManager()
    sharedObjectRegistry = {}

    log = TextLogView(evManager)
    timer = TimerController(evManager, reactor)
    #clientContr = NetworkClientController( evManager, sharedObjectRegistry )
    clientView = NetworkClientView(evManager, sharedObjectRegistry)
    game = Game(evManager)

    #from twisted.spread.jelly import globalSecurity
    #globalSecurity.allowModules( network )

    application = app.Application("myServer")
    auth = DefaultAuthorizer(application)

    #create a service, tell it to generate NetworkClientControllers
    serv = pb.Service("myService", application, auth)
    serv.perspectiveClass = NetworkClientController

    #create a Perspective
    per1 = serv.createPerspective("perspective1")
    per1.PostInit(evManager, sharedObjectRegistry)

    #create an Identity
    iden1 = auth.createIdentity("user1")
    iden1.setPassword("asdf")
    #allow it access to the perspective named perspective1
    iden1.addKeyByString("myService", "perspective1")
    auth.addIdentity(iden1)

    #application.listenTCP(8000, pb.BrokerFactory(clientContr) )
    application.listenTCP(8000, pb.PBServerFactory(pb.AuthRoot(auth)))

    application.run(save=0)
    def setUp(self, authentication=False):
        SMPPServerTestCases.setUp(self)

        # Initiating config objects without any filename
        self.SMPPServerPBConfigInstance = SMPPServerPBConfig()
        self.SMPPServerPBConfigInstance.authentication = authentication

        # Launch the SMPPServerPB
        pbRoot = SMPPServerPB(self.SMPPServerPBConfigInstance)
        pbRoot.addSmpps(self.smpps_factory)

        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbPort = self.PBServer.getHost().port
Beispiel #4
0
def daemon_main(self):

    reactor.listenTCPonExistingFD = listenTCPonExistingFD

    reactor.listenTCPonExistingFD(reactor,
                                  fd=self.socket_rpc.fileno(),
                                  factory=pb.PBServerFactory(rpc_server))

    for i in range(config.processes):
        subprocess = spawnT2W(self.childFDs, self.fds_https, self.fds_http)
        subprocesses.append(subprocess.pid)

    if config.debugmode:
        if config.debugtostdout:
            log.startLogging(sys.stdout)
    else:
        log.startLogging(log.NullFile)

    sys.excepthook = MailException

    reactor.run()
Beispiel #5
0
    def setUp(self, authentication = False):
        # Initiating config objects without any filename
        # will lead to setting defaults and that's what we
        # need to run the tests
        self.SMPPClientPBConfigInstance = SMPPClientPBConfig()
        self.SMPPClientPBConfigInstance.authentication = authentication
        AMQPServiceConfigInstance = AmqpConfig()
        AMQPServiceConfigInstance.reconnectOnConnectionLoss = False

        # Launch AMQP Broker
        self.amqpBroker = AmqpFactory(AMQPServiceConfigInstance)
        self.amqpBroker.preConnect()
        self.amqpClient = reactor.connectTCP(AMQPServiceConfigInstance.host, AMQPServiceConfigInstance.port, self.amqpBroker)

        # Wait for AMQP Broker connection to get ready
        yield self.amqpBroker.getChannelReadyDeferred()

        # Launch the client manager server
        pbRoot = SMPPClientManagerPB()
        pbRoot.setConfig(self.SMPPClientPBConfigInstance)
        yield pbRoot.addAmqpBroker(self.amqpBroker)
        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbPort = self.PBServer.getHost().port

        # Default SMPPClientConfig
        defaultSMPPClientId = '001-testconnector'

        self.defaultConfig = SMPPClientConfig(id=defaultSMPPClientId,
                                              username='******',
                                              reconnectOnConnectionFailure=True,
                                              port=9002,
                                              )
Beispiel #6
0
def main():
    """
    Run a simple echo pb server to test the checker. It defines a custom query
    for dealing with sqlite special quoting, but otherwise it's a
    straightforward use of the object.

    You can test it running C{pbechoclient.py}.
    """
    import sys
    from twisted.python import log
    log.startLogging(sys.stdout)
    import os
    if os.path.isfile('testcred'):
        os.remove('testcred')
    from twisted.enterprise import adbapi
    pool = adbapi.ConnectionPool('pysqlite2.dbapi2', 'testcred')
    # Create the table that will be used
    query1 = """CREATE TABLE user (
            username string,
            password string
        )"""
    # Insert a test user
    query2 = """INSERT INTO user VALUES ('guest', 'guest')"""

    def cb(res):
        pool.runQuery(query2)

    pool.runQuery(query1).addCallback(cb)

    checker = DBCredentialsChecker(
        pool.runQuery,
        query="SELECT username, password FROM user WHERE username = ?")
    from twisted.cred.portal import Portal

    import pbecho
    from twisted.spread import pb
    portal = Portal(pbecho.SimpleRealm())
    portal.registerChecker(checker)
    reactor.listenTCP(pb.portno, pb.PBServerFactory(portal))
Beispiel #7
0
def run_server ():
	reactor.listenTCP(8789, pb.PBServerFactory(ExperimentMarshal()))
	log.msg("PB listening on port 8789")

	factory = WampServerFactory("ws://localhost:9000")
	factory.protocol = LabspiralServerProtocol
	listenWS(factory)
	log.msg("WS listening on port 9000")

	ExperimentMarshal.publish = factory.dispatch

	root = resource.Resource()
	root.putChild("", Root())
	root.putChild("experiments", ExperimentList())
	root.putChild("resources", static.File("resources"))
	site = server.Site(root)
	reactor.listenTCP(8001, site)
	log.msg("HTTP listening on port 8001")

	reactor.run()

	log.msg("Server stopped")
Beispiel #8
0
def makeService(config):
    # finger on port 79
    s = service.MultiService()
    f = FingerService(config["file"])
    h = strports.service("tcp:1079", IFingerFactory(f))
    h.setServiceParent(s)

    # website on port 8000
    r = resource.IResource(f)
    r.templateDirectory = config["templates"]
    site = server.Site(r)
    j = strports.service("tcp:8000", site)
    j.setServiceParent(s)

    # ssl on port 443
    #    if config.get('ssl'):
    #        k = strports.service(
    #            "ssl:port=443:certKey=cert.pem:privateKey=key.pem", site
    #        )
    #        k.setServiceParent(s)

    # irc fingerbot
    if "ircnick" in config:
        i = IIRCClientFactory(f)
        i.nickname = config["ircnick"]
        ircserver = config["ircserver"]
        b = internet.ClientService(
            endpoints.HostnameEndpoint(reactor, ircserver, 6667), i)
        b.setServiceParent(s)

    # Pespective Broker on port 8889
    if "pbport" in config:
        m = internet.StreamServerEndpointService(
            endpoints.TCP4ServerEndpoint(reactor, int(config["pbport"])),
            pb.PBServerFactory(IPerspectiveFinger(f)),
        )
        m.setServiceParent(s)

    return s
Beispiel #9
0
    def startInterceptorPBService(self):
        """Start Interceptor PB server"""

        InterceptorPBConfigInstance = InterceptorPBConfig(self.options['config'])
        self.components['interceptor-pb-factory'] = InterceptorPB(InterceptorPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components['interceptor-pb-factory']))
        if InterceptorPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(InterceptorPBConfigInstance.admin_username,
                      InterceptorPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components['interceptor-pb-server'] = reactor.listenTCP(
            InterceptorPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=InterceptorPBConfigInstance.bind)
Beispiel #10
0
    def setUp(self):
        self.services = []
        self.clients = []
        self.servers = []

        # Start a server and append to self.servers
        self.sroot = PBRemoteEngineRootFromService(self)
        self.sf = pb.PBServerFactory(self.sroot)
        self.servers.append(reactor.listenTCP(10201, self.sf))

        # Start an EngineService and append to services/client
        self.engineService = es.EngineService()
        ef = PBEngineClientFactory(self.engineService)
        client = reactor.connectTCP('127.0.0.1', 10201, ef)
        self.clients.append(client)
        self.services.append(self.engineService)
        self.engineService.startService()

        # Create and returna Deferred that will fire when self.registerEngine
        # is called.  By returning this deferred, the actual tests will not
        # be run until the client has connected and is registered.
        self.setUpDeferred = defer.Deferred()
        return self.setUpDeferred
Beispiel #11
0
    def startSMPPClientManagerPBService(self):
        "Start SMPP Client Manager PB server"

        SMPPClientPBConfigInstance = SMPPClientPBConfig(self.options['config'])
        self.components['smppcm-pb-factory'] = SMPPClientManagerPB()
        self.components['smppcm-pb-factory'].setConfig(
            SMPPClientPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components['smppcm-pb-factory']))
        if SMPPClientPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(SMPPClientPBConfigInstance.admin_username,
                      SMPPClientPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components['smppcm-pb-server'] = reactor.listenTCP(
            SMPPClientPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=SMPPClientPBConfigInstance.bind)

        # AMQP Broker is used to listen to submit_sm queues and publish to deliver_sm/dlr queues
        self.components['smppcm-pb-factory'].addAmqpBroker(
            self.components['amqp-broker-factory'])
        self.components['smppcm-pb-factory'].addRedisClient(
            self.components['rc'])
        self.components['smppcm-pb-factory'].addRouterPB(
            self.components['router-pb-factory'])

        # Add interceptor if enabled:
        if 'interceptor-pb-client' in self.components:
            self.components['smppcm-pb-factory'].addInterceptorPBClient(
                self.components['interceptor-pb-client'])
    def __init__(self, basedir, configFileName="master.cfg"):
        service.MultiService.__init__(self)
        self.setName("buildmaster")
        self.basedir = basedir
        self.configFileName = configFileName

        # the dispatcher is the realm in which all inbound connections are
        # looked up: slave builders, change notifications, status clients, and
        # the debug port
        dispatcher = Dispatcher()
        dispatcher.master = self
        self.dispatcher = dispatcher
        self.checker = checkers.InMemoryUsernamePasswordDatabaseDontUse()
        # the checker starts with no user/passwd pairs: they are added later
        p = portal.Portal(dispatcher)
        p.registerChecker(self.checker)
        self.slaveFactory = pb.PBServerFactory(p)
        self.slaveFactory.unsafeTracebacks = True  # let them see exceptions

        self.slavePortnum = None
        self.slavePort = None

        self.botmaster = BotMaster()
        self.botmaster.setName("botmaster")
        self.botmaster.setServiceParent(self)
        dispatcher.botmaster = self.botmaster

        self.status = Status(self.botmaster, self.basedir)

        self.statusTargets = []

        # this ChangeMaster is a dummy, only used by tests. In the real
        # buildmaster, where the BuildMaster instance is activated
        # (startService is called) by twistd, this attribute is overwritten.
        self.useChanges(ChangeMaster())

        self.readConfig = False
Beispiel #13
0
def makeService(config):
    # finger on port 79
    s = service.MultiService()
    f = FingerService(config['file'])
    h = internet.TCPServer(1079, IFingerFactory(f))
    h.setServiceParent(s)


    # website on port 8000
    r = resource.IResource(f)
    r.templateDirectory = config['templates']
    site = server.Site(r)
    j = internet.TCPServer(8000, site)
    j.setServiceParent(s)

    # ssl on port 443
#    if config.get('ssl'):
#        k = internet.SSLServer(443, site, ServerContextFactory())
#        k.setServiceParent(s)

    # irc fingerbot
    if 'ircnick' in config:
        i = IIRCClientFactory(f)
        i.nickname = config['ircnick']
        ircserver = config['ircserver']
        b = internet.TCPClient(ircserver, 6667, i)
        b.setServiceParent(s)

    # Pespective Broker on port 8889
    if 'pbport' in config:
        m = internet.TCPServer(
            int(config['pbport']),
            pb.PBServerFactory(IPerspectiveFinger(f)))
        m.setServiceParent(s)

    return s
Beispiel #14
0
    def __init__(self, map, total_players):
        import player

        players = [player.PlayerCacheable(i) for i in range(total_players)]
        import game

        self.game = game.Game(players=players, server=self)
        map.setup()
        self.game.set_map(map)
        self.ai_players = []

        from twisted.cred.portal import Portal
        from twisted.cred.checkers import (
            AllowAnonymousAccess,
            InMemoryUsernamePasswordDatabaseDontUse,
        )

        portal = Portal(RequestClientRealm(self))
        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "guest")
        # 	checker = AllowAnonymousAccess()
        portal.registerChecker(checker)
        self.listening_port = reactor.listenTCP(pb.portno,
                                                pb.PBServerFactory(portal))
Beispiel #15
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
This shows an example of a bare-bones distributed web set up.  The "master" and
"slave" parts will usually be in different files -- they are here together only
for brevity of illustration.  In normal usage they would each run in a separate
process.

Usage:
    $ python silly-web.py

Then visit http://localhost:19988/.
"""

from twisted.internet import reactor, protocol
from twisted.web import server, distrib, static
from twisted.spread import pb

# The "master" server
site = server.Site(distrib.ResourceSubscription('unix', '.rp'))
reactor.listenTCP(19988, site)

# The "slave" server
fact = pb.PBServerFactory(distrib.ResourcePublisher(server.Site(static.File('static'))))

reactor.listenUNIX('./.rp', fact)
reactor.run()
Beispiel #16
0
def makeService (options):
	"""
	This will be called from twistd plugin system and we are supposed to
	create and return our application service.
	"""

	application = service.IServiceCollection(
		service.Application("octopus_server", uid = 1, gid = 1)
	)

	wamp_service = WampService(
		int(options["wampport"]), 
		debug = False
	)
	wamp_service.setServiceParent(application)

	ExperimentMarshal.publish = wamp_service.factory.dispatch
	internet.TCPServer(
		int(options["pbport"]),
		pb.PBServerFactory(ExperimentMarshal())
	).setServiceParent(application)
	
	resources_path = os.path.join(os.path.dirname(__file__), "resources")

	# class ExperimentListRealm (object):
		# """
		# A realm which gives out L{ExperimentList} instances for authenticated
		# users.
		# """
		# implements(IRealm)

		# def requestAvatar(self, avatarId, mind, *interfaces):
			# if resource.IResource in interfaces:
				# return resource.IResource, ExperimentList(), lambda: None
			# raise NotImplementedError()

	#from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
	#checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe='blow')]
	#wrapper = guard.HTTPAuthSessionWrapper(
	#	Portal(ExperimentListRealm(), checkers),
	#	[guard.DigestCredentialFactory('md5', 'example.com')])

	# Read in preconfigured scripts list
	if options["scripts"] is not None:
		try:
			with open(options["scripts"]) as f:
				scripts = [line.split("\t") for line in f.readlines()]
				scripts = [(s[0], s[1].strip()) for s in scripts if len(s) is 2]
		except IOError:
			scripts = []
	else:
		scripts = []

	root = resource.Resource()
	root.putChild("", Root())
	#root.putChild("experiments", wrapper)
	root.putChild("experiments", ExperimentList())
	root.putChild("programs", ProgramList(scripts))
	root.putChild("resources", static.File(resources_path))
	site = server.Site(root)
	internet.TCPServer(
		int(options["port"]),
		site
	).setServiceParent(application)

	return application
Beispiel #17
0
    def __init__(self, http_port=None, distrib_port=None, allowForce=False):
        """Run a web server that provides Buildbot status.

        @type  http_port: int or L{twisted.application.strports} string
        @param http_port: a strports specification describing which port the
                          buildbot should use for its web server, with the
                          Waterfall display as the root page. For backwards
                          compatibility this can also be an int. Use
                          'tcp:8000' to listen on that port, or
                          'tcp:12345:interface=127.0.0.1' if you only want
                          local processes to connect to it (perhaps because
                          you are using an HTTP reverse proxy to make the
                          buildbot available to the outside world, and do not
                          want to make the raw port visible).

        @type  distrib_port: int or L{twisted.application.strports} string
        @param distrib_port: Use this if you want to publish the Waterfall
                             page using web.distrib instead. The most common
                             case is to provide a string that is an absolute
                             pathname to the unix socket on which the
                             publisher should listen
                             (C{os.path.expanduser(~/.twistd-web-pb)} will
                             match the default settings of a standard
                             twisted.web 'personal web server'). Another
                             possibility is to pass an integer, which means
                             the publisher should listen on a TCP socket,
                             allowing the web server to be on a different
                             machine entirely. Both forms are provided for
                             backwards compatibility; the preferred form is a
                             strports specification like
                             'unix:/home/buildbot/.twistd-web-pb'. Providing
                             a non-absolute pathname will probably confuse
                             the strports parser.
        @param allowForce: boolean, if True then the webserver will allow
                           visitors to trigger and cancel builds
        """

        service.MultiService.__init__(self)
        if type(http_port) is int:
            http_port = "tcp:%d" % http_port
        self.http_port = http_port
        if distrib_port is not None:
            if type(distrib_port) is int:
                distrib_port = "tcp:%d" % distrib_port
            if distrib_port[0] in "/~.":  # pathnames
                distrib_port = "unix:%s" % distrib_port
        self.distrib_port = distrib_port
        self.allowForce = allowForce

        # this will be replaced once we've been attached to a parent (and
        # thus have a basedir and can reference BASEDIR/public_html/)
        root = static.Data("placeholder", "text/plain")
        self.site = server.Site(root)
        self.childrenToBeAdded = {}

        self.setupUsualPages()

        # the following items are accessed by HtmlResource when it renders
        # each page.
        self.site.buildbot_service = self
        self.header = HEADER
        self.head_elements = HEAD_ELEMENTS[:]
        self.body_attrs = BODY_ATTRS.copy()
        self.footer = FOOTER
        self.template_values = {}

        # keep track of cached connections so we can break them when we shut
        # down. See ticket #102 for more details.
        self.channels = weakref.WeakKeyDictionary()

        if self.http_port is not None:
            s = strports.service(self.http_port, self.site)
            s.setServiceParent(self)
        if self.distrib_port is not None:
            f = pb.PBServerFactory(distrib.ResourcePublisher(self.site))
            s = strports.service(self.distrib_port, f)
            s.setServiceParent(self)
 def getFactory(cls, realm, portal):
     from twisted.spread import pb
     return pb.PBServerFactory(portal, True)
Beispiel #19
0
#! /usr/bin/python

from twisted.application import service, internet
from twisted.internet import reactor
from twisted.spread import pb
import copy2_classes  # needed to get ReceiverPond registered with Jelly


class Receiver(pb.Root):
    def remote_takePond(self, pond):
        print " got pond:", pond
        print " count %d" % pond.count()
        return "safe and sound"  # positive acknowledgement

    def remote_shutdown(self):
        reactor.stop()


application = service.Application("copy_receiver")
internet.TCPServer(8800, pb.PBServerFactory(Receiver())).setServiceParent(
    service.IServiceCollection(application))
Beispiel #20
0
#!/usr/bin/python2

import os
from twisted.spread import pb
from twisted.internet import reactor


class PBDirLister(pb.Root):
    def remote_ls(self, directory):
        try:
            return os.listdir(directory)
        except OSError:
            return []

    def remote_ls_boom(self, directory):
        return os.listdir(directory)


if __name__ == '__main__':
    reactor.listenTCP(9876, pb.PBServerFactory(PBDirLister()))
    reactor.run()
Beispiel #21
0
class ServerContextFactory:
    def getContext(self):
        """
        Create an SSL context.

        This is a sample implementation that loads a certificate from a file
        called 'server.pem'.
        """
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_certificate_file('server.pem')
        ctx.use_privatekey_file('server.pem')
        return ctx


application = service.Application('finger', uid=1, gid=1)
f = FingerService('/etc/users')
serviceCollection = service.IServiceCollection(application)
f.setServiceParent(serviceCollection)
internet.TCPServer(79, IFingerFactory(f)).setServiceParent(serviceCollection)
site = server.Site(resource.IResource(f))
internet.TCPServer(8000, site).setServiceParent(serviceCollection)
internet.SSLServer(443, site,
                   ServerContextFactory()).setServiceParent(serviceCollection)
i = IIRCClientFactory(f)
i.nickname = 'fingerbot'
internet.TCPClient('irc.freenode.org', 6667,
                   i).setServiceParent(serviceCollection)
internet.TCPServer(8889, pb.PBServerFactory(
    IPerspectiveFinger(f))).setServiceParent(serviceCollection)
    def remote_reference(self):
        return self.o

    def remote_local(self, obj):
        d = obj.callRemote("hello")
        d.addCallback(self._local_success)

    def _local_success(self, result):
        if result != "hello, world":
            raise ValueError("%r != %r" % (result, "hello, world"))

    def remote_receive(self, obj):
        expected = [1, 1.5, "hi", u"hi", {1: 2}]
        if obj != expected:
            raise ValueError("%r != %r" % (obj, expected))

    def remote_self(self, obj):
        if obj != self:
            raise ValueError("%r != %r" % (obj, self))

    def remote_copy(self, x):
        o = flavors.Copyable()
        o.x = x
        return o


if __name__ == '__main__':
    reactor.listenTCP(8789, pb.PBServerFactory(Interop()))
    reactor.run()
Beispiel #23
0
def main():
    reactor.listenTCP(8800, pb.PBServerFactory(One()))
    reactor.run()
Beispiel #24
0
 def start_server(self):
     reactor.listenTCP(int(self.port), pb.PBServerFactory(self))
     reactor.run()
    def perspective_get(self, arg):
        self.queue.get(arg)
        return arg


class MyRealm:
    '''
    The realm handles the user authentications, we could have different
    perspectives for the producer and the consumer where each would have
    access to its methods.
    '''
    implements(portal.IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        assert pb.IPerspective in interfaces
        return pb.IPerspective, MyPerspective(avatarId), lambda: None


p = portal.Portal(MyRealm())
c1 = checkers.InMemoryUsernamePasswordDatabaseDontUse(producer="prod",
                                                      consumer="cons")
p.registerChecker(c1)
q = Queue('q1')
m = Monitor(q)

reactor.listenTCP(8800, pb.PBServerFactory(p))
t = task.LoopingCall(stackless.schedule).start(0.0001)
re = stackless.tasklet(reactor.run)()
stackless.run()
Beispiel #26
0
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

from twisted.internet import reactor
from twisted.spread import pb


class Echoer(pb.Root):
    def remote_echo(self, st):
        print("echoing:", st)
        return st


if __name__ == "__main__":
    reactor.listenTCP(8789, pb.PBServerFactory(Echoer()))
    reactor.run()
Beispiel #27
0
#! /usr/bin/python
from twisted.spread import pb


class Two(pb.Referenceable):
    def remote_three(self, arg):
        print "Two.three was given", arg


class One(pb.Root):
    def remote_getTwo(self):
        two = Two()
        print "returning a Two called", two
        return two


from twisted.internet import reactor
reactor.listenTCP(8800, pb.PBServerFactory(One()))
reactor.run()
Beispiel #28
0
    def perspective_deleteItem(self, index):
        return self.todoList.deleteItem(index)


class TestRealm(object):
    implements(portal.IRealm)

    def __init__(self, todoList):
        self.todoList = todoList

    def requestAvatar(self, avatarId, mind, *interfaces):
        if not pb.IPerspective in interfaces:
            raise NotImplementedError, "No supported avatar interface."
        else:
            if avatarId == 'admin':
                avatar = AdminPerspective(self.todoList)
            else:
                avatar = UserPerspective(self.todoList)
            return pb.IPerspective, avatar, lambda: None


if __name__ == "__main__":
    import sys
    from twisted.internet import reactor
    p = portal.Portal(TestRealm(TodoList()))
    p.registerChecker(
        checkers.InMemoryUsernamePasswordDatabaseDontUse(admin='aaa',
                                                         guest='bbb'))
    reactor.listenTCP(8789, pb.PBServerFactory(p))
    reactor.run()
Beispiel #29
0
def start(server):
    reactor.listenTCP(8800, pb.PBServerFactory(server))
    #reactor.listenTCP(8800, pb.PBServerFactory(CrawlerServer()))
    reactor.run()
Beispiel #30
0
 def _setUpServer(self):
     self.serverFactory = pb.PBServerFactory(SimpleRoot())
     self.serverFactory.unsafeTracebacks = self.unsafeTracebacks
     self.serverPort = reactor.listenTCP(0,
                                         self.serverFactory,
                                         interface="127.0.0.1")