twisted.application.service.MultiService.__init__

Here are the examples of the python api twisted.application.service.MultiService.__init__ taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

59 Examples 7

Page 1 Selected Page 2

Example 1

Project: petmail Source File: retrieval.py
Function: init
    def __init__(self, descriptor, got_msgC):
        service.MultiService.__init__(self)
        self.descriptor = descriptor
        self.baseurl = str(descriptor["baseurl"])
        assert self.baseurl.endswith("/")
        self.server_pubkey = descriptor["retrieval_pubkey"].decode("hex")
        self.symkey = descriptor["retrieval_symkey"].decode("hex")
        self.RT = descriptor["RT"].decode("hex")
        self.got_msgC = got_msgC
        self.clock_offset = 0 # TODO
        self.fetchable = [] # list of (fetch_token, delete_token, length)
        self.source = ReconnectingEventSource(self.baseurl,
                                              self.start_source,
                                              self.handle_SSE)
        self.source.setServiceParent(self)
        self.source.activate()

Example 2

Project: Piped Source File: provider.py
Function: init
    def __init__(self):
        service.MultiService.__init__(self) # MultiService is an old-style class

        # we store the apis by the account name since we might have
        # multiple consumers of the same api.
        self._api_by_name = dict()

Example 3

Project: tahoe-lafs Source File: cachedir.py
    def __init__(self, basedir, pollinterval=1*HOUR, old=1*HOUR):
        service.MultiService.__init__(self)
        self.basedir = basedir
        fileutil.make_dirs(basedir)
        self.old = old
        self.files = weakref.WeakValueDictionary()

        t = internet.TimerService(pollinterval, self.check)
        t.setServiceParent(self)

Example 4

Project: magic-wormhole Source File: transit_server.py
Function: init
    def __init__(self, db, blur_usage):
        service.MultiService.__init__(self)
        self._db = db
        self._blur_usage = blur_usage
        self._pending_requests = {} # token -> TransitConnection
        self._active_connections = set() # TransitConnection
        self._counts = collections.defaultdict(int)
        self._count_bytes = 0

Example 5

Project: foolscap Source File: server.py
    def __init__(self, basedir=".", stdout=sys.stdout):
        service.MultiService.__init__(self)
        self.basedir = os.path.abspath(basedir)
        try:
            umask = open(os.path.join(basedir, "umask")).read().strip()
            self.umask = int(umask, 8) # octal string like 0022
        except EnvironmentError:
            self.umask = None
        self.port = open(os.path.join(basedir, "port")).read().strip()
        self.tub = Tub(certFile=os.path.join(basedir, "tub.pem"))
        self.tub.listenOn(self.port)
        self.tub.setServiceParent(self)
        self.tub.registerNameLookupHandler(self.lookup)
        self.setMyLocation()
        print >>stdout, "Server Running"

Example 6

Project: tahoe-lafs Source File: storage_client.py
Function: init
    def __init__(self, permute_peers, tub_maker, preferred_peers=()):
        service.MultiService.__init__(self)
        assert permute_peers # False not implemented yet
        self.permute_peers = permute_peers
        self._tub_maker = tub_maker
        self.preferred_peers = preferred_peers

        # self.servers maps serverid -> IServer, and keeps track of all the
        # storage servers that we've heard about. Each descriptor manages its
        # own Reconnector, and will give us a RemoteReference when we ask
        # them for it.
        self.servers = {}
        self._static_server_ids = set() # ignore announcements for these
        self.introducer_client = None
        self._threshold_listeners = [] # tuples of (threshold, Deferred)
        self._connected_high_water_mark = 0

Example 7

Project: callsign Source File: orchestra.py
Function: init
    def __init__(self, conf):
        service.MultiService.__init__(self)
        self.conf = conf
        self.dnsserver = DNSService(conf)
        self.dnsserver.setServiceParent(self)
        self.webserver = webservice(conf, self.dnsserver)
        self.webserver.setServiceParent(self)

Example 8

Project: petmail Source File: node.py
Function: init
    def __init__(self, basedir, dbfile):
        service.MultiService.__init__(self)
        self.basedir = basedir
        self.dbfile = dbfile

        self.db = database.make_observable_db(dbfile)
        self.init_webport()
        self.agent = None
        c = self.db.execute("SELECT name FROM services")
        for (name,) in c.fetchall():
            name = str(name)
            if name == "agent":
                self.init_mailbox_server(self.baseurl)
                self.init_agent()
                self.web.enable_agent(self.agent, self.db)
            else:
                raise ValueError("Unknown service '%s'" % name)

Example 9

