예제 #1
0
def _get_connection_dict(host_port_list,
                         use_ssl=False,
                         cert_file=None,
                         key_file=None,
                         vhost=None,
                         force=False):
    """
    get dict {conn_id: connection}
    """
    tmp_logger = logger_utils.make_logger(base_logger,
                                          method_name='_get_connection_dict')
    conn_dict = dict()
    # resolve all distinct hosts behind hostname
    resolved_host_port_set = set()
    for host_port in host_port_list:
        host, port = host_port.split(':')
        port = int(port)
        addrinfos = socket.getaddrinfo(host, port)
        for addrinfo in addrinfos:
            resolved_host = socket.getfqdn(addrinfo[4][0])
            resolved_host_port_set.add((resolved_host, port))
    # make connections
    for host, port in resolved_host_port_set:
        host_port = '{0}:{1}'.format(host, port)
        conn_id = host_port
        if conn_id not in conn_dict:
            try:
                conn = stomp.Connection12(host_and_ports=[(host, port)],
                                          vhost=vhost)
                if use_ssl:
                    ssl_opts = {
                        'ssl_version': ssl.PROTOCOL_TLSv1,
                        'cert_file': cert_file,
                        'key_file': key_file
                    }
                    conn.set_ssl(for_hosts=[(host, port)], **ssl_opts)
            except AttributeError:
                # Older version of stomp.py
                ssl_opts = {
                    'use_ssl': use_ssl,
                    'ssl_version': ssl.PROTOCOL_TLSv1,
                    'ssl_cert_file': cert_file,
                    'ssl_key_file': key_file
                }
                conn = stomp.Connection12(host_and_ports=[(host, port)],
                                          vhost=vhost,
                                          **ssl_opts)
            conn_dict[conn_id] = conn
    tmp_logger.debug('got {0} connections to {1}'.format(
        len(conn_dict), ' , '.join(conn_dict.keys())))
    return conn_dict
예제 #2
0
파일: notify.py 프로젝트: akanksham3/pagure
def stomp_publish(topic, message):
    """ Try to publish a message on a Stomp-compliant message bus. """
    if not pagure_config.get("STOMP_NOTIFICATIONS", True):
        return
    # We catch Exception if we want :-p
    # pylint: disable=broad-except
    # Ignore message about stomp import
    # pylint: disable=import-error
    try:
        import stomp

        global stomp_conn
        if not stomp_conn or not stomp_conn.is_connected():
            stomp_conn = stomp.Connection12(pagure_config["STOMP_BROKERS"])
            if pagure_config.get("STOMP_SSL"):
                stomp_conn.set_ssl(
                    pagure_config["STOMP_BROKERS"],
                    key_file=pagure_config.get("STOMP_KEY_FILE"),
                    cert_file=pagure_config.get("STOMP_CERT_FILE"),
                    password=pagure_config.get("STOMP_CREDS_PASSWORD"),
                )
            from stomp import PrintingListener

            stomp_conn.set_listener("", PrintingListener())
            stomp_conn.start()
            stomp_conn.connect(wait=True)
        hierarchy = pagure_config["STOMP_HIERARCHY"]
        stomp_conn.send(
            destination=hierarchy + topic, body=json.dumps(message)
        )
    except Exception:
        _log.exception("Error sending stomp message")
