Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* 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 java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Locale;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarRuntime;

/**
* The SemSitter servers shipped inside this plugin, one per Linux architecture, for the runners that have no server
* installed: the performance-validation benchmark and SonarQube Cloud, whose analysis service runs on arm64. A server is
* used only there. Every other analysis keeps the default frontend unless an executable is configured.
*
* <p>Where a server is expected, it must be usable: a host that is not Linux amd64 or arm64, or a server that cannot be
* extracted, fails the analysis instead of silently leaving it to the default frontend.
*/
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Resolved
final class BundledServer {

static final String RESOURCE_X86_64 = "udg-java-server-x86_64-unknown-linux-musl";
static final String RESOURCE_AARCH64 = "udg-java-server-aarch64-unknown-linux-musl";
static final String PERFORMANCE_VALIDATION_CONTEXT = "sonar.java.context";
private static final AtomicReference<Path> COPY = new AtomicReference<>();

private BundledServer() {
}

static Optional<Path> extract(SonarRuntime runtime) {
if (!performanceValidation() && runtime.getEdition() != SonarEdition.SONARCLOUD) {
return Optional.empty();
}
return Optional.of(copyOnce(resourceFor(System.getProperty("os.name", ""), System.getProperty("os.arch", ""))));
}

/** The server that runs on the given host, or a failure for a host none of them runs on. */
static String resourceFor(String osName, String architecture) {
if (!osName.toLowerCase(Locale.ROOT).contains("linux")) {
throw new IllegalStateException("The bundled SemSitter server only runs on Linux, not on " + osName);
}
return switch (architecture.toLowerCase(Locale.ROOT)) {
case "amd64", "x86_64" -> RESOURCE_X86_64;
case "aarch64", "arm64" -> RESOURCE_AARCH64;
default -> throw new IllegalStateException("No SemSitter server is bundled for the architecture " + architecture);
};
}

/**
* Copies the server once per JVM, to a file of the user that no concurrent analysis on the same host writes to. A
* server that cannot be extracted fails the analysis, so that a performance validation never silently runs ECJ.
*/
private static synchronized Path copyOnce(String resource) {
Path copy = COPY.get();
if (copy != null) {
return copy;
}
try (InputStream in = BundledServer.class.getResourceAsStream(resource)) {
copy = install(in, resource, installDirectory(System.getProperty("user.home", ""), System.getProperty("java.io.tmpdir")));
COPY.set(copy);
return copy;
} catch (IOException failure) {
throw new IllegalStateException("The bundled SemSitter server could not be extracted: " + failure.getMessage(), failure);
}
}

/** The directory of the user's home for the server, or else the temporary directory when the home does not exist or cannot be written, as in a container. */
static Path installDirectory(String home, String temporaryDirectory) throws IOException {
Path homeDirectory = Path.of(home, ".sonar", "semsitter");
return isUsable(homeDirectory) ? homeDirectory : Files.createDirectories(Path.of(temporaryDirectory));
}

private static boolean isUsable(Path directory) {
try {
Files.createDirectories(directory);
return Files.isWritable(directory);
} catch (IOException | RuntimeException failure) {
return false;
}
}

/** Writes the server to a new executable file of {@code directory}, deleted when the JVM exits or right away if the copy fails. */
static Path install(@Nullable InputStream in, String resource, Path directory) throws IOException {
if (in == null) {
throw new IllegalStateException("The SemSitter server is not bundled in this plugin.");
}
Path destination = Files.createTempFile(directory, resource, "");
if (!copyTo(in, destination)) {
delete(destination);
throw new IllegalStateException("The bundled SemSitter server could not be copied to " + destination);
}
Runtime.getRuntime().addShutdownHook(new Thread(() -> delete(destination)));
return destination;
}

private static boolean copyTo(InputStream in, Path destination) {
try {
Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING);
return destination.toFile().setExecutable(true);
} catch (IOException failure) {
return false;
}
}

private static boolean delete(Path path) {
try {
return Files.deleteIfExists(path);
} catch (IOException failure) {
return false;
}
}