Project: tahoe-lafs Source File: webish.py
Function: init
    def __init__(self, client, webport, nodeurl_path=None, staticdir=None,
                 clock=None, now_fn=time.time):
        service.MultiService.__init__(self)
        # the 'data' argument to all render() methods default to the Client
        # the 'clock' argument to root.Root is, if set, a
        # twisted.internet.task.Clock that is provided by the unit tests
        # so that they can test features that involve the passage of
        # time in a deterministic manner.
        self.root = root.Root(client, clock, now_fn)
        self.buildServer(webport, nodeurl_path, staticdir)
        if self.root.child_operations:
            self.site.remember(self.root.child_operations, IOpHandleTable)
            self.root.child_operations.setServiceParent(self)

Example 10

Project: tahoe-lafs Source File: stats.py
    def __init__(self, basedir):
        service.MultiService.__init__(self)
        self.basedir = basedir

        self.clients = {}
        self.nicknames = {}

        self.timer = TimerService(self.poll_interval, self.poll)
        self.timer.setServiceParent(self)

Example 11

Project: magic-wormhole Source File: rendezvous.py
Function: init
    def __init__(self, db, welcome, blur_usage):
        service.MultiService.__init__(self)
        self._db = db
        self._welcome = welcome
        self._blur_usage = blur_usage
        log_requests = blur_usage is None
        self._log_requests = log_requests
        self._apps = {}

Example 12

Project: ccs-calendarserver Source File: metafd.py
Function: init
    def __init__(self, maxAccepts, maxRequests):
        """
        Create a L{ConnectionLimiter} with an associated dispatcher and
        list of factories.
        """
        MultiService.__init__(self)
        self.factories = []
        # XXX dispatcher needs to be a service, so that it can shut down its
        # sub-sockets.
        self.dispatcher = InheritedSocketDispatcher(self)
        self.maxAccepts = maxAccepts
        self.maxRequests = maxRequests
        self.overloaded = False

Example 13

Project: callsign Source File: dns.py
Function: init
    def __init__(self, conf):
        service.MultiService.__init__(self)
        self.conf = conf
        forwarders = self.conf['forwarders'].split()
        savedir = self.conf['savedir']
        self.port = self.conf['udp_port']
        self.authorities = []
        self.factory = CallsignServerFactory(forwarders, savedir, self.get_ent())
        self.protocol = DNSDatagramProtocol(self.factory)

Example 14

Project: petmail Source File: eventsource.py
Function: init
    def __init__(self, baseurl, connection_starting, handler):
        service.MultiService.__init__(self)
        # we don't use any of the basic Factory/ClientFactory methods of
        # this, just the ReconnectingClientFactory.retry, stopTrying, and
        # resetDelay methods.

        self.baseurl = baseurl
        self.connection_starting = connection_starting
        self.handler = handler
        # IService provides self.running, toggled by {start,stop}Service.
        # self.active is toggled by {,de}activate. If both .running and
        # .active are True, then we want to have an outstanding EventSource
        # and will start one if necessary. If either is False, then we don't
        # want one to be outstanding, and will initiate shutdown.
        self.active = False
        self.connector = Connector(self)
        self.es = None # set we have an outstanding EventSource
        self.when_stopped = [] # list of Deferreds

Example 15

Project: tahoe-lafs Source File: crawler.py
Function: init
    def __init__(self, server, statefile, allowed_cpu_percentage=None):
        service.MultiService.__init__(self)
        if allowed_cpu_percentage is not None:
            self.allowed_cpu_percentage = allowed_cpu_percentage
        self.server = server
        self.sharedir = server.sharedir
        self.statefile = statefile
        self.prefixes = [si_b2a(struct.pack(">H", i << (16-10)))[:2]
                         for i in range(2**10)]
        self.prefixes.sort()
        self.timer = None
        self.bucket_cache = (None, [])
        self.current_sleep_time = None
        self.next_wake_time = None
        self.last_prefix_finished_time = None
        self.last_prefix_elapsed_time = None
        self.last_cycle_started_time = None
        self.last_cycle_elapsed_time = None
        self.load_state()

Example 16

Project: petmail Source File: web.py
Function: init
    def __init__(self, listenport, access_token):
        service.MultiService.__init__(self)
        self.root = Root()
        site = server.Site(self.root)
        assert listenport != "tcp:0" # must be configured
        self.port_service = strports.service(listenport, site)
        self.port_service.setServiceParent(self)
        self.access_token = access_token

Example 17

Project: tahoe-lafs Source File: i2p_provider.py
Function: init
    def __init__(self, basedir, node_for_config, reactor):
        service.MultiService.__init__(self)
        self._basedir = basedir
        self._node_for_config = node_for_config
        self._i2p = _import_i2p()
        self._txi2p = _import_txi2p()
        self._reactor = reactor

Example 18

