Skip to content

Commit

Permalink
AMBARI-20684. Implement a websocket adapter for stomp.py (aonishuk)
Browse files Browse the repository at this point in the history
  • Loading branch information
aonishuk committed Apr 6, 2017
1 parent fb4637b commit 8de3961
Show file tree
Hide file tree
Showing 23 changed files with 3,009 additions and 5 deletions.
28 changes: 28 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,34 @@ 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.

For ws4py websocket python library.

Copyright (c) 2011-2016, Sylvain Hellegouarch
All rights reserved.

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 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.

For jQuery 1.9.1 (ambari-web/vendor/scripts.jquery-1.9.1.js):

Expand Down
5 changes: 5 additions & 0 deletions NOTICE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,9 @@ Some rights reserved.
This product includes Simplejson, library fast encoding and decoding of json. (https://github.com/simplejson/simplejson - MIT license)

Copyright (c) 2006 Bob Ippolito.
All rights reserved.

Ws4py, python library for websocket connectivity

Copyright (c) 2011-2016, Sylvain Hellegouarch
All rights reserved.
11 changes: 11 additions & 0 deletions ambari-agent/conf/unix/install-helper.sh
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,15 @@ RESOURCE_MANAGEMENT_DIR="/usr/lib/python2.6/site-packages/resource_management"
JINJA_DIR="/usr/lib/python2.6/site-packages/ambari_jinja2"
SIMPLEJSON_DIR="/usr/lib/python2.6/site-packages/ambari_simplejson"
STOMP_DIR="/usr/lib/python2.6/site-packages/ambari_stomp"
WS4PY_DIR="/usr/lib/python2.6/site-packages/ambari_ws4py"
OLD_COMMON_DIR="/usr/lib/python2.6/site-packages/common_functions"
INSTALL_HELPER_SERVER="/var/lib/ambari-server/install-helper.sh"
COMMON_DIR_AGENT="/usr/lib/ambari-agent/lib/ambari_commons"
RESOURCE_MANAGEMENT_DIR_AGENT="/usr/lib/ambari-agent/lib/resource_management"
JINJA_AGENT_DIR="/usr/lib/ambari-agent/lib/ambari_jinja2"
SIMPLEJSON_AGENT_DIR="/usr/lib/ambari-agent/lib/ambari_simplejson"
STOMP_AGENT_DIR="/usr/lib/ambari-agent/lib/ambari_stomp"
WS4PY_AGENT_DIR="/usr/lib/ambari-agent/lib/ambari_ws4py"
AMBARI_AGENT="/usr/lib/python2.6/site-packages/ambari_agent"
PYTHON_WRAPER_TARGET="/usr/bin/ambari-python-wrap"
AMBARI_AGENT_VAR="/var/lib/ambari-agent"
Expand Down Expand Up @@ -70,6 +72,11 @@ do_install(){
if [ ! -d "$STOMP_DIR" ]; then
ln -s "$STOMP_AGENT_DIR" "$STOMP_DIR"
fi

# setting ws4py shared resource
if [ ! -d "$WS4PY_DIR" ]; then
ln -s "$WS4PY_AGENT_DIR" "$WS4PY_DIR"
fi

# on nano Ubuntu, when umask=027 those folders are created without 'x' bit for 'others'.
# which causes failures when hadoop users try to access tmp_dir
Expand Down Expand Up @@ -159,6 +166,10 @@ do_remove(){
rm -f $STOMP_DIR
fi

if [ -d "$WS4PY_DIR" ]; then
rm -f $WS4PY_DIR
fi

if [ -d "$OLD_COMMON_DIR" ]; then
rm -f $OLD_COMMON_DIR
fi
Expand Down
1 change: 1 addition & 0 deletions ambari-agent/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
<jinja.install.dir>/usr/lib/ambari-agent/lib/ambari_jinja2</jinja.install.dir>
<simplejson.install.dir>/usr/lib/ambari-agent/lib/ambari_simplejson</simplejson.install.dir>
<stomp.install.dir>/usr/lib/ambari-agent/lib/ambari_stomp</stomp.install.dir>
<ws4py.install.dir>/usr/lib/ambari-agent/lib/ambari_ws4py</ws4py.install.dir>
<lib.dir>/usr/lib/ambari-agent/lib</lib.dir>
<deb.architecture>amd64</deb.architecture>
<ambari.server.module>../ambari-server</ambari.server.module>
Expand Down
69 changes: 69 additions & 0 deletions ambari-agent/src/main/python/ambari_agent/client_example.py
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()
5 changes: 5 additions & 0 deletions ambari-agent/src/packages/tarball/all.xml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@
<directory>${project.basedir}/../ambari-common/src/main/python/ambari_stomp</directory>
<outputDirectory>${stomp.install.dir}</outputDirectory>
</fileSet>
<fileSet>
<directoryMode>755</directoryMode>
<directory>${project.basedir}/../ambari-common/src/main/python/ambari_ws4py</directory>
<outputDirectory>${ws4py.install.dir}</outputDirectory>
</fileSet>
<fileSet>
<directoryMode>755</directoryMode>
<directory>src/examples</directory>
Expand Down
106 changes: 106 additions & 0 deletions ambari-common/src/main/python/ambari_stomp/adapter/websocket.py
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()
67 changes: 67 additions & 0 deletions ambari-common/src/main/python/ambari_ws4py/__init__.py
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
Loading

0 comments on commit 8de3961

Please sign in to comment.