def __ssl_connect(self): conn = stomp.Connection(host_and_ports=[ ('localhost', int(os.environ["STOMP_PORT_TLS"])) ], use_ssl=True, ssl_key_file=ssl_key_file, ssl_cert_file=ssl_cert_file, ssl_ca_certs=ssl_ca_certs) print("FILE: ".format(ssl_cert_file)) conn.connect("guest", "guest") return conn
def stompConnect(self): try: host_and_ports = (self.host, self.port) self.conn = stomp.Connection([host_and_ports]) self.conn.start() self.conn.connect(self.userName, self.password) except stomp.exception.NotConnectedException, e: try: raise TransportException(e.strerror) except AttributeError: raise TransportException('Unspecified exception encountered')
def consume(): HOST = "127.0.0.1" PORT = 61613 QUEUE_NAME = "/queue/lxw_activemq" conn = stomp.Connection([(HOST, PORT)]) conn.set_listener("", MyListener()) conn.start() # essential conn.connect(wait=True) # essential conn.subscribe(destination=QUEUE_NAME, id=1, ack="auto") time.sleep(3)
def __init__(self): #Instance state variables self.window_date = "" self.window_time = "" self.current = {} self.previous = {} self.stats = {} #Connection variables self.pub_conn = stomp.Connection(host_and_ports=[('localhost', '61613')]) self.pub_conn.connect(login='******', passcode='manager', wait=True)
def __init__(self, workflow): self.workflow = workflow self.destination = {} # taskId : QueueInfo self.preQueue = {} # taskId : QueueInfo self.postQueue = {} # taskId : QueueInfo self.rxConnections = {} self.txConnection = stomp.Connection(self.workflow.getBroker()) self.txConnection.connect(wait=True) # add credentials? self.consumers = [] self.cacheManagerTask = CacheManagerTask(workflow)
def start(): print '####################' print '# GUMSTIX MAIN APP #' print '####################' global conn global motors global run global sensorControl global commandQ run = True ##Start Queues for commands commandQ = Queue.Queue() ##Start stomp connection logger.info('Starting Stomp') conn = stomp.Connection([(hostIp, hostPort)]) # Who to connect to conn.set_listener('', Listener()) # Rover specific listener conn.start() conn.connect(wait=True) conn.subscribe(destination=queueCommands, ack='auto') # Auto get commands ##Setup motors class logger.info('Configuring Motors') motors = motor_controls(config.get('motors', 'wheelBase'), config.get('motors', 'maxAngle'), config.get('motors', 'halfLength'), config.get('motors', 'diffInc'), config.get('motors', 'servoMid'), config.get('motors', 'servoDif')) ##Setup sensor threads if config.getboolean('sensors', 'enabled'): logger.info('Configuring Sensors') sensorControl(ast.literal_eval(config.get('sensors', 'config'))) # Start data collection timer st = threading.Timer( config.get('sensors', 'timer'), sensors_data_collect(config.get('sensors', 'timer'))) st.start() ##Loop through other processes while run: try: ##Handle Command Queue command = commandQ.get(0) command_handle(command) commandQ.task_done() except Queue.Empty: pass conn.send("Rover '%s' Disconnecting" % RID, destination=queueLog) st.stop() conn.disconnect()
def test_timeout(self): conn = stomp.Connection([('192.0.2.0', 60000)], timeout=5, reconnect_attempts_max=1) conn.set_listener('', self.listener) try: ms = monotonic() conn.connect("test", "test") self.fail("shouldn't happen") except exception.ConnectFailedException: pass # success! ms = monotonic() - ms self.assertTrue(ms > 5.0, 'connection timeout should have been at least 5 seconds')
def subscribe(self, topic, on_msg): self.on_msg = on_msg c = stomp.Connection([(self.ip, int(self.port))]) listener = self._Listener() listener.set_on_msg(on_msg) c.set_listener('', listener) c.start() c.connect(self.user, self.pw, wait=True) c.subscribe(destination="/topic/" + topic, id=1, ack='auto') time.sleep(0.01) # TODO fix this properly thread = Thread(target=self._keepalive) thread.start()
def connect_activemqs(self): print 'start connect_activemq' self.frontier_sender_conn = stomp.Connection( host_and_ports=[(self.conf.frontier_host, self.conf.frontier_port)]) print 'stomp.connection finished' self.frontier_sender_conn.start() print 'stomp.frontier_sender_conn.start finished' self.frontier_sender_conn.connect() print 'stomp.frontier_sender_conn.connect finished' return True
def main() -> None: host_name = socket.gethostname() host_ip = socket.gethostbyname(host_name) host_port = 61613 queue = "test_queue" conn = stomp.Connection([(host_ip, host_port)]) if try_connection(conn, host_ip, host_port): subscribe(conn, queue, host_ip, host_port) send_message(conn, queue) time.sleep(1) conn.disconnect()
def get_connection(self): logging.info("connection =") connection = stomp.Connection(host_and_ports=self._brokers, use_ssl=True, ssl_version=3) logging.info("Starting connection") connection.start() logging.info("connection.connect") connection.connect(self._user, self._password, wait=False) time.sleep(0.5) return connection
def queue_message(message, subject, to): conn = stomp.Connection([('mq', 61613)]) conn.set_listener('', MyListener()) conn.start() conn.connect('user', 'user', wait=True) #conn.subscribe(destination='/queue/test', id=1, ack='auto') queue = {"message": message, "subject": subject, "to": to} conn.send(body=json.dumps(queue), destination='/queue/emailer') time.sleep(0.01) conn.disconnect()
def receive_from_queue(): conn = stomp.Connection([(conf_data['mq']['host'], conf_data['mq']['port']) ]) conn.set_listener(listener_name, SampleListener(conn)) # 注册消息监听者,异步 connect_and_subscribe(conn, queue_name) while True: try: time.sleep(1) except: break conn.disconnect()
def test_noresponse(self): try: conn = stomp.Connection([('127.0.0.1', 60000)], heartbeats=(1000, 1000)) listener = TestListener(print_to_log=True) conn.set_listener('', listener) self.timeout_thread.start() conn.connect(wait=True) self.fail("Shouldn't happen") except ConnectFailedException: logging.info('Received connect failed - test success') except Exception: self.fail("Shouldn't happen")
def __init__(self, topic, host, userid, password, port=DEFAULT_STOMP_PORT): """ Parameters: topic (:term:`string`): Name of the HMC notification topic. 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`. """ self._topic = topic 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() 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.start() self._conn.connect(self._userid, self._password, wait=True) dest = "/topic/" + topic self._conn.subscribe(destination=dest, id=self._sub_id, ack='auto')
def consume(options): connection = stomp.Connection(host_and_ports=[(options.host, options.port)]) try: connection.set_listener('', SimpleListener()) connection.start() connection.connect() connection.subscribe(destination=options.destination, ack='auto') while True: time.sleep(60) finally: connection.disconnect()
def setUp(self): conn = stomp.Connection(get_default_host()) # check thread override here conn.transport.override_threading(create_thread) listener = ReconnectListener(conn) conn.set_listener('', listener) conn.connect(get_default_user(), get_default_password(), wait=True) self.conn = conn self.listener = listener self.timestamp = time.strftime('%Y%m%d%H%M%S')
def create_stomp_connection() -> StompConnection11: """Create a Connection object with the correct parameters.""" host_and_ports = [("localhost", 61613)] conn = stomp.Connection(host_and_ports=host_and_ports, heartbeats=(10000, 0)) conn.connect("beer_garden", "password", wait=True, headers={"client-id": "beer_garden"}) return conn
def send(self, data): """ Connect to the stomp host and send a single notification (or a list of notifications). :param data: Either a single notification (as returned by `make_notification`) or a list of such. :return: a list of notification bodies that failed to send """ # If only a single notification, put it in a list if isinstance(data, dict) and 'body' in data: data = [data] conn = stomp.Connection(host_and_ports=self._host_and_ports) if self._use_ssl: # This requires stomp >= 4.1.15 conn.set_ssl(for_hosts=self._host_and_ports, key_file=self._key, cert_file=self._cert) conn.set_listener('StompyListener', StompyListener(self.logger)) try: conn.start() # If cert/key are used, ignore username and password if self._use_ssl: conn.connect(wait=True) else: conn.connect(username=self._username, passcode=self._password, wait=True) except stomp.exception.ConnectFailedException as exc: self.logger.error("Connection to %s failed %s", repr(self._host_and_ports), str(exc)) return [] failedNotifications = [] for notification in data: result = self._send_single(conn, notification) if result: failedNotifications.append(result) if conn.is_connected(): conn.disconnect() if failedNotifications: self.logger.warning('Failed to send to %s %i docs out of %i', repr(self._host_and_ports), len(failedNotifications), len(data)) return failedNotifications
def send(self, token, username=None, *args): if not username or len(args) <= 0: return { 'status': 1, 'message': 'Usage: send <user> <friend> <message>' } message = ' '.join(args) receiver = User.get_or_none(User.username == username) if receiver: res1 = Friend.get_or_none((Friend.user == token.owner) & (Friend.friend == receiver)) res2 = Friend.get_or_none((Friend.user == receiver) & (Friend.friend == token.owner)) if res1 or res2: online = Token.get_or_none(Token.owner == receiver) if online: # connect to ActiveMQ conn = stomp.Connection([('localhost', 61613)]) conn.start() conn.connect('admin', 'admin', wait=True) dest = '/queue/' + str(username) # <<<USER_A->USER_B: HELLO WORLD>>> msg_formatted = '<<<{USER_A}->{USER_B}: {msg}>>>'.format(USER_A=token.owner.username, USER_B=username, msg=message) conn.send(body=msg_formatted, destination=dest) conn.disconnect() return { 'status': 0, 'message': 'Success!' #activemq message } else: return{ 'status': 1, 'message': '{} is not online'.format(username) } else: return { 'status': 1, 'message': '{} is not your friend'.format(username) } else: return { 'status': 1, 'message': 'No such user exist' } pass
def __ssl_connect(self): conn = stomp.Connection(user="******", passcode="guest", host_and_ports=[('localhost', 61614)], use_ssl=True, ssl_key_file=ssl_key_file, ssl_cert_file=ssl_cert_file, ssl_ca_certs=ssl_ca_certs) print "FILE: ", ssl_cert_file conn.start() conn.connect() return conn
def send(self, data): """ Connect to the stomp host and send a single notification (or a list of notifications). :param data: Either a single notification (as returned by `make_notification`) or a list of such. :return: a list of successfully sent notification bodies """ if not isinstance(data, list): self.logger.error( "Argument for send method has to be a list, not %s", type(data)) return data conn = stomp.Connection(host_and_ports=self._host_and_ports) if (self._use_ssl): conn.set_ssl(for_hosts=self._host_and_ports, key_file=self._key, cert_file=self._cert) conn.set_listener('StompyListener', StompyListener(self.logger)) try: conn.start() # If cert/key are used, ignore username and password if (self._use_ssl): conn.connect(wait=True) else: conn.connect(username=self._username, passcode=self._password, wait=True) except stomp.exception.ConnectFailedException as exc: self.logger.error("Connection to %s failed %s", repr(self._host_and_ports), str(exc)) return [] failedNotifications = [] for notification in data: result = self._send_single(conn, notification) if result: failedNotifications.append(result) if conn.is_connected(): conn.disconnect() if failedNotifications: self.logger.warning('Failed to send to %s %i docs out of %i', repr(self._host_and_ports), len(failedNotifications), len(data)) return failedNotifications
def main(): parser = argparse.ArgumentParser( description='Submit a run to the autoreduction service.', epilog='./manual-submission.py GEM 83880 [-e 83882]') parser.add_argument('instrument', metavar='instrument', type=str, help='a string of the instrument name e.g "GEM"') parser.add_argument( '-e', metavar='end_run_number', nargs='?', type=int, help='if submitting a range, the end run number e.g. "83882"') parser.add_argument('start_run_number', metavar='start_run_number', type=int, help='the start run number e.g. "83880"') args = parser.parse_args() run_numbers = [args.start_run_number] if args.e: # Range submission if not args.e > args.start_run_number: print("'end_run_number' must be greater than 'start_run_number'.") print("e.g './manual-submission.py GEM 83880 -e 83882'") sys.exit(1) run_numbers = range(args.start_run_number, args.e + 1) print("Logging into ICAT") icat_client = icat.client.Client(ICAT['URL']) icat_client.login(ICAT['AUTH'], { 'username': ICAT['USER'], 'password': ICAT['PASSWORD'] }) print("Logging into ActiveMQ " + ACTIVE_MQ['URL']) activemq_client = stomp.Connection([(ACTIVE_MQ['URL'], 61613)]) activemq_client.start() activemq_client.connect(ACTIVE_MQ['USER'], ACTIVE_MQ['PASSWORD'], wait=True) instrument = args.instrument.upper() for run in run_numbers: datafile = get_data_file(icat_client, instrument, run, "nxs") location = datafile.location rb_num = datafile.dataset.investigation.name submit_run(activemq_client, rb_num, instrument, location, run)
def __init__( self, host: str, port: int, username: str, password: str, destinations: list[str], connectionParams: Optional[dict] = None, ack: str = "auto", ): """ Be careful with the ``ack`` parameter. This will just set the ``ack`` parameter of the ~stomp.Connection.subscribe method, but it is up to the listener to effectively ack/nack if needed. :param host: alias of the broker :param port: port to connect to :param username: username to connect to the broker :param password: password to connect to the broker :param destinations: list of topic or queues to listen to :param connectionParams: any parameters that should be passed to ~stomp.Connection :param ack: see ~stomp.Connection.subscribe """ if not connectionParams: connectionParams = {} # Keep the list of connections self.connections = {} # Resolve the various brokers behind the alias # We have to make sure to use only either ipv4 or ipv6 # to avoid doubling the messages brokers = _resolve_brokers(host, port, ipv4Only=True) # We create independant connections for each host behind the broker alias for broker in brokers: conn = stomp.Connection([broker], **connectionParams) connAndSubArgs = [ conn, broker, username, password, destinations, ack ] self._connectAndSubscribe(*connAndSubArgs) conn.set_listener( "ReconnectListener", ReconnectListener(self._connectAndSubscribe, *connAndSubArgs)) connectionID = "%s-%s" % (broker[0], broker[1]) self.connections[connectionID] = conn
def send(self): # depending on the value of the port number indicates the distribution # of the message to AlertViz # 9581 is global distribution thru ThriftClient to Edex # 61999 is local distribution if (int(self.port) == 61999): # use stomp.py conn = stomp.Connection(host_and_ports=[(self.host, 61999)]) timeout = threading.Timer(5.0, self.connection_timeout, [conn]) try: timeout.start(); conn.start() finally: timeout.cancel() conn.connect() sm = ET.Element("statusMessage") sm.set("machine", socket.gethostname()) sm.set("priority", self.priority) sm.set("category", self.category) sm.set("sourceKey", self.source) sm.set("audioFile", self.audioFile) if self.filters is not None and len(self.filters) > 0: sm.set("filters", self.filters) msg = ET.SubElement(sm, "message") msg.text = self.message details = ET.SubElement(sm, "details") msg = ET.tostring(sm, "UTF-8") try : conn.send(msg, destination='/queue/messages') time.sleep(2) finally: conn.stop() else: # use ThriftClient alertVizRequest = createRequest(self.message, self.priority, self.source, self.category, self.audioFile, self.filters) thriftClient = ThriftClient.ThriftClient(self.host, self.port, "/services") serverResponse = None try: serverResponse = thriftClient.sendRequest(alertVizRequest) except Exception, ex: print "Caught exception submitting AlertVizRequest: ", str(ex) if (serverResponse != "None"): print "Error occurred submitting Notification Message to AlertViz receiver: ", serverResponse sys.exit(1) else: print "Response: " + str(serverResponse)
def _connectIfNeeded(self, description): self.log("connectIfNeeded start (" + description + ")") self._connectIfNeededLock.acquire(blocking=True, timeout=-1) if self.connected: self.log("connectIfNeeded already connected(" + description + ")") self._connectIfNeededLock.release() return self.stompConnection = stomp.Connection( host_and_ports=[ (self.fullConnectionDetails["FormattedConnectionDetails"]["Url"], self.fullConnectionDetails["FormattedConnectionDetails"]["Port"]) ], heartbeats=(4000, 4000) #heartbeats every 4 seconds ) if self.fullConnectionDetails["FormattedConnectionDetails"]["Protocol"] == "stomp": pass elif self.fullConnectionDetails["FormattedConnectionDetails"]["Protocol"] == "stomp+ssl": self.stompConnection.set_ssl( for_hosts=[(self.fullConnectionDetails["FormattedConnectionDetails"]["Url"], self.fullConnectionDetails["FormattedConnectionDetails"]["Port"])], ssl_version=ssl.PROTOCOL_TLSv1_2) else: self._connectIfNeededLock.release() raise Exception("Unknown protocol") if self.clientId is None: self.stompConnection.connect( self.fullConnectionDetails["Username"], self.fullConnectionDetails["Password"], wait=True ) else: self.stompConnection.connect( self.fullConnectionDetails["Username"], self.fullConnectionDetails["Password"], wait=True, headers = {'client-id': self.clientId} ) self.stompConnection.set_listener( '', StompConnectionListenerClass( messageFunction=self._onMessage, disconnectedFunction=self._onDisconnected, errorFunction=self._onError ) ) if self.clientId is None: print("STOMP Connection successful " + description) else: print("STOMP Connection successful " + description + " using client id " + self.clientId) self.connected = True self._connectIfNeededLock.release()
def _connect(self): """Connects to MSG server if not already connected.""" cx = self._cx if cx is None or not cx.is_connected(): self._log(logging_DEBUG, 'Connecting.') # create connection global stomp_major_version if stomp_major_version > 2: cx = stomp.Connection(self._cx_hostname_ports) else: cx = stomp.Connection(*self._cx_params) # add logger listener to connection if self._logger is not None: cx.set_listener('logger', LoggerListener(self._logger)) cx.start() if stomp_major_version > 2: cx.connect(username=self._cx_username, passcode=self._cx_password) else: cx.connect() self._cx = cx self._log(logging_DEBUG, 'Connected.')
def create_stomp_connection(self): """Creates the Connection class and closes when completed""" host_and_ports = [("localhost", 61613)] conn = stomp.Connection(host_and_ports=host_and_ports, heartbeats=(10000, 0)) conn.connect("beer_garden", "password", wait=True, headers={"client-id": "beer_garden"}) return conn
def start(): logging.info('Starting ActiveMQ Listener') ip = read_conf.get_config('CONFIG_MQ', 'IP') port = int(read_conf.get_config('CONFIG_MQ', 'PORT')) logging.info('Server : ' + ip) logging.info('Topic : ' + '/topic/macro_data') conn = stomp.Connection([(ip, port)]) connect_and_subscribe(conn) logging.info('Started listener successfully : macro_data') conn2 = stomp.Connection([(ip, port)]) connect_and_subscribe_unstruct(conn2) logging.info('Started listener successfully : unstructured_data') while True: time.sleep(20) conn.disconnect()
def sendMessage(brokerHost, brokerPort, destination, msg, aheaders): conn = stomp.Connection([(brokerHost, brokerPort)], auto_content_length=False) conn.start() conn.connect() tx = conn.begin() headers = dict(aheaders) headers['persistent'] = 'true' conn.send(body=msg, destination=destination, headers=headers) conn.commit(tx) time.sleep(1) conn.disconnect() print('{} Ok'.format(msg)) logging.info('businessKey_send_to_mq_gmp: %s ' % (format(msg)))