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


Python components.PluginRegistry类代码示例

本文整理汇总了Python中gosa.common.components.PluginRegistry的典型用法代码示例。如果您正苦于以下问题:Python PluginRegistry类的具体用法?Python PluginRegistry怎么用?Python PluginRegistry使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


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

示例1: handle_request

    def handle_request(self, topic, message):
        if topic == self.subtopic:
            # event from proxy received
            try:
                data = etree.fromstring(message, PluginRegistry.getEventParser())
                event_type = stripNs(data.xpath('/g:Event/*', namespaces={'g': "http://www.gonicus.de/Events"})[0].tag)
                if event_type == "ClientLeave":
                    proxy_id = str(data.ClientLeave.Id)
                    registry = PluginRegistry.getInstance("BackendRegistry")
                    registry.unregisterBackend(proxy_id)

            except etree.XMLSyntaxError as e:
                self.log.error("Event parsing error: %s" % e)

        elif topic.startswith(self.subtopic):
            response_topic = "%s/response" % "/".join(topic.split("/")[0:4])

            try:
                id_, res = self.process(topic, message)
                if is_future(res):
                    res = yield res
                response = dumps({"result": res, "id": id_})
                self.log.debug("MQTT-RPC response: %s on topic %s" % (response, topic))

            except Exception as e:
                err = str(e)
                self.log.error("MQTT RPC call error: %s" % err)
                response = dumps({'id': topic.split("/")[-2], 'error': err})

            # Get rid of it...
            self.mqtt.send_message(response, topic=response_topic, qos=2)

        else:
            self.log.warning("unhandled topic request received: %s" % topic)
开发者ID:gonicus,项目名称:gosa,代码行数:34,代码来源:mqttrpc_service.py

示例2: mainLoop

def mainLoop(env):
    """
    Main event loop which will process all registerd threads in a loop.
    It will run as long env.active is set to True.
    """
    log = logging.getLogger(__name__)

    try:
        # Load plugins
        oreg = ObjectRegistry.getInstance() #@UnusedVariable
        pr = PluginRegistry() #@UnusedVariable
        cr = PluginRegistry.getInstance("CommandRegistry")

        httpd = PluginRegistry.getInstance("HTTPService")
        if not hasattr(sys, "_called_from_test") or sys._called_from_test is False:
            httpd.thread.join()

    # Catchall, pylint: disable=W0703
    except Exception as detail:
        log.critical("unexpected error in mainLoop")
        log.exception(detail)

    except KeyboardInterrupt:
        log.info("console requested shutdown")

    finally:
        if not hasattr(sys, "_called_from_test") or sys._called_from_test is False:
            shutdown()
开发者ID:peuter,项目名称:gosa,代码行数:28,代码来源:main.py

示例3: __dbus_proxy_monitor

    def __dbus_proxy_monitor(self, bus_name):
        """
        This method monitors the DBus service 'org.gosa' and whenever there is a
        change in the status (dbus closed/startet) we will take notice.
        And can register or unregister methods to the dbus
        """
        if "org.gosa" in self.bus.list_names():
            if self.gosa_dbus:
                del self.gosa_dbus

            # Trigger resend of capapability event
            self.gosa_dbus = self.bus.get_object('org.gosa', '/org/gosa/inventory')
            ccr = PluginRegistry.getInstance('ClientCommandRegistry')
            ccr.register("request_inventory", 'Inventory.request_inventory', [], ['old_checksum=None'], 'Request client inventory information')
            mqtt = PluginRegistry.getInstance('MQTTClientService')
            mqtt.reAnnounce()
            self.log.info("established dbus connection")

        else:
            if self.gosa_dbus:
                del(self.gosa_dbus)

                # Trigger resend of capapability event
                ccr = PluginRegistry.getInstance('ClientCommandRegistry')
                ccr.unregister("request_inventory")
                mqtt = PluginRegistry.getInstance('MQTTClientService')
                mqtt.reAnnounce()
                self.log.info("lost dbus connection")
            else:
                self.log.info("no dbus connection")
