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


Python EventSubscriber.deactivate方法代码示例

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


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

示例1: test_pub_on_different_subtypes

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]
    def test_pub_on_different_subtypes(self):
        ar = event.AsyncResult()
        gq = queue.Queue()
        self.count = 0

        def cb(event, *args, **kwargs):
            self.count += 1
            gq.put(event)
            if event.description == "end":
                ar.set()

        sub = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="st1", callback=cb)
        sub.activate()

        pub1 = EventPublisher(event_type="ResourceModifiedEvent")
        pub2 = EventPublisher(event_type="ContainerLifecycleEvent")

        pub1.publish_event(origin="two", sub_type="st2", description="2")
        pub2.publish_event(origin="three", sub_type="st1", description="3")
        pub1.publish_event(origin="one", sub_type="st1", description="1")
        pub1.publish_event(origin="four", sub_type="st1", description="end")

        ar.get(timeout=5)
        sub.deactivate()

        res = []
        for x in xrange(self.count):
            res.append(gq.get(timeout=5))

        self.assertEquals(len(res), 2)
        self.assertEquals(res[0].description, "1")
开发者ID:ooici-dm,项目名称:pyon,代码行数:33,代码来源:test_event.py

示例2: test_l4_ci_sa_rq_145_323

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]
    def test_l4_ci_sa_rq_145_323(self):
        """
        Instrument management shall update physical resource metadata when change occurs

        For example, when there is a change of state.

        note from maurice 2012-05-18: consider this to mean a change of stored RR data
        """

        inst_obj = any_old(RT.InstrumentDevice)
        instrument_device_id, _ = self.RR.create(inst_obj)
        self.received_event = AsyncResult()

        #Create subscribers for agent and driver events.

        def consume_event(*args, **kwargs):
            self.received_event.set(True)
            log.info("L4-CI-SA-RQ-323")
            log.info("L4-CI-SA-RQ-145")

        event_sub = EventSubscriber(event_type="ResourceModifiedEvent", callback=consume_event)
        event_sub.activate()


        inst_obj = self.RR.read(instrument_device_id)
        inst_obj.description = "brand new description"
        self.RR.update(inst_obj)

        #wait for event
        result = self.received_event.get(timeout=10)
        event_sub.deactivate()

        self.assertTrue(result)
开发者ID:dstuebe,项目名称:coi-services,代码行数:35,代码来源:test_l4_ci_sa.py

示例3: Notification

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]
class Notification(object):
    """
    Encapsulates a notification's info and it's event subscriber

    @David - is this class needed? It does not seem to serve any purpose?
    """

    def  __init__(self, notification_request=None, subscriber_callback=None):
        self._res_obj = notification_request  # The notification Request Resource Object
        # setup subscription using subscription_callback()
        # msg_recipientDO: make this walk the lists and set up a subscriber for every pair of
        # origin/event.  This will require a list to hold all the subscribers so they can
        # be started and killed

        self.subscriber = EventSubscriber(origin=notification_request.origin,
                                            origin_type = notification_request.origin_type,
                                            event_type=notification_request.event_type,
                                            sub_type=notification_request.event_subtype,
                                            callback=subscriber_callback)
        self.notification_id = None

    def set_notification_id(self, id_=None):
        """
        Set the notification id of the notification object
        @param notification id
        """
        self.notification_id = id_

    def activate(self):
        """
        Start subscribing
        """
        self.subscriber.activate()

    def deactivate(self):
        """
        Stop subscribing
        """
        self.subscriber.deactivate()
开发者ID:ooici-eoi,项目名称:coi-services,代码行数:41,代码来源:user_notification_service.py

