def test_createOrGetApplicationWithTapFile(self): """ Ensure that the createOrGetApplication call that 'twistd -f foo.tap' makes will load the Application out of foo.tap. """ config = twistd.ServerOptions() config.parseOptions(['-f', self.tapfile]) application = CrippledApplicationRunner(config).createOrGetApplication() self.assertEquals(service.IService(application).name, 'Hi!')
def postApplication(self): """ Start the application and run the reactor. """ service.IService(self.application).privilegedStartService() app.startApplication(self.application, not self.config["no_save"]) app.startApplication(internet.TimerService(0.1, lambda: None), 0) self.startReactor(None, self.oldstdout, self.oldstderr) log.msg("Server Shut Down.")
def postApplication(self): """ Start the application and run the reactor. """ service.IService(self.application).privilegedStartService() app.startApplication(self.application, not self.config['no_save']) app.startApplication(internet.TimerService(0.1, lambda:None), 0) app.runReactorWithLogging(self.config, self.oldstdout, self.oldstderr, self.profiler) log.msg("Server Shut Down.")
def test_convertStyle(self): appl = service.Application("lala") for instyle in 'source pickle'.split(): for outstyle in 'source pickle'.split(): sob.IPersistable(appl).setStyle(instyle) sob.IPersistable(appl).save(filename="converttest") app.convertStyle("converttest", instyle, None, "converttest.out", outstyle, 0) appl2 = service.loadApplication("converttest.out", outstyle) self.assertEqual(service.IService(appl2).name, "lala")
def _inner_run(): # Initialize logging log.startLogging(sys.stdout) # Setup Twisted application application = service.Application('django') wsgi_root = wsgi_resource() root = Root(wsgi_root) main_site = server.Site(root) internet.TCPServer(int(self.port), main_site ).setServiceParent(application) service.IService(application).startService() app.startApplication(application, False) reactor.addSystemEventTrigger('before', 'shutdown', service.IService(application).stopService) reactor.run()
def setUp(self): """ Make 'run' the LeoServer application """ from twisted.application import service print "Starting LeoServer services." app = LeoServer.create_application() s = service.IService(self.sever_app) s.startService() reactor.iterate() # execute all pending tasks, and return return
def Application(name, uid=None, gid=None): """Return a compound class. Return an object supporting the C{IService}, C{IServiceCollection}, C{IProcess} and C{sob.IPersistable} interfaces, with the given parameters. Always access the return value by explicit casting to one of the interfaces. """ ret = components.Componentized() for comp in (Bots(), sob.Persistent(ret, name), service.Process(uid, gid)): ret.addComponent(comp, ignoreClass=1) service.IService(ret).setName(name) return ret
def testLoadApplication(self): """ Test loading an application file in different dump format. """ a = service.Application("hello") baseconfig = {'file': None, 'source': None, 'python': None} for style in 'source pickle'.split(): config = baseconfig.copy() config[{'pickle': 'file'}.get(style, style)] = 'helloapplication' sob.IPersistable(a).setStyle(style) sob.IPersistable(a).save(filename='helloapplication') a1 = app.getApplication(config, None) self.assertEqual(service.IService(a1).name, "hello") config = baseconfig.copy() config['python'] = 'helloapplication' with open("helloapplication", 'w') as f: f.writelines([ "from twisted.application import service\n", "application = service.Application('hello')\n", ]) a1 = app.getApplication(config, None) self.assertEqual(service.IService(a1).name, "hello")
def testLoadApplication(self): """ Test loading an application file in different dump format. """ a = service.Application("hello") baseconfig = {"file": None, "source": None, "python": None} for style in "source pickle".split(): config = baseconfig.copy() config[{"pickle": "file"}.get(style, style)] = "helloapplication" sob.IPersistable(a).setStyle(style) sob.IPersistable(a).save(filename="helloapplication") a1 = app.getApplication(config, None) self.assertEqual(service.IService(a1).name, "hello") config = baseconfig.copy() config["python"] = "helloapplication" with open("helloapplication", "w") as f: f.writelines([ "from twisted.application import service\n", "application = service.Application('hello')\n", ]) a1 = app.getApplication(config, None) self.assertEqual(service.IService(a1).name, "hello")
def testCalling(self): """ Test invoking a method on an item in the batch process. """ dbdir = filepath.FilePath(self.mktemp()) s = store.Store(dbdir) ss = substore.SubStore.createNew(s, 'substore') service.IService(s).startService() d = iaxiom.IBatchService(ss).call(BatchCallTestItem(store=ss.open()).callIt) def called(ign): self.failUnless(ss.open().findUnique(BatchCallTestItem).called, "Was not called") return service.IService(s).stopService() return d.addCallback(called)
def test_convertStyle(self): appl = service.Application("lala") for instyle in 'xml source pickle'.split(): if instyle == 'xml' and not gotMicrodom: continue for outstyle in 'xml source pickle'.split(): if outstyle == 'xml' and not gotMicrodom: continue sob.IPersistable(appl).setStyle(instyle) sob.IPersistable(appl).save(filename="converttest") app.convertStyle("converttest", instyle, None, "converttest.out", outstyle, 0) appl2 = service.loadApplication("converttest.out", outstyle) self.assertEqual(service.IService(appl2).name, "lala")
def startApplication(config, application): process = service.IProcess(application, None) if not config['originalname']: launchWithName(process.processName) setupEnvironment(config) service.IService(application).privilegedStartService() uid, gid = mktap.getid(config['uid'], config['gid']) if uid is None: uid = process.uid if gid is None: gid = process.gid shedPrivileges(config['euid'], uid, gid) app.startApplication(application, not config['no_save'])
def test_subStoreBatchServiceStart(self): """ The substore implementation of L{IBatchService.start} starts the batch process. """ st = store.Store(self.mktemp()) svc = service.IService(st) svc.startService() self.addCleanup(svc.stopService) ss = substore.SubStore.createNew(st, ['substore']).open() iaxiom.IBatchService(ss).start() batchService = iaxiom.IBatchService(st) self.assertIn(batchService.batchController.mode, ('starting', 'ready'))
def runApp(config): passphrase = app.getPassphrase(config['encrypted']) app.installReactor(config['reactor']) application = app.getApplication(config, passphrase) oldstdout = sys.stdout oldstderr = sys.stderr startLogging(config['logfile']) app.initialLog() os.chdir(config['rundir']) service.IService(application).privilegedStartService() app.startApplication(application, not config['no_save']) app.startApplication(internet.TimerService(0.1, lambda: None), 0) app.runReactorWithLogging(config, oldstdout, oldstderr) app.reportProfile(config['report-profile'], service.IProcess(application).processName) log.msg("Server Shut Down.")
def main(): #Start UP application import nanny.daemon application = service.Application('nanny') daemon = nanny.daemon.Daemon(application) app_service = service.IService(application) app_service.privilegedStartService() app_service.startService() reactor.addSystemEventTrigger('before', 'shutdown', app_service.stopService) #Reactor Run if not hasattr(sys, "frozen") : reactor.run() else: reactor.run(installSignalHandlers=0)
def storeBatchServiceSpecialCase(st, pups): """ Adapt a L{Store} to L{IBatchService}. If C{st} is a substore, return a simple wrapper that delegates to the site store's L{IBatchService} powerup. Return C{None} if C{st} has no L{BatchProcessingControllerService}. """ if st.parent is not None: try: return _SubStoreBatchChannel(st) except TypeError: return None storeService = service.IService(st) try: return storeService.getServiceNamed("Batch Processing Controller") except KeyError: return None
def test_applicationRunnerGetsCorrectApplication(self): """ Ensure that a twistd plugin gets used in appropriate ways: it is passed its Options instance, and the service it returns is added to the application. """ arunner = CrippledApplicationRunner(self.config) arunner.run() self.assertIdentical( self.serviceMaker.options, self.config.subOptions, "ServiceMaker.makeService needs to be passed the correct " "sub Command object.") self.assertIdentical( self.serviceMaker.service, service.IService(arunner.application).services[0], "ServiceMaker.makeService's result needs to be set as a child " "of the Application.")
def testEverythingThere(self): trans = 'TCP UNIX SSL UDP UNIXDatagram Multicast'.split() for tran in trans[:]: if not getattr(interfaces, "IReactor"+tran)(reactor, None): trans.remove(tran) if interfaces.IReactorArbitrary(reactor, None) is not None: trans.insert(0, "Generic") for tran in trans: for side in 'Server Client'.split(): if tran == "Multicast" and side == "Client": continue self.assert_(hasattr(internet, tran+side)) method = getattr(internet, tran+side).method prefix = {'Server': 'listen', 'Client': 'connect'}[side] self.assert_(hasattr(reactor, prefix+method) or (prefix == "connect" and method == "UDP")) o = getattr(internet, tran+side)() self.assertEqual(service.IService(o), o)
def test_itemAddedWithoutBatchService(self): """ If the store has no batch service, C{itemAdded} doesn't start the batch process and also doesn't raise an exception. """ # An in-memory store can't have a batch service. st = store.Store() svc = service.IService(st) svc.startService() self.addCleanup(svc.stopService) procType = batch.processor(TestWorkUnit) proc = procType(store=st) listener = WorkListener(store=st) proc.addReliableListener(listener, style=iaxiom.REMOTE) proc.itemAdded() # And still there should be no batch service at all. self.assertIdentical(iaxiom.IBatchService(st, None), None)
def test_everythingThere(self): """ L{twisted.application.internet} dynamically defines a set of L{service.Service} subclasses that in general have corresponding reactor.listenXXX or reactor.connectXXX calls. """ trans = 'TCP UNIX SSL UDP UNIXDatagram Multicast'.split() for tran in trans[:]: if not getattr(interfaces, "IReactor" + tran)(reactor, None): trans.remove(tran) for tran in trans: for side in 'Server Client'.split(): if tran == "Multicast" and side == "Client": continue self.assertTrue(hasattr(internet, tran + side)) method = getattr(internet, tran + side).method prefix = {'Server': 'listen', 'Client': 'connect'}[side] self.assertTrue(hasattr(reactor, prefix + method) or (prefix == "connect" and method == "UDP")) o = getattr(internet, tran + side)() self.assertEqual(service.IService(o), o)
def testSimpleInternet(self): # XXX - replace this test with one that does the same thing, but # with no web dependencies. if not gotMicrodom: raise unittest.SkipTest("Need twisted.web to run this test.") s = "(dp0\nS'udpConnectors'\np1\n(lp2\nsS'unixConnectors'\np3\n(lp4\nsS'twisted.internet.app.Application.persistenceVersion'\np5\nI12\nsS'name'\np6\nS'web'\np7\nsS'sslConnectors'\np8\n(lp9\nsS'sslPorts'\np10\n(lp11\nsS'tcpPorts'\np12\n(lp13\n(I8080\n(itwisted.web.server\nSite\np14\n(dp16\nS'resource'\np17\n(itwisted.web.demo\nTest\np18\n(dp19\nS'files'\np20\n(lp21\nsS'paths'\np22\n(dp23\nsS'tmpl'\np24\n(lp25\nS'\\n Congratulations, twisted.web appears to work!\\n <ul>\\n <li>Funky Form:\\n '\np26\naS'self.funkyForm()'\np27\naS'\\n <li>Exception Handling:\\n '\np28\naS'self.raiseHell()'\np29\naS'\\n </ul>\\n '\np30\nasS'widgets'\np31\n(dp32\nsS'variables'\np33\n(dp34\nsS'modules'\np35\n(lp36\nsS'children'\np37\n(dp38\nsbsS'logPath'\np39\nNsS'timeOut'\np40\nI43200\nsS'sessions'\np41\n(dp42\nsbI5\nS''\np43\ntp44\nasS'unixPorts'\np45\n(lp46\nsS'services'\np47\n(dp48\nsS'gid'\np49\nI1000\nsS'tcpConnectors'\np50\n(lp51\nsS'extraConnectors'\np52\n(lp53\nsS'udpPorts'\np54\n(lp55\nsS'extraPorts'\np56\n(lp57\nsS'persistStyle'\np58\nS'pickle'\np59\nsS'uid'\np60\nI1000\ns." d = pickle.loads(s) a = Dummy() a.__dict__ = d appl = compat.convert(a) self.assertEqual(service.IProcess(appl).uid, 1000) self.assertEqual(service.IProcess(appl).gid, 1000) self.assertEqual(service.IService(appl).name, "web") services = list(service.IServiceCollection(appl)) self.assertEqual(len(services), 1) s = services[0] self.assertEqual(s.parent, service.IServiceCollection(appl)) self.assert_(s.privileged) self.assert_(isinstance(s, internet.TCPServer)) args = s.args self.assertEqual(args[0], 8080) self.assertEqual(args[3], '')
def __init__(self, cfg): cfg = cfg bus0 = Relay(cfg.get("http", "multicast"), "leela.%s.http.multicast" % config.hostname()) bus1 = Relay(cfg.get("http", "timeline"), "leela.%s.http.timeline" % config.hostname()) sto = cassandra_proto.CassandraProto(cfg) app = web.Application([ (r"^/v1/version$" , http_proto.Version), (r"^/v1/data/past24/(.*)" , http_proto.Past24 , {"storage": sto, "class_" : data.Data}), (r"^/v1/data/pastweek/(.*)" , http_proto.PastWeek , {"storage": sto, "class_" : data.Data}), (r"^/v1/data/(\d+)/(\d+)/(\d+)/(.*)", http_proto.YearMonthDay , {"storage": sto, "class_" : data.Data}), (r"^/v1/data/(\d+)/(\d+)/(.*)" , http_proto.YearMonth , {"storage": sto, "class_" : data.Data}), (r"^/v1/data/(.*)" , http_proto.RangeDataRdwr , {"storage": sto, "class_" : data.Data, "relay": bus0}), (r"^/v1/past24/(.*)" , http_proto.Past24 , {"storage": sto, "class_" : event.Event}), (r"^/v1/pastweek/(.*)" , http_proto.PastWeek , {"storage": sto, "class_" : event.Event}), (r"^/v1/(\d+)/(\d+)/(\d+)/(.*)" , http_proto.YearMonthDay , {"storage": sto, "class_" : event.Event}), (r"^/v1/(\d+)/(\d+)/(.*)" , http_proto.YearMonth , {"storage": sto, "class_" : event.Event}), (r"^/v1/(.*)" , http_proto.RangeMetricRdwr, {"storage": sto, "class_" : event.Event, "relay": bus1}), (r".*" , resthandler.Always404) ]) self.srv = service.MultiService() self.srv.addService(service.IService(internet.TCPServer(cfg.getint("http", "port"), app, interface=cfg.get("http", "address")))) self.srv.addService(sto)
def test_itemAddedBeforeStarted(self): """ If C{itemAdded} is called before the batch service is started, the batch process is not started. """ st = store.Store(self.mktemp()) procType = batch.processor(TestWorkUnit) proc = procType(store=st) listener = WorkListener(store=st) proc.addReliableListener(listener, style=iaxiom.REMOTE) proc.itemAdded() # When the service later starts, the batch service needn't start its # process. Not that this would be bad. Feel free to reverse this # behavior if you really want. svc = service.IService(st) svc.startService() self.addCleanup(svc.stopService) batchService = iaxiom.IBatchService(st) self.assertEqual(batchService.batchController.mode, 'stopped')
def testSimpleUNIX(self): # XXX - replace this test with one that does the same thing, but # with no web dependencies. if not interfaces.IReactorUNIX(reactor, None): raise unittest.SkipTest, "This reactor does not support UNIX domain sockets" if not gotMicrodom: raise unittest.SkipTest("Need twisted.web to run this test.") s = "(dp0\nS'udpConnectors'\np1\n(lp2\nsS'unixConnectors'\np3\n(lp4\nsS'twisted.internet.app.Application.persistenceVersion'\np5\nI12\nsS'name'\np6\nS'web'\np7\nsS'sslConnectors'\np8\n(lp9\nsS'sslPorts'\np10\n(lp11\nsS'tcpPorts'\np12\n(lp13\nsS'unixPorts'\np14\n(lp15\n(S'/home/moshez/.twistd-web-pb'\np16\n(itwisted.spread.pb\nBrokerFactory\np17\n(dp19\nS'objectToBroker'\np20\n(itwisted.web.distrib\nResourcePublisher\np21\n(dp22\nS'twisted.web.distrib.ResourcePublisher.persistenceVersion'\np23\nI2\nsS'site'\np24\n(itwisted.web.server\nSite\np25\n(dp26\nS'resource'\np27\n(itwisted.web.static\nFile\np28\n(dp29\nS'ignoredExts'\np30\n(lp31\nsS'defaultType'\np32\nS'text/html'\np33\nsS'registry'\np34\n(itwisted.web.static\nRegistry\np35\n(dp36\nS'twisted.web.static.Registry.persistenceVersion'\np37\nI1\nsS'twisted.python.components.Componentized.persistenceVersion'\np38\nI1\nsS'_pathCache'\np39\n(dp40\nsS'_adapterCache'\np41\n(dp42\nS'twisted.internet.interfaces.IServiceCollection'\np43\n(itwisted.internet.app\nApplication\np44\n(dp45\ng1\ng2\nsg3\ng4\nsg5\nI12\nsg6\ng7\nsg8\ng9\nsg10\ng11\nsg12\ng13\nsg14\ng15\nsS'extraPorts'\np46\n(lp47\nsS'gid'\np48\nI1053\nsS'tcpConnectors'\np49\n(lp50\nsS'extraConnectors'\np51\n(lp52\nsS'udpPorts'\np53\n(lp54\nsS'services'\np55\n(dp56\nsS'persistStyle'\np57\nS'pickle'\np58\nsS'delayeds'\np59\n(lp60\nsS'uid'\np61\nI1053\nsbssbsS'encoding'\np62\nNsS'twisted.web.static.File.persistenceVersion'\np63\nI6\nsS'path'\np64\nS'/home/moshez/public_html.twistd'\np65\nsS'type'\np66\ng33\nsS'children'\np67\n(dp68\nsS'processors'\np69\n(dp70\nS'.php3'\np71\nctwisted.web.twcgi\nPHP3Script\np72\nsS'.rpy'\np73\nctwisted.web.script\nResourceScript\np74\nsS'.php'\np75\nctwisted.web.twcgi\nPHPScript\np76\nsS'.cgi'\np77\nctwisted.web.twcgi\nCGIScript\np78\nsS'.epy'\np79\nctwisted.web.script\nPythonScript\np80\nsS'.trp'\np81\nctwisted.web.trp\nResourceUnpickler\np82\nssbsS'logPath'\np83\nNsS'sessions'\np84\n(dp85\nsbsbsS'twisted.spread.pb.BrokerFactory.persistenceVersion'\np86\nI3\nsbI5\nI438\ntp87\nasg55\ng56\nsg48\nI1053\nsg49\ng50\nsg51\ng52\nsg53\ng54\nsg46\ng47\nsg57\ng58\nsg61\nI1053\nsg59\ng60\ns." d = pickle.loads(s) a = Dummy() a.__dict__ = d appl = compat.convert(a) self.assertEqual(service.IProcess(appl).uid, 1053) self.assertEqual(service.IProcess(appl).gid, 1053) self.assertEqual(service.IService(appl).name, "web") services = list(service.IServiceCollection(appl)) self.assertEqual(len(services), 1) s = services[0] self.assertEqual(s.parent, service.IServiceCollection(appl)) self.assert_(s.privileged) self.assert_(isinstance(s, internet.UNIXServer)) args = s.args self.assertEqual(args[0], '/home/moshez/.twistd-web-pb')
def test_implicitConversion(self): a = Dummy() a.__dict__ = { 'udpConnectors': [], 'unixConnectors': [], '_listenerDict': {}, 'name': 'dummy', 'sslConnectors': [], 'unixPorts': [], '_extraListeners': {}, 'sslPorts': [], 'tcpPorts': [], 'services': {}, 'gid': 0, 'tcpConnectors': [], 'extraConnectors': [], 'udpPorts': [], 'extraPorts': [], 'uid': 0 } pickle.dump(a, open("file.tap", 'wb')) a1 = service.loadApplication("file.tap", "pickle", None) self.assertEqual(service.IService(a1).name, "dummy") self.assertEqual(list(service.IServiceCollection(a1)), [])
def startApplication(self, application): """ Configure global process state based on the given application and run the application. @param application: An object which can be adapted to L{service.IProcess} and L{service.IService}. """ process = service.IProcess(application) if not self.config['originalname']: launchWithName(process.processName) self.setupEnvironment(self.config['chroot'], self.config['rundir'], self.config['nodaemon'], self.config['pidfile']) service.IService(application).privilegedStartService() uid, gid = self.config['uid'], self.config['gid'] if uid is None: uid = process.uid if gid is None: gid = process.gid self.shedPrivileges(self.config['euid'], uid, gid) app.startApplication(application, not self.config['no_save'])
def test_startApplication(self): appl = service.Application("lala") app.startApplication(appl, 0) self.assert_(service.IService(appl).running)
def testServiceComponent(self): a = service.Application("hello") self.assert_(service.IService(a) is service.IServiceCollection(a)) self.assertEqual(service.IService(a).name, "hello") self.assertEqual(service.IService(a).parent, None)
unittest.TextTestRunner().run(the_test_suite) print "End of LeoNtest." # let the server running print "Look at http://localhost:8788 for the results" if ("1" in sys.argv) or ("2" in sys.argv): os.system("./leon.py LeoNtest.leo &") # LeoNtest.leo contain nodes for automatic test sequence execution on the clien side. if "2" in sys.argv: os.system("./leon.py LeoNtest.leo &") # run a second instance reactor.run() # keep the LeoServer running if "save_tap" in sys.argv: from twisted.persisted import sob per = sob.IPersistable(server_app) from twisted.application import service t_filename = "%s-shutdown.tap" % service.IService(server_app).name print "Creating the %s file." % t_filename print "'.tap' files are executed with 'twistd'.\n'twistd -f %s' for normal usage. 'twistd -nf %s' for debugging.\nSee 'twistd' help for avanced options" % (t_filename, t_filename) per.save(filename= t_filename) print "Finishing the LeoNtest services." #@nonl #@-node:@file LeoNtest.py #@-leo
def main(): import sys import getopt args = sys.argv[1:] optlist, args = getopt.getopt(args, 's:p:c:n:d:e:ha:vqiruw:x:', [ "server=", "port=", "channel=", "nick=", "dir=", "stylesheet=", "help", "password="******"version", "quiet", "private", "address", "utf-8", "web", "xsl", "pingurl=", "formchatport=", "jabber-id=", "jabber-server=", "jabber-password="******"Error: Erroneous web port." sys.exit(1) elif name in ('-p', '--port'): try: port = int(value) except ValueError: print "Error: Erroneous port." sys.exit(1) elif name in ('-c', '--channel'): channel = value elif name in ('-n', '--nick'): nickname = value elif name in ('-d', '--dir'): directory = value elif name in ('-e', '--stylesheet'): sheet = value elif name in ('-a', '--password'): password = value elif name in ('-i', '--private'): mode = _M_PRIVMSG elif name in ('-q', '--quiet'): mode = _M_QUIET elif name in ('-r', '--address'): addressing = _A_SPECIFIC elif name in ('-u', '--utf-8'): use_unicode = 1 elif name in ('-h', '--help'): usage(sys.argv[0]) sys.exit(0) elif name in ('-v', '--version'): version() sys.exit(0) elif name in ('--pingurl'): pingurls.append(value) elif name in ('--formchatport'): formchatport = int(value) elif name in ('--jabber-server'): jabber_server = value elif name in ('--jabber-id'): jabber_id = value elif name in ('--jabber-password'): jabber_password = value from dailychumptwist import DailyChumpTwistFactory, DailyChumpTwist if (directory != '' and channel != '' and nickname != '' and server != ''): chump = DailyChump(directory, use_unicode) bot = DailyChumpTwistFactory(chump, channel, nickname, sheet, password, mode, addressing, use_unicode) app = service.Application("chump") servcoll = service.IServiceCollection(app) internet.TCPClient(server, port, bot).setServiceParent(servcoll) if len(pingurls) > 0: chump.add_listener(URLPinger(servcoll, pingurls)) if formchatport is not None: g = TellChannelSite(chump) reactor.listenTCP(formchatport, g) if web_port is not None and xsldir is not None: try: import web web.xsldir = xsldir web.chumproot = directory import quixote.server.twisted_http quixote.server.twisted_http.Server("web", web_port) except ImportError: print "quixote not found, can't start web server" service.IService(app).startService() if jabber_password is not None and jabber_id is not None and jabber_server is not None: TwitterInterface(reactor, chump, jabber_id, jabber_password, jabber_server) reactor.run() else: usage(sys.argv[0]) sys.exit(1)