开发者ID:peuter,项目名称:gosa,代码行数:30,代码来源:main.py

示例4: test_handle_backend_message

    def test_handle_backend_message(self):
        e = EventMaker()

        # send client poll
        with mock.patch.object(self.service.proxy_mqtt, "send_message") as mps:

            # send ACLChanged
            m_resolver = PluginRegistry.getInstance("ACLResolver")
            self.service._handle_backend_message("%s/proxy" % self.env.domain,
                                                 etree.tostring(e.Event(e.Trigger(e.Type("ACLChanged"))),
                                                                pretty_print=True).decode())
            assert m_resolver.load_acls.called
            assert not mps.called

            m_index = PluginRegistry.getInstance("ObjectIndex")
            self.service._handle_backend_message("%s/client/broadcast" % self.env.domain,
                                                 etree.tostring(e.Event(e.ClientPoll()),
                                                                pretty_print=True).decode())
            assert m_index.registerProxy.called
            assert mps.called
            mps.reset_mock()

            # send client RPC
            payload = dumps({"id": "mqttrpc", "method": "test", "params": []})
            topic = "%s/client/client_id/request_id/request" % self.env.domain
            self.service._handle_backend_message(topic, payload)
            mps.assert_called_with(payload, topic, qos=1, proxied=True)
开发者ID:gonicus,项目名称:gosa,代码行数:27,代码来源:test_mqtt_relay.py

示例5: setSambaPassword

    def setSambaPassword(self, user, object_dn, password):
        """
        Set a new samba-password for a user
        """

        # Do we have read permissions for the requested attribute
        env = Environment.getInstance()
        topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "sambaNTPassword")
        aclresolver = PluginRegistry.getInstance("ACLResolver")
        if not aclresolver.check(user, topic, "w", base=object_dn):
            self.__log.debug("user '%s' has insufficient permissions to write %s on %s, required is %s:%s" % (
                user, "isLocked", object_dn, topic, "w"))
            raise ACLException(C.make_error('PERMISSION_ACCESS', topic, target=object_dn))

        topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "sambaLMPassword")
        aclresolver = PluginRegistry.getInstance("ACLResolver")
        if not aclresolver.check(user, topic, "w", base=object_dn):
            self.__log.debug("user '%s' has insufficient permissions to write %s on %s, required is %s:%s" % (
                user, "isLocked", object_dn, topic, "w"))
            raise ACLException(C.make_error('PERMISSION_ACCESS', topic, target=object_dn))

        # Set the password and commit the changes
        user = ObjectProxy(object_dn)
        user.sambaNTPassword = nthash.encrypt(password)
        user.sambaLMPassword = lmhash.encrypt(password)
        user.commit()
开发者ID:gonicus,项目名称:gosa,代码行数:26,代码来源:domain.py

示例6: serve

    def serve(self):
        """ Start AMQP service for this GOsa service provider. """
        # Load AMQP and Command registry instances
        amqp = PluginRegistry.getInstance('AMQPHandler')
        self.__cr = PluginRegistry.getInstance('CommandRegistry')

        # Create a list of queues we need here
        queues = {}
        for dsc in self.__cr.commands.values():
            queues[dsc['target']] = True

        # Finally create the queues
        for queue in queues:
            # Add round robin processor for queue
            self.__cmdWorker = AMQPWorker(self.env, connection=amqp.getConnection(),
                r_address='%s.command.%s; { create:always, node:{ type:queue, x-bindings:[ { exchange:"amq.direct", queue:"%s.command.%s" } ] } }' % (self.env.domain, queue, self.env.domain, queue),
                workers=self.env.config.get('amqp.command-worker', default=1),
                callback=self.commandReceived)

            # Add private processor for queue
            self.__cmdWorker = AMQPWorker(self.env, connection=amqp.getConnection(),
                    r_address='%s.command.%s.%s; { create:always, delete:receiver, node:{ type:queue, x-bindings:[ { exchange:"amq.direct", queue:"%s.command.%s.%s" } ] } }' % (self.env.domain, queue, self.env.id, self.env.domain, queue, self.env.id),
                workers=self.env.config.get('amqp.command-worker', default=1),
                callback=self.commandReceived)

        # Announce service
        url = parseURL(self.env.config.get("amqp.url"))
        self.__zeroconf = ZeroconfService(name="GOsa AMQP command service",
                port=url['port'],
                stype="_%s._tcp" % url['scheme'],
                text="path=%s\001service=gosa" % url['path'])
        self.__zeroconf.publish()

        self.log.info("ready to process incoming requests")