示例4: Directory

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]
class Directory(object):
    """
    Class that uses a datastore to provide a directory lookup mechanism.
    Terms:
      directory: instance of a Directory, representing entries within one Org. A tree of entries.
      path: parent+key (= qualified name of an entry). All paths start with '/'
      entry: node in the directory tree with a name (key) and parent path, holding arbitrary attributes
      key: local name of an entry
    """

    def __init__(self, orgname=None, datastore_manager=None, events_enabled=False):
        # Get an instance of datastore configured as directory.
        datastore_manager = datastore_manager or bootstrap.container_instance.datastore_manager
        self.dir_store = datastore_manager.get_datastore(DataStore.DS_DIRECTORY)

        self.orgname = orgname or CFG.system.root_org
        self.is_root = (self.orgname == CFG.system.root_org)

        self.events_enabled = events_enabled
        self.event_pub = None
        self.event_sub = None

        # Create directory root entry (for current org) if not existing
        if CFG.system.auto_bootstrap:
            root_de = self.register("/", "DIR", sys_name=bootstrap.get_sys_name())
            if root_de is None:
                # We created this directory just now
                pass

        if self.events_enabled:
            # init change event publisher
            self.event_pub = EventPublisher()

            # Register to receive directory changes
            self.event_sub = EventSubscriber(event_type="ContainerConfigModifiedEvent",
                origin="Directory",
                callback=self.receive_directory_change_event)

    def close(self):
        """
        Close directory and all resources including datastore and event listener.
        """
        if self.event_sub:
            self.event_sub.deactivate()
        self.dir_store.close()

    def _get_path(self, parent, key):
        """
        Returns the qualified directory path for a directory entry.
        """
        if parent == "/":
            return parent + key
        elif parent.startswith("/"):
            return parent + "/" + key
        else:
            raise BadRequest("Illegal parent: %s" % parent)

    def _get_key(self, path):
        """
        Returns the key from a qualified directory path
        """
        parent, key = path.rsplit("/", 1)
        return key

    def _create_dir_entry(self, parent, key, orgname=None, ts=None, attributes=None):
        """
        Standard way to create a DirEntry object (without persisting it)
        """
        orgname = orgname or self.orgname
        ts = ts or get_ion_ts()
        attributes = attributes if attributes is not None else {}
        de = DirEntry(org=orgname, parent=parent, key=key, attributes=attributes, ts_created=ts, ts_updated=ts)
        return de

    def _read_by_path(self, path, orgname=None):
        """
        Given a qualified path, find entry in directory and return DirEntry
        object or None if not found
        """
        if path is None:
            raise BadRequest("Illegal arguments")
        orgname = orgname or self.orgname
        parent, key = path.rsplit("/", 1)
        parent = parent or "/"
        find_key = [orgname, key, parent]
        view_res = self.dir_store.find_by_view('directory', 'by_key', key=find_key, id_only=True, convert_doc=True)

        match = [doc for docid, index, doc in view_res]
        if len(match) > 1:
            raise Inconsistent("More than one directory entry found for key %s" % path)
        elif match:
            return match[0]
        return None

    def lookup(self, parent, key=None, return_entry=False):
        """
        Read entry residing in directory at parent node level.
        """
        path = self._get_path(parent, key) if key else parent
        direntry = self._read_by_path(path)
#.........这里部分代码省略.........
开发者ID:daf,项目名称:pyon,代码行数:103,代码来源:directory.py

