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;
private static Object[] startupComponents() {
return new Object[] {
- LogServerId.class,
ServerLifecycleNotifier.class,
PurgeCeActivities.class,
CeQueueCleaner.class
);
assertThat(picoContainer.getParent().getParent().getComponentAdapters()).hasSize(
CONTAINER_ITSELF
- + 12 // MigrationConfigurationModule
+ + 13 // MigrationConfigurationModule
+ 17 // level 2
);
assertThat(picoContainer.getParent().getParent().getParent().getComponentAdapters()).hasSize(
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
DbVersion64.class,
DbVersion65.class,
DbVersion66.class,
+ DbVersion67.class,
// migration steps
MigrationStepRegistryImpl.class,
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;
--- /dev/null
+/*
+ * 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();
+ }
+
+}
--- /dev/null
+/*
+ * 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)
+ ;
+ }
+}
--- /dev/null
+/*
+ * 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.
+ */
+@ParametersAreNonnullByDefault
+package org.sonar.server.platform.db.migration.version.v67;
+
+import javax.annotation.ParametersAreNonnullByDefault;
+
assertThat(container.getPicoContainer().getComponentAdapters())
.hasSize(COMPONENTS_IN_EMPTY_COMPONENT_CONTAINER
// DbVersion classes
- + 9
+ + 10
// Others
+ 3);
}
--- /dev/null
+/*
+ * 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);
+ }
+}
--- /dev/null
+/*
+ * 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);
+ }
+
+}
--- /dev/null
+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");
+++ /dev/null
-/*
- * 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 javax.annotation.concurrent.Immutable;
-
-@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;
- }
-}
+++ /dev/null
-/*
- * 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;
- }
-}
+++ /dev/null
-/*
- * 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);
- });
- }
-}
@Override
public String getPermanentServerId() {
- return config.get(CoreProperties.PERMANENT_SERVER_ID).orElse(null);
+ return getId();
}
@Override
}
/**
- * 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>
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;
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
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());
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;
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;
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;
}
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());
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;
DatabaseSettingLoader.class,
DatabaseSettingsEnabler.class,
UriReader.class,
- ServerIdLoader.class,
- ServerIdGenerator.class,
- LogServerId.class,
DefaultHttpDownloader.class,
DefaultOrganizationProviderImpl.class,
OrganizationFlagsImpl.class);
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;
ChangeLogLevelStandaloneService.class);
add(
+ LogServerId.class,
PluginDownloader.class,
DeprecatedViews.class,
PageRepository.class,
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;
*/
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;
*/
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
// 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');
- }
-
}
+++ /dev/null
-/*
- * 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();
- }
-
-}
+++ /dev/null
-/*
- * 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);
- }
-}
@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");
}
}
*/
package org.sonar.server.platform.monitoring;
-import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
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;
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
@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
*/
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;
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() {
assertThat(underTest.toProtobuf().getName()).isEqualTo("System");
}
- @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);
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");
}
}
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");
}
*/
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;
@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();
}
-
}
/**
* @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";
/**
/**
* SonarSource license
+ * @deprecated in 6.7.
*/
+ @Deprecated
LICENSE,
/**
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();
/**
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();
}
@Override
public String getPermanentServerId() {
- return settings.getString(CoreProperties.PERMANENT_SERVER_ID);
+ return getId();
}
}
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");
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();
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;
RestartTest.class,
SettingsTestRestartingOrchestrator.class,
SystemStateTest.class,
- LicensesPageTest.class,
// update center
UpdateCenterTest.class,
RealmAuthenticationTest.class,
+++ /dev/null
-/*
- * 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);
- }
-}