Project: txloadbalancer Source File: service.py
Function: init
    def __init__(self, pm):
        """
        Set up the service structure that the LoadBalancedService will need.
        """
        service.MultiService.__init__(self)
        self.director = pm
        self.primaryName = 'primary'
        self.proxyCollection = service.MultiService()
        self.proxyCollection.setName('proxies')
        self.proxyCollection.setServiceParent(self)
        # this gets set with setScheduler when the proxies are created
        self.scheduler = None
        self.proxiesFactory()

Example 19

Project: Piped Source File: spread_provider.py
Function: init
    def __init__(self, listen, processor, wait_for_processor=False, default_callback=Ellipsis, checker=None):
        service.MultiService.__init__(self)
        
        if isinstance(listen, basestring):
            listen = [listen]
        self.listen = listen

        self.processor_config = dict(provider=processor) if isinstance(processor, basestring) else processor
        self.wait_for_processor = wait_for_processor
        self.default_callback = default_callback

        self.checker = checker

Example 20

Project: tahoe-lafs Source File: cpu-watcher-subscribe.py
    def __init__(self, furlthing):
        service.MultiService.__init__(self)
        if furlthing.startswith("pb://"):
            furl = furlthing
        else:
            furlfile = os.path.expanduser(furlthing)
            if os.path.isdir(furlfile):
                furlfile = os.path.join(furlfile, "watcher.furl")
            furl = open(furlfile, "r").read().strip()
        tub = Tub()
        tub.setServiceParent(self)
        tub.connectTo(furl, self.connected)

Example 21

Project: tahoe-lafs Source File: tor_provider.py
Function: init
    def __init__(self, basedir, node_for_config, reactor):
        service.MultiService.__init__(self)
        self._basedir = basedir
        self._node_for_config = node_for_config
        self._tor_launched = None
        self._onion_ehs = None
        self._onion_tor_control_proto = None
        self._tor = _import_tor()
        self._txtorcon = _import_txtorcon()
        self._reactor = reactor

Example 22

Project: palaver Source File: groupchat.py
Function: init
    def __init__(self, storage, use_cache = False):
        service.MultiService.__init__(self)
        self.use_cache = use_cache
        self.storage = storage

        self.storage.use_cache = use_cache

        self.active_rooms = []

Example 23

Project: tahoe-lafs Source File: stats.py
Function: init
    def __init__(self, provider, warn_if_delay_exceeds=1):
        service.MultiService.__init__(self)
        self.provider = provider
        self.warn_if_delay_exceeds = warn_if_delay_exceeds
        self.started = False
        self.last = None
        self.stats = deque()
        self.timer = None

Example 24

Project: foolscap Source File: services.py
    def __init__(self, basedir, tub, options):
        # tub might be None. No network activity should be done until
        # startService. Validate all options in the constructor. Do not use
        # the Service/MultiService ".name" attribute (which would prevent
        # having multiple instances of a single service type in the same
        # server).
        service.MultiService.__init__(self)
        self.basedir = basedir
        self.tub = tub
        self.options = options
        self.targetdir = filepath.FilePath(options.targetdir)

Example 25

Project: tahoe-lafs Source File: stats.py
    def __init__(self):
        service.MultiService.__init__(self)
        # we don't use time.clock() here, because the constructor is run by
        # the twistd parent process (as it loads the .tac file), whereas the
        # rest of the program will be run by the child process, after twistd
        # forks. Instead, set self.initial_cpu as soon as the reactor starts
        # up.
        self.initial_cpu = 0.0 # just in case
        eventually(self._set_initial_cpu)
        self.samples = []
        # we provide 1min, 5min, and 15min moving averages
        TimerService(self.POLL_INTERVAL, self.check).setServiceParent(self)

Example 26

Project: SubliminalCollaborator Source File: mail.py
    def __init__(self):
        service.MultiService.__init__(self)
        # Domains and portals for "client" protocols - POP3, IMAP4, etc
        self.domains = DomainWithDefaultDict({}, BounceDomain())
        self.portals = {}

        self.monitor = FileMonitoringService()
        self.monitor.setServiceParent(self)
        self.smtpPortal = cred.portal.Portal(self)

Example 27

Project: foolscap Source File: pb.py
Function: init
    def __init__(self, certData=None, certFile=None, _test_options={}):
        service.MultiService.__init__(self)
        self.setup(_test_options)
        if certFile:
            self.setupEncryptionFile(certFile)
        else:
            self.setupEncryption(certData)

Example 28

