当前位置: 首页>>代码示例>>Python>>正文


Python MultiService.addService方法代码示例

本文整理汇总了Python中twisted.application.service.MultiService.addService方法的典型用法代码示例。如果您正苦于以下问题:Python MultiService.addService方法的具体用法?Python MultiService.addService怎么用?Python MultiService.addService使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.application.service.MultiService的用法示例。


在下文中一共展示了MultiService.addService方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
    def makeService(self, options):
        if options['data-dir'] != None:
            if not os.access(options['data-dir'], os.X_OK | os.W_OK):
                raise core.SmapException("Cannot access " + options['data-dir'])
            smapconf.SERVER['DataDir'] = options['data-dir']

        inst = loader.load(options['conf'])
        # override defaults with command-line args
        smapconf.SERVER.update(dict([(k.lower(), v) for (k, v) in
                                     options.iteritems() if v != None]))

        if 'SuggestThreadPool' in smapconf.SERVER:
            reactor.suggestThreadPoolSize(int(smapconf.SERVER['SuggestThreadPool']))

        inst.start()
        reactor.addSystemEventTrigger('before', 'shutdown', inst.stop)

        site = getSite(inst, docroot=smapconf.SERVER['docroot'])
        service = MultiService()

        # add HTTP and HTTPS servers to the twisted multiservice
        if 'port' in smapconf.SERVER:
            service.addService(internet.TCPServer(int(smapconf.SERVER['port']), site))
        if 'sslport' in smapconf.SERVER:
            service.addService(internet.SSLServer(int(smapconf.SERVER['sslport']), 
                                                  site, 
                                                  SslServerContextFactory(smapconf.SERVER)))
        return service
开发者ID:Alwnikrotikz,项目名称:smap-data,代码行数:30,代码来源:smap_plugin.py

示例2: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
 def makeService(self, options):
     if not os.path.isfile(options['config']):
         raise ConfigNotFoundException()
     
     config = yaml.load(open(options['config']), OrderedDictYAMLLoader)
     
     self.processProtocol = processProtocol = protocol.ProcessProtocol()
     reactor.spawnProcess(processProtocol, config['config']['udpxy'],
         args=[config['config']['udpxy'],
               '-T',
               '-m', config['config']['iptv_if'],
               '-p', str(config['config']['udpxy_port']),
               '-a', '127.0.0.1',
               '-c', '10'])
     
     from tidaltv.server import TidalTVServer
     tidaltvserver = TidalTVServer(configfile=config, use_ssl=os.path.isfile(config['config']['ssl']))
     
     if config['config']['broadcast_keepalive']:
         from tidaltv.broadcast import KeepAliver
         keepaliver = KeepAliver(config, tidaltvserver.channel_watchers)
     
     site = server.Site(tidaltvserver)
     ms = MultiService()
     tidaltvport = int(config['config']['port'])
     if os.path.isfile(config['config']['ssl']):
         from OpenSSL import SSL
         ms.addService(internet.SSLServer(tidaltvport, site,
                                          ServerContextFactory(config['config']['ssl'])))
     else:
         ms.addService(internet.TCPServer(tidaltvport, site))
     return ms
开发者ID:pombredanne,项目名称:tidalstream-livetv,代码行数:34,代码来源:tidaltvserver.py

示例3: __init__

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
    def __init__(self):
        MultiService.__init__(self)

        # Start up our AMP RPC.
        self.amp = TCPServer(25600, ConsoleRPCFactory(self))
        MultiService.addService(self, self.amp)

        self.configure_services(configuration)
开发者ID:Mortal,项目名称:bravo,代码行数:10,代码来源:service.py

