You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ambari.apache.org by ao...@apache.org on 2018/03/23 10:09:29 UTC
[ambari] branch trunk updated: AMBARI-23337. Remove python3 files
from ws4py since they can cause build failure (aonishuk)
This is an automated email from the ASF dual-hosted git repository.
aonishuk pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/ambari.git
The following commit(s) were added to refs/heads/trunk by this push:
new 79f0cc3 AMBARI-23337. Remove python3 files from ws4py since they can cause build failure (aonishuk)
79f0cc3 is described below
commit 79f0cc36923fa214cf6017d3b0d261f6d4ee2b2d
Author: Andrew Onishuk <ao...@hortonworks.com>
AuthorDate: Fri Mar 23 12:03:47 2018 +0200
AMBARI-23337. Remove python3 files from ws4py since they can cause build failure (aonishuk)
---
.../main/python/ambari_ws4py/async_websocket.py | 126 ------------
.../main/python/ambari_ws4py/server/tulipserver.py | 224 ---------------------
2 files changed, 350 deletions(-)
diff --git a/ambari-common/src/main/python/ambari_ws4py/async_websocket.py b/ambari-common/src/main/python/ambari_ws4py/async_websocket.py
deleted file mode 100644
index 37ad572..0000000
--- a/ambari-common/src/main/python/ambari_ws4py/async_websocket.py
+++ /dev/null
@@ -1,126 +0,0 @@
-# -*- coding: utf-8 -*-
-__doc__ = """
-WebSocket implementation that relies on two new Python
-features:
-
-* asyncio to provide the high-level interface above transports
-* yield from to delegate to the reading stream whenever more
- bytes are required
-
-You can use these implementations in that context
-and benefit from those features whilst using ws4py.
-
-Strictly speaking this module probably doesn't have to
-be called async_websocket but it feels this will be its typical
-usage and is probably more readable than
-delegated_generator_websocket_on_top_of_asyncio.py
-"""
-import asyncio
-import types
-
-from ambari_ws4py.websocket import WebSocket as _WebSocket
-from ambari_ws4py.messaging import Message
-
-__all__ = ['WebSocket', 'EchoWebSocket']
-
-class WebSocket(_WebSocket):
- def __init__(self, proto):
- """
- A :pep:`3156` ready websocket handler that works
- well in a coroutine-aware loop such as the one provided
- by the asyncio module.
-
- The provided `proto` instance is a
- :class:`asyncio.Protocol` subclass instance that will
- be used internally to read and write from the
- underlying transport.
-
- Because the base :class:`ws4py.websocket.WebSocket`
- class is still coupled a bit to the socket interface,
- we have to override a little more than necessary
- to play nice with the :pep:`3156` interface. Hopefully,
- some day this will be cleaned out.
- """
- _WebSocket.__init__(self, None)
- self.started = False
- self.proto = proto
-
- @property
- def local_address(self):
- """
- Local endpoint address as a tuple
- """
- if not self._local_address:
- self._local_address = self.proto.reader.transport.get_extra_info('sockname')
- if len(self._local_address) == 4:
- self._local_address = self._local_address[:2]
- return self._local_address
-
- @property
- def peer_address(self):
- """
- Peer endpoint address as a tuple
- """
- if not self._peer_address:
- self._peer_address = self.proto.reader.transport.get_extra_info('peername')
- if len(self._peer_address) == 4:
- self._peer_address = self._peer_address[:2]
- return self._peer_address
-
- def once(self):
- """
- The base class directly is used in conjunction with
- the :class:`ws4py.manager.WebSocketManager` which is
- not actually used with the asyncio implementation
- of ws4py. So let's make it clear it shan't be used.
- """
- raise NotImplemented()
-
- def close_connection(self):
- """
- Close the underlying transport
- """
- @asyncio.coroutine
- def closeit():
- yield from self.proto.writer.drain()
- self.proto.writer.close()
- asyncio.async(closeit())
-
- def _write(self, data):
- """
- Write to the underlying transport
- """
- @asyncio.coroutine
- def sendit(data):
- self.proto.writer.write(data)
- yield from self.proto.writer.drain()
- asyncio.async(sendit(data))
-
- @asyncio.coroutine
- def run(self):
- """
- Coroutine that runs until the websocket
- exchange is terminated. It also calls the
- `opened()` method to indicate the exchange
- has started.
- """
- self.started = True
- try:
- self.opened()
- reader = self.proto.reader
- while True:
- data = yield from reader.read(self.reading_buffer_size)
- if not self.process(data):
- return False
- finally:
- self.terminate()
-
- return True
-
-class EchoWebSocket(WebSocket):
- def received_message(self, message):
- """
- Automatically sends back the provided ``message`` to
- its originating endpoint.
- """
- self.send(message.data, message.is_binary)
diff --git a/ambari-common/src/main/python/ambari_ws4py/server/tulipserver.py b/ambari-common/src/main/python/ambari_ws4py/server/tulipserver.py
deleted file mode 100644
index 6a5e1be..0000000
--- a/ambari-common/src/main/python/ambari_ws4py/server/tulipserver.py
+++ /dev/null
@@ -1,224 +0,0 @@
-# -*- coding: utf-8 -*-
-import base64
-from hashlib import sha1
-from email.parser import BytesHeaderParser
-import io
-
-import asyncio
-
-from ambari_ws4py import WS_KEY, WS_VERSION
-from ambari_ws4py.exc import HandshakeError
-from ambari_ws4py.websocket import WebSocket
-
-LF = b'\n'
-CRLF = b'\r\n'
-SPACE = b' '
-EMPTY = b''
-
-__all__ = ['WebSocketProtocol']
-
-class WebSocketProtocol(asyncio.StreamReaderProtocol):
- def __init__(self, handler_cls):
- asyncio.StreamReaderProtocol.__init__(self, asyncio.StreamReader(),
- self._pseudo_connected)
- self.ws = handler_cls(self)
-
- def _pseudo_connected(self, reader, writer):
- pass
-
- def connection_made(self, transport):
- """
- A peer is now connected and we receive an instance
- of the underlying :class:`asyncio.Transport`.
-
- We :class:`asyncio.StreamReader` is created
- and the transport is associated before the
- initial HTTP handshake is undertaken.
- """
- #self.transport = transport
- #self.stream = asyncio.StreamReader()
- #self.stream.set_transport(transport)
- asyncio.StreamReaderProtocol.connection_made(self, transport)
- # Let make it concurrent for others to tag along
- f = asyncio.async(self.handle_initial_handshake())
- f.add_done_callback(self.terminated)
-
- @property
- def writer(self):
- return self._stream_writer
-
- @property
- def reader(self):
- return self._stream_reader
-
- def terminated(self, f):
- if f.done() and not f.cancelled():
- ex = f.exception()
- if ex:
- response = [b'HTTP/1.0 400 Bad Request']
- response.append(b'Content-Length: 0')
- response.append(b'Connection: close')
- response.append(b'')
- response.append(b'')
- self.writer.write(CRLF.join(response))
- self.ws.close_connection()
-
- def close(self):
- """
- Initiate the websocket closing handshake
- which will eventuall lead to the underlying
- transport.
- """
- self.ws.close()
-
- def timeout(self):
- self.ws.close_connection()
- if self.ws.started:
- self.ws.closed(1002, "Peer connection timed-out")
-
- def connection_lost(self, exc):
- """
- The peer connection is now, the closing
- handshake won't work so let's not even try.
- However let's make the websocket handler
- be aware of it by calling its `closed`
- method.
- """
- if exc is not None:
- self.ws.close_connection()
- if self.ws.started:
- self.ws.closed(1002, "Peer connection was lost")
-
- @asyncio.coroutine
- def handle_initial_handshake(self):
- """
- Performs the HTTP handshake described in :rfc:`6455`. Note that
- this implementation is really basic and it is strongly advised
- against using it in production. It would probably break for
- most clients. If you want a better support for HTTP, please
- use a more reliable HTTP server implemented using asyncio.
- """
- request_line = yield from self.next_line()
- method, uri, req_protocol = request_line.strip().split(SPACE, 2)
-
- # GET required
- if method.upper() != b'GET':
- raise HandshakeError('HTTP method must be a GET')
-
- headers = yield from self.read_headers()
- if req_protocol == b'HTTP/1.1' and 'Host' not in headers:
- raise ValueError("Missing host header")
-
- for key, expected_value in [('Upgrade', 'websocket'),
- ('Connection', 'upgrade')]:
- actual_value = headers.get(key, '').lower()
- if not actual_value:
- raise HandshakeError('Header %s is not defined' % str(key))
- if expected_value not in actual_value:
- raise HandshakeError('Illegal value for header %s: %s' %
- (key, actual_value))
-
- response_headers = {}
-
- ws_version = WS_VERSION
- version = headers.get('Sec-WebSocket-Version')
- supported_versions = ', '.join([str(v) for v in ws_version])
- version_is_valid = False
- if version:
- try: version = int(version)
- except: pass
- else: version_is_valid = version in ws_version
-
- if not version_is_valid:
- response_headers['Sec-WebSocket-Version'] = supported_versions
- raise HandshakeError('Unhandled or missing WebSocket version')
-
- key = headers.get('Sec-WebSocket-Key')
- if key:
- ws_key = base64.b64decode(key.encode('utf-8'))
- if len(ws_key) != 16:
- raise HandshakeError("WebSocket key's length is invalid")
-
- protocols = []
- ws_protocols = []
- subprotocols = headers.get('Sec-WebSocket-Protocol')
- if subprotocols:
- for s in subprotocols.split(','):
- s = s.strip()
- if s in protocols:
- ws_protocols.append(s)
-
- exts = []
- ws_extensions = []
- extensions = headers.get('Sec-WebSocket-Extensions')
- if extensions:
- for ext in extensions.split(','):
- ext = ext.strip()
- if ext in exts:
- ws_extensions.append(ext)
-
- self.ws.protocols = ws_protocols
- self.ws.extensions = ws_extensions
- self.ws.headers = headers
-
- response = [req_protocol + b' 101 Switching Protocols']
- response.append(b'Upgrade: websocket')
- response.append(b'Content-Type: text/plain')
- response.append(b'Content-Length: 0')
- response.append(b'Connection: Upgrade')
- response.append(b'Sec-WebSocket-Version:' + bytes(str(version), 'utf-8'))
- response.append(b'Sec-WebSocket-Accept:' + base64.b64encode(sha1(key.encode('utf-8') + WS_KEY).digest()))
- if ws_protocols:
- response.append(b'Sec-WebSocket-Protocol:' + b', '.join(ws_protocols))
- if ws_extensions:
- response.append(b'Sec-WebSocket-Extensions:' + b','.join(ws_extensions))
- response.append(b'')
- response.append(b'')
- self.writer.write(CRLF.join(response))
- yield from self.handle_websocket()
-
- @asyncio.coroutine
- def handle_websocket(self):
- """
- Starts the websocket process until the
- exchange is completed and terminated.
- """
- yield from self.ws.run()
-
- @asyncio.coroutine
- def read_headers(self):
- """
- Read all HTTP headers from the HTTP request
- and returns a dictionary of them.
- """
- headers = b''
- while True:
- line = yield from self.next_line()
- headers += line
- if line == CRLF:
- break
- return BytesHeaderParser().parsebytes(headers)
-
- @asyncio.coroutine
- def next_line(self):
- """
- Reads data until \r\n is met and then return all read
- bytes.
- """
- line = yield from self.reader.readline()
- if not line.endswith(CRLF):
- raise ValueError("Missing mandatory trailing CRLF")
- return line
-
-if __name__ == '__main__':
- from ambari_ws4py.async_websocket import EchoWebSocket
-
- loop = asyncio.get_event_loop()
-
- def start_server():
- proto_factory = lambda: WebSocketProtocol(EchoWebSocket)
- return loop.create_server(proto_factory, '', 9007)
-
- s = loop.run_until_complete(start_server())
- print('serving on', s.sockets[0].getsockname())
- loop.run_forever()
--
To stop receiving notification emails like this one, please contact
aonishuk@apache.org.