Project: tahoe-lafs Source File: server.py
    def __init__(self, storedir, nodeid, reserved_space=0,
                 discard_storage=False, readonly_storage=False,
                 stats_provider=None,
                 expiration_enabled=False,
                 expiration_mode="age",
                 expiration_override_lease_duration=None,
                 expiration_cutoff_date=None,
                 expiration_sharetypes=("mutable", "immutable")):
        service.MultiService.__init__(self)
        assert isinstance(nodeid, str)
        assert len(nodeid) == 20
        self.my_nodeid = nodeid
        self.storedir = storedir
        sharedir = os.path.join(storedir, "shares")
        fileutil.make_dirs(sharedir)
        self.sharedir = sharedir
        # we don't actually create the corruption-advisory dir until necessary
        self.corruption_advisory_dir = os.path.join(storedir,
                                                    "corruption-advisories")
        self.reserved_space = int(reserved_space)
        self.no_storage = discard_storage
        self.readonly_storage = readonly_storage
        self.stats_provider = stats_provider
        if self.stats_provider:
            self.stats_provider.register_producer(self)
        self.incomingdir = os.path.join(sharedir, 'incoming')
        self._clean_incomplete()
        fileutil.make_dirs(self.incomingdir)
        self._active_writers = weakref.WeakKeyDictionary()
        log.msg("StorageServer created", facility="tahoe.storage")

        if reserved_space:
            if self.get_available_space() is None:
                log.msg("warning: [storage]reserved_space= is set, but this platform does not support an API to get disk statistics (statvfs(2) or GetDiskFreeSpaceEx), so this reservation cannot be honored",
                        umin="0wZ27w", level=log.UNUSUAL)

        self.latencies = {"allocate": [], # immutable
                          "write": [],
                          "close": [],
                          "read": [],
                          "get": [],
                          "writev": [], # mutable
                          "readv": [],
                          "add-lease": [], # both
                          "renew": [],
                          "cancel": [],
                          }
        self.add_bucket_counter()

        statefile = os.path.join(self.storedir, "lease_checker.state")
        historyfile = os.path.join(self.storedir, "lease_checker.history")
        klass = self.LeaseCheckerClass
        self.lease_checker = klass(self, statefile, historyfile,
                                   expiration_enabled, expiration_mode,
                                   expiration_override_lease_duration,
                                   expiration_cutoff_date,
                                   expiration_sharetypes)
        self.lease_checker.setServiceParent(self)

Example 29

Project: magic-wormhole Source File: server.py
    def __init__(self, rendezvous_web_port, transit_port,
                 advertise_version, db_url=":memory:", blur_usage=None,
                 signal_error=None, stats_file=None):
        service.MultiService.__init__(self)
        self._blur_usage = blur_usage

        db = get_db(db_url)
        welcome = {
            # The primary (python CLI) implementation will emit a message if
            # its version does not match this key. If/when we have
            # distributions which include older version, but we still expect
            # them to be compatible, stop sending this key.
            "current_cli_version": __version__,

            # adding .motd will cause all clients to display the message,
            # then keep running normally
            #"motd": "Welcome to the public relay.\nPlease enjoy this service.",

            # adding .error will cause all clients to fail, with this message
            #"error": "This server has been disabled, see URL for details.",
            }
        if advertise_version:
            welcome["current_cli_version"] = advertise_version
        if signal_error:
            welcome["error"] = signal_error

        self._rendezvous = Rendezvous(db, welcome, blur_usage)
        self._rendezvous.setServiceParent(self) # for the pruning timer

        root = Root()
        wsrf = WebSocketRendezvousFactory(None, self._rendezvous)
        root.putChild(b"v1", WebSocketResource(wsrf))

        site = PrivacyEnhancedSite(root)
        if blur_usage:
            site.logRequests = False

        r = endpoints.serverFromString(reactor, rendezvous_web_port)
        rendezvous_web_service = internet.StreamServerEndpointService(r, site)
        rendezvous_web_service.setServiceParent(self)

        if transit_port:
            transit = Transit(db, blur_usage)
            transit.setServiceParent(self) # for the timer
            t = endpoints.serverFromString(reactor, transit_port)
            transit_service = internet.StreamServerEndpointService(t, transit)
            transit_service.setServiceParent(self)

        self._stats_file = stats_file
        if self._stats_file and os.path.exists(self._stats_file):
            os.unlink(self._stats_file)
            # this will be regenerated immediately, but if something goes
            # wrong in dump_stats(), it's better to have a missing file than
            # a stale one
        t = internet.TimerService(EXPIRATION_CHECK_PERIOD, self.timer)
        t.setServiceParent(self)

        # make some things accessible for tests
        self._db = db
        self._root = root
        self._rendezvous_web_service = rendezvous_web_service
        self._rendezvous_websocket = wsrf
        self._transit = None
        if transit_port:
            self._transit = transit
            self._transit_service = transit_service

Example 30

