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


Python stomp.Connection方法代码示例

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


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

示例1: create_connection

# 需要导入模块: import stomp [as 别名]
# 或者: from stomp import Connection [as 别名]
def create_connection(client_cert, client_key, root_ca):
    client_path = None
    client_key_path = None
    if client_cert:
        client_path = 'client.cert'
        with open(client_path, 'wb') as file:
            file.write(client_cert)
            client_path = os.path.abspath(client_path)
    if client_key:
        client_key_path = 'client_key.key'
        with open(client_key_path, 'wb') as file:
            file.write(client_key)
    if root_ca:
        root_ca_path = 'root_ca.key'
        with open(root_ca_path, 'wb') as file:
            file.write(root_ca)

    if client_cert or client_key or root_ca:
        conn = stomp.Connection(host_and_ports=[(HOSTNAME, PORT)], use_ssl=True,
                                ssl_key_file=client_key_path, ssl_cert_file=client_path)
    else:
        conn = stomp.Connection([(HOSTNAME, PORT)])

    return conn 
开发者ID:demisto,项目名称:content,代码行数:26,代码来源:ActiveMQ.py

示例2: fetch_incidents

# 需要导入模块: import stomp [as 别名]
# 或者: from stomp import Connection [as 别名]
def fetch_incidents(client, conn, subscription_id, queue_name, topic_name):
    if not queue_name and not topic_name:
        raise ValueError('To fetch incidents you must provide either Queue Name or Topic Name')
    elif queue_name and topic_name:
        raise ValueError('Can\'t provide both Queue Name and Topic name.')

    # conn = stomp.Connection(heartbeats=(4000, 4000))
    listener = MsgListener()
    if client and len(client) > 0:
        conn.set_listener('Demisto', listener)

    if queue_name:
        conn.subscribe('/queue/' + queue_name, subscription_id, ack='client-individual')
    else:
        conn.subscribe(
            '/topic/' + topic_name,
            subscription_id,
            ack='client-individual',
            headers={'activemq.subscriptionName': client}
        )

    incidents = []
    time.sleep(10)
    for i in range(len(listener.result_arr)):
        msg = listener.result_arr[i]
        msg_id = listener.msg_ids[i]
        incidents.append({
            'Name': 'ActiveMQ incident:' + msg_id,
            'rawJSON': msg,
            'details': msg
        })
    demisto.incidents(incidents)

    for msg_id in listener.msg_ids:
        conn.ack(msg_id, subscription_id) 
开发者ID:demisto,项目名称:content,代码行数:37,代码来源:ActiveMQ.py

示例3: __init__

# 需要导入模块: import stomp [as 别名]
# 或者: from stomp import Connection [as 别名]
def __init__(self, topic_names, host, userid, password,
                 port=DEFAULT_STOMP_PORT):
        """
        Parameters:

          topic_names (:term:`string` or list/tuple thereof): Name(s) of the
            HMC notification topic(s).
            Must not be `None`.

          host (:term:`string`):
            HMC host. For valid formats, see the
            :attr:`~zhmcclient.Session.host` property.
            Must not be `None`.

          userid (:term:`string`):
            Userid of the HMC user to be used.
            Must not be `None`.

          password (:term:`string`):
            Password of the HMC user to be used.
            Must not be `None`.

          port (:term:`integer`):
            STOMP TCP port. Defaults to
            :attr:`~zhmcclient._constants.DEFAULT_STOMP_PORT`.
        """
        if not isinstance(topic_names, (list, tuple)):
            topic_names = [topic_names]
        self._topic_names = topic_names
        self._host = host
        self._port = port
        self._userid = userid
        self._password = password

        # Wait timeout to honor keyboard interrupts after this time:
        self._wait_timeout = 10.0  # seconds

        # Subscription ID. We use some value that allows to identify on the
        # HMC that this is the zhmcclient, but otherwise we are not using
        # this value ourselves.
        self._sub_id = 'zhmcclient.%s' % id(self)

        # Sync variables for thread-safe handover between listener thread and
        # receiver thread:
        self._handover_dict = {}
        self._handover_cond = threading.Condition()

        # Lazy importing for stomp, because it is so slow (ca. 5 sec)
        if 'Stomp_Connection' not in globals():
            from stomp import Connection as Stomp_Connection

        self._conn = Stomp_Connection(
            [(self._host, self._port)], use_ssl="SSL")
        listener = _NotificationListener(self._handover_dict,
                                         self._handover_cond)
        self._conn.set_listener('', listener)
        self._conn.connect(self._userid, self._password, wait=True)

        for topic_name in self._topic_names:
            dest = "/topic/" + topic_name
            self._conn.subscribe(destination=dest, id=self._sub_id, ack='auto') 
开发者ID:zhmcclient,项目名称:python-zhmcclient,代码行数:63,代码来源:_notification.py

示例4: consumer