示例5: test_pub_on_different_subsubtypes

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]
    def test_pub_on_different_subsubtypes(self):
        res_list = [DotDict(ar=event.AsyncResult(), gq=queue.Queue(), count=0) for i in xrange(4)]

        def cb_gen(num):
            def cb(event, *args, **kwargs):
                res_list[num].count += 1
                res_list[num].gq.put(event)
                if event.description == "end":
                    res_list[num].ar.set()

            return cb

        sub0 = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="st1.*", callback=cb_gen(0))
        sub0.activate()

        sub1 = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="st1.a", callback=cb_gen(1))
        sub1.activate()

        sub2 = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="*.a", callback=cb_gen(2))
        sub2.activate()

        sub3 = EventSubscriber(event_type="ResourceModifiedEvent", sub_type="st1", callback=cb_gen(3))
        sub3.activate()

        pub1 = EventPublisher(event_type="ResourceModifiedEvent")

        pub1.publish_event(origin="one", sub_type="st1.a", description="1")
        pub1.publish_event(origin="two", sub_type="st1", description="2")
        pub1.publish_event(origin="three", sub_type="st1.b", description="3")

        pub1.publish_event(origin="four", sub_type="st2.a", description="4")
        pub1.publish_event(origin="five", sub_type="st2", description="5")

        pub1.publish_event(origin="six", sub_type="a", description="6")
        pub1.publish_event(origin="seven", sub_type="", description="7")

        pub1.publish_event(origin="end", sub_type="st1.a", description="end")
        pub1.publish_event(origin="end", sub_type="st1", description="end")

        [res_list[i].ar.get(timeout=5) for i in xrange(3)]

        sub0.deactivate()
        sub1.deactivate()
        sub2.deactivate()
        sub3.deactivate()

        for i in xrange(4):
            res_list[i].res = []
            for x in xrange(res_list[i].count):
                res_list[i].res.append(res_list[i].gq.get(timeout=5))

        self.assertEquals(len(res_list[0].res), 3)
        self.assertEquals(res_list[0].res[0].description, "1")

        self.assertEquals(len(res_list[1].res), 2)
        self.assertEquals(res_list[1].res[0].description, "1")

        self.assertEquals(len(res_list[2].res), 3)
        self.assertEquals(res_list[2].res[0].description, "1")

        self.assertEquals(len(res_list[3].res), 2)
        self.assertEquals(res_list[3].res[0].description, "2")
开发者ID:ooici-dm,项目名称:pyon,代码行数:64,代码来源:test_event.py

示例6: GovernanceController

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]
class GovernanceController(object):


    def __init__(self,container):
        log.debug('GovernanceController.__init__()')
        self.container = container
        self.enabled = False
        self.interceptor_by_name_dict = dict()
        self.interceptor_order = []
        self.policy_decision_point_manager = None
        self.governance_dispatcher = None

    def start(self):

        log.debug("GovernanceController starting ...")

        config = CFG.interceptor.interceptors.governance.config

        if config is None:
            config['enabled'] = False

        if "enabled" in config:
            self.enabled = config["enabled"]

        log.debug("GovernanceInterceptor enabled: %s" % str(self.enabled))

        self.resource_policy_event_subscriber = None

        if self.enabled:
            self.initialize_from_config(config)

            self.resource_policy_event_subscriber = EventSubscriber(event_type="ResourcePolicyEvent", callback=self.policy_event_callback)
            self.resource_policy_event_subscriber.activate()

            self.rr_client = ResourceRegistryServiceProcessClient(node=self.container.node, process=self.container)
            self.policy_client = PolicyManagementServiceProcessClient(node=self.container.node, process=self.container)
            self.org_client = OrgManagementServiceProcessClient(node=self.container.node, process=self.container)

    def initialize_from_config(self, config):

        self.governance_dispatcher = GovernanceDispatcher()

        self.policy_decision_point_manager = PolicyDecisionPointManager()

        if 'interceptor_order' in config:
            self.interceptor_order = config['interceptor_order']

        if 'governance_interceptors' in config:
            gov_ints = config['governance_interceptors']

            for name in gov_ints:
                interceptor_def = gov_ints[name]

                # Instantiate and put in by_name array
                parts = interceptor_def["class"].split('.')
                modpath = ".".join(parts[:-1])
                classname = parts[-1]
                module = __import__(modpath, fromlist=[classname])
                classobj = getattr(module, classname)
                classinst = classobj()

                # Put in by_name_dict for possible re-use
                self.interceptor_by_name_dict[name] = classinst

    def stop(self):
        log.debug("GovernanceController stopping ...")

        if self.resource_policy_event_subscriber is not None:
            self.resource_policy_event_subscriber.deactivate()


    def process_incoming_message(self,invocation):

        self.process_message(invocation, self.interceptor_order,'incoming' )
        return self.governance_dispatcher.handle_incoming_message(invocation)

    def process_outgoing_message(self,invocation):
        self.process_message(invocation, reversed(self.interceptor_order),'outgoing')
        return self.governance_dispatcher.handle_outgoing_message(invocation)

    def process_message(self,invocation,interceptor_list, method):

        for int_name in interceptor_list:
            class_inst = self.interceptor_by_name_dict[int_name]
            getattr(class_inst, method)(invocation)

        return invocation

    def policy_event_callback(self, *args, **kwargs):
        resource_policy_event = args[0]

        policy_id = resource_policy_event.origin
        resource_id = resource_policy_event.resource_id
        resource_type = resource_policy_event.resource_type
        resource_name = resource_policy_event.resource_name

        log.info("Resource policy modified: %s %s %s" % ( policy_id, resource_id, resource_type))

        if resource_type == 'ServiceDefinition':  #TODO - REDO to have a configurable Org boundary by container
            ion_org = self.org_client.find_org()
