forked from apache/ambari
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
AMBARI-20684. Implement a websocket adapter for stomp.py (aonishuk)
- Loading branch information
Showing
23 changed files
with
3,009 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
ambari-agent/src/main/python/ambari_agent/client_example.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
''' | ||
Licensed to the Apache Software Foundation (ASF) under one | ||
or more contributor license agreements. See the NOTICE file | ||
distributed with this work for additional information | ||
regarding copyright ownership. The ASF licenses this file | ||
to you under the Apache License, Version 2.0 (the | ||
"License"); you may not use this file except in compliance | ||
with the License. You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
''' | ||
|
||
# TODO: remove this | ||
|
||
import time | ||
import ambari_stomp | ||
from ambari_stomp.adapter import websocket | ||
import base64 | ||
|
||
correlationId = 0 | ||
|
||
def get_headers(): | ||
global correlationId | ||
correlationId += 1 | ||
headers = { | ||
"content-type": "text/plain", | ||
"correlationId": correlationId | ||
} | ||
return headers | ||
|
||
class MyListener(ambari_stomp.ConnectionListener): | ||
def on_message(self, headers, message): | ||
print('MyListener:\nreceived a message "{0}"\n'.format(message)) | ||
global read_messages | ||
print headers | ||
print message | ||
read_messages.append({'id': headers['message-id'], 'subscription':headers['subscription']}) | ||
|
||
|
||
class MyStatsListener(ambari_stomp.StatsListener): | ||
def on_disconnected(self): | ||
super(MyStatsListener, self).on_disconnected() | ||
print('MyStatsListener:\n{0}\n'.format(self)) | ||
|
||
read_messages = [] | ||
|
||
conn = websocket.WsConnection('ws://gc6401:8080/api/stomp/v1') | ||
conn.transport.ws.extra_headers = [("Authorization", "Basic " + base64.b64encode('admin:admin'))] | ||
conn.set_listener('my_listener', MyListener()) | ||
conn.set_listener('stats_listener', MyStatsListener()) | ||
conn.start() | ||
|
||
conn.connect(wait=True, headers=get_headers()) | ||
|
||
conn.subscribe(destination='/user/', id='sub-0', ack='client-individual') | ||
|
||
#conn.send(body="", destination='/test/time', headers=get_headers()) | ||
conn.send(body="some message", destination='/test/echo', headers=get_headers()) | ||
time.sleep(1) | ||
for message in read_messages: | ||
conn.ack(message['id'], message['subscription']) | ||
|
||
conn.disconnect() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
106 changes: 106 additions & 0 deletions
106
ambari-common/src/main/python/ambari_stomp/adapter/websocket.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
''' | ||
Licensed to the Apache Software Foundation (ASF) under one | ||
or more contributor license agreements. See the NOTICE file | ||
distributed with this work for additional information | ||
regarding copyright ownership. The ASF licenses this file | ||
to you under the Apache License, Version 2.0 (the | ||
"License"); you may not use this file except in compliance | ||
with the License. You may obtain a copy of the License at | ||
http://www.apache.org/licenses/LICENSE-2.0 | ||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
''' | ||
|
||
import copy | ||
import logging | ||
|
||
from Queue import Queue | ||
|
||
from ambari_stomp.connect import BaseConnection | ||
from ambari_stomp.protocol import Protocol12 | ||
from ambari_stomp.transport import Transport, DEFAULT_SSL_VERSION | ||
|
||
from ambari_ws4py.client.threadedclient import WebSocketClient | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
class QueuedWebSocketClient(WebSocketClient): | ||
def __init__(self, *args, **kwargs): | ||
WebSocketClient.__init__(self, *args, **kwargs) | ||
self.messages = Queue() | ||
|
||
def received_message(self, message): | ||
""" | ||
Override the base class to store the incoming message | ||
in the `messages` queue. | ||
""" | ||
self.messages.put(copy.deepcopy(message)) | ||
|
||
def receive(self): | ||
""" | ||
Returns messages that were stored into the | ||
`messages` queue and returns `None` when the | ||
websocket is terminated or closed. | ||
""" | ||
# If the websocket was terminated and there are no messages | ||
# left in the queue, return None immediately otherwise the client | ||
# will block forever | ||
if self.terminated and self.messages.empty(): | ||
return None | ||
message = self.messages.get() | ||
if message is StopIteration: | ||
return None | ||
return message | ||
|
||
def closed(self, code, reason=None): | ||
self.messages.put(StopIteration) | ||
|
||
class WsTransport(Transport): | ||
def __init__(self, url): | ||
Transport.__init__(self, (0, 0), False, False, 0.0, 0.0, 0.0, 0.0, 0, False, None, None, None, None, False, | ||
DEFAULT_SSL_VERSION, None, None, None) | ||
self.current_host_and_port = (0, 0) # mocking | ||
self.ws = QueuedWebSocketClient(url, protocols=['http-only', 'chat']) | ||
self.ws.daemon = False | ||
|
||
def is_connected(self): | ||
return self.connected | ||
|
||
def attempt_connection(self): | ||
self.ws.connect() | ||
|
||
def send(self, encoded_frame): | ||
logger.debug("Outgoing STOMP message:\n>>> " + encoded_frame) | ||
self.ws.send(encoded_frame) | ||
|
||
def receive(self): | ||
try: | ||
msg = str(self.ws.receive()) | ||
logger.debug("Incoming STOMP message:\n<<< " + msg) | ||
return msg | ||
except: | ||
# exceptions from this method are hidden by the framework so implementing logging by ourselves | ||
logger.exception("Exception while handling incoming STOMP message:") | ||
return None | ||
|
||
def stop(self): | ||
self.running = False | ||
self.ws.close_connection() | ||
self.disconnect_socket() | ||
Transport.stop(self) | ||
|
||
class WsConnection(BaseConnection, Protocol12): | ||
def __init__(self, url, wait_on_receipt=False): | ||
self.transport = WsTransport(url) | ||
self.transport.set_listener('ws-listener', self) | ||
self.transactions = {} | ||
Protocol12.__init__(self, self.transport, (0, 0)) | ||
|
||
def disconnect(self, receipt=None, headers=None, **keyword_headers): | ||
Protocol12.disconnect(self, receipt, headers, **keyword_headers) | ||
self.transport.stop() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
# -*- coding: utf-8 -*- | ||
# | ||
# Redistribution and use in source and binary forms, with or without | ||
# modification, are permitted provided that the following conditions are | ||
# met: | ||
# | ||
# * Redistributions of source code must retain the above copyright | ||
# notice, this list of conditions and the following disclaimer. | ||
# * Redistributions in binary form must reproduce the above | ||
# copyright notice, this list of conditions and the following disclaimer | ||
# in the documentation and/or other materials provided with the | ||
# distribution. | ||
# * Neither the name of ambari_ws4py nor the names of its | ||
# contributors may be used to endorse or promote products derived from | ||
# this software without specific prior written permission. | ||
# | ||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | ||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | ||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | ||
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | ||
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | ||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | ||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | ||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | ||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | ||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
# | ||
import logging | ||
import logging.handlers as handlers | ||
|
||
__author__ = "Sylvain Hellegouarch" | ||
__version__ = "0.4.2" | ||
__all__ = ['WS_KEY', 'WS_VERSION', 'configure_logger', 'format_addresses'] | ||
|
||
WS_KEY = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" | ||
WS_VERSION = (8, 13) | ||
|
||
def configure_logger(stdout=True, filepath=None, level=logging.INFO): | ||
logger = logging.getLogger('ambari_ws4py') | ||
logger.setLevel(level) | ||
logfmt = logging.Formatter("[%(asctime)s] %(levelname)s %(message)s") | ||
|
||
if filepath: | ||
h = handlers.RotatingFileHandler(filepath, maxBytes=10485760, backupCount=3) | ||
h.setLevel(level) | ||
h.setFormatter(logfmt) | ||
logger.addHandler(h) | ||
|
||
if stdout: | ||
import sys | ||
h = logging.StreamHandler(sys.stdout) | ||
h.setLevel(level) | ||
h.setFormatter(logfmt) | ||
logger.addHandler(h) | ||
|
||
return logger | ||
|
||
def format_addresses(ws): | ||
me = ws.local_address | ||
peer = ws.peer_address | ||
if isinstance(me, tuple) and isinstance(peer, tuple): | ||
me_ip, me_port = ws.local_address | ||
peer_ip, peer_port = ws.peer_address | ||
return "[Local => %s:%d | Remote => %s:%d]" % (me_ip, me_port, peer_ip, peer_port) | ||
|
||
return "[Bound to '%s']" % me |
Oops, something went wrong.