示例4: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
    def makeService(self, options):
        if options['conf']:
            settings.conf = settings.load(options['conf'])

        # we better add 
        reactor.suggestThreadPoolSize(settings.conf['threadpool size'])

        if options['memdebug']:
            from twisted.internet import task
            import objgraph
            import gc
            def stats():
                print gc.collect()
                print
                print '\n'.join(map(str, objgraph.most_common_types(limit=10)))
            task.LoopingCall(stats).start(2)

        cp = adbapi.ConnectionPool(settings.conf['database']['module'],
                                   host=settings.conf['database']['host'],
                                   database=settings.conf['database']['db'],
                                   user=settings.conf['database']['user'],
                                   password=settings.conf['database']['password'],
                                   port=settings.conf['database']['port'],
                                   cp_min=5, cp_max=30,
                                   cp_reconnect=True)

        if options['subscribe']:
            subscribe(cp, settings)


        # create a single republisher to send the data out on
        http_repub = republisher.ReResource(cp)
        websocket_repub = republisher.WebSocketRepublishResource(cp)
        if settings.conf['mongo']['enabled']:
            mongo_repub = republisher.MongoRepublisher(cp)
        else:
            mongo_repub = None

        service = MultiService()
        for svc in settings.conf['server']:
            scfg = settings.conf['server'][svc]
            site = getSite(cp, 
                           resources=scfg['resources'],
                           http_repub=http_repub, 
                           websocket_repub=websocket_repub,
                           mongo_repub=mongo_repub)

            if not len(scfg['ssl']) > 1:
                service.addService(internet.TCPServer(scfg['port'],
                                                      site,
                                                      interface=scfg['interface']))
            else:
                service.addService(internet.SSLServer(scfg['port'],
                                                      site,
                                                      SslServerContextFactory(scfg['ssl']),
                                                      interface=scfg['interface']))

        return service
开发者ID:hobzcalvin,项目名称:smap,代码行数:60,代码来源:smap_archiver_plugin.py

示例5: __init__

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
    def __init__(self):
        MultiService.__init__(self)

        # Start up our AMP RPC.
        self.amp = TCPServer(25601, ConsoleRPCFactory(self))
        MultiService.addService(self, self.amp)
        self.factorylist = list()
        self.irc = False
        self.ircbots = list()
        self.configure_services(configuration)
开发者ID:RyanED,项目名称:bravo,代码行数:12,代码来源:service.py

示例6: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
    def makeService(self, options):
        """
        Construct a dispersy service.
        """

        tracker_service = MultiService()
        tracker_service.setName("Bartercast Crawler")
        # crypto
        if options["crypto"] == 'NoCrypto':
            crypto = NoCrypto()
        else:
            crypto = NoVerifyCrypto()

        container = [None]
        manhole_namespace = {}
        if options["manhole"]:
            port = options["manhole"]
            manhole = manhole_tap.makeService({
                'namespace': manhole_namespace,
                'telnetPort': 'tcp:%d:interface=127.0.0.1' % port,
                'sshPort': None,
                'passwd': os.path.join(os.path.dirname(__file__), 'passwd'),
            })
            tracker_service.addService(manhole)
            manhole.startService()

        def run():
            # setup
            dispersy = BartercastCrawler(StandaloneEndpoint(options["port"],
                                                          options["ip"]),
                                       unicode(options["statedir"]),
                                       bool(options["silent"]),
                                       crypto)
            container[0] = dispersy
            manhole_namespace['dispersy'] = dispersy

            self._stopping = False
            def signal_handler(sig, frame):
                msg("Received signal '%s' in %s (shutting down)" % (sig, frame))
                if not self._stopping:
                    self._stopping = True
                    try:
                        dispersy.stop()
                    except Exception, e:
                        msg("Got exception when stopping dispersy: %s" % e)
                    reactor.stop()
            signal.signal(signal.SIGINT, signal_handler)
            signal.signal(signal.SIGTERM, signal_handler)

            # start
            print "starting dispersy"
            if not dispersy.start():
                raise RuntimeError("Unable to start Dispersy")
开发者ID:Antiade,项目名称:tribler,代码行数:55,代码来源:bartercast_crawler_plugin.py

示例7: ServerManagerFrameImpl

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
class ServerManagerFrameImpl(ServerManagerFrame):
   def __init__(self, *args, **kw):
      super(self.__class__, self).__init__(*args, **kw)
      
      #self.hostsDialog = HostsDialogImpl(self)
      
      #servers = dict([((gethostbyname(k[0]), k[1]), v) for k, v in servers.iteritems()])
      
      # TODO?: make this Service a serialized Application then load from XML
      self.services = MultiService()
      for klass, addresses in servers.iteritems():
         module, klass = klass.rsplit('.', 1)
         self.services.addService(__import__(module).__dict__[klass](addresses))
      
      # setup log window
      class Redirect(object):
         def write(inner, *args, **kw):
            self.text_ctrl_log.AppendText(args[0])
         def flush(self, *args, **kw): pass
      log.startLogging(Redirect())
         
   def isValidClick(self, button, other):
      if other.GetValue():
         button.SetValue(True)
         other.SetValue(False)
         return True
      else:
         button.SetValue(not button.GetValue())
         return False

   def StartServer(self, event):
      # NOTE: button is already flipped by the time we get here
      button = self.button_start
      other = self.button_stop
      if not self.isValidClick(button, other):
         return
      self.services.startService()

   def StopServer(self, event):
      # NOTE: button is already flipped by the time we get here
      button = self.button_stop
      other = self.button_start
      if not self.isValidClick(button, other):
         return
      self.services.stopService()
   
   def OnHostsButton(self, event):
      self.hostsDialog.Show(not self.hostsDialog.IsShown())
