proxy.py 20.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
"""RPC proxy, allows both client/server to connect and match connection.

In normal RPC, client directly connect to server's IP address.
Sometimes this cannot be done when server do not have a static address.
RPCProxy allows both client and server connect to the proxy server,
the proxy server will forward the message between the client and server.
"""
# pylint: disable=unused-variable, unused-argument
from __future__ import absolute_import

import os
import logging
import socket
import multiprocessing
import errno
import struct
17
import time
18

19 20 21 22 23
try:
    import tornado
    from tornado import gen
    from tornado import websocket
    from tornado import ioloop
24
    from . import tornado_util
25 26
except ImportError as error_msg:
    raise ImportError("RPCProxy module requires tornado package %s" % error_msg)
27 28

from . import base
29
from .base import TrackerCode
30
from .server import _server_env
31
from .._ffi.base import py_str
32

33

34 35 36 37 38 39 40 41 42 43
class ForwardHandler(object):
    """Forward handler to forward the message."""
    def _init_handler(self):
        """Initialize handler."""
        self._init_message = bytes()
        self._init_req_nbytes = 4
        self._magic = None
        self.timeout = None
        self._rpc_key_length = None
        self._done = False
44 45 46 47 48
        self._proxy = ProxyServerHandler.current
        assert self._proxy
        self.rpc_key = None
        self.match_key = None
        self.forward_proxy = None
49
        self.alloc_time = None
50 51 52 53 54 55 56 57 58 59 60

    def __del__(self):
        logging.info("Delete %s...", self.name())

    def name(self):
        """Name of this connection."""
        return "RPCConnection"

    def _init_step(self, message):
        if self._magic is None:
            assert len(message) == 4
tqchen committed
61
            self._magic = struct.unpack('<i', message)[0]
62
            if self._magic != base.RPC_MAGIC:
63 64 65 66 67
                logging.info("Invalid RPC magic from %s", self.name())
                self.close()
            self._init_req_nbytes = 4
        elif self._rpc_key_length is None:
            assert len(message) == 4
tqchen committed
68
            self._rpc_key_length = struct.unpack('<i', message)[0]
69 70 71 72
            self._init_req_nbytes = self._rpc_key_length
        elif self.rpc_key is None:
            assert len(message) == self._rpc_key_length
            self.rpc_key = py_str(message)
73 74
            # match key is used to do the matching
            self.match_key = self.rpc_key[7:].split()[0]
75 76 77 78 79 80
            self.on_start()
        else:
            assert False

    def on_start(self):
        """Event when the initialization is completed"""
81
        self._proxy.handler_ready(self)
82 83

    def on_data(self, message):
Leyuan Wang committed
84
        """on data"""
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
        assert isinstance(message, bytes)
        if self.forward_proxy:
            self.forward_proxy.send_data(message)
        else:
            while message and self._init_req_nbytes > len(self._init_message):
                nbytes = self._init_req_nbytes - len(self._init_message)
                self._init_message += message[:nbytes]
                message = message[nbytes:]
                if self._init_req_nbytes == len(self._init_message):
                    temp = self._init_message
                    self._init_req_nbytes = 0
                    self._init_message = bytes()
                    self._init_step(temp)
            if message:
                logging.info("Invalid RPC protocol, too many bytes %s", self.name())
                self.close()

    def on_error(self, err):
        logging.info("%s: Error in RPC %s", self.name(), err)
        self.close_pair()

    def close_pair(self):
        if self.forward_proxy:
            self.forward_proxy.signal_close()
            self.forward_proxy = None
        self.close()

    def on_close_event(self):
Leyuan Wang committed
113
        """on close event"""
114 115
        assert not self._done
        logging.info("RPCProxy:on_close %s ...", self.name())
116 117 118 119 120 121
        if self.match_key:
            key = self.match_key
            if self._proxy._client_pool.get(key, None) == self:
                self._proxy._client_pool.pop(key)
            if self._proxy._server_pool.get(key, None) == self:
                self._proxy._server_pool.pop(key)