#.........这里部分代码省略.........
开发者ID:oldpatricka,项目名称:pyon,代码行数:103,代码来源:governance_controller.py

示例7: ServiceGatewayService

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]
class ServiceGatewayService(BaseServiceGatewayService):
    """
	The Service Gateway Service is the service that uses a gevent web server and Flask
	to bridge HTTP requests to AMQP RPC ION process service calls.
    """

    def on_init(self):
        # defaults
        self.http_server = None

        # retain a pointer to this object for use in ProcessRPC calls
        global service_gateway_instance
        service_gateway_instance = self

        self.server_hostname = self.CFG.get_safe(
            "container.service_gateway.web_server.hostname", DEFAULT_WEB_SERVER_HOSTNAME
        )
        self.server_port = self.CFG.get_safe("container.service_gateway.web_server.port", DEFAULT_WEB_SERVER_PORT)
        self.web_server_enabled = self.CFG.get_safe("container.service_gateway.web_server.enabled", True)
        self.logging = self.CFG.get_safe("container.service_gateway.web_server.log")

        # Optional list of trusted originators can be specified in config.
        self.trusted_originators = self.CFG.get_safe("container.service_gateway.trusted_originators")
        if not self.trusted_originators:
            self.trusted_originators = None
            log.info("Service Gateway will not check requests against trusted originators since none are configured.")

        # Get the user_cache_size
        self.user_cache_size = self.CFG.get_safe("container.service_gateway.user_cache_size", DEFAULT_USER_CACHE_SIZE)

        # Start the gevent web server unless disabled
        if self.web_server_enabled:
            log.info("Starting service gateway on %s:%s", self.server_hostname, self.server_port)
            self.start_service(self.server_hostname, self.server_port)

        self.user_role_event_subscriber = EventSubscriber(
            event_type="UserRoleModifiedEvent", origin_type="Org", callback=self.user_role_event_callback
        )
        self.user_role_event_subscriber.activate()

        # Initialize an LRU Cache to keep user roles cached for performance reasons
        # maxSize = maximum number of elements to keep in cache
        # maxAgeMs = oldest entry to keep
        self.user_data_cache = LRUCache(self.user_cache_size, 0, 0)

    def on_quit(self):
        self.stop_service()

        if self.user_role_event_subscriber is not None:
            self.user_role_event_subscriber.deactivate()

    def start_service(self, hostname=DEFAULT_WEB_SERVER_HOSTNAME, port=DEFAULT_WEB_SERVER_PORT):
        """Responsible for starting the gevent based web server."""

        if self.http_server is not None:
            self.stop_service()

        self.http_server = WSGIServer((hostname, port), app, log=self.logging)
        self.http_server.start()

        return True

    def stop_service(self):
        """Responsible for stopping the gevent based web server."""
        if self.http_server is not None:
            self.http_server.stop()
        return True

    def is_trusted_address(self, requesting_address):

        if self.trusted_originators is None:
            return True

        for addr in self.trusted_originators:
            if requesting_address == addr:
                return True

        return False

    def user_role_event_callback(self, *args, **kwargs):
        """
        This method is a callback function for receiving User Role Modified Events.
        """
        user_role_event = args[0]
        org_id = user_role_event.origin
        user_id = user_role_event.user_id
        role_name = user_role_event.role_name
        log.debug("User Role modified: %s %s %s" % (org_id, user_id, role_name))

        # Evict the user and their roles from the cache so that it gets updated with the next call.
        if service_gateway_instance.user_data_cache.has_key(user_id):
            log.debug("Evicting user from the user_data_cache: %s" % user_id)
            service_gateway_instance.user_data_cache.evict(user_id)
