|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Small wrapper to correctly initialize the Java DAP. |
| 3 | +
|
| 4 | +This launches the (normal) Java LSP and then tells it to initialize with the |
| 5 | +Java DAP plugin bundle. This causes the DAP plugin to bind to a TCP port, and |
| 6 | +once that's done, the communication with the DAP can start. |
| 7 | +
|
| 8 | +This is known to be flaky, so this retries until it succeeds. |
| 9 | +""" |
| 10 | + |
| 11 | +import argparse |
| 12 | +import json |
| 13 | +import logging |
| 14 | +import os |
| 15 | +import signal |
| 16 | +import subprocess |
| 17 | +import sys |
| 18 | +import time |
| 19 | + |
| 20 | +from typing import Any, IO, Dict, List, Mapping, Optional |
| 21 | + |
| 22 | + |
| 23 | +def _send_lsp_message(msg: Dict[str, Any], lsp: IO[bytes]) -> None: |
| 24 | + """Sends one LSP message.""" |
| 25 | + serialized_msg = json.dumps({ |
| 26 | + 'jsonrpc': '2.0', |
| 27 | + **msg, |
| 28 | + }) |
| 29 | + payload = len(serialized_msg) |
| 30 | + lsp.write((f'Content-Length: {len(serialized_msg)}\r\n\r\n' + |
| 31 | + serialized_msg).encode('utf-8')) |
| 32 | + lsp.flush() |
| 33 | + |
| 34 | + |
| 35 | +def _receive_lsp_message(lsp: IO[bytes]) -> Optional[Dict[str, Any]]: |
| 36 | + """Receives one LSP message.""" |
| 37 | + headers = b'' |
| 38 | + while not headers.endswith(b'\r\n\r\n'): |
| 39 | + byte = lsp.read(1) |
| 40 | + if len(byte) == 0: |
| 41 | + return None |
| 42 | + headers += byte |
| 43 | + content_length = 0 |
| 44 | + for header in headers.strip().split(b'\r\n'): |
| 45 | + name, value = header.split(b':', maxsplit=2) |
| 46 | + if name.strip().lower() == b'content-length': |
| 47 | + content_length = int(value.strip()) |
| 48 | + serialized = b'' |
| 49 | + while content_length: |
| 50 | + chunk = lsp.read(content_length) |
| 51 | + if not chunk: |
| 52 | + raise Exception(f'short read: {serialized!r}') |
| 53 | + content_length -= len(chunk) |
| 54 | + serialized += chunk |
| 55 | + message: Dict[str, Any] = json.loads(serialized) |
| 56 | + return message |
| 57 | + |
| 58 | + |
| 59 | +def _run(use_ephemeral_port: bool, language_server: str, debug_plugin: str) -> bool: |
| 60 | + """Attempts to start the DAP. Returns whether the caller should retry.""" |
| 61 | + args = [language_server] |
| 62 | + if use_ephemeral_port: |
| 63 | + args.append('-Dcom.microsoft.java.debug.serverAddress=localhost:0') |
| 64 | + else: |
| 65 | + args.append('-Dcom.microsoft.java.debug.serverAddress=localhost:41010') |
| 66 | + |
| 67 | + with subprocess.Popen(args, |
| 68 | + stdout=subprocess.PIPE, |
| 69 | + stdin=subprocess.PIPE, |
| 70 | + preexec_fn=os.setsid) as dap: |
| 71 | + try: |
| 72 | + _send_lsp_message( |
| 73 | + { |
| 74 | + 'id': 1, |
| 75 | + 'method': 'initialize', |
| 76 | + 'params': { |
| 77 | + 'processId': None, |
| 78 | + 'initializationOptions': { |
| 79 | + 'bundles': [ |
| 80 | + debug_plugin, |
| 81 | + ], |
| 82 | + }, |
| 83 | + 'trace': 'verbose', |
| 84 | + 'capabilities': {}, |
| 85 | + }, |
| 86 | + }, dap.stdin) |
| 87 | + # Wait for the initialize message has been acknowledged. |
| 88 | + # This maximizes the probability of success. |
| 89 | + while True: |
| 90 | + message = _receive_lsp_message(dap.stdout) |
| 91 | + if not message: |
| 92 | + return True |
| 93 | + if message.get('method') == 'window/logMessage': |
| 94 | + print(message.get('params', {}).get('message'), |
| 95 | + file=sys.stderr) |
| 96 | + if message.get('id') == 1: |
| 97 | + break |
| 98 | + _send_lsp_message( |
| 99 | + { |
| 100 | + 'id': 2, |
| 101 | + 'method': 'workspace/executeCommand', |
| 102 | + 'params': { |
| 103 | + 'command': 'vscode.java.startDebugSession', |
| 104 | + }, |
| 105 | + }, dap.stdin) |
| 106 | + # Wait for the reply. If the request errored out, exit early to |
| 107 | + # send a clear signal to the caller. |
| 108 | + while True: |
| 109 | + message = _receive_lsp_message(dap.stdout) |
| 110 | + if not message: |
| 111 | + return True |
| 112 | + if message.get('method') == 'window/logMessage': |
| 113 | + print(message.get('params', {}).get('message'), |
| 114 | + file=sys.stderr) |
| 115 | + if message.get('id') == 2: |
| 116 | + if 'error' in message: |
| 117 | + print(message['error'].get('message'), file=sys.stderr) |
| 118 | + # This happens often during the first launch before |
| 119 | + # things warm up. |
| 120 | + return True |
| 121 | + if use_ephemeral_port: |
| 122 | + with os.fdopen(3, 'w') as port_fd: |
| 123 | + port_fd.write(str(message['result'])) |
| 124 | + break |
| 125 | + # If we reached this point, the LSP and DAP have both |
| 126 | + # successfully initialized. |
| 127 | + # Keep reading to drain the queue. |
| 128 | + while True: |
| 129 | + message = _receive_lsp_message(dap.stdout) |
| 130 | + if not message: |
| 131 | + break |
| 132 | + if message.get('method') == 'window/logMessage': |
| 133 | + print(message.get('params', {}).get('message'), |
| 134 | + file=sys.stderr) |
| 135 | + except Exception: |
| 136 | + logging.exception('failed') |
| 137 | + finally: |
| 138 | + pgrp = os.getpgid(dap.pid) |
| 139 | + os.killpg(pgrp, signal.SIGINT) |
| 140 | + return False |
| 141 | + |
| 142 | + |
| 143 | +def _main() -> None: |
| 144 | + parser = argparse.ArgumentParser(description=__doc__) |
| 145 | + # TODO: remove this flag and always use the ephemeral port. |
| 146 | + parser.add_argument( |
| 147 | + '--use-ephemeral-port', |
| 148 | + action='store_true', |
| 149 | + help='Use an ephemeral port and write the port number to fd 3') |
| 150 | + parser.add_argument( |
| 151 | + '--language-server', |
| 152 | + type=str, |
| 153 | + help='The language server to launch') |
| 154 | + parser.add_argument( |
| 155 | + '--debug-plugin', |
| 156 | + type=str, |
| 157 | + help='The path to the debug plugin') |
| 158 | + args = parser.parse_args() |
| 159 | + while True: |
| 160 | + retry = _run(args.use_ephemeral_port, args.language_server, args.debug_plugin) |
| 161 | + if not retry: |
| 162 | + break |
| 163 | + |
| 164 | + |
| 165 | +if __name__ == '__main__': |
| 166 | + _main() |
0 commit comments