122 123
        self._done = True
        self.forward_proxy = None
124 125


126
class TCPHandler(tornado_util.TCPHandler, ForwardHandler):
127 128
    """Event driven TCP handler."""
    def __init__(self, sock, addr):
129
        super(TCPHandler, self).__init__(sock)
130 131 132 133
        self._init_handler()
        self.addr = addr

    def name(self):
134
        return "TCPSocketProxy:%s:%s"  % (str(self.addr[0]), self.rpc_key)
135 136

    def send_data(self, message, binary=True):
137
        self.write_message(message, True)
138

139 140
    def on_message(self, message):
        self.on_data(message)
141

142 143 144 145 146 147
    def on_close(self):
        if self.forward_proxy:
            self.forward_proxy.signal_close()
            self.forward_proxy = None
        logging.info("%s Close socket..", self.name())
        self.on_close_event()
148 149 150 151 152 153 154 155 156


class WebSocketHandler(websocket.WebSocketHandler, ForwardHandler):
    """Handler for websockets."""
    def __init__(self, *args, **kwargs):
        super(WebSocketHandler, self).__init__(*args, **kwargs)
        self._init_handler()

    def name(self):
157
        return "WebSocketProxy:%s" % (self.rpc_key)
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183

    def on_message(self, message):
        self.on_data(message)

    def data_received(self, _):
        raise NotImplementedError()

    def send_data(self, message):
        try:
            self.write_message(message, True)
        except websocket.WebSocketClosedError as err:
            self.on_error(err)

    def on_close(self):
        if self.forward_proxy:
            self.forward_proxy.signal_close()
            self.forward_proxy = None
        self.on_close_event()

    def signal_close(self):
        self.close()


class RequestHandler(tornado.web.RequestHandler):
    """Handles html request."""
    def __init__(self, *args, **kwargs):
184 185 186 187 188 189 190 191 192 193
        file_path = kwargs.pop("file_path")
        if file_path.endswith("html"):
            self.page = open(file_path).read()
            web_port = kwargs.pop("rpc_web_port", None)
            if web_port:
                self.page = self.page.replace(
                    "ws://localhost:9190/ws",
                    "ws://localhost:%d/ws" % web_port)
        else:
            self.page = open(file_path, "rb").read()
194 195 196 197 198 199 200 201 202 203 204 205 206 207
        super(RequestHandler, self).__init__(*args, **kwargs)

    def data_received(self, _):
        pass

    def get(self, *args, **kwargs):
        self.write(self.page)


class ProxyServerHandler(object):
    """Internal proxy server handler class."""
    current = None
    def __init__(self,
                 sock,
208
                 listen_port,
209 210 211
                 web_port,
                 timeout_client,
                 timeout_server,
212
                 tracker_addr,
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
                 index_page=None,
                 resource_files=None):
        assert ProxyServerHandler.current is None
        ProxyServerHandler.current = self
        if web_port:
            handlers = [
                (r"/ws", WebSocketHandler),
            ]
            if index_page:
                handlers.append(
                    (r"/", RequestHandler, {"file_path": index_page, "rpc_web_port": web_port}))
                logging.info("Serving RPC index html page at http://localhost:%d", web_port)
            resource_files = resource_files if resource_files else []
            for fname in resource_files:
                basename = os.path.basename(fname)
                pair = (r"/%s" % basename, RequestHandler, {"file_path": fname})
                handlers.append(pair)
                logging.info(pair)
            self.app = tornado.web.Application(handlers)
            self.app.listen(web_port)
        self.sock = sock
        self.sock.setblocking(0)
        self.loop = ioloop.IOLoop.current()
        def event_handler(_, events):
            self._on_event(events)
        self.loop.add_handler(
            self.sock.fileno(), event_handler, self.loop.READ)
        self._client_pool = {}
        self._server_pool = {}
242
        self.timeout_alloc = 5
243 244
        self.timeout_client = timeout_client
        self.timeout_server = timeout_server