开发者ID:ooici-eoi,项目名称:coi-services,代码行数:95,代码来源:service_gateway_service.py

示例8: PolicyManagementService

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]
class PolicyManagementService(BasePolicyManagementService):


    def on_init(self):
        self.event_pub = EventPublisher()

        self.policy_event_subscriber = EventSubscriber(event_type="ResourceModifiedEvent", origin_type="Policy", callback=self.policy_event_callback)
        self.policy_event_subscriber.activate()

    def on_quit(self):

        if self.policy_event_subscriber is not None:
            self.policy_event_subscriber.deactivate()


    """
    Provides the interface to define and manage policy and a repository to store and retrieve policy and templates for
    policy definitions, aka attribute authority.
    """
    def create_policy(self, policy=None):
        """Persists the provided Policy object for the specified Org id. The id string returned
        is the internal id by which Policy will be identified in the data store.

        @param policy    Policy
        @retval policy_id    str
        @throws BadRequest    if object passed has _id or _rev attribute
        """
        if not is_basic_identifier(policy.name):
            raise BadRequest("The policy name '%s' can only contain alphanumeric and underscore characters" % policy.name)

        policy.rule = policy.rule % (policy.name, policy.description)
        policy_id, version = self.clients.resource_registry.create(policy)
        return policy_id

    def update_policy(self, policy=None):
        """Updates the provided Policy object.  Throws NotFound exception if
        an existing version of Policy is not found.  Throws Conflict if
        the provided Policy object is not based on the latest persisted
        version of the object.

        @param policy    Policy
        @throws NotFound    object with specified id does not exist
        @throws BadRequest    if object does not have _id or _rev attribute
        @throws Conflict    object not based on latest persisted object version
        """
        if not is_basic_identifier(policy.name):
            raise BadRequest("The policy name '%s' can only contain alphanumeric and underscore characters" % policy.name)

        self.clients.resource_registry.update(policy)

    def read_policy(self, policy_id=''):
        """Returns the Policy object for the specified policy id.
        Throws exception if id does not match any persisted Policy
        objects.

        @param policy_id    str
        @retval policy    Policy
        @throws NotFound    object with specified id does not exist
        """
        if not policy_id:
            raise BadRequest("The policy_id parameter is missing")

        policy = self.clients.resource_registry.read(policy_id)
        if not policy:
            raise NotFound("Policy %s does not exist" % policy_id)
        return policy

    def delete_policy(self, policy_id=''):
        """For now, permanently deletes Policy object with the specified
        id. Throws exception if id does not match any persisted Policy.

        @param policy_id    str
        @throws NotFound    object with specified id does not exist
        """
        if not policy_id:
            raise BadRequest("The policy_id parameter is missing")

        policy = self.clients.resource_registry.read(policy_id)
        if not policy:
            raise NotFound("Policy %s does not exist" % policy_id)
        self.clients.resource_registry.delete(policy_id)


    def enable_policy(self, policy_id=''):
        """Sets a flag to enable the use of the policy rule

        @param policy_id    str
        @throws NotFound    object with specified id does not exist
        """
        policy = self.read_policy(policy_id)
        policy.enabled = True
        self.update_policy(policy)


    def disable_policy(self, policy_id=''):
        """Resets a flag to disable the use of the policy rule

        @param policy_id    str
        @throws NotFound    object with specified id does not exist
        """