예제 #3
0
    def subscribe(self):
        self.conns = []

        broker_addresses = []
        for b in self.brokers:
            try:
                addrinfos = socket.getaddrinfo(b, 0, socket.AF_INET, 0,
                                               socket.IPPROTO_TCP)
                for addrinfo in addrinfos:
                    b_addr = addrinfo[4][0]
                    broker_addresses.append(b_addr)
            except socket.gaierror as error:
                self.logger.error('Cannot resolve hostname %s: %s' %
                                  (b, str(error)))

        self.logger.info("Resolved broker addresses: %s" % broker_addresses)

        for broker in broker_addresses:
            conn = stomp.Connection12(host_and_ports=[(broker, self.port)],
                                      vhost=self.vhost,
                                      keepalive=True)
            conn.set_listener(
                'message-receiver',
                self.get_listener(
                    conn.transport._Transport__host_and_ports[0]))
            conn.connect(self.username, self.password, wait=True)
            conn.subscribe(destination=self.destination,
                           id='atlas-idds-messaging',
                           ack='auto')
            self.conns.append(conn)

        while not self.graceful_stop.is_set():
            try:
                for conn in self.conns:
                    if not conn.is_connected():
                        self.logger.info(
                            'connecting to %s' %
                            conn.transport._Transport__host_and_ports[0][0])
                        conn.set_listener(
                            'message-receiver',
                            self.get_listener(
                                conn.transport._Transport__host_and_ports[0]))
                        # conn.start()
                        conn.connect(self.username, self.password, wait=True)
                        conn.subscribe(destination=self.destination,
                                       id='atlas-idds-messaging',
                                       ack='auto')
                time.sleep(1)
            except Exception as error:
                self.logger.error(
                    "Messaging receiver throws an exception: %s, %s" %
                    (error, traceback.format_exc()))

        self.logger.info('receiver graceful stop requested')

        for conn in self.conns:
            try:
                conn.disconnect()
            except Exception:
                pass
예제 #4
0
def lambda_handler(event, context):
    """Sample pure Lambda function

    Parameters
    ----------
    event: dict, required
    context: object, required
    Returns
    ------
    API Gateway Lambda Proxy Output Format: dict
    """

    conn = stomp.Connection12(
        [(os.getenv("MSG_BROKER_HOST"), os.getenv("MSG_BROKER_PORT"))],
        auto_decode=False,
        heartbeats=(HEARTBEAT_INTERVAL_MS, HEARTBEAT_INTERVAL_MS))

    conn.set_listener('', StompClient())
    connect_and_subscribe(connection=conn,
                          credentials=json.loads(
                              get_secret(os.getenv("SECRET_NAME"))),
                          topic=os.getenv("MSG_BROKER_TOPIC"))

    for _ in range(POLL_ATTEMPTS):
        time.sleep(POLL_INTERVAL_SECS)

    conn.disconnect()

    return dict(statusCode=200,
                body=json.dumps(dict(message="polling complete, terminating")))
예제 #5
0
    def send_message(self, message, headers, cmd):
        """ Send a message to ActiveMQ
            DGEP will only send a message back, i.e. it will never initiate;
            thus, to ensure the message is sent to the correct topic, the command
            originally receieved is sent back

            :param message the message to send
            :param cmd the command originally sent to which this message is responding
            :type message json
            :type cmd str
        """

        if cmd == "moves" or cmd == "interaction" or cmd == "draftinteraction" or cmd == "commit":
            topic = "moves"
        else:
            topic = "response"

        print("Sending message:")
        print(message)

        headers["ttl"] = 30000

        conn = stomp.Connection12([(self.amq_host, 61613)],
                                  auto_content_length=False)
        conn.start()
        conn.connect('admin', 'admin', wait=True)
        conn.send(destination='/topic/DGEP/' + topic,
                  body=message,
                  headers=headers)