开发者ID:istobran,项目名称:eaEmu,代码行数:50,代码来源:wxMain.py

示例8: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
    def makeService(self, options):
        """
        Construct a TCPServer from a factory defined in myproject.
        """

        multi_service = MultiService()
        from wokkel.client import XMPPClient
        from twisted.words.protocols.jabber import jid
        import forwarder

        xmppclient = XMPPClient(jid.internJID(options["account"]), options["password"])
        xmppclient.logTraffic = False
        bot = forwarder.ForwarderProtocol(options["uri"])
        bot.setHandlerParent(xmppclient)
        multi_service.addService(xmppclient)

        return multi_service
开发者ID:our-city-app,项目名称:mobicage-xmpp-service-forwarder,代码行数:19,代码来源:forwarder_plugin.py

示例9: __init__

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
    def __init__(self, path):
        """
        Initialize this service.

        The path should be a ``FilePath`` which points to the configuration
        file to use.
        """

        MultiService.__init__(self)

        # Grab configuration.
        self.config = read_configuration(path)

        # Start up our AMP RPC.
        self.amp = TCPServer(25601, ConsoleRPCFactory(self))
        MultiService.addService(self, self.amp)
        self.factorylist = list()
        self.irc = False
        self.ircbots = list()
        self.configure_services()
开发者ID:KingPsychopath,项目名称:bravo,代码行数:22,代码来源:service.py

示例10: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
    def makeService(self, options):
        """Construct a server using MLLPFactory.

        :rtype: :py:class:`twisted.application.internet.StreamServerEndpointService`
        """
        from twisted.internet import reactor
        from txHL7.mllp import IHL7Receiver, MLLPFactory

        receiver_name = options['receiver']
        receiver_class = reflect.namedClass(receiver_name)
        verifyClass(IHL7Receiver, receiver_class)
        factory = MLLPFactory(receiver_class())
        multi_service = MultiService()

        for port_number in PORTS:
            port = "tcp:interface={0}:port={1}".format(HOST, port_number,)
            endpoint = endpoints.serverFromString(reactor, port)
            server = internet.StreamServerEndpointService(endpoint, factory)
            server.setName(u"mllp-{0}-{1}".format(receiver_name, port_number))
            multi_service.addService(server)
        return multi_service
开发者ID:openhealthcare,项目名称:gloss,代码行数:23,代码来源:multiple_mllp_plugin.py

示例11: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
    def makeService(self, options):
        """
        Construct a Tribler service.
        """
        tribler_service = MultiService()
        tribler_service.setName("Tribler")

        manhole_namespace = {}
        if options["manhole"] > 0:
            port = options["manhole"]
            manhole = manhole_tap.makeService({
                'namespace': manhole_namespace,
                'telnetPort': 'tcp:%d:interface=127.0.0.1' % port,
                'sshPort': None,
                'passwd': os.path.join(os.path.dirname(__file__), 'passwd'),
            })
            tribler_service.addService(manhole)

        reactor.callWhenRunning(self.start_tribler, options)

        return tribler_service
开发者ID:Tribler,项目名称:tribler,代码行数:23,代码来源:tribler_plugin.py

