diff options
author | Simon Brandhof <simon.brandhof@sonarsource.com> | 2017-10-12 10:00:14 +0200 |
---|---|---|
committer | Simon Brandhof <simon.brandhof@sonarsource.com> | 2017-10-16 09:36:55 +0200 |
commit | 252fbe63ae0edb86307e54c5c5fbfe83e47b965e (patch) | |
tree | bbf7091a5476b1a923e025429add17a8e762888c | |
parent | 36e1afc3d93ab23b01bb3911d311f157ef8c8fb0 (diff) | |
download | sonarqube-252fbe63ae0edb86307e54c5c5fbfe83e47b965e.tar.gz sonarqube-252fbe63ae0edb86307e54c5c5fbfe83e47b965e.zip |
SONAR-9863 replace old "permanent server ID" by the new one
37 files changed, 302 insertions, 832 deletions
diff --git a/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java b/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java index da99c929216..9e214a27a86 100644 --- a/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java +++ b/server/sonar-ce/src/main/java/org/sonar/ce/container/ComputeEngineContainerImpl.java @@ -145,7 +145,6 @@ import org.sonar.server.search.EsSearchModule; import org.sonar.server.setting.DatabaseSettingLoader; import org.sonar.server.setting.DatabaseSettingsEnabler; import org.sonar.server.setting.ThreadLocalSettings; -import org.sonar.server.startup.LogServerId; import org.sonar.server.test.index.TestIndexer; import org.sonar.server.user.DefaultUserFinder; import org.sonar.server.user.DeprecatedUserFinder; @@ -442,7 +441,6 @@ public class ComputeEngineContainerImpl implements ComputeEngineContainer { private static Object[] startupComponents() { return new Object[] { - LogServerId.class, ServerLifecycleNotifier.class, PurgeCeActivities.class, CeQueueCleaner.class diff --git a/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java b/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java index 8a003284a5d..3a6b1a74cf2 100644 --- a/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java +++ b/server/sonar-ce/src/test/java/org/sonar/ce/container/ComputeEngineContainerImplTest.java @@ -146,7 +146,7 @@ public class ComputeEngineContainerImplTest { ); assertThat(picoContainer.getParent().getParent().getComponentAdapters()).hasSize( CONTAINER_ITSELF - + 12 // MigrationConfigurationModule + + 13 // MigrationConfigurationModule + 17 // level 2 ); assertThat(picoContainer.getParent().getParent().getParent().getComponentAdapters()).hasSize( diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/MigrationConfigurationModule.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/MigrationConfigurationModule.java index 43de1b33971..5f7026a9b4d 100644 --- a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/MigrationConfigurationModule.java +++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/MigrationConfigurationModule.java @@ -32,6 +32,7 @@ import org.sonar.server.platform.db.migration.version.v63.DbVersion63; import org.sonar.server.platform.db.migration.version.v64.DbVersion64; import org.sonar.server.platform.db.migration.version.v65.DbVersion65; import org.sonar.server.platform.db.migration.version.v66.DbVersion66; +import org.sonar.server.platform.db.migration.version.v67.DbVersion67; public class MigrationConfigurationModule extends Module { @Override @@ -47,6 +48,7 @@ public class MigrationConfigurationModule extends Module { DbVersion64.class, DbVersion65.class, DbVersion66.class, + DbVersion67.class, // migration steps MigrationStepRegistryImpl.class, diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/step/Select.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/step/Select.java index 471e1641ce1..b2430466afd 100644 --- a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/step/Select.java +++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/step/Select.java @@ -144,17 +144,12 @@ public interface Select extends SqlStatement<Select> { RowReader<Long> LONG_READER = new LongReader(); class StringReader implements RowReader<String> { - private StringReader() { - } - @Override public String read(Row row) throws SQLException { return row.getNullableString(1); } } - RowReader<String> STRING_READER = new StringReader(); - @FunctionalInterface interface RowHandler { void handle(Row row) throws SQLException; diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v66/CopyDeprecatedServerId.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v66/CopyDeprecatedServerId.java new file mode 100644 index 00000000000..d2a0a314167 --- /dev/null +++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v66/CopyDeprecatedServerId.java @@ -0,0 +1,64 @@ +/* + * SonarQube + * Copyright (C) 2009-2017 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * 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 GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package org.sonar.server.platform.db.migration.version.v66; + +import java.sql.SQLException; +import org.sonar.db.Database; +import org.sonar.server.platform.db.migration.step.DataChange; +import org.sonar.server.platform.db.migration.step.Select; + +public class CopyDeprecatedServerId extends DataChange { + + private static final String DEPRECATED_KEY = "sonar.server_id"; + private static final String NEW_KEY = "sonar.core.id"; + + public CopyDeprecatedServerId(Database db) { + super(db); + } + + @Override + protected void execute(Context context) throws SQLException { + String deprecatedValue = context + .prepareSelect("select text_value from properties where prop_key = '" + DEPRECATED_KEY + "'") + .get(new Select.StringReader()); + if (deprecatedValue != null && !deprecatedValue.isEmpty()) { + deleteProperty(context, NEW_KEY); + context.prepareUpsert("insert into properties" + + " (prop_key, is_empty, text_value, created_at)" + + " values " + + " (?, ?, ?, ?)") + .setString(1, NEW_KEY) + .setBoolean(2, false) + .setString(3, deprecatedValue) + .setLong(4, System.currentTimeMillis()) + .execute() + .commit(); + } + deleteProperty(context, DEPRECATED_KEY); + } + + private static void deleteProperty(Context context, String key) throws SQLException { + context.prepareUpsert("delete from properties where prop_key = '" + key + "'") + .execute() + .commit(); + } + +} diff --git a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v67/DbVersion67.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v67/DbVersion67.java new file mode 100644 index 00000000000..9743728de76 --- /dev/null +++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v67/DbVersion67.java @@ -0,0 +1,33 @@ +/* + * SonarQube + * Copyright (C) 2009-2017 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * 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 GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.server.platform.db.migration.version.v67; + +import org.sonar.server.platform.db.migration.step.MigrationStepRegistry; +import org.sonar.server.platform.db.migration.version.DbVersion; +import org.sonar.server.platform.db.migration.version.v66.CopyDeprecatedServerId; + +public class DbVersion67 implements DbVersion { + @Override + public void addSteps(MigrationStepRegistry registry) { + registry + .add(1830, "Copy deprecated server ID", CopyDeprecatedServerId.class) + ; + } +} diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerId.java b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v67/package-info.java index 51a589cb210..070baa2b5c0 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerId.java +++ b/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/version/v67/package-info.java @@ -17,25 +17,8 @@ * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ -package org.sonar.server.platform; +@ParametersAreNonnullByDefault +package org.sonar.server.platform.db.migration.version.v67; -import javax.annotation.concurrent.Immutable; +import javax.annotation.ParametersAreNonnullByDefault; -@Immutable -public final class ServerId { - private final String id; - private final boolean valid; - - public ServerId(String id, boolean valid) { - this.id = id; - this.valid = valid; - } - - public String getId() { - return id; - } - - public boolean isValid() { - return valid; - } -} diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/MigrationConfigurationModuleTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/MigrationConfigurationModuleTest.java index edea77696f7..313c1dec0ea 100644 --- a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/MigrationConfigurationModuleTest.java +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/MigrationConfigurationModuleTest.java @@ -37,7 +37,7 @@ public class MigrationConfigurationModuleTest { assertThat(container.getPicoContainer().getComponentAdapters()) .hasSize(COMPONENTS_IN_EMPTY_COMPONENT_CONTAINER // DbVersion classes - + 9 + + 10 // Others + 3); } diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v67/CopyDeprecatedServerIdTest.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v67/CopyDeprecatedServerIdTest.java new file mode 100644 index 00000000000..7f43080267f --- /dev/null +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v67/CopyDeprecatedServerIdTest.java @@ -0,0 +1,91 @@ +/* + * SonarQube + * Copyright (C) 2009-2017 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * 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 GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.server.platform.db.migration.version.v67; + +import java.sql.SQLException; +import java.util.List; +import org.junit.Rule; +import org.junit.Test; +import org.sonar.db.CoreDbTester; +import org.sonar.server.platform.db.migration.version.v66.CopyDeprecatedServerId; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CopyDeprecatedServerIdTest { + + private static final String DEPRECATED_KEY = "sonar.server_id"; + private static final String TARGET_KEY = "sonar.core.id"; + + @Rule + public CoreDbTester db = CoreDbTester.createForSchema(CopyDeprecatedServerIdTest.class, "properties.sql"); + + private CopyDeprecatedServerId underTest = new CopyDeprecatedServerId(db.database()); + + @Test + public void override_server_id_with_deprecated_value_if_present() throws SQLException { + insertProperty(DEPRECATED_KEY, "foo"); + insertProperty(TARGET_KEY, "bar"); + + underTest.execute(); + + assertThatTargetKeyHasValue("foo"); + assertThatDeprecatedKeyDoesNotExist(); + } + + @Test + public void set_server_id_with_deprecated_value_if_present() throws SQLException { + // the target property does not exist + insertProperty(DEPRECATED_KEY, "foo"); + + underTest.execute(); + + assertThatTargetKeyHasValue("foo"); + assertThatDeprecatedKeyDoesNotExist(); + } + + @Test + public void keep_existing_server_id_if_deprecated_value_if_absent() throws SQLException { + insertProperty(TARGET_KEY, "foo"); + + underTest.execute(); + + assertThatTargetKeyHasValue("foo"); + assertThatDeprecatedKeyDoesNotExist(); + } + + private void assertThatTargetKeyHasValue(String expected) { + String value = (String) db.selectFirst("SELECT TEXT_VALUE FROM PROPERTIES WHERE PROP_KEY = '" + TARGET_KEY + "'") + .get("TEXT_VALUE"); + assertThat(value).isEqualTo(expected); + } + + private void assertThatDeprecatedKeyDoesNotExist() { + List rows = db.select("SELECT * FROM PROPERTIES WHERE PROP_KEY = '" + DEPRECATED_KEY + "'"); + assertThat(rows).isEmpty(); + } + + public void insertProperty(String key, String value) { + db.executeInsert( + "properties", + "prop_key", key, + "is_empty", "false", + "text_value", value); + } +} diff --git a/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v67/DbVersion67Test.java b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v67/DbVersion67Test.java new file mode 100644 index 00000000000..41ea47048be --- /dev/null +++ b/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v67/DbVersion67Test.java @@ -0,0 +1,42 @@ +/* + * SonarQube + * Copyright (C) 2009-2017 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * 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 GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package org.sonar.server.platform.db.migration.version.v67; + +import org.junit.Test; + +import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMigrationCount; +import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMinimumMigrationNumber; + +public class DbVersion67Test { + + private DbVersion67 underTest = new DbVersion67(); + + @Test + public void migrationNumber_starts_at_1830() { + verifyMinimumMigrationNumber(underTest, 1830); + } + + @Test + public void verify_migration_count() { + verifyMigrationCount(underTest, 1); + } + +} diff --git a/server/sonar-db-migration/src/test/resources/org/sonar/server/platform/db/migration/version/v67/CopyDeprecatedServerIdTest/properties.sql b/server/sonar-db-migration/src/test/resources/org/sonar/server/platform/db/migration/version/v67/CopyDeprecatedServerIdTest/properties.sql new file mode 100644 index 00000000000..dfc39d8d285 --- /dev/null +++ b/server/sonar-db-migration/src/test/resources/org/sonar/server/platform/db/migration/version/v67/CopyDeprecatedServerIdTest/properties.sql @@ -0,0 +1,11 @@ +CREATE TABLE "PROPERTIES" ( + "ID" INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1), + "PROP_KEY" VARCHAR(512) NOT NULL, + "RESOURCE_ID" INTEGER, + "USER_ID" INTEGER, + "IS_EMPTY" BOOLEAN NOT NULL, + "TEXT_VALUE" VARCHAR(4000), + "CLOB_VALUE" CLOB(2147483647), + "CREATED_AT" BIGINT +); +CREATE INDEX "PROPERTIES_KEY" ON "PROPERTIES" ("PROP_KEY"); diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerIdGenerator.java b/server/sonar-server/src/main/java/org/sonar/server/platform/ServerIdGenerator.java deleted file mode 100644 index b736bff11e1..00000000000 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerIdGenerator.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * 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 GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.platform; - -import com.google.common.annotations.VisibleForTesting; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Objects; -import java.util.regex.Pattern; -import javax.annotation.CheckForNull; -import org.apache.commons.codec.digest.DigestUtils; -import org.sonar.api.utils.log.Loggers; - -import static com.google.common.base.Preconditions.checkArgument; -import static org.apache.commons.lang.StringUtils.isBlank; -import static org.apache.commons.lang.StringUtils.isNotBlank; - -public class ServerIdGenerator { - - private static final Pattern ORGANIZATION_PATTERN = Pattern.compile("[a-zA-Z0-9]+[a-zA-Z0-9 ]*"); - - /** - * Increment this version each time the algorithm is changed. Do not exceed 9. - */ - static final String VERSION = "1"; - - static final int CHECKSUM_SIZE = 14; - - private final boolean acceptPrivateAddress; - - public ServerIdGenerator() { - this(false); - } - - @VisibleForTesting - ServerIdGenerator(boolean acceptPrivateAddress) { - this.acceptPrivateAddress = acceptPrivateAddress; - } - - public boolean validate(String organizationName, String ipAddress, String expectedServerId) { - String organization = organizationName.trim(); - String ip = ipAddress.trim(); - if (isBlank(ip) || isBlank(organization) || !isValidOrganizationName(organization)) { - return false; - } - - InetAddress inetAddress = toValidAddress(ip); - - return inetAddress != null - && Objects.equals(expectedServerId, toId(organization, inetAddress)); - } - - public String generate(String organizationName, String ipAddress) { - String organization = organizationName.trim(); - String ip = ipAddress.trim(); - checkArgument(isNotBlank(organization), "Organization name must not be null or empty"); - checkArgument(isValidOrganizationName(organization), "Organization name is invalid. Alpha numeric characters and space only are allowed. '%s' was provided.", organization); - checkArgument(isNotBlank(ip), "IP must not be null or empty"); - - InetAddress inetAddress = toValidAddress(ip); - checkArgument(inetAddress != null, "Invalid IP '%s'", ip); - - return toId(organization, inetAddress); - } - - static boolean isValidOrganizationName(String organization) { - return ORGANIZATION_PATTERN.matcher(organization).matches(); - } - - boolean isFixed(InetAddress address) { - // Loopback addresses are in the range 127/8. - // Link local addresses are in the range 169.254/16 (IPv4) or fe80::/10 (IPv6). They are "autoconfiguration" addresses. - // They can assigned pseudorandomly, so they don't guarantee to be the same between two server startups. - return acceptPrivateAddress || (!address.isLoopbackAddress() && !address.isLinkLocalAddress()); - } - - static String toId(String organization, InetAddress address) { - String id = new StringBuilder().append(organization).append("-").append(address.getHostAddress()).toString(); - return VERSION + DigestUtils.sha1Hex(id.getBytes(StandardCharsets.UTF_8)).substring(0, CHECKSUM_SIZE); - } - - @CheckForNull - private InetAddress toValidAddress(String ipAddress) { - if (isNotBlank(ipAddress)) { - List<InetAddress> validAddresses = getAvailableAddresses(); - try { - InetAddress address = InetAddress.getByName(ipAddress); - if (validAddresses.contains(address)) { - return address; - } - } catch (UnknownHostException e) { - // ignore, not valid property - } - } - return null; - } - - public List<InetAddress> getAvailableAddresses() { - List<InetAddress> result = new ArrayList<>(); - try { - Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); - while (networkInterfaces.hasMoreElements()) { - NetworkInterface networkInterface = networkInterfaces.nextElement(); - Enumeration<InetAddress> addresses = networkInterface.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress ownedAddress = addresses.nextElement(); - if (isFixed(ownedAddress)) { - result.add(ownedAddress); - } - } - } - } catch (SocketException e) { - Loggers.get(ServerIdGenerator.class).error("Fail to browse network interfaces", e); - } - return result; - } -} diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerIdLoader.java b/server/sonar-server/src/main/java/org/sonar/server/platform/ServerIdLoader.java deleted file mode 100644 index 049316a0e47..00000000000 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerIdLoader.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * 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 GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.platform; - -import java.util.Optional; -import org.sonar.api.CoreProperties; -import org.sonar.api.config.Configuration; - -public class ServerIdLoader { - - private final Configuration config; - private final ServerIdGenerator idGenerator; - - public ServerIdLoader(Configuration config, ServerIdGenerator idGenerator) { - this.config = config; - this.idGenerator = idGenerator; - } - - public Optional<String> getRaw() { - return config.get(CoreProperties.PERMANENT_SERVER_ID); - } - - public Optional<ServerId> get() { - return getRaw().map(rawId -> { - Optional<String> organization = config.get(CoreProperties.ORGANISATION); - Optional<String> ipAddress = config.get(CoreProperties.SERVER_ID_IP_ADDRESS); - boolean validated = organization.isPresent() - && ipAddress.isPresent() - && idGenerator.validate(organization.get(), ipAddress.get(), rawId); - - return new ServerId(rawId, validated); - }); - } -} diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerImpl.java b/server/sonar-server/src/main/java/org/sonar/server/platform/ServerImpl.java index 7a5c1217d55..e84711cb940 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/ServerImpl.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/ServerImpl.java @@ -58,7 +58,7 @@ public class ServerImpl extends Server { @Override public String getPermanentServerId() { - return config.get(CoreProperties.PERMANENT_SERVER_ID).orElse(null); + return getId(); } @Override diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/StartupMetadataProvider.java b/server/sonar-server/src/main/java/org/sonar/server/platform/StartupMetadataProvider.java index 1d210b465d0..f43253df1e4 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/StartupMetadataProvider.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/StartupMetadataProvider.java @@ -53,8 +53,7 @@ public class StartupMetadataProvider extends ProviderAdapter { } /** - * Generate {@link CoreProperties#SERVER_ID} if it doesn't exist yet, otherwise just load it from DB, and always - * generate a {@link CoreProperties#SERVER_STARTTIME}. + * Generate a {@link CoreProperties#SERVER_STARTTIME}. * <p> * Persistence is performed by {@link StartupMetadataPersister}. * </p> diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/StandaloneSystemSection.java b/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/StandaloneSystemSection.java index 90f8b838bd6..09006cf1dde 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/StandaloneSystemSection.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/StandaloneSystemSection.java @@ -32,7 +32,6 @@ import org.sonar.core.util.stream.MoreCollectors; import org.sonar.process.ProcessProperties; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.authentication.IdentityProviderRepository; -import org.sonar.server.platform.ServerIdLoader; import org.sonar.server.platform.ServerLogging; import org.sonar.server.user.SecurityRealmFactory; @@ -47,24 +46,22 @@ public class StandaloneSystemSection extends BaseSectionMBean implements SystemS private final IdentityProviderRepository identityProviderRepository; private final Server server; private final ServerLogging serverLogging; - private final ServerIdLoader serverIdLoader; private final OfficialDistribution officialDistribution; public StandaloneSystemSection(Configuration config, SecurityRealmFactory securityRealmFactory, IdentityProviderRepository identityProviderRepository, Server server, ServerLogging serverLogging, - ServerIdLoader serverIdLoader, OfficialDistribution officialDistribution) { + OfficialDistribution officialDistribution) { this.config = config; this.securityRealmFactory = securityRealmFactory; this.identityProviderRepository = identityProviderRepository; this.server = server; this.serverLogging = serverLogging; - this.serverIdLoader = serverIdLoader; this.officialDistribution = officialDistribution; } @Override public String getServerId() { - return serverIdLoader.getRaw().orElse(null); + return server.getId(); } @Override @@ -115,10 +112,7 @@ public class StandaloneSystemSection extends BaseSectionMBean implements SystemS ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); - serverIdLoader.get().ifPresent(serverId -> { - setAttribute(protobuf, "Server ID", serverId.getId()); - setAttribute(protobuf, "Server ID validated", serverId.isValid()); - }); + setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "Version", getVersion()); setAttribute(protobuf, "External User Authentication", getExternalUserAuthentication()); addIfNotEmpty(protobuf, "Accepted external identity providers", getEnabledIdentityProviders()); diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSection.java b/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSection.java index e2999dcb56a..a3c19a42a17 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSection.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSection.java @@ -25,6 +25,7 @@ import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.CoreProperties; import org.sonar.api.config.Configuration; +import org.sonar.api.platform.Server; import org.sonar.api.security.SecurityRealm; import org.sonar.api.server.ServerSide; import org.sonar.api.server.authentication.IdentityProvider; @@ -33,7 +34,6 @@ import org.sonar.process.systeminfo.Global; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.authentication.IdentityProviderRepository; -import org.sonar.server.platform.ServerIdLoader; import org.sonar.server.user.SecurityRealmFactory; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @@ -43,14 +43,14 @@ public class GlobalSystemSection implements SystemInfoSection, Global { private static final Joiner COMMA_JOINER = Joiner.on(", "); private final Configuration config; - private final ServerIdLoader serverIdLoader; + private final Server server; private final SecurityRealmFactory securityRealmFactory; private final IdentityProviderRepository identityProviderRepository; - public GlobalSystemSection(Configuration config, ServerIdLoader serverIdLoader, SecurityRealmFactory securityRealmFactory, + public GlobalSystemSection(Configuration config, Server server, SecurityRealmFactory securityRealmFactory, IdentityProviderRepository identityProviderRepository) { this.config = config; - this.serverIdLoader = serverIdLoader; + this.server = server; this.securityRealmFactory = securityRealmFactory; this.identityProviderRepository = identityProviderRepository; } @@ -60,10 +60,7 @@ public class GlobalSystemSection implements SystemInfoSection, Global { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); - serverIdLoader.get().ifPresent(serverId -> { - setAttribute(protobuf, "Server ID", serverId.getId()); - setAttribute(protobuf, "Server ID validated", serverId.isValid()); - }); + setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "High Availability", true); setAttribute(protobuf, "External User Authentication", getExternalUserAuthentication()); addIfNotEmpty(protobuf, "Accepted external identity providers", getEnabledIdentityProviders()); diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel3.java b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel3.java index a275fad23b5..b816cde5fd1 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel3.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel3.java @@ -23,8 +23,6 @@ import org.sonar.api.utils.UriReader; import org.sonar.core.util.DefaultHttpDownloader; import org.sonar.server.organization.DefaultOrganizationProviderImpl; import org.sonar.server.organization.OrganizationFlagsImpl; -import org.sonar.server.platform.ServerIdGenerator; -import org.sonar.server.platform.ServerIdLoader; import org.sonar.server.platform.ServerIdManager; import org.sonar.server.platform.ServerImpl; import org.sonar.server.platform.StartupMetadataPersister; @@ -48,9 +46,6 @@ public class PlatformLevel3 extends PlatformLevel { DatabaseSettingLoader.class, DatabaseSettingsEnabler.class, UriReader.class, - ServerIdLoader.class, - ServerIdGenerator.class, - LogServerId.class, DefaultHttpDownloader.class, DefaultOrganizationProviderImpl.class, OrganizationFlagsImpl.class); diff --git a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java index c128441fb77..1647effbf21 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java +++ b/server/sonar-server/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java @@ -186,6 +186,7 @@ import org.sonar.server.source.ws.LinesAction; import org.sonar.server.source.ws.RawAction; import org.sonar.server.source.ws.ScmAction; import org.sonar.server.source.ws.SourcesWs; +import org.sonar.server.startup.LogServerId; import org.sonar.server.telemetry.TelemetryClient; import org.sonar.server.telemetry.TelemetryDaemon; import org.sonar.server.telemetry.TelemetryDataLoader; @@ -250,6 +251,7 @@ public class PlatformLevel4 extends PlatformLevel { ChangeLogLevelStandaloneService.class); add( + LogServerId.class, PluginDownloader.class, DeprecatedViews.class, PageRepository.class, diff --git a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ScannerSettings.java b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ScannerSettings.java index 6fadbf2ad93..6cb20ba0546 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ScannerSettings.java +++ b/server/sonar-server/src/main/java/org/sonar/server/setting/ws/ScannerSettings.java @@ -30,7 +30,6 @@ import org.sonar.db.property.PropertyDto; import static java.util.stream.Collectors.toSet; import static java.util.stream.Stream.concat; -import static org.sonar.api.CoreProperties.PERMANENT_SERVER_ID; import static org.sonar.api.CoreProperties.SERVER_ID; import static org.sonar.api.CoreProperties.SERVER_STARTTIME; import static org.sonar.api.PropertyType.LICENSE; @@ -41,7 +40,7 @@ import static org.sonar.server.setting.ws.SettingsWsSupport.LICENSE_HASH_SUFFIX; */ public class ScannerSettings { - private static final Set<String> SERVER_SETTING_KEYS = ImmutableSet.of(PERMANENT_SERVER_ID, SERVER_STARTTIME, SERVER_ID); + private static final Set<String> SERVER_SETTING_KEYS = ImmutableSet.of(SERVER_STARTTIME, SERVER_ID); private final DbClient dbClient; private final PropertyDefinitions propertyDefinitions; diff --git a/server/sonar-server/src/main/java/org/sonar/server/startup/LogServerId.java b/server/sonar-server/src/main/java/org/sonar/server/startup/LogServerId.java index 35dd10f9979..48e7c57cddc 100644 --- a/server/sonar-server/src/main/java/org/sonar/server/startup/LogServerId.java +++ b/server/sonar-server/src/main/java/org/sonar/server/startup/LogServerId.java @@ -19,44 +19,21 @@ */ package org.sonar.server.startup; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; import org.picocontainer.Startable; -import org.sonar.api.CoreProperties; +import org.sonar.api.platform.Server; import org.sonar.api.utils.log.Loggers; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.property.PropertyDto; public final class LogServerId implements Startable { - private final DbClient dbClient; + private final Server server; - public LogServerId(DbClient dbClient) { - this.dbClient = dbClient; + public LogServerId(Server server) { + this.server = server; } @Override public void start() { - try (DbSession dbSession = dbClient.openSession(false)) { - String propertyKey = CoreProperties.PERMANENT_SERVER_ID; - PropertyDto serverIdProp = selectProperty(dbSession, propertyKey); - if (serverIdProp != null) { - // a server ID has been generated, let's print out the other useful information that can help debugging license issues - PropertyDto organizationProp = selectProperty(dbSession, CoreProperties.ORGANISATION); - PropertyDto ipAddressProp = selectProperty(dbSession, CoreProperties.SERVER_ID_IP_ADDRESS); - - StringBuilder message = new StringBuilder("Server information:\n"); - message.append(" - ID : "); - addQuotedValue(serverIdProp, message); - message.append(" - Organization : "); - addQuotedValue(organizationProp, message); - message.append(" - Registered IP: "); - addQuotedValue(ipAddressProp, message); - - Loggers.get(LogServerId.class).info(message.toString()); - } - } + Loggers.get(getClass()).info("Server ID: " + server.getId()); } @Override @@ -64,20 +41,4 @@ public final class LogServerId implements Startable { // nothing to do } - @CheckForNull - private PropertyDto selectProperty(DbSession dbSession, String propertyKey) { - return dbClient.propertiesDao().selectGlobalProperty(dbSession, propertyKey); - } - - private static void addQuotedValue(@Nullable PropertyDto property, StringBuilder message) { - if (property == null || property.getValue() == null) { - message.append('-'); - } else { - message.append("\""); - message.append(property.getValue()); - message.append("\""); - } - message.append('\n'); - } - } diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/ServerIdGeneratorTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/ServerIdGeneratorTest.java deleted file mode 100644 index 8dd9d58c978..00000000000 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/ServerIdGeneratorTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * 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 GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.platform; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import org.apache.commons.lang.StringUtils; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import static org.apache.commons.lang.StringUtils.isBlank; -import static org.assertj.core.api.Assertions.assertThat; - -public class ServerIdGeneratorTest { - static InetAddress localhost; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - ServerIdGenerator underTest = new ServerIdGenerator(true); - - @BeforeClass - public static void init() throws UnknownHostException { - localhost = InetAddress.getLocalHost(); - } - - @Test - public void shouldNotGenerateIdIfBlankParams() { - ServerIdGenerator generator = new ServerIdGenerator(true); - assertThat(generator.validate(" ", "127.0.0.1", "191e806623bb0c2")).isFalse(); - assertThat(generator.validate("SonarSource", " ", "191e806623bb0c2")).isFalse(); - } - - @Test - public void organizationShouldRespectPattern() { - ServerIdGenerator generator = new ServerIdGenerator(true); - assertThat(generator.generate("SonarSource", "127.0.0.1")).isEqualTo("191e806623bb0c2"); - assertThat(generator.validate("SonarSource", "127.0.0.1", "191e806623bb0c2")).isTrue(); - assertThat(generator.validate("SonarSource$", "127.0.0.1", "191e806623bb0c2")).isFalse(); - } - - @Test - public void fail_if_organization_does_not_respect_pattern() { - assertThat(underTest.generate("SonarSource", "127.0.0.1")).isNotEmpty(); - - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Organization name is invalid. Alpha numeric characters and space only are allowed. 'SonarSource$' was provided."); - - underTest.generate("SonarSource$", "127.0.0.1"); - } - - @Test - public void fail_if_organization_is_blank() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Organization name must not be null or empty"); - - underTest.generate(" ", "127.0.0.1"); - } - - @Test - public void fail_if_ip_blank() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("IP must not be null or empty"); - - underTest.generate("SonarSource", " "); - } - - @Test - public void fail_if_ip_is_unknown() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("Invalid IP '50.154.42.42'"); - - underTest.generate("SonarSource", "50.154.42.42"); - } - - @Test - public void checkValidOrganizationName() { - ServerIdGenerator generator = new ServerIdGenerator(); - assertThat(generator.isValidOrganizationName("Sonar Source")).isTrue(); - assertThat(generator.isValidOrganizationName("Sonar Source 5")).isTrue(); - assertThat(generator.isValidOrganizationName("Sonar Source $")).isFalse(); - assertThat(generator.isValidOrganizationName("Sonar Source Héhé")).isFalse(); - assertThat(generator.isValidOrganizationName("Sonar Source \n")).isFalse(); - assertThat(generator.isValidOrganizationName(" ")).isFalse(); - assertThat(generator.isValidOrganizationName("\tBar ")).isFalse(); - } - - @Test - public void idShouldHaveTenCharacters() { - String id = new ServerIdGenerator().toId("SonarSource", localhost); - assertThat(id).hasSize(15); // first character is version + 14 characters for checksum - assertThat(isBlank(id)).isFalse(); - } - - @Test - public void idShouldStartWithVersion() { - String id = new ServerIdGenerator().toId("SonarSource", localhost); - assertThat(id).startsWith(ServerIdGenerator.VERSION); - } - - @Test - public void loopbackAddressesShouldNotBeAccepted() throws UnknownHostException { - assertThat(new ServerIdGenerator().isFixed(InetAddress.getLoopbackAddress())).isFalse(); - } - - @Test - public void idShouldBeUniquePerOrganization() { - ServerIdGenerator generator = new ServerIdGenerator(true); - - String k1 = generator.generate("Corp One", "127.0.0.1"); - String k2 = generator.generate("Corp Two", "127.0.0.1"); - assertThat(StringUtils.equals(k1, k2)).isFalse(); - } - - @Test - public void idShouldBeReproducible() { - ServerIdGenerator generator = new ServerIdGenerator(true); - String i1 = generator.generate("SonarSource", "127.0.0.1"); - String i2 = generator.generate("SonarSource", "127.0.0.1"); - assertThat(StringUtils.equals(i1, i2)).isTrue(); - } - -} diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/ServerIdLoaderTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/ServerIdLoaderTest.java deleted file mode 100644 index 0289e76b7fe..00000000000 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/ServerIdLoaderTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * 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 GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.platform; - -import java.util.Optional; -import org.junit.Test; -import org.sonar.api.CoreProperties; -import org.sonar.api.config.internal.MapSettings; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.Mockito.when; - -public class ServerIdLoaderTest { - - private static final String AN_ID = "ABC"; - private static final String AN_IP = "1.2.3.4"; - public static final String AN_ORGANIZATION = "corp"; - - MapSettings settings = new MapSettings(); - ServerIdGenerator idGenerator = mock(ServerIdGenerator.class); - ServerIdLoader underTest = new ServerIdLoader(settings.asConfig(), idGenerator); - - @Test - public void get_returns_absent_if_id_property_is_not_set() { - settings.setProperty(CoreProperties.ORGANISATION, AN_ORGANIZATION); - settings.setProperty(CoreProperties.SERVER_ID_IP_ADDRESS, AN_IP); - - Optional<ServerId> serverIdOpt = underTest.get(); - assertThat(serverIdOpt).isEmpty(); - verifyZeroInteractions(idGenerator); - } - - @Test - public void get_returns_valid_id() { - settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, AN_ID); - settings.setProperty(CoreProperties.ORGANISATION, AN_ORGANIZATION); - settings.setProperty(CoreProperties.SERVER_ID_IP_ADDRESS, AN_IP); - when(idGenerator.validate(AN_ORGANIZATION, AN_IP, AN_ID)).thenReturn(true); - - Optional<ServerId> serverIdOpt = underTest.get(); - verifyServerId(serverIdOpt.get(), AN_ID, true); - verify(idGenerator).validate(AN_ORGANIZATION, AN_IP, AN_ID); - } - - @Test - public void get_returns_invalid_id_if_id_cant_be_generated_because_missing_organization() { - settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, AN_ID); - settings.setProperty(CoreProperties.SERVER_ID_IP_ADDRESS, AN_IP); - - Optional<ServerId> serverIdOpt = underTest.get(); - - verifyServerId(serverIdOpt.get(), AN_ID, false); - } - - @Test - public void get_returns_invalid_id_if_id_cant_be_generated_because_missing_ip() { - settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, AN_ID); - settings.setProperty(CoreProperties.ORGANISATION, AN_ORGANIZATION); - - Optional<ServerId> serverIdOpt = underTest.get(); - - verifyServerId(serverIdOpt.get(), AN_ID, false); - verifyZeroInteractions(idGenerator); - } - - @Test - public void get_returns_invalid_id_if_id_cant_be_generated_because_missing_ip_and_organization() { - settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, AN_ID); - - Optional<ServerId> serverIdOpt = underTest.get(); - - verifyServerId(serverIdOpt.get(), AN_ID, false); - verifyZeroInteractions(idGenerator); - } - - @Test - public void get_returns_invalid_id_if_input_is_different_than_newly_generated_id() { - settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, AN_ID); - settings.setProperty(CoreProperties.ORGANISATION, AN_ORGANIZATION); - settings.setProperty(CoreProperties.SERVER_ID_IP_ADDRESS, AN_IP); - when(idGenerator.generate(AN_ORGANIZATION, AN_IP)).thenReturn("OTHER"); - - Optional<ServerId> serverIdOpt = underTest.get(); - - verifyServerId(serverIdOpt.get(), AN_ID, false); - verify(idGenerator).validate(AN_ORGANIZATION, AN_IP, AN_ID); - } - - @Test - public void getRaw_loads_id_from_settings() { - assertThat(underTest.getRaw().isPresent()).isFalse(); - - settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, AN_ID); - assertThat(underTest.getRaw().isPresent()).isTrue(); - } - - private static void verifyServerId(ServerId serverId, String expectedId, boolean expectedValid) { - assertThat(serverId.getId()).isEqualTo(expectedId); - assertThat(serverId.isValid()).isEqualTo(expectedValid); - } -} diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/ServerImplTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/ServerImplTest.java index ae164982d5b..e0c0a4b357a 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/ServerImplTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/platform/ServerImplTest.java @@ -84,18 +84,17 @@ public class ServerImplTest { @Test public void test_id() throws IOException { - settings.setProperty(CoreProperties.SERVER_ID, "an_id"); + settings.setProperty(CoreProperties.SERVER_ID, "foo"); - assertThat(underTest.getId()).isEqualTo("an_id"); + assertThat(underTest.getId()).isEqualTo("foo"); + assertThat(underTest.getPermanentServerId()).isEqualTo("foo"); } @Test - public void test_runtime() throws IOException { - settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, "an_id"); + public void test_getVersion() throws IOException { Version version = Version.create(6, 1); when(runtime.getApiVersion()).thenReturn(version); assertThat(underTest.getVersion()).isEqualTo(version.toString()); - assertThat(underTest.getPermanentServerId()).isEqualTo("an_id"); } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/StandaloneSystemSectionTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/StandaloneSystemSectionTest.java index 50730c7a928..9a96abceeb2 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/StandaloneSystemSectionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/StandaloneSystemSectionTest.java @@ -19,7 +19,6 @@ */ package org.sonar.server.platform.monitoring; -import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -30,8 +29,6 @@ import org.sonar.api.utils.log.LoggerLevel; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.authentication.IdentityProviderRepositoryRule; import org.sonar.server.authentication.TestIdentityProvider; -import org.sonar.server.platform.ServerId; -import org.sonar.server.platform.ServerIdLoader; import org.sonar.server.platform.ServerLogging; import org.sonar.server.user.SecurityRealmFactory; @@ -51,19 +48,16 @@ public class StandaloneSystemSectionTest { private MapSettings settings = new MapSettings(); private Server server = mock(Server.class); - private ServerIdLoader serverIdLoader = mock(ServerIdLoader.class); private ServerLogging serverLogging = mock(ServerLogging.class); private SecurityRealmFactory securityRealmFactory = mock(SecurityRealmFactory.class); private OfficialDistribution officialDistribution = mock(OfficialDistribution.class); private StandaloneSystemSection underTest = new StandaloneSystemSection(settings.asConfig(), securityRealmFactory, identityProviderRepository, server, - serverLogging, serverIdLoader, officialDistribution); + serverLogging, officialDistribution); @Before public void setUp() throws Exception { when(serverLogging.getRootLoggerLevel()).thenReturn(LoggerLevel.DEBUG); - when(serverIdLoader.getRaw()).thenReturn(Optional.empty()); - when(serverIdLoader.get()).thenReturn(Optional.empty()); } @Test @@ -73,38 +67,8 @@ public class StandaloneSystemSectionTest { @Test public void test_getServerId() { - when(serverIdLoader.getRaw()).thenReturn(Optional.of("ABC")); + when(server.getId()).thenReturn("ABC"); assertThat(underTest.getServerId()).isEqualTo("ABC"); - - when(serverIdLoader.getRaw()).thenReturn(Optional.empty()); - assertThat(underTest.getServerId()).isNull(); - } - - @Test - public void attributes_contain_information_about_valid_server_id() { - when(serverIdLoader.get()).thenReturn(Optional.of(new ServerId("ABC", true))); - - ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); - assertThatAttributeIs(protobuf, SERVER_ID_PROPERTY, "ABC"); - assertThatAttributeIs(protobuf, SERVER_ID_VALIDATED_PROPERTY, true); - } - - @Test - public void attributes_contain_information_about_non_valid_server_id() { - when(serverIdLoader.get()).thenReturn(Optional.of(new ServerId("ABC", false))); - - ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); - assertThatAttributeIs(protobuf, SERVER_ID_PROPERTY, "ABC"); - assertThatAttributeIs(protobuf, SERVER_ID_VALIDATED_PROPERTY, false); - } - - @Test - public void attributes_do_not_contain_information_about_server_id_if_absent() { - when(serverIdLoader.get()).thenReturn(Optional.empty()); - - ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); - assertThat(attribute(protobuf, SERVER_ID_PROPERTY)).isNull(); - assertThat(attribute(protobuf, SERVER_ID_VALIDATED_PROPERTY)).isNull(); } @Test diff --git a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSectionTest.java b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSectionTest.java index 5d663f52a0e..583f3af5183 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSectionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSectionTest.java @@ -19,17 +19,14 @@ */ package org.sonar.server.platform.monitoring.cluster; -import java.util.Optional; -import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; +import org.sonar.api.platform.Server; import org.sonar.api.security.SecurityRealm; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.authentication.IdentityProviderRepositoryRule; import org.sonar.server.authentication.TestIdentityProvider; -import org.sonar.server.platform.ServerId; -import org.sonar.server.platform.ServerIdLoader; import org.sonar.server.user.SecurityRealmFactory; import static org.assertj.core.api.Assertions.assertThat; @@ -38,27 +35,17 @@ import static org.mockito.Mockito.when; import static org.sonar.process.systeminfo.SystemInfoUtils.attribute; import static org.sonar.server.platform.monitoring.SystemInfoTesting.assertThatAttributeIs; - public class GlobalSystemSectionTest { - private static final String SERVER_ID_PROPERTY = "Server ID"; - private static final String SERVER_ID_VALIDATED_PROPERTY = "Server ID validated"; - @Rule public IdentityProviderRepositoryRule identityProviderRepository = new IdentityProviderRepositoryRule(); private MapSettings settings = new MapSettings(); - private ServerIdLoader serverIdLoader = mock(ServerIdLoader.class); + private Server server = mock(Server.class); private SecurityRealmFactory securityRealmFactory = mock(SecurityRealmFactory.class); private GlobalSystemSection underTest = new GlobalSystemSection(settings.asConfig(), - serverIdLoader, securityRealmFactory, identityProviderRepository); - - @Before - public void setUp() throws Exception { - when(serverIdLoader.getRaw()).thenReturn(Optional.empty()); - when(serverIdLoader.get()).thenReturn(Optional.empty()); - } + server, securityRealmFactory, identityProviderRepository); @Test public void name_is_not_empty() { @@ -66,33 +53,6 @@ public class GlobalSystemSectionTest { } @Test - public void attributes_contain_information_about_valid_server_id() { - when(serverIdLoader.get()).thenReturn(Optional.of(new ServerId("ABC", true))); - - ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); - assertThatAttributeIs(protobuf, SERVER_ID_PROPERTY, "ABC"); - assertThatAttributeIs(protobuf, SERVER_ID_VALIDATED_PROPERTY, true); - } - - @Test - public void attributes_contain_information_about_non_valid_server_id() { - when(serverIdLoader.get()).thenReturn(Optional.of(new ServerId("ABC", false))); - - ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); - assertThatAttributeIs(protobuf, SERVER_ID_PROPERTY, "ABC"); - assertThatAttributeIs(protobuf, SERVER_ID_VALIDATED_PROPERTY, false); - } - - @Test - public void attributes_do_not_contain_information_about_server_id_if_absent() { - when(serverIdLoader.get()).thenReturn(Optional.empty()); - - ProtobufSystemInfo.Section protobuf = underTest.toProtobuf(); - assertThat(attribute(protobuf, SERVER_ID_PROPERTY)).isNull(); - assertThat(attribute(protobuf, SERVER_ID_VALIDATED_PROPERTY)).isNull(); - } - - @Test public void get_realm() throws Exception { SecurityRealm realm = mock(SecurityRealm.class); when(realm.getName()).thenReturn("LDAP"); diff --git a/server/sonar-server/src/test/java/org/sonar/server/setting/ws/ScannerSettingsTest.java b/server/sonar-server/src/test/java/org/sonar/server/setting/ws/ScannerSettingsTest.java index 034d81e613c..6ee20dbe5ea 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/setting/ws/ScannerSettingsTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/setting/ws/ScannerSettingsTest.java @@ -62,6 +62,6 @@ public class ScannerSettingsTest { PropertyDefinition.builder("foo").build(), PropertyDefinition.builder("myplugin.license.secured").type(LICENSE).build())); - assertThat(underTest.getScannerSettingKeys(db.getSession())).contains("sonar.server_id", "sonar.core.id", "sonar.core.startTime"); + assertThat(underTest.getScannerSettingKeys(db.getSession())).contains("sonar.core.id", "sonar.core.startTime"); } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java b/server/sonar-server/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java index 951d74abe7e..5e4afa54144 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/setting/ws/ValuesActionTest.java @@ -710,7 +710,7 @@ public class ValuesActionTest { ValuesWsResponse result = executeRequestForGlobalProperties(); - assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).containsOnly("sonar.server_id", "sonar.core.id", "sonar.core.startTime", "plugin.license.secured", + assertThat(result.getSettingsList()).extracting(Settings.Setting::getKey).containsOnly("sonar.core.id", "sonar.core.startTime", "plugin.license.secured", "sonar.plugin.licenseHash.secured"); } diff --git a/server/sonar-server/src/test/java/org/sonar/server/startup/LogServerIdTest.java b/server/sonar-server/src/test/java/org/sonar/server/startup/LogServerIdTest.java index 10596e6e58a..725f4b0f3f6 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/startup/LogServerIdTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/startup/LogServerIdTest.java @@ -19,21 +19,13 @@ */ package org.sonar.server.startup; -import javax.annotation.Nullable; -import org.junit.After; import org.junit.Rule; import org.junit.Test; -import org.sonar.api.CoreProperties; +import org.sonar.api.platform.Server; import org.sonar.api.utils.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.property.PropertyDto; import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -42,87 +34,17 @@ public class LogServerIdTest { @Rule public LogTester logTester = new LogTester(); - DbClient dbClient = mock(DbClient.class, RETURNS_DEEP_STUBS); - LogServerId underTest = new LogServerId(dbClient); - - @After - public void tearDown() { - underTest.stop(); - } - - @Test - public void log_all_information_at_startup() { - setProperty(CoreProperties.PERMANENT_SERVER_ID, "123456789"); - setProperty(CoreProperties.ORGANISATION, "SonarSource"); - setProperty(CoreProperties.SERVER_ID_IP_ADDRESS, "1.2.3.4"); - - underTest.start(); - - verifyLog("\"123456789\"", "\"SonarSource\"", "\"1.2.3.4\""); - } - @Test - public void do_not_log_if_server_id_is_absent() { - setProperty(CoreProperties.PERMANENT_SERVER_ID, null); + public void log_server_id_at_startup() { + Server server = mock(Server.class); + when(server.getId()).thenReturn("foo"); - underTest.start(); - - assertThat(logTester.logs(LoggerLevel.INFO)).isEmpty(); - } - - @Test - public void log_partial_information_if_organisation_is_missing() { - setProperty(CoreProperties.PERMANENT_SERVER_ID, "123456789"); - setProperty(CoreProperties.SERVER_ID_IP_ADDRESS, "1.2.3.4"); + LogServerId underTest = new LogServerId(server); underTest.start(); + assertThat(logTester.logs(LoggerLevel.INFO)).contains("Server ID: foo"); - verifyLog("\"123456789\"", "-", "\"1.2.3.4\""); - } - - @Test - public void log_partial_information_if_ip_is_missing() { - setProperty(CoreProperties.PERMANENT_SERVER_ID, "123456789"); - setProperty(CoreProperties.ORGANISATION, "SonarSource"); - - underTest.start(); - - verifyLog("\"123456789\"", "\"SonarSource\"", "-"); - } - - @Test - public void log_partial_information_if_ip_and_organisation_are_missing() { - setProperty(CoreProperties.PERMANENT_SERVER_ID, "123456789"); - - underTest.start(); - - verifyLog("\"123456789\"", "-", "-"); - } - - @Test - public void log_partial_information_if_property_is_set_without_value() { - setProperty(CoreProperties.PERMANENT_SERVER_ID, "123456789"); - PropertyDto dto = new PropertyDto().setKey(CoreProperties.ORGANISATION).setValue(null); - when(dbClient.propertiesDao().selectGlobalProperty(any(DbSession.class), eq(CoreProperties.ORGANISATION))).thenReturn(dto); - - underTest.start(); - - verifyLog("\"123456789\"", "-", "-"); - } - - private void setProperty(String propertyKey, @Nullable String propertyValue) { - PropertyDto dto = null; - if (propertyValue != null) { - dto = new PropertyDto().setKey(propertyKey).setValue(propertyValue); - } - when(dbClient.propertiesDao().selectGlobalProperty(any(DbSession.class), eq(propertyKey))).thenReturn(dto); - } - - private void verifyLog(String expectedId, String expectedOrganisation, String expectedIp) { - assertThat(logTester.logs(LoggerLevel.INFO)).contains("Server information:\n" - + " - ID : " + expectedId + "\n" - + " - Organization : " + expectedOrganisation + "\n" - + " - Registered IP: " + expectedIp + "\n"); + // do not fail + underTest.stop(); } - } diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java b/sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java index ba01afdc6d5..7d04c3b095d 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/CoreProperties.java @@ -279,17 +279,23 @@ public interface CoreProperties { /** * @since 2.11 + * @deprecated in 6.7. See {@link Server#getPermanentServerId()} */ + @Deprecated String ORGANISATION = "sonar.organisation"; /** * @since 2.11 + * @deprecated in 6.7. See {@link Server#getPermanentServerId()} */ + @Deprecated String PERMANENT_SERVER_ID = "sonar.server_id"; /** * @since 2.11 + * @deprecated in 6.7. See {@link Server#getPermanentServerId()} */ + @Deprecated String SERVER_ID_IP_ADDRESS = "sonar.server_id.ip_address"; /** diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/PropertyType.java b/sonar-plugin-api/src/main/java/org/sonar/api/PropertyType.java index af6bb545efb..a6d8eadb61d 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/PropertyType.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/PropertyType.java @@ -68,7 +68,9 @@ public enum PropertyType { /** * SonarSource license + * @deprecated in 6.7. */ + @Deprecated LICENSE, /** diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/platform/Server.java b/sonar-plugin-api/src/main/java/org/sonar/api/platform/Server.java index 36f0abd82c6..1d5a7fcb51a 100644 --- a/sonar-plugin-api/src/main/java/org/sonar/api/platform/Server.java +++ b/sonar-plugin-api/src/main/java/org/sonar/api/platform/Server.java @@ -48,13 +48,14 @@ public abstract class Server { public abstract String getId(); /** - * UUID generated on demand by system administrators. It is - * {@code null} by default on fresh installations. When defined, - * value does not change when server is restarted. - * In the context of cluster, value is the same on all nodes. + * Since 6.7, it returns exactly {@link #getId()}. In previous + * versions it returned ab UUID generated on demand by system + * administrators and may be null. + * + * @deprecated replaced by {@link #getId()} in 6.7. * @since 2.10 */ - @CheckForNull + @Deprecated public abstract String getPermanentServerId(); /** diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalConfiguration.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalConfiguration.java index f22c14f4f99..7e6b04b51df 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalConfiguration.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/GlobalConfiguration.java @@ -51,7 +51,7 @@ public class GlobalConfiguration extends DefaultConfiguration { super(propertyDefinitions, encryption, mode, settings); this.serverSideSettings = unmodifiableMapWithTrimmedValues(propertyDefinitions, serverSideSettings); - get(CoreProperties.PERMANENT_SERVER_ID).ifPresent(v -> LOG.info("Server id: {}", v)); + get(CoreProperties.SERVER_ID).ifPresent(v -> LOG.info("Server id: {}", v)); new DroppedPropertyChecker(getProperties(), DROPPED_PROPERTIES).checkDroppedProperties(); } diff --git a/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/DefaultServer.java b/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/DefaultServer.java index 06f72c3d250..796c6b4ea52 100644 --- a/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/DefaultServer.java +++ b/sonar-scanner-engine/src/main/java/org/sonar/scanner/platform/DefaultServer.java @@ -105,6 +105,6 @@ public class DefaultServer extends Server { @Override public String getPermanentServerId() { - return settings.getString(CoreProperties.PERMANENT_SERVER_ID); + return getId(); } } diff --git a/sonar-scanner-engine/src/test/java/org/sonar/scanner/platform/DefaultServerTest.java b/sonar-scanner-engine/src/test/java/org/sonar/scanner/platform/DefaultServerTest.java index 2af9a10feab..886588d6597 100644 --- a/sonar-scanner-engine/src/test/java/org/sonar/scanner/platform/DefaultServerTest.java +++ b/sonar-scanner-engine/src/test/java/org/sonar/scanner/platform/DefaultServerTest.java @@ -39,7 +39,6 @@ public class DefaultServerTest { Settings settings = new MapSettings(); settings.setProperty(CoreProperties.SERVER_ID, "123"); settings.setProperty(CoreProperties.SERVER_STARTTIME, "2010-05-18T17:59:00+0000"); - settings.setProperty(CoreProperties.PERMANENT_SERVER_ID, "abcde"); ScannerWsClient client = mock(ScannerWsClient.class); when(client.baseUrl()).thenReturn("http://foo.com"); @@ -49,7 +48,7 @@ public class DefaultServerTest { assertThat(metadata.getVersion()).isEqualTo("2.2"); assertThat(metadata.getStartedAt()).isNotNull(); assertThat(metadata.getURL()).isEqualTo("http://foo.com"); - assertThat(metadata.getPermanentServerId()).isEqualTo("abcde"); + assertThat(metadata.getPermanentServerId()).isEqualTo("123"); assertThat(metadata.getRootDir()).isNull(); assertThat(metadata.getDeployDir()).isNull(); diff --git a/tests/src/test/java/org/sonarqube/tests/Category5Suite.java b/tests/src/test/java/org/sonarqube/tests/Category5Suite.java index c2d259ebac4..bd4ee5b26d0 100644 --- a/tests/src/test/java/org/sonarqube/tests/Category5Suite.java +++ b/tests/src/test/java/org/sonarqube/tests/Category5Suite.java @@ -34,7 +34,6 @@ import org.sonarqube.tests.serverSystem.RestartTest; import org.sonarqube.tests.serverSystem.ServerSystemRestartingOrchestrator; import org.sonarqube.tests.serverSystem.SystemStateTest; import org.sonarqube.tests.settings.ElasticsearchSettingsTest; -import org.sonarqube.tests.settings.LicensesPageTest; import org.sonarqube.tests.settings.SettingsTestRestartingOrchestrator; import org.sonarqube.tests.startup.StartupIndexationTest; import org.sonarqube.tests.telemetry.TelemetryOptOutTest; @@ -57,7 +56,6 @@ import org.sonarqube.tests.user.UserEsResilienceTest; RestartTest.class, SettingsTestRestartingOrchestrator.class, SystemStateTest.class, - LicensesPageTest.class, // update center UpdateCenterTest.class, RealmAuthenticationTest.class, diff --git a/tests/src/test/java/org/sonarqube/tests/settings/LicensesPageTest.java b/tests/src/test/java/org/sonarqube/tests/settings/LicensesPageTest.java deleted file mode 100644 index 5f0ebe0078d..00000000000 --- a/tests/src/test/java/org/sonarqube/tests/settings/LicensesPageTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * 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 GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonarqube.tests.settings; - -import com.sonar.orchestrator.Orchestrator; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.sonarqube.ws.Settings.ValuesWsResponse; -import org.sonarqube.ws.client.WsClient; -import org.sonarqube.ws.client.setting.ValuesRequest; -import org.sonarqube.pageobjects.Navigation; -import org.sonarqube.pageobjects.licenses.LicenseItem; -import org.sonarqube.pageobjects.licenses.LicensesPage; -import util.user.UserRule; - -import static com.codeborne.selenide.Condition.text; -import static org.assertj.core.api.Assertions.assertThat; -import static util.ItUtils.newAdminWsClient; -import static util.ItUtils.pluginArtifact; - -public class LicensesPageTest { - private static Orchestrator orchestrator; - private static WsClient wsClient; - - @Rule - public UserRule userRule = UserRule.from(orchestrator); - - private String adminUser; - - @BeforeClass - public static void start() { - orchestrator = Orchestrator.builderEnv() - .addPlugin(pluginArtifact("license-plugin")) - .build(); - orchestrator.start(); - - wsClient = newAdminWsClient(orchestrator); - } - - @AfterClass - public static void stop() { - if (orchestrator != null) { - orchestrator.stop(); - } - } - - @Before - public void before() { - adminUser = userRule.createAdminUser(); - } - - @Test - public void display_licenses() { - LicensesPage page = Navigation.create(orchestrator).logIn().submitCredentials(adminUser).openLicenses(); - - page.getLicenses().shouldHaveSize(2); - page.getLicensesAsItems().get(0).getName().shouldHave(text("Typed property")); - page.getLicensesAsItems().get(1).getName().shouldHave(text("Property without license type")); - } - - @Test - public void change_licenses() { - String EXAMPLE_LICENSE = "TmFtZTogRGV2ZWxvcHBlcnMKUGx1Z2luOiBhdXRvY29udHJvbApFeHBpcmVzOiAyMDEyLTA0LTAxCktleTogNjI5N2MxMzEwYzg2NDZiZTE5MDU1MWE4ZmZmYzk1OTBmYzEyYTIyMgo="; - - LicensesPage page = Navigation.create(orchestrator).logIn().submitCredentials(adminUser).openLicenses(); - LicenseItem licenseItem = page.getLicenseByKey("typed.license.secured"); - licenseItem.setLicense(EXAMPLE_LICENSE); - - ValuesWsResponse response = wsClient.settings() - .values(ValuesRequest.builder().setKeys("typed.license.secured").build()); - assertThat(response.getSettings(0).getValue()).isEqualTo(EXAMPLE_LICENSE); - } -} |