예제 #6
0
def _registerWithGOSS(username,
                      password,
                      simulationId,
                      gossServer='localhost',
                      stompPort='61613'):
    '''Register with the GOSS server broker and return.
    
    Function arguments:
        gossServer -- Type: string. Description: The ip location
        for the GOSS server. It must not be an empty string.
            Default: 'localhost'.
        stompPort -- Type: string. Description: The port for Stomp 
        protocol for the GOSS server. It must not be an empty string.
            Default: '61613'.
        username -- Type: string. Description: User name for GOSS connection.
        password -- Type: string. Description: Password for GOSS connection.
        
    Function returns:
        None.
    Function exceptions:
        RuntimeError()
    '''
    if (gossServer == None or gossServer == '' or type(gossServer) != str):
        raise ValueError('gossServer must be a nonempty string.\n' +
                         'gossServer = {0}'.format(gossServer))
    if (stompPort == None or stompPort == '' or type(stompPort) != str):
        raise ValueError('stompPort must be a nonempty string.\n' +
                         'stompPort = {0}'.format(stompPort))
    gossConnection = stomp.Connection12([(gossServer, stompPort)])
    gossConnection.start()
    gossConnection.connect(username, password)
    gossConnection.set_listener('GOSSStatusListener', GOSSStatusListener())
    gossConnection.subscribe(goss_simulation_status_topic + simulationId, 1)
    def _connect(self):
        try:
            if self._stomp_connection:
                self._stomp_connection.remove_listener('push')
                self._stomp_connection.transport.cleanup()
        except:
            pass

        self._stomp_connection = stomp.Connection12(
            host_and_ports=[
                (self.host, self.port),
            ],
            use_ssl=self.use_ssl,
            keepalive=KEEPALIVE,
            timeout=self._connection_timeout,
            heartbeats=self._heartbeats)
        self._stomp_connection.set_listener('push', self)
        self._stomp_connection.start()
        try:
            self._stomp_connection.connect(self._tiger_id,
                                           self._sign,
                                           wait=True,
                                           headers=self._generate_headers())
        except ConnectFailedException as e:
            raise e
예제 #8
0
    def __init__(self,
                 my_endpoint_id,
                 host="127.0.0.1",
                 port=61613,
                 username="******",
                 password="******",
                 virtual_host="/",
                 outgoing_heartbeats=0,
                 incoming_heartbeats=0,
                 debug=False):
        """Initialize the STOMP USP Binding for a USP Endpoint
            - 61613 is the default STOMP port for RabbitMQ installations"""
        generic_usp_binding.GenericUspBinding.__init__(self)
        self._host = host
        self._port = port
        self._debug = debug
        self._my_dest = None
        self._username = username
        self._password = password
        self._my_endpoint_id = my_endpoint_id
        self._listener = MyStompConnListener(self, debug)
        self._logger = logging.getLogger(self.__class__.__name__)

        # If we don't use auto_decode=False, then we get decode problems
        self._conn = stomp.Connection12([(host, port)],
                                        heartbeats=(outgoing_heartbeats,
                                                    incoming_heartbeats),
                                        vhost=virtual_host,
                                        auto_decode=False)
        self._conn.set_listener("defaultListener", self._listener)
        self._conn.start()
        self._conn.connect(username,
                           password,
                           wait=True,
                           headers={"endpoint-id": self._my_endpoint_id})
예제 #9
0
    def connect_to_messaging_brokers(self):
        broker_addresses = []
        for b in self.brokers:
            try:
                addrinfos = socket.getaddrinfo(b, 0, socket.AF_INET, 0,
                                               socket.IPPROTO_TCP)
                for addrinfo in addrinfos:
                    b_addr = addrinfo[4][0]
                    broker_addresses.append(b_addr)
            except socket.gaierror as error:
                self.logger.error('Cannot resolve hostname %s: %s' %
                                  (b, str(error)))

        self.logger.info("Resolved broker addresses: %s" % broker_addresses)

        for broker in broker_addresses:
            conn = stomp.Connection12(host_and_ports=[(broker, self.port)],
                                      vhost=self.vhost,
                                      keepalive=True,
                                      timeout=self.broker_timeout)
            conn.set_listener(
                'message-sender',
                MessagingListener(
                    conn.transport._Transport__host_and_ports[0]))
            self.conns.append(conn)
예제 #10
0
def conn():
    conn = stomp.Connection12(get_default_host())
    listener = TestListener("123", print_to_log=True)
    conn.set_listener("testlistener", listener)
    conn.connect(get_default_user(), get_default_password(), wait=True)
    yield conn
    conn.disconnect(receipt=None)