示例12: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
def makeService(options):
    if options['data-dir'] != None:
        if not os.access(options['data-dir'], os.X_OK | os.W_OK):
            raise util.SmapException("Cannot access " + options['data-dir'])
        smapconf.SERVER['DataDir'] = options['data-dir']
    inst = loader.load(options['conf'])
    smapconf.start_logging()
    # override defaults with command-line args
    smapconf.SERVER.update(dict([(k.lower(), v) for (k, v) in
                                 options.iteritems() if v != None]))

    if 'SuggestThreadPool' in smapconf.SERVER:
        reactor.suggestThreadPoolSize(int(smapconf.SERVER['SuggestThreadPool']))

    inst.start()
    reactor.addSystemEventTrigger('before', 'shutdown', inst.stop)

    site = getSite(inst, docroot=smapconf.SERVER['docroot'])
    service = MultiService()
    # add HTTP and HTTPS servers to the twisted multiservice

    meta = make_dns_meta(inst)        
    af = 'tcp6' if options['ipv6'] else 'tcp'

    if 'port' in smapconf.SERVER:
        endpoint = "%s:%i" % (af, int(smapconf.SERVER['port']))
        http = StreamServerEndpointService(
            serverFromString(reactor, endpoint),
            site)
        service.addService(http)
        broadcast(reactor, "_smap._tcp", int(smapconf.SERVER['port']), 'sMAP Server', meta)
    if 'sslport' in smapconf.SERVER:
        endpoint = "%s:%i" % (af, int(smapconf.SERVER['sslport']))
        https = StreamServerEndpointService(
            serverFromString(reactor, endpoint),
            site)
        service.addService(internet.SSLServer(int(smapconf.SERVER['sslport']), 
                                              site, 
                                              SslServerContextFactory(smapconf.SERVER)))
    return service
开发者ID:ahaas,项目名称:smap,代码行数:42,代码来源:plugin.py

示例13: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
 def makeService(self, options):
     if not os.path.isfile(options['config']):
         from sdfs.exceptions import ConfigNotFoundException
         raise ConfigNotFoundException('No configuration file found at %s' % options['config'])
     
     config = ConfigParser.ConfigParser()
     config.read(options['config'])
     
     from sdfs.server import SDFSServer, SDFSWebServer
     ms = MultiService()
     
     sdfsserver = self.sdfsserver = SDFSServer(configfile=config)
     
     checkers = [FilePasswordDB(config.get('general', 'userfile'))]
     portal.PORTAL = Portal(portal.SDFSRealm(), checkers)
     portal.CHECKERS = [guard.BasicCredentialFactory('SDFS')]
     
     from sdfs.site import Site
     site = Site(SDFSWebServer(sdfsserver))
     
     sdfsport = config.getint('general', 'controlport')
     if config.getboolean('general', 'usessl'):
         from OpenSSL import SSL
         ms.addService(internet.SSLServer(sdfsport, site,
                                          ServerContextFactory(config.get('general', 'certfile'))))
     else:
         ms.addService(internet.TCPServer(sdfsport, site))
     
     ms.addService(KillerService(sdfsserver))
     reactor.callLater(0.0, sdfsserver.initialize_all_plugins)
     return ms
开发者ID:pombredanne,项目名称:tidalstream-sdfs,代码行数:33,代码来源:sdfsnode.py

示例14: create_service

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
def create_service(reactor, options):
    """Based on options provided by the user create a service that
    will provide whatever it is that Nesoi do.
    """
    service = MultiService()

    listen_address = options['listen-address']

    storage = shelve.open(options['data-file'], writeback=True)
    cluster_node = ClusterNode(reactor, storage)
    service.addService(cluster_node)

    model = ResourceModel(reactor, cluster_node.keystore)

    gossiper = Gossiper(reactor, cluster_node, listen_address)
    if options['seed']:
        gossiper.seed([options['seed']])

    service.addService(UDPServer(int(options['listen-port']), gossiper,
        interface=listen_address))

    router = rest.Router()
    router.addController('app', api.ApplicationCollectionResource(model))
    router.addController('app/{appname}/web-hooks', api.WebhookCollectionResource(model, 'appname', 'app'))
    router.addController('app/{appname}/web-hooks/{hookname}', api.WebhookResource(model, 'appname', 'app'))
    router.addController('app/{appname}', api.ApplicationResource(model))
    router.addController('srv', api.ServiceCollectionResource(model))
    router.addController('srv/{srvname}', api.ServiceHostCollectionResource(model))
    router.addController('srv/{srvname}/web-hooks', api.WebhookCollectionResource(model, 'srvname', 'service'))
    router.addController('srv/{srvname}/web-hooks/{hookname}', api.WebhookResource(model, 'srvname', 'service'))
    router.addController('srv/{srvname}/{hostname}', api.ServiceHostResource(model))

    service.addService(TCPServer(int(options['listen-port']), Site(router),
        interface=listen_address))

    #gossiper.set(cluster_node.election.PRIO_KEY, 0)
    #cluster_node.keystore.load_from(storage)

    return service
