repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/tester/MockUserSession.java
/* * SonarQube * Copyright (C) 2009-2023 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.tester; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Optional; import javax.annotation.CheckForNull; import org.jetbrains.annotations.Nullable; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.user.AbstractUserSession; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; import static org.sonar.server.user.UserSession.IdentityProvider.SONARQUBE; public class MockUserSession extends AbstractMockUserSession<MockUserSession> { private final String login; private String uuid; private String name; private List<GroupDto> groups = new ArrayList<>(); private UserSession.IdentityProvider identityProvider; private UserSession.ExternalIdentity externalIdentity; private Long lastSonarlintConnectionDate; public MockUserSession(String login) { super(MockUserSession.class); checkArgument(!login.isEmpty()); this.login = login; setUuid(login + "uuid"); setName(login + " name"); setInternalIdentity(); } public MockUserSession(UserDto userDto) { super(MockUserSession.class); checkArgument(!userDto.getLogin().isEmpty()); this.login = userDto.getLogin(); setUuid(userDto.getUuid()); setName(userDto.getName()); AbstractUserSession.Identity identity = AbstractUserSession.computeIdentity(userDto); this.identityProvider = identity.getIdentityProvider(); this.externalIdentity = identity.getExternalIdentity(); } @CheckForNull @Override public Long getLastSonarlintConnectionDate() { return lastSonarlintConnectionDate; } public MockUserSession setLastSonarlintConnectionDate(@Nullable Long lastSonarlintConnectionDate) { this.lastSonarlintConnectionDate = lastSonarlintConnectionDate; return this; } @Override public boolean isLoggedIn() { return true; } @Override public boolean isActive() { return true; } @Override public String getLogin() { return this.login; } @Override public String getUuid() { return this.uuid; } public MockUserSession setUuid(String uuid) { this.uuid = requireNonNull(uuid); return this; } @Override public String getName() { return this.name; } public MockUserSession setName(String s) { this.name = requireNonNull(s); return this; } @Override public Collection<GroupDto> getGroups() { return groups; } public MockUserSession setGroups(GroupDto... groups) { this.groups = asList(groups); return this; } @Override public Optional<UserSession.IdentityProvider> getIdentityProvider() { return Optional.ofNullable(identityProvider); } public void setExternalIdentity(UserSession.IdentityProvider identityProvider, UserSession.ExternalIdentity externalIdentity) { checkArgument(identityProvider != SONARQUBE); this.identityProvider = identityProvider; this.externalIdentity = requireNonNull(externalIdentity); } public void setInternalIdentity() { this.identityProvider = SONARQUBE; this.externalIdentity = null; } @Override public Optional<UserSession.ExternalIdentity> getExternalIdentity() { return Optional.ofNullable(externalIdentity); } }
4,235
28.213793
129
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/tester/UserSessionRule.java
/* * SonarQube * Copyright (C) 2009-2023 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.tester; import com.google.common.base.Preconditions; import java.util.Collection; import java.util.List; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.user.UserSession; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; /** * {@code UserSessionRule} is intended to be used as a {@link org.junit.Rule} to easily manage {@link UserSession} in * unit tests. * <p> * It can be used as a {@link org.junit.ClassRule} but be careful not to modify its states from inside tests methods * unless you purposely want to have side effects between each tests. * </p> * <p> * One can define user session behavior which should apply on all tests directly on the property, eg.: * <pre> * {@literal @}Rule * public UserSessionRule userSession = UserSessionRule.standalone().login("admin").setOrganizationPermissions(OrganizationPermissions.SYSTEM_ADMIN); * </pre> * </p> * <p> * Behavior defined at property-level can obviously be override at test method level. For example, one could define * all methods to use an authenticated session such as presented above but can easily overwrite that behavior in a * specific test method as follow: * <pre> * {@literal @}Test * public void test_method() { * userSession.standalone(); * {@literal [...]} * } * </pre> * </p> * <p> * {@code UserSessionRule}, emulates by default an anonymous * session. Therefore, call {@code UserSessionRule.standalone()} is equivalent to calling * {@code UserSessionRule.standalone().anonymous()}. * </p> * <p> * To emulate an identified user, either use method {@link #logIn(String)} if you want to specify the user's login, or * method {@link #logIn()} which will do the same but using the value of {@link #DEFAULT_LOGIN} as the user's login * (use the latest override if you don't care about the actual value of the login, it will save noise in your test). * </p> */ public class UserSessionRule implements TestRule, UserSession { private static final String DEFAULT_LOGIN = "default_login"; private UserSession currentUserSession; private UserSessionRule() { anonymous(); } public static UserSessionRule standalone() { return new UserSessionRule(); } /** * Log in with the default login {@link #DEFAULT_LOGIN} */ public UserSessionRule logIn() { return logIn(DEFAULT_LOGIN); } /** * Log in with the specified login */ public UserSessionRule logIn(String login) { setCurrentUserSession(new MockUserSession(login)); return this; } /** * Log in with the specified login */ public UserSessionRule logIn(UserDto userDto) { setCurrentUserSession(new MockUserSession(userDto)); return this; } /** * Disconnect/go anonymous */ public UserSessionRule anonymous() { setCurrentUserSession(new AnonymousMockUserSession()); return this; } public UserSessionRule setSystemAdministrator() { ensureMockUserSession().setSystemAdministrator(true); return this; } public UserSessionRule setNonSystemAdministrator() { ensureMockUserSession().setSystemAdministrator(false); return this; } public UserSessionRule setExternalIdentity(IdentityProvider identityProvider, ExternalIdentity externalIdentity) { ensureMockUserSession().setExternalIdentity(identityProvider, externalIdentity); return this; } public UserSessionRule setInternalIdentity() { ensureMockUserSession().setInternalIdentity(); return this; } @Override public Statement apply(Statement statement, Description description) { return this.statement(statement); } private Statement statement(final Statement base) { return new Statement() { public void evaluate() throws Throwable { UserSessionRule.this.before(); try { base.evaluate(); } finally { UserSessionRule.this.after(); } } }; } protected void before() { setCurrentUserSession(currentUserSession); } protected void after() { this.currentUserSession = null; } public void set(UserSession userSession) { checkNotNull(userSession); setCurrentUserSession(userSession); } public UserSessionRule registerPortfolios(ComponentDto... portfolios) { ensureAbstractMockUserSession().registerComponents(portfolios); return this; } public UserSessionRule registerPortfolios(PortfolioDto... portfolioDtos) { ensureAbstractMockUserSession().registerPortfolios(portfolioDtos); return this; } public UserSessionRule registerProjects(ProjectDto... projectDtos) { ensureAbstractMockUserSession().registerProjects(projectDtos); return this; } public UserSessionRule registerApplication(ProjectDto application, ProjectDto... appProjects) { ensureAbstractMockUserSession().registerApplication(application, appProjects); return this; } public UserSessionRule addProjectPermission(String projectPermission, ComponentDto... components) { ensureAbstractMockUserSession().addProjectPermission(projectPermission, components); return this; } public UserSessionRule addPortfolioPermission(String projectPermission, ComponentDto... components) { ensureAbstractMockUserSession().addProjectPermission(projectPermission, components); return this; } public UserSessionRule addProjectBranchMapping(String projectUuid, ComponentDto... branchComponents) { ensureAbstractMockUserSession().addProjectBranchMapping(projectUuid, branchComponents); return this; } public UserSessionRule registerBranches(BranchDto... branchDtos) { ensureAbstractMockUserSession().registerBranches(branchDtos); return this; } public UserSessionRule addProjectPermission(String projectPermission, ProjectDto... projectDto) { ensureAbstractMockUserSession().addProjectPermission(projectPermission, projectDto); return this; } public UserSessionRule addPortfolioPermission(String portfolioPermission, PortfolioDto... portfolioDto) { ensureAbstractMockUserSession().addPortfolioPermission(portfolioPermission, portfolioDto); return this; } public UserSessionRule addPermission(GlobalPermission permission) { ensureAbstractMockUserSession().addPermission(permission); return this; } /** * Groups that user is member of. User must be logged in. An exception * is thrown if session is anonymous. */ public UserSessionRule setGroups(GroupDto... groups) { ensureMockUserSession().setGroups(groups); return this; } public UserSessionRule setName(@Nullable String s) { ensureMockUserSession().setName(s); return this; } private AbstractMockUserSession ensureAbstractMockUserSession() { checkState(currentUserSession instanceof AbstractMockUserSession, "rule state can not be changed if a UserSession has explicitly been provided"); return (AbstractMockUserSession) currentUserSession; } private MockUserSession ensureMockUserSession() { checkState(currentUserSession instanceof MockUserSession, "rule state can not be changed if a UserSession has explicitly been provided"); return (MockUserSession) currentUserSession; } private void setCurrentUserSession(UserSession userSession) { this.currentUserSession = Preconditions.checkNotNull(userSession); } @Override public boolean hasComponentPermission(String permission, ComponentDto component) { return currentUserSession.hasComponentPermission(permission, component); } @Override public boolean hasEntityPermission(String permission, EntityDto entity) { return currentUserSession.hasEntityPermission(permission, entity.getUuid()); } @Override public boolean hasEntityPermission(String permission, String entityUuid) { return currentUserSession.hasEntityPermission(permission, entityUuid); } @Override public boolean hasChildProjectsPermission(String permission, ComponentDto component) { return currentUserSession.hasChildProjectsPermission(permission, component); } @Override public boolean hasChildProjectsPermission(String permission, EntityDto application) { return currentUserSession.hasChildProjectsPermission(permission, application); } @Override public boolean hasPortfolioChildProjectsPermission(String permission, ComponentDto component) { return currentUserSession.hasPortfolioChildProjectsPermission(permission, component); } @Override public boolean hasComponentUuidPermission(String permission, String componentUuid) { return currentUserSession.hasComponentUuidPermission(permission, componentUuid); } @Override public List<ComponentDto> keepAuthorizedComponents(String permission, Collection<ComponentDto> components) { return currentUserSession.keepAuthorizedComponents(permission, components); } @Override public <T extends EntityDto> List<T> keepAuthorizedEntities(String permission, Collection<T> entities) { return currentUserSession.keepAuthorizedEntities(permission, entities); } @Override @CheckForNull public String getLogin() { return currentUserSession.getLogin(); } @Override @CheckForNull public String getUuid() { return currentUserSession.getUuid(); } @Override @CheckForNull public String getName() { return currentUserSession.getName(); } @Override @CheckForNull public Long getLastSonarlintConnectionDate() { return currentUserSession.getLastSonarlintConnectionDate(); } @Override public Collection<GroupDto> getGroups() { return currentUserSession.getGroups(); } @Override public boolean shouldResetPassword() { return currentUserSession.shouldResetPassword(); } @Override public Optional<IdentityProvider> getIdentityProvider() { return currentUserSession.getIdentityProvider(); } @Override public Optional<ExternalIdentity> getExternalIdentity() { return currentUserSession.getExternalIdentity(); } @Override public boolean isLoggedIn() { return currentUserSession.isLoggedIn(); } @Override public UserSession checkLoggedIn() { currentUserSession.checkLoggedIn(); return this; } @Override public boolean hasPermission(GlobalPermission permission) { return currentUserSession.hasPermission(permission); } @Override public UserSession checkPermission(GlobalPermission permission) { currentUserSession.checkPermission(permission); return this; } @Override public UserSession checkComponentPermission(String projectPermission, ComponentDto component) { currentUserSession.checkComponentPermission(projectPermission, component); return this; } @Override public UserSession checkEntityPermission(String projectPermission, EntityDto entity) { currentUserSession.checkEntityPermission(projectPermission, entity); return this; } @Override public UserSession checkChildProjectsPermission(String projectPermission, ComponentDto component) { currentUserSession.checkChildProjectsPermission(projectPermission, component); return this; } @Override public UserSession checkChildProjectsPermission(String projectPermission, EntityDto application) { currentUserSession.checkChildProjectsPermission(projectPermission, application); return this; } @Override public UserSession checkComponentUuidPermission(String permission, String componentUuid) { currentUserSession.checkComponentUuidPermission(permission, componentUuid); return this; } @Override public boolean isSystemAdministrator() { return currentUserSession.isSystemAdministrator(); } @Override public UserSession checkIsSystemAdministrator() { currentUserSession.checkIsSystemAdministrator(); return this; } @Override public boolean isActive() { return currentUserSession.isActive(); } }
13,255
30.637232
149
java
sonarqube
sonarqube-master/server/sonar-webserver-auth/src/testFixtures/java/org/sonar/server/user/TestUserSessionFactory.java
/* * SonarQube * Copyright (C) 2009-2023 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.user; import java.util.Collection; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.db.permission.GlobalPermission; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTokenDto; import static java.util.Objects.requireNonNull; /** * Simple implementation of {@link UserSessionFactory}. It creates * instances of {@link UserSession} that don't manage groups nor * permissions. Only basic user information like {@link UserSession#isLoggedIn()} * and {@link UserSession#getLogin()} are available. The methods * relying on groups or permissions throw {@link UnsupportedOperationException}. */ public class TestUserSessionFactory implements UserSessionFactory { private TestUserSessionFactory() { } @Override public UserSession create(UserDto user) { return new TestUserSession(requireNonNull(user)); } @Override public UserSession create(UserDto user, UserTokenDto userToken) { return new TestUserSession(requireNonNull(user)); } @Override public GithubWebhookUserSession createGithubWebhookUserSession() { return new GithubWebhookUserSession(); } @Override public UserSession createAnonymous() { return new TestUserSession(null); } public static TestUserSessionFactory standalone() { return new TestUserSessionFactory(); } private static class TestUserSession extends AbstractUserSession { private final UserDto user; public TestUserSession(@Nullable UserDto user) { this.user = user; } @Override public String getLogin() { return user != null ? user.getLogin() : null; } @Override public String getUuid() { return user != null ? user.getUuid() : null; } @Override public String getName() { return user != null ? user.getName() : null; } @Override public Collection<GroupDto> getGroups() { throw notImplemented(); } @Override public boolean shouldResetPassword() { return user != null && user.isResetPassword(); } @Override public Optional<IdentityProvider> getIdentityProvider() { throw notImplemented(); } @Override public Optional<ExternalIdentity> getExternalIdentity() { throw notImplemented(); } @Override public boolean isLoggedIn() { return user != null; } @Override protected boolean hasPermissionImpl(GlobalPermission permission) { throw notImplemented(); } @Override protected Optional<String> componentUuidToEntityUuid(String componentUuid) { throw notImplemented(); } @Override protected boolean hasEntityUuidPermission(String permission, String entityUuid) { throw notImplemented(); } @Override protected boolean hasChildProjectsPermission(String permission, String applicationUuid) { throw notImplemented(); } @Override protected boolean hasPortfolioChildProjectsPermission(String permission, String portfolioUuid) { throw notImplemented(); } @Override public boolean isSystemAdministrator() { throw notImplemented(); } @Override public boolean isActive() { throw notImplemented(); } private static RuntimeException notImplemented() { return new UnsupportedOperationException("not implemented"); } } }
4,237
26.699346
126
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/it/java/org/sonar/server/platform/PersistentSettingsIT.java
/* * SonarQube * Copyright (C) 2009-2023 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 org.junit.Rule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.config.internal.Settings; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.server.setting.SettingsChangeNotifier; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class PersistentSettingsIT { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private Settings delegate = new MapSettings(); private SettingsChangeNotifier changeNotifier = mock(SettingsChangeNotifier.class); private PersistentSettings underTest = new PersistentSettings(delegate, dbTester.getDbClient(), changeNotifier); @Test public void insert_property_into_database_and_notify_extensions() { assertThat(underTest.getString("foo")).isNull(); underTest.saveProperty("foo", "bar"); assertThat(underTest.getString("foo")).isEqualTo("bar"); assertThat(dbTester.getDbClient().propertiesDao().selectGlobalProperty("foo").getValue()).isEqualTo("bar"); verify(changeNotifier).onGlobalPropertyChange("foo", "bar"); } @Test public void delete_property_from_database_and_notify_extensions() { underTest.saveProperty("foo", "bar"); underTest.saveProperty("foo", null); assertThat(underTest.getString("foo")).isNull(); assertThat(dbTester.getDbClient().propertiesDao().selectGlobalProperty("foo")).isNull(); verify(changeNotifier).onGlobalPropertyChange("foo", null); } @Test public void getSettings_returns_delegate() { assertThat(underTest.getSettings()).isSameAs(delegate); } }
2,561
37.238806
114
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/it/java/org/sonar/server/platform/StartupMetadataPersisterIT.java
/* * SonarQube * Copyright (C) 2009-2023 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 org.junit.Rule; import org.junit.Test; import org.sonar.api.CoreProperties; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.property.PropertyDto; import static org.assertj.core.api.Assertions.assertThat; public class StartupMetadataPersisterIT { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private StartupMetadata metadata = new StartupMetadata(123_456_789L); private StartupMetadataPersister underTest = new StartupMetadataPersister(metadata, dbTester.getDbClient()); @Test public void persist_metadata_at_startup() { underTest.start(); assertPersistedProperty(CoreProperties.SERVER_STARTTIME, DateUtils.formatDateTime(metadata.getStartedAt())); underTest.stop(); } private void assertPersistedProperty(String propertyKey, String expectedValue) { PropertyDto prop = dbTester.getDbClient().propertiesDao().selectGlobalProperty(dbTester.getSession(), propertyKey); assertThat(prop.getValue()).isEqualTo(expectedValue); } }
1,954
35.203704
119
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/it/java/org/sonar/server/platform/serverid/ServerIdManagerIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.serverid; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.CoreProperties; import org.sonar.api.SonarEdition; import org.sonar.api.SonarQubeSide; import org.sonar.api.internal.SonarRuntimeImpl; import org.sonar.api.utils.System2; import org.sonar.api.utils.Version; import org.sonar.core.platform.ServerId; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.property.PropertyDto; import org.sonar.server.platform.NodeInformation; import org.sonar.server.property.InternalProperties; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.api.SonarQubeSide.COMPUTE_ENGINE; import static org.sonar.api.SonarQubeSide.SERVER; import static org.sonar.core.platform.ServerId.DATABASE_ID_LENGTH; import static org.sonar.core.platform.ServerId.NOT_UUID_DATASET_ID_LENGTH; import static org.sonar.core.platform.ServerId.UUID_DATASET_ID_LENGTH; @RunWith(DataProviderRunner.class) public class ServerIdManagerIT { private static final ServerId WITH_DATABASE_ID_SERVER_ID = ServerId.of(randomAlphanumeric(DATABASE_ID_LENGTH), randomAlphanumeric(NOT_UUID_DATASET_ID_LENGTH)); private static final String CHECKSUM_1 = randomAlphanumeric(12); @Rule public final DbTester dbTester = DbTester.create(System2.INSTANCE); private final ServerIdChecksum serverIdChecksum = mock(ServerIdChecksum.class); private final ServerIdFactory serverIdFactory = mock(ServerIdFactory.class); private final DbClient dbClient = dbTester.getDbClient(); private final DbSession dbSession = dbTester.getSession(); private final NodeInformation nodeInformation = mock(NodeInformation.class); private ServerIdManager underTest; @After public void tearDown() { if (underTest != null) { underTest.stop(); } } @Test public void web_leader_persists_new_server_id_if_missing() { mockCreateNewServerId(); mockChecksumOf(WITH_DATABASE_ID_SERVER_ID, CHECKSUM_1); when(nodeInformation.isStartupLeader()).thenReturn(true); test(SERVER); verifyDb(CHECKSUM_1); verifyCreateNewServerIdFromScratch(); } @Test public void web_leader_persists_new_server_id_if_value_is_empty() { insertServerId(""); mockCreateNewServerId(); mockChecksumOf(WITH_DATABASE_ID_SERVER_ID, CHECKSUM_1); when(nodeInformation.isStartupLeader()).thenReturn(true); test(SERVER); verifyDb(CHECKSUM_1); verifyCreateNewServerIdFromScratch(); } @Test public void web_leader_keeps_existing_server_id_if_valid() { insertServerId(WITH_DATABASE_ID_SERVER_ID); insertChecksum(CHECKSUM_1); mockChecksumOf(WITH_DATABASE_ID_SERVER_ID, CHECKSUM_1); when(nodeInformation.isStartupLeader()).thenReturn(true); test(SERVER); verifyDb(CHECKSUM_1); } @Test public void web_leader_creates_server_id_from_current_serverId_with_databaseId_if_checksum_fails() { ServerId currentServerId = ServerId.of(randomAlphanumeric(DATABASE_ID_LENGTH), randomAlphanumeric(UUID_DATASET_ID_LENGTH)); insertServerId(currentServerId); insertChecksum("does_not_match_WITH_DATABASE_ID_SERVER_ID"); mockChecksumOf(currentServerId, "matches_WITH_DATABASE_ID_SERVER_ID"); mockCreateNewServerIdFrom(currentServerId); mockChecksumOf(WITH_DATABASE_ID_SERVER_ID, CHECKSUM_1); when(nodeInformation.isStartupLeader()).thenReturn(true); test(SERVER); verifyDb(CHECKSUM_1); verifyCreateNewServerIdFrom(currentServerId); } @Test public void web_leader_generates_missing_checksum_for_current_serverId_with_databaseId() { insertServerId(WITH_DATABASE_ID_SERVER_ID); mockChecksumOf(WITH_DATABASE_ID_SERVER_ID, CHECKSUM_1); when(nodeInformation.isStartupLeader()).thenReturn(true); test(SERVER); verifyDb(CHECKSUM_1); } @Test public void web_follower_does_not_fail_if_server_id_matches_checksum() { insertServerId(WITH_DATABASE_ID_SERVER_ID); insertChecksum(CHECKSUM_1); mockChecksumOf(WITH_DATABASE_ID_SERVER_ID, CHECKSUM_1); when(nodeInformation.isStartupLeader()).thenReturn(false); test(SERVER); // no changes verifyDb(CHECKSUM_1); } @Test public void web_follower_fails_if_server_id_is_missing() { when(nodeInformation.isStartupLeader()).thenReturn(false); expectMissingServerIdException(() -> test(SERVER)); } @Test public void web_follower_fails_if_server_id_is_empty() { insertServerId(""); when(nodeInformation.isStartupLeader()).thenReturn(false); expectEmptyServerIdException(() -> test(SERVER)); } @Test public void web_follower_fails_if_checksum_does_not_match() { String dbChecksum = "boom"; insertServerId(WITH_DATABASE_ID_SERVER_ID); insertChecksum(dbChecksum); mockChecksumOf(WITH_DATABASE_ID_SERVER_ID, CHECKSUM_1); when(nodeInformation.isStartupLeader()).thenReturn(false); try { test(SERVER); fail("An ISE should have been raised"); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Server ID is invalid"); // no changes verifyDb(dbChecksum); } } @Test public void compute_engine_does_not_fail_if_server_id_is_valid() { insertServerId(WITH_DATABASE_ID_SERVER_ID); insertChecksum(CHECKSUM_1); mockChecksumOf(WITH_DATABASE_ID_SERVER_ID, CHECKSUM_1); test(COMPUTE_ENGINE); // no changes verifyDb(CHECKSUM_1); } @Test public void compute_engine_fails_if_server_id_is_missing() { expectMissingServerIdException(() -> test(COMPUTE_ENGINE)); } @Test public void compute_engine_fails_if_server_id_is_empty() { insertServerId(""); expectEmptyServerIdException(() -> test(COMPUTE_ENGINE)); } @Test public void compute_engine_fails_if_server_id_is_invalid() { String dbChecksum = "boom"; insertServerId(WITH_DATABASE_ID_SERVER_ID); insertChecksum(dbChecksum); mockChecksumOf(WITH_DATABASE_ID_SERVER_ID, CHECKSUM_1); try { test(SERVER); fail("An ISE should have been raised"); } catch (IllegalStateException e) { assertThat(e.getMessage()).isEqualTo("Server ID is invalid"); // no changes verifyDb(dbChecksum); } } private void expectEmptyServerIdException(ThrowingCallable callback) { assertThatThrownBy(callback) .isInstanceOf(IllegalStateException.class) .hasMessage("Property sonar.core.id is empty in database"); } private void expectMissingServerIdException(ThrowingCallable callback) { assertThatThrownBy(callback) .isInstanceOf(IllegalStateException.class) .hasMessage("Property sonar.core.id is missing in database"); } private void verifyDb(String expectedChecksum) { assertThat(dbClient.propertiesDao().selectGlobalProperty(dbSession, CoreProperties.SERVER_ID)) .extracting(PropertyDto::getValue) .isEqualTo(ServerIdManagerIT.WITH_DATABASE_ID_SERVER_ID.toString()); assertThat(dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.SERVER_ID_CHECKSUM)) .hasValue(expectedChecksum); } private void mockCreateNewServerId() { when(serverIdFactory.create()).thenReturn(WITH_DATABASE_ID_SERVER_ID); when(serverIdFactory.create(any())).thenThrow(new IllegalStateException("new ServerId should not be created from current server id")); } private void mockCreateNewServerIdFrom(ServerId currentServerId) { when(serverIdFactory.create()).thenThrow(new IllegalStateException("new ServerId should be created from current server id")); when(serverIdFactory.create(currentServerId)).thenReturn(ServerIdManagerIT.WITH_DATABASE_ID_SERVER_ID); } private void verifyCreateNewServerIdFromScratch() { verify(serverIdFactory).create(); } private void verifyCreateNewServerIdFrom(ServerId currentServerId) { verify(serverIdFactory).create(currentServerId); } private void mockChecksumOf(ServerId serverId, String checksum1) { when(serverIdChecksum.computeFor(serverId.toString())).thenReturn(checksum1); } private void insertServerId(ServerId serverId) { insertServerId(serverId.toString()); } private void insertServerId(String serverId) { dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto().setKey(CoreProperties.SERVER_ID).setValue(serverId), null, null, null, null); dbSession.commit(); } private void insertChecksum(String value) { dbClient.internalPropertiesDao().save(dbSession, InternalProperties.SERVER_ID_CHECKSUM, value); dbSession.commit(); } private void test(SonarQubeSide side) { underTest = new ServerIdManager(serverIdChecksum, serverIdFactory, dbClient, SonarRuntimeImpl .forSonarQube(Version.create(6, 7), side, SonarEdition.COMMUNITY), nodeInformation); underTest.start(); } }
10,225
33.901024
161
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/it/java/org/sonar/server/startup/RegisterMetricsIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.startup; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Random; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import org.sonar.api.measures.Metrics; import org.sonar.api.utils.System2; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.metric.MetricDto; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RegisterMetricsIT { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private final UuidFactory uuidFactory = new SequenceUuidFactory(); private final DbClient dbClient = dbTester.getDbClient(); private final RegisterMetrics register = new RegisterMetrics(dbClient, uuidFactory); /** * Insert new metrics, including custom metrics */ @Test public void insert_new_metrics() { Metric m1 = new Metric.Builder("m1", "One", Metric.ValueType.FLOAT) .setDescription("desc1") .setDirection(1) .setQualitative(true) .setDomain("domain1") .setUserManaged(false) .create(); Metric custom = new Metric.Builder("custom", "Custom", Metric.ValueType.FLOAT) .setDescription("This is a custom metric") .setUserManaged(true) .create(); register.register(asList(m1, custom)); Map<String, MetricDto> metricsByKey = selectAllMetrics(); assertThat(metricsByKey).hasSize(2); assertEquals(m1, metricsByKey.get("m1")); assertEquals(custom, metricsByKey.get("custom")); } /** * Update existing metrics */ @Test public void update_metrics() { dbTester.measures().insertMetric(t -> t.setKey("m1") .setShortName("name") .setValueType(Metric.ValueType.INT.name()) .setDescription("old desc") .setDomain("old domain") .setShortName("old short name") .setQualitative(false) .setEnabled(true) .setOptimizedBestValue(false) .setDirection(1) .setHidden(false)); Metric m1 = new Metric.Builder("m1", "New name", Metric.ValueType.FLOAT) .setDescription("new description") .setDirection(-1) .setQualitative(true) .setDomain("new domain") .setUserManaged(false) .setDecimalScale(3) .setHidden(true) .create(); register.register(asList(m1)); Map<String, MetricDto> metricsByKey = selectAllMetrics(); assertThat(metricsByKey).hasSize(1); assertEquals(m1, metricsByKey.get("m1")); } @Test public void disable_undefined_metrics() { Random random = new Random(); int count = 1 + random.nextInt(10); IntStream.range(0, count) .forEach(t -> dbTester.measures().insertMetric(m -> m.setEnabled(random.nextBoolean()))); register.register(Collections.emptyList()); assertThat(selectAllMetrics().values().stream()) .extracting(MetricDto::isEnabled) .containsOnly(IntStream.range(0, count).mapToObj(t -> false).toArray(Boolean[]::new)); } @Test public void enable_disabled_metrics() { MetricDto enabledMetric = dbTester.measures().insertMetric(t -> t.setEnabled(true)); MetricDto disabledMetric = dbTester.measures().insertMetric(t -> t.setEnabled(false)); register.register(asList(builderOf(enabledMetric).create(), builderOf(disabledMetric).create())); assertThat(selectAllMetrics().values()) .extracting(MetricDto::isEnabled) .containsOnly(true, true); } @Test public void insert_core_metrics() { register.start(); assertThat(dbTester.countRowsOfTable("metrics")).isEqualTo(CoreMetrics.getMetrics().size()); } @Test public void fail_if_duplicated_plugin_metrics() { Metrics plugin1 = new TestMetrics(new Metric.Builder("m1", "In first plugin", Metric.ValueType.FLOAT).create()); Metrics plugin2 = new TestMetrics(new Metric.Builder("m1", "In second plugin", Metric.ValueType.FLOAT).create()); assertThatThrownBy(() -> new RegisterMetrics(dbClient, uuidFactory, new Metrics[] {plugin1, plugin2}).start()) .isInstanceOf(IllegalStateException.class); } @Test public void fail_if_plugin_duplicates_core_metric() { Metrics plugin = new TestMetrics(new Metric.Builder("ncloc", "In plugin", Metric.ValueType.FLOAT).create()); assertThatThrownBy(() -> new RegisterMetrics(dbClient, uuidFactory, new Metrics[] {plugin}).start()) .isInstanceOf(IllegalStateException.class); } private static class TestMetrics implements Metrics { private final List<Metric> metrics; public TestMetrics(Metric... metrics) { this.metrics = asList(metrics); } @Override public List<Metric> getMetrics() { return metrics; } } private Map<String, MetricDto> selectAllMetrics() { return dbTester.getDbClient().metricDao().selectAll(dbTester.getSession()) .stream() .collect(Collectors.toMap(MetricDto::getKey, Function.identity())); } private void assertEquals(Metric expected, MetricDto actual) { assertThat(actual.getKey()).isEqualTo(expected.getKey()); assertThat(actual.getShortName()).isEqualTo(expected.getName()); assertThat(actual.getValueType()).isEqualTo(expected.getType().name()); assertThat(actual.getDescription()).isEqualTo(expected.getDescription()); assertThat(actual.getDirection()).isEqualTo(expected.getDirection()); assertThat(actual.isQualitative()).isEqualTo(expected.getQualitative()); } private static Metric.Builder builderOf(MetricDto enabledMetric) { return new Metric.Builder(enabledMetric.getKey(), enabledMetric.getShortName(), Metric.ValueType.valueOf(enabledMetric.getValueType())) .setDescription(enabledMetric.getDescription()) .setDirection(enabledMetric.getDirection()) .setQualitative(enabledMetric.isQualitative()) .setQualitative(enabledMetric.isQualitative()) .setDomain(enabledMetric.getDomain()) .setHidden(enabledMetric.isHidden()); } }
7,114
34.575
139
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/it/java/org/sonar/server/startup/RegisterPluginsIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.startup; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.utils.System2; import org.sonar.core.platform.PluginInfo; import org.sonar.core.plugin.PluginType; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.plugin.PluginDto; import org.sonar.db.plugin.PluginDto.Type; import org.sonar.server.plugins.PluginFilesAndMd5; import org.sonar.server.plugins.ServerPlugin; import org.sonar.server.plugins.ServerPluginRepository; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RegisterPluginsIT { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private final long now = 12345L; private final DbClient dbClient = dbTester.getDbClient(); private final ServerPluginRepository serverPluginRepository = new ServerPluginRepository(); private final UuidFactory uuidFactory = mock(UuidFactory.class); private final System2 system2 = mock(System2.class); private final RegisterPlugins register = new RegisterPlugins(serverPluginRepository, dbClient, uuidFactory, system2); @Before public void setUp() { when(system2.now()).thenReturn(now); } /** * Insert new plugins */ @Test public void insert_new_plugins() throws IOException { addPlugin("java", null); addPlugin("javacustom", "java"); when(uuidFactory.create()).thenReturn("a").thenReturn("b").thenThrow(new IllegalStateException("Should be called only twice")); register.start(); Map<String, PluginDto> pluginsByKey = selectAllPlugins(); assertThat(pluginsByKey).hasSize(2); verify(pluginsByKey.get("java"), Type.BUNDLED, null, "93f725a07423fe1c889f448b33d21f46", false, now, now); verify(pluginsByKey.get("javacustom"), Type.BUNDLED, "java", "bf8b3d4cb91efc5f9ef0bcd02f128ebf", false, now, now); register.stop(); } @Test public void update_removed_plugins() throws IOException { // will be flagged as removed dbClient.pluginDao().insert(dbTester.getSession(), new PluginDto() .setUuid("a") .setKee("java") .setBasePluginKey(null) .setFileHash("bd451e47a1aa76e73da0359cef63dd63") .setType(Type.BUNDLED) .setCreatedAt(1L) .setUpdatedAt(1L)); // already flagged as removed dbClient.pluginDao().insert(dbTester.getSession(), new PluginDto() .setUuid("b") .setKee("java2") .setBasePluginKey(null) .setFileHash("bd451e47a1aa76e73da0359cef63dd63") .setType(Type.BUNDLED) .setRemoved(true) .setCreatedAt(1L) .setUpdatedAt(1L)); dbClient.pluginDao().insert(dbTester.getSession(), new PluginDto() .setUuid("c") .setKee("csharp") .setBasePluginKey(null) .setFileHash("a20d785dbacb8f41a3b7392aa7d03b78") .setType(Type.EXTERNAL) .setCreatedAt(1L) .setUpdatedAt(1L)); dbTester.commit(); addPlugin("csharp", PluginType.EXTERNAL, null); register.start(); Map<String, PluginDto> pluginsByKey = selectAllPlugins(); assertThat(pluginsByKey).hasSize(3); verify(pluginsByKey.get("java"), Type.BUNDLED, null, "bd451e47a1aa76e73da0359cef63dd63", true, 1L, now); verify(pluginsByKey.get("java2"), Type.BUNDLED, null, "bd451e47a1aa76e73da0359cef63dd63", true, 1L, 1L); verify(pluginsByKey.get("csharp"), Type.EXTERNAL, null, "a20d785dbacb8f41a3b7392aa7d03b78", false, 1L, 1L); } @Test public void re_add_previously_removed_plugin() throws IOException { dbClient.pluginDao().insert(dbTester.getSession(), new PluginDto() .setUuid("c") .setKee("csharp") .setBasePluginKey(null) .setFileHash("a20d785dbacb8f41a3b7392aa7d03b78") .setType(Type.EXTERNAL) .setRemoved(true) .setCreatedAt(1L) .setUpdatedAt(1L)); dbTester.commit(); addPlugin("csharp", PluginType.EXTERNAL, null); register.start(); Map<String, PluginDto> pluginsByKey = selectAllPlugins(); assertThat(pluginsByKey).hasSize(1); verify(pluginsByKey.get("csharp"), Type.EXTERNAL, null, "a20d785dbacb8f41a3b7392aa7d03b78", false, 1L, now); } /** * Update existing plugins, only when checksum is different and don't remove uninstalled plugins */ @Test public void update_changed_plugins() throws IOException { dbClient.pluginDao().insert(dbTester.getSession(), new PluginDto() .setUuid("a") .setKee("java") .setBasePluginKey(null) .setFileHash("bd451e47a1aa76e73da0359cef63dd63") .setType(Type.BUNDLED) .setCreatedAt(1L) .setUpdatedAt(1L)); dbClient.pluginDao().insert(dbTester.getSession(), new PluginDto() .setUuid("b") .setKee("javacustom") .setBasePluginKey("java") .setFileHash("de9b2de3ddc0680904939686c0dba5be") .setType(Type.BUNDLED) .setCreatedAt(1L) .setUpdatedAt(1L)); dbClient.pluginDao().insert(dbTester.getSession(), new PluginDto() .setUuid("c") .setKee("csharp") .setBasePluginKey(null) .setFileHash("a20d785dbacb8f41a3b7392aa7d03b78") .setType(Type.EXTERNAL) .setCreatedAt(1L) .setUpdatedAt(1L)); dbClient.pluginDao().insert(dbTester.getSession(), new PluginDto() .setUuid("d") .setKee("new-measures") .setBasePluginKey(null) .setFileHash("6d24712cf701c41ce5eaa948e0bd6d22") .setType(Type.EXTERNAL) .setCreatedAt(1L) .setUpdatedAt(1L)); dbTester.commit(); addPlugin("javacustom", PluginType.BUNDLED, "java2"); // csharp plugin type changed addPlugin("csharp", PluginType.BUNDLED, null); register.start(); Map<String, PluginDto> pluginsByKey = selectAllPlugins(); assertThat(pluginsByKey).hasSize(4); verify(pluginsByKey.get("java"), Type.BUNDLED, null, "bd451e47a1aa76e73da0359cef63dd63", true, 1L, now); verify(pluginsByKey.get("javacustom"), Type.BUNDLED, "java2", "bf8b3d4cb91efc5f9ef0bcd02f128ebf", false, 1L, now); verify(pluginsByKey.get("csharp"), Type.BUNDLED, null, "a20d785dbacb8f41a3b7392aa7d03b78", false, 1L, now); verify(pluginsByKey.get("new-measures"), Type.EXTERNAL, null, "6d24712cf701c41ce5eaa948e0bd6d22", true, 1L, now); } private ServerPlugin addPlugin(String key, @Nullable String basePlugin) throws IOException { return addPlugin(key, PluginType.BUNDLED, basePlugin); } private ServerPlugin addPlugin(String key, PluginType type, @Nullable String basePlugin) throws IOException { File file = createPluginFile(key); PluginFilesAndMd5.FileAndMd5 jar = new PluginFilesAndMd5.FileAndMd5(file); PluginInfo info = new PluginInfo(key) .setBasePlugin(basePlugin) .setJarFile(file); ServerPlugin serverPlugin = new ServerPlugin(info, type, null, jar, null); serverPluginRepository.addPlugin(serverPlugin); return serverPlugin; } private File createPluginFile(String key) throws IOException { File pluginJar = temp.newFile(); FileUtils.write(pluginJar, key, StandardCharsets.UTF_8); return pluginJar; } private Map<String, PluginDto> selectAllPlugins() { return dbTester.getDbClient().pluginDao().selectAll(dbTester.getSession()).stream() .collect(Collectors.toMap(PluginDto::getKee, Function.identity())); } private void verify(PluginDto pluginDto, Type type, @Nullable String basePluginKey, String fileHash, boolean removed, @Nullable Long createdAt, long updatedAt) { assertThat(pluginDto.getBasePluginKey()).isEqualTo(basePluginKey); assertThat(pluginDto.getType()).isEqualTo(type); assertThat(pluginDto.getFileHash()).isEqualTo(fileHash); assertThat(pluginDto.isRemoved()).isEqualTo(removed); assertThat(pluginDto.getCreatedAt()).isEqualTo(createdAt); assertThat(pluginDto.getUpdatedAt()).isEqualTo(updatedAt); } }
9,106
36.945833
163
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/it/java/org/sonar/server/startup/UpgradeSuggestionsCleanerIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.startup; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.SonarEdition; import org.sonar.api.SonarRuntime; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskMessageDto; import org.sonar.db.ce.CeTaskMessageType; import org.sonar.db.user.UserDismissedMessageDto; import org.sonar.db.user.UserDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class UpgradeSuggestionsCleanerIT { private static final String TASK_UUID = "b8d564dd-4ceb-4dba-8a3d-5fafa2d72cdf"; @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private final SonarRuntime sonarRuntime = mock(SonarRuntime.class); private final UpgradeSuggestionsCleaner underTest = new UpgradeSuggestionsCleaner(dbTester.getDbClient(), sonarRuntime); private UserDto user; @Before public void setup() { user = dbTester.users().insertUser(); } @DataProvider public static Object[][] editionsWithCleanup() { return new Object[][] { {SonarEdition.DEVELOPER}, {SonarEdition.ENTERPRISE}, {SonarEdition.DATACENTER} }; } @DataProvider public static Object[][] allEditions() { return new Object[][] { {SonarEdition.COMMUNITY}, {SonarEdition.DEVELOPER}, {SonarEdition.ENTERPRISE}, {SonarEdition.DATACENTER} }; } @Test @UseDataProvider("editionsWithCleanup") public void start_cleans_up_obsolete_upgrade_suggestions(SonarEdition edition) { when(sonarRuntime.getEdition()).thenReturn(edition); insertTask(TASK_UUID); insertCeTaskMessage("ctm1", CeTaskMessageType.GENERIC, "msg1"); insertCeTaskMessage("ctm2", CeTaskMessageType.GENERIC, "msg2"); insertCeTaskMessage("ctm3", CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE, "upgrade-msg-1"); insertInUserDismissedMessages("u1", CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE); insertInUserDismissedMessages("u2", CeTaskMessageType.GENERIC); underTest.start(); underTest.stop(); assertThat(getTaskMessages(TASK_UUID)) .extracting(CeTaskMessageDto::getUuid) .containsExactly("ctm1", "ctm2"); assertThat(dbTester.getDbClient().userDismissedMessagesDao().selectByUser(dbTester.getSession(), user)) .extracting(UserDismissedMessageDto::getUuid) .containsExactly("u2"); } @Test public void start_does_nothing_in_community_edition() { when(sonarRuntime.getEdition()).thenReturn(SonarEdition.COMMUNITY); insertTask(TASK_UUID); insertCeTaskMessage("ctm1", CeTaskMessageType.GENERIC, "msg1"); insertCeTaskMessage("ctm2", CeTaskMessageType.GENERIC, "msg2"); insertCeTaskMessage("ctm3", CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE, "upgrade-msg-1"); insertInUserDismissedMessages("u1", CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE); insertInUserDismissedMessages("u2", CeTaskMessageType.GENERIC); underTest.start(); assertThat(getTaskMessages(TASK_UUID)) .extracting(CeTaskMessageDto::getUuid) .containsExactly("ctm1", "ctm2", "ctm3"); assertThat(dbTester.getDbClient().userDismissedMessagesDao().selectByUser(dbTester.getSession(), user)) .extracting(UserDismissedMessageDto::getUuid) .containsExactlyInAnyOrder("u1", "u2"); } @Test @UseDataProvider("allEditions") public void start_does_nothing_when_no_suggest_upgrade_messages(SonarEdition edition) { when(sonarRuntime.getEdition()).thenReturn(edition); underTest.start(); assertThat(getTaskMessages(TASK_UUID)).isEmpty(); assertThat(dbTester.getDbClient().userDismissedMessagesDao().selectByUser(dbTester.getSession(), user)).isEmpty(); } private List<CeTaskMessageDto> getTaskMessages(String taskUuid) { return dbTester.getDbClient().ceActivityDao().selectByUuid(dbTester.getSession(), taskUuid).map(CeActivityDto::getCeTaskMessageDtos).orElse(List.of()); } private void insertTask(String taskUuid) { dbTester.getDbClient().ceActivityDao().insert(dbTester.getSession(), new CeActivityDto(new CeQueueDto().setUuid(taskUuid).setTaskType("ISSUE_SYNC")).setStatus(CeActivityDto.Status.FAILED)); } private void insertCeTaskMessage(String uuid, CeTaskMessageType messageType, String msg) { CeTaskMessageDto dto = new CeTaskMessageDto() .setUuid(uuid) .setMessage(msg) .setType(messageType) .setTaskUuid(TASK_UUID); dbTester.getDbClient().ceTaskMessageDao().insert(dbTester.getSession(), dto); dbTester.getSession().commit(); } private void insertInUserDismissedMessages(String uuid, CeTaskMessageType messageType) { UserDismissedMessageDto dto = new UserDismissedMessageDto() .setUuid(uuid) .setUserUuid(user.getUuid()) .setProjectUuid("PROJECT_1") .setCeMessageType(messageType); dbTester.getDbClient().userDismissedMessagesDao().insert(dbTester.getSession(), dto); dbTester.getSession().commit(); } }
6,249
37.343558
155
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/it/java/org/sonar/server/webhook/WebhookQGChangeEventListenerIT.java
/* * SonarQube * Copyright (C) 2009-2023 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.webhook; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.function.Supplier; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.sonar.api.config.Configuration; import org.sonar.api.measures.Metric; import org.sonar.api.utils.System2; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.component.AnalysisPropertyDto; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.db.component.ProjectData; import org.sonar.db.component.SnapshotDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.qualitygate.EvaluatedQualityGate; import org.sonar.server.qualitygate.changeevent.QGChangeEvent; import org.sonar.server.qualitygate.changeevent.QGChangeEventListener; import static java.util.Arrays.stream; import static java.util.Collections.emptySet; import static java.util.stream.Stream.concat; import static java.util.stream.Stream.of; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.db.component.BranchType.BRANCH; @RunWith(DataProviderRunner.class) public class WebhookQGChangeEventListenerIT { private static final Set<QGChangeEventListener.ChangedIssue> CHANGED_ISSUES_ARE_IGNORED = emptySet(); @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private DbClient dbClient = dbTester.getDbClient(); private EvaluatedQualityGate newQualityGate = mock(EvaluatedQualityGate.class); private WebHooks webHooks = mock(WebHooks.class); private WebhookPayloadFactory webhookPayloadFactory = mock(WebhookPayloadFactory.class); private DbClient spiedOnDbClient = Mockito.spy(dbClient); private WebhookQGChangeEventListener underTest = new WebhookQGChangeEventListener(webHooks, webhookPayloadFactory, spiedOnDbClient); private DbClient mockedDbClient = mock(DbClient.class); private WebhookQGChangeEventListener mockedUnderTest = new WebhookQGChangeEventListener(webHooks, webhookPayloadFactory, mockedDbClient); @Test @UseDataProvider("allCombinationsOfStatuses") public void onIssueChanges_has_no_effect_if_no_webhook_is_configured(Metric.Level previousStatus, Metric.Level newStatus) { Configuration configuration1 = mock(Configuration.class); when(newQualityGate.getStatus()).thenReturn(newStatus); QGChangeEvent qualityGateEvent = newQGChangeEvent(configuration1, previousStatus, newQualityGate); mockWebhookDisabled(qualityGateEvent.getProject()); mockedUnderTest.onIssueChanges(qualityGateEvent, CHANGED_ISSUES_ARE_IGNORED); verify(webHooks).isEnabled(qualityGateEvent.getProject()); verifyNoInteractions(webhookPayloadFactory, mockedDbClient); } @DataProvider public static Object[][] allCombinationsOfStatuses() { Metric.Level[] levelsAndNull = concat(of((Metric.Level) null), stream(Metric.Level.values())) .toArray(Metric.Level[]::new); Object[][] res = new Object[levelsAndNull.length * levelsAndNull.length][2]; int i = 0; for (Metric.Level previousStatus : levelsAndNull) { for (Metric.Level newStatus : levelsAndNull) { res[i][0] = previousStatus; res[i][1] = newStatus; i++; } } return res; } @Test public void onIssueChanges_has_no_effect_if_event_has_neither_previousQGStatus_nor_qualityGate() { Configuration configuration = mock(Configuration.class); QGChangeEvent qualityGateEvent = newQGChangeEvent(configuration, null, null); mockWebhookEnabled(qualityGateEvent.getProject()); underTest.onIssueChanges(qualityGateEvent, CHANGED_ISSUES_ARE_IGNORED); verifyNoInteractions(webhookPayloadFactory, mockedDbClient); } @Test public void onIssueChanges_has_no_effect_if_event_has_same_status_in_previous_and_new_QG() { Configuration configuration = mock(Configuration.class); Metric.Level previousStatus = randomLevel(); when(newQualityGate.getStatus()).thenReturn(previousStatus); QGChangeEvent qualityGateEvent = newQGChangeEvent(configuration, previousStatus, newQualityGate); mockWebhookEnabled(qualityGateEvent.getProject()); underTest.onIssueChanges(qualityGateEvent, CHANGED_ISSUES_ARE_IGNORED); verifyNoInteractions(webhookPayloadFactory, mockedDbClient); } @Test @UseDataProvider("newQGorNot") public void onIssueChanges_calls_webhook_for_changeEvent_with_webhook_enabled(@Nullable EvaluatedQualityGate newQualityGate) { ProjectAndBranch projectBranch = insertBranch(BRANCH, "foo"); SnapshotDto analysis = insertAnalysisTask(projectBranch); Configuration configuration = mock(Configuration.class); mockPayloadSupplierConsumedByWebhooks(); Map<String, String> properties = new HashMap<>(); properties.put("sonar.analysis.test1", randomAlphanumeric(50)); properties.put("sonar.analysis.test2", randomAlphanumeric(5000)); insertPropertiesFor(analysis.getUuid(), properties); QGChangeEvent qualityGateEvent = newQGChangeEvent(projectBranch, analysis, configuration, newQualityGate); mockWebhookEnabled(qualityGateEvent.getProject()); underTest.onIssueChanges(qualityGateEvent, CHANGED_ISSUES_ARE_IGNORED); ProjectAnalysis projectAnalysis = verifyWebhookCalledAndExtractPayloadFactoryArgument(projectBranch, analysis, qualityGateEvent.getProject()); assertThat(projectAnalysis).isEqualTo( new ProjectAnalysis( new Project(projectBranch.project.getUuid(), projectBranch.project.getKey(), projectBranch.project.getName()), null, new Analysis(analysis.getUuid(), analysis.getCreatedAt(), analysis.getRevision()), new Branch(false, "foo", Branch.Type.BRANCH), newQualityGate, null, properties)); } @Test @UseDataProvider("newQGorNot") public void onIssueChanges_calls_webhook_on_main_branch(@Nullable EvaluatedQualityGate newQualityGate) { ProjectAndBranch mainBranch = insertMainBranch(); SnapshotDto analysis = insertAnalysisTask(mainBranch); Configuration configuration = mock(Configuration.class); QGChangeEvent qualityGateEvent = newQGChangeEvent(mainBranch, analysis, configuration, newQualityGate); mockWebhookEnabled(qualityGateEvent.getProject()); underTest.onIssueChanges(qualityGateEvent, CHANGED_ISSUES_ARE_IGNORED); verifyWebhookCalled(mainBranch, analysis, qualityGateEvent.getProject()); } @Test public void onIssueChanges_calls_webhook_on_branch() { onIssueChangesCallsWebhookOnBranch(BRANCH); } @Test public void onIssueChanges_calls_webhook_on_pr() { onIssueChangesCallsWebhookOnBranch(BranchType.PULL_REQUEST); } public void onIssueChangesCallsWebhookOnBranch(BranchType branchType) { ProjectAndBranch nonMainBranch = insertBranch(branchType, "foo"); SnapshotDto analysis = insertAnalysisTask(nonMainBranch); Configuration configuration = mock(Configuration.class); QGChangeEvent qualityGateEvent = newQGChangeEvent(nonMainBranch, analysis, configuration, null); mockWebhookEnabled(qualityGateEvent.getProject()); underTest.onIssueChanges(qualityGateEvent, CHANGED_ISSUES_ARE_IGNORED); verifyWebhookCalled(nonMainBranch, analysis, qualityGateEvent.getProject()); } @DataProvider public static Object[][] newQGorNot() { EvaluatedQualityGate newQualityGate = mock(EvaluatedQualityGate.class); return new Object[][] { {null}, {newQualityGate} }; } private void mockWebhookEnabled(ProjectDto... projects) { for (ProjectDto dto : projects) { when(webHooks.isEnabled(dto)).thenReturn(true); } } private void mockWebhookDisabled(ProjectDto... projects) { for (ProjectDto dto : projects) { when(webHooks.isEnabled(dto)).thenReturn(false); } } private void mockPayloadSupplierConsumedByWebhooks() { Mockito.doAnswer(invocationOnMock -> { Supplier<WebhookPayload> supplier = (Supplier<WebhookPayload>) invocationOnMock.getArguments()[1]; supplier.get(); return null; }).when(webHooks) .sendProjectAnalysisUpdate(any(), any()); } private void insertPropertiesFor(String snapshotUuid, Map<String, String> properties) { List<AnalysisPropertyDto> analysisProperties = properties.entrySet().stream() .map(entry -> new AnalysisPropertyDto() .setUuid(UuidFactoryFast.getInstance().create()) .setAnalysisUuid(snapshotUuid) .setKey(entry.getKey()) .setValue(entry.getValue())) .toList(); dbTester.getDbClient().analysisPropertiesDao().insert(dbTester.getSession(), analysisProperties); dbTester.getSession().commit(); } private SnapshotDto insertAnalysisTask(ProjectAndBranch projectAndBranch) { return dbTester.components().insertSnapshot(projectAndBranch.getBranch()); } private ProjectAnalysis verifyWebhookCalledAndExtractPayloadFactoryArgument(ProjectAndBranch projectAndBranch, SnapshotDto analysis, ProjectDto project) { verifyWebhookCalled(projectAndBranch, analysis, project); return extractPayloadFactoryArguments(1).iterator().next(); } private void verifyWebhookCalled(ProjectAndBranch projectAndBranch, SnapshotDto analysis, ProjectDto project) { verify(webHooks).isEnabled(project); verify(webHooks).sendProjectAnalysisUpdate( eq(new WebHooks.Analysis(projectAndBranch.uuid(), analysis.getUuid(), null)), any()); } private List<ProjectAnalysis> extractPayloadFactoryArguments(int time) { ArgumentCaptor<ProjectAnalysis> projectAnalysisCaptor = ArgumentCaptor.forClass(ProjectAnalysis.class); verify(webhookPayloadFactory, Mockito.times(time)).create(projectAnalysisCaptor.capture()); return projectAnalysisCaptor.getAllValues(); } public ProjectAndBranch insertMainBranch() { ProjectData project = dbTester.components().insertPrivateProject(); return new ProjectAndBranch(project.getProjectDto(), project.getMainBranchDto()); } public ProjectAndBranch insertBranch(BranchType type, String branchKey) { ProjectDto project = dbTester.components().insertPrivateProject().getProjectDto(); BranchDto branch = dbTester.components().insertProjectBranch(project, b -> b.setKey(branchKey).setBranchType(type)); return new ProjectAndBranch(project, branch); } public ProjectAndBranch insertBranch(ProjectDto project, BranchType type, String branchKey) { BranchDto branch = dbTester.components().insertProjectBranch(project, b -> b.setKey(branchKey).setBranchType(type)); return new ProjectAndBranch(project, branch); } private static class ProjectAndBranch { private final ProjectDto project; private final BranchDto branch; private ProjectAndBranch(ProjectDto project, BranchDto branch) { this.project = project; this.branch = branch; } public ProjectDto getProject() { return project; } public BranchDto getBranch() { return branch; } public String uuid() { return project.getUuid(); } } private static QGChangeEvent newQGChangeEvent(Configuration configuration, @Nullable Metric.Level previousQQStatus, @Nullable EvaluatedQualityGate evaluatedQualityGate) { return new QGChangeEvent(new ProjectDto(), new BranchDto(), new SnapshotDto(), configuration, previousQQStatus, () -> Optional.ofNullable(evaluatedQualityGate)); } private static QGChangeEvent newQGChangeEvent(ProjectAndBranch branch, SnapshotDto analysis, Configuration configuration, @Nullable EvaluatedQualityGate evaluatedQualityGate) { Metric.Level previousStatus = randomLevel(); if (evaluatedQualityGate != null) { Metric.Level otherLevel = stream(Metric.Level.values()) .filter(s -> s != previousStatus) .toArray(Metric.Level[]::new)[new Random().nextInt(Metric.Level.values().length - 1)]; when(evaluatedQualityGate.getStatus()).thenReturn(otherLevel); } return new QGChangeEvent(branch.project, branch.branch, analysis, configuration, previousStatus, () -> Optional.ofNullable(evaluatedQualityGate)); } private static Metric.Level randomLevel() { return Metric.Level.values()[new Random().nextInt(Metric.Level.values().length)]; } }
13,791
41.04878
178
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/app/WebServerProcessLogging.java
/* * SonarQube * Copyright (C) 2009-2023 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.app; import ch.qos.logback.classic.Level; import org.sonar.process.ProcessId; import org.sonar.process.logging.LogDomain; import org.sonar.process.logging.LogLevelConfig; import org.sonar.server.log.ServerProcessLogging; import static org.sonar.server.platform.web.requestid.RequestIdMDCStorage.HTTP_REQUEST_ID_MDC_KEY; /** * Configure logback for the Web Server process. Logs are written to file "web.log" in SQ's log directory. */ public class WebServerProcessLogging extends ServerProcessLogging { public WebServerProcessLogging() { super(ProcessId.WEB_SERVER, "%X{" + HTTP_REQUEST_ID_MDC_KEY + "}"); } @Override protected void extendLogLevelConfiguration(LogLevelConfig.Builder logLevelConfigBuilder) { logLevelConfigBuilder.levelByDomain("sql", ProcessId.WEB_SERVER, LogDomain.SQL); logLevelConfigBuilder.levelByDomain("es", ProcessId.WEB_SERVER, LogDomain.ES); logLevelConfigBuilder.levelByDomain("auth.event", ProcessId.WEB_SERVER, LogDomain.AUTH_EVENT); JMX_RMI_LOGGER_NAMES.forEach(loggerName -> logLevelConfigBuilder.levelByDomain(loggerName, ProcessId.WEB_SERVER, LogDomain.JMX)); logLevelConfigBuilder.offUnlessTrace("org.apache.catalina.core.ContainerBase"); logLevelConfigBuilder.offUnlessTrace("org.apache.catalina.core.StandardContext"); logLevelConfigBuilder.offUnlessTrace("org.apache.catalina.core.StandardService"); LOGGER_NAMES_TO_TURN_OFF.forEach(loggerName -> logLevelConfigBuilder.immutableLevel(loggerName, Level.OFF)); } @Override protected void extendConfigure() { // No extension needed } }
2,453
41.310345
133
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/app/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.app; import javax.annotation.ParametersAreNonnullByDefault;
960
39.041667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/ce/CeModule.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce; import org.sonar.ce.queue.CeQueueImpl; import org.sonar.ce.task.log.CeTaskLogging; import org.sonar.core.platform.Module; import org.sonar.server.ce.http.CeHttpClientImpl; public class CeModule extends Module { @Override protected void configureModule() { add(CeTaskLogging.class, CeHttpClientImpl.class, // Queue CeQueueImpl.class); } }
1,241
32.567568
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/ce/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce; import javax.annotation.ParametersAreNonnullByDefault;
959
39
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/ce/http/CeHttpClientImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.http; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Optional; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import org.apache.commons.io.IOUtils; import org.sonar.api.config.Configuration; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static java.util.Objects.requireNonNull; import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH; import static org.sonar.process.ProcessId.COMPUTE_ENGINE; /** * Client for the HTTP server of the Compute Engine. */ public class CeHttpClientImpl implements CeHttpClient { private static final String PATH_CHANGE_LOG_LEVEL = "changeLogLevel"; private static final String PATH_SYSTEM_INFO = "systemInfo"; private final File ipcSharedDir; public CeHttpClientImpl(Configuration config) { this.ipcSharedDir = new File(config.get(PROPERTY_SHARED_PATH).get()); } /** * Connects to the specified JVM process and requests system information. * * @return the system info, or absent if the process is not up or if its HTTP URL * is not registered into IPC. */ @Override public Optional<ProtobufSystemInfo.SystemInfo> retrieveSystemInfo() { return call(SystemInfoActionClient.INSTANCE); } private enum SystemInfoActionClient implements ActionClient<Optional<ProtobufSystemInfo.SystemInfo>> { INSTANCE; @Override public String getPath() { return PATH_SYSTEM_INFO; } @Override public Optional<ProtobufSystemInfo.SystemInfo> getDefault() { return Optional.empty(); } @Override public Optional<ProtobufSystemInfo.SystemInfo> call(String url) throws Exception { byte[] protobuf = IOUtils.toByteArray(new URI(url)); return Optional.of(ProtobufSystemInfo.SystemInfo.parseFrom(protobuf)); } } @Override public void changeLogLevel(LoggerLevel level) { requireNonNull(level, "level can't be null"); call(new ChangeLogLevelActionClient(level)); } private static final class ChangeLogLevelActionClient implements ActionClient<Void> { private final LoggerLevel newLogLevel; private ChangeLogLevelActionClient(LoggerLevel newLogLevel) { this.newLogLevel = newLogLevel; } @Override public String getPath() { return PATH_CHANGE_LOG_LEVEL; } @Override public Void getDefault() { return null; } @Override public Void call(String url) throws Exception { okhttp3.Request request = new okhttp3.Request.Builder() .post(RequestBody.create(null, new byte[0])) .url(url + "?level=" + newLogLevel.name()) .build(); try (okhttp3.Response response = new OkHttpClient().newCall(request).execute()) { if (response.code() != 200) { throw new IOException( String.format( "Failed to change log level in Compute Engine. Code was '%s' and response was '%s' for url '%s'", response.code(), response.body().string(), url)); } return null; } } } private <T> T call(ActionClient<T> actionClient) { try (DefaultProcessCommands commands = DefaultProcessCommands.secondary(ipcSharedDir, COMPUTE_ENGINE.getIpcIndex())) { if (commands.isUp()) { return actionClient.call(commands.getHttpUrl() + "/" + actionClient.getPath()); } return actionClient.getDefault(); } catch (Exception e) { throw new IllegalStateException("Failed to call HTTP server of process " + COMPUTE_ENGINE, e); } } private interface ActionClient<T> { /** * Path of the action. */ String getPath(); /** * Value to return when the Compute Engine is not ready. */ T getDefault(); /** * Delegates to perform the call to the Compute Engine's specified absolute URL. */ T call(String url) throws Exception; } }
4,892
30.772727
122
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/ce/http/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.ce.http; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/es/IndexerStartupTask.java
/* * SonarQube * Copyright (C) 2009-2023 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.es; import java.util.Set; import java.util.stream.Collectors; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.sonar.api.config.Configuration; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.server.es.metadata.MetadataIndex; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toSet; public class IndexerStartupTask { private static final Logger LOG = Loggers.get(IndexerStartupTask.class); private final EsClient esClient; private final Configuration config; private final MetadataIndex metadataIndex; private final StartupIndexer[] indexers; public IndexerStartupTask(EsClient esClient, Configuration config, MetadataIndex metadataIndex, StartupIndexer... indexers) { this.esClient = esClient; this.config = config; this.metadataIndex = metadataIndex; this.indexers = indexers; } public void execute() { if (indexesAreEnabled()) { stream(indexers) .forEach(this::indexUninitializedTypes); } } private boolean indexesAreEnabled() { return !config.getBoolean("sonar.internal.es.disableIndexes").orElse(false); } private void indexUninitializedTypes(StartupIndexer indexer) { Set<IndexType> uninitializedTypes = getUninitializedTypes(indexer); if (!uninitializedTypes.isEmpty()) { Profiler profiler = Profiler.create(LOG); StartupIndexer.Type type = indexer.getType(); switch (type) { case SYNCHRONOUS: synchronousIndexing(indexer, uninitializedTypes, profiler); break; case ASYNCHRONOUS: asynchronousIndexing(indexer, uninitializedTypes, profiler); break; default: throw new IllegalArgumentException("Unsupported StartupIndexer type:" + type); } } } private void synchronousIndexing(StartupIndexer indexer, Set<IndexType> uninitializedTypes, Profiler profiler) { String logMessage = getSynchronousIndexingLogMessage(uninitializedTypes); profiler.startInfo(logMessage + "..."); indexer.indexOnStartup(uninitializedTypes); uninitializedTypes.forEach(this::setInitialized); profiler.stopInfo(logMessage + " done"); } private void asynchronousIndexing(StartupIndexer indexer, Set<IndexType> uninitializedTypes, Profiler profiler) { String logMessage = getAsynchronousIndexingLogMessage(uninitializedTypes); profiler.startInfo(logMessage + "..."); indexer.triggerAsyncIndexOnStartup(uninitializedTypes); uninitializedTypes.forEach(this::setInitialized); profiler.stopInfo(logMessage + " done"); } private Set<IndexType> getUninitializedTypes(StartupIndexer indexer) { return indexer.getIndexTypes().stream() .filter(indexType -> !metadataIndex.getInitialized(indexType)) .collect(toSet()); } private void setInitialized(IndexType indexType) { waitForIndexYellow(indexType.getMainType().getIndex().getName()); metadataIndex.setInitialized(indexType, true); } private void waitForIndexYellow(String index) { esClient.clusterHealth(new ClusterHealthRequest() .indices(index) .waitForYellowStatus()); } private static String getSynchronousIndexingLogMessage(Set<IndexType> emptyTypes) { String s = emptyTypes.size() == 1 ? "" : "s"; String typeList = emptyTypes.stream().map(Object::toString).collect(Collectors.joining(",")); return String.format("Indexing of type%s %s", s, typeList); } private static String getAsynchronousIndexingLogMessage(Set<IndexType> emptyTypes) { String s = emptyTypes.size() == 1 ? "" : "s"; String typeList = emptyTypes.stream().map(Object::toString).collect(Collectors.joining(",")); return String.format("Trigger asynchronous indexing of type%s %s", s, typeList); } }
4,741
36.634921
127
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/es/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.es; import javax.annotation.ParametersAreNonnullByDefault;
960
37.44
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/issue/index/AsyncIssueIndexingImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.issue.index; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.ce.queue.CeQueue; import org.sonar.ce.queue.CeTaskSubmit; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.db.component.SnapshotDto; import static java.util.stream.Collectors.toCollection; import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_KEY; import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_TYPE_KEY; import static org.sonar.db.ce.CeTaskCharacteristicDto.PULL_REQUEST; import static org.sonar.db.ce.CeTaskTypes.BRANCH_ISSUE_SYNC; public class AsyncIssueIndexingImpl implements AsyncIssueIndexing { private static final Logger LOG = LoggerFactory.getLogger(AsyncIssueIndexingImpl.class); private final CeQueue ceQueue; private final DbClient dbClient; public AsyncIssueIndexingImpl(CeQueue ceQueue, DbClient dbClient) { this.ceQueue = ceQueue; this.dbClient = dbClient; } @Override public void triggerOnIndexCreation() { try (DbSession dbSession = dbClient.openSession(false)) { // remove already existing indexation task, if any removeExistingIndexationTasks(dbSession); dbClient.branchDao().updateAllNeedIssueSync(dbSession); List<BranchDto> branchInNeedOfIssueSync = dbClient.branchDao().selectBranchNeedingIssueSync(dbSession); LOG.info("{} branch found in need of issue sync.", branchInNeedOfIssueSync.size()); if (branchInNeedOfIssueSync.isEmpty()) { return; } List<String> projectUuids = branchInNeedOfIssueSync.stream().map(BranchDto::getProjectUuid).distinct().collect(toCollection(ArrayList<String>::new)); LOG.info("{} projects found in need of issue sync.", projectUuids.size()); sortProjectUuids(dbSession, projectUuids); Map<String, List<BranchDto>> branchesByProject = branchInNeedOfIssueSync.stream() .collect(Collectors.groupingBy(BranchDto::getProjectUuid)); List<CeTaskSubmit> tasks = new ArrayList<>(); for (String projectUuid : projectUuids) { List<BranchDto> branches = branchesByProject.get(projectUuid); for (BranchDto branch : branches) { tasks.add(buildTaskSubmit(branch)); } } ceQueue.massSubmit(tasks); dbSession.commit(); } } @Override public void triggerForProject(String projectUuid) { try (DbSession dbSession = dbClient.openSession(false)) { // remove already existing indexation task, if any removeExistingIndexationTasksForProject(dbSession, projectUuid); dbClient.branchDao().updateAllNeedIssueSyncForProject(dbSession, projectUuid); List<BranchDto> branchInNeedOfIssueSync = dbClient.branchDao().selectBranchNeedingIssueSyncForProject(dbSession, projectUuid); LOG.info("{} branch(es) found in need of issue sync for project.", branchInNeedOfIssueSync.size()); List<CeTaskSubmit> tasks = new ArrayList<>(); for (BranchDto branch : branchInNeedOfIssueSync) { tasks.add(buildTaskSubmit(branch)); } ceQueue.massSubmit(tasks); dbSession.commit(); } } private void sortProjectUuids(DbSession dbSession, List<String> projectUuids) { Map<String, SnapshotDto> snapshotByProjectUuid = dbClient.snapshotDao() .selectLastAnalysesByRootComponentUuids(dbSession, projectUuids).stream() .collect(Collectors.toMap(SnapshotDto::getRootComponentUuid, Function.identity())); projectUuids.sort(compareBySnapshot(snapshotByProjectUuid)); } static Comparator<String> compareBySnapshot(Map<String, SnapshotDto> snapshotByProjectUuid) { return (uuid1, uuid2) -> { SnapshotDto snapshot1 = snapshotByProjectUuid.get(uuid1); SnapshotDto snapshot2 = snapshotByProjectUuid.get(uuid2); if (snapshot1 == null && snapshot2 == null) { return 0; } if (snapshot1 == null) { return 1; } if (snapshot2 == null) { return -1; } return snapshot2.getCreatedAt().compareTo(snapshot1.getCreatedAt()); }; } private void removeExistingIndexationTasks(DbSession dbSession) { Set<String> ceQueueUuids = dbClient.ceQueueDao().selectAllInAscOrder(dbSession) .stream().filter(p -> p.getTaskType().equals(BRANCH_ISSUE_SYNC)) .map(CeQueueDto::getUuid).collect(Collectors.toSet()); Set<String> ceActivityUuids = dbClient.ceActivityDao().selectByTaskType(dbSession, BRANCH_ISSUE_SYNC) .stream().map(CeActivityDto::getUuid).collect(Collectors.toSet()); removeIndexationTasks(dbSession, ceQueueUuids, ceActivityUuids); } private void removeExistingIndexationTasksForProject(DbSession dbSession, String projectUuid) { Set<String> ceQueueUuidsForProject = dbClient.ceQueueDao().selectByEntityUuid(dbSession, projectUuid) .stream().filter(p -> p.getTaskType().equals(BRANCH_ISSUE_SYNC)) .map(CeQueueDto::getUuid).collect(Collectors.toSet()); Set<String> ceActivityUuidsForProject = dbClient.ceActivityDao().selectByTaskType(dbSession, BRANCH_ISSUE_SYNC) .stream() .filter(ceActivityDto -> projectUuid.equals(ceActivityDto.getEntityUuid())) .map(CeActivityDto::getUuid).collect(Collectors.toSet()); removeIndexationTasks(dbSession, ceQueueUuidsForProject, ceActivityUuidsForProject); } private void removeIndexationTasks(DbSession dbSession, Set<String> ceQueueUuids, Set<String> ceActivityUuids) { LOG.info(String.format("%s pending indexation task found to be deleted...", ceQueueUuids.size())); for (String uuid : ceQueueUuids) { dbClient.ceQueueDao().deleteByUuid(dbSession, uuid); } LOG.info(String.format("%s completed indexation task found to be deleted...", ceQueueUuids.size())); dbClient.ceActivityDao().deleteByUuids(dbSession, ceActivityUuids); LOG.info("Indexation task deletion complete."); LOG.info("Deleting tasks characteristics..."); Set<String> tasksUuid = Stream.concat(ceQueueUuids.stream(), ceActivityUuids.stream()).collect(Collectors.toSet()); dbClient.ceTaskCharacteristicsDao().deleteByTaskUuids(dbSession, tasksUuid); LOG.info("Tasks characteristics deletion complete."); dbSession.commit(); } private CeTaskSubmit buildTaskSubmit(BranchDto branch) { Map<String, String> characteristics = new HashMap<>(); characteristics.put(branch.getBranchType() == BranchType.BRANCH ? BRANCH_KEY : PULL_REQUEST, branch.getKey()); characteristics.put(BRANCH_TYPE_KEY, branch.getBranchType().name()); return ceQueue.prepareSubmit() .setType(BRANCH_ISSUE_SYNC) .setComponent(new CeTaskSubmit.Component(branch.getUuid(), branch.getProjectUuid())) .setCharacteristics(characteristics).build(); } }
7,980
40.352332
155
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/issue/index/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.issue.index; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/notification/NotificationDaemon.java
/* * SonarQube * Copyright (C) 2009-2023 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.notification; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.sonar.api.Startable; import org.sonar.api.Properties; import org.sonar.api.Property; import org.sonar.api.config.Configuration; import org.sonar.api.notifications.Notification; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.Collections.singleton; @Properties({ @Property( key = NotificationDaemon.PROPERTY_DELAY, defaultValue = "60", name = "Delay of notifications, in seconds", global = false), @Property( key = NotificationDaemon.PROPERTY_DELAY_BEFORE_REPORTING_STATUS, defaultValue = "600", name = "Delay before reporting notification status, in seconds", global = false) }) @ServerSide public class NotificationDaemon implements Startable { private static final String THREAD_NAME_PREFIX = "sq-notification-service-"; private static final Logger LOG = LoggerFactory.getLogger(NotificationDaemon.class); public static final String PROPERTY_DELAY = "sonar.notifications.delay"; public static final String PROPERTY_DELAY_BEFORE_REPORTING_STATUS = "sonar.notifications.runningDelayBeforeReportingStatus"; private final long delayInSeconds; private final long delayBeforeReportingStatusInSeconds; private final DefaultNotificationManager manager; private final NotificationService service; private ScheduledExecutorService executorService; private boolean stopping = false; public NotificationDaemon(Configuration config, DefaultNotificationManager manager, NotificationService service) { this.delayInSeconds = config.getLong(PROPERTY_DELAY).get(); this.delayBeforeReportingStatusInSeconds = config.getLong(PROPERTY_DELAY_BEFORE_REPORTING_STATUS).get(); this.manager = manager; this.service = service; } @Override public void start() { executorService = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat(THREAD_NAME_PREFIX + "%d") .setPriority(Thread.MIN_PRIORITY) .build()); executorService.scheduleWithFixedDelay(() -> { try { processQueue(); } catch (Exception e) { LOG.error("Error in NotificationService", e); } }, 0, delayInSeconds, TimeUnit.SECONDS); LOG.info("Notification service started (delay {} sec.)", delayInSeconds); } @Override public void stop() { try { stopping = true; executorService.shutdown(); executorService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.error("Error during stop of notification service", e); Thread.currentThread().interrupt(); } LOG.info("Notification service stopped"); } private synchronized void processQueue() { long start = now(); long lastLog = start; long notifSentCount = 0; Notification notifToSend = manager.getFromQueue(); while (notifToSend != null) { notifSentCount += service.deliverEmails(singleton(notifToSend)); // compatibility with old API notifSentCount += service.deliver(notifToSend); if (stopping) { break; } long now = now(); if (now - lastLog > delayBeforeReportingStatusInSeconds * 1000) { long remainingNotifCount = manager.count(); lastLog = now; long spentTimeInMinutes = (now - start) / (60 * 1000); log(notifSentCount, remainingNotifCount, spentTimeInMinutes); } notifToSend = manager.getFromQueue(); } } @VisibleForTesting void log(long notifSentCount, long remainingNotifCount, long spentTimeInMinutes) { LOG.info("{} notifications sent during the past {} minutes and {} still waiting to be sent", notifSentCount, spentTimeInMinutes, remainingNotifCount); } @VisibleForTesting long now() { return System.currentTimeMillis(); } }
4,964
34.719424
126
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/notification/NotificationModule.java
/* * SonarQube * Copyright (C) 2009-2023 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.notification; import org.sonar.api.config.EmailSettings; import org.sonar.core.platform.Module; import org.sonar.server.notification.email.EmailNotificationChannel; public class NotificationModule extends Module { @Override protected void configureModule() { add( EmailSettings.class, NotificationService.class, DefaultNotificationManager.class, NotificationDaemon.class, EmailNotificationChannel.class); } }
1,319
34.675676
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/notification/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.notification; import javax.annotation.ParametersAreNonnullByDefault;
969
39.416667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/AbstractSystemInfoWriter.java
/* * SonarQube * Copyright (C) 2009-2023 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.Collection; import org.sonar.api.utils.text.JsonWriter; import org.sonar.process.systeminfo.SystemInfoUtils; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.health.Health; public abstract class AbstractSystemInfoWriter implements SystemInfoWriter { private static final String[] ORDERED_SECTION_NAMES = { // standalone "System", "Statistics", "Database", "Bundled", "Plugins", // cluster "Web JVM State", "Web Database Connection", "Web Logging", "Web JVM Properties", "Compute Engine Tasks", "Compute Engine JVM State", "Compute Engine Database Connection", "Compute Engine Logging", "Compute Engine JVM Properties", "Search State", "Search Indexes"}; protected void writeSections(Collection<ProtobufSystemInfo.Section> sections, JsonWriter json) { SystemInfoUtils .order(sections, ORDERED_SECTION_NAMES) .forEach(section -> writeSection(section, json)); } private static void writeSection(ProtobufSystemInfo.Section section, JsonWriter json) { json.name(section.getName()); json.beginObject(); for (ProtobufSystemInfo.Attribute attribute : section.getAttributesList()) { writeAttribute(attribute, json); } json.endObject(); } private static void writeAttribute(ProtobufSystemInfo.Attribute attribute, JsonWriter json) { switch (attribute.getValueCase()) { case BOOLEAN_VALUE: json.prop(attribute.getKey(), attribute.getBooleanValue()); break; case LONG_VALUE: json.prop(attribute.getKey(), attribute.getLongValue()); break; case DOUBLE_VALUE: json.prop(attribute.getKey(), attribute.getDoubleValue()); break; case STRING_VALUE: json.prop(attribute.getKey(), attribute.getStringValue()); break; case VALUE_NOT_SET: json.name(attribute.getKey()).beginArray().values(attribute.getStringValuesList()).endArray(); break; default: throw new IllegalArgumentException("Unsupported type: " + attribute.getValueCase()); } } protected void writeHealth(Health health, JsonWriter json) { json.prop("Health", health.getStatus().name()); json.name("Health Causes").beginArray().values(health.getCauses()).endArray(); } }
3,176
38.222222
152
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/ClusterSystemInfoWriter.java
/* * SonarQube * Copyright (C) 2009-2023 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.Collection; import org.sonar.api.utils.text.JsonWriter; import org.sonar.server.health.ClusterHealth; import org.sonar.server.health.HealthChecker; import org.sonar.server.platform.monitoring.cluster.AppNodesInfoLoader; import org.sonar.server.platform.monitoring.cluster.GlobalInfoLoader; import org.sonar.server.platform.monitoring.cluster.NodeInfo; import org.sonar.server.platform.monitoring.cluster.SearchNodesInfoLoader; public class ClusterSystemInfoWriter extends AbstractSystemInfoWriter { private final GlobalInfoLoader globalInfoLoader; private final AppNodesInfoLoader appNodesInfoLoader; private final SearchNodesInfoLoader searchNodesInfoLoader; private final HealthChecker healthChecker; public ClusterSystemInfoWriter(GlobalInfoLoader globalInfoLoader, AppNodesInfoLoader appNodesInfoLoader, SearchNodesInfoLoader searchNodesInfoLoader, HealthChecker healthChecker) { this.globalInfoLoader = globalInfoLoader; this.appNodesInfoLoader = appNodesInfoLoader; this.searchNodesInfoLoader = searchNodesInfoLoader; this.healthChecker = healthChecker; } @Override public void write(JsonWriter json) throws InterruptedException { ClusterHealth clusterHealth = healthChecker.checkCluster(); writeHealth(clusterHealth.getHealth(), json); writeGlobalSections(json); writeApplicationNodes(json, clusterHealth); writeSearchNodes(json, clusterHealth); } private void writeGlobalSections(JsonWriter json) { writeSections(globalInfoLoader.load(), json); } private void writeApplicationNodes(JsonWriter json, ClusterHealth clusterHealth) throws InterruptedException { json.name("Application Nodes").beginArray(); Collection<NodeInfo> appNodes = appNodesInfoLoader.load(); for (NodeInfo applicationNode : appNodes) { writeNodeInfo(applicationNode, clusterHealth, json); } json.endArray(); } private void writeSearchNodes(JsonWriter json, ClusterHealth clusterHealth) { json.name("Search Nodes").beginArray(); Collection<NodeInfo> searchNodes = searchNodesInfoLoader.load(); searchNodes.forEach(node -> writeNodeInfo(node, clusterHealth, json)); json.endArray(); } private void writeNodeInfo(NodeInfo nodeInfo, ClusterHealth clusterHealth, JsonWriter json) { json.beginObject(); json.prop("Name", nodeInfo.getName()); json.prop("Error", nodeInfo.getErrorMessage().orElse(null)); json.prop("Host", nodeInfo.getHost().orElse(null)); json.prop("Started At", nodeInfo.getStartedAt().orElse(null)); clusterHealth.getNodeHealth(nodeInfo.getName()).ifPresent(h -> { json.prop("Health", h.getStatus().name()); json.name("Health Causes").beginArray().values(h.getCauses()).endArray(); }); writeSections(nodeInfo.getSections(), json); json.endObject(); } }
3,719
39
151
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/ClusterVerification.java
/* * SonarQube * Copyright (C) 2009-2023 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.Nullable; import javax.inject.Inject; import org.sonar.api.Startable; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.MessageException; @ServerSide public class ClusterVerification implements Startable { private final NodeInformation server; @Nullable private final ClusterFeature feature; @Inject public ClusterVerification(NodeInformation server, @Nullable ClusterFeature feature) { this.server = server; this.feature = feature; } public ClusterVerification(NodeInformation server) { this(server, null); } @Override public void start() { if (server.isStandalone()) { return; } if (feature == null || !feature.isEnabled()) { throw MessageException.of( "Cluster mode can't be enabled. Please install the Data Center Edition. More details at https://www.sonarsource.com/plans-and-pricing/data-center/."); } } @Override public void stop() { // nothing to do } }
1,868
29.639344
158
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/ContainerSupport.java
/* * SonarQube * Copyright (C) 2009-2023 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.CheckForNull; public interface ContainerSupport { /** * @return {@code true} if we can detect that SQ is running inside a docker container */ boolean isRunningInContainer(); @CheckForNull String getContainerContext(); }
1,140
32.558824
87
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/ContainerSupportImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.util.Objects; import java.util.Scanner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.utils.System2; import org.sonar.server.util.Paths2; import static java.nio.charset.StandardCharsets.UTF_8; public class ContainerSupportImpl implements ContainerSupport { private static final Logger LOG = LoggerFactory.getLogger(ContainerSupportImpl.class); private static final String CONTAINER_FILE_PATH = "/run/.containerenv"; private static final String DOCKER = "docker"; private static final String PODMAN = "podman"; private static final String BUILDAH = "buildah"; private static final String CONTAINER_D = "containerd"; private static final String GENERAL_CONTAINER = "general_container"; private static final String[] MOUNT_GREP_COMMAND = {"bash", "-c", "mount | grep 'overlay on /'"}; private static final String[] CAT_COMMAND = {"bash", "-c", "cat /run/.containerenv"}; private final System2 system2; private final Paths2 paths2; private String containerContextCache; public ContainerSupportImpl(Paths2 paths2, System2 system2) { this.paths2 = paths2; this.system2 = system2; populateCache(); } @VisibleForTesting void populateCache() { if (isDocker()) { containerContextCache = DOCKER; } else if (isPodman()) { containerContextCache = PODMAN; } else if (isBuildah()) { containerContextCache = BUILDAH; } else if (isContainerd()) { containerContextCache = CONTAINER_D; } else if (isGeneralContainer()) { containerContextCache = GENERAL_CONTAINER; } else { containerContextCache = null; } } @Override public boolean isRunningInContainer() { return containerContextCache != null; } @Override public String getContainerContext() { return containerContextCache; } private boolean isDocker() { return executeCommand(MOUNT_GREP_COMMAND).contains("/docker") && paths2.exists("/.dockerenv"); } private boolean isPodman() { return Objects.equals(system2.envVariable("container"), PODMAN) && paths2.exists(CONTAINER_FILE_PATH); } private boolean isBuildah() { return paths2.exists(CONTAINER_FILE_PATH) && executeCommand(CAT_COMMAND).contains("engine=\"buildah-"); } private boolean isContainerd() { return executeCommand(MOUNT_GREP_COMMAND).contains("/containerd"); } private boolean isGeneralContainer() { return paths2.exists(CONTAINER_FILE_PATH); } @VisibleForTesting String executeCommand(String[] command) { try { Process process = new ProcessBuilder().command(command).start(); try (Scanner scanner = new Scanner(process.getInputStream(), UTF_8)) { scanner.useDelimiter("\n"); return scanner.next(); } finally { process.destroy(); } } catch (Exception e) { LOG.debug("Failed to execute command", e); return ""; } } }
3,854
31.394958
107
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/DatabaseServerCompatibility.java
/* * SonarQube * Copyright (C) 2009-2023 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.Startable; import org.sonar.api.utils.MessageException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.server.platform.db.migration.version.DatabaseVersion; import static org.sonar.server.log.ServerProcessLogging.STARTUP_LOGGER_NAME; public class DatabaseServerCompatibility implements Startable { private static final String HIGHLIGHTER = "################################################################################"; private final DatabaseVersion version; public DatabaseServerCompatibility(DatabaseVersion version) { this.version = version; } @Override public void start() { DatabaseVersion.Status status = version.getStatus(); if (status == DatabaseVersion.Status.REQUIRES_DOWNGRADE) { throw MessageException.of("Database was upgraded to a more recent version of SonarQube. " + "A backup must probably be restored or the DB settings are incorrect."); } if (status == DatabaseVersion.Status.REQUIRES_UPGRADE) { Optional<Long> currentVersion = this.version.getVersion(); if (currentVersion.isPresent() && currentVersion.get() < DatabaseVersion.MIN_UPGRADE_VERSION) { throw MessageException.of("The version of SonarQube is too old. Please upgrade to the Long Term Support version first."); } String msg = "The database must be manually upgraded. Please backup the database and browse /setup. " + "For more information: https://docs.sonarqube.org/latest/setup/upgrading"; LoggerFactory.getLogger(DatabaseServerCompatibility.class).warn(msg); Logger logger = LoggerFactory.getLogger(STARTUP_LOGGER_NAME); logger.warn(HIGHLIGHTER); logger.warn(msg); logger.warn(HIGHLIGHTER); } } @Override public void stop() { // do nothing } }
2,726
38.521739
129
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/DefaultServerUpgradeStatus.java
/* * SonarQube * Copyright (C) 2009-2023 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.apache.commons.lang.builder.ReflectionToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.sonar.api.platform.ServerUpgradeStatus; import org.sonar.process.ProcessProperties; import org.sonar.server.platform.db.migration.step.MigrationSteps; import org.sonar.server.platform.db.migration.version.DatabaseVersion; public class DefaultServerUpgradeStatus implements ServerUpgradeStatus, Startable { private final DatabaseVersion dbVersion; private final MigrationSteps migrationSteps; private final Configuration configuration; // available when connected to db private long initialDbVersion; public DefaultServerUpgradeStatus(DatabaseVersion dbVersion, MigrationSteps migrationSteps, Configuration configuration) { this.dbVersion = dbVersion; this.migrationSteps = migrationSteps; this.configuration = configuration; } @Override public void start() { Optional<Long> v = dbVersion.getVersion(); this.initialDbVersion = v.orElse(-1L); } @Override public void stop() { // do nothing } @Override public boolean isUpgraded() { return !isFreshInstall() && (initialDbVersion < migrationSteps.getMaxMigrationNumber()); } @Override public boolean isFreshInstall() { return initialDbVersion < 0; } @Override public int getInitialDbVersion() { return (int) initialDbVersion; } public boolean isAutoDbUpgrade() { return configuration.getBoolean(ProcessProperties.Property.AUTO_DATABASE_UPGRADE.getKey()).orElse(false); } @Override public String toString() { return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).toString(); } }
2,668
31.54878
124
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/LogServerVersion.java
/* * SonarQube * Copyright (C) 2009-2023 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.base.Joiner; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.sonar.api.Startable; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.platform.SonarQubeVersion; @ServerSide public class LogServerVersion implements Startable { private static final Logger LOG = LoggerFactory.getLogger(LogServerVersion.class); private final SonarQubeVersion sonarQubeVersion; public LogServerVersion(SonarQubeVersion sonarQubeVersion) { this.sonarQubeVersion = sonarQubeVersion; } @Override public void start() { String scmRevision = read("/build.properties").getProperty("Implementation-Build"); Version version = sonarQubeVersion.get(); LOG.info("SonarQube {}", Joiner.on(" / ").skipNulls().join("Server", version, scmRevision)); } @Override public void stop() { // nothing to do } private static Properties read(String filePath) { try (InputStream stream = LogServerVersion.class.getResourceAsStream(filePath)) { Properties properties = new Properties(); properties.load(stream); return properties; } catch (IOException e) { throw new IllegalStateException("Fail to read file " + filePath + " from classpath", e); } } }
2,246
33.569231
96
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/PersistentSettings.java
/* * SonarQube * Copyright (C) 2009-2023 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.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.config.internal.Settings; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.PropertyDto; import org.sonar.server.setting.SettingsChangeNotifier; public class PersistentSettings { private final Settings delegate; private final DbClient dbClient; private final SettingsChangeNotifier changeNotifier; public PersistentSettings(Settings delegate, DbClient dbClient, SettingsChangeNotifier changeNotifier) { this.delegate = delegate; this.dbClient = dbClient; this.changeNotifier = changeNotifier; } @CheckForNull public String getString(String key) { return delegate.getString(key); } /** * Insert property into database if value is not {@code null}, else delete property from * database. Session is not committed but {@link org.sonar.api.config.GlobalPropertyChangeHandler} * are executed. */ public PersistentSettings saveProperty(DbSession dbSession, String key, @Nullable String value) { savePropertyImpl(dbSession, key, value); changeNotifier.onGlobalPropertyChange(key, value); return this; } /** * Same as {@link #saveProperty(DbSession, String, String)} but a new database session is * opened and committed. */ public PersistentSettings saveProperty(String key, @Nullable String value) { try (DbSession dbSession = dbClient.openSession(false)) { savePropertyImpl(dbSession, key, value); dbSession.commit(); changeNotifier.onGlobalPropertyChange(key, value); return this; } } private void savePropertyImpl(DbSession dbSession, String key, @Nullable String value) { if (value == null) { dbClient.propertiesDao().deleteGlobalProperty(key, dbSession); } else { dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto().setKey(key).setValue(value)); } // refresh the cache of settings delegate.setProperty(key, value); } public Settings getSettings() { return delegate; } }
2,955
33.776471
106
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/StandaloneSystemInfoWriter.java
/* * SonarQube * Copyright (C) 2009-2023 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.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.sonar.api.utils.text.JsonWriter; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.ce.http.CeHttpClient; import org.sonar.server.health.Health; import org.sonar.server.health.HealthChecker; import static java.util.Arrays.stream; public class StandaloneSystemInfoWriter extends AbstractSystemInfoWriter { private final CeHttpClient ceHttpClient; private final HealthChecker healthChecker; private final SystemInfoSection[] systemInfoSections; public StandaloneSystemInfoWriter(CeHttpClient ceHttpClient, HealthChecker healthChecker, SystemInfoSection... systemInfoSections) { this.ceHttpClient = ceHttpClient; this.healthChecker = healthChecker; this.systemInfoSections = systemInfoSections; } @Override public void write(JsonWriter json) { writeHealth(json); List<ProtobufSystemInfo.Section> sections = stream(systemInfoSections) .map(SystemInfoSection::toProtobuf) .collect(Collectors.toCollection(ArrayList::new)); ceHttpClient.retrieveSystemInfo() .ifPresent(ce -> sections.addAll(ce.getSectionsList())); writeSections(sections, json); } private void writeHealth(JsonWriter json) { Health health = healthChecker.checkNode(); writeHealth(health, json); } }
2,311
35.698413
134
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/StartupMetadataPersister.java
/* * SonarQube * Copyright (C) 2009-2023 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.Date; import org.sonar.api.CoreProperties; import org.sonar.api.Startable; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.DateUtils; import org.sonar.db.DbClient; import org.sonar.db.property.PropertyDto; /** * The server node marked as "startup leader" generates some information about startup. These * information are loaded by "startup follower" servers and all Compute Engine nodes. * * @see StartupMetadataProvider#load(DbClient) */ @ServerSide public class StartupMetadataPersister implements Startable { private final StartupMetadata metadata; // PersistentSettings can not be used as it has to be // instantiated in level 4 of container, whereas // StartupMetadataPersister is level 3. private final DbClient dbClient; public StartupMetadataPersister(StartupMetadata metadata, DbClient dbClient) { this.metadata = metadata; this.dbClient = dbClient; } @Override public void start() { String startedAt = DateUtils.formatDateTime(new Date(metadata.getStartedAt())); save(CoreProperties.SERVER_STARTTIME, startedAt); } private void save(String key, String value) { dbClient.propertiesDao().saveProperty(new PropertyDto().setKey(key).setValue(value)); } @Override public void stop() { // nothing to do } }
2,191
32.723077
93
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/StatisticsSupport.java
/* * SonarQube * Copyright (C) 2009-2023 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 org.sonar.db.DbClient; import org.sonar.db.DbSession; public class StatisticsSupport { private final DbClient dbClient; public StatisticsSupport(DbClient dbClient) { this.dbClient = dbClient; } public long getLinesOfCode(){ try (DbSession dbSession = dbClient.openSession(false)) { return dbClient.projectDao().getNclocSum(dbSession); } } }
1,259
31.307692
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/SystemInfoWriterModule.java
/* * SonarQube * Copyright (C) 2009-2023 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 org.sonar.core.platform.Module; import org.sonar.process.systeminfo.JvmPropertiesSection; import org.sonar.process.systeminfo.JvmStateSection; import org.sonar.server.platform.monitoring.AlmConfigurationSection; import org.sonar.server.platform.monitoring.BundledSection; import org.sonar.server.platform.monitoring.CommonSystemInformation; import org.sonar.server.platform.monitoring.DbConnectionSection; import org.sonar.server.platform.monitoring.DbSection; import org.sonar.server.platform.monitoring.EsIndexesSection; import org.sonar.server.platform.monitoring.EsStateSection; import org.sonar.server.platform.monitoring.LoggingSection; import org.sonar.server.platform.monitoring.PluginsSection; import org.sonar.server.platform.monitoring.SettingsSection; import org.sonar.server.platform.monitoring.StandaloneSystemSection; import org.sonar.server.platform.monitoring.cluster.AppNodesInfoLoaderImpl; import org.sonar.server.platform.monitoring.cluster.CeQueueGlobalSection; import org.sonar.server.platform.monitoring.cluster.EsClusterStateSection; import org.sonar.server.platform.monitoring.cluster.GlobalInfoLoader; import org.sonar.server.platform.monitoring.cluster.GlobalSystemSection; import org.sonar.server.platform.monitoring.cluster.NodeSystemSection; import org.sonar.server.platform.monitoring.cluster.ProcessInfoProvider; import org.sonar.server.platform.monitoring.cluster.SearchNodesInfoLoaderImpl; import org.sonar.server.platform.monitoring.cluster.ServerPushSection; public class SystemInfoWriterModule extends Module { private final NodeInformation nodeInformation; public SystemInfoWriterModule(NodeInformation nodeInformation) { this.nodeInformation = nodeInformation; } @Override protected void configureModule() { boolean standalone = nodeInformation.isStandalone(); add( new JvmPropertiesSection("Web JVM Properties"), new JvmStateSection("Web JVM State"), DbSection.class, DbConnectionSection.class, EsIndexesSection.class, LoggingSection.class, PluginsSection.class, SettingsSection.class, AlmConfigurationSection.class, ServerPushSection.class, BundledSection.class, StatisticsSupport.class, CommonSystemInformation.class ); if (standalone) { add( EsStateSection.class, StandaloneSystemSection.class, StandaloneSystemInfoWriter.class ); } else { add( CeQueueGlobalSection.class, EsClusterStateSection.class, GlobalSystemSection.class, NodeSystemSection.class, ProcessInfoProvider.class, GlobalInfoLoader.class, AppNodesInfoLoaderImpl.class, SearchNodesInfoLoaderImpl.class, ClusterSystemInfoWriter.class ); } } }
3,684
36.989691
78
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/WebCoreExtensionsInstaller.java
/* * SonarQube * Copyright (C) 2009-2023 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 org.sonar.api.SonarRuntime; import org.sonar.api.server.ServerSide; import org.sonar.core.extension.CoreExtensionRepository; import org.sonar.core.extension.CoreExtensionsInstaller; @ServerSide public class WebCoreExtensionsInstaller extends CoreExtensionsInstaller { public WebCoreExtensionsInstaller(SonarRuntime sonarRuntime, CoreExtensionRepository coreExtensionRepository) { super(sonarRuntime, coreExtensionRepository, ServerSide.class); } }
1,343
39.727273
113
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/CheckAnyonePermissionsAtStartup.java
/* * SonarQube * Copyright (C) 2009-2023 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; import java.util.List; import java.util.Optional; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; /** * Checks if there are any projects which have 'Anyone' group permissions at startup, after executing db migrations. If * any are found, it is logged as a warning, and some example projects (up to 3) are listed. This requires to be defined * in platform level 4 ({@link org.sonar.server.platform.platformlevel.PlatformLevel4}). */ public class CheckAnyonePermissionsAtStartup implements Startable { private static final Logger LOG = LoggerFactory.getLogger(CheckAnyonePermissionsAtStartup.class); private static final String FORCE_AUTHENTICATION_PROPERTY_NAME = "sonar.forceAuthentication"; private final DbClient dbClient; private final Configuration config; public CheckAnyonePermissionsAtStartup(DbClient dbClient, Configuration config) { this.dbClient = dbClient; this.config = config; } @Override public void start() { Optional<Boolean> property = config.getBoolean(FORCE_AUTHENTICATION_PROPERTY_NAME); if (property.isEmpty() || Boolean.TRUE.equals(property.get())) { return; } logWarningsIfAnyonePermissionsExist(); } private void logWarningsIfAnyonePermissionsExist() { try (DbSession dbSession = dbClient.openSession(false)) { if (!dbClient.groupPermissionDao().selectGlobalPermissionsOfGroup(dbSession, null).isEmpty()) { LOG.warn("Authentication is not enforced, and permissions assigned to the 'Anyone' group globally expose the " + "instance to security risks. Unauthenticated visitors may unintentionally have permissions on projects."); } int total = dbClient.groupPermissionDao().countEntitiesWithAnyonePermissions(dbSession); if (total > 0) { List<String> list = dbClient.groupPermissionDao().selectProjectKeysWithAnyonePermissions(dbSession, 3); LOG.warn("Authentication is not enforced, and project permissions assigned to the 'Anyone' group expose {} " + "public project(s) to security risks, including: {}. Unauthenticated visitors have permissions on these project(s).", total, String.join(", ", list)); } } } @Override public void stop() { // do nothing } }
3,277
39.469136
129
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/CheckDatabaseCharsetAtStartup.java
/* * SonarQube * Copyright (C) 2009-2023 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; import org.sonar.api.Startable; import org.sonar.api.platform.ServerUpgradeStatus; import org.sonar.server.platform.db.migration.charset.DatabaseCharsetChecker; /** * Checks charset of all existing database columns at startup, before executing db migrations. This requires * to be defined in platform level 2 ({@link org.sonar.server.platform.platformlevel.PlatformLevel2}). */ public class CheckDatabaseCharsetAtStartup implements Startable { private final ServerUpgradeStatus upgradeStatus; private final DatabaseCharsetChecker charsetChecker; public CheckDatabaseCharsetAtStartup(ServerUpgradeStatus upgradeStatus, DatabaseCharsetChecker charsetChecker) { this.upgradeStatus = upgradeStatus; this.charsetChecker = charsetChecker; } @Override public void start() { DatabaseCharsetChecker.State state = DatabaseCharsetChecker.State.STARTUP; if (upgradeStatus.isUpgraded()) { state = DatabaseCharsetChecker.State.UPGRADE; } else if (upgradeStatus.isFreshInstall()) { state = DatabaseCharsetChecker.State.FRESH_INSTALL; } charsetChecker.check(state); } @Override public void stop() { // do nothing } }
2,056
35.087719
114
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/CheckLanguageSpecificParamsAtStartup.java
/* * SonarQube * Copyright (C) 2009-2023 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; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS; /** * Checks if there are any language specific parameters set for calculating technical debt as functionality is deprecated from 9.9. * If found, it is logged as a warning. This requires to be defined in platform level 4 ({@link org.sonar.server.platform.platformlevel.PlatformLevel4}). */ public class CheckLanguageSpecificParamsAtStartup implements Startable { private static final Logger LOG = LoggerFactory.getLogger(CheckLanguageSpecificParamsAtStartup.class); private final Configuration config; public CheckLanguageSpecificParamsAtStartup(Configuration config) { this.config = config; } @Override public void start() { String[] languageSpecificParams = config.getStringArray(LANGUAGE_SPECIFIC_PARAMETERS); if (languageSpecificParams.length > 0) { LOG.warn("The development cost used for calculating the technical debt is currently configured with {} language specific parameters [Key: languageSpecificParameters]. " + "Please be aware that this functionality is deprecated, and will be removed in a future version.", languageSpecificParams.length); } } @Override public void stop() { // do nothing } }
2,262
38.017241
176
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/EmbeddedDatabase.java
/* * SonarQube * Copyright (C) 2009-2023 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; import java.io.File; import java.net.InetAddress; import java.sql.DriverManager; import java.sql.SQLException; import org.h2.Driver; import org.h2.tools.Server; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.sonar.api.utils.System2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.isNotEmpty; import static org.sonar.process.ProcessProperties.Property.JDBC_EMBEDDED_PORT; import static org.sonar.process.ProcessProperties.Property.JDBC_PASSWORD; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; import static org.sonar.process.ProcessProperties.Property.JDBC_USERNAME; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; public class EmbeddedDatabase implements Startable { private static final String IGNORED_KEYWORDS_OPTION = ";NON_KEYWORDS=VALUE"; private static final Logger LOG = LoggerFactory.getLogger(EmbeddedDatabase.class); private final Configuration config; private final System2 system2; private Server server; public EmbeddedDatabase(Configuration config, System2 system2) { this.config = config; this.system2 = system2; } @Override public void start() { File dbHome = new File(getRequiredSetting(PATH_DATA.getKey())); if (!dbHome.exists()) { dbHome.mkdirs(); } startServer(dbHome); } private void startServer(File dbHome) { String url = getRequiredSetting(JDBC_URL.getKey()); String port = getRequiredSetting(JDBC_EMBEDDED_PORT.getKey()); String user = getSetting(JDBC_USERNAME.getKey()); String password = getSetting(JDBC_PASSWORD.getKey()); try { // Db is used only by web server and compute engine. No need // to make it accessible from outside. system2.setProperty("h2.bindAddress", InetAddress.getLoopbackAddress().getHostAddress()); if (url.contains("/mem:")) { server = Server.createTcpServer("-tcpPort", port, "-baseDir", dbHome.getAbsolutePath()); } else { createDatabase(dbHome, user, password); server = Server.createTcpServer("-tcpPort", port, "-ifExists", "-baseDir", dbHome.getAbsolutePath()); } LOG.info("Starting embedded database on port " + server.getPort() + " with url " + url); server.start(); LOG.info("Embedded database started. Data stored in: " + dbHome.getAbsolutePath()); } catch (SQLException e) { throw new IllegalStateException("Unable to start database", e); } } @Override public void stop() { if (server != null) { server.stop(); server = null; LOG.info("Embedded database stopped"); } } private String getRequiredSetting(String property) { String value = config.get(property).orElse(""); checkArgument(isNotEmpty(value), "Missing property %s", property); return value; } private String getSetting(String name) { return config.get(name).orElse(""); } private static void createDatabase(File dbHome, String user, String password) throws SQLException { String url = format("jdbc:h2:%s/sonar;USER=%s;PASSWORD=%s%s", dbHome.getAbsolutePath(), user, password, IGNORED_KEYWORDS_OPTION); DriverManager.registerDriver(new Driver()); DriverManager.getConnection(url).close(); } }
4,294
35.398305
133
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/EmbeddedDatabaseFactory.java
/* * SonarQube * Copyright (C) 2009-2023 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; import com.google.common.annotations.VisibleForTesting; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.sonar.api.utils.System2; import static org.apache.commons.lang.StringUtils.startsWith; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; public class EmbeddedDatabaseFactory implements Startable { private static final String URL_PREFIX = "jdbc:h2:tcp:"; private final Configuration config; private final System2 system2; private EmbeddedDatabase embeddedDatabase; public EmbeddedDatabaseFactory(Configuration config, System2 system2) { this.config = config; this.system2 = system2; } @Override public void start() { if (embeddedDatabase == null) { String jdbcUrl = config.get(JDBC_URL.getKey()).get(); if (startsWith(jdbcUrl, URL_PREFIX)) { embeddedDatabase = createEmbeddedDatabase(); embeddedDatabase.start(); } } } @Override public void stop() { if (embeddedDatabase != null) { embeddedDatabase.stop(); embeddedDatabase = null; } } @VisibleForTesting EmbeddedDatabase createEmbeddedDatabase() { return new EmbeddedDatabase(config, system2); } }
2,103
30.402985
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/migration/AutoDbMigration.java
/* * SonarQube * Copyright (C) 2009-2023 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; import org.sonar.api.Startable; import org.slf4j.LoggerFactory; import org.sonar.server.platform.DefaultServerUpgradeStatus; import org.sonar.server.platform.db.migration.engine.MigrationEngine; public class AutoDbMigration implements Startable { private final DefaultServerUpgradeStatus serverUpgradeStatus; private final MigrationEngine migrationEngine; public AutoDbMigration(DefaultServerUpgradeStatus serverUpgradeStatus, MigrationEngine migrationEngine) { this.serverUpgradeStatus = serverUpgradeStatus; this.migrationEngine = migrationEngine; } @Override public void start() { if (serverUpgradeStatus.isFreshInstall()) { LoggerFactory.getLogger(getClass()).info("Automatically perform DB migration on fresh install"); migrationEngine.execute(); } else if (serverUpgradeStatus.isUpgraded() && serverUpgradeStatus.isAutoDbUpgrade()) { LoggerFactory.getLogger(getClass()).info("Automatically perform DB migration, as automatic database upgrade is enabled"); migrationEngine.execute(); } } @Override public void stop() { // nothing to do } }
2,010
36.943396
127
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/migration/DatabaseMigrationExecutorService.java
/* * SonarQube * Copyright (C) 2009-2023 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; import java.util.concurrent.ExecutorService; /** * Flag interface for the ExecutorService to be used by the {@link DatabaseMigrationImpl} * component. */ public interface DatabaseMigrationExecutorService extends ExecutorService { }
1,128
36.633333
89
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/migration/DatabaseMigrationExecutorServiceImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.sonar.server.util.AbstractStoppableExecutorService; import java.util.concurrent.Executors; /** * Since only one DB migration can run at a time, this implementation of DatabaseMigrationExecutorService * wraps a single thread executor from the JDK. */ public class DatabaseMigrationExecutorServiceImpl extends AbstractStoppableExecutorService implements DatabaseMigrationExecutorService { public DatabaseMigrationExecutorServiceImpl() { super( Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setDaemon(false) .setNameFormat("DB_migration-%d") .build() )); } }
1,609
34.777778
105
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/migration/DatabaseMigrationImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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; import java.util.Date; import java.util.concurrent.Semaphore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.util.logs.Profiler; import org.sonar.server.platform.Platform; import org.sonar.server.platform.db.migration.DatabaseMigrationState.Status; import org.sonar.server.platform.db.migration.engine.MigrationEngine; import org.sonar.server.platform.db.migration.step.MigrationStepExecutionException; /** * Handles concurrency to make sure only one DB migration can run at a time. */ public class DatabaseMigrationImpl implements DatabaseMigration { private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseMigrationImpl.class); /** * ExecutorService implements threads management. */ private final DatabaseMigrationExecutorService executorService; private final MigrationEngine migrationEngine; private final Platform platform; private final MutableDatabaseMigrationState migrationState; /** * This semaphore implements thread safety from concurrent calls of method {@link #startIt()} */ private final Semaphore semaphore = new Semaphore(1); public DatabaseMigrationImpl(DatabaseMigrationExecutorService executorService, MutableDatabaseMigrationState migrationState, MigrationEngine migrationEngine, Platform platform) { this.executorService = executorService; this.migrationState = migrationState; this.migrationEngine = migrationEngine; this.platform = platform; } @Override public void startIt() { if (semaphore.tryAcquire()) { try { executorService.execute(this::doDatabaseMigration); } catch (RuntimeException e) { semaphore.release(); throw e; } } else { LOGGER.trace("{}: lock is already taken or process is already running", Thread.currentThread().getName()); } } private void doDatabaseMigration() { migrationState.setStatus(Status.RUNNING); migrationState.setStartedAt(new Date()); migrationState.setError(null); Profiler profiler = Profiler.create(LOGGER); try { profiler.startInfo("Starting DB Migration and container restart"); doUpgradeDb(); doRestartContainer(); migrationState.setStatus(Status.SUCCEEDED); profiler.stopInfo("DB Migration and container restart: success"); } catch (MigrationStepExecutionException e) { profiler.stopError("DB migration failed"); LOGGER.error("DB migration ended with an exception", e); saveStatus(e); } catch (Throwable t) { profiler.stopError("Container restart failed"); LOGGER.error("Container restart failed", t); saveStatus(t); } finally { semaphore.release(); } } private void saveStatus(Throwable e) { migrationState.setStatus(Status.FAILED); migrationState.setError(e); } private void doUpgradeDb() { Profiler profiler = Profiler.createIfTrace(LOGGER); profiler.startTrace("Starting DB Migration"); migrationEngine.execute(); profiler.stopTrace("DB Migration ended"); } private void doRestartContainer() { Profiler profiler = Profiler.createIfTrace(LOGGER); profiler.startTrace("Restarting container"); platform.doStart(); profiler.stopTrace("Container restarted successfully"); } }
4,172
34.666667
126
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/db/migration/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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; import javax.annotation.ParametersAreNonnullByDefault;
978
39.791667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/AlmConfigurationSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import java.util.List; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.alm.setting.AlmSettingDto; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @ServerSide public class AlmConfigurationSection implements SystemInfoSection { private final DbClient dbClient; public AlmConfigurationSection(DbClient dbClient) { this.dbClient = dbClient; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("ALMs"); try (DbSession dbSession = dbClient.openSession(false)) { List<AlmSettingDto> almSettingDtos = dbClient.almSettingDao().selectAll(dbSession); for (AlmSettingDto almSettingDto : almSettingDtos) { setAttribute(protobuf, almSettingDto.getKey(), buildValue(almSettingDto)); } } return protobuf.build(); } private static String buildValue(AlmSettingDto almSettingDto) { String value = String.format("Alm:%s", almSettingDto.getRawAlm()); if (almSettingDto.getUrl() != null) { value += String.format(", Url:%s", almSettingDto.getUrl()); } switch (almSettingDto.getAlm()) { case GITHUB: // add APP_ID and CLIENT_ID value += String.format(", App Id:%s, Client Id:%s", almSettingDto.getAppId(), almSettingDto.getClientId()); break; case BITBUCKET_CLOUD: // WORKSPACE ID & OAuth key value += String.format(", Workspace Id:%s, OAuth Key:%s", almSettingDto.getAppId(), almSettingDto.getClientId()); break; default: // no additional information for the other ALMs break; } return value; } }
2,782
35.142857
121
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/BundledSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import org.sonar.api.server.ServerSide; import org.sonar.core.platform.PluginInfo; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.core.plugin.PluginType; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.updatecenter.common.Version; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @ServerSide public class BundledSection implements SystemInfoSection { private final ServerPluginRepository repository; public BundledSection(ServerPluginRepository repository) { this.repository = repository; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Bundled"); for (PluginInfo plugin : repository.getPluginsInfoByType(PluginType.BUNDLED)) { String label = ""; Version version = plugin.getVersion(); if (version != null) { label = version.getName() + " "; } label += String.format("[%s]", plugin.getName()); setAttribute(protobuf, plugin.getKey(), label); } return protobuf.build(); } }
2,106
35.327586
90
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/CommonSystemInformation.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import java.util.List; import javax.annotation.CheckForNull; import org.sonar.api.CoreProperties; import org.sonar.api.config.Configuration; import org.sonar.api.security.SecurityRealm; import org.sonar.api.server.authentication.IdentityProvider; import org.sonar.server.authentication.IdentityProviderRepository; import org.sonar.server.management.ManagedInstanceService; import org.sonar.server.user.SecurityRealmFactory; import static java.util.Collections.emptyList; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE; public class CommonSystemInformation { private final Configuration config; private final IdentityProviderRepository identityProviderRepository; private final ManagedInstanceService managedInstanceService; private final SecurityRealmFactory securityRealmFactory; public CommonSystemInformation(Configuration config, IdentityProviderRepository identityProviderRepository, ManagedInstanceService managedInstanceService, SecurityRealmFactory securityRealmFactory) { this.config = config; this.identityProviderRepository = identityProviderRepository; this.managedInstanceService = managedInstanceService; this.securityRealmFactory = securityRealmFactory; } public boolean getForceAuthentication() { return config.getBoolean(CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY).orElse(CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE); } public List<String> getEnabledIdentityProviders() { return identityProviderRepository.getAllEnabledAndSorted() .stream() .filter(IdentityProvider::isEnabled) .map(IdentityProvider::getName) .toList(); } public List<String> getAllowsToSignUpEnabledIdentityProviders() { if (managedInstanceService.isInstanceExternallyManaged()) { return emptyList(); } return identityProviderRepository.getAllEnabledAndSorted() .stream() .filter(IdentityProvider::isEnabled) .filter(IdentityProvider::allowsUsersToSignUp) .map(IdentityProvider::getName) .toList(); } public String getManagedInstanceProviderName() { if (managedInstanceService.isInstanceExternallyManaged()) { return managedInstanceService.getProviderName(); } return null; } @CheckForNull public String getExternalUserAuthentication() { SecurityRealm realm = securityRealmFactory.getRealm(); return realm == null ? null : realm.getName(); } }
3,326
37.686047
128
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/DbConnectionSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarRuntime; import org.sonar.db.DatabaseMBean; import org.sonar.db.DbClient; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section; import org.sonar.server.platform.db.migration.version.DatabaseVersion; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; /** * Information about database connection pool */ public class DbConnectionSection extends DatabaseMBean implements DbConnectionSectionMBean { private final DatabaseVersion dbVersion; private final SonarRuntime runtime; public DbConnectionSection(DatabaseVersion dbVersion, DbClient dbClient, SonarRuntime runtime) { super(dbClient); this.dbVersion = dbVersion; this.runtime = runtime; } @Override public String name() { return "Database"; } @Override public String getMigrationStatus() { return dbVersion.getStatus().name(); } @Override public Section toProtobuf() { Section.Builder protobuf = Section.newBuilder(); String side = runtime.getSonarQubeSide() == SonarQubeSide.COMPUTE_ENGINE ? "Compute Engine" : "Web"; protobuf.setName(side + " Database Connection"); completePoolAttributes(protobuf); return protobuf.build(); } private void completePoolAttributes(Section.Builder protobuf) { setAttribute(protobuf, "Pool Total Connections", getPoolTotalConnections()); setAttribute(protobuf, "Pool Active Connections", getPoolActiveConnections()); setAttribute(protobuf, "Pool Idle Connections", getPoolIdleConnections()); setAttribute(protobuf, "Pool Max Connections", getPoolMaxConnections()); setAttribute(protobuf, "Pool Min Idle Connections", getPoolMinIdleConnections()); setAttribute(protobuf, "Pool Max Wait (ms)", getPoolMaxWaitMillis()); setAttribute(protobuf, "Pool Max Lifetime (ms)", getPoolMaxLifeTimeMillis()); } }
2,784
36.133333
104
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/DbConnectionSectionMBean.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; public interface DbConnectionSectionMBean { /** * Is database schema up-to-date or should it be upgraded ? */ String getMigrationStatus(); /** * Get the number of currently active connections in the pool. */ int getPoolActiveConnections(); /** * The maximum number of connections that can be allocated from this pool at the same time, or negative for no limit. */ int getPoolMaxConnections(); /** * Total number of connections currently in the pool */ int getPoolTotalConnections(); /** * Get the number of currently idle connections in the pool. */ int getPoolIdleConnections(); /** * The minimum number of connections that can remain idle in the pool, without extra ones being created, or zero to create none. */ int getPoolMinIdleConnections(); /** * Maximum lifetime of a connection in the pool. */ long getPoolMaxLifeTimeMillis(); /** * The maximum number of milliseconds that the pool will wait * (when there are no available connections) for a connection to be returned before throwing an exception, or -1 to wait indefinitely. */ long getPoolMaxWaitMillis(); }
2,052
30.106061
136
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/EsIndexesSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import org.elasticsearch.ElasticsearchException; import org.sonar.api.server.ServerSide; import org.slf4j.LoggerFactory; import org.sonar.process.systeminfo.Global; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsClient; import org.sonar.server.es.response.IndexStats; import org.sonar.server.es.response.IndicesStatsResponse; import static org.sonar.core.util.FileUtils.humanReadableByteCountSI; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @ServerSide public class EsIndexesSection implements SystemInfoSection, Global { private final EsClient esClient; public EsIndexesSection(EsClient esClient) { this.esClient = esClient; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Search Indexes"); try { completeIndexAttributes(protobuf); } catch (Exception es) { LoggerFactory.getLogger(EsIndexesSection.class).warn("Failed to retrieve ES attributes. There will be only a single \"Error\" attribute.", es); setAttribute(protobuf, "Error", es.getCause() instanceof ElasticsearchException ? es.getCause().getMessage() : es.getMessage()); } return protobuf.build(); } private void completeIndexAttributes(ProtobufSystemInfo.Section.Builder protobuf) { IndicesStatsResponse indicesStats = esClient.indicesStats(); for (IndexStats indexStats : indicesStats.getAllIndexStats()) { String prefix = "Index " + indexStats.getName() + " - "; setAttribute(protobuf, prefix + "Docs", indexStats.getDocCount()); setAttribute(protobuf, prefix + "Shards", indexStats.getShardsCount()); setAttribute(protobuf, prefix + "Store Size", humanReadableByteCountSI(indexStats.getStoreSizeBytes())); } } }
2,818
41.074627
149
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/EsStateSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import java.util.Locale; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.slf4j.LoggerFactory; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsClient; import org.sonar.server.es.response.NodeStats; import org.sonar.server.es.response.NodeStatsResponse; import static java.lang.String.format; import static org.sonar.core.util.FileUtils.humanReadableByteCountSI; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; public class EsStateSection implements SystemInfoSection { private final EsClient esClient; public EsStateSection(EsClient esClient) { this.esClient = esClient; } private ClusterHealthStatus getStateAsEnum() { return esClient.clusterHealth(new ClusterHealthRequest()).getStatus(); } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Search State"); try { setAttribute(protobuf, "State", getStateAsEnum().name()); completeNodeAttributes(protobuf); } catch (Exception es) { LoggerFactory.getLogger(EsStateSection.class).warn("Failed to retrieve ES attributes. There will be only a single \"state\" attribute.", es); setAttribute(protobuf, "State", es.getCause() instanceof ElasticsearchException ? es.getCause().getMessage() : es.getMessage()); } return protobuf.build(); } private void completeNodeAttributes(ProtobufSystemInfo.Section.Builder protobuf) { NodeStatsResponse nodesStatsResponse = esClient.nodesStats(); if (!nodesStatsResponse.getNodeStats().isEmpty()) { toProtobuf(nodesStatsResponse.getNodeStats().get(0), protobuf); } } public static void toProtobuf(NodeStats stats, ProtobufSystemInfo.Section.Builder protobuf) { setAttribute(protobuf, "CPU Usage (%)", stats.getCpuUsage()); setAttribute(protobuf, "Disk Available", humanReadableByteCountSI(stats.getDiskAvailableBytes())); setAttribute(protobuf, "Store Size", humanReadableByteCountSI(stats.getIndicesStats().getStoreSizeInBytes())); setAttribute(protobuf, "Translog Size", humanReadableByteCountSI(stats.getIndicesStats().getTranslogSizeInBytes())); setAttribute(protobuf, "Open File Descriptors", stats.getOpenFileDescriptors()); setAttribute(protobuf, "Max File Descriptors", stats.getMaxFileDescriptors()); setAttribute(protobuf, "JVM Heap Usage", formatPercent(stats.getJvmStats().getHeapUsedPercent())); setAttribute(protobuf, "JVM Heap Used", humanReadableByteCountSI(stats.getJvmStats().getHeapUsedInBytes())); setAttribute(protobuf, "JVM Heap Max", humanReadableByteCountSI(stats.getJvmStats().getHeapMaxInBytes())); setAttribute(protobuf, "JVM Non Heap Used", humanReadableByteCountSI(stats.getJvmStats().getNonHeapUsedInBytes())); setAttribute(protobuf, "JVM Threads", stats.getJvmStats().getThreadCount()); setAttribute(protobuf, "Field Data Memory", humanReadableByteCountSI(stats.getIndicesStats().getFieldDataMemorySizeInBytes())); setAttribute(protobuf, "Field Data Circuit Breaker Limit", humanReadableByteCountSI(stats.getFieldDataCircuitBreakerLimit())); setAttribute(protobuf, "Field Data Circuit Breaker Estimation", humanReadableByteCountSI(stats.getFieldDataCircuitBreakerEstimation())); setAttribute(protobuf, "Request Circuit Breaker Limit", humanReadableByteCountSI(stats.getRequestCircuitBreakerLimit())); setAttribute(protobuf, "Request Circuit Breaker Estimation", humanReadableByteCountSI(stats.getRequestCircuitBreakerEstimation())); setAttribute(protobuf, "Query Cache Memory", humanReadableByteCountSI(stats.getIndicesStats().getQueryCacheMemorySizeInBytes())); setAttribute(protobuf, "Request Cache Memory", humanReadableByteCountSI(stats.getIndicesStats().getRequestCacheMemorySizeInBytes())); } private static String formatPercent(long amount) { return format(Locale.ENGLISH, "%.1f%%", 100.0 * amount * 1.0 / 100.0); } }
5,131
49.811881
147
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/PluginsSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import org.sonar.api.server.ServerSide; import org.sonar.core.platform.PluginInfo; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.core.plugin.PluginType; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.updatecenter.common.Version; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @ServerSide public class PluginsSection implements SystemInfoSection { private final ServerPluginRepository repository; public PluginsSection(ServerPluginRepository repository) { this.repository = repository; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Plugins"); for (PluginInfo plugin : repository.getPluginsInfoByType(PluginType.EXTERNAL)) { String label = ""; Version version = plugin.getVersion(); if (version != null) { label = version.getName() + " "; } label += String.format("[%s]", plugin.getName()); setAttribute(protobuf, plugin.getKey(), label); } return protobuf.build(); } }
2,107
35.344828
90
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/SettingsSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import java.util.Collection; import java.util.Map.Entry; import java.util.Optional; import java.util.TreeMap; import java.util.stream.Stream; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.Settings; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.newcodeperiod.NewCodePeriodDto; import org.sonar.process.ProcessProperties.Property; import org.sonar.process.systeminfo.Global; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo.Section.Builder; import org.sonar.server.platform.NodeInformation; import static java.util.stream.Collectors.toUnmodifiableSet; import static org.apache.commons.lang.StringUtils.containsIgnoreCase; import static org.apache.commons.lang.StringUtils.endsWithIgnoreCase; import static org.sonar.process.ProcessProperties.Property.AUTH_JWT_SECRET; import static org.sonar.process.ProcessProperties.Property.CE_JAVA_ADDITIONAL_OPTS; import static org.sonar.process.ProcessProperties.Property.CE_JAVA_OPTS; import static org.sonar.process.ProcessProperties.Property.SEARCH_JAVA_ADDITIONAL_OPTS; import static org.sonar.process.ProcessProperties.Property.SEARCH_JAVA_OPTS; import static org.sonar.process.ProcessProperties.Property.WEB_JAVA_ADDITIONAL_OPTS; import static org.sonar.process.ProcessProperties.Property.WEB_JAVA_OPTS; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @ServerSide public class SettingsSection implements SystemInfoSection, Global { private static final String PASSWORD_VALUE = "xxxxxxxx"; private static final Collection<String> IGNORED_SETTINGS_IN_CLUSTER = Stream.of( WEB_JAVA_OPTS, WEB_JAVA_ADDITIONAL_OPTS, CE_JAVA_OPTS, CE_JAVA_ADDITIONAL_OPTS, SEARCH_JAVA_OPTS, SEARCH_JAVA_ADDITIONAL_OPTS) .map(Property::getKey) .collect(toUnmodifiableSet()); private final DbClient dbClient; private final Settings settings; private final NodeInformation nodeInformation; public SettingsSection(DbClient dbClient, Settings settings, NodeInformation nodeInformation) { this.dbClient = dbClient; this.settings = settings; this.nodeInformation = nodeInformation; } @Override public ProtobufSystemInfo.Section toProtobuf() { Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Settings"); PropertyDefinitions definitions = settings.getDefinitions(); TreeMap<String, String> orderedProps = new TreeMap<>(settings.getProperties()); orderedProps.entrySet() .stream() .filter(prop -> nodeInformation.isStandalone() || !IGNORED_SETTINGS_IN_CLUSTER.contains(prop.getKey())) .forEach(prop -> includeSetting(protobuf, definitions, prop)); addDefaultNewCodeDefinition(protobuf); return protobuf.build(); } private static void includeSetting(Builder protobuf, PropertyDefinitions definitions, Entry<String, String> prop) { String key = prop.getKey(); String value = obfuscateValue(definitions, key, prop.getValue()); setAttribute(protobuf, key, value); } private void addDefaultNewCodeDefinition(Builder protobuf) { try (DbSession dbSession = dbClient.openSession(false)) { Optional<NewCodePeriodDto> period = dbClient.newCodePeriodDao().selectGlobal(dbSession); setAttribute(protobuf, "Default New Code Definition", parseDefaultNewCodeDefinition(period.orElse(NewCodePeriodDto.defaultInstance()))); } } private static String obfuscateValue(PropertyDefinitions definitions, String key, String value) { PropertyDefinition def = definitions.get(key); if (def != null && def.type() == PropertyType.PASSWORD) { return PASSWORD_VALUE; } if (endsWithIgnoreCase(key, ".secured") || containsIgnoreCase(key, "password") || containsIgnoreCase(key, "passcode") || AUTH_JWT_SECRET.getKey().equals(key)) { return PASSWORD_VALUE; } return value; } private static String parseDefaultNewCodeDefinition(NewCodePeriodDto period) { if (period.getValue() == null) { return period.getType().name(); } return period.getType().name() + ": " + period.getValue(); } }
5,291
40.669291
142
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/StandaloneSystemSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import org.sonar.api.SonarRuntime; import org.sonar.api.config.Configuration; import org.sonar.api.platform.Server; import org.sonar.process.systeminfo.BaseSectionMBean; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.log.ServerLogging; import org.sonar.server.platform.ContainerSupport; import org.sonar.server.platform.OfficialDistribution; import org.sonar.server.platform.StatisticsSupport; import static org.sonar.api.measures.CoreMetrics.NCLOC; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.systeminfo.SystemInfoUtils.addIfNotEmpty; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; public class StandaloneSystemSection extends BaseSectionMBean implements SystemSectionMBean { private final Configuration config; private final Server server; private final ServerLogging serverLogging; private final OfficialDistribution officialDistribution; private final ContainerSupport containerSupport; private final StatisticsSupport statisticsSupport; private final SonarRuntime sonarRuntime; private final CommonSystemInformation commonSystemInformation; public StandaloneSystemSection(Configuration config, Server server, ServerLogging serverLogging, OfficialDistribution officialDistribution, ContainerSupport containerSupport, StatisticsSupport statisticsSupport, SonarRuntime sonarRuntime, CommonSystemInformation commonSystemInformation) { this.config = config; this.server = server; this.serverLogging = serverLogging; this.officialDistribution = officialDistribution; this.containerSupport = containerSupport; this.statisticsSupport = statisticsSupport; this.sonarRuntime = sonarRuntime; this.commonSystemInformation = commonSystemInformation; } @Override public String getServerId() { return server.getId(); } @Override public String getVersion() { return server.getVersion(); } @Override public String getLogLevel() { return serverLogging.getRootLoggerLevel().name(); } @Override public String name() { // JMX name return "SonarQube"; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "Version", getVersion()); setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel()); setAttribute(protobuf, NCLOC.getName(), statisticsSupport.getLinesOfCode()); setAttribute(protobuf, "Container", containerSupport.isRunningInContainer()); setAttribute(protobuf, "External Users and Groups Provisioning", commonSystemInformation.getManagedInstanceProviderName()); setAttribute(protobuf, "External User Authentication", commonSystemInformation.getExternalUserAuthentication()); addIfNotEmpty(protobuf, "Accepted external identity providers", commonSystemInformation.getEnabledIdentityProviders()); addIfNotEmpty(protobuf, "External identity providers whose users are allowed to sign themselves up", commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()); setAttribute(protobuf, "High Availability", false); setAttribute(protobuf, "Official Distribution", officialDistribution.check()); setAttribute(protobuf, "Force authentication", commonSystemInformation.getForceAuthentication()); setAttribute(protobuf, "Home Dir", config.get(PATH_HOME.getKey()).orElse(null)); setAttribute(protobuf, "Data Dir", config.get(PATH_DATA.getKey()).orElse(null)); setAttribute(protobuf, "Temp Dir", config.get(PATH_TEMP.getKey()).orElse(null)); setAttribute(protobuf, "Processors", Runtime.getRuntime().availableProcessors()); return protobuf.build(); } }
4,916
43.7
127
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/SystemSectionMBean.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import javax.annotation.CheckForNull; public interface SystemSectionMBean { @CheckForNull String getServerId(); String getVersion(); String getLogLevel(); }
1,058
32.09375
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring; import javax.annotation.ParametersAreNonnullByDefault;
976
39.708333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/AppNodesInfoLoader.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import java.util.Collection; public interface AppNodesInfoLoader { Collection<NodeInfo> load() throws InterruptedException; }
1,028
35.75
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/AppNodesInfoLoaderImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.MemberSelector; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.api.server.ServerSide; import org.sonar.process.ProcessId; import org.sonar.process.cluster.hz.DistributedAnswer; import org.sonar.process.cluster.hz.HazelcastMember; import org.sonar.process.cluster.hz.HazelcastMemberSelectors; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static org.sonar.process.cluster.hz.HazelcastMember.Attribute.NODE_NAME; @ServerSide public class AppNodesInfoLoaderImpl implements AppNodesInfoLoader { /** * Timeout to get information from all nodes */ private static final long DISTRIBUTED_TIMEOUT_MS = 15_000L; private final HazelcastMember hzMember; public AppNodesInfoLoaderImpl(@Nullable HazelcastMember hzMember) { this.hzMember = hzMember; } public Collection<NodeInfo> load() throws InterruptedException { Map<String, NodeInfo> nodesByName = new HashMap<>(); MemberSelector memberSelector = HazelcastMemberSelectors.selectorForProcessIds(ProcessId.WEB_SERVER, ProcessId.COMPUTE_ENGINE); DistributedAnswer<ProtobufSystemInfo.SystemInfo> distributedAnswer = hzMember.call(ProcessInfoProvider::provide, memberSelector, DISTRIBUTED_TIMEOUT_MS); for (Member member : distributedAnswer.getMembers()) { String nodeName = member.getAttribute(NODE_NAME.getKey()); NodeInfo nodeInfo = nodesByName.computeIfAbsent(nodeName, name -> { NodeInfo info = new NodeInfo(name); info.setHost(member.getAddress().getHost()); return info; }); completeNodeInfo(distributedAnswer, member, nodeInfo); } return nodesByName.values(); } private static void completeNodeInfo(DistributedAnswer<ProtobufSystemInfo.SystemInfo> distributedAnswer, Member member, NodeInfo nodeInfo) { Optional<ProtobufSystemInfo.SystemInfo> nodeAnswer = distributedAnswer.getAnswer(member); Optional<Exception> failure = distributedAnswer.getFailed(member); if (distributedAnswer.hasTimedOut(member)) { nodeInfo.setErrorMessage("Failed to retrieve information on time"); } else if (failure.isPresent()) { nodeInfo.setErrorMessage("Failed to retrieve information: " + failure.get().getMessage()); } else if (nodeAnswer.isPresent()) { nodeAnswer.get().getSectionsList().forEach(nodeInfo::addSection); } } }
3,398
41.4875
157
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/CeQueueGlobalSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import javax.annotation.Nullable; import org.sonar.api.server.ServerSide; import org.sonar.ce.configuration.WorkerCountProvider; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeQueueDto; import org.sonar.process.systeminfo.Global; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.property.InternalProperties; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @ServerSide public class CeQueueGlobalSection implements SystemInfoSection, Global { private static final int DEFAULT_NB_OF_WORKERS = 1; private final DbClient dbClient; @Nullable private final WorkerCountProvider workerCountProvider; public CeQueueGlobalSection(DbClient dbClient, @Nullable WorkerCountProvider workerCountProvider) { this.dbClient = dbClient; this.workerCountProvider = workerCountProvider; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Compute Engine Tasks"); try (DbSession dbSession = dbClient.openSession(false)) { setAttribute(protobuf, "Total Pending", dbClient.ceQueueDao().countByStatus(dbSession, CeQueueDto.Status.PENDING)); setAttribute(protobuf, "Total In Progress", dbClient.ceQueueDao().countByStatus(dbSession, CeQueueDto.Status.IN_PROGRESS)); setAttribute(protobuf, "Max Workers per Node", workerCountProvider == null ? DEFAULT_NB_OF_WORKERS : workerCountProvider.get()); setAttribute(protobuf, "Workers Paused", "true".equals(dbClient.internalPropertiesDao().selectByKey(dbSession, InternalProperties.COMPUTE_ENGINE_PAUSE).orElse(null))); } return protobuf.build(); } }
2,714
42.790323
173
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/EsClusterStateSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import org.sonar.api.server.ServerSide; import org.sonar.process.systeminfo.Global; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsClient; import org.sonar.server.es.response.ClusterStatsResponse; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; /** * In cluster mode, section "Search" that displays all ES information * that are not specific to a node or an index */ @ServerSide public class EsClusterStateSection implements SystemInfoSection, Global { private final EsClient esClient; public EsClusterStateSection(EsClient esClient) { this.esClient = esClient; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Search State"); ClusterStatsResponse stats = esClient.clusterStats(); setAttribute(protobuf, "State", stats.getHealthStatus().name()); setAttribute(protobuf, "Nodes", stats.getNodeCount()); return protobuf.build(); } }
2,021
35.763636
90
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalInfoLoader.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import java.util.Arrays; import java.util.List; import org.sonar.api.server.ServerSide; import org.sonar.process.systeminfo.Global; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; @ServerSide public class GlobalInfoLoader { private final List<SystemInfoSection> globalSections; public GlobalInfoLoader(SystemInfoSection[] sections) { this.globalSections = Arrays.stream(sections) .filter(section -> section instanceof Global) .toList(); } public List<ProtobufSystemInfo.Section> load() { return globalSections.stream() .map(SystemInfoSection::toProtobuf) .toList(); } }
1,585
34.244444
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/GlobalSystemSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import org.sonar.api.SonarRuntime; import org.sonar.api.platform.Server; import org.sonar.api.server.ServerSide; import org.sonar.process.systeminfo.Global; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.platform.ContainerSupport; import org.sonar.server.platform.StatisticsSupport; import org.sonar.server.platform.monitoring.CommonSystemInformation; import static org.sonar.api.measures.CoreMetrics.NCLOC; import static org.sonar.process.systeminfo.SystemInfoUtils.addIfNotEmpty; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @ServerSide public class GlobalSystemSection implements SystemInfoSection, Global { private final Server server; private final ContainerSupport containerSupport; private final StatisticsSupport statisticsSupport; private final SonarRuntime sonarRuntime; private final CommonSystemInformation commonSystemInformation; public GlobalSystemSection(Server server, ContainerSupport containerSupport, StatisticsSupport statisticsSupport, SonarRuntime sonarRuntime, CommonSystemInformation commonSystemInformation) { this.server = server; this.containerSupport = containerSupport; this.statisticsSupport = statisticsSupport; this.sonarRuntime = sonarRuntime; this.commonSystemInformation = commonSystemInformation; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); setAttribute(protobuf, "Server ID", server.getId()); setAttribute(protobuf, "Edition", sonarRuntime.getEdition().getLabel()); setAttribute(protobuf, NCLOC.getName() ,statisticsSupport.getLinesOfCode()); setAttribute(protobuf, "Container", containerSupport.isRunningInContainer()); setAttribute(protobuf, "High Availability", true); setAttribute(protobuf, "External Users and Groups Provisioning", commonSystemInformation.getManagedInstanceProviderName()); setAttribute(protobuf, "External User Authentication", commonSystemInformation.getExternalUserAuthentication()); addIfNotEmpty(protobuf, "Accepted external identity providers", commonSystemInformation.getEnabledIdentityProviders()); addIfNotEmpty(protobuf, "External identity providers whose users are allowed to sign themselves up", commonSystemInformation.getAllowsToSignUpEnabledIdentityProviders()); setAttribute(protobuf, "Force authentication", commonSystemInformation.getForceAuthentication()); return protobuf.build(); } }
3,546
45.671053
142
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/NodeInfo.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; /** * Represents the system information of a cluster node. In the case of * application node, it merges information from Web Server and Compute * Engine processes. * */ public class NodeInfo { private final String name; private String host = null; private Long startedAt = null; private String errorMessage = null; private final List<ProtobufSystemInfo.Section> sections = new ArrayList<>(); public NodeInfo(String name) { this.name = name; } public String getName() { return name; } public Optional<String> getHost() { return Optional.ofNullable(host); } public void setHost(@Nullable String s) { this.host = s; } public Optional<Long> getStartedAt() { return Optional.ofNullable(startedAt); } public void setStartedAt(@Nullable Long l) { this.startedAt = l; } public Optional<String> getErrorMessage() { return Optional.ofNullable(errorMessage); } public void setErrorMessage(@Nullable String s) { this.errorMessage = s; } public NodeInfo addSection(ProtobufSystemInfo.Section section) { this.sections.add(section); return this; } public List<ProtobufSystemInfo.Section> getSections() { return sections; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NodeInfo nodeInfo = (NodeInfo) o; return name.equals(nodeInfo.name); } @Override public int hashCode() { return name.hashCode(); } }
2,620
25.21
78
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/NodeSystemSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import org.sonar.api.config.Configuration; import org.sonar.api.platform.Server; import org.sonar.api.server.ServerSide; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.platform.OfficialDistribution; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @ServerSide public class NodeSystemSection implements SystemInfoSection { private final Configuration config; private final Server server; private final OfficialDistribution officialDistribution; public NodeSystemSection(Configuration config, Server server, OfficialDistribution officialDistribution) { this.config = config; this.server = server; this.officialDistribution = officialDistribution; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("System"); setAttribute(protobuf, "Version", server.getVersion()); setAttribute(protobuf, "Official Distribution", officialDistribution.check()); setAttribute(protobuf, "Home Dir", config.get(PATH_HOME.getKey()).orElse(null)); setAttribute(protobuf, "Data Dir", config.get(PATH_DATA.getKey()).orElse(null)); setAttribute(protobuf, "Temp Dir", config.get(PATH_TEMP.getKey()).orElse(null)); setAttribute(protobuf, "Processors", Runtime.getRuntime().availableProcessors()); return protobuf.build(); } }
2,610
41.112903
108
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/SearchNodesInfoLoader.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import java.util.Collection; /** * Loads "system information" of all Elasticsearch nodes. */ public interface SearchNodesInfoLoader { Collection<NodeInfo> load(); }
1,069
33.516129
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/SearchNodesInfoLoaderImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.sonar.api.server.ServerSide; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.es.EsClient; import org.sonar.server.es.response.NodeStats; import org.sonar.server.es.response.NodeStatsResponse; import org.sonar.server.platform.monitoring.EsStateSection; @ServerSide public class SearchNodesInfoLoaderImpl implements SearchNodesInfoLoader { private final EsClient esClient; public SearchNodesInfoLoaderImpl(EsClient esClient) { this.esClient = esClient; } public Collection<NodeInfo> load() { NodeStatsResponse response = esClient.nodesStats(); List<NodeInfo> result = new ArrayList<>(); response.getNodeStats().forEach(nodeStat -> result.add(toNodeInfo(nodeStat))); return result; } private static NodeInfo toNodeInfo(NodeStats stat) { String nodeName = stat.getName(); NodeInfo info = new NodeInfo(nodeName); info.setHost(stat.getHost()); ProtobufSystemInfo.Section.Builder section = ProtobufSystemInfo.Section.newBuilder(); section.setName("Search State"); EsStateSection.toProtobuf(stat, section); info.addSection(section.build()); return info; } }
2,154
33.758065
89
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/ServerPushSection.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import org.sonar.api.server.ServerSide; import org.sonar.process.systeminfo.SystemInfoSection; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import org.sonar.server.pushapi.sonarlint.SonarLintClientsRegistry; import static org.sonar.process.systeminfo.SystemInfoUtils.setAttribute; @ServerSide public class ServerPushSection implements SystemInfoSection { private final SonarLintClientsRegistry sonarLintClientsRegistry; public ServerPushSection(SonarLintClientsRegistry sonarLintClientsRegistry) { this.sonarLintClientsRegistry = sonarLintClientsRegistry; } @Override public ProtobufSystemInfo.Section toProtobuf() { ProtobufSystemInfo.Section.Builder protobuf = ProtobufSystemInfo.Section.newBuilder(); protobuf.setName("Server Push Connections"); setAttribute(protobuf, "SonarLint Connected Clients", sonarLintClientsRegistry.countConnectedClients()); return protobuf.build(); } }
1,838
38.978261
108
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/monitoring/cluster/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.monitoring.cluster; import javax.annotation.ParametersAreNonnullByDefault;
984
40.041667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/serverid/ServerIdFactory.java
/* * SonarQube * Copyright (C) 2009-2023 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.serverid; import org.sonar.core.platform.ServerId; public interface ServerIdFactory { /** * Create a new ServerId from scratch. */ ServerId create(); /** * Create a new ServerId from the current serverId. */ ServerId create(ServerId currentServerId); }
1,153
31.971429
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/serverid/ServerIdFactoryImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.serverid; import com.google.common.annotations.VisibleForTesting; import java.nio.charset.StandardCharsets; import java.util.Locale; import java.util.zip.CRC32; import org.apache.commons.lang.StringUtils; import org.sonar.api.config.Configuration; import org.sonar.core.platform.ServerId; import org.sonar.core.util.UuidFactory; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; public class ServerIdFactoryImpl implements ServerIdFactory { private final Configuration config; private final UuidFactory uuidFactory; private final JdbcUrlSanitizer jdbcUrlSanitizer; public ServerIdFactoryImpl(Configuration config, UuidFactory uuidFactory, JdbcUrlSanitizer jdbcUrlSanitizer) { this.config = config; this.uuidFactory = uuidFactory; this.jdbcUrlSanitizer = jdbcUrlSanitizer; } @Override public ServerId create() { return ServerId.of(computeDatabaseId(), uuidFactory.create()); } @Override public ServerId create(ServerId currentServerId) { return ServerId.of(computeDatabaseId(), currentServerId.getDatasetId()); } private String computeDatabaseId() { String jdbcUrl = config.get(JDBC_URL.getKey()).orElseThrow(() -> new IllegalStateException("Missing JDBC URL")); return crc32Hex(jdbcUrlSanitizer.sanitize(jdbcUrl)); } @VisibleForTesting static String crc32Hex(String str) { CRC32 crc32 = new CRC32(); crc32.update(str.getBytes(StandardCharsets.UTF_8)); long hash = crc32.getValue(); String s = Long.toHexString(hash).toUpperCase(Locale.ENGLISH); return StringUtils.leftPad(s, ServerId.DATABASE_ID_LENGTH, "0"); } }
2,500
34.728571
116
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/serverid/ServerIdManager.java
/* * SonarQube * Copyright (C) 2009-2023 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.serverid; import java.util.Optional; import org.sonar.api.SonarQubeSide; import org.sonar.api.SonarRuntime; import org.sonar.api.Startable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.platform.ServerId; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.PropertyDto; import org.sonar.server.platform.NodeInformation; import org.sonar.server.property.InternalProperties; import static com.google.common.base.Preconditions.checkState; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; import static org.sonar.api.CoreProperties.SERVER_ID; import static org.sonar.server.property.InternalProperties.SERVER_ID_CHECKSUM; public class ServerIdManager implements Startable { private static final Logger LOGGER = LoggerFactory.getLogger(ServerIdManager.class); private final ServerIdChecksum serverIdChecksum; private final ServerIdFactory serverIdFactory; private final DbClient dbClient; private final SonarRuntime runtime; private final NodeInformation nodeInformation; public ServerIdManager(ServerIdChecksum serverIdChecksum, ServerIdFactory serverIdFactory, DbClient dbClient, SonarRuntime runtime, NodeInformation nodeInformation) { this.serverIdChecksum = serverIdChecksum; this.serverIdFactory = serverIdFactory; this.dbClient = dbClient; this.runtime = runtime; this.nodeInformation = nodeInformation; } @Override public void start() { try (DbSession dbSession = dbClient.openSession(false)) { if (runtime.getSonarQubeSide() == SonarQubeSide.SERVER && nodeInformation.isStartupLeader()) { Optional<String> checksum = dbClient.internalPropertiesDao().selectByKey(dbSession, SERVER_ID_CHECKSUM); ServerId serverId = readCurrentServerId(dbSession) .map(currentServerId -> keepOrReplaceCurrentServerId(dbSession, currentServerId, checksum)) .orElseGet(() -> createFirstServerId(dbSession)); updateChecksum(dbSession, serverId); dbSession.commit(); } else { ensureServerIdIsValid(dbSession); } } } private ServerId keepOrReplaceCurrentServerId(DbSession dbSession, ServerId currentServerId, Optional<String> checksum) { if (keepServerId(currentServerId, checksum)) { return currentServerId; } ServerId serverId = replaceCurrentServerId(currentServerId); persistServerId(dbSession, serverId); return serverId; } private boolean keepServerId(ServerId serverId, Optional<String> checksum) { if (checksum.isPresent()) { String expectedChecksum = serverIdChecksum.computeFor(serverId.toString()); if (!expectedChecksum.equals(checksum.get())) { LOGGER.warn("Server ID is reset because it is not valid anymore. Database URL probably changed. The new server ID affects SonarSource licensed products."); return false; } } // Existing server ID must be kept when upgrading to 6.7+. In that case the checksum does not exist. return true; } private ServerId replaceCurrentServerId(ServerId currentServerId) { return serverIdFactory.create(currentServerId); } private ServerId createFirstServerId(DbSession dbSession) { ServerId serverId = serverIdFactory.create(); persistServerId(dbSession, serverId); return serverId; } private Optional<ServerId> readCurrentServerId(DbSession dbSession) { PropertyDto dto = dbClient.propertiesDao().selectGlobalProperty(dbSession, SERVER_ID); if (dto == null) { return Optional.empty(); } String value = dto.getValue(); if (isEmpty(value)) { return Optional.empty(); } return Optional.of(ServerId.parse(value)); } private void updateChecksum(DbSession dbSession, ServerId serverId) { // checksum must be generated when it does not exist (upgrading to 6.7 or greater) // or when server ID changed. String checksum = serverIdChecksum.computeFor(serverId.toString()); persistChecksum(dbSession, checksum); } private void persistServerId(DbSession dbSession, ServerId serverId) { dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto().setKey(SERVER_ID).setValue(serverId.toString())); } private void persistChecksum(DbSession dbSession, String checksump) { dbClient.internalPropertiesDao().save(dbSession, InternalProperties.SERVER_ID_CHECKSUM, checksump); } private void ensureServerIdIsValid(DbSession dbSession) { PropertyDto id = dbClient.propertiesDao().selectGlobalProperty(dbSession, SERVER_ID); checkState(id != null, "Property %s is missing in database", SERVER_ID); checkState(isNotEmpty(id.getValue()), "Property %s is empty in database", SERVER_ID); Optional<String> checksum = dbClient.internalPropertiesDao().selectByKey(dbSession, SERVER_ID_CHECKSUM); checkState(checksum.isPresent(), "Internal property %s is missing in database", SERVER_ID_CHECKSUM); checkState(checksum.get().equals(serverIdChecksum.computeFor(id.getValue())), "Server ID is invalid"); } @Override public void stop() { // nothing to do } }
6,058
38.344156
163
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/serverid/ServerIdModule.java
/* * SonarQube * Copyright (C) 2009-2023 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.serverid; import org.sonar.core.platform.Module; public class ServerIdModule extends Module { @Override protected void configureModule() { add( ServerIdFactoryImpl.class, JdbcUrlSanitizer.class, ServerIdChecksum.class, ServerIdManager.class ); } }
1,166
31.416667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/serverid/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.serverid; import javax.annotation.ParametersAreNonnullByDefault;
974
39.625
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/AbortTomcatStartException.java
/* * SonarQube * Copyright (C) 2009-2023 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.web; /** * An exception without any stacktrace nor message which point is solely to make tomcat startup fail during * initialization of the Context Listener {@link PlatformServletContextListener}. */ public class AbortTomcatStartException extends RuntimeException { public AbortTomcatStartException() { super("Aborting tomcat servlet context startup"); } /** * Does not fill in the stack trace * * @see Throwable#fillInStackTrace() */ @Override public synchronized Throwable fillInStackTrace() { return this; } @Override public String toString() { return getMessage(); } }
1,498
31.586957
107
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/RootFilter.java
/* * SonarQube * Copyright (C) 2009-2023 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.web; import com.google.common.annotations.VisibleForTesting; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.lang.String.format; import static java.util.stream.Collectors.joining; /** * <p>Profile HTTP requests using platform profiling utility.</p> * <p>To avoid profiling of requests for static resources, the <code>staticDirs</code> * filter parameter can be set in the servlet context descriptor. This parameter should * contain a comma-separated list of paths, starting at the context root; * requests on subpaths of these paths will not be profiled.</p> * * @since 4.1 */ public class RootFilter implements Filter { private static final Logger LOGGER = LoggerFactory.getLogger(RootFilter.class); @Override public void init(FilterConfig filterConfig) { // nothing to do } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest httpRequest) { HttpServletResponse httpResponse = (HttpServletResponse) response; try { chain.doFilter(new ServletRequestWrapper(httpRequest), httpResponse); } catch (Throwable e) { if (httpResponse.isCommitted()) { // Request has been aborted by the client, nothing can been done as Tomcat has committed the response LOGGER.debug(format("Processing of request %s failed", toUrl(httpRequest)), e); return; } LOGGER.error(format("Processing of request %s failed", toUrl(httpRequest)), e); httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } else { // Not an HTTP request, not profiled chain.doFilter(request, response); } } private static String toUrl(HttpServletRequest request) { String requestURI = request.getRequestURI(); String queryString = request.getQueryString(); if (queryString == null) { return requestURI; } return requestURI + '?' + queryString; } @Override public void destroy() { // Nothing } @VisibleForTesting static class ServletRequestWrapper extends HttpServletRequestWrapper { private String body; ServletRequestWrapper(HttpServletRequest request) { super(request); } @Override public HttpSession getSession(boolean create) { if (!create) { return null; } throw notSupported(); } @Override public HttpSession getSession() { throw notSupported(); } private static UnsupportedOperationException notSupported() { return new UnsupportedOperationException("Sessions are disabled so that web server is stateless"); } @Override public BufferedReader getReader() throws IOException { if (body == null) { body = getBodyInternal((HttpServletRequest) getRequest()); } return new BufferedReader(new StringReader(body)); } private static String getBodyInternal(HttpServletRequest request) throws IOException { return request.getReader().lines().collect(joining(System.lineSeparator())); } } }
4,517
32.716418
130
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.web; import javax.annotation.ParametersAreNonnullByDefault;
969
39.416667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/requestid/HttpRequestIdModule.java
/* * SonarQube * Copyright (C) 2009-2023 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.web.requestid; import org.sonar.core.platform.Module; public class HttpRequestIdModule extends Module { @Override protected void configureModule() { add(new RequestIdConfiguration(RequestIdGeneratorImpl.UUID_GENERATOR_RENEWAL_COUNT), RequestIdGeneratorBaseImpl.class, RequestIdGeneratorImpl.class); } }
1,204
36.65625
88
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/requestid/RequestIdConfiguration.java
/* * SonarQube * Copyright (C) 2009-2023 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.web.requestid; public class RequestIdConfiguration { /** * @see RequestIdGeneratorImpl#mustRenewUuidGenerator(long) */ private final long uuidGeneratorRenewalCount; public RequestIdConfiguration(long uuidGeneratorRenewalCount) { this.uuidGeneratorRenewalCount = uuidGeneratorRenewalCount; } public long getUidGeneratorRenewalCount() { return uuidGeneratorRenewalCount; } }
1,279
34.555556
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/requestid/RequestIdGenerator.java
/* * SonarQube * Copyright (C) 2009-2023 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.web.requestid; /** * Generate a Unique Identifier for Http Requests. */ public interface RequestIdGenerator { /** * Generate a new and unique request id for each call. */ String generate(); }
1,082
33.935484
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/requestid/RequestIdGeneratorBase.java
/* * SonarQube * Copyright (C) 2009-2023 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.web.requestid; import org.sonar.core.util.UuidGenerator; public interface RequestIdGeneratorBase { /** * Provides a new instance of {@link UuidGenerator.WithFixedBase} to be used by {@link RequestIdGeneratorImpl}. */ UuidGenerator.WithFixedBase createNew(); }
1,149
37.333333
113
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/requestid/RequestIdGeneratorBaseImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.web.requestid; import org.sonar.core.util.UuidGenerator; import org.sonar.core.util.UuidGeneratorImpl; public class RequestIdGeneratorBaseImpl implements RequestIdGeneratorBase { @Override public UuidGenerator.WithFixedBase createNew() { return new UuidGeneratorImpl().withFixedBase(); } }
1,180
35.90625
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/requestid/RequestIdGeneratorImpl.java
/* * SonarQube * Copyright (C) 2009-2023 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.web.requestid; import java.util.Base64; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.sonar.core.util.UuidGenerator; /** * This implementation of {@link RequestIdGenerator} creates unique identifiers for HTTP requests leveraging * {@link UuidGenerator.WithFixedBase#generate(int)} and a counter of HTTP requests. * <p> * To work around the limit of unique values produced by {@link UuidGenerator.WithFixedBase#generate(int)}, the * {@link UuidGenerator.WithFixedBase} instance will be renewed every * {@link RequestIdConfiguration#getUidGeneratorRenewalCount() RequestIdConfiguration#uidGeneratorRenewalCount} * HTTP requests. * </p> * <p> * This implementation is Thread safe. * </p> */ public class RequestIdGeneratorImpl implements RequestIdGenerator { /** * The value to which the HTTP request count will be compared to (using a modulo operator, * see {@link #mustRenewUuidGenerator(long)}). * * <p> * This value can't be the last value before {@link UuidGenerator.WithFixedBase#generate(int)} returns a non unique * value, ie. 2^23-1 because there is no guarantee the renewal will happen before any other thread calls * {@link UuidGenerator.WithFixedBase#generate(int)} method of the deplated {@link UuidGenerator.WithFixedBase} instance. * </p> * * <p> * To keep a comfortable margin of error, 2^22 will be used. * </p> */ public static final long UUID_GENERATOR_RENEWAL_COUNT = 4_194_304; private final AtomicLong counter = new AtomicLong(); private final RequestIdGeneratorBase requestIdGeneratorBase; private final RequestIdConfiguration requestIdConfiguration; private final AtomicReference<UuidGenerator.WithFixedBase> uuidGenerator; public RequestIdGeneratorImpl(RequestIdGeneratorBase requestIdGeneratorBase, RequestIdConfiguration requestIdConfiguration) { this.requestIdGeneratorBase = requestIdGeneratorBase; this.uuidGenerator = new AtomicReference<>(requestIdGeneratorBase.createNew()); this.requestIdConfiguration = requestIdConfiguration; } @Override public String generate() { UuidGenerator.WithFixedBase currentUuidGenerator = this.uuidGenerator.get(); long counterValue = counter.getAndIncrement(); if (counterValue != 0 && mustRenewUuidGenerator(counterValue)) { UuidGenerator.WithFixedBase newUuidGenerator = requestIdGeneratorBase.createNew(); uuidGenerator.set(newUuidGenerator); return generate(newUuidGenerator, counterValue); } return generate(currentUuidGenerator, counterValue); } /** * Since renewal of {@link UuidGenerator.WithFixedBase} instance is based on the HTTP request counter, only a single * thread can get the right value which will make this method return true. So, this is thread-safe by design, therefor * this method doesn't need external synchronization. * <p> * The value to which the counter is compared should however be chosen with caution: see {@link #UUID_GENERATOR_RENEWAL_COUNT}. * </p> */ private boolean mustRenewUuidGenerator(long counter) { return counter % requestIdConfiguration.getUidGeneratorRenewalCount() == 0; } private static String generate(UuidGenerator.WithFixedBase uuidGenerator, long increment) { return Base64.getEncoder().encodeToString(uuidGenerator.generate((int) increment)); } }
4,272
43.051546
129
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/requestid/RequestIdMDCStorage.java
/* * SonarQube * Copyright (C) 2009-2023 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.web.requestid; import org.slf4j.MDC; import static java.util.Objects.requireNonNull; /** * Wraps MDC calls to store the HTTP request ID in the {@link MDC} into an {@link AutoCloseable}. */ public class RequestIdMDCStorage implements AutoCloseable { public static final String HTTP_REQUEST_ID_MDC_KEY = "HTTP_REQUEST_ID"; public RequestIdMDCStorage(String requestId) { MDC.put(HTTP_REQUEST_ID_MDC_KEY, requireNonNull(requestId, "Request ID can't be null")); } @Override public void close() { MDC.remove(HTTP_REQUEST_ID_MDC_KEY); } }
1,436
34.04878
97
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/platform/web/requestid/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.web.requestid; import javax.annotation.ParametersAreNonnullByDefault;
979
39.833333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/plugins/PluginsRiskConsentFilter.java
/* * SonarQube * Copyright (C) 2009-2023 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.plugins; import java.io.IOException; import java.util.Set; import org.sonar.api.config.Configuration; import org.sonar.api.impl.ws.StaticResources; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.web.FilterChain; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.UrlPattern; import org.sonar.core.extension.PluginRiskConsent; import org.sonar.server.user.ThreadLocalUserSession; import static org.sonar.core.config.CorePropertyDefinitions.PLUGINS_RISK_CONSENT; import static org.sonar.core.extension.PluginRiskConsent.NOT_ACCEPTED; import static org.sonar.core.extension.PluginRiskConsent.REQUIRED; import static org.sonar.server.authentication.AuthenticationRedirection.redirectTo; public class PluginsRiskConsentFilter extends HttpFilter { private static final String PLUGINS_RISK_CONSENT_PATH = "/admin/plugin_risk_consent"; //NOSONAR this path will be the same in every environment private static final Set<String> SKIPPED_URLS = Set.of( PLUGINS_RISK_CONSENT_PATH, "/account/reset_password", "/admin/change_admin_password", "/batch/*", "/api/*", "/api/v2/*"); private final ThreadLocalUserSession userSession; private final Configuration config; public PluginsRiskConsentFilter(Configuration config, ThreadLocalUserSession userSession) { this.userSession = userSession; this.config = config; } @Override public void init() { //nothing to do } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException{ PluginRiskConsent riskConsent = PluginRiskConsent.valueOf(config.get(PLUGINS_RISK_CONSENT).orElse(NOT_ACCEPTED.name())); if (userSession.hasSession() && userSession.isLoggedIn() && userSession.isSystemAdministrator() && riskConsent == REQUIRED) { redirectTo(response, request.getContextPath() + PLUGINS_RISK_CONSENT_PATH); } chain.doFilter(request, response); } @Override public UrlPattern doGetPattern() { return UrlPattern.builder() .includes("/*") .excludes(StaticResources.patterns()) .excludes(SKIPPED_URLS) .build(); } @Override public void destroy() { //nothing to do } }
3,122
34.896552
145
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/plugins/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.plugins; import javax.annotation.ParametersAreNonnullByDefault;
965
37.64
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/project/ProjectQGChangeEventListener.java
/* * SonarQube * Copyright (C) 2009-2023 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.project; import java.util.Optional; import java.util.Set; import java.util.UUID; import javax.annotation.Nullable; import org.sonar.api.measures.Metric; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventDto; import org.sonar.server.qualitygate.EvaluatedQualityGate; import org.sonar.server.qualitygate.changeevent.QGChangeEvent; import org.sonar.server.qualitygate.changeevent.QGChangeEventListener; import static org.sonar.db.event.EventDto.CATEGORY_ALERT; public class ProjectQGChangeEventListener implements QGChangeEventListener { private final DbClient dbClient; public ProjectQGChangeEventListener(DbClient dbClient) { this.dbClient = dbClient; } @Override public void onIssueChanges(QGChangeEvent qualityGateEvent, Set<ChangedIssue> changedIssues) { Optional<EvaluatedQualityGate> evaluatedQualityGate = qualityGateEvent.getQualityGateSupplier().get(); Optional<Metric.Level> previousStatusOptional = qualityGateEvent.getPreviousStatus(); if (evaluatedQualityGate.isEmpty() || previousStatusOptional.isEmpty()) { return; } Metric.Level currentStatus = evaluatedQualityGate.get().getStatus(); Metric.Level previousStatus = previousStatusOptional.get(); if (previousStatus.getColorName().equals(currentStatus.getColorName())) { // QG status didn't change - no action return; } addQualityGateEventToProject(qualityGateEvent, currentStatus); } private void addQualityGateEventToProject(QGChangeEvent qualityGateEvent, Metric.Level currentStatus) { try (DbSession dbSession = dbClient.openSession(false)) { String componentUuid = qualityGateEvent.getAnalysis().getRootComponentUuid(); SnapshotDto liveMeasureSnapshotDto = createLiveMeasureSnapshotDto(qualityGateEvent.getAnalysis().getProjectVersion(), componentUuid); dbClient.snapshotDao().insert(dbSession, liveMeasureSnapshotDto); EventDto eventDto = createEventDto(componentUuid, liveMeasureSnapshotDto.getUuid(), currentStatus); dbClient.eventDao().insert(dbSession, eventDto); dbSession.commit(); } } private static EventDto createEventDto(String componentUuid, String snapshotUuid, Metric.Level currentStatus) { EventDto eventDto = new EventDto(); eventDto.setComponentUuid(componentUuid); eventDto.setCreatedAt(System2.INSTANCE.now()); eventDto.setCategory(CATEGORY_ALERT); eventDto.setDate(System2.INSTANCE.now()); eventDto.setAnalysisUuid(snapshotUuid); eventDto.setUuid(UUID.randomUUID().toString()); eventDto.setName(currentStatus.getColorName().equals(Metric.Level.OK.getColorName()) ? Measure.Level.OK.getLabel() : Measure.Level.ERROR.getLabel()); return eventDto; } private static SnapshotDto createLiveMeasureSnapshotDto(@Nullable String projectVersion, String componentUuid) { SnapshotDto dto = new SnapshotDto(); dto.setUuid(UUID.randomUUID().toString()); dto.setCreatedAt(System2.INSTANCE.now()); dto.setProjectVersion(projectVersion); dto.setLast(false); dto.setStatus(SnapshotDto.STATUS_LIVE_MEASURE_COMPUTED); dto.setRootComponentUuid(componentUuid); return dto; } }
4,199
39.384615
153
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/project/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.project; import javax.annotation.ParametersAreNonnullByDefault;
965
37.64
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/ProjectsInWarningDaemon.java
/* * SonarQube * Copyright (C) 2009-2023 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.qualitygate; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.Optional; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.sonar.api.Startable; import org.sonar.api.config.Configuration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.server.es.SearchOptions; import org.sonar.server.measure.index.ProjectMeasuresIndex; import org.sonar.server.measure.index.ProjectMeasuresQuery; import org.sonar.server.util.GlobalLockManager; import static org.sonar.api.measures.Metric.Level.WARN; /** * This class is regularly checking the number of projects in warning state, in order to not return the "Warning" value * in the quality gate facet of the Projects page when there are no more projects in warning. * * @see <a href="https://jira.sonarsource.com/browse/SONAR-12140">SONAR-12140</a> for more information */ public class ProjectsInWarningDaemon implements Startable { static final String PROJECTS_IN_WARNING_INTERNAL_PROPERTY = "projectsInWarning"; private static final Logger LOG = LoggerFactory.getLogger(ProjectsInWarningDaemon.class); private static final String FREQUENCY_IN_MILLISECONDS_PROPERTY = "sonar.projectsInWarning.frequencyInMilliseconds"; private static final int DEFAULT_FREQUENCY_IN_MILLISECONDS = 1000 * 60 * 60 * 24; private static final String THREAD_NAME_PREFIX = "sq-projects-in-warning-service-"; private static final String LOCK_NAME = "ProjectsInWarn"; private static final int LOCK_DURATION_IN_SECOND = 60 * 60; private final DbClient dbClient; private final ProjectMeasuresIndex projectMeasuresIndex; private final Configuration config; private final GlobalLockManager lockManager; private final ProjectsInWarning projectsInWarning; private ScheduledExecutorService executorService; public ProjectsInWarningDaemon(DbClient dbClient, ProjectMeasuresIndex projectMeasuresIndex, Configuration config, GlobalLockManager lockManager, ProjectsInWarning projectsInWarning) { this.dbClient = dbClient; this.projectMeasuresIndex = projectMeasuresIndex; this.config = config; this.lockManager = lockManager; this.projectsInWarning = projectsInWarning; } public void notifyStart() { try (DbSession dbSession = dbClient.openSession(false)) { Optional<String> internalProperty = dbClient.internalPropertiesDao().selectByKey(dbSession, PROJECTS_IN_WARNING_INTERNAL_PROPERTY); if (internalProperty.isPresent() && internalProperty.get().equals("0")) { projectsInWarning.update(0L); LOG.info("Counting number of projects in warning is not started as there are no projects in this situation."); return; } } LOG.info("Counting number of projects in warning is enabled."); executorService = Executors.newSingleThreadScheduledExecutor(newThreadFactory()); executorService.scheduleWithFixedDelay(countProjectsInWarning(), 0, frequency(), TimeUnit.MILLISECONDS); } private int frequency() { return config.getInt(FREQUENCY_IN_MILLISECONDS_PROPERTY).orElse(DEFAULT_FREQUENCY_IN_MILLISECONDS); } private Runnable countProjectsInWarning() { return () -> { long nbProjectsInWarning = projectMeasuresIndex.search( new ProjectMeasuresQuery() .setQualityGateStatus(WARN) .setIgnoreAuthorization(true), // We only need the number of projects in warning new SearchOptions().setLimit(1)).getTotal(); try (DbSession dbSession = dbClient.openSession(false)) { updateProjectsInWarningInDb(dbSession, nbProjectsInWarning); } catch (Exception e) { LOG.error("Error updating number of projects in warning: {}", e.getMessage(), e); } projectsInWarning.update(nbProjectsInWarning); if (nbProjectsInWarning == 0L) { LOG.info("Counting number of projects in warning will be disabled as there are no more projects in warning."); executorService.shutdown(); } }; } private void updateProjectsInWarningInDb(DbSession dbSession, long nbProjectsInWarning) { // Only one web node should do the update in db to avoid any collision if (!lockManager.tryLock(LOCK_NAME, LOCK_DURATION_IN_SECOND)) { return; } dbClient.internalPropertiesDao().save(dbSession, PROJECTS_IN_WARNING_INTERNAL_PROPERTY, Long.toString(nbProjectsInWarning)); dbSession.commit(); } @Override public void start() { // Nothing is done here, as this component needs to be started after ES indexing. See PlatformLevelStartup for more info. } @Override public void stop() { if (executorService == null) { return; } try { executorService.shutdown(); executorService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private static ThreadFactory newThreadFactory() { return new ThreadFactoryBuilder() .setNameFormat(THREAD_NAME_PREFIX + "%d") .setPriority(Thread.MIN_PRIORITY) .build(); } }
6,112
39.217105
147
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/ProjectsInWarningModule.java
/* * SonarQube * Copyright (C) 2009-2023 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.qualitygate; import org.sonar.core.platform.Module; public class ProjectsInWarningModule extends Module { @Override protected void configureModule() { add( ProjectsInWarningDaemon.class, ProjectsInWarning.class ); } }
1,115
31.823529
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/qualitygate/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 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.qualitygate; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/AdvancedRuleDescriptionSectionsGenerator.java
/* * SonarQube * Copyright (C) 2009-2023 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.rule; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.elasticsearch.common.util.set.Sets; import org.jetbrains.annotations.Nullable; import org.sonar.api.server.rule.Context; import org.sonar.api.server.rule.RuleDescriptionSection; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.core.util.UuidFactory; import org.sonar.db.rule.RuleDescriptionSectionContextDto; import org.sonar.db.rule.RuleDescriptionSectionDto; import static org.sonar.api.rules.RuleType.*; public class AdvancedRuleDescriptionSectionsGenerator implements RuleDescriptionSectionsGenerator { private final UuidFactory uuidFactory; private final LegacyIssueRuleDescriptionSectionsGenerator legacyIssueRuleDescriptionSectionsGenerator; public AdvancedRuleDescriptionSectionsGenerator(UuidFactory uuidFactory, LegacyIssueRuleDescriptionSectionsGenerator legacyIssueRuleDescriptionSectionsGenerator) { this.uuidFactory = uuidFactory; this.legacyIssueRuleDescriptionSectionsGenerator = legacyIssueRuleDescriptionSectionsGenerator; } @Override public boolean isGeneratorForRule(RulesDefinition.Rule rule) { return !rule.ruleDescriptionSections().isEmpty() && skipHotspotRulesForSonar16635(rule); } private static boolean skipHotspotRulesForSonar16635(RulesDefinition.Rule rule) { return !SECURITY_HOTSPOT.equals(rule.type()); } @Override public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) { Set<RuleDescriptionSectionDto> advancedSections = rule.ruleDescriptionSections().stream() .map(this::toRuleDescriptionSectionDto) .collect(Collectors.toSet()); return addLegacySectionToAdvancedSections(advancedSections, rule); } /** * This was done to preserve backward compatibility with SonarLint until they stop using htmlDesc field in api/rules/[show|search] endpoints, see SONAR-16635 * @deprecated the method should be removed once SonarLint supports rules.descriptionSections fields, I.E in 10.x */ @Deprecated(since = "9.6", forRemoval = true) private Set<RuleDescriptionSectionDto> addLegacySectionToAdvancedSections(Set<RuleDescriptionSectionDto> advancedSections, RulesDefinition.Rule rule) { Set<RuleDescriptionSectionDto> legacySection = legacyIssueRuleDescriptionSectionsGenerator.generateSections(rule); return Sets.union(advancedSections, legacySection); } private RuleDescriptionSectionDto toRuleDescriptionSectionDto(RuleDescriptionSection section) { return RuleDescriptionSectionDto.builder() .uuid(uuidFactory.create()) .key(section.getKey()) .content(section.getHtmlContent()) .context(toRuleDescriptionSectionContextDto(section.getContext())) .build(); } @Nullable private static RuleDescriptionSectionContextDto toRuleDescriptionSectionContextDto(Optional<Context> context) { return context .map(c -> RuleDescriptionSectionContextDto.of(c.getKey(), c.getDisplayName())) .orElse(null); } }
3,887
42.685393
165
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/LegacyHotspotRuleDescriptionSectionsGenerator.java
/* * SonarQube * Copyright (C) 2009-2023 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.rule; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.core.util.UuidFactory; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.markdown.Markdown; import static java.util.Collections.emptySet; import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ASSESS_THE_PROBLEM_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.HOW_TO_FIX_SECTION_KEY; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.ROOT_CAUSE_SECTION_KEY; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; public class LegacyHotspotRuleDescriptionSectionsGenerator implements RuleDescriptionSectionsGenerator { private final UuidFactory uuidFactory; public LegacyHotspotRuleDescriptionSectionsGenerator(UuidFactory uuidFactory) { this.uuidFactory = uuidFactory; } @Override public boolean isGeneratorForRule(RulesDefinition.Rule rule) { // To prevent compatibility issues with SonarLint, this Generator is used for all hotspots rules, regardless of if they expose advanced sections or not. See SONAR-16635. // In the future, the generator should not be used for advanced rules (add condition && rule.ruleDescriptionSections().isEmpty()) return SECURITY_HOTSPOT.equals(rule.type()); } @Override public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) { return getDescriptionInHtml(rule) .map(this::generateSections) .orElse(emptySet()); } private static Optional<String> getDescriptionInHtml(RulesDefinition.Rule rule) { if (rule.htmlDescription() != null) { return Optional.of(rule.htmlDescription()); } else if (rule.markdownDescription() != null) { return Optional.of(Markdown.convertToHtml(rule.markdownDescription())); } return Optional.empty(); } private Set<RuleDescriptionSectionDto> generateSections(String descriptionInHtml) { if (descriptionInHtml.isEmpty()) { return emptySet(); } String[] split = extractSection("", descriptionInHtml); String remainingText = split[0]; String ruleDescriptionSection = split[1]; split = extractSection("<h2>Exceptions</h2>", remainingText); remainingText = split[0]; String exceptions = split[1]; split = extractSection("<h2>Ask Yourself Whether</h2>", remainingText); remainingText = split[0]; String askSection = split[1]; split = extractSection("<h2>Sensitive Code Example</h2>", remainingText); remainingText = split[0]; String sensitiveSection = split[1]; split = extractSection("<h2>Noncompliant Code Example</h2>", remainingText); remainingText = split[0]; String noncompliantSection = split[1]; split = extractSection("<h2>Recommended Secure Coding Practices</h2>", remainingText); remainingText = split[0]; String recommendedSection = split[1]; split = extractSection("<h2>Compliant Solution</h2>", remainingText); remainingText = split[0]; String compliantSection = split[1]; split = extractSection("<h2>See</h2>", remainingText); remainingText = split[0]; String seeSection = split[1]; RuleDescriptionSectionDto rootSection = createSection(ROOT_CAUSE_SECTION_KEY, ruleDescriptionSection, exceptions, remainingText); RuleDescriptionSectionDto assessSection = createSection(ASSESS_THE_PROBLEM_SECTION_KEY, askSection, sensitiveSection, noncompliantSection); RuleDescriptionSectionDto fixSection = createSection(HOW_TO_FIX_SECTION_KEY, recommendedSection, compliantSection, seeSection); // For backward compatibility with SonarLint, see SONAR-16635. Should be removed in 10.x RuleDescriptionSectionDto defaultSection = createDefaultRuleDescriptionSection(uuidFactory.create(), descriptionInHtml); return Stream.of(rootSection, assessSection, fixSection, defaultSection) .filter(Objects::nonNull) .collect(Collectors.toSet()); } private static String[] extractSection(String beginning, String description) { String endSection = "<h2>"; int beginningIndex = description.indexOf(beginning); if (beginningIndex != -1) { int endIndex = description.indexOf(endSection, beginningIndex + beginning.length()); if (endIndex == -1) { endIndex = description.length(); } return new String[] { description.substring(0, beginningIndex) + description.substring(endIndex), description.substring(beginningIndex, endIndex) }; } else { return new String[] {description, ""}; } } @CheckForNull private RuleDescriptionSectionDto createSection(String key, String... contentPieces) { String content = trimToNull(String.join("", contentPieces)); if (content == null) { return null; } return RuleDescriptionSectionDto.builder() .uuid(uuidFactory.create()) .key(key) .content(content) .build(); } @CheckForNull private static String trimToNull(String input) { return input.isEmpty() ? null : input; } }
6,235
38.974359
173
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/LegacyIssueRuleDescriptionSectionsGenerator.java
/* * SonarQube * Copyright (C) 2009-2023 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.rule; import java.util.EnumSet; import java.util.Set; import org.sonar.api.rules.RuleType; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.core.util.UuidFactory; import org.sonar.db.rule.RuleDescriptionSectionDto; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static org.apache.commons.lang.StringUtils.isNotEmpty; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.VULNERABILITY; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; public class LegacyIssueRuleDescriptionSectionsGenerator implements RuleDescriptionSectionsGenerator { private static final Set<RuleType> ISSUE_RULE_TYPES = EnumSet.of(CODE_SMELL, BUG, VULNERABILITY); private final UuidFactory uuidFactory; public LegacyIssueRuleDescriptionSectionsGenerator(UuidFactory uuidFactory) { this.uuidFactory = uuidFactory; } @Override public boolean isGeneratorForRule(RulesDefinition.Rule rule) { return ISSUE_RULE_TYPES.contains(rule.type()) && rule.ruleDescriptionSections().isEmpty(); } @Override public Set<RuleDescriptionSectionDto> generateSections(RulesDefinition.Rule rule) { if (isNotEmpty(rule.htmlDescription())) { return singleton(createDefaultRuleDescriptionSection(uuidFactory.create(), rule.htmlDescription())); } else if (isNotEmpty(rule.markdownDescription())) { return singleton(createDefaultRuleDescriptionSection(uuidFactory.create(), rule.markdownDescription())); } return emptySet(); } }
2,513
40.213115
110
java
sonarqube
sonarqube-master/server/sonar-webserver-core/src/main/java/org/sonar/server/rule/RegisterRules.java
/* * SonarQube * Copyright (C) 2009-2023 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.rule; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.Startable; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleScope; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; import org.sonar.api.server.debt.DebtRemediationFunction; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.ActiveRuleDto; import org.sonar.db.qualityprofile.ActiveRuleParamDto; import org.sonar.db.rule.DeprecatedRuleKeyDto; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleDto.Format; import org.sonar.db.rule.RuleDto.Scope; import org.sonar.db.rule.RuleParamDto; import org.sonar.db.rule.RuleRepositoryDto; import org.sonar.server.es.metadata.MetadataIndex; import org.sonar.server.qualityprofile.ActiveRuleChange; import org.sonar.server.qualityprofile.QProfileRules; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.rule.index.RuleIndexer; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Sets.difference; import static com.google.common.collect.Sets.intersection; import static java.lang.String.format; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.unmodifiableMap; import static org.apache.commons.lang.StringUtils.isNotEmpty; /** * Register rules at server startup */ public class RegisterRules implements Startable { private static final Logger LOG = Loggers.get(RegisterRules.class); private final RuleDefinitionsLoader defLoader; private final QProfileRules qProfileRules; private final DbClient dbClient; private final RuleIndexer ruleIndexer; private final ActiveRuleIndexer activeRuleIndexer; private final Languages languages; private final System2 system2; private final WebServerRuleFinder webServerRuleFinder; private final UuidFactory uuidFactory; private final MetadataIndex metadataIndex; private final RuleDescriptionSectionsGeneratorResolver ruleDescriptionSectionsGeneratorResolver; public RegisterRules(RuleDefinitionsLoader defLoader, QProfileRules qProfileRules, DbClient dbClient, RuleIndexer ruleIndexer, ActiveRuleIndexer activeRuleIndexer, Languages languages, System2 system2, WebServerRuleFinder webServerRuleFinder, UuidFactory uuidFactory, MetadataIndex metadataIndex, RuleDescriptionSectionsGeneratorResolver ruleDescriptionSectionsGeneratorResolver) { this.defLoader = defLoader; this.qProfileRules = qProfileRules; this.dbClient = dbClient; this.ruleIndexer = ruleIndexer; this.activeRuleIndexer = activeRuleIndexer; this.languages = languages; this.system2 = system2; this.webServerRuleFinder = webServerRuleFinder; this.uuidFactory = uuidFactory; this.metadataIndex = metadataIndex; this.ruleDescriptionSectionsGeneratorResolver = ruleDescriptionSectionsGeneratorResolver; } @Override public void start() { Profiler profiler = Profiler.create(LOG).startInfo("Register rules"); try (DbSession dbSession = dbClient.openSession(true)) { RulesDefinition.Context ruleDefinitionContext = defLoader.load(); List<RulesDefinition.Repository> repositories = ruleDefinitionContext.repositories(); RegisterRulesContext registerRulesContext = createRegisterRulesContext(dbSession); verifyRuleKeyConsistency(repositories, registerRulesContext); for (RulesDefinition.ExtendedRepository repoDef : repositories) { if (languages.get(repoDef.language()) != null) { registerRules(registerRulesContext, repoDef.rules(), dbSession); dbSession.commit(); } } processRemainingDbRules(registerRulesContext, dbSession); List<ActiveRuleChange> changes = removeActiveRulesOnStillExistingRepositories(dbSession, registerRulesContext, repositories); dbSession.commit(); persistRepositories(dbSession, ruleDefinitionContext.repositories()); // FIXME lack of resiliency, active rules index is corrupted if rule index fails // to be updated. Only a single DB commit should be executed. ruleIndexer.commitAndIndex(dbSession, registerRulesContext.getAllModified().map(RuleDto::getUuid).collect(Collectors.toSet())); changes.forEach(arChange -> dbClient.qProfileChangeDao().insert(dbSession, arChange.toDto(null))); activeRuleIndexer.commitAndIndex(dbSession, changes); registerRulesContext.getRenamed().forEach(e -> LOG.info("Rule {} re-keyed to {}", e.getValue(), e.getKey().getKey())); profiler.stopDebug(); if (!registerRulesContext.hasDbRules()) { Stream.concat(ruleIndexer.getIndexTypes().stream(), activeRuleIndexer.getIndexTypes().stream()) .forEach(t -> metadataIndex.setInitialized(t, true)); } webServerRuleFinder.startCaching(); } } private RegisterRulesContext createRegisterRulesContext(DbSession dbSession) { Map<RuleKey, RuleDto> allRules = dbClient.ruleDao().selectAll(dbSession).stream() .collect(Collectors.toMap(RuleDto::getKey, Function.identity())); Map<String, Set<SingleDeprecatedRuleKey>> existingDeprecatedKeysById = loadDeprecatedRuleKeys(dbSession); Map<String, List<RuleParamDto>> ruleParamsByRuleUuid = loadAllRuleParameters(dbSession); return new RegisterRulesContext(allRules, existingDeprecatedKeysById, ruleParamsByRuleUuid); } private Map<String, List<RuleParamDto>> loadAllRuleParameters(DbSession dbSession) { return dbClient.ruleDao().selectAllRuleParams(dbSession).stream() .collect(Collectors.groupingBy(RuleParamDto::getRuleUuid)); } private Map<String, Set<SingleDeprecatedRuleKey>> loadDeprecatedRuleKeys(DbSession dbSession) { return dbClient.ruleDao().selectAllDeprecatedRuleKeys(dbSession).stream() .map(SingleDeprecatedRuleKey::from) .collect(Collectors.groupingBy(SingleDeprecatedRuleKey::getRuleUuid, Collectors.toSet())); } private static class RegisterRulesContext { // initial immutable data private final Map<RuleKey, RuleDto> dbRules; private final Set<RuleDto> known; private final Map<String, Set<SingleDeprecatedRuleKey>> dbDeprecatedKeysByUuid; private final Map<String, List<RuleParamDto>> ruleParamsByRuleUuid; private final Map<RuleKey, RuleDto> dbRulesByDbDeprecatedKey; // mutable data private final Set<RuleDto> created = new HashSet<>(); private final Map<RuleDto, RuleKey> renamed = new HashMap<>(); private final Set<RuleDto> updated = new HashSet<>(); private final Set<RuleDto> unchanged = new HashSet<>(); private final Set<RuleDto> removed = new HashSet<>(); private RegisterRulesContext(Map<RuleKey, RuleDto> dbRules, Map<String, Set<SingleDeprecatedRuleKey>> dbDeprecatedKeysByUuid, Map<String, List<RuleParamDto>> ruleParamsByRuleUuid) { this.dbRules = ImmutableMap.copyOf(dbRules); this.known = ImmutableSet.copyOf(dbRules.values()); this.dbDeprecatedKeysByUuid = dbDeprecatedKeysByUuid; this.ruleParamsByRuleUuid = ruleParamsByRuleUuid; this.dbRulesByDbDeprecatedKey = buildDbRulesByDbDeprecatedKey(dbDeprecatedKeysByUuid, dbRules); } private static Map<RuleKey, RuleDto> buildDbRulesByDbDeprecatedKey(Map<String, Set<SingleDeprecatedRuleKey>> dbDeprecatedKeysByUuid, Map<RuleKey, RuleDto> dbRules) { Map<String, RuleDto> dbRulesByRuleUuid = dbRules.values().stream() .collect(Collectors.toMap(RuleDto::getUuid, Function.identity())); Map<RuleKey, RuleDto> rulesByKey = new LinkedHashMap<>(); for (Map.Entry<String, Set<SingleDeprecatedRuleKey>> entry : dbDeprecatedKeysByUuid.entrySet()) { String ruleUuid = entry.getKey(); RuleDto rule = dbRulesByRuleUuid.get(ruleUuid); if (rule == null) { LOG.warn("Could not retrieve rule with uuid %s referenced by a deprecated rule key. " + "The following deprecated rule keys seem to be referencing a non-existing rule", ruleUuid, entry.getValue()); } else { entry.getValue().forEach(d -> rulesByKey.put(d.getOldRuleKeyAsRuleKey(), rule)); } } return unmodifiableMap(rulesByKey); } private boolean hasDbRules() { return !dbRules.isEmpty(); } private Optional<RuleDto> getDbRuleFor(RulesDefinition.Rule ruleDef) { RuleKey ruleKey = RuleKey.of(ruleDef.repository().key(), ruleDef.key()); Optional<RuleDto> res = Stream.concat(Stream.of(ruleKey), ruleDef.deprecatedRuleKeys().stream()) .map(dbRules::get) .filter(Objects::nonNull) .findFirst(); // may occur in case of plugin downgrade if (res.isEmpty()) { return Optional.ofNullable(dbRulesByDbDeprecatedKey.get(ruleKey)); } return res; } private Map<RuleKey, SingleDeprecatedRuleKey> getDbDeprecatedKeysByOldRuleKey() { return dbDeprecatedKeysByUuid.values().stream() .flatMap(Collection::stream) .collect(Collectors.toMap(SingleDeprecatedRuleKey::getOldRuleKeyAsRuleKey, Function.identity())); } private Set<SingleDeprecatedRuleKey> getDBDeprecatedKeysFor(RuleDto rule) { return dbDeprecatedKeysByUuid.getOrDefault(rule.getUuid(), emptySet()); } private List<RuleParamDto> getRuleParametersFor(String ruleUuid) { return ruleParamsByRuleUuid.getOrDefault(ruleUuid, emptyList()); } private Stream<RuleDto> getRemaining() { Set<RuleDto> res = new HashSet<>(dbRules.values()); res.removeAll(unchanged); res.removeAll(renamed.keySet()); res.removeAll(updated); res.removeAll(removed); return res.stream(); } private Stream<RuleDto> getRemoved() { return removed.stream(); } public Stream<Map.Entry<RuleDto, RuleKey>> getRenamed() { return renamed.entrySet().stream(); } private Stream<RuleDto> getAllModified() { return Stream.of( created.stream(), updated.stream(), removed.stream(), renamed.keySet().stream()) .flatMap(s -> s); } private boolean isCreated(RuleDto ruleDto) { return created.contains(ruleDto); } private boolean isRenamed(RuleDto ruleDto) { return renamed.containsKey(ruleDto); } private boolean isUpdated(RuleDto ruleDto) { return updated.contains(ruleDto); } private void created(RuleDto ruleDto) { checkState(!known.contains(ruleDto), "known RuleDto can't be created"); created.add(ruleDto); } private void renamed(RuleDto ruleDto) { ensureKnown(ruleDto); renamed.put(ruleDto, ruleDto.getKey()); } private void updated(RuleDto ruleDto) { ensureKnown(ruleDto); updated.add(ruleDto); } private void removed(RuleDto ruleDto) { ensureKnown(ruleDto); removed.add(ruleDto); } private void unchanged(RuleDto ruleDto) { ensureKnown(ruleDto); unchanged.add(ruleDto); } private void ensureKnown(RuleDto ruleDto) { checkState(known.contains(ruleDto), "unknown RuleDto"); } } private void persistRepositories(DbSession dbSession, List<RulesDefinition.Repository> repositories) { List<String> keys = repositories.stream().map(RulesDefinition.Repository::key).toList(); Set<String> existingKeys = dbClient.ruleRepositoryDao().selectAllKeys(dbSession); Map<Boolean, List<RuleRepositoryDto>> dtos = repositories.stream() .map(r -> new RuleRepositoryDto(r.key(), r.language(), r.name())) .collect(Collectors.groupingBy(i -> existingKeys.contains(i.getKey()))); dbClient.ruleRepositoryDao().update(dbSession, dtos.getOrDefault(true, emptyList())); dbClient.ruleRepositoryDao().insert(dbSession, dtos.getOrDefault(false, emptyList())); dbClient.ruleRepositoryDao().deleteIfKeyNotIn(dbSession, keys); dbSession.commit(); } @Override public void stop() { // nothing } private void registerRules(RegisterRulesContext context, List<RulesDefinition.Rule> ruleDefs, DbSession session) { Map<RulesDefinition.Rule, RuleDto> dtos = new LinkedHashMap<>(ruleDefs.size()); for (RulesDefinition.Rule ruleDef : ruleDefs) { RuleKey ruleKey = RuleKey.of(ruleDef.repository().key(), ruleDef.key()); RuleDto ruleDto = findOrCreateRuleDto(context, session, ruleDef); dtos.put(ruleDef, ruleDto); // we must detect renaming __before__ we modify the DTO if (!ruleDto.getKey().equals(ruleKey)) { context.renamed(ruleDto); ruleDto.setRuleKey(ruleKey); } if (anyMerge(ruleDef, ruleDto)) { context.updated(ruleDto); } if (context.isUpdated(ruleDto) || context.isRenamed(ruleDto)) { update(session, ruleDto); } else if (!context.isCreated(ruleDto)) { context.unchanged(ruleDto); } } for (Map.Entry<RulesDefinition.Rule, RuleDto> e : dtos.entrySet()) { mergeParams(context, e.getKey(), e.getValue(), session); updateDeprecatedKeys(context, e.getKey(), e.getValue(), session); } } @Nonnull private RuleDto findOrCreateRuleDto(RegisterRulesContext context, DbSession session, RulesDefinition.Rule ruleDef) { return context.getDbRuleFor(ruleDef) .orElseGet(() -> { RuleDto newRule = createRuleDto(ruleDef, session); context.created(newRule); return newRule; }); } private RuleDto createRuleDto(RulesDefinition.Rule ruleDef, DbSession session) { RuleDto ruleDto = new RuleDto() .setUuid(uuidFactory.create()) .setRuleKey(RuleKey.of(ruleDef.repository().key(), ruleDef.key())) .setPluginKey(ruleDef.pluginKey()) .setIsTemplate(ruleDef.template()) .setConfigKey(ruleDef.internalKey()) .setLanguage(ruleDef.repository().language()) .setName(ruleDef.name()) .setSeverity(ruleDef.severity()) .setStatus(ruleDef.status()) .setGapDescription(ruleDef.gapDescription()) .setSystemTags(ruleDef.tags()) .setSecurityStandards(ruleDef.securityStandards()) .setType(RuleType.valueOf(ruleDef.type().name())) .setScope(toDtoScope(ruleDef.scope())) .setIsExternal(ruleDef.repository().isExternal()) .setIsAdHoc(false) .setCreatedAt(system2.now()) .setUpdatedAt(system2.now()) .setEducationPrinciples(ruleDef.educationPrincipleKeys()); if (isNotEmpty(ruleDef.htmlDescription())) { ruleDto.setDescriptionFormat(Format.HTML); } else if (isNotEmpty(ruleDef.markdownDescription())) { ruleDto.setDescriptionFormat(Format.MARKDOWN); } generateRuleDescriptionSections(ruleDef) .forEach(ruleDto::addRuleDescriptionSectionDto); DebtRemediationFunction debtRemediationFunction = ruleDef.debtRemediationFunction(); if (debtRemediationFunction != null) { ruleDto.setDefRemediationFunction(debtRemediationFunction.type().name()); ruleDto.setDefRemediationGapMultiplier(debtRemediationFunction.gapMultiplier()); ruleDto.setDefRemediationBaseEffort(debtRemediationFunction.baseEffort()); ruleDto.setGapDescription(ruleDef.gapDescription()); } dbClient.ruleDao().insert(session, ruleDto); return ruleDto; } private Set<RuleDescriptionSectionDto> generateRuleDescriptionSections(RulesDefinition.Rule ruleDef) { RuleDescriptionSectionsGenerator descriptionSectionGenerator = ruleDescriptionSectionsGeneratorResolver.getRuleDescriptionSectionsGenerator(ruleDef); return descriptionSectionGenerator.generateSections(ruleDef); } private static Scope toDtoScope(RuleScope scope) { switch (scope) { case ALL: return Scope.ALL; case MAIN: return Scope.MAIN; case TEST: return Scope.TEST; default: throw new IllegalArgumentException("Unknown rule scope: " + scope); } } private boolean anyMerge(RulesDefinition.Rule ruleDef, RuleDto ruleDto) { boolean ruleMerged = mergeRule(ruleDef, ruleDto); boolean debtDefinitionsMerged = mergeDebtDefinitions(ruleDef, ruleDto); boolean tagsMerged = mergeTags(ruleDef, ruleDto); boolean securityStandardsMerged = mergeSecurityStandards(ruleDef, ruleDto); boolean educationPrinciplesMerged = mergeEducationPrinciples(ruleDef, ruleDto); return ruleMerged || debtDefinitionsMerged || tagsMerged || securityStandardsMerged || educationPrinciplesMerged; } private boolean mergeRule(RulesDefinition.Rule def, RuleDto dto) { boolean changed = false; if (!Objects.equals(dto.getName(), def.name())) { dto.setName(def.name()); changed = true; } if (mergeDescription(def, dto)) { changed = true; } if (!Objects.equals(dto.getPluginKey(), def.pluginKey())) { dto.setPluginKey(def.pluginKey()); changed = true; } if (!Objects.equals(dto.getConfigKey(), def.internalKey())) { dto.setConfigKey(def.internalKey()); changed = true; } String severity = def.severity(); if (!Objects.equals(dto.getSeverityString(), severity)) { dto.setSeverity(severity); changed = true; } boolean isTemplate = def.template(); if (isTemplate != dto.isTemplate()) { dto.setIsTemplate(isTemplate); changed = true; } if (def.status() != dto.getStatus()) { dto.setStatus(def.status()); changed = true; } if (!Objects.equals(dto.getScope().name(), def.scope().name())) { dto.setScope(toDtoScope(def.scope())); changed = true; } if (!Objects.equals(dto.getLanguage(), def.repository().language())) { dto.setLanguage(def.repository().language()); changed = true; } RuleType type = RuleType.valueOf(def.type().name()); if (!Objects.equals(dto.getType(), type.getDbConstant())) { dto.setType(type); changed = true; } if (dto.isAdHoc()) { dto.setIsAdHoc(false); changed = true; } return changed; } private boolean mergeDescription(RulesDefinition.Rule rule, RuleDto ruleDto) { Set<RuleDescriptionSectionDto> newRuleDescriptionSectionDtos = generateRuleDescriptionSections(rule); if (ruleDescriptionSectionsUnchanged(ruleDto, newRuleDescriptionSectionDtos)) { return false; } ruleDto.replaceRuleDescriptionSectionDtos(newRuleDescriptionSectionDtos); if (containsHtmlDescription(rule)) { ruleDto.setDescriptionFormat(Format.HTML); return true; } else if (isNotEmpty(rule.markdownDescription())) { ruleDto.setDescriptionFormat(Format.MARKDOWN); return true; } return false; } private static boolean containsHtmlDescription(RulesDefinition.Rule rule) { return isNotEmpty(rule.htmlDescription()) || !rule.ruleDescriptionSections().isEmpty(); } private static boolean ruleDescriptionSectionsUnchanged(RuleDto ruleDto, Set<RuleDescriptionSectionDto> newRuleDescriptionSectionDtos) { if (ruleDto.getRuleDescriptionSectionDtos().size() != newRuleDescriptionSectionDtos.size()) { return false; } return ruleDto.getRuleDescriptionSectionDtos().stream() .allMatch(sectionDto -> contains(newRuleDescriptionSectionDtos, sectionDto)); } private static boolean contains(Set<RuleDescriptionSectionDto> sectionDtos, RuleDescriptionSectionDto sectionDto) { return sectionDtos.stream() .filter(s -> s.getKey().equals(sectionDto.getKey()) && s.getContent().equals(sectionDto.getContent())) .anyMatch(s -> Objects.equals(s.getContext(), sectionDto.getContext())); } private static boolean mergeDebtDefinitions(RulesDefinition.Rule def, RuleDto dto) { // Debt definitions are set to null if the sub-characteristic and the remediation function are null DebtRemediationFunction debtRemediationFunction = def.debtRemediationFunction(); boolean hasDebt = debtRemediationFunction != null; if (hasDebt) { return mergeDebtDefinitions(dto, debtRemediationFunction.type().name(), debtRemediationFunction.gapMultiplier(), debtRemediationFunction.baseEffort(), def.gapDescription()); } return mergeDebtDefinitions(dto, null, null, null, null); } private static boolean mergeDebtDefinitions(RuleDto dto, @Nullable String remediationFunction, @Nullable String remediationCoefficient, @Nullable String remediationOffset, @Nullable String gapDescription) { boolean changed = false; if (!Objects.equals(dto.getDefRemediationFunction(), remediationFunction)) { dto.setDefRemediationFunction(remediationFunction); changed = true; } if (!Objects.equals(dto.getDefRemediationGapMultiplier(), remediationCoefficient)) { dto.setDefRemediationGapMultiplier(remediationCoefficient); changed = true; } if (!Objects.equals(dto.getDefRemediationBaseEffort(), remediationOffset)) { dto.setDefRemediationBaseEffort(remediationOffset); changed = true; } if (!Objects.equals(dto.getGapDescription(), gapDescription)) { dto.setGapDescription(gapDescription); changed = true; } return changed; } private void mergeParams(RegisterRulesContext context, RulesDefinition.Rule ruleDef, RuleDto rule, DbSession session) { List<RuleParamDto> paramDtos = context.getRuleParametersFor(rule.getUuid()); Map<String, RuleParamDto> existingParamsByName = new HashMap<>(); Profiler profiler = Profiler.create(Loggers.get(getClass())); for (RuleParamDto paramDto : paramDtos) { RulesDefinition.Param paramDef = ruleDef.param(paramDto.getName()); if (paramDef == null) { profiler.start(); dbClient.activeRuleDao().deleteParamsByRuleParam(session, paramDto); profiler.stopDebug(format("Propagate deleted param with name %s to active rules of rule %s", paramDto.getName(), rule.getKey())); dbClient.ruleDao().deleteRuleParam(session, paramDto.getUuid()); } else { if (mergeParam(paramDto, paramDef)) { dbClient.ruleDao().updateRuleParam(session, rule, paramDto); } existingParamsByName.put(paramDto.getName(), paramDto); } } // Create newly parameters for (RulesDefinition.Param param : ruleDef.params()) { RuleParamDto paramDto = existingParamsByName.get(param.key()); if (paramDto != null) { continue; } paramDto = RuleParamDto.createFor(rule) .setName(param.key()) .setDescription(param.description()) .setDefaultValue(param.defaultValue()) .setType(param.type().toString()); dbClient.ruleDao().insertRuleParam(session, rule, paramDto); if (StringUtils.isEmpty(param.defaultValue())) { continue; } // Propagate the default value to existing active rule parameters profiler.start(); for (ActiveRuleDto activeRule : dbClient.activeRuleDao().selectByRuleUuid(session, rule.getUuid())) { ActiveRuleParamDto activeParam = ActiveRuleParamDto.createFor(paramDto).setValue(param.defaultValue()); dbClient.activeRuleDao().insertParam(session, activeRule, activeParam); } profiler.stopDebug(format("Propagate new param with name %s to active rules of rule %s", paramDto.getName(), rule.getKey())); } } private static boolean mergeParam(RuleParamDto paramDto, RulesDefinition.Param paramDef) { boolean changed = false; if (!Objects.equals(paramDto.getType(), paramDef.type().toString())) { paramDto.setType(paramDef.type().toString()); changed = true; } if (!Objects.equals(paramDto.getDefaultValue(), paramDef.defaultValue())) { paramDto.setDefaultValue(paramDef.defaultValue()); changed = true; } if (!Objects.equals(paramDto.getDescription(), paramDef.description())) { paramDto.setDescription(paramDef.description()); changed = true; } return changed; } private void updateDeprecatedKeys(RegisterRulesContext context, RulesDefinition.Rule ruleDef, RuleDto rule, DbSession dbSession) { Set<SingleDeprecatedRuleKey> deprecatedRuleKeysFromDefinition = SingleDeprecatedRuleKey.from(ruleDef); Set<SingleDeprecatedRuleKey> deprecatedRuleKeysFromDB = context.getDBDeprecatedKeysFor(rule); // DeprecatedKeys that must be deleted List<String> uuidsToBeDeleted = difference(deprecatedRuleKeysFromDB, deprecatedRuleKeysFromDefinition).stream() .map(SingleDeprecatedRuleKey::getUuid) .toList(); dbClient.ruleDao().deleteDeprecatedRuleKeys(dbSession, uuidsToBeDeleted); // DeprecatedKeys that must be created Sets.SetView<SingleDeprecatedRuleKey> deprecatedRuleKeysToBeCreated = difference(deprecatedRuleKeysFromDefinition, deprecatedRuleKeysFromDB); deprecatedRuleKeysToBeCreated .forEach(r -> dbClient.ruleDao().insert(dbSession, new DeprecatedRuleKeyDto() .setUuid(uuidFactory.create()) .setRuleUuid(rule.getUuid()) .setOldRepositoryKey(r.getOldRepositoryKey()) .setOldRuleKey(r.getOldRuleKey()) .setCreatedAt(system2.now()))); } private static boolean mergeTags(RulesDefinition.Rule ruleDef, RuleDto dto) { boolean changed = false; if (RuleStatus.REMOVED == ruleDef.status()) { dto.setSystemTags(emptySet()); changed = true; } else if (dto.getSystemTags().size() != ruleDef.tags().size() || !dto.getSystemTags().containsAll(ruleDef.tags())) { dto.setSystemTags(ruleDef.tags()); changed = true; } return changed; } private static boolean mergeSecurityStandards(RulesDefinition.Rule ruleDef, RuleDto dto) { boolean changed = false; if (RuleStatus.REMOVED == ruleDef.status()) { dto.setSecurityStandards(emptySet()); changed = true; } else if (dto.getSecurityStandards().size() != ruleDef.securityStandards().size() || !dto.getSecurityStandards().containsAll(ruleDef.securityStandards())) { dto.setSecurityStandards(ruleDef.securityStandards()); changed = true; } return changed; } private static boolean mergeEducationPrinciples(RulesDefinition.Rule ruleDef, RuleDto dto) { boolean changed = false; if (dto.getEducationPrinciples().size() != ruleDef.educationPrincipleKeys().size() || !dto.getEducationPrinciples().containsAll(ruleDef.educationPrincipleKeys())) { dto.setEducationPrinciples(ruleDef.educationPrincipleKeys()); changed = true; } return changed; } private void processRemainingDbRules(RegisterRulesContext recorder, DbSession dbSession) { // custom rules check status of template, so they must be processed at the end List<RuleDto> customRules = new ArrayList<>(); recorder.getRemaining().forEach(rule -> { if (rule.isCustomRule()) { customRules.add(rule); } else if (!rule.isAdHoc() && rule.getStatus() != RuleStatus.REMOVED) { removeRule(dbSession, recorder, rule); } }); for (RuleDto customRule : customRules) { String templateUuid = customRule.getTemplateUuid(); checkNotNull(templateUuid, "Template uuid of the custom rule '%s' is null", customRule); Optional<RuleDto> template = dbClient.ruleDao().selectByUuid(templateUuid, dbSession); if (template.isPresent() && template.get().getStatus() != RuleStatus.REMOVED) { if (updateCustomRuleFromTemplateRule(customRule, template.get())) { recorder.updated(customRule); update(dbSession, customRule); } } else { removeRule(dbSession, recorder, customRule); } } dbSession.commit(); } private void removeRule(DbSession session, RegisterRulesContext recorder, RuleDto rule) { LOG.info(format("Disable rule %s", rule.getKey())); rule.setStatus(RuleStatus.REMOVED); rule.setSystemTags(emptySet()); update(session, rule); // FIXME resetting the tags for all organizations must be handled a different way // rule.setTags(Collections.emptySet()); // update(session, rule.getMetadata()); recorder.removed(rule); if (recorder.getRemoved().count() % 100 == 0) { session.commit(); } } private static boolean updateCustomRuleFromTemplateRule(RuleDto customRule, RuleDto templateRule) { boolean changed = false; if (!Objects.equals(customRule.getLanguage(), templateRule.getLanguage())) { customRule.setLanguage(templateRule.getLanguage()); changed = true; } if (!Objects.equals(customRule.getConfigKey(), templateRule.getConfigKey())) { customRule.setConfigKey(templateRule.getConfigKey()); changed = true; } if (!Objects.equals(customRule.getPluginKey(), templateRule.getPluginKey())) { customRule.setPluginKey(templateRule.getPluginKey()); changed = true; } if (!Objects.equals(customRule.getDefRemediationFunction(), templateRule.getDefRemediationFunction())) { customRule.setDefRemediationFunction(templateRule.getDefRemediationFunction()); changed = true; } if (!Objects.equals(customRule.getDefRemediationGapMultiplier(), templateRule.getDefRemediationGapMultiplier())) { customRule.setDefRemediationGapMultiplier(templateRule.getDefRemediationGapMultiplier()); changed = true; } if (!Objects.equals(customRule.getDefRemediationBaseEffort(), templateRule.getDefRemediationBaseEffort())) { customRule.setDefRemediationBaseEffort(templateRule.getDefRemediationBaseEffort()); changed = true; } if (!Objects.equals(customRule.getGapDescription(), templateRule.getGapDescription())) { customRule.setGapDescription(templateRule.getGapDescription()); changed = true; } if (customRule.getStatus() != templateRule.getStatus()) { customRule.setStatus(templateRule.getStatus()); changed = true; } if (!Objects.equals(customRule.getSeverityString(), templateRule.getSeverityString())) { customRule.setSeverity(templateRule.getSeverityString()); changed = true; } if (!Objects.equals(customRule.getRepositoryKey(), templateRule.getRepositoryKey())) { customRule.setRepositoryKey(templateRule.getRepositoryKey()); changed = true; } return changed; } /** * SONAR-4642 * <p/> * Remove active rules on repositories that still exists. * <p/> * For instance, if the javascript repository do not provide anymore some rules, active rules related to this rules will be removed. * But if the javascript repository do not exists anymore, then related active rules will not be removed. * <p/> * The side effect of this approach is that extended repositories will not be managed the same way. * If an extended repository do not exists anymore, then related active rules will be removed. */ private List<ActiveRuleChange> removeActiveRulesOnStillExistingRepositories(DbSession dbSession, RegisterRulesContext recorder, List<RulesDefinition.Repository> context) { Set<String> existingAndRenamedRepositories = getExistingAndRenamedRepositories(recorder, context); List<ActiveRuleChange> changes = new ArrayList<>(); Profiler profiler = Profiler.create(Loggers.get(getClass())); recorder.getRemoved() .filter(rule -> existingAndRenamedRepositories.contains(rule.getRepositoryKey())) .forEach(rule -> { // SONAR-4642 Remove active rules only when repository still exists profiler.start(); changes.addAll(qProfileRules.deleteRule(dbSession, rule)); profiler.stopDebug(format("Remove active rule for rule %s", rule.getKey())); }); return changes; } private static Set<String> getExistingAndRenamedRepositories(RegisterRulesContext recorder, Collection<RulesDefinition.Repository> context) { return Stream.concat( context.stream().map(RulesDefinition.ExtendedRepository::key), recorder.getRenamed().map(Map.Entry::getValue).map(RuleKey::repository)) .collect(Collectors.toSet()); } private void update(DbSession session, RuleDto rule) { rule.setUpdatedAt(system2.now()); dbClient.ruleDao().update(session, rule); } private static void verifyRuleKeyConsistency(List<RulesDefinition.Repository> repositories, RegisterRulesContext registerRulesContext) { List<RulesDefinition.Rule> definedRules = repositories.stream() .flatMap(r -> r.rules().stream()) .toList(); Set<RuleKey> definedRuleKeys = definedRules.stream() .map(r -> RuleKey.of(r.repository().key(), r.key())) .collect(Collectors.toSet()); List<RuleKey> definedDeprecatedRuleKeys = definedRules.stream() .flatMap(r -> r.deprecatedRuleKeys().stream()) .toList(); // Find duplicates in declared deprecated rule keys Set<RuleKey> duplicates = findDuplicates(definedDeprecatedRuleKeys); checkState(duplicates.isEmpty(), "The following deprecated rule keys are declared at least twice [%s]", lazyToString(() -> duplicates.stream().map(RuleKey::toString).collect(Collectors.joining(",")))); // Find rule keys that are both deprecated and used Set<RuleKey> intersection = intersection(new HashSet<>(definedRuleKeys), new HashSet<>(definedDeprecatedRuleKeys)).immutableCopy(); checkState(intersection.isEmpty(), "The following rule keys are declared both as deprecated and used key [%s]", lazyToString(() -> intersection.stream().map(RuleKey::toString).collect(Collectors.joining(",")))); // Find incorrect usage of deprecated keys Map<RuleKey, SingleDeprecatedRuleKey> dbDeprecatedRuleKeysByOldRuleKey = registerRulesContext.getDbDeprecatedKeysByOldRuleKey(); Set<String> incorrectRuleKeyMessage = definedRules.stream() .flatMap(r -> filterInvalidDeprecatedRuleKeys(dbDeprecatedRuleKeysByOldRuleKey, r)) .filter(Objects::nonNull) .collect(Collectors.toSet()); checkState(incorrectRuleKeyMessage.isEmpty(), "An incorrect state of deprecated rule keys has been detected.\n %s", lazyToString(() -> String.join("\n", incorrectRuleKeyMessage))); } private static Stream<String> filterInvalidDeprecatedRuleKeys(Map<RuleKey, SingleDeprecatedRuleKey> dbDeprecatedRuleKeysByOldRuleKey, RulesDefinition.Rule rule) { return rule.deprecatedRuleKeys().stream() .map(rk -> { SingleDeprecatedRuleKey singleDeprecatedRuleKey = dbDeprecatedRuleKeysByOldRuleKey.get(rk); if (singleDeprecatedRuleKey == null) { // new deprecated rule key : OK return null; } RuleKey parentRuleKey = RuleKey.of(rule.repository().key(), rule.key()); if (parentRuleKey.equals(singleDeprecatedRuleKey.getNewRuleKeyAsRuleKey())) { // same parent : OK return null; } if (rule.deprecatedRuleKeys().contains(singleDeprecatedRuleKey.getNewRuleKeyAsRuleKey())) { // the new rule is deprecating the old parentRuleKey : OK return null; } return format("The deprecated rule key [%s] was previously deprecated by [%s]. [%s] should be a deprecated key of [%s],", rk.toString(), singleDeprecatedRuleKey.getNewRuleKeyAsRuleKey().toString(), singleDeprecatedRuleKey.getNewRuleKeyAsRuleKey().toString(), RuleKey.of(rule.repository().key(), rule.key()).toString()); }); } private static Object lazyToString(Supplier<String> toString) { return new Object() { @Override public String toString() { return toString.get(); } }; } private static <T> Set<T> findDuplicates(Collection<T> list) { Set<T> duplicates = new HashSet<>(); Set<T> uniques = new HashSet<>(); list.forEach(t -> { if (!uniques.add(t)) { duplicates.add(t); } }); return duplicates; } }
37,618
40.613938
173
java