|
| 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 json |
| 12 | +import logging |
| 13 | +import os |
| 14 | +import signal |
| 15 | +import subprocess |
| 16 | +import sys |
| 17 | +import time |
| 18 | + |
| 19 | +from typing import Any, IO, Dict, List, Optional |
| 20 | + |
| 21 | +_JAVA_DAP_BUNDLE = '/run_dir/com.microsoft.java.debug.plugin-0.32.0.jar' |
| 22 | + |
| 23 | + |
| 24 | +def _send_lsp_message(msg: Dict[str, Any], lsp: IO[bytes]) -> None: |
| 25 | + """Sends one LSP message.""" |
| 26 | + serialized_msg = json.dumps({ |
| 27 | + 'jsonrpc': '2.0', |
| 28 | + **msg, |
| 29 | + }) |
| 30 | + payload = len(serialized_msg) |
| 31 | + lsp.write((f'Content-Length: {len(serialized_msg)}\r\n\r\n' + |
| 32 | + serialized_msg).encode('utf-8')) |
| 33 | + lsp.flush() |
| 34 | + |
| 35 | + |
| 36 | +def _receive_lsp_message(lsp: IO[bytes]) -> Optional[Dict[str, Any]]: |
| 37 | + """Receives one LSP message.""" |
| 38 | + headers = b'' |
| 39 | + while not headers.endswith(b'\r\n\r\n'): |
| 40 | + byte = lsp.read(1) |
| 41 | + if len(byte) == 0: |
| 42 | + return None |
| 43 | + headers += byte |
| 44 | + content_length = 0 |
| 45 | + for header in headers.strip().split(b'\r\n'): |
| 46 | + name, value = header.split(b':', maxsplit=2) |
| 47 | + if name.strip().lower() == b'content-length': |
| 48 | + content_length = int(value.strip()) |
| 49 | + serialized = b'' |
| 50 | + while content_length: |
| 51 | + chunk = lsp.read(content_length) |
| 52 | + if not chunk: |
| 53 | + raise Exception(f'short read: {serialized!r}') |
| 54 | + content_length -= len(chunk) |
| 55 | + serialized += chunk |
| 56 | + return json.loads(serialized) |
| 57 | + |
| 58 | + |
| 59 | +def _run() -> bool: |
| 60 | + """Attempts to start the DAP. Returns whether the caller should retry.""" |
| 61 | + with subprocess.Popen(['/usr/bin/run-language-server', '-l', 'java'], |
| 62 | + stdout=subprocess.PIPE, |
| 63 | + stdin=subprocess.PIPE, |
| 64 | + preexec_fn=os.setsid) as dap: |
| 65 | + try: |
| 66 | + _send_lsp_message( |
| 67 | + { |
| 68 | + 'id': 1, |
| 69 | + 'method': 'initialize', |
| 70 | + 'params': { |
| 71 | + 'processId': None, |
| 72 | + 'initializationOptions': { |
| 73 | + 'bundles': [ |
| 74 | + _JAVA_DAP_BUNDLE, |
| 75 | + ], |
| 76 | + }, |
| 77 | + 'trace': 'verbose', |
| 78 | + 'capabilities': {}, |
| 79 | + }, |
| 80 | + }, dap.stdin) |
| 81 | + # Wait for the initialize message has been acknowledged. |
| 82 | + # This maximizes the probability of success. |
| 83 | + while True: |
| 84 | + message = _receive_lsp_message(dap.stdout) |
| 85 | + if not message: |
| 86 | + return True |
| 87 | + if message.get('method') == 'window/logMessage': |
| 88 | + print(message.get('params', {}).get('message'), |
| 89 | + file=sys.stderr) |
| 90 | + if message.get('id') == 1: |
| 91 | + break |
| 92 | + _send_lsp_message( |
| 93 | + { |
| 94 | + 'id': 2, |
| 95 | + 'method': 'workspace/executeCommand', |
| 96 | + 'params': { |
| 97 | + 'command': 'vscode.java.startDebugSession', |
| 98 | + }, |
| 99 | + }, dap.stdin) |
| 100 | + # Wait for the reply. If the request errored out, exit early to |
| 101 | + # send a clear signal to the caller. |
| 102 | + while True: |
| 103 | + message = _receive_lsp_message(dap.stdout) |
| 104 | + if not message: |
| 105 | + return True |
| 106 | + if message.get('method') == 'window/logMessage': |
| 107 | + print(message.get('params', {}).get('message'), |
| 108 | + file=sys.stderr) |
| 109 | + if message.get('id') == 2: |
| 110 | + if 'error' in message: |
| 111 | + print(message['error'].get('message'), file=sys.stderr) |
| 112 | + # This happens often during the first launch before |
| 113 | + # things warm up. |
| 114 | + return True |
| 115 | + break |
| 116 | + # Keep reading to drain the queue. |
| 117 | + while True: |
| 118 | + message = _receive_lsp_message(dap.stdout) |
| 119 | + if not message: |
| 120 | + break |
| 121 | + if message.get('method') == 'window/logMessage': |
| 122 | + print(message.get('params', {}).get('message'), |
| 123 | + file=sys.stderr) |
| 124 | + except Exception: |
| 125 | + logging.exception('failed') |
| 126 | + finally: |
| 127 | + pgrp = os.getpgid(dap.pid) |
| 128 | + os.killpg(pgrp, signal.SIGINT) |
| 129 | + return False |
| 130 | + |
| 131 | + |
| 132 | +def _main() -> None: |
| 133 | + while True: |
| 134 | + retry = _run() |
| 135 | + if not retry: |
| 136 | + break |
| 137 | + |
| 138 | + |
| 139 | +if __name__ == '__main__': |
| 140 | + _main() |
0 commit comments