Project: tahoe-lafs Source File: server.py
Function: init
    def __init__(self, basedir="."):
        service.MultiService.__init__(self)
        self.introducer_url = None
        # 'index' is (service_name, key_s, tubid), where key_s or tubid is
        # None
        self._announcements = {} # dict of index ->
                                 # (ann_t, canary, ann, timestamp)

        # ann (the announcement dictionary) is cleaned up: nickname is always
        # unicode, servicename is always ascii, etc, even though
        # simplejson.loads sometimes returns either

        # self._subscribers is a dict mapping servicename to subscriptions
        # 'subscriptions' is a dict mapping rref to a subscription
        # 'subscription' is a tuple of (subscriber_info, timestamp)
        # 'subscriber_info' is a dict, provided directly by v2 clients. The
        # expected keys are: version, nickname, app-versions, my-version,
        # oldest-supported
        self._subscribers = {}

        self._debug_counts = {"inbound_message": 0,
                              "inbound_duplicate": 0,
                              "inbound_no_seqnum": 0,
                              "inbound_old_replay": 0,
                              "inbound_update": 0,
                              "outbound_message": 0,
                              "outbound_announcements": 0,
                              "inbound_subscribe": 0}
        self._debug_outstanding = 0

Example 31

Project: petmail Source File: agent.py
Function: init
    def __init__(self, db, basedir, mailbox_server):
        service.MultiService.__init__(self)
        self.db = db
        self.mailbox_server = mailbox_server

        self.mailbox_retrievers = set()
        c = self.db.execute("SELECT * FROM agent_profile").fetchone()
        self.advertise_local_mailbox = bool(c["advertise_local_mailbox"])
        mboxes = {}
        if self.advertise_local_mailbox:
            local_tid = mailbox_server.get_local_transport()
            local_mbrec = mailbox_server.get_mailbox_record(local_tid)
            mboxes["local"] = local_mbrec["retrieval"]
        for row in self.db.execute("SELECT * FROM mailboxes").fetchall():
            mbrec = json.loads(row["mailbox_record_json"])
            mboxes[row["id"]] = mbrec["retrieval"]

        for mbid, rrec in mboxes.items():
            rc = self.build_retriever(mbid, rrec)
            self.subscribe_to_mailbox(rc)

        # the invitations are activated in startService
        row = self.db.execute("SELECT * FROM relay_servers").fetchone()
        relay_url = row["url"].encode("ascii")
        self.im = invitation.InvitationManager(db, relay_url)

Example 32

Project: tahoe-lafs Source File: storage_client.py
    def __init__(self, server_id, ann, tub_maker, handler_overrides):
        service.MultiService.__init__(self)
        assert isinstance(server_id, str)
        self._server_id = server_id
        self.announcement = ann
        self._tub_maker = tub_maker
        self._handler_overrides = handler_overrides

        assert "anonymous-storage-FURL" in ann, ann
        furl = str(ann["anonymous-storage-FURL"])
        m = re.match(r'pb://(\w+)@', furl)
        assert m, furl
        tubid_s = m.group(1).lower()
        self._tubid = base32.a2b(tubid_s)
        if "permutation-seed-base32" in ann:
            ps = base32.a2b(str(ann["permutation-seed-base32"]))
        elif re.search(r'^v0-[0-9a-zA-Z]{52}$', server_id):
            ps = base32.a2b(server_id[3:])
        else:
            log.msg("unable to parse serverid '%(server_id)s as pubkey, "
                    "hashing it to get permutation-seed, "
                    "may not converge with other clients",
                    server_id=server_id,
                    facility="tahoe.storage_broker",
                    level=log.UNUSUAL, umid="qu86tw")
            ps = hashlib.sha256(server_id).digest()
        self._permutation_seed = ps

        assert server_id
        self._long_description = server_id
        if server_id.startswith("v0-"):
            # remove v0- prefix from abbreviated name
            self._short_description = server_id[3:3+8]
        else:
            self._short_description = server_id[:8]

        self.last_connect_time = None
        self.last_loss_time = None
        self.remote_host = None
        self.rref = None
        self._is_connected = False
        self._reconnector = None
        self._trigger_cb = None
        self._on_status_changed = ObserverList()

Example 33

Project: petmail Source File: retrieval.py
Function: init
    def __init__(self, descriptor, got_msgC, server):
        service.MultiService.__init__(self)
        server.register_local_transport_handler(got_msgC)

Example 34

Project: airpnp Source File: airpnp_plugin.py
Function: init
    def __init__(self, ip_addr, if_index, configfile, configloaded):
        MultiService.__init__(self)
        BridgeServer((ip_addr, if_index)).setServiceParent(self)
        self.cf = configfile
        self.cl = configloaded

Example 35