开发者ID:lhm-limux,项目名称:gosa,代码行数:34,代码来源:amqp_service.py

示例7: accountUnlockable

    def accountUnlockable(self, user, object_dn):
        index = PluginRegistry.getInstance("ObjectIndex")

        # Do we have read permissions for the requested attribute
        env = Environment.getInstance()
        topic = "%s.objects.%s.attributes.%s" % (env.domain, "User", "isLocked")
        aclresolver = PluginRegistry.getInstance("ACLResolver")
        if not aclresolver.check(user, topic, "r", base=object_dn):

            self.__log.debug("user '%s' has insufficient permissions to read %s on %s, required is %s:%s" % (
                user, "isLocked", object_dn, topic, "r"))
            raise ACLException(C.make_error('PERMISSION_ACCESS', topic, target=object_dn))

        res = index.search({'dn': object_dn, 'userPassword': '%'}, {'userPassword': 1})
        if len(res):
            hsh = res[0]['userPassword'][0]
        else:
            # No password hash -> cannot lock/unlock account
            return False

        # Try to detect the responsible password method-class
        pwd_o = self.detect_method_by_hash(hsh)
        if not pwd_o:

            # Could not identify password method
            return False

        return pwd_o.isUnlockable(hsh)
开发者ID:peuter,项目名称:gosa,代码行数:28,代码来源:manager.py

示例8: serve

    def serve(self):
        """ Start JSONRPC service for this GOsa service provider. """

        # Get http service instance
        self.__http = PluginRegistry.getInstance("HTTPService")
        cr = PluginRegistry.getInstance("CommandRegistry")

        # Register ourselves
        app = JsonRpcApp(cr)
        self.__http.app.register(
            self.path,
            AuthCookieHandler(
                app,
                timeout=self.env.config.get("jsonrpc.cookie-lifetime", default=1800),
                cookie_name="GOsaRPC",
                secret=self.env.config.get("http.cookie_secret", default="TecloigJink4"),
            ),
        )

        # Announce service
        self.__zeroconf = ZeroconfService(
            name="GOsa JSONRPC command service",
            port=self.__http.port,
            stype="_%s._tcp" % self.__http.scheme,
            text="path=%s\001service=gosa" % self.path,
        )
        self.__zeroconf.publish()

        self.log.info("ready to process incoming requests")
开发者ID:lhm-limux,项目名称:gosa,代码行数:29,代码来源:jsonrpc_service.py

示例9: serve

    def serve(self):
        # Collect value extenders
        self.__value_extender = gosa.backend.objects.renderer.get_renderers()
        self.__search_aid = PluginRegistry.getInstance("ObjectIndex").get_search_aid()
        self.__oi = PluginRegistry.getInstance("ObjectIndex")

        # Load DB session
        self.__session = self.env.getDatabaseSession('backend-database')
开发者ID:peuter,项目名称:gosa,代码行数:8,代码来源:methods.py

示例10: shutdown

def shutdown():
    """
    Function to shut down the backend. Do some clean up and close sockets.
    """
    # Shutdown plugin registry
    PluginRegistry.shutdown()

    logging.info("shut down")
    logging.shutdown()
开发者ID:peuter,项目名称:gosa,代码行数:9,代码来源:main.py

示例11: test_clientLeave

    def test_clientLeave(self):
        service = PluginRegistry.getInstance("MQTTRPCService")
        e = EventMaker()
        goodbye = e.Event(e.ClientLeave(e.Id("fake_uuid")))
        data = etree.tostring(goodbye).decode('utf-8')

        with mock.patch.object(PluginRegistry.getInstance("BackendRegistry"), "unregisterBackend") as m:
            service.handle_request("%s/proxy" % Environment.getInstance().domain, data)
            m.assert_called_with("fake_uuid")
