|
| 1 | +import logging |
| 2 | +import socket |
| 3 | +from uuid import uuid4 |
| 4 | +from contextlib import closing |
| 5 | +from multiprocessing import Process |
| 6 | +from http.server import SimpleHTTPRequestHandler, HTTPServer |
| 7 | + |
| 8 | +import requests |
| 9 | +from notebook import notebookapp |
| 10 | + |
| 11 | +from .jupyter_server_extension import IDOM_RESOURCE_BASE_PATH, IDOM_WEB_MODULES_DIR |
| 12 | +from .widget import set_import_source_base_url |
| 13 | + |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +def setup_import_resources(): |
| 19 | + if _try_to_set_import_source_base_url(): |
| 20 | + return None |
| 21 | + |
| 22 | + host = "127.0.0.1" |
| 23 | + port = _find_available_port("127.0.0.1") |
| 24 | + |
| 25 | + logger.debug( |
| 26 | + f"Serving web modules via local static file server at http://{host}:{port}/" |
| 27 | + ) |
| 28 | + serve_dir = str(IDOM_WEB_MODULES_DIR.current) |
| 29 | + |
| 30 | + proc = Process( |
| 31 | + target=lambda: _run_simple_static_file_server(host, port, serve_dir), |
| 32 | + daemon=True, |
| 33 | + ) |
| 34 | + proc.start() |
| 35 | + |
| 36 | + |
| 37 | +def _try_to_set_import_source_base_url() -> bool: |
| 38 | + # Try to see if there's a local server we should use. This might happen when running |
| 39 | + # in a notebook from within VSCode |
| 40 | + _temp_file_name = f"__temp_{uuid4().hex}__" |
| 41 | + _temp_file = IDOM_WEB_MODULES_DIR.current / _temp_file_name |
| 42 | + _temp_file.touch() |
| 43 | + for _server_info in notebookapp.list_running_servers(): |
| 44 | + if _server_info["hostname"] not in ("localhost", "127.0.0.1"): |
| 45 | + continue |
| 46 | + |
| 47 | + _resource_url_parts = [ |
| 48 | + _server_info["url"].rstrip("/"), |
| 49 | + _server_info["base_url"].strip("/"), |
| 50 | + IDOM_RESOURCE_BASE_PATH, |
| 51 | + ] |
| 52 | + _resource_url = "/".join(filter(None, _resource_url_parts)) |
| 53 | + _temp_file_url = _resource_url + "/" + _temp_file_name |
| 54 | + |
| 55 | + response = requests.get(_temp_file_url, params={"token": _server_info["token"]}) |
| 56 | + |
| 57 | + if response.status_code == 200: |
| 58 | + set_import_source_base_url(_resource_url) |
| 59 | + logger.debug( |
| 60 | + f"Serving web modules via existing NotebookApp server at {_resource_url!r}" |
| 61 | + ) |
| 62 | + return True |
| 63 | + _temp_file.unlink() |
| 64 | + return False |
| 65 | + |
| 66 | + |
| 67 | +def _run_simple_static_file_server(host, port, directory): |
| 68 | + class CORSRequestHandler(SimpleHTTPRequestHandler): |
| 69 | + def end_headers(self): |
| 70 | + self.send_header("Access-Control-Allow-Origin", "*") |
| 71 | + SimpleHTTPRequestHandler.end_headers(self) |
| 72 | + |
| 73 | + def log_message(self, format, *args): |
| 74 | + logger.info( |
| 75 | + "%s - - [%s] %s\n" |
| 76 | + % (self.address_string(), self.log_date_time_string(), format % args) |
| 77 | + ) |
| 78 | + |
| 79 | + def make_cors_handler(*args, **kwargs): |
| 80 | + return CORSRequestHandler(*args, directory=directory, **kwargs) |
| 81 | + |
| 82 | + with HTTPServer((host, port), make_cors_handler) as httpd: |
| 83 | + httpd.serve_forever() |
| 84 | + |
| 85 | + |
| 86 | +def _find_available_port( |
| 87 | + host: str, |
| 88 | + port_min: int = 8000, |
| 89 | + port_max: int = 9000, |
| 90 | + allow_reuse_waiting_ports: bool = True, |
| 91 | +) -> int: |
| 92 | + """Get a port that's available for the given host and port range""" |
| 93 | + for port in range(port_min, port_max): |
| 94 | + with closing(socket.socket()) as sock: |
| 95 | + try: |
| 96 | + if allow_reuse_waiting_ports: |
| 97 | + # As per this answer: https://stackoverflow.com/a/19247688/3159288 |
| 98 | + # setting can be somewhat unreliable because we allow the use of |
| 99 | + # ports that are stuck in TIME_WAIT. However, not setting the option |
| 100 | + # means we're overly cautious and almost always use a different addr |
| 101 | + # even if it could have actually been used. |
| 102 | + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 103 | + sock.bind((host, port)) |
| 104 | + except OSError: |
| 105 | + pass |
| 106 | + else: |
| 107 | + return port |
| 108 | + raise RuntimeError( |
| 109 | + f"Host {host!r} has no available port in range {port_max}-{port_max}" |
| 110 | + ) |
0 commit comments