Project: tahoe-lafs Source File: node.py
    def __init__(self, basedir=u"."):
        service.MultiService.__init__(self)
        self.basedir = abspath_expanduser_unicode(unicode(basedir))
        self.config_fname = os.path.join(self.basedir, "tahoe.cfg")
        self._portnumfile = os.path.join(self.basedir, self.PORTNUMFILE)
        fileutil.make_dirs(os.path.join(self.basedir, "private"), 0700)
        with open(os.path.join(self.basedir, "private", "README"), "w") as f:
            f.write(PRIV_README)

        # creates self.config
        self.read_config()
        nickname_utf8 = self.get_config("node", "nickname", "<unspecified>")
        self.nickname = nickname_utf8.decode("utf-8")
        assert type(self.nickname) is unicode

        self.init_tempdir()
        self.check_privacy()

        self.create_log_tub()
        self.logSource="Node"
        self.setup_logging()

        self.create_i2p_provider()
        self.create_tor_provider()
        self.init_connections()
        self.set_tub_options()
        self.create_main_tub()
        self.create_control_tub()

        self.log("Node constructed. " + get_package_versions_string())
        iputil.increase_rlimits()

Example 36

Project: tahoe-lafs Source File: no_network.py
    def __init__(self, basedir, num_clients=1, num_servers=10,
                 client_config_hooks={}):
        service.MultiService.__init__(self)
        self.basedir = basedir
        fileutil.make_dirs(basedir)

        self.servers_by_number = {} # maps to StorageServer instance
        self.wrappers_by_id = {} # maps to wrapped StorageServer instance
        self.proxies_by_id = {} # maps to IServer on which .rref is a wrapped
                                # StorageServer
        self.clients = []
        self.client_config_hooks = client_config_hooks

        for i in range(num_servers):
            ss = self.make_server(i)
            self.add_server(i, ss)
        self.rebuild_serverlist()

        for i in range(num_clients):
            c = self.make_client(i)
            self.clients.append(c)

Example 37

Project: petmail Source File: server.py
Function: init
    def __init__(self):
        service.MultiService.__init__(self)

Example 38

Project: airpnp Source File: AirPlayService.py
Function: init
    def __init__(self, apserver, name=None, host="0.0.0.0", port=22555, index=-1, device_id=None):
        MultiService.__init__(self)

        self.apserver = IAirPlayServer(apserver)

        if device_id:
            self.deviceid = device_id
        else:
            macstr = "%012X" % uuid.getnode()
            self.deviceid = ''.join("%s:" % macstr[i:i + 2] for i in range(0, len(macstr), 2))[:-1]

        # 0x77 instead of 0x07 in order to support AirPlay from ordinary apps;
        # also means that the body for play will be a binary plist.
        self.features = 0x77
        self.model = "AppleTV2,1"

        # create TCP server
        TCPServer(port, self.create_site(), 100, interface=host).setServiceParent(self)

        # create avahi service
        if (name is None):
            name = "Airplay Service on " + platform.node()
        zconf = ZeroconfService(name, port=port, stype="_airplay._tcp",
                                text=["deviceid=" + self.deviceid, "features=" + hex(self.features), "model=" + self.model],
                                index=index)
        zconf.setServiceParent(self)

        # for logging
        self.name_ = name
        self.host = host
        self.port = port

Example 39

Project: filesync-server Source File: ssl_proxy.py
    def __init__(self, ssl_cert, ssl_key, ssl_cert_chain, ssl_port,
                 dest_host, dest_port, server_name, status_port):
        """ Create a rageServerService.

        @param ssl_cert: the certificate text.
        @param ssl_key: the key text.
        @param ssl_port: the port to listen on with ssl.
        @param dest_host: destination hostname.
        @param dest_port: destination port.
        @param server_name: name of this server.
        """
        MultiService.__init__(self)
        self.heartbeat_writer = None
        if server_name is None:
            server_name = "anonymous_instance"
        self.server_name = server_name
        self.factory = SSLProxyFactory(ssl_port, dest_host, dest_port,
                                       self.server_name)
        ssl_context_factory = ProxyContextFactory(ssl_cert, ssl_key,
                                                  ssl_cert_chain)
        self.ssl_service = SSLServer(ssl_port, self.factory,
                                     ssl_context_factory)
        self.ssl_service.setName("SSL")
        self.ssl_service.setServiceParent(self)
        # setup the status service
        self.status_service = create_status_service(self.factory, status_port)
        self.status_service.setServiceParent(self)
        # disable ssl compression
        if config.ssl_proxy.disable_ssl_compression:
            disable_ssl_compression(logger)

Example 40

Project: Piped Source File: providers.py
Function: init
    def __init__(self):
        self._connection_by_name = dict()
        self._connection_config_by_name = dict()
        service.MultiService.__init__(self)

Example 41

Project: tahoe-lafs Source File: webish.py
Function: init
    def __init__(self, introducer, webport, nodeurl_path=None, staticdir=None):
        service.MultiService.__init__(self)
        self.root = introweb.IntroducerRoot(introducer)
        self.buildServer(webport, nodeurl_path, staticdir)

Example 42

