本文整理汇总了Python中pyon.event.event.EventSubscriber.activate方法的典型用法代码示例。如果您正苦于以下问题:Python EventSubscriber.activate方法的具体用法?Python EventSubscriber.activate怎么用?Python EventSubscriber.activate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyon.event.event.EventSubscriber
的用法示例。
在下文中一共展示了EventSubscriber.activate方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_l4_ci_sa_rq_145_323
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [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)
示例2: test_pub_on_different_subtypes
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [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")
示例3: _start_event_subscribers
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [as 别名]
def _start_event_subscribers(self):
"""
Create subscribers for agent and driver events.
"""
def consume_event(*args, **kwargs):
log.info('Test recieved ION event: args=%s kwargs=%s.', str(args), str(kwargs))
self._events_received.append(args[0])
if self._no_events and self._no_events == len(self._event_received):
self._async_event_result.set()
event_sub = EventSubscriber(event_type="DeviceEvent", callback=consume_event)
event_sub.activate()
self._event_subscribers.append(event_sub)
示例4: __init__
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [as 别名]
def __init__(self):
# Start event subscribers, add stop to cleanup.
self.no_events = None
self.async_event_result = AsyncResult()
self.events_received = []
self.event_subscribers = []
def consume_event(*args, **kwargs):
log.info('Test recieved ION event: args=%s, kwargs=%s, event=%s.',
str(args), str(kwargs), str(args[0]))
self.events_received.append(args[0])
if self.no_events and self.no_events == len(self.event_received):
self.async_event_result.set()
event_sub = EventSubscriber(event_type="DeviceEvent", callback=consume_event)
event_sub.activate()
self.event_subscribers.append(event_sub)
示例5: Notification
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [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()
示例6: ProcessDispatcherServiceIntTest
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [as 别名]
class ProcessDispatcherServiceIntTest(IonIntegrationTestCase):
def setUp(self):
self._start_container()
self.container.start_rel_from_url('res/deploy/r2cei.yml')
self.pd_cli = ProcessDispatcherServiceClient(node=self.container.node)
self.process_definition = ProcessDefinition(name='test_process')
self.process_definition.executable = {'module': 'ion.services.cei.test.test_process_dispatcher',
'class':'TestProcess'}
self.process_definition_id = self.pd_cli.create_process_definition(self.process_definition)
self.event_queue = queue.Queue()
self.event_sub = None
def tearDown(self):
if self.event_sub:
self.event_sub.deactivate()
def _event_callback(self, event, *args, **kwargs):
self.event_queue.put(event)
def subscribe_events(self, origin):
self.event_sub = EventSubscriber(event_type="ProcessLifecycleEvent",
callback=self._event_callback, origin=origin, origin_type="DispatchedProcess")
self.event_sub.activate()
def await_state_event(self, pid, state):
event = self.event_queue.get(timeout=5)
log.debug("Got event: %s", event)
self.assertEqual(event.origin, pid)
self.assertEqual(event.state, state)
return event
def test_create_schedule_cancel(self):
process_schedule = ProcessSchedule()
pid = self.pd_cli.create_process(self.process_definition_id)
self.subscribe_events(pid)
pid2 = self.pd_cli.schedule_process(self.process_definition_id,
process_schedule, configuration={}, process_id=pid)
self.assertEqual(pid, pid2)
self.await_state_event(pid, ProcessStateEnum.SPAWN)
# now try communicating with the process to make sure it is really running
test_client = TestClient()
for i in range(5):
# this timeout may be too low
self.assertEqual(i+1, test_client.count(timeout=1))
# kill the process and start it again
self.pd_cli.cancel_process(pid)
self.await_state_event(pid, ProcessStateEnum.TERMINATE)
oldpid = pid
pid = self.pd_cli.create_process(self.process_definition_id)
self.subscribe_events(pid)
pid2 = self.pd_cli.schedule_process(self.process_definition_id,
process_schedule, configuration={}, process_id=pid)
self.assertEqual(pid, pid2)
self.assertNotEqual(oldpid, pid)
self.await_state_event(pid, ProcessStateEnum.SPAWN)
for i in range(5):
# this timeout may be too low
self.assertEqual(i+1, test_client.count(timeout=1))
# kill the process for good
self.pd_cli.cancel_process(pid)
self.await_state_event(pid, ProcessStateEnum.TERMINATE)
def test_schedule_bad_config(self):
process_schedule = ProcessSchedule()
# a non-JSON-serializable IonObject
o = ProcessTarget()
with self.assertRaises(BadRequest) as ar:
self.pd_cli.schedule_process(self.process_definition_id,
process_schedule, configuration={"bad" : o})
self.assertTrue(ar.exception.message.startswith("bad configuration"))
示例7: test_pub_on_different_subsubtypes
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [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")
示例8: GovernanceController
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [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()
#.........这里部分代码省略.........
示例9: ServiceGatewayService
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [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)
示例10: PolicyManagementService
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [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
"""
#.........这里部分代码省略.........
示例11: VisualizationService
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [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
#.........这里部分代码省略.........
示例12: ExternalDatasetAgentTestBase
# 需要导入模块: from pyon.event.event import EventSubscriber [as 别名]
# 或者: from pyon.event.event.EventSubscriber import activate [as 别名]
#.........这里部分代码省略.........
########################################
# Private "setup" functions
########################################
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))