245 246 247 248 249 250
        # tracker information
        self._listen_port = listen_port
        self._tracker_addr = tracker_addr
        self._tracker_conn = None
        self._tracker_pending_puts = []
        self._key_set = set()
251
        self.update_tracker_period = 2
252 253
        if tracker_addr:
            logging.info("Tracker address:%s", str(tracker_addr))
254 255 256
            def _callback():
                self._update_tracker(True)
            self.loop.call_later(self.update_tracker_period, _callback)
257 258 259 260 261 262 263 264 265 266 267 268 269 270
        logging.info("RPCProxy: Websock port bind to %d", web_port)

    def _on_event(self, _):
        while True:
            try:
                conn, addr = self.sock.accept()
                TCPHandler(conn, addr)
            except socket.error as err:
                if err.args[0] in (errno.EAGAIN, errno.EWOULDBLOCK):
                    break

    def _pair_up(self, lhs, rhs):
        lhs.forward_proxy = rhs
        rhs.forward_proxy = lhs
271

tqchen committed
272 273
        lhs.send_data(struct.pack('<i', base.RPC_CODE_SUCCESS))
        lhs.send_data(struct.pack('<i', len(rhs.rpc_key)))
274 275
        lhs.send_data(rhs.rpc_key.encode("utf-8"))

tqchen committed
276 277
        rhs.send_data(struct.pack('<i', base.RPC_CODE_SUCCESS))
        rhs.send_data(struct.pack('<i', len(lhs.rpc_key)))
278
        rhs.send_data(lhs.rpc_key.encode("utf-8"))
279 280
        logging.info("Pairup connect %s  and %s", lhs.name(), rhs.name())

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    def _regenerate_server_keys(self, keys):
        """Regenerate keys for server pool"""
        keyset = set(self._server_pool.keys())
        new_keys = []
        # re-generate the server match key, so old information is invalidated.
        for key in keys:
            rpc_key, _ = key.split(":")
            handle = self._server_pool[key]
            del self._server_pool[key]
            new_key = base.random_key(rpc_key + ":", keyset)
            self._server_pool[new_key] = handle
            keyset.add(new_key)
            new_keys.append(new_key)
        return new_keys

    def _update_tracker(self, period_update=False):
297 298 299 300 301
        """Update information on tracker."""
        try:
            if self._tracker_conn is None:
                self._tracker_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self._tracker_conn.connect(self._tracker_addr)
tqchen committed
302 303
                self._tracker_conn.sendall(struct.pack("<i", base.RPC_TRACKER_MAGIC))
                magic = struct.unpack("<i", base.recvall(self._tracker_conn, 4))[0]
304 305 306 307 308 309
                if magic != base.RPC_TRACKER_MAGIC:
                    self.loop.stop()
                    raise RuntimeError("%s is not RPC Tracker" % str(self._tracker_addr))
                # just connect to tracker, need to update all keys
                self._tracker_pending_puts = self._server_pool.keys()

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
            if self._tracker_conn and period_update:
                # periodically update tracker information
                # regenerate key if the key is not in tracker anymore
                # and there is no in-coming connection after timeout_alloc
                base.sendjson(self._tracker_conn, [TrackerCode.GET_PENDING_MATCHKEYS])
                pending_keys = set(base.recvjson(self._tracker_conn))
                update_keys = []
                for k, v in self._server_pool.items():
                    if k not in pending_keys:
                        if v.alloc_time is None:
                            v.alloc_time = time.time()
                        elif time.time() - v.alloc_time > self.timeout_alloc:
                            update_keys.append(k)
                            v.alloc_time = None
                if update_keys:
                    logging.info("RPCProxy: No incoming conn on %s, regenerate keys...",
                                 str(update_keys))
                    new_keys = self._regenerate_server_keys(update_keys)
                    self._tracker_pending_puts += new_keys

330 331 332
            need_update_info = False
            # report new connections
            for key in self._tracker_pending_puts:
333
                rpc_key = key.split(":")[0]