Project: tahoe-lafs Source File: ftpd.py
    def __init__(self, client, accountfile, accounturl, ftp_portstr):
        precondition(isinstance(accountfile, (unicode, NoneType)), accountfile)
        service.MultiService.__init__(self)

        r = Dispatcher(client)
        p = portal.Portal(r)

        if accountfile:
            c = AccountFileChecker(self, accountfile)
            p.registerChecker(c)
        if accounturl:
            c = AccountURLChecker(self, accounturl)
            p.registerChecker(c)
        if not accountfile and not accounturl:
            # we could leave this anonymous, with just the /uri/CAP form
            raise NeedRootcapLookupScheme("must provide some translation")

        f = ftp.FTPFactory(p)
        s = strports.service(ftp_portstr, f)
        s.setServiceParent(self)

Example 43

Project: tahoe-lafs Source File: stats.py
Function: init
    def __init__(self, node, gatherer_furl):
        service.MultiService.__init__(self)
        self.node = node
        self.gatherer_furl = gatherer_furl # might be None

        self.counters = {}
        self.stats_producers = []

        # only run the LoadMonitor (which submits a timer every second) if
        # there is a gatherer who is going to be paying attention. Our stats
        # are visible through HTTP even without a gatherer, so run the rest
        # of the stats (including the once-per-minute CPUUsageMonitor)
        if gatherer_furl:
            self.load_monitor = LoadMonitor(self)
            self.load_monitor.setServiceParent(self)
            self.register_producer(self.load_monitor)

        self.cpu_monitor = CPUUsageMonitor()
        self.cpu_monitor.setServiceParent(self)
        self.register_producer(self.cpu_monitor)

Example 44

Project: vertex Source File: depserv.py
    def __init__(self, **kw):
        service.MultiService.__init__(self)

        # this makes it possible for one service to change the configuration of
        # another. Avoid if possible, there if you need it. Be sure to properly
        # set the dependencies.
        self.config = kw
        self.servers = []

        services = kw.keys()
        initedServices = Set()
        uninitedServices = Set(services)

        # build dependencies
        dependencies = {}
        for serv in services:
            try:
                dependMethod = self._getDependsMethod(serv)
            except AttributeError:
                continue
            dependencies[serv] = dependMethod(**kw[serv])

        def initializeService(svc):
            self._getServiceMethod(svc)(**kw[svc])
            initedServices.add(svc)
            uninitedServices.remove(svc)

        for svc in self.requiredServices:
            if dependencies.get(svc):
                raise StartupError(
                    '%r is a required service but has unsatisfied '
                    'dependency on %r' % (svc, dependencies[svc]))
            initializeService(svc)

        while uninitedServices:
            # iterate over the uninitialized services, adding those with no
            # outstanding dependencies to initThisRound.
            initThisRound = []
            for serv in uninitedServices:
                for dep in dependencies.get(serv, []):
                    if dep not in initedServices:
                        if dep not in uninitedServices:
                            raise StartupError(
                                'service %r depends on service %r, which is not '
                                'configured or does not exist.' % (serv, dep))
                        break
                else:
                    initThisRound.append(serv)
            if not initThisRound:
                raise StartupError(
                    'Can not initialize all services. Circular dependencies '
                    'between setup methods?')
            for svc in initThisRound:
                initializeService(svc)

Example 45

Project: tahoe-lafs Source File: stats.py
    def __init__(self, basedir=".", verbose=False):
        service.MultiService.__init__(self)
        self.basedir = basedir
        self.tub = Tub(certFile=os.path.join(self.basedir,
                                             "stats_gatherer.pem"))
        self.tub.setServiceParent(self)
        self.tub.setOption("logLocalFailures", True)
        self.tub.setOption("logRemoteFailures", True)
        self.tub.setOption("expose-remote-exception-types", False)

        self.stats_gatherer = JSONStatsGatherer(self.basedir, verbose)
        self.stats_gatherer.setServiceParent(self)

        try:
            with open(os.path.join(self.basedir, "location")) as f:
                location = f.read().strip()
        except EnvironmentError:
            raise ValueError("Unable to find 'location' in BASEDIR, please rebuild your stats-gatherer")
        try:
            with open(os.path.join(self.basedir, "port")) as f:
                port = f.read().strip()
        except EnvironmentError:
            raise ValueError("Unable to find 'port' in BASEDIR, please rebuild your stats-gatherer")

        self.tub.listenOn(port)
        self.tub.setLocation(location)
        ff = os.path.join(self.basedir, self.furl_file)
        self.gatherer_furl = self.tub.registerReference(self.stats_gatherer,
                                                        furlFile=ff)

Example 46

Project: foolscap Source File: services.py
Function: init
    def __init__(self, basedir, tub, options):
        service.MultiService.__init__(self)
        self.basedir = basedir
        self.tub = tub
        self.options = options

Example 47