private static boolean performanceValidation() {
return PERFORMANCE_VALIDATION_CONTEXT.equals(System.getProperty("sensor.context.key"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,18 +21,22 @@
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.SonarRuntime;
import org.sonar.api.config.Configuration;
import org.sonar.java.model.JParser;
import org.sonar.java.model.JParserProvider;
import org.sonar.plugins.java.api.JavaVersion;

/**
* Offers the SemSitter frontend when {@link SemSitterFlag} is on, that is when SonarQube Cloud sent
* {@value SemSitterFlag#ENABLED_PROPERTY}. An analysis that asks for the SemSitter frontend gets it or fails: a flag that is
* on without a known SemSitter executable fails the analysis, and never leaves it to another frontend. So does
* {@value SemSitterFlag#ENABLED_PROPERTY}, or when the analysis runs where a {@link BundledServer} is expected: the
* performance validation and SonarQube Cloud, where the frontend is always on. An analysis that asks for the SemSitter frontend
* gets it or fails: it fails when no SemSitter executable is known, and never falls back to another frontend. So does
* {@value SemSitterFullSources#PROPERTY} when the frontend is not in use. Once chosen, the SemSitter frontend never hands files
* to another frontend.
*/
Expand All @@ -45,36 +49,50 @@ public final class SemSitterParserProvider implements JParserProvider {

private final UnaryOperator<String> environment;
private final DocumentTranslator translator;
private final Function<SonarRuntime, Optional<Path>> bundledServer;
private volatile boolean enabled;
private final AtomicReference<List<String>> fullSources = new AtomicReference<>(List.of());
private final AtomicReference<Path> executable = new AtomicReference<>();

public SemSitterParserProvider() {
this(System::getenv, SemSitterTranslator::translate);
this(System::getenv, SemSitterTranslator::translate, BundledServer::extract);
}

SemSitterParserProvider(UnaryOperator<String> environment, DocumentTranslator translator) {
SemSitterParserProvider(UnaryOperator<String> environment, DocumentTranslator translator, Function<SonarRuntime, Optional<Path>> bundledServer) {
this.environment = environment;
this.translator = translator;
this.bundledServer = bundledServer;
}

@Override
public void configure(Configuration configuration) {
start(configuration, null);
}

@Override
public void configure(Configuration configuration, SonarRuntime runtime) {
start(configuration, runtime);
}

/** A configured executable is used as is. The bundled server is the one of a runtime where it is expected, and is used even if the flag is off. */
private void start(Configuration configuration, @Nullable SonarRuntime runtime) {
enabled = false;
executable.set(null);
fullSources.set(List.of());
List<String> entries = SemSitterFullSources.entries(configuration);
if (!SemSitterFlag.isEnabled(configuration)) {
Optional<Path> configured = configuredExecutable(configuration).map(Path::of);
Optional<Path> bundled = configured.isPresent() || runtime == null ? Optional.empty() : bundledServer.apply(runtime);
if (bundled.isEmpty() && !SemSitterFlag.isEnabled(configuration)) {
rejectFullSources(entries);
return;
}
String path = configuredExecutable(configuration).orElseThrow(() -> new IllegalStateException(
Path server = configured.or(() -> bundled).orElseThrow(() -> new IllegalStateException(
"The SemSitter frontend is turned on by " + SemSitterFlag.ENABLED_PROPERTY + " but no SemSitter executable is known: set "
+ EXECUTABLE_PROPERTY + " or the environment variable " + EXECUTABLE_ENVIRONMENT));
executable.set(Path.of(path));
executable.set(server);
fullSources.set(entries);
enabled = true;
LOG.info("The Java analyzer will use the SemSitter frontend with the server {}.", path);
LOG.info("The Java analyzer will use the SemSitter frontend with the {} server {}.", bundled.isPresent() ? "bundled" : "configured", server);
}

List<String> fullSources() {
Expand Down
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
* 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.sonarsource.scanner.engine.sensor.test.fixtures.TestSonarRuntime;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.sonar.api.SonarEdition;
import org.sonar.api.SonarQubeSide;
import org.sonar.api.SonarRuntime;
import org.sonar.api.utils.Version;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

class BundledServerTest {

@TempDir
Path project;

@Test
void bundled_server_stays_unused_outside_performance_validation_and_sonarqube_cloud() {
System.clearProperty("sensor.context.key");

assertThat(BundledServer.extract(runtime(SonarEdition.COMMUNITY))).isEmpty();
assertThat(BundledServer.extract(runtime(SonarEdition.ENTERPRISE))).isEmpty();
}

@Test
void the_server_follows_the_architecture_of_the_linux_host() {
assertThat(BundledServer.resourceFor("Linux", "amd64")).isEqualTo(BundledServer.RESOURCE_X86_64);
assertThat(BundledServer.resourceFor("Linux", "x86_64")).isEqualTo(BundledServer.RESOURCE_X86_64);
assertThat(BundledServer.resourceFor("Linux", "aarch64")).isEqualTo(BundledServer.RESOURCE_AARCH64);
assertThat(BundledServer.resourceFor("Linux", "arm64")).isEqualTo(BundledServer.RESOURCE_AARCH64);
}

@Test
void a_host_without_a_bundled_server_fails() {
assertThatThrownBy(() -> BundledServer.resourceFor("Mac OS X", "aarch64")).isInstanceOf(IllegalStateException.class).hasMessageContaining("only runs on Linux");
assertThatThrownBy(() -> BundledServer.resourceFor("Linux", "riscv64")).isInstanceOf(IllegalStateException.class).hasMessageContaining("riscv64");
}

@Test
void both_linux_servers_are_bundled() throws Exception {
for (String resource : new String[] {BundledServer.RESOURCE_X86_64, BundledServer.RESOURCE_AARCH64}) {
try (InputStream in = BundledServer.class.getResourceAsStream(resource)) {
assertThat(in).isNotNull();
assertThat(in.readNBytes(4)).containsExactly(0x7f, 'E', 'L', 'F');
}
}
}

@Test
void the_installed_copy_is_executable() throws Exception {
Path copy = BundledServer.install(new ByteArrayInputStream(new byte[] {1, 2, 3}), "server", project);

assertThat(Files.isExecutable(copy)).isTrue();
assertThat(Files.readAllBytes(copy)).containsExactly(1, 2, 3);
}

@Test
void a_failed_copy_fails_and_leaves_no_file_behind() throws Exception {
InputStream broken = new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("broken");
}
};

assertThatThrownBy(() -> BundledServer.install(broken, "server", project)).isInstanceOf(IllegalStateException.class).hasMessageContaining("could not be copied");
try (var files = Files.list(project)) {
assertThat(files).isEmpty();
}
}

@Test
void the_server_goes_to_the_home_of_the_user() throws Exception {
Path directory = BundledServer.installDirectory(project.toString(), project.resolve("tmp").toString());

assertThat(directory).isEqualTo(project.resolve(".sonar").resolve("semsitter"));
}

@Test
void the_server_goes_to_the_temporary_directory_when_the_home_is_unusable() throws Exception {
Path notADirectory = Files.writeString(project.resolve("home"), "file");
Path temporary = project.resolve("tmp");

assertThat(BundledServer.installDirectory(notADirectory.toString(), temporary.toString())).isEqualTo(temporary);
}

@Test
void a_missing_bundled_server_fails() {
assertThatThrownBy(() -> BundledServer.install(null, "server", project)).hasMessage("The SemSitter server is not bundled in this plugin.");
}

@Test
void bundled_linux_server_speaks_the_protocol() throws Exception {
String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
String architecture = System.getProperty("os.arch", "");
assumeTrue(os.contains("linux") && List.of("amd64", "x86_64", "aarch64", "arm64").contains(architecture));
System.setProperty("sensor.context.key", BundledServer.PERFORMANCE_VALIDATION_CONTEXT);
try {
Optional<Path> server = BundledServer.extract(runtime(SonarEdition.COMMUNITY));
assertThat(server).isPresent();

try (SemSitterClient client = SemSitterClient.start(server.get(), project)) {
assertThat(client).isNotNull();
}
assertThat(Files.isExecutable(server.get())).isTrue();
} finally {
System.clearProperty("sensor.context.key");
}
}

private static SonarRuntime runtime(SonarEdition edition) {
return TestSonarRuntime.forSonarQube(Version.create(10, 0), SonarQubeSide.SCANNER, edition);
}
}
Loading