예제 #11
0
 def setUp(self):
     conn = stomp.Connection12(get_default_host(), vhost=get_default_vhost())
     listener = TestListener('123')
     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')
예제 #12
0
 def setup_device(self):
     self.conn = stomp.Connection12(host_and_ports=((activemq_address,
                                                     activemq_port), ),
                                    auto_content_length=False)
     self.conn.set_listener('', MyTestListener())
     self.conn.start()
     self.conn.connect(activemq_user, activemq_password, wait=True)
     self.conn.subscribe(destination=response_queue, id=1, ack='auto')
예제 #13
0
 def setUp(self):
     conn = stomp.Connection12(get_standard_host())
     listener = TestListener('123')
     conn.set_listener('', listener)
     conn.start()
     conn.connect('admin', 'password', wait=True)
     self.conn = conn
     self.listener = listener
     self.timestamp = time.strftime('%Y%m%d%H%M%S')
예제 #14
0
    def test_suppress_content_length(self):
        queuename = '/queue/testspecialchars12-%s' % self.timestamp
        self.conn = stomp.Connection12(get_default_host(), vhost=get_default_vhost(), auto_content_length=False)
        self.conn.transport = Mock()

        self.conn.send(body='test', destination=queuename, receipt='123')

        args, kwargs = self.conn.transport.transmit.call_args
        frame = args[0]
        self.assertTrue('content-length' not in frame.headers)
예제 #15
0
    def test_suppress_content_length(self, conn, mocker):
        listener = conn.get_listener("testlistener")
        queuename = "/queue/testspecialchars12-%s" % listener.timestamp
        conn = stomp.Connection12(get_default_host(),
                                  vhost=get_default_vhost(),
                                  auto_content_length=False)
        conn.transport = mocker.Mock()

        conn.send(body="test", destination=queuename, receipt="123")

        args, kwargs = conn.transport.transmit.call_args
        frame = args[0]
        assert "content-length" not in frame.headers