Project: pika Source File: twisted_service.py
Function: init
    def __init__(self, parameter):
        service.MultiService.__init__(self)
        self.parameters = parameter

Example 48

Project: airpnp Source File: device_discovery.py
Function: init
    def __init__(self, ip_addr, sn_types=[], device_types=[], required_services=[]): # pylint: disable-msg=W0102
        """Initialize the service.

        Arguments:
        ip_addr           -- IP address for listening services.
        sn_types          -- list of device and/or service types to look for in
                             UPnP notifications and responses; other types will
                             be ignored. "upnp:rootdevice" is automatically
                             tracked, and should not be in this list.
        device_types      -- list of interesting device types, used to filter
                             out devices based on their "deviceType" attribute.
                             An empty list means that all types are interesting.
        required_services -- if non-empty, list of services that the device
                             must have for it to be considered

        """
        MultiService.__init__(self)
        self._builders = {}
        self._devices = {}
        self._ignored = []
        self._sn_types = ['upnp:rootdevice'] + sn_types
        self._dev_types = device_types
        self._req_services = required_services
        self._ip_addr = ip_addr

        # create the UPnP listener service
        UpnpService(self._datagram_handler, ip_addr).setServiceParent(self)
        
        # create the periodic M-SEARCH request service
        msearch = MSearchRequest(self._datagram_handler)
        TimerService(DISCOVERY_INTERVAL, self._msearch_discover,
                     msearch).setServiceParent(self)

Example 49

Project: tahoe-lafs Source File: magic_folder.py
    def __init__(self, client, upload_dircap, collective_dircap, local_path_u, dbfile, umask,
                 uploader_delay=1.0, clock=None, downloader_delay=3):
        precondition_abspath(local_path_u)

        service.MultiService.__init__(self)

        clock = clock or reactor
        db = magicfolderdb.get_magicfolderdb(dbfile, create_version=(magicfolderdb.SCHEMA_v1, 1))
        if db is None:
            return Failure(Exception('ERROR: Unable to load magic folder db.'))

        # for tests
        self._client = client
        self._db = db

        upload_dirnode = self._client.create_node_from_uri(upload_dircap)
        collective_dirnode = self._client.create_node_from_uri(collective_dircap)

        self.uploader = Uploader(client, local_path_u, db, upload_dirnode, uploader_delay, clock)
        self.downloader = Downloader(client, local_path_u, db, collective_dirnode,
                                     upload_dirnode.get_readonly_uri(), clock, self.uploader.is_pending, umask,
                                     self.set_public_status, poll_interval=downloader_delay)
        self._public_status = (False, ['Magic folder has not yet started'])

Example 50

Project: foolscap Source File: gatherer.py
    def __init__(self, basedir):
        service.MultiService.__init__(self)
        if basedir is None:
            # This instance was created by a gatherer.tac file. Confirm that
            # we're running from the right directory (the one with the .tac
            # file), otherwise we'll put the logfiles in the wrong place.
            basedir = os.getcwd()
            tac = os.path.join(basedir, self.tacFile)
            if not os.path.exists(tac):
                raise RuntimeError("running in the wrong directory")
        self.basedir = basedir
        certFile = os.path.join(self.basedir, "gatherer.pem")
        portfile = os.path.join(self.basedir, "port")
        locationfile = os.path.join(self.basedir, "location")
        furlFile = os.path.join(self.basedir, self.furlFile)

        # Foolscap-0.11.0 was the last release that used
        # automatically-determined listening addresses and ports. New ones
        # (created with "flogtool create-gatherer" or
        # "create-incident-gathererer" now require --location and --port
        # arguments to provide these values. If you really don't want to
        # create a new one, you can write "tcp:3117" (or some other port
        # number of your choosing) to BASEDIR/port, and "tcp:$HOSTNAME:3117"
        # (with your hostname or IP address) to BASEDIR/location

        if (not os.path.exists(portfile) or
            not os.path.exists(locationfile)):
            raise ObsoleteGatherer("Please create a new gatherer, with both "
                                   "--port and --location")
        try:
            with open(portfile, "r") as f:
                port = f.read().strip()
        except EnvironmentError:
            raise ObsoleteGatherer("Please create a new gatherer, with both "
                                   "--port and --location")
        try:
            with open(locationfile, "r") as f:
                location = f.read().strip()
        except EnvironmentError:
            raise ObsoleteGatherer("Please create a new gatherer, with both "
                                   "--port and --location")

        self._tub = Tub(certFile=certFile)
        self._tub.setServiceParent(self)
        self._tub.listenOn(port)
        self._tub.setLocation(location)

        self.my_furl = self._tub.registerReference(self, furlFile=furlFile)
        if self.verbose:
            print "Gatherer waiting at:", self.my_furl
See More Examples - Go to Next Page
Page 1 Selected Page 2