开发者ID:jrydberg,项目名称:nesoi,代码行数:41,代码来源:service.py

示例15: makeService

# 需要导入模块: from twisted.application.service import MultiService [as 别名]
# 或者: from twisted.application.service.MultiService import addService [as 别名]
def makeService(config):
    """
    Set up the otter-api service.
    """
    config = dict(config)
    set_config_data(config)

    parent = MultiService()

    region = config_value('region')

    seed_endpoints = [
        clientFromString(reactor, str(host))
        for host in config_value('cassandra.seed_hosts')]

    cassandra_cluster = LoggingCQLClient(
        TimingOutCQLClient(
            reactor,
            RoundRobinCassandraCluster(
                seed_endpoints,
                config_value('cassandra.keyspace'),
                disconnect_on_cancel=True),
            config_value('cassandra.timeout') or 30),
        log.bind(system='otter.silverberg'))

    store = CassScalingGroupCollection(
        cassandra_cluster, reactor, config_value('limits.absolute.maxGroups'))
    admin_store = CassAdmin(cassandra_cluster)

    bobby_url = config_value('bobby_url')
    if bobby_url is not None:
        set_bobby(BobbyClient(bobby_url))

    service_configs = get_service_configs(config)

    authenticator = generate_authenticator(reactor, config['identity'])
    supervisor = SupervisorService(authenticator, region, coiterate,
                                   service_configs)
    supervisor.setServiceParent(parent)

    set_supervisor(supervisor)

    health_checker = HealthChecker(reactor, {
        'store': getattr(store, 'health_check', None),
        'kazoo': store.kazoo_health_check,
        'supervisor': supervisor.health_check
    })

    # Setup cassandra cluster to disconnect when otter shuts down
    if 'cassandra_cluster' in locals():
        parent.addService(FunctionalService(stop=partial(
            call_after_supervisor, cassandra_cluster.disconnect, supervisor)))

    otter = Otter(store, region, health_checker.health_check)
    site = Site(otter.app.resource())
    site.displayTracebacks = False

    api_service = service(str(config_value('port')), site)
    api_service.setServiceParent(parent)

    # Setup admin service
    admin_port = config_value('admin')
    if admin_port:
        admin = OtterAdmin(admin_store)
        admin_site = Site(admin.app.resource())
        admin_site.displayTracebacks = False
        admin_service = service(str(admin_port), admin_site)
        admin_service.setServiceParent(parent)

    # setup cloud feed
    cf_conf = config.get('cloudfeeds', None)
    if cf_conf is not None:
        id_conf = deepcopy(config['identity'])
        id_conf['strategy'] = 'single_tenant'
        add_to_fanout(CloudFeedsObserver(
            reactor=reactor,
            authenticator=generate_authenticator(reactor, id_conf),
            tenant_id=cf_conf['tenant_id'],
            region=region,
            service_configs=service_configs))

    # Setup Kazoo client
    if config_value('zookeeper'):
        threads = config_value('zookeeper.threads') or 10
        disable_logs = config_value('zookeeper.no_logs')
        threadpool = ThreadPool(maxthreads=threads)
        sync_kz_client = KazooClient(
            hosts=config_value('zookeeper.hosts'),
            # Keep trying to connect until the end of time with
            # max interval of 10 minutes
            connection_retry=dict(max_tries=-1, max_delay=600),
            logger=None if disable_logs else TxLogger(log.bind(system='kazoo'))
        )
        kz_client = TxKazooClient(reactor, threadpool, sync_kz_client)
        # Don't timeout. Keep trying to connect forever
        d = kz_client.start(timeout=None)

        def on_client_ready(_):
            dispatcher = get_full_dispatcher(reactor, authenticator, log,
                                             get_service_configs(config),
#.........这里部分代码省略.........
开发者ID:meker12,项目名称:otter,代码行数:103,代码来源:api.py


注:本文中的twisted.application.service.MultiService.addService方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。