예제 #16
0
def _startTest(username,password,gossServer='localhost',stompPort='61613', simulationID=1234, rulePort=5000, topic="input"):
    simulationCfg = '{"power_system_config":{"GeographicalRegion_name":"ieee8500nodecktassets_Region","SubGeographicalRegion_name":"ieee8500nodecktassets_SubRegion","Line_name":"ieee8500"}, "simulation_config":{"start_time":"03-07-2017 00:00:00","duration":"60","simulator":"GridLAB-D","simulation_name":"my test simulation","power_flow_solver_method":"FBS"}}'
    # testCfg = "{\"testConfigPath\":\"/Users/jsimpson/git/adms/GOSS-GridAPPS-D/gov.pnnl.goss.gridappsd/applications/python/exampleTestConfig.json\",\"testScriptPath\":\"/Users/jsimpson/git/adms/GOSS-GridAPPS-D/gov.pnnl.goss.gridappsd/applications/python/exampleTestScript.json\"}";
    testCfg = '{"testConfigPath":"/Users/jsimpson/git/adms/GOSS-GridAPPS-D/gov.pnnl.goss.gridappsd/test/gov/pnnl/goss/gridappsd/exampleTestConfig.json", \
    		+	"testScriptPath":"/Users/jsimpson/git/adms/GOSS-GridAPPS-D/gov.pnnl.goss.gridappsd/test/gov/pnnl/goss/gridappsd/exampleTestScript.json", \
    		+	"simulationID": 1234, \
    		+	"expectResults":"/Users/jsimpson/git/adms/GOSS-GridAPPS-D/gov.pnnl.goss.gridappsd/test/gov/pnnl/goss/gridappsd/expected_output_series3.json", \
    		+	"simulationOutputObject":"/Users/jsimpson/git/adms/GOSS-GridAPPS-D/gov.pnnl.goss.gridappsd/test/gov/pnnl/goss/gridappsd/sim_output_object.json" \
    }'
    loc = "/home/gridappsd/gridappsd_project/sources/GOSS-GridAPPS-D/gov.pnnl.goss.gridappsd"
    # loc = "/Users/jsimpson/git/adms/GOSS-GridAPPS-D/gov.pnnl.goss.gridappsd"

    loc = os.path.realpath(__file__)
    loc =  os.path.dirname(os.path.dirname(os.path.dirname(loc)))
    print (loc)
    testCfg = {"testConfigPath":loc+"/test/gov/pnnl/goss/gridappsd/exampleTestConfig.json",
            "testScriptPath":loc+"/test/gov/pnnl/goss/gridappsd/exampleTestScript.json",
            "simulationID": 1234,
            "rulePort": 5000,
            "topic":"input",
            "expectedResult":loc+"/test/gov/pnnl/goss/gridappsd/expected_output_series3.json",
            "simulationOutputObject":loc+"/test/gov/pnnl/goss/gridappsd/sim_output_object.json"
            }
    testCfg =json.dumps(testCfg)
    simulationCfg=json.dumps(_simulationRequest)

    print (testCfg)

    if (gossServer == None or gossServer == ''
        or type(gossServer) != str):
        raise ValueError(
                         'gossServer must be a nonempty string.\n'
                         + 'gossServer = {0}'.format(gossServer))
    if (stompPort == None or stompPort == ''
        or type(stompPort) != str):
        raise ValueError(
                         'stompPort must be a nonempty string.\n'
                         + 'stompPort = {0}'.format(stompPort))
    gossConnection = stomp.Connection12([(gossServer, stompPort)])
    gossConnection.set_listener('GOSSSimulationStartListener',GOSSSimulationStartListener())

    gossConnection.start()
    gossConnection.connect(username, password, wait=True)
    # gossConnection.subscribe(destination='/queue/reply',id=2)
    gossConnection.subscribe(destination=responseQueueTopic,id=2)
    gossConnection.send(body=testCfg, destination=test_topic, headers={'reply-to': '/queue/reply'})
#    gossConnection.send(body=simulationCfg, destination=goss_sim, headers={'reply-to': '/queue/reply'})

    time.sleep(3)
    print('sent test request')
예제 #17
0
    def send_message(self, message, headers, topic):
        log("Sending message: {} to {}".format(message, topic))

        if "request-id" not in headers:
            headers["request-id"] = uuid.uuid4()

        log("RequestID: {}".format(headers["request-id"]))

        headers["ttl"] = 30000

        conn = stomp.Connection12([self.amq_host], auto_content_length=False)
        conn.connect('admin', 'admin', wait=True)
        conn.send(destination='/topic/' + topic, body=message, headers=headers)
        conn.disconnect()
예제 #18
0
    def __init__(self):
        host = os.environ.get('TEST_SERVER_HOST', 'localhost')
        port = int(os.environ.get('TEST_SERVER_PORT', '8000'))

        self._connection = stomp.Connection12([(host, port)])
        self.listener = listeners.TestListener()
        self._connection.set_listener('', self.listener)
        # NOTE:
        # * Putting time.sleep because the socket takes some time to process the
        # request to get connected. The *.start() will open the trnasport object.
        # reference: https://stackoverflow.com/questions/11585377/
        #
        # * The connection.start() is depricated in the master version.
        time.sleep(1)
        self._connection.start()
        self._connection.connect(wait=True)
예제 #19
0
def send_message(topic, message, headers=None):

    if not headers:
        headers = {}

    headers["ttl"] = 30000

    if type(message) is dict:
        message = json.dumps(message)

    daf.log("Sending message {} to {}".format(str(message), topic))

    conn = stomp.Connection12([host], auto_content_length=False)
    conn.connect('admin', 'admin', wait=True)
    conn.send(destination='/topic/' + topic, body=message, headers=headers)
    conn.disconnect()