334 335
                base.sendjson(self._tracker_conn,
                              [TrackerCode.PUT, rpc_key,
eqy committed
336
                               (self._listen_port, key), None])
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
                assert base.recvjson(self._tracker_conn) == TrackerCode.SUCCESS
                if rpc_key not in self._key_set:
                    self._key_set.add(rpc_key)
                    need_update_info = True

            if need_update_info:
                keylist = "[" + ",".join(self._key_set) + "]"
                cinfo = {"key": "server:proxy" + keylist}
                base.sendjson(self._tracker_conn,
                              [TrackerCode.UPDATE_INFO, cinfo])
                assert base.recvjson(self._tracker_conn) == TrackerCode.SUCCESS
            self._tracker_pending_puts = []
        except (socket.error, IOError) as err:
            logging.info(
                "Lost tracker connection: %s, try reconnect in %g sec",
352
                str(err), self.update_tracker_period)
353 354
            self._tracker_conn.close()
            self._tracker_conn = None
355 356 357
            self._regenerate_server_keys(self._server_pool.keys())

        if period_update:
358
            def _callback():
359 360
                self._update_tracker(True)
            self.loop.call_later(self.update_tracker_period, _callback)
361 362 363 364 365 366 367 368 369 370 371 372 373

    def _handler_ready_tracker_mode(self, handler):
        """tracker mode to handle handler ready."""
        if handler.rpc_key.startswith("server:"):
            key = base.random_key(handler.match_key + ":", self._server_pool)
            handler.match_key = key
            self._server_pool[key] = handler
            self._tracker_pending_puts.append(key)
            self._update_tracker()
        else:
            if handler.match_key in self._server_pool:
                self._pair_up(self._server_pool.pop(handler.match_key), handler)
            else:
tqchen committed
374
                handler.send_data(struct.pack('<i', base.RPC_CODE_MISMATCH))
375 376 377 378
                handler.signal_close()

    def _handler_ready_proxy_mode(self, handler):
        """Normal proxy mode when handler is ready."""
379 380 381 382 383 384 385
        if handler.rpc_key.startswith("server:"):
            pool_src, pool_dst = self._client_pool, self._server_pool
            timeout = self.timeout_server
        else:
            pool_src, pool_dst = self._server_pool, self._client_pool
            timeout = self.timeout_client

386
        key = handler.match_key
387 388 389 390 391 392 393 394 395 396 397
        if key in pool_src:
            self._pair_up(pool_src.pop(key), handler)
            return
        elif key not in pool_dst:
            pool_dst[key] = handler
            def cleanup():
                """Cleanup client connection if timeout"""
                if pool_dst.get(key, None) == handler:
                    logging.info("Timeout client connection %s, cannot find match key=%s",
                                 handler.name(), key)
                    pool_dst.pop(key)
tqchen committed
398
                    handler.send_data(struct.pack('<i', base.RPC_CODE_MISMATCH))
399 400 401 402
                    handler.signal_close()
            self.loop.call_later(timeout, cleanup)
        else:
            logging.info("Duplicate connection with same key=%s", key)
tqchen committed
403
            handler.send_data(struct.pack('<i', base.RPC_CODE_DUPLICATE))
404 405
            handler.signal_close()

406 407 408 409 410 411 412 413
    def handler_ready(self, handler):
        """Report handler to be ready."""
        logging.info("Handler ready %s", handler.name())
        if self._tracker_addr:
            self._handler_ready_tracker_mode(handler)
        else:
            self._handler_ready_proxy_mode(handler)

414 415 416 417
    def run(self):
        """Run the proxy server"""
        ioloop.IOLoop.current().start()

418

419
def _proxy_server(listen_sock,
420
                  listen_port,
421 422 423
                  web_port,
                  timeout_client,
                  timeout_server,
424
                  tracker_addr,
425 426 427
                  index_page,
                  resource_files):
    handler = ProxyServerHandler(listen_sock,
428
                                 listen_port,
429 430 431
                                 web_port,
                                 timeout_client,
                                 timeout_server,
432
                                 tracker_addr,
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
                                 index_page,
                                 resource_files)
    handler.run()