# 需要导入模块: import stomp [as 别名]
# 或者: from stomp import Connection [as 别名]
def consumer(id, num_thread=1):
    """
    Main loop to consume messages from the Rucio Cache producer.
    """

    logging.info('Rucio Cache consumer starting')

    brokers_alias = []
    brokers_resolved = []
    try:
        brokers_alias = [b.strip() for b in config_get('messaging-cache', 'brokers').split(',')]
    except:
        raise Exception('Could not load rucio cache brokers from configuration')

    logging.info('resolving rucio cache broker dns alias: %s' % brokers_alias)

    brokers_resolved = []
    for broker in brokers_alias:
        addrinfos = socket.getaddrinfo(broker, 0, socket.AF_INET, 0, socket.IPPROTO_TCP)
        brokers_resolved.extend(ai[4][0] for ai in addrinfos)

    logging.debug('Rucio cache brokers resolved to %s', brokers_resolved)

    conns = {}
    for broker in brokers_resolved:
        conn = stomp.Connection(host_and_ports=[(broker, config_get_int('messaging-cache', 'port'))],
                                use_ssl=True,
                                ssl_key_file=config_get('messaging-cache', 'ssl_key_file'),
                                ssl_cert_file=config_get('messaging-cache', 'ssl_cert_file'),
                                vhost=config_get('messaging-cache', 'broker_virtual_host', raise_exception=False)
                                )
        conns[conn] = Consumer(conn.transport._Transport__host_and_ports[0], account=config_get('messaging-cache', 'account'), id=id, num_thread=num_thread)

    logging.info('consumer started')

    while not GRACEFUL_STOP.is_set():

        for conn in conns:

            if not conn.is_connected():
                logging.info('connecting to %s' % conn.transport._Transport__host_and_ports[0][0])
                record_counter('daemons.messaging.cache.reconnect.%s' % conn.transport._Transport__host_and_ports[0][0].split('.')[0])

                conn.set_listener('rucio-cache-messaging', conns[conn])
                conn.start()
                conn.connect()
                conn.subscribe(destination=config_get('messaging-cache', 'destination'),
                               id='rucio-cache-messaging',
                               ack='auto')

        time.sleep(1)

    logging.info('graceful stop requested')

    for conn in conns:
        try:
            conn.disconnect()
        except:
            pass

    logging.info('graceful stop done') 
开发者ID:rucio,项目名称:rucio,代码行数:63,代码来源:consumer.py

示例5: alert

# 需要导入模块: import stomp [as 别名]
# 或者: from stomp import Connection [as 别名]
def alert(self, matches):
        alerts = []

        qk = self.rule.get('query_key', None)

        fullmessage = {}
        for match in matches:
            if qk is not None:
                resmatch = lookup_es_key(match, qk)
            else:
                resmatch = None

            if resmatch is not None:
                elastalert_logger.info(
                    'Alert for %s, %s at %s:' % (self.rule['name'], resmatch, lookup_es_key(match, self.rule['timestamp_field'])))
                alerts.append(
                    'Alert for %s, %s at %s:' % (self.rule['name'], resmatch, lookup_es_key(
                        match, self.rule['timestamp_field']))
                )
                fullmessage['match'] = resmatch
            else:
                elastalert_logger.info('Rule %s generated an alert at %s:' % (
                    self.rule['name'], lookup_es_key(match, self.rule['timestamp_field'])))
                alerts.append(
                    'Rule %s generated an alert at %s:' % (self.rule['name'], lookup_es_key(
                        match, self.rule['timestamp_field']))
                )
                fullmessage['match'] = lookup_es_key(
                    match, self.rule['timestamp_field'])
            elastalert_logger.info(str(BasicMatchString(self.rule, match)))

        fullmessage['alerts'] = alerts
        fullmessage['rule'] = self.rule['name']
        fullmessage['rule_file'] = self.rule['rule_file']

        fullmessage['matching'] = str(BasicMatchString(self.rule, match))
        fullmessage['alertDate'] = datetime.datetime.now(
        ).strftime("%Y-%m-%d %H:%M:%S")
        fullmessage['body'] = self.create_alert_body(matches)

        fullmessage['matches'] = matches

        self.stomp_hostname = self.rule.get('stomp_hostname', 'localhost')
        self.stomp_hostport = self.rule.get('stomp_hostport', '61613')
        self.stomp_login = self.rule.get('stomp_login', 'admin')
        self.stomp_password = self.rule.get('stomp_password', 'admin')
        self.stomp_destination = self.rule.get(
            'stomp_destination', '/queue/ALERT')
        self.stomp_ssl = self.rule.get('stomp_ssl', False)

        conn = stomp.Connection([(self.stomp_hostname, self.stomp_hostport)], use_ssl=self.stomp_ssl)

        conn.start()
        conn.connect(self.stomp_login, self.stomp_password)
        # Ensures that the CONNECTED frame is received otherwise, the disconnect call will fail.
        time.sleep(1)
        conn.send(self.stomp_destination, json.dumps(fullmessage))
        conn.disconnect() 
开发者ID:Yelp,项目名称:elastalert,代码行数:60,代码来源:alerts.py


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