예제 #20
0
def send_message(host='localhost', port=61613, user='', password='', ver='1.1',
                 use_ssl=False,  body='', subscription_type='topic',
                 subscription_name=''):

    # before connecting, validate that the message is valid
    try:
        json_body = json.loads(body)
    except:
        print("Invalid body provided, needs to be a JSON file")
        sys.exit(1)

    result, error_message = validate_json_message(json_body)
    if not result:
        print("Validation error: %s" % error_message)
        sys.exit(1)

    try:
        # establish the right stomp connection
        if ver == '1.0':
            conn = stomp.Connection10([(host, port)])
        elif ver == '1.1':
            conn = stomp.Connection11([(host, port)])
        elif ver == '1.2':
            conn = stomp.Connection12([(host, port)])
        elif ver == 'multicast':
            conn = MulticastConnection()

        if use_ssl:
            conn.set_ssl([(host, port)])

        conn.set_listener('', OpenCIListener(conn, user, password))
        conn.start()

        # connect and send message
        conn.connect(user, password, wait=True)
        txid = conn.begin()
        conn.send(destination='/%s/%s' % (subscription_type, subscription_name),
                  body=body, headers={'JMSType': json_body['type'],
                                      'JMSOrigin': json_body['origin'],
                                      'JMSScenario': json_body['scenario'],},
                  transaction=txid)
        conn.commit(txid)
        conn.disconnect()
    except Exception as e:
        print("Error connecting to broker: %s" % str(e))
        sys.exit(1)
    print("finish")
예제 #21
0
def _register_with_goss(
    sim_id,
    username,
    password,
    goss_server='localhost',
    stomp_port='61613',
):
    """Register with the GOSS server broker and return.
    
    Function arguments:
        sim_id -- Type: string. Description: The simulation id.
            It must not be an empty string. Default: None.
        goss_server -- Type: string. Description: The ip location
        for the GOSS server. It must not be an empty string.
            Default: 'localhost'.
        stomp_port -- Type: string. Description: The port for Stomp 
        protocol for the GOSS server. It must not be an empty string.
            Default: '61613'.
        username -- Type: string. Description: User name for GOSS connection.
        password -- Type: string. Description: Password for GOSS connection.
        
    Function returns:
        None.
    Function exceptions:
        RuntimeError()
    """
    global simulation_id
    global goss_connection
    simulation_id = sim_id
    if (goss_server == None or goss_server == '' or type(goss_server) != str):
        raise ValueError('goss_server must be a nonempty string.\n' +
                         'goss_server = {0}'.format(goss_server))
    if (stomp_port == None or stomp_port == '' or type(stomp_port) != str):
        raise ValueError('stomp_port must be a nonempty string.\n' +
                         'stomp_port = {0}'.format(stomp_port))

    goss_connection = stomp.Connection12([(goss_server, stomp_port)])
    goss_connection.start()
    goss_connection.connect(username, password, wait=True)
    goss_connection.set_listener('GOSSListener', GOSSListener())
    goss_connection.subscribe(input_from_goss_topic, 1)
    goss_connection.subscribe(input_from_goss_queue, 2)

    message_str = 'Registered with GOSS on topic ' + input_from_goss_topic + ' ' + str(
        goss_connection.is_connected())
    _send_simulation_status('STARTED', message_str, 'INFO')
예제 #22
0
    def connect(self):
        """
        Establishes a new connection to the message broker.

        :raises stomp.exception.StompException:
            Common exception class. All specific stomp.py exceptions are subclasses of
            StompException, allowing the library user to catch all current and future library
            exceptions.
        """
        try:
            self.connection = stomp.Connection12([self.host_and_port])
            self.connection.set_listener('PrintingListener', stomp.listener.PrintingListener())
            self.connection.start()
            self.connection.connect(wait=True)
        except stomp.exception.StompException as ex:
            LOGGER.error(ex)
            quit(1)