#.........这里部分代码省略.........
开发者ID:dstuebe,项目名称:coi-services,代码行数:103,代码来源:policy_management_service.py

示例9: VisualizationService

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]
class VisualizationService(BaseVisualizationService):

    def on_start(self):

        # The data dictionary object holds a copy of all the viz products created by the service. The viz
        # products are indexed by the viz_product_type and data_product_id (which could be google_datatables or
        # mpl_graphs
        self.viz_data_dictionary = {}
        self.viz_data_dictionary['google_dt'] = {}
        self.viz_data_dictionary['google_realtime_dt'] = {}
        self.viz_data_dictionary['matplotlib_graphs'] = {}
        # Kind of redundant but we will maintain a separate list of data product_ids registered with the viz_service
        self.data_products = []

        # Create clients to interface with PubSub, Transform Management Service and Resource Registry
        self.pubsub_cli = self.clients.pubsub_management
        self.tms_cli = self.clients.transform_management
        self.rr_cli = self.clients.resource_registry
        self.dr_cli = self.clients.data_retriever
        self.dsm_cli = self.clients.dataset_management

        """
        # Create process definitions which will used to spawn off the transform processes
        self.matplotlib_proc_def = IonObject(RT.ProcessDefinition, name='viz_transform_process'+'.'+self.random_id_generator())
        self.matplotlib_proc_def.executable = {
            'module': 'ion.services.ans.visualization_service',
            'class':'VizTransformProcForMatplotlibGraphs'
        }
        self.matplotlib_proc_def_id, _ = self.rr_cli.create(self.matplotlib_proc_def)

        self.google_dt_proc_def = IonObject(RT.ProcessDefinition, name='viz_transform_process'+'.'+self.random_id_generator())
        self.google_dt_proc_def.executable = {
            'module': 'ion.services.ans.visualization_service',
            'class':'VizTransformProcForGoogleDT'
        }
        self.google_dt_proc_def_id, _ = self.rr_cli.create(self.google_dt_proc_def)
        """

        # Query resource registry to get process definitions and streams ids made by the bootstrap
        proc_def_ids,_ = self.rr_cli.find_resources(restype=RT.ProcessDefinition, lcstate=None, name="viz_matplotlib_transform_process", id_only=True)
        self.matplotlib_proc_def_id = proc_def_ids[0]

        proc_def_ids,_ = self.rr_cli.find_resources(restype=RT.ProcessDefinition, lcstate=None, name="viz_google_dt_transform_process", id_only=True)
        self.google_dt_proc_def_id = proc_def_ids[0]

        # Create a stream that all the transform processes will use to submit data back to the viz service
        self.viz_service_submit_stream_id = self.pubsub_cli.create_stream(name="visualization_service_submit_stream." + self.random_id_generator())

        # subscribe to this stream since all the results from transforms will be submitted here
        query = StreamQuery(stream_ids=[self.viz_service_submit_stream_id,])
        self.viz_service_submit_stream_sub_id = self.pubsub_cli.create_subscription(query=query, exchange_name="visualization_service_submit_queue")
        submit_stream_subscriber_registrar = StreamSubscriberRegistrar(process = self.container, node = self.container.node )
        submit_stream_subscriber = submit_stream_subscriber_registrar.create_subscriber(exchange_name='visualization_service_submit_queue', callback=self.process_submission)
        submit_stream_subscriber.start()

        self.pubsub_cli.activate_subscription(self.viz_service_submit_stream_sub_id)

        # Discover the existing data_product_ids active in the system
        sys_prod_ids, _ = self.rr_cli.find_resources(RT.DataProduct, None, None, True)

        # Register all the streams in the system, which will in turn start transform processes
        for dp_id in sys_prod_ids:
            self.register_new_data_product(dp_id)


        # listen for events when new data_products show up
        self.event_subscriber = EventSubscriber(
            event_type = "ResourceModifiedEvent",
            origin_type = "DataProduct",
            sub_type="UPDATE",
            callback=self.receive_new_dataproduct_event
        )

        self.event_subscriber.activate()

        return

    def on_stop(self):
        self.event_subscriber.deactivate()

        super(VisualizationService, self).on_stop()
        return

    def process_submission(self, packet, headers):

        # The packet is a dictionary containing the data_product_id and viz_product_type.
        if(packet["viz_product_type"] == "google_realtime_dt"):
            self.submit_google_realtime_dt(data_product_id=packet["data_product_id"], data_table=packet["data_table"])

        if(packet["viz_product_type"] == "google_dt"):
            self.submit_google_dt(data_product_id_token=packet["data_product_id_token"], data_table=packet["data_table"])

        if(packet["viz_product_type"] == "matplotlib_graphs"):
            self.submit_mpl_image(data_product_id=packet["data_product_id"], image_obj=packet["image_obj"],
                                image_name=packet["image_name"])

        return

    def start_google_dt_transform(self, data_product_id='', query=''):
        """Request to fetch the datatable for a data product as specified in the query. Query will also specify whether its a realtime view or one-shot
#.........这里部分代码省略.........
开发者ID:seman,项目名称:coi-services,代码行数:103,代码来源:visualization_service.py

示例10: ExternalDatasetAgentTestBase

# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import deactivate [as 别名]

#.........这里部分代码省略.........
    def _setup_resources(self):
        raise NotImplementedError('_setup_resources must be implemented in the subclass')

    def create_stream_and_logger(self, name, stream_id=''):
        if not stream_id or stream_id is '':
            stream_id = self._pubsub_client.create_stream(name=name, encoding='ION R2')

        pid = self._container_client.spawn_process(
            name=name+'_logger',
            module='ion.processes.data.stream_granule_logger',
            cls='StreamGranuleLogger',
            config={'process':{'stream_id':stream_id}}
        )
        log.info('Started StreamGranuleLogger \'{0}\' subscribed to stream_id={1}'.format(pid, stream_id))

        return stream_id

    def _start_finished_event_subscriber(self):

        def consume_event(*args,**kwargs):
            if args[0].description == 'TestingFinished':
                log.debug('TestingFinished event received')
                self._finished_events_received.append(args[0])
                if self._finished_count and self._finished_count == len(self._finished_events_received):
                    log.debug('Finishing test...')
                    self._async_finished_result.set(len(self._finished_events_received))
                    log.debug('Called self._async_finished_result.set({0})'.format(len(self._finished_events_received)))

        self._finished_event_subscriber = EventSubscriber(event_type='DeviceEvent', callback=consume_event)
        self._finished_event_subscriber.activate()

    def _stop_finished_event_subscriber(self):
        if self._finished_event_subscriber:
            self._finished_event_subscriber.deactivate()
            self._finished_event_subscriber = None


    ########################################
    # Custom assertion functions
    ########################################

    def assertListsEqual(self, lst1, lst2):
        lst1.sort()
        lst2.sort()
        return lst1 == lst2

    def assertSampleDict(self, val):
        """
        Verify the value is a sample dictionary for the sbe37.
        """
        #{'p': [-6.945], 'c': [0.08707], 't': [20.002], 'time': [1333752198.450622]}
        self.assertTrue(isinstance(val, dict))
        self.assertTrue(val.has_key('c'))
        self.assertTrue(val.has_key('t'))
        self.assertTrue(val.has_key('p'))
        self.assertTrue(val.has_key('time'))
        c = val['c'][0]
        t = val['t'][0]
        p = val['p'][0]
        time = val['time'][0]

        self.assertTrue(isinstance(c, float))
        self.assertTrue(isinstance(t, float))
        self.assertTrue(isinstance(p, float))
        self.assertTrue(isinstance(time, float))
开发者ID:dstuebe,项目名称:coi-services,代码行数:69,代码来源:test_external_dataset_agent.py


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