class Proxy(object):
    """Start RPC proxy server on a seperate process.

    Python implementation based on multi-processing.

    Parameters
    ----------
    host : str
        The host url of the server.

    port : int
        The TCP port to be bind to

    port_end : int, optional
        The end TCP port to search

    web_port : int, optional
        The http/websocket port of the server.

    timeout_client : float, optional
        Timeout of client until it sees a matching connection.

    timeout_server : float, optional
        Timeout of server until it sees a matching connection.

    index_page : str, optional
        Path to an index page that can be used to display at proxy index.

    resource_files : str, optional
        Path to local resources that can be included in the http request
    """
    def __init__(self,
                 host,
                 port=9091,
                 port_end=9199,
                 web_port=0,
474
                 timeout_client=600,
475
                 timeout_server=600,
476
                 tracker_addr=None,
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
                 index_page=None,
                 resource_files=None):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.port = None
        for my_port in range(port, port_end):
            try:
                sock.bind((host, my_port))
                self.port = my_port
                break
            except socket.error as sock_err:
                if sock_err.errno in [98, 48]:
                    continue
                else:
                    raise sock_err
        if not self.port:
            raise ValueError("cannot bind to any port in [%d, %d)" % (port, port_end))
        logging.info("RPCProxy: client port bind to %s:%d", host, self.port)
        sock.listen(1)
        self.proc = multiprocessing.Process(
496 497 498 499
            target=_proxy_server,
            args=(sock, self.port, web_port,
                  timeout_client, timeout_server,
                  tracker_addr, index_page, resource_files))
500
        self.proc.start()
501
        sock.close()
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
        self.host = host

    def terminate(self):
        """Terminate the server process"""
        if self.proc:
            logging.info("Terminating Proxy Server...")
            self.proc.terminate()
            self.proc = None

    def __del__(self):
        self.terminate()


def websocket_proxy_server(url, key=""):
    """Create a RPC server that uses an websocket that connects to a proxy.

    Parameters
    ----------
    url : str
        The url to be connected.

    key : str
        The key to identify the server.
    """
    def create_on_message(conn):
        def _fsend(data):
            data = bytes(data)
            conn.write_message(data, binary=True)
            return len(data)
531 532
        on_message = base._CreateEventDrivenServer(
            _fsend, "WebSocketProxyServer", "%toinit")
533 534 535 536 537 538
        return on_message

    @gen.coroutine
    def _connect(key):
        conn = yield websocket.websocket_connect(url)
        on_message = create_on_message(conn)
539
        temp = _server_env(None, None)
540
        # Start connecton
tqchen committed
541
        conn.write_message(struct.pack('<i', base.RPC_MAGIC), binary=True)
542
        key = "server:" + key
tqchen committed
543
        conn.write_message(struct.pack('<i', len(key)), binary=True)
544 545 546
        conn.write_message(key.encode("utf-8"), binary=True)
        msg = yield conn.read_message()
        assert len(msg) >= 4
tqchen committed
547
        magic = struct.unpack('<i', msg[:4])[0]
548
        if magic == base.RPC_CODE_DUPLICATE:
549
            raise RuntimeError("key: %s has already been used in proxy" % key)
550
        elif magic == base.RPC_CODE_MISMATCH:
551
            logging.info("RPCProxy do not have matching client key %s", key)
552
        elif magic != base.RPC_CODE_SUCCESS:
553 554
            raise RuntimeError("%s is not RPC Proxy" % url)
        msg = msg[4:]
555 556 557

        logging.info("Connection established with remote")

558
        if msg:
559
            on_message(bytearray(msg), 3)
560 561 562 563 564 565

        while True:
            try:
                msg = yield conn.read_message()
                if msg is None:
                    break
566
                on_message(bytearray(msg), 3)
567 568 569 570 571 572 573
            except websocket.WebSocketClosedError as err:
                break
        logging.info("WebSocketProxyServer closed...")
        temp.remove()
        ioloop.IOLoop.current().stop()
    ioloop.IOLoop.current().spawn_callback(_connect, key)
    ioloop.IOLoop.current().start()