예제 #23
0
    def test_timeout(self):
        server = TestStompServer('127.0.0.1', 60000)
        try:
            server.start()

            server.add_frame('''ERROR
message: connection failed\x00''')

            conn = stomp.Connection12([('127.0.0.1', 60000)])
            listener = TestListener()
            conn.set_listener('', listener)
            try:
                conn.connect(wait=True)
                self.fail("shouldn't happen")
            except exception.ConnectFailedException:
                pass
        finally:
            server.stop()
def send_to_queue(msg=None, id=None, friend_id=None):
    try:
        queue_name = queue_dir + friend_id

        send_data = {
            'status': 'q',
            'id': friend_id,
            'message': msg,
            'from': id
        }

        conn = stomp.Connection12([(ip, port)])
        conn.start()
        conn.connect()
        conn.send(queue_name, json.dumps(send_data))
        conn.disconnect()

    except Exception as e:
        print('[ERROR] Server send to the \'%s\' queue fail:' % friend_id, e)
예제 #25
0
    def __init__(self, host="127.0.0.1", port=61613, username="******", password="******", virtual_host="/",
                 outgoing_heartbeats=0, incoming_heartbeats=0, proxy_endpoint_id="", fail_bad_content_type=False):
        """Initialize the STOMP USP Binding for a USP Endpoint
            - 61613 is the default STOMP port for RabbitMQ installations"""
        self._host = host
        self._port = port
        self._username = username
        self._password = password
        self._subscribed_to_dest = None
        self._queue = utils.GenericReceivingQueue()
        self._listener = MyStompConnListener(self._queue, fail_bad_content_type)
        self._logger = logging.getLogger(self.__class__.__name__)

        # We don't want to decode the payload, so use auto_decode=False
        self._conn = stomp.Connection12([(host, port)], heartbeats=(outgoing_heartbeats, incoming_heartbeats),
                                        vhost=virtual_host, auto_decode=False)
        self._conn.set_listener("defaultListener", self._listener)
        self._conn.start()
        self._conn.connect(username, password, wait=True, headers={"endpoint-id": proxy_endpoint_id})
def send_to_topic(msg=None, id=None, group_name=None):
    try:
        topic_name = topic_dir + group_name

        send_data = {
            'status': 't',
            'group': group_name,
            'message': msg,
            'from': id
        }

        conn = stomp.Connection12([(ip, port)])
        conn.start()
        conn.connect()
        conn.send(topic_name, json.dumps(send_data))
        conn.disconnect()

    except Exception as e:
        print('[ERROR] Server send to the \'%s\' topic fail:' % group_name, e)
def receive_from_queue(id=None, friend_id=None, channel_id=None):
    conn = None

    try:
        if id:
            queue_name = queue_dir + friend_id + '.reply.' + id
        else:
            queue_name = queue_dir + friend_id

        conn = stomp.Connection12([(ip, port)])
        conn.set_listener(listener_name, Listener())
        conn.start()
        conn.connect()
        conn.subscribe(destination=queue_name, id=channel_id)

    except Exception as e:
        print(
            '[ERROR] Server receive from the \'%s\' queue fail:' % friend_id +
            '.reply.' + id, e)

    return conn