开发者ID:gonicus,项目名称:gosa,代码行数:9,代码来源:test_mqttrpc_service.py

示例12: initialize

    def initialize(self):
        self.dispatcher = PluginRegistry.getInstance('CommandRegistry')
        self.env = Environment.getInstance()
        self.log = logging.getLogger(__name__)
        self.ident = "GOsa JSON-RPC service (%s)" % VERSION
        self.executor = PluginRegistry.getInstance('ExecutorWrapper').executor

        if JsonRpcHandler.__gc_job is None:
            sched = PluginRegistry.getInstance('SchedulerService').getScheduler()
            JsonRpcHandler.__gc_job = sched.add_interval_job(self.__gc_sessions, minutes=180, tag='_internal', jobstore="ram")
开发者ID:gonicus,项目名称:gosa,代码行数:10,代码来源:jsonrpc_service.py

示例13: post

    def post(self, uuid):
        try:
            self.ps.data_complete() # You MUST call this to close the incoming stream.
            # Here can use self.ps to access the fields and the corresponding ``StreamedPart`` objects.
            self.upload_handler.handle_upload(self.ps.get_parts_by_name('file')[0], self.request)

            # cleanup
            PluginRegistry.getInstance("UploadManager").unregisterUploadPath(uuid)
            self.upload_handler = None

        finally:
            # When ready, don't forget to release resources.
            self.ps.release_parts()
            self.finish() # And of course, you MUST call finish()
开发者ID:gonicus,项目名称:gosa,代码行数:14,代码来源:main.py

示例14: shutdown

    def shutdown():
        env.active = False

        # Wait for threads to shut down
        for t in env.threads:
            if hasattr(t, 'stop'):
                t.stop()
            if hasattr(t, 'cancel'):
                t.cancel()
            t.join(2)

        PluginRegistry.shutdown()
        if has_dbus:
            dr.stop()
开发者ID:gonicus,项目名称:gosa,代码行数:14,代码来源:conftest.py

示例15: sendEvent

    def sendEvent(self, user, data):
        """
        Sends an event to the SSE handler and the zope event bus. Data must be in XML format,
        see :ref:`Events handling <events>` for details.

        ========== ============
        Parameter  Description
        ========== ============
        data       valid event
        ========== ============

        *sendEvent* will indirectly validate the event against the bundled "XSD".
        """

        try:
            event = "<?xml version='1.0'?>\n"

            if isinstance(data, str):
                event += data
            elif isinstance(data, bytes):
                event += data.decode('utf-8')
            else:
                event += etree.tostring(data, pretty_print=True).decode('utf-8')

            # Validate event
            xml = objectify.fromstring(event, PluginRegistry.getEventParser())
            event_type = list(xml.__dict__.keys())[0]
            # If a user was supplied, check if she's authorized...
            if user:
                acl = PluginRegistry.getInstance("ACLResolver")
                topic = ".".join([self.env.domain, 'event', event_type])
                if not acl.check(user, topic, "x"):
                    raise EventNotAuthorized("sending the event '%s' is not permitted" % topic)

            if event_type in ['ObjectChanged', 'Notification', 'ObjectCloseAnnouncement']:
                params = {'channel': 'broadcast'}

                if event_type == "Notification" and xml.Notification.Target.text != "all":
                    params['channel'] = "user.%s" % xml.Notification.Target.text
                if event_type == "ObjectCloseAnnouncement":
                    params['channel'] = "user.%s" % xml.ObjectCloseAnnouncement.Target.text

                SseHandler.notify(xml, **params)

            zope.event.notify(Event(data=xml, emitter=user))

        except etree.XMLSyntaxError as e:
            if self.env:
                self.log.error("event rejected (%s): %s" % (str(e), data))
            raise
开发者ID:peuter,项目名称:gosa,代码行数:50,代码来源:command.py


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