|
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 2 | +# not use this file except in compliance with the License. You may obtain |
| 3 | +# a copy of the License at |
| 4 | +# |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# |
| 7 | +# Unless required by applicable law or agreed to in writing, software |
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 9 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 10 | +# License for the specific language governing permissions and limitations |
| 11 | +# under the License. |
| 12 | + |
| 13 | +""" |
| 14 | +Websocket proxy adapted from similar code in Nova |
| 15 | +""" |
| 16 | + |
| 17 | +import socket |
| 18 | +import threading |
| 19 | +import traceback |
| 20 | +from urllib import parse as urlparse |
| 21 | +import websockify |
| 22 | + |
| 23 | +from oslo_log import log as logging |
| 24 | +from oslo_utils import importutils |
| 25 | +from oslo_utils import timeutils |
| 26 | + |
| 27 | +from esi_leap.common import exception |
| 28 | +from esi_leap.common import ironic |
| 29 | +import esi_leap.conf |
| 30 | +from esi_leap.objects import console_auth_token |
| 31 | + |
| 32 | + |
| 33 | +CONF = esi_leap.conf.CONF |
| 34 | +LOG = logging.getLogger(__name__) |
| 35 | + |
| 36 | + |
| 37 | +# Location of WebSockifyServer class in websockify v0.9.0 |
| 38 | +websockifyserver = importutils.try_import("websockify.websockifyserver") |
| 39 | + |
| 40 | + |
| 41 | +class ProxyRequestHandler(websockify.ProxyRequestHandler): |
| 42 | + def __init__(self, *args, **kwargs): |
| 43 | + websockify.ProxyRequestHandler.__init__(self, *args, **kwargs) |
| 44 | + |
| 45 | + def verify_origin_proto(self, connect_info, origin_proto): |
| 46 | + if "access_url_base" not in connect_info: |
| 47 | + detail = "No access_url_base in connect_info." |
| 48 | + raise Exception(detail) |
| 49 | + |
| 50 | + expected_protos = [urlparse.urlparse(connect_info.access_url_base).scheme] |
| 51 | + # NOTE: For serial consoles the expected protocol could be ws or |
| 52 | + # wss which correspond to http and https respectively in terms of |
| 53 | + # security. |
| 54 | + if "ws" in expected_protos: |
| 55 | + expected_protos.append("http") |
| 56 | + if "wss" in expected_protos: |
| 57 | + expected_protos.append("https") |
| 58 | + |
| 59 | + return origin_proto in expected_protos |
| 60 | + |
| 61 | + def _get_connect_info(self, token): |
| 62 | + """Validate the token and get the connect info.""" |
| 63 | + connect_info = console_auth_token.ConsoleAuthToken.validate(token) |
| 64 | + if CONF.serialconsoleproxy.timeout > 0: |
| 65 | + connect_info.expires = ( |
| 66 | + timeutils.utcnow_ts() + CONF.serialconsoleproxy.timeout |
| 67 | + ) |
| 68 | + |
| 69 | + # get host and port |
| 70 | + console_info = ironic.get_ironic_client().node.get_console( |
| 71 | + connect_info.node_uuid |
| 72 | + ) |
| 73 | + console_type = console_info["console_info"]["type"] |
| 74 | + if console_type != "socat": |
| 75 | + raise exception.UnsupportedConsoleType( |
| 76 | + console_type=console_type, |
| 77 | + ) |
| 78 | + url = urlparse.urlparse(console_info["console_info"]["url"]) |
| 79 | + connect_info.host = url.hostname |
| 80 | + connect_info.port = url.port |
| 81 | + |
| 82 | + return connect_info |
| 83 | + |
| 84 | + def _close_connection(self, tsock, host, port): |
| 85 | + """takes target socket and close the connection.""" |
| 86 | + try: |
| 87 | + tsock.shutdown(socket.SHUT_RDWR) |
| 88 | + except OSError: |
| 89 | + pass |
| 90 | + finally: |
| 91 | + if tsock.fileno() != -1: |
| 92 | + tsock.close() |
| 93 | + LOG.debug( |
| 94 | + "%(host)s:%(port)s: " |
| 95 | + "Websocket client or target closed" % {"host": host, "port": port} |
| 96 | + ) |
| 97 | + |
| 98 | + def new_websocket_client(self): |
| 99 | + """Called after a new WebSocket connection has been established.""" |
| 100 | + # Reopen the eventlet hub to make sure we don't share an epoll |
| 101 | + # fd with parent and/or siblings, which would be bad |
| 102 | + from eventlet import hubs |
| 103 | + |
| 104 | + hubs.use_hub() |
| 105 | + |
| 106 | + token = ( |
| 107 | + urlparse.parse_qs(urlparse.urlparse(self.path).query) |
| 108 | + .get("token", [""]) |
| 109 | + .pop() |
| 110 | + ) |
| 111 | + |
| 112 | + try: |
| 113 | + connect_info = self._get_connect_info(token) |
| 114 | + except Exception: |
| 115 | + LOG.debug(traceback.format_exc()) |
| 116 | + raise |
| 117 | + |
| 118 | + host = connect_info.host |
| 119 | + port = connect_info.port |
| 120 | + |
| 121 | + # Connect to the target |
| 122 | + LOG.debug("Connecting to: %(host)s:%(port)s" % {"host": host, "port": port}) |
| 123 | + tsock = self.socket(host, port, connect=True) |
| 124 | + |
| 125 | + # Start proxying |
| 126 | + try: |
| 127 | + if CONF.serialconsoleproxy.timeout > 0: |
| 128 | + conn_timeout = connect_info.expires - timeutils.utcnow_ts() |
| 129 | + LOG.debug("%s seconds to terminate connection." % conn_timeout) |
| 130 | + threading.Timer( |
| 131 | + conn_timeout, self._close_connection, [tsock, host, port] |
| 132 | + ).start() |
| 133 | + self.do_proxy(tsock) |
| 134 | + except Exception: |
| 135 | + LOG.debug(traceback.format_exc()) |
| 136 | + raise |
| 137 | + finally: |
| 138 | + self._close_connection(tsock, host, port) |
| 139 | + |
| 140 | + def socket(self, *args, **kwargs): |
| 141 | + return websockifyserver.WebSockifyServer.socket(*args, **kwargs) |
| 142 | + |
| 143 | + |
| 144 | +class WebSocketProxy(websockify.WebSocketProxy): |
| 145 | + def __init__(self, *args, **kwargs): |
| 146 | + super(WebSocketProxy, self).__init__(*args, **kwargs) |
| 147 | + |
| 148 | + @staticmethod |
| 149 | + def get_logger(): |
| 150 | + return LOG |
0 commit comments