예제 #28
0
def _registerWithGOSS(
    username,
    password,
    gossServer='localhost',
    stompPort='61613',
):
    '''Register with the GOSS server broker and return.

    Function arguments:
        gossServer -- Type: string. Description: The ip location
        for the GOSS server. It must not be an empty string.
            Default: 'localhost'.
        stompPort -- Type: string. Description: The port for Stomp
        protocol for the GOSS server. It must not be an empty string.
            Default: '61613'.
        username -- Type: string. Description: User name for GOSS connection.
        password -- Type: string. Description: Password for GOSS connection.

    Function returns:
        None.
    Function exceptions:
        RuntimeError()
    '''
    if (gossServer == None or gossServer == '' or type(gossServer) != str):
        raise ValueError('gossServer must be a nonempty string.\n' +
                         'gossServer = {0}'.format(gossServer))
    if (stompPort == None or stompPort == '' or type(stompPort) != str):
        raise ValueError('stompPort must be a nonempty string.\n' +
                         'stompPort = {0}'.format(stompPort))
    global gossConnection
    gossConnection = stomp.Connection12([(gossServer, stompPort)])
    gossConnection.start()
    gossConnection.connect(username, password, wait=True)
    gossConnection.set_listener('GOSSListener', GOSSListener(opts.t0))
    gossConnection.subscribe(read_topic, 1)
    gossConnection.subscribe(read_topic, 2)

    print('Registered with GOSS on topic ' + read_topic + ' ' +
          str(gossConnection.is_connected()))
예제 #29
0
    def init_app( self, app ):
        """Init the Flask-Stomp addon.

        :param Flask app:
        """
        if not app.config.get( "STOMPMQ_ENABLED", False ):
            return

        self.__app          = app
        self.__username     = app.config.get( "STOMPMQ_USERNAME", "" )
        self.__password     = app.config.get( "STOMPMQ_PASSWORD", "" )
        version             = app.config.get( "STOMPMQ_VERSION", "1.1" )
        broker_hosts        = app.config.get( "STOMPMQ_BROKER_HOSTS", [] )
        if len( broker_hosts ) == 0:
            broker_hosts.append( [ app.config.get( "STOMPMQ_BROKER_URL", "localhost" ),
                                   app.config.get( "STOMPMQ_BROKER_PORT", 61613 ) ] )
        global logger
        #logger = app.logger
        logger.info( 'MQ username     : %s' % ( self.__username ) )
        logger.info( 'MQ password     : %s' % ( self.__password ) )
        logger.info( 'MQ version      : %s' % ( version ) )
        logger.info( 'MQ broker_hosts : %s' % ( repr( broker_hosts ) ) )

        if version == '1.0':
            self.__broker = stomp.Connection10( broker_hosts )

        elif version == '1.1':
            self.__broker = stomp.Connection11( broker_hosts )

        elif version == '1.2':
            self.__broker = stomp.Connection12( broker_hosts )

        else:
            raise Exception( "Invalid STOMPMQ_VERSION only '1.0', '1.1' or '1.2' are allowed" )

        # self.__listener = FlaskStompListener( self.__broker, app )
        self.__broker.set_listener( 'flask_app', self.__listener )
        self._connect()
        return
예제 #30
0
def _startSimulation(username,
                     password,
                     gossServer='localhost',
                     stompPort='61613'):
    simulationCfg = '{"power_system_config":{"GeographicalRegion_name":"ieee8500nodecktassets_Region","SubGeographicalRegion_name":"ieee8500nodecktassets_SubRegion","Line_name":"ieee8500"}, "simulation_config":{"start_time":"03/07/2017 00:00:00","duration":"60","simulator":"GridLAB-D","simulation_name":"my test simulation","power_flow_solver_method":"FBS"}}'
    if (gossServer == None or gossServer == '' or type(gossServer) != str):
        raise ValueError('gossServer must be a nonempty string.\n' +
                         'gossServer = {0}'.format(gossServer))
    if (stompPort == None or stompPort == '' or type(stompPort) != str):
        raise ValueError('stompPort must be a nonempty string.\n' +
                         'stompPort = {0}'.format(stompPort))
    gossConnection = stomp.Connection12([(gossServer, stompPort)])
    gossConnection.start()
    gossConnection.connect(username, password, wait=True)
    gossConnection.set_listener('GOSSSimulationStartListener',
                                GOSSSimulationStartListener())
    gossConnection.subscribe(destination='/queue/reply', id=2)
    gossConnection.send(body=simulationCfg,
                        destination=goss_simulation_topic,
                        headers={'reply-to': '/queue/reply'})
    time.sleep(3)
    print('sent simulation request')