def __init__(self, application): """ Setup the server. application - an instantiated Twisted application """ sys.path.insert(1, '.') # create a store of services self.services = service.IServiceCollection(application) self.amp_protocol = None # set by amp factory self.sessions = SESSIONS self.sessions.server = self # Database-specific startup optimizations. self.sqlite3_prep() self.start_time = time.time() # Run the initial setup if needed self.run_initial_setup() # initialize channelhandler channelhandler.CHANNELHANDLER.update() # set a callback if the server is killed abruptly, # by Ctrl-C, reboot etc. reactor.addSystemEventTrigger('before', 'shutdown', self.shutdown, _reactor_stopping=True) self.game_running = True # track the server time self.run_init_hooks()
def convert(oldApp): '''Convert an C{i.app.Application} to a C{application.service.Application} @type oldApp: C{twisted.internet.app.Application} @rtype C{twisted.application.service.Application} This function might damage oldApp beyond repair: services that other parts might be depending on might be missing. It is not safe to use oldApp after it has been converted. In case this behaviour is not desirable, pass a deep copy of the old application ''' ret = service.Application(oldApp.name, getattr(oldApp, "uid", None), getattr(oldApp, "gid", None)) c = service.IServiceCollection(ret) service.IProcess(ret).processName = oldApp.processName for (pList, klass) in [(oldApp.extraPorts, internet.GenericServer), (oldApp.extraConnectors, internet.GenericClient),]: for (portType, args, kw) in pList: klass(portType, *args, **kw).setServiceParent(c) for (name, klass) in _mapping: for args in getattr(oldApp, name): klass(*args).setServiceParent(c) for s in c: if hasattr(s, 'privileged'): s.privileged = 1 for s in oldApp.services.values(): if not service.IService.providedBy(s): s.serviceParent = None s = _NewService(s) s.setServiceParent(IOldApplication(c)) else: s.serviceParent = None s.setServiceParent(c) return ret
def _changeServices(self, request): serviceList = request.args.get('service', []) for srv in service.IServiceCollection(self.env.app): if srv.running and not srv.service_id in serviceList: self.env.disableService(srv.service_id) elif not srv.running and srv.service_id in serviceList: self.env.enableService(srv.service_id)
def newApplication(settings, one_time=False): stats = service.Application('pokerstats') services = service.IServiceCollection(stats) i = 1 ds = [] for server in settings.headerGetProperties("/settings/server"): host = server['host'] port = int(server['port']) stop_service_deferred = None if one_time: stop_service_deferred = defer.Deferred() ds.append(stop_service_deferred) factory = PokerStatsFactory( settings=settings, server=i, stop_service_deferred=stop_service_deferred) stat = Stat(host, port, factory) stat.setServiceParent(services) stat.factory = factory i += 1 if one_time and len(ds) > 0: global stop_application stop_application = defer.DeferredList(ds) return stats
def makeService(options): """ This will be called from twistd plugin system and we are supposed to create and return an application service. """ application = service.IServiceCollection( service.Application("octopus_editor_server", uid=1, gid=1)) ws_factory = makeWebsocketServerFactory(str(options["wshost"]), int(options["wsport"])) internet.TCPServer(int(options["wsport"]), ws_factory).setServiceParent(application) http_factory = makeHTTPResourcesServerFactory() internet.TCPServer(int(options["port"]), http_factory).setServiceParent(application) try: console_factory = makeConsoleServerFactory() internet.TCPServer(int(options["consoleport"]), console_factory).setServiceParent(application) except IOError: log.err( "ERROR: Console could not be started. Create SSH keys using initialise.py before running." ) return application
def main(reactor): parser = argparse.ArgumentParser() parser.add_argument("--farm-os-url", help="The url for connecting to FarmOS", type=str, default='http://localhost:80') parser.add_argument("--proxy-spec", help="The specification for hosting the proxy port", type=str, default='tcp:5707') args = parser.parse_args() log.startLogging(sys.stdout) application = service.Application('FarmOsAreaFeatureProxy', uid=1, gid=1) service_collection = service.IServiceCollection(application) site = server.Site(WfsResource(FarmOsProxyFeatureServer(args.farm_os_url))) svc = strports.service(args.proxy_spec, site) svc.setServiceParent(service_collection) try: svc.startService() reactor.run() finally: svc.stopService()
def createApplication(): appName = getAppConfig('app_name') apiServerIp = getAppConfig('api_server.bind_address') apiServerPort = int(getAppConfig('api_server.port')) games = getAppConfig('games').split(",") application = service.Application(name=appName) # log.msg(orderServerOption.get('nodaemon')) # log.msg(orderServerOption.keys()) # log.msg(orderServerOption.values()) # if orderServerOption.get('nodaemon') != 0: logDir = os.path.realpath(os.path.dirname(getAppConfig('logdir'))) logName = "%s.log" % ( appName, ) logFile = logfile.DailyLogFile(logName, logDir) #log.msg(logDir) application.setComponent(log.ILogObserver, log.FileLogObserver(logFile).emit) log.msg("load application: ", appName) log.msg("load games:", games) appSrv = service.IServiceCollection(application) _apiService = apiService(bindAddress=apiServerIp, port=apiServerPort, games=games) _apiService.setServiceParent(appSrv) _consumerService = consumerService(games=games) _consumerService.setServiceParent(appSrv) return application
def __init__(self, application): """ Setup the server. Args: application (Application): An instantiated Twisted application """ sys.path.append('.') # create a store of services self.services = service.IServiceCollection(application) self.amp_protocol = None # set by amp factory self.sessions = PORTAL_SESSIONS self.sessions.portal = self self.process_id = os.getpid() self.server_process_id = None self.server_restart_mode = "shutdown" self.server_info_dict = {} # in non-interactive portal mode, this gets overwritten by # cmdline sent by the evennia launcher self.server_twistd_cmd = self._get_backup_server_twistd_cmd() # set a callback if the server is killed abruptly, # by Ctrl-C, reboot etc. reactor.addSystemEventTrigger('before', 'shutdown', self.shutdown, _reactor_stopping=True, _stop_server=True)
def __init__(self, factory): """ :param factory: :type IDefaultFactory """ self.factory = factory self.__logger = Logger() self.listener = None if self.factory.ws_protocol == 'wss': self.__ssl_context = ssl.DefaultOpenSSLContextFactory( self.factory.crt_keys.get('key'), self.factory.crt_keys.get('crt') ) self.setName(self.factory.name) if self.factory.belong_to is False: self.__application = service.Application(self.factory.name, uid=1000, gid=1000) self.service_collection = service.IServiceCollection(self.__application) else: self.service_collection = self.factory.belong_to
def testSimpleService(self): a = DummyApp() a.__dict__ = { 'udpConnectors': [], 'unixConnectors': [], '_listenerDict': {}, 'name': 'dummy', 'sslConnectors': [], 'unixPorts': [], '_extraListeners': {}, 'sslPorts': [], 'tcpPorts': [], 'services': {}, 'gid': 0, 'tcpConnectors': [], 'extraConnectors': [], 'udpPorts': [], 'extraPorts': [], 'uid': 0 } s = service.Service() s.setName("lala") s.setServiceParent(a) appl = compat.convert(a) services = list(service.IServiceCollection(appl)) self.assertEqual(len(services), 1) s1 = services[0] self.assertEqual(s, s1)
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
def makeService(self, options): """ Make services to handle push event notifications. """ # check confguration file is specified and exists if not options["config"]: raise ValueError( 'Configuration file not specified (try to check --help option)' ) cfgFileName = options["config"] if not os.path.isfile(cfgFileName): raise ValueError('Configuration file not found:', cfgFileName) # read configuration file cfg = ConfigParser() cfg.read(cfgFileName) # create Twisted application application = service.Application("gitlab-webhook-xmpp") serviceCollection = service.IServiceCollection(application) # create XMPP client client = XMPPClient(JID(cfg.get('xmpp', 'jid')), cfg.get('xmpp', 'password')) # client.logTraffic = True client.setServiceParent(application) # join to all MUC rooms nickname = cfg.get('xmpp', 'nickname') if cfg.has_option( 'xmpp', 'nickname') else DEFAULT_NICKNAME notifications = cfg.items('notifications') for room, repositoryMasks in notifications: mucHandler = MUCHandler(JID(room), nickname, repositoryMasks.split(',')) mucHandler.setHandlerParent(client) self.mucHandlers.append(mucHandler) templateLoader = None if cfg.has_option('message', 'template'): templateFullName = cfg.get('message', 'template') templatePath, self.templateName = os.path.split(templateFullName) templateLoader = FileSystemLoader(templatePath) else: self.templateName = DEFAULT_TEMPLATE_NAME templateLoader = PackageLoader('xmpp_webhook', 'templates') self.templateEnvironment = Environment(loader=templateLoader, extensions=['jinja2.ext.i18n']) self.templateEnvironment.install_null_translations( ) # use i18n to pluralize only # create web hook handler rootHttpResource = Resource() rootHttpResource.putChild('', WebHookHandler(self)) site = server.Site(rootHttpResource) httpPort = cfg.getint('http', 'port') if cfg.has_option( 'http', 'port') else DEFAULT_HTTP_PORT httpServer = internet.TCPServer(httpPort, site) httpServer.setServiceParent(serviceCollection) return serviceCollection
def startService(self): IApp = service.IServiceCollection(self.app, self.app) self.task_storage = IApp.getServiceNamed('task_storage') self.signal_manager = get_signal_manager(self.app) self.signal_manager.connect(self.update_tasks, signal=signals.tasks_updated) self.update_tasks() # same as pooler > pools list of projects
def makeService(options): application = service.Application(meta.description) services = service.IServiceCollection(application) makeSSHService(options, application, services) # XXX if run-internal server is true, run process.makeSCSynthService ... # XXX fix broken internal server startup ... #process.boot(mode="internal", options=options, services=services) return services
def startService(self): log.msg("Start pooler ...") IApp = service.IServiceCollection(self.app, self.app) self.task_storage = IApp.getServiceNamed('task_storage') self.signal_manager = get_signal_manager(self.app) self.signal_manager.connect(self.update_tasks, signal=signals.tasks_updated) self.update_tasks()
def makeApplication(argv): default_path = "/etc/poker-network" + sys.version[:3] + "/poker.server.xml" if not exists(default_path): default_path = "/etc/poker-network/poker.server.xml" configuration = argv[-1][-4:] == ".xml" and argv[-1] or default_path application = service.Application('poker') serviceCollection = service.IServiceCollection(application) poker_service = makeService(configuration) poker_service.setServiceParent(serviceCollection) return application
def _flatSubservices(root, acc=None): if acc is None: acc = list() acc.append(root) sc = service.IServiceCollection(root, None) if sc: for ss in sc: _flatSubservices(ss, acc) logger.debug("root %r, subservices %r", root, acc) return acc
def disableService(self, id): """ Disable a service. """ for srv in service.IServiceCollection(self.app): if srv.service_id == id: self.config.set(srv.service_id, 'autostart', False) self.config.save() yield defer.maybeDeferred(srv.stopService) self.log.info('Stopping service %s.' % srv.name)
def startPersistentDictServer(): """This code belongs in a twisted tac file (at toplevel).""" from .pdict import NamedDicts, PersistentDictFactory from twisted.application import internet, service namedDict = "EventStore" port = NamedDicts[namedDict]['port'] application = service.Application("pdict") factory = PersistentDictFactory(namedDict) pdictService = internet.TCPServer(port, factory) pdictService.setServiceParent(service.IServiceCollection(application))
def makeService(options): cql_client = CQLClient( endpoints.clientFromString( reactor, "tcp:{0}:{1}".format(options["cql-host"], options["cql-port"])), 'bobby') application = service.Application("Dammit, Bobby!") services = service.IServiceCollection(application) bobby = Bobby(cql_client) bobbyServer = strports.service('tcp:{0}'.format(options["port"]), server.Site(bobby.app.resource())) bobbyServer.setServiceParent(application) return services
def _configure_twisted_reactor(self): LDAPExploitServer._output_twisted_logs_to_python_logger() registerAdapter(lambda x: x.root, LDAPServerFactory, IConnectedLDAPEntry) tree = Tree(self._http_server_ip, self._http_server_port, self._storage_dir) factory = LDAPServerFactory(tree.db) factory.debug = True application = service.Application("ldaptor-server") service.IServiceCollection(application) reactor.listenTCP(self._ldap_server_port, factory)
def render(self, request): if request.method == 'POST': if 'shutdown' in request.args: self._shutdownSeisHub() elif 'reload' in request.args: self._changeServices(request) elif 'restart' in request.args: self._restartSeisHub() data = { 'services': service.IServiceCollection(self.env.app), } return data
def addToApplication(ser, name, append, procname, type, encrypted, uid, gid): if append and os.path.exists(append): a = service.loadApplication(append, 'pickle', None) else: a = service.Application(name, uid, gid) if procname: service.IProcess(a).processName = procname ser.setServiceParent(service.IServiceCollection(a)) sob.IPersistable(a).setStyle(type) passphrase = app.getSavePassphrase(encrypted) if passphrase: append = None sob.IPersistable(a).save(filename=append, passphrase=passphrase)
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 executeCommand(self, request, args): services = service.IServiceCollection(self.env.app) if len(args) == 2: ENABLE = ['start', 'enable', 'on'] DISABLE = ['stop', 'disable', 'off'] srv_name = args[1].lower() action = args[0].lower() if action in ENABLE: self.env.enableService(srv_name) elif action in DISABLE: self.env.disableService(srv_name) RUNNING = ['OFF', 'ON'] for s in services: request.writeln(s.name + ' ' + RUNNING[s.running])
def enableService(self, id): """ Enable a service. """ for srv in service.IServiceCollection(self.app): if srv.service_id == id: # ensure not to start a service twice; may be fatal with timers if srv.running: self.log.info('Service %s already started.' % srv.name) return self.config.set(srv.service_id, 'autostart', True) self.config.save() yield defer.maybeDeferred(srv.startService) self.log.info('Starting service %s.' % srv.name)
def render_POST(self, request): actions = [] serviceList = request.args.get('service', []) for srv in service.IServiceCollection(self.app): if srv.running and not srv.name in serviceList: stopping = defer.maybeDeferred(srv.stopService) actions.append(stopping) elif not srv.running and srv.name in serviceList: # wouldn't work if this program were using reserved ports # and running under an unprivileged user id starting = defer.maybeDeferred(srv.startService) actions.append(starting) defer.DeferredList(actions).addCallback(self._finishedActions, request) return webserver.NOT_DONE_YET
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 create_application(): rd = txredisapi.lazyRedisConnectionPool() redisBackend = RedisResolverBackend(rd, servers=[('8.8.8.8', 53)]) application = service.Application("txdnsredis") srv_collection = service.IServiceCollection(application) dnsFactory = server.DNSServerFactory(caches=[cache.CacheResolver()], clients=[redisBackend]) internet.TCPServer(53, dnsFactory).setServiceParent(srv_collection) internet.UDPServer( 53, dns.DNSDatagramProtocol(dnsFactory)).setServiceParent(srv_collection) return application
def makeService(options): # primary setup application = service.Application(meta.description) services = service.IServiceCollection(application) # setup ssh for the game server sshFactory = getGameShellFactory(app=application, services=services) sshServer = internet.TCPServer(config.ssh.port, sshFactory) sshServer.setName(config.ssh.servicename) sshServer.setServiceParent(services) # setup telnet for creating user accounts #telnetFactory = getSetupShellFactory() #telnetServer = internet.TCPServer(config.telnet.port, telnetFactory) #telnetServer.setName(config.telnet.servicename) #telnetServer.setServiceParent(services) return services