Repository navigation
SONARJAVA-7339 Add the SemSitter client #6542
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
50add01
1bb8174
9679d02
44acda0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,228 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.semsitter; | ||
|
|
||
| import com.google.gson.JsonArray; | ||
| import com.google.gson.JsonElement; | ||
| import com.google.gson.JsonObject; | ||
| import com.google.gson.JsonParser; | ||
| import com.google.protobuf.CodedInputStream; | ||
| import java.io.BufferedWriter; | ||
| import java.io.ByteArrayOutputStream; | ||
| import java.io.IOException; | ||
| import java.io.InputStream; | ||
| import java.io.OutputStreamWriter; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.nio.file.Path; | ||
| import java.util.ArrayList; | ||
| import java.util.Collection; | ||
| import java.util.LinkedHashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.concurrent.TimeUnit; | ||
| import org.sonarsource.semsitter.wire.Document; | ||
|
|
||
| /** | ||
| * Client of one SemSitter Java analyzer server process. Control messages are JSON lines. A {@code get-file} answer | ||
| * carries a {@link Document} and a {@code get-types} answer carries a JSON object, each prefixed by the byte count | ||
| * the header names. The process starts with the client and ends with {@link #close()}. | ||
| */ | ||
| public final class SemSitterClient implements AutoCloseable { | ||
|
|
||
| static final String PROTOCOL_MAJOR = "2"; | ||
|
|
||
| private static final List<String> SERVER_FLAGS = List.of("--server", "--lang", "java", "--modifiers", "--structural", | ||
| "--decl-location", "--field-items", "--field-reference-edges", "--override-edges"); | ||
|
|
||
| private final Process process; | ||
| private final BufferedWriter toServer; | ||
| private final InputStream fromServer; | ||
| private int nextId = 1; | ||
|
|
||
| private SemSitterClient(Process process) { | ||
| this.process = process; | ||
| this.toServer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8)); | ||
| this.fromServer = process.getInputStream(); | ||
| } | ||
|
|
||
| /** | ||
| * Starts the server on the sources of {@code projectRoot} and checks that it speaks this protocol. | ||
| */ | ||
| public static SemSitterClient start(Path executable, Path projectRoot) throws IOException { | ||
| return start(command(List.of(executable.toAbsolutePath().toString()), projectRoot)); | ||
| } | ||
|
|
||
| static SemSitterClient start(List<String> command) throws IOException { | ||
| Process process = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.INHERIT).start(); | ||
| SemSitterClient client = new SemSitterClient(process); | ||
|
Check failure on line 71 in java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java
|
||
| try { | ||
| String protocol = client.send(client.command("hello")).get("protocol").getAsString(); | ||
| if (!protocol.startsWith(PROTOCOL_MAJOR + ".")) { | ||
| throw new IOException("Unsupported SemSitter protocol " + protocol); | ||
| } | ||
| } catch (IOException | RuntimeException e) { | ||
| process.destroyForcibly(); | ||
| throw e; | ||
| } | ||
| return client; | ||
| } | ||
|
|
||
| static List<String> command(List<String> launcher, Path projectRoot) { | ||
| String root = projectRoot.toAbsolutePath().toString(); | ||
| List<String> command = new ArrayList<>(launcher); | ||
| command.addAll(SERVER_FLAGS); | ||
| command.addAll(List.of("--src", root, "--project-root", root)); | ||
| return command; | ||
| } | ||
|
|
||
| public void setSettings(Map<String, List<String>> settings) throws IOException { | ||
| JsonObject request = command("set-settings"); | ||
| JsonObject values = new JsonObject(); | ||
| settings.forEach((key, list) -> { | ||
| JsonArray array = new JsonArray(); | ||
| list.forEach(array::add); | ||
| values.add(key, array); | ||
| }); | ||
| request.add("settings", values); | ||
| send(request); | ||
| } | ||
|
|
||
| /** | ||
| * Scans {@code files}, or the source roots when empty. | ||
| * @return how many files the server scanned | ||
| */ | ||
| public int fullGen(Collection<String> files) throws IOException { | ||
| JsonObject request = command("full-gen"); | ||
| if (!files.isEmpty()) { | ||
| JsonArray array = new JsonArray(); | ||
| files.forEach(array::add); | ||
| request.add("files", array); | ||
| } | ||
| return send(request).get("files").getAsInt(); | ||
| } | ||
|
|
||
| public Document getFile(String path, int ahead) throws IOException { | ||
| JsonObject request = command("get-file"); | ||
| request.addProperty("path", path); | ||
| request.addProperty("ahead", ahead); | ||
| CodedInputStream input = CodedInputStream.newInstance(exchange(request).payload); | ||
| input.setRecursionLimit(Integer.MAX_VALUE); | ||
| return Document.parseFrom(input); | ||
| } | ||
|
|
||
| /** | ||
| * @return the JSON object of declarations, as {@code types.schema.json} describes it | ||
| */ | ||
| public byte[] getTypes(Collection<String> names) throws IOException { | ||
| JsonObject request = command("get-types"); | ||
| JsonArray array = new JsonArray(); | ||
| names.forEach(array::add); | ||
| request.add("names", array); | ||
| return exchange(request).payload; | ||
| } | ||
|
|
||
| public Map<String, Boolean> hasPackage(Collection<String> names) throws IOException { | ||
| JsonObject request = command("has-package"); | ||
| JsonArray array = new JsonArray(); | ||
| names.forEach(array::add); | ||
| request.add("names", array); | ||
| Map<String, Boolean> found = new LinkedHashMap<>(); | ||
| for (Map.Entry<String, JsonElement> entry : send(request).getAsJsonObject("packages").entrySet()) { | ||
| found.put(entry.getKey(), entry.getValue().getAsBoolean()); | ||
| } | ||
| return found; | ||
| } | ||
|
|
||
| private JsonObject command(String name) { | ||
|
Check warning on line 150 in java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java
|
||
| JsonObject request = new JsonObject(); | ||
| request.addProperty("cmd", name); | ||
| return request; | ||
| } | ||
|
|
||
| private synchronized JsonObject send(JsonObject request) throws IOException { | ||
| return exchange(request).header; | ||
| } | ||
|
|
||
| private Answer exchange(JsonObject request) throws IOException { | ||
| int id = nextId; | ||
| nextId++; | ||
| request.addProperty("id", id); | ||
| try { | ||
| toServer.write(request.toString()); | ||
| toServer.write('\n'); | ||
| toServer.flush(); | ||
| String text = readLine(fromServer); | ||
| JsonObject header = JsonParser.parseString(text).getAsJsonObject(); | ||
| byte[] payload = new byte[0]; | ||
| if (header.has("payload_bytes")) { | ||
| payload = fromServer.readNBytes(header.get("payload_bytes").getAsInt()); | ||
| } | ||
|
Comment on lines
+171
to
+173
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 💡 Edge Case: A truncated payload is accepted without any error
Fail when fewer bytes arrive than the header announced:
Check the box to apply the fix or reply for a change | Was this helpful? React with 👍 / 👎 |
||
| if (header.get("id").getAsInt() != id) { | ||
| throw new IOException("SemSitter server answered request " + header.get("id") + " instead of " + id); | ||
| } | ||
| if (!header.get("ok").getAsBoolean()) { | ||
| throw new IOException("SemSitter server: " + header.get("error").getAsString()); | ||
| } | ||
| return new Answer(header, payload); | ||
| } catch (IOException e) { | ||
| String message = e.getMessage().startsWith("SemSitter") ? e.getMessage() : ("SemSitter server: " + e.getMessage()); | ||
| throw new IOException(message, e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Asks the server to quit and waits for it, forcing it to stop when it does not answer. | ||
| */ | ||
| @Override | ||
| public void close() { | ||
| try { | ||
| if (process.isAlive()) { | ||
| send(command("quit")); | ||
| toServer.close(); | ||
| if (!process.waitFor(10, TimeUnit.SECONDS)) { | ||
| process.destroyForcibly(); | ||
| } | ||
| } | ||
| } catch (IOException e) { | ||
| process.destroyForcibly(); | ||
|
Comment on lines
+187
to
+201
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } catch (InterruptedException e) { | ||
| process.destroyForcibly(); | ||
| Thread.currentThread().interrupt(); | ||
| } | ||
| } | ||
|
|
||
| private static String readLine(InputStream in) throws IOException { | ||
| ByteArrayOutputStream line = new ByteArrayOutputStream(); | ||
| for (int b = in.read(); b != '\n'; b = in.read()) { | ||
| if (b < 0) { | ||
| throw new IOException("SemSitter server closed its output"); | ||
| } | ||
| line.write(b); | ||
| } | ||
| return line.toString(StandardCharsets.UTF_8); | ||
| } | ||
|
|
||
| private static final class Answer { | ||
| private final JsonObject header; | ||
| private final byte[] payload; | ||
|
|
||
| private Answer(JsonObject header, byte[] payload) { | ||
| this.header = header; | ||
| this.payload = payload; | ||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.semsitter; | ||
|
|
||
| import com.google.gson.JsonObject; | ||
| import com.google.gson.JsonParser; | ||
| import java.io.ByteArrayOutputStream; | ||
| import java.io.FileDescriptor; | ||
| import java.io.FileInputStream; | ||
| import java.io.FileOutputStream; | ||
| import java.io.IOException; | ||
| import java.io.InputStream; | ||
| import java.io.OutputStream; | ||
| import java.io.UncheckedIOException; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.List; | ||
| import org.sonarsource.semsitter.wire.Document; | ||
| import org.sonarsource.semsitter.wire.Node; | ||
|
|
||
| /** | ||
| * Stand-in for the SemSitter server, run as a separate process by the tests. The first argument is the protocol | ||
| * version it announces. {@code --exit-after-hello} stops after the handshake and {@code --wrong-id} answers | ||
| * {@code get-file} with another id. A requested path ending with {@code Deep.java} gets a tree nested | ||
| * {@link #DEEP_TREE_DEPTH} levels deep. | ||
| */ | ||
| public final class FakeServer { | ||
|
|
||
| static final int DEEP_TREE_DEPTH = 1_000; | ||
|
|
||
| private FakeServer() { | ||
| } | ||
|
|
||
| public static void main(String[] args) { | ||
| try (InputStream in = new FileInputStream(FileDescriptor.in); OutputStream out = new FileOutputStream(FileDescriptor.out)) { | ||
| serve(List.of(args), in, out); | ||
| } catch (IOException e) { | ||
| throw new UncheckedIOException(e); | ||
| } | ||
| } | ||
|
|
||
| private static void serve(List<String> args, InputStream in, OutputStream out) throws IOException { | ||
| String line; | ||
| while ((line = readLine(in)) != null) { | ||
| JsonObject request = JsonParser.parseString(line).getAsJsonObject(); | ||
| JsonObject header = new JsonObject(); | ||
| header.addProperty("id", args.contains("--wrong-id") && "get-file".equals(request.get("cmd").getAsString()) ? 0 : request.get("id").getAsInt()); | ||
| header.addProperty("ok", true); | ||
| byte[] payload = answer(request, header, args.get(0)); | ||
| if (payload.length > 0) { | ||
| header.addProperty("payload_bytes", payload.length); | ||
| } | ||
| out.write(header.toString().getBytes(StandardCharsets.UTF_8)); | ||
| out.write('\n'); | ||
| out.write(payload); | ||
| out.flush(); | ||
| if ("quit".equals(request.get("cmd").getAsString()) || ("hello".equals(request.get("cmd").getAsString()) && args.contains("--exit-after-hello"))) { | ||
| return; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static byte[] answer(JsonObject request, JsonObject header, String protocol) { | ||
| switch (request.get("cmd").getAsString()) { | ||
| case "hello" -> header.addProperty("protocol", protocol); | ||
| case "set-settings" -> header.add("settings", request.get("settings")); | ||
| case "full-gen" -> header.addProperty("files", request.has("files") ? request.getAsJsonArray("files").size() : 0); | ||
| case "get-file" -> { | ||
| String path = request.get("path").getAsString(); | ||
| if (path.endsWith("Nope.java")) { | ||
| header.addProperty("ok", false); | ||
| header.addProperty("error", "no such file " + path); | ||
| return new byte[0]; | ||
| } | ||
| header.addProperty("format", "protobuf"); | ||
| Node.Builder tree = Node.newBuilder().setKind("program"); | ||
| if (path.endsWith("Deep.java")) { | ||
| for (int depth = 0; depth < DEEP_TREE_DEPTH; depth++) { | ||
| tree = Node.newBuilder().setKind("parenthesized_expression").addChildren(tree); | ||
| } | ||
| } | ||
| return Document.newBuilder().setPath(path).setTree(tree).build().toByteArray(); | ||
| } | ||
| case "get-types" -> { | ||
| header.addProperty("format", "json"); | ||
| return "{\"java.lang.String\":{\"kind\":\"class\"}}".getBytes(StandardCharsets.UTF_8); | ||
| } | ||
| case "has-package" -> { | ||
| JsonObject packages = new JsonObject(); | ||
| request.getAsJsonArray("names").forEach(name -> packages.addProperty(name.getAsString(), name.getAsString().startsWith("java"))); | ||
| header.add("packages", packages); | ||
| } | ||
| default -> { | ||
| // a quit request has no result beyond ok | ||
| } | ||
| } | ||
| return new byte[0]; | ||
| } | ||
|
|
||
| private static String readLine(InputStream in) throws IOException { | ||
| ByteArrayOutputStream line = new ByteArrayOutputStream(); | ||
| for (int b = in.read(); b != '\n'; b = in.read()) { | ||
| if (b < 0) { | ||
| return line.size() == 0 ? null : line.toString(StandardCharsets.UTF_8); | ||
| } | ||
| line.write(b); | ||
| } | ||
| return line.toString(StandardCharsets.UTF_8); | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sendissynchronized, which shows the client is meant to be safe across threads.getFileandgetTypescall the unsynchronizedexchangedirectly, though, so they skip that lock. If agetFileoverlaps asend(for examplehasPackageorclose) or anothergetFile, the two can race onnextId, write interleaved bytes totoServer, and each read the other's header and payload fromfromServer. The result is id-mismatch failures or a payload parsed as the wrong document. The fix is to makeexchangeitselfsynchronized, so all three paths go through one lock.Put the lock on exchange so every request/response pair is atomic:
Check the box to apply the fix or reply for a change | Was this helpful? React with 👍 / 👎