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-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/CreateUniqueIndexForReportSchedulesTableTest.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.version.v101; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static org.sonar.server.platform.db.migration.version.v101.AddReportSchedulesTable.TABLE_NAME; import static org.sonar.server.platform.db.migration.version.v101.CreateUniqueIndexForReportSchedulesTable.COLUMN_NAME_BRANCH; import static org.sonar.server.platform.db.migration.version.v101.CreateUniqueIndexForReportSchedulesTable.COLUMN_NAME_PORTFOLIO; import static org.sonar.server.platform.db.migration.version.v101.CreateUniqueIndexForReportSchedulesTable.INDEX_NAME; public class CreateUniqueIndexForReportSchedulesTableTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(CreateUniqueIndexForReportSchedulesTableTest.class, "schema.sql"); private final CreateUniqueIndexForReportSchedulesTable createUniqueIndexForReportSchedulesTable = new CreateUniqueIndexForReportSchedulesTable(db.database()); @Test public void migration_should_create_index() throws SQLException { db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME); createUniqueIndexForReportSchedulesTable.execute(); db.assertUniqueIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME_PORTFOLIO, COLUMN_NAME_BRANCH); } @Test public void migration_should_be_reentrant() throws SQLException { createUniqueIndexForReportSchedulesTable.execute(); createUniqueIndexForReportSchedulesTable.execute(); db.assertUniqueIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME_PORTFOLIO, COLUMN_NAME_BRANCH); } }
2,432
42.446429
160
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/CreateUniqueIndexForReportSubscriptionsTableTest.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.version.v101; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static org.sonar.server.platform.db.migration.version.v101.AddReportSubscriptionsTable.TABLE_NAME; import static org.sonar.server.platform.db.migration.version.v101.CreateUniqueIndexForReportSubscriptionsTable.COLUMN_NAME_BRANCH; import static org.sonar.server.platform.db.migration.version.v101.CreateUniqueIndexForReportSubscriptionsTable.COLUMN_NAME_PORTFOLIO; import static org.sonar.server.platform.db.migration.version.v101.CreateUniqueIndexForReportSubscriptionsTable.COLUMN_NAME_USER; import static org.sonar.server.platform.db.migration.version.v101.CreateUniqueIndexForReportSubscriptionsTable.INDEX_NAME; public class CreateUniqueIndexForReportSubscriptionsTableTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(CreateUniqueIndexForReportSubscriptionsTableTest.class, "schema.sql"); private final CreateUniqueIndexForReportSubscriptionsTable createUniqueIndexForReportSubscriptionsTable = new CreateUniqueIndexForReportSubscriptionsTable(db.database()); @Test public void migration_should_create_index() throws SQLException { db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME); createUniqueIndexForReportSubscriptionsTable.execute(); db.assertUniqueIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME_PORTFOLIO, COLUMN_NAME_BRANCH, COLUMN_NAME_USER); } @Test public void migration_should_be_reentrant() throws SQLException { createUniqueIndexForReportSubscriptionsTable.execute(); createUniqueIndexForReportSubscriptionsTable.execute(); db.assertUniqueIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME_PORTFOLIO, COLUMN_NAME_BRANCH, COLUMN_NAME_USER); } }
2,645
45.421053
172
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/DbVersion101Test.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.version.v101; import org.junit.Test; import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMigrationNotEmpty; import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMinimumMigrationNumber; public class DbVersion101Test { private final DbVersion101 underTest = new DbVersion101(); @Test public void migrationNumber_starts_at_10_1_000() { verifyMinimumMigrationNumber(underTest, 10_1_000); } @Test public void verify_migration_is_not_empty() { verifyMigrationNotEmpty(underTest); } }
1,463
34.707317
109
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/DropProjectKeyInUserTokensTest.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.version.v101; import java.sql.SQLException; import java.sql.Types; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DdlChange; import static org.sonar.server.platform.db.migration.version.v101.DropProjectKeyInUserTokens.COLUMN_NAME; import static org.sonar.server.platform.db.migration.version.v101.DropProjectKeyInUserTokens.TABLE_NAME; public class DropProjectKeyInUserTokensTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropProjectKeyInUserTokensTest.class, "schema.sql"); private final DdlChange underTest = new DropProjectKeyInUserTokens(db.database()); @Test public void drops_column() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 255, true); underTest.execute(); db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 255, true); underTest.execute(); underTest.execute(); db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME); } }
2,062
38.673077
114
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/DropScmAccountsInUsersTest.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.version.v101; import java.sql.SQLException; import java.sql.Types; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DdlChange; import static org.sonar.server.platform.db.migration.version.v101.DropScmAccountsInUsers.COLUMN_NAME; import static org.sonar.server.platform.db.migration.version.v101.DropScmAccountsInUsers.TABLE_NAME; public class DropScmAccountsInUsersTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropScmAccountsInUsersTest.class, "schema.sql"); private final DdlChange dropScmAccountsInUsers = new DropScmAccountsInUsers(db.database()); @Test public void drops_column() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 4000, true); dropScmAccountsInUsers.execute(); db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 4000, true); dropScmAccountsInUsers.execute(); dropScmAccountsInUsers.execute(); db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME); } }
2,097
38.584906
110
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/FixDifferentUuidsForSubportfoliosTest.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.version.v101; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import org.assertj.core.api.Assertions; import org.junit.Rule; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import org.sonar.db.CoreDbTester; import static java.util.stream.Collectors.toSet; public class FixDifferentUuidsForSubportfoliosTest { private static final String OLD_UUID = "differentSubPfUuid"; private static final String SUB_PF_KEY = "subPfKey"; private static final String NEW_SUBPF_UUID = "subPfUuid"; private static final String PF_UUID = "pfUuid"; private static final String NEW_CHILD_SUBPF_UUID = "childsubpfUuid"; private static final String OLD_CHILD_SUBPF_UUID = "old_child_subpf_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(FixDifferentUuidsForSubportfoliosTest.class, "schema.sql"); private final FixDifferentUuidsForSubportfolios underTest = new FixDifferentUuidsForSubportfolios(db.database()); @Test public void execute_shouldUpdatePortfoliosAndPortfolioProjectsAndPortfolioReferenceTable() throws SQLException { insertPortfolio("pfKey", PF_UUID); insertComponent(SUB_PF_KEY, NEW_SUBPF_UUID, PF_UUID, Qualifiers.SUBVIEW); insertSubPortfolio(SUB_PF_KEY, PF_UUID, PF_UUID, OLD_UUID); insertPortfolioProject("projUuid", OLD_UUID); insertPortfolioReference("refUuid", OLD_UUID); underTest.execute(); Assertions.assertThat(findValueIn("portfolios", "UUID")).containsExactlyInAnyOrder(PF_UUID, NEW_SUBPF_UUID); Assertions.assertThat(findValueIn("portfolio_projects", "PORTFOLIO_UUID")).containsExactlyInAnyOrder(NEW_SUBPF_UUID); Assertions.assertThat(findValueIn("portfolio_references", "PORTFOLIO_UUID")).containsExactlyInAnyOrder(NEW_SUBPF_UUID); } @Test public void execute_shouldBeRentrant() throws SQLException { insertPortfolio("pfKey", PF_UUID); insertComponent(SUB_PF_KEY, NEW_SUBPF_UUID, PF_UUID, Qualifiers.SUBVIEW); insertSubPortfolio(SUB_PF_KEY, PF_UUID, PF_UUID, OLD_UUID); insertPortfolioProject("projUuid", OLD_UUID); insertPortfolioReference("refUuid", OLD_UUID); underTest.execute(); underTest.execute(); Assertions.assertThat(findValueIn("portfolios", "UUID")).containsExactlyInAnyOrder(PF_UUID, NEW_SUBPF_UUID); Assertions.assertThat(findValueIn("portfolio_projects", "PORTFOLIO_UUID")).containsExactlyInAnyOrder(NEW_SUBPF_UUID); Assertions.assertThat(findValueIn("portfolio_references", "PORTFOLIO_UUID")).containsExactlyInAnyOrder(NEW_SUBPF_UUID); } @Test public void execute_shouldFixUuidForSubPortfolioAtDifferentLevels() throws SQLException { insertPortfolio("pfKey", PF_UUID); insertComponent(SUB_PF_KEY, NEW_SUBPF_UUID, PF_UUID, Qualifiers.SUBVIEW); insertComponent("child_subpfkey", NEW_CHILD_SUBPF_UUID, PF_UUID, Qualifiers.SUBVIEW); insertSubPortfolio(SUB_PF_KEY, PF_UUID, PF_UUID, OLD_UUID); insertSubPortfolio("child_subpfkey", OLD_UUID, PF_UUID, OLD_CHILD_SUBPF_UUID); insertPortfolioProject("projUuid", OLD_CHILD_SUBPF_UUID); insertPortfolioReference("refUuid", OLD_CHILD_SUBPF_UUID); underTest.execute(); Assertions.assertThat(findValueIn("portfolios", "UUID")).containsExactlyInAnyOrder(PF_UUID, NEW_SUBPF_UUID, NEW_CHILD_SUBPF_UUID); Assertions.assertThat(findValueIn("portfolios", "PARENT_UUID")).containsExactlyInAnyOrder(null, PF_UUID, NEW_SUBPF_UUID); Assertions.assertThat(findValueIn("portfolio_projects", "PORTFOLIO_UUID")).containsExactlyInAnyOrder(NEW_CHILD_SUBPF_UUID); Assertions.assertThat(findValueIn("portfolio_references", "PORTFOLIO_UUID")).containsExactlyInAnyOrder(NEW_CHILD_SUBPF_UUID); } private Set<String> findValueIn(String table, String field) { return db.select(String.format("select %s FROM %s", field, table)) .stream() .map(row -> (String) row.get(field)) .collect(toSet()); } private String insertComponent(String key, String uuid, String branchUuid, String qualifier) { Map<String, Object> map = new HashMap<>(); map.put("UUID", uuid); map.put("KEE", key); map.put("BRANCH_UUID", branchUuid); map.put("UUID_PATH", "." + uuid + "."); map.put("QUALIFIER", qualifier); map.put("ENABLED", true); map.put("PRIVATE", true); db.executeInsert("components", map); return uuid; } private String insertPortfolio(String kee, String uuid) { return insertSubPortfolio(kee, uuid, uuid); } private String insertSubPortfolio(String kee, String rootUuid, String uuid) { return insertSubPortfolio(kee, null, rootUuid, uuid); } private String insertSubPortfolio(String kee, @Nullable String parentUuid, String rootUuid, String uuid) { Map<String, Object> map = new HashMap<>(); map.put("UUID", uuid); map.put("KEE", kee); map.put("NAME", uuid); map.put("ROOT_UUID", rootUuid); map.put("PRIVATE", false); map.put("SELECTION_MODE", "MANUAL"); map.put("PARENT_UUID", parentUuid); map.put("CREATED_AT", System.currentTimeMillis()); map.put("UPDATED_AT", System.currentTimeMillis()); db.executeInsert("portfolios", map); return uuid; } private String insertPortfolioReference(String uuid, String portfolioUuid) { Map<String, Object> map = new HashMap<>(); map.put("UUID", uuid); map.put("PORTFOLIO_UUID", portfolioUuid); map.put("REFERENCE_UUID", "reference"); map.put("CREATED_AT", System.currentTimeMillis()); db.executeInsert("portfolio_references", map); return uuid; } private String insertPortfolioProject(String uuid, String portfolioUuid) { Map<String, Object> map = new HashMap<>(); map.put("UUID", uuid); map.put("PORTFOLIO_UUID", portfolioUuid); map.put("PROJECT_UUID", portfolioUuid); map.put("CREATED_AT", System.currentTimeMillis()); db.executeInsert("portfolio_projects", map); return uuid; } }
6,848
40.011976
134
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/IncreaseKeeColumnSizeInInternalPropertiesTest.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.version.v101; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static java.sql.Types.VARCHAR; import static org.sonar.server.platform.db.migration.version.v101.IncreaseKeeColumnSizeInInternalProperties.COLUMN_NAME; import static org.sonar.server.platform.db.migration.version.v101.IncreaseKeeColumnSizeInInternalProperties.NEW_COLUMN_SIZE; import static org.sonar.server.platform.db.migration.version.v101.IncreaseKeeColumnSizeInInternalProperties.TABLE_NAME; public class IncreaseKeeColumnSizeInInternalPropertiesTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(IncreaseKeeColumnSizeInInternalPropertiesTest.class, "schema.sql"); private final IncreaseKeeColumnSizeInInternalProperties underTest = new IncreaseKeeColumnSizeInInternalProperties(db.database()); @Test public void execute_increaseColumnSize() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, 20, false); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, NEW_COLUMN_SIZE, false); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, 20, false); underTest.execute(); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, NEW_COLUMN_SIZE, false); } }
2,313
41.851852
131
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/IncreaseTaskTypeColumnSizeInCeActivityTest.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.version.v101; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static java.sql.Types.VARCHAR; import static org.sonar.server.platform.db.migration.version.v101.IncreaseTaskTypeColumnSizeInCeActivity.COLUMN_NAME; import static org.sonar.server.platform.db.migration.version.v101.IncreaseTaskTypeColumnSizeInCeActivity.NEW_COLUMN_SIZE; import static org.sonar.server.platform.db.migration.version.v101.IncreaseTaskTypeColumnSizeInCeActivity.TABLE_NAME; public class IncreaseTaskTypeColumnSizeInCeActivityTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(IncreaseTaskTypeColumnSizeInCeActivityTest.class, "schema.sql"); private final IncreaseTaskTypeColumnSizeInCeActivity underTest = new IncreaseTaskTypeColumnSizeInCeActivity(db.database()); @Test public void execute_increaseColumnSize() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, 15, false); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, NEW_COLUMN_SIZE, false); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, 15, false); underTest.execute(); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, NEW_COLUMN_SIZE, false); } }
2,292
41.462963
126
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/IncreaseTaskTypeColumnSizeInCeQueueTest.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.version.v101; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static java.sql.Types.VARCHAR; import static org.sonar.server.platform.db.migration.version.v101.IncreaseTaskTypeColumnSizeInCeQueue.COLUMN_NAME; import static org.sonar.server.platform.db.migration.version.v101.IncreaseTaskTypeColumnSizeInCeQueue.NEW_COLUMN_SIZE; import static org.sonar.server.platform.db.migration.version.v101.IncreaseTaskTypeColumnSizeInCeQueue.TABLE_NAME; public class IncreaseTaskTypeColumnSizeInCeQueueTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(IncreaseTaskTypeColumnSizeInCeQueueTest.class, "schema.sql"); private final IncreaseTaskTypeColumnSizeInCeQueue underTest = new IncreaseTaskTypeColumnSizeInCeQueue(db.database()); @Test public void execute_increaseColumnSize() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, 15, false); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, NEW_COLUMN_SIZE, false); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, 15, false); underTest.execute(); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, VARCHAR, NEW_COLUMN_SIZE, false); } }
2,271
41.074074
123
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/MigrateScmAccountsFromUsersToScmAccountsTest.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.version.v101; import java.sql.SQLException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DataChange; import org.sonar.server.platform.db.migration.version.v101.MigrateScmAccountsFromUsersToScmAccounts.ScmAccountRow; import static java.lang.String.format; import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.sonar.server.platform.db.migration.version.v101.MigrateScmAccountsFromUsersToScmAccounts.SCM_ACCOUNTS_SEPARATOR_CHAR; public class MigrateScmAccountsFromUsersToScmAccountsTest { private static final UuidFactory UUID_FACTORY = UuidFactoryFast.getInstance(); private static final String SCM_ACCOUNT1 = "scmaccount"; private static final String SCM_ACCOUNT2 = "scmaccount2"; private static final String SCM_ACCOUNT_CAMELCASE = "scmAccount3"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(MigrateScmAccountsFromUsersToScmAccountsTest.class, "schema.sql"); private final DataChange migrateScmAccountsFromUsersToScmAccounts = new MigrateScmAccountsFromUsersToScmAccounts(db.database()); @Test public void execute_whenUserHasNullScmAccounts_doNotInsertInScmAccounts() throws SQLException { insertUserAndGetUuid(null); migrateScmAccountsFromUsersToScmAccounts.execute(); Set<ScmAccountRow> scmAccounts = findAllScmAccounts(); assertThat(scmAccounts).isEmpty(); } @Test public void execute_whenUserHasEmptyScmAccounts_doNotInsertInScmAccounts() throws SQLException { insertUserAndGetUuid(""); migrateScmAccountsFromUsersToScmAccounts.execute(); Set<ScmAccountRow> scmAccounts = findAllScmAccounts(); assertThat(scmAccounts).isEmpty(); } @Test public void execute_whenUserHasEmptyScmAccountsWithOneSeparator_doNotInsertInScmAccounts() throws SQLException { insertUserAndGetUuid(String.valueOf(SCM_ACCOUNTS_SEPARATOR_CHAR)); migrateScmAccountsFromUsersToScmAccounts.execute(); Set<ScmAccountRow> scmAccounts = findAllScmAccounts(); assertThat(scmAccounts).isEmpty(); } @Test public void execute_whenUserHasEmptyScmAccountsWithTwoSeparators_doNotInsertInScmAccounts() throws SQLException { insertUserAndGetUuid(SCM_ACCOUNTS_SEPARATOR_CHAR + String.valueOf(SCM_ACCOUNTS_SEPARATOR_CHAR)); migrateScmAccountsFromUsersToScmAccounts.execute(); Set<ScmAccountRow> scmAccounts = findAllScmAccounts(); assertThat(scmAccounts).isEmpty(); } @Test public void execute_whenUserHasOneScmAccountWithoutSeparator_insertsInScmAccounts() throws SQLException { String userUuid = insertUserAndGetUuid(SCM_ACCOUNT1); migrateScmAccountsFromUsersToScmAccounts.execute(); Set<ScmAccountRow> scmAccounts = findAllScmAccounts(); assertThat(scmAccounts).containsExactly(new ScmAccountRow(userUuid, SCM_ACCOUNT1)); } @Test public void execute_whenUserHasOneScmAccountWithSeparators_insertsInScmAccounts() throws SQLException { String userUuid = insertUserAndGetUuid(format("%s%s%s", SCM_ACCOUNTS_SEPARATOR_CHAR, SCM_ACCOUNT1, SCM_ACCOUNTS_SEPARATOR_CHAR)); migrateScmAccountsFromUsersToScmAccounts.execute(); Set<ScmAccountRow> scmAccounts = findAllScmAccounts(); assertThat(scmAccounts).containsExactly(new ScmAccountRow(userUuid, SCM_ACCOUNT1)); } @Test public void execute_whenUserHasOneScmAccountWithMixedCase_insertsInScmAccountsInLowerCase() throws SQLException { String userUuid = insertUserAndGetUuid(format("%s%s%s", SCM_ACCOUNTS_SEPARATOR_CHAR, SCM_ACCOUNT_CAMELCASE, SCM_ACCOUNTS_SEPARATOR_CHAR)); migrateScmAccountsFromUsersToScmAccounts.execute(); Set<ScmAccountRow> scmAccounts = findAllScmAccounts(); assertThat(scmAccounts).containsExactly(new ScmAccountRow(userUuid, SCM_ACCOUNT_CAMELCASE.toLowerCase(Locale.ENGLISH))); } @Test public void execute_whenUserHasTwoScmAccount_insertsInScmAccounts() throws SQLException { String userUuid = insertUserAndGetUuid(format("%s%s%s%s%s", SCM_ACCOUNTS_SEPARATOR_CHAR, SCM_ACCOUNT1, SCM_ACCOUNTS_SEPARATOR_CHAR, SCM_ACCOUNT2, SCM_ACCOUNTS_SEPARATOR_CHAR)); migrateScmAccountsFromUsersToScmAccounts.execute(); Set<ScmAccountRow> scmAccounts = findAllScmAccounts(); assertThat(scmAccounts).containsExactlyInAnyOrder( new ScmAccountRow(userUuid, SCM_ACCOUNT1), new ScmAccountRow(userUuid, SCM_ACCOUNT2) ); } @Test public void migration_should_be_reentrant() throws SQLException { String userUuid = insertUserAndGetUuid(SCM_ACCOUNT1); migrateScmAccountsFromUsersToScmAccounts.execute(); migrateScmAccountsFromUsersToScmAccounts.execute(); Set<ScmAccountRow> scmAccounts = findAllScmAccounts(); assertThat(scmAccounts).containsExactly(new ScmAccountRow(userUuid, SCM_ACCOUNT1)); } @Test public void migration_should_be_reentrant_if_scm_account_column_dropped() { db.executeDdl("alter table users drop column scm_accounts"); assertThatNoException().isThrownBy(migrateScmAccountsFromUsersToScmAccounts::execute); } private Set<ScmAccountRow> findAllScmAccounts() { Set<ScmAccountRow> scmAccounts = db.select("select user_uuid USERUUID, scm_account SCMACCOUNT from scm_accounts") .stream() .map(row -> new ScmAccountRow((String) row.get("USERUUID"), (String) row.get("SCMACCOUNT"))) .collect(toSet()); return scmAccounts; } private String insertUserAndGetUuid(@Nullable String scmAccounts) { Map<String, Object> map = new HashMap<>(); String uuid = UUID_FACTORY.create(); String login = "login_" + uuid; map.put("UUID", uuid); map.put("LOGIN", login); map.put("HASH_METHOD", "tagada"); map.put("EXTERNAL_LOGIN", login); map.put("EXTERNAL_IDENTITY_PROVIDER", "sonarqube"); map.put("EXTERNAL_ID", login); map.put("CREATED_AT", System.currentTimeMillis()); map.put("RESET_PASSWORD", false); map.put("USER_LOCAL", true); map.put("SCM_ACCOUNTS", scmAccounts); db.executeInsert("users", map); return uuid; } }
7,256
38.227027
142
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/PopulateProjectUuidInUserTokensTest.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.version.v101; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DataChange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; public class PopulateProjectUuidInUserTokensTest { private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); @Rule public CoreDbTester db = CoreDbTester.createForSchema(PopulateProjectUuidInUserTokensTest.class, "schema.sql"); private final DataChange underTest = new PopulateProjectUuidInUserTokens(db.database()); @Test public void migration_populates_project_uuid_for_tokens() throws SQLException { String project1Uuid = insertProject("project1"); String project2Uuid = insertProject("project2"); String token1Uuid = insertUserToken("project1"); String token2Uuid = insertUserToken("project1"); String token3Uuid = insertUserToken("project2"); String token4Uuid = insertUserToken(null); underTest.execute(); assertThat(db.select("select * from user_tokens")) .extracting(r -> r.get("UUID"), r -> r.get("PROJECT_UUID")) .containsOnly( tuple(token1Uuid, project1Uuid), tuple(token2Uuid, project1Uuid), tuple(token3Uuid, project2Uuid), tuple(token4Uuid, null)); } @Test public void migration_should_be_reentrant() throws SQLException { String project1Uuid = insertProject("project1"); String project2Uuid = insertProject("project2"); String token1Uuid = insertUserToken("project1"); String token2Uuid = insertUserToken("project1"); String token3Uuid = insertUserToken("project2"); String token4Uuid = insertUserToken(null); underTest.execute(); underTest.execute(); assertThat(db.select("select * from user_tokens")) .extracting(r -> r.get("UUID"), r -> r.get("PROJECT_UUID")) .containsOnly( tuple(token1Uuid, project1Uuid), tuple(token2Uuid, project1Uuid), tuple(token3Uuid, project2Uuid), tuple(token4Uuid, null)); } private String insertUserToken(@Nullable String projectKey) { Map<String, Object> map = new HashMap<>(); String uuid = uuidFactory.create(); map.put("UUID", uuid); map.put("USER_UUID", "user" + uuid); map.put("NAME", "name" + uuid); map.put("TOKEN_HASH", "token" + uuid); map.put("CREATED_AT", 1); map.put("PROJECT_KEY", projectKey); map.put("TYPE", "PROJECT_ANALYSIS_TOKEN"); db.executeInsert("user_tokens", map); return uuid; } private String insertProject(String projectKey) { Map<String, Object> map = new HashMap<>(); String uuid = uuidFactory.create(); map.put("UUID", uuid); map.put("KEE", projectKey); map.put("QUALIFIER", "TRK"); map.put("PRIVATE", true); map.put("UPDATED_AT", System.currentTimeMillis()); db.executeInsert("projects", map); return uuid; } }
4,031
34.681416
113
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/PopulateReportSchedulesTest.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.version.v101; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DataChange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class PopulateReportSchedulesTest { @Rule public CoreDbTester db = CoreDbTester.createForSchema(PopulateReportSchedulesTest.class, "schema.sql"); private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); private final DataChange underTest = new PopulateReportSchedules(db.database()); @Test public void execute_shouldPopulateFromPortfolioProperties() throws SQLException { insertPortfolio("uuid1"); insertPortfolioProperty("uuid1", "1234"); underTest.execute(); assertThat(db.select("select * from report_schedules")) .extracting(m -> m.get("PORTFOLIO_UUID"), m -> m.get("BRANCH_UUID"), m -> m.get("LAST_SEND_TIME_IN_MS")) .containsOnly(tuple("uuid1", null, 1234L)); } @Test public void execute_shouldPopulateFromBranchProperties() throws SQLException { insertBranch("uuid1"); insertProjectBranchProperty("uuid1", "1234"); underTest.execute(); assertThat(db.select("select * from report_schedules")) .extracting(m -> m.get("PORTFOLIO_UUID"), m -> m.get("BRANCH_UUID"), m -> m.get("LAST_SEND_TIME_IN_MS")) .containsOnly(tuple(null, "uuid1", 1234L)); } @Test public void execute_whenPropertyMatchesBothBranchAndPortfolio_shouldNotPopulate() throws SQLException { insertBranch("uuid1"); insertPortfolio("uuid1"); insertProjectBranchProperty("uuid1", "1234"); underTest.execute(); underTest.execute(); assertThat(db.select("select * from report_schedules")).isEmpty(); } private void insertPortfolio(String uuid) { db.executeInsert("portfolios", "uuid", uuid, "kee", "kee_" + uuid, "name", "name_" + uuid, "root_uuid", uuid, "private", true, "selection_mode", "manual", "created_at", 1000, "updated_at", 1000 ); } private void insertProjectBranchProperty(String portfolioUuid, String value) { db.executeInsert("properties", "uuid", uuidFactory.create(), "prop_key", "sonar.governance.report.project.branch.lastSendTimeInMs", "is_empty", false, "text_value", value, "created_at", 1000, "entity_uuid", portfolioUuid ); } private void insertPortfolioProperty(String portfolioUuid, String value) { db.executeInsert("properties", "uuid", uuidFactory.create(), "prop_key", "sonar.governance.report.lastSendTimeInMs", "is_empty", false, "text_value", value, "created_at", 1000, "entity_uuid", portfolioUuid ); } private void insertBranch(String uuid) { db.executeInsert("project_branches", "uuid", uuid, "project_uuid", "project_" + uuid, "kee", "kee_" + uuid, "branch_type", "BRANCH", "created_at", "1000", "updated_at", "1000", "need_issue_sync", false, "is_main", true ); } }
4,099
32.064516
110
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/PopulateReportSubscriptionsTest.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.version.v101; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DataChange; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; public class PopulateReportSubscriptionsTest { @Rule public CoreDbTester db = CoreDbTester.createForSchema(PopulateReportSubscriptionsTest.class, "schema.sql"); private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); private final DataChange underTest = new PopulateReportSubscriptions(db.database()); @Test public void execute_shouldPopulateFromPortfolioProperties() throws SQLException { insertPortfolio("uuid1"); insertPortfolioProperty("uuid1", "1234"); underTest.execute(); assertThat(db.select("select * from report_subscriptions")) .extracting(m -> m.get("PORTFOLIO_UUID"), m -> m.get("BRANCH_UUID"), m -> m.get("USER_UUID")) .containsOnly(tuple("uuid1", null, "1234")); } @Test public void execute_shouldPopulateFromBranchProperties() throws SQLException { insertBranch("uuid1"); insertBranchProperty("uuid1", "1234"); underTest.execute(); assertThat(db.select("select * from report_subscriptions")) .extracting(m -> m.get("PORTFOLIO_UUID"), m -> m.get("BRANCH_UUID"), m -> m.get("USER_UUID")) .containsOnly(tuple(null, "uuid1", "1234")); } @Test public void execute_whenPropertyMatchesBothBranchAndPortfolio_shouldNotPopulate() throws SQLException { insertBranch("uuid1"); insertPortfolio("uuid1"); insertBranchProperty("uuid1", "1234"); underTest.execute(); underTest.execute(); assertThat(db.select("select * from report_subscriptions")).isEmpty(); } private void insertPortfolio(String uuid) { db.executeInsert("portfolios", "uuid", uuid, "kee", "kee_" + uuid, "name", "name_" + uuid, "root_uuid", uuid, "private", true, "selection_mode", "manual", "created_at", 1000, "updated_at", 1000 ); } private void insertBranchProperty(String branchUuid, String userUuid){ insertProperty( branchUuid, userUuid, "sonar.governance.report.userNotification"); } private void insertPortfolioProperty(String branchUuid, String userUuid){ insertProperty( branchUuid, userUuid, "sonar.governance.report.project.branch.userNotification"); } private void insertProperty(String componentUuid, String userUuid, String propertyKey) { db.executeInsert("properties", "uuid", uuidFactory.create(), "prop_key", propertyKey, "is_empty", false, "text_value", "true", "created_at", 1000, "entity_uuid", componentUuid, "user_uuid", userUuid ); } private void insertBranch(String uuid) { db.executeInsert("project_branches", "uuid", uuid, "project_uuid", "project_" + uuid, "kee", "kee_" + uuid, "branch_type", "BRANCH", "created_at", "1000", "updated_at", "1000", "need_issue_sync", false, "is_main", true ); } }
4,096
32.581967
109
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/RemoveOrphanUserTokensTest.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.version.v101; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DataChange; import static org.assertj.core.api.Assertions.assertThat; public class RemoveOrphanUserTokensTest { private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); @Rule public CoreDbTester db = CoreDbTester.createForSchema(RemoveOrphanUserTokensTest.class, "schema.sql"); private final DataChange underTest = new RemoveOrphanUserTokens(db.database()); @Test public void migration_deletes_orphan_tokens() throws SQLException { String project1Uuid = insertProject("project1"); String token1Uuid = insertUserToken("project1"); String token2Uuid = insertUserToken("orphan"); String token3Uuid = insertUserToken(null); underTest.execute(); assertThat(db.select("select * from user_tokens")) .extracting(r -> r.get("UUID")) .containsOnly(token1Uuid, token3Uuid); } @Test public void migration_should_be_reentrant() throws SQLException { String project1Uuid = insertProject("project1"); String token1Uuid = insertUserToken("project1"); String token2Uuid = insertUserToken("orphan"); underTest.execute(); underTest.execute(); assertThat(db.select("select * from user_tokens")) .extracting(r -> r.get("UUID")) .containsOnly(token1Uuid); } private String insertUserToken( @Nullable String projectKey) { Map<String, Object> map = new HashMap<>(); String uuid = uuidFactory.create(); map.put("UUID", uuid); map.put("USER_UUID", "user" + uuid); map.put("NAME", "name" + uuid); map.put("TOKEN_HASH", "token" + uuid); map.put("CREATED_AT", 1); map.put("PROJECT_KEY", projectKey); map.put("TYPE", "PROJECT_ANALYSIS_TOKEN"); db.executeInsert("user_tokens", map); return uuid; } private String insertProject(String projectKey) { Map<String, Object> map = new HashMap<>(); String uuid = uuidFactory.create(); map.put("UUID", uuid); map.put("KEE", projectKey); map.put("QUALIFIER", "TRK"); map.put("PRIVATE", true); map.put("UPDATED_AT", System.currentTimeMillis()); db.executeInsert("projects", map); return uuid; } }
3,345
32.79798
104
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/RemoveReportPropertiesTest.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.version.v101; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DataChange; import static org.assertj.core.api.Assertions.assertThat; public class RemoveReportPropertiesTest { private static final String SONAR_GOVERNANCE_REPORT_USER_NOTIFICATION = "sonar.governance.report.userNotification"; private static final String SONAR_GOVERNANCE_REPORT_PROJECT_BRANCH_USER_NOTIFICATION = "sonar.governance.report.project.branch.userNotification"; private static final String SONAR_GOVERNANCE_REPORT_LAST_SEND_TIME_IN_MS = "sonar.governance.report.lastSendTimeInMs"; private static final String SONAR_GOVERNANCE_REPORT_PROJECT_BRANCH_LAST_SEND_TIME_IN_MS = "sonar.governance.report.project.branch.lastSendTimeInMs"; @Rule public CoreDbTester db = CoreDbTester.createForSchema(RemoveReportPropertiesTest.class, "schema.sql"); private final DataChange underTest = new RemoveReportProperties(db.database()); private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); @Test public void execute_shouldRemoveRelevantPropertiesFromTable() throws SQLException { insertProperty( "branch_uuid", "user_uuid", SONAR_GOVERNANCE_REPORT_USER_NOTIFICATION, "true"); insertProperty( "portfolio_uuid", "user_uuid", SONAR_GOVERNANCE_REPORT_PROJECT_BRANCH_USER_NOTIFICATION, "true"); insertProperty( "branch_uuid", "user_uuid", SONAR_GOVERNANCE_REPORT_LAST_SEND_TIME_IN_MS, "12"); insertProperty( "portfolio_uuid", "user_uuid", SONAR_GOVERNANCE_REPORT_PROJECT_BRANCH_LAST_SEND_TIME_IN_MS, "123"); insertProperty( "portfolio_uuid", "user_uuid", "sonar.other.property", "123"); underTest.execute(); assertThat(db.select("select * from properties")).hasSize(1) .extracting(r->r.get("PROP_KEY")).containsExactly("sonar.other.property"); } @Test public void execute_shouldBeIdempotent() throws SQLException { insertProperty( "branch_uuid", "user_uuid", SONAR_GOVERNANCE_REPORT_USER_NOTIFICATION, "true"); insertProperty( "portfolio_uuid", "user_uuid", SONAR_GOVERNANCE_REPORT_PROJECT_BRANCH_USER_NOTIFICATION, "true"); underTest.execute(); underTest.execute(); assertThat(db.select("select * from properties")).isEmpty(); } private void insertProperty(String componentUuid, String userUuid, String propertyKey, String value) { db.executeInsert("properties", "uuid", uuidFactory.create(), "prop_key", propertyKey, "is_empty", false, "text_value", value, "created_at", 1000, "component_uuid", componentUuid, "user_uuid", userUuid ); } }
3,646
43.47561
150
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/RenameColumnComponentUuidInPropertiesTest.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.version.v101; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static java.sql.Types.VARCHAR; public class RenameColumnComponentUuidInPropertiesTest { public static final String TABLE_NAME = "properties"; public static final String NEW_COLUMN_NAME = "entity_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(RenameColumnComponentUuidInPropertiesTest.class, "schema.sql"); private final RenameColumnComponentUuidInProperties underTest = new RenameColumnComponentUuidInProperties(db.database()); @Test public void columnIsRenamed() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } }
1,990
36.566038
125
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v101/UpdateIsMainColumnInProjectBranchesTest.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.version.v101; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import org.junit.Rule; import org.junit.Test; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DataChange; import static org.assertj.core.api.Assertions.assertThat; public class UpdateIsMainColumnInProjectBranchesTest { private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); @Rule public CoreDbTester db = CoreDbTester.createForSchema(UpdateIsMainColumnInProjectBranchesTest.class, "schema.sql"); private final DataChange underTest = new UpdateIsMainColumnInProjectBranches(db.database()); private static int not_random_value_always_incremented = 0; @Test public void migration_updates_is_main_if_row_has_the_same_uuids() throws SQLException { String branchUuid1 = insertProjectBranch(true); String branchUuid2 = insertProjectBranch(false); underTest.execute(); assertBranchIsMain(branchUuid1); assertBranchIsNotMain(branchUuid2); } @Test public void migration_should_be_reentrant() throws SQLException { String branchUuid1 = insertProjectBranch(true); String branchUuid2 = insertProjectBranch(false); underTest.execute(); // re-entrant underTest.execute(); assertBranchIsMain(branchUuid1); assertBranchIsNotMain(branchUuid2); } private void assertBranchIsMain(String branchUuid) { assertBranchIs(branchUuid, true); } private void assertBranchIsNotMain(String branchUuid) { assertBranchIs(branchUuid, false); } private void assertBranchIs(String branchUuid, boolean isMain) { String selectSql = String.format("select is_main from project_branches where uuid='%s'", branchUuid); assertThat(db.select(selectSql).stream() .map(row -> row.get("IS_MAIN")) .toList()) .containsExactlyInAnyOrder(isMain); } private String insertProjectBranch(boolean sameUuids) { Map<String, Object> map = new HashMap<>(); String uuid = uuidFactory.create(); map.put("UUID", uuid); if(sameUuids) { map.put("PROJECT_UUID", uuid); } else { map.put("PROJECT_UUID", "uuid" + not_random_value_always_incremented++); } map.put("KEE", "randomKey"); map.put("BRANCH_TYPE", "BRANCH"); map.put("MERGE_BRANCH_UUID", null); map.put("CREATED_AT", System.currentTimeMillis()); map.put("UPDATED_AT", System.currentTimeMillis()); map.put("PULL_REQUEST_BINARY", null); map.put("EXCLUDE_FROM_PURGE", true); map.put("NEED_ISSUE_SYNC", false); db.executeInsert("project_branches", map); return uuid; } }
3,591
32.886792
117
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/CreateIndexEntityUuidInCeActivityTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class CreateIndexEntityUuidInCeActivityTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(CreateIndexEntityUuidInCeActivityTest.class, "schema.sql"); private final CreateIndexEntityUuidInCeActivity createIndex = new CreateIndexEntityUuidInCeActivity(db.database()); @Test public void migration_should_create_index() throws SQLException { db.assertIndexDoesNotExist("ce_activity", "ce_activity_entity_uuid"); createIndex.execute(); db.assertIndex("ce_activity", "ce_activity_entity_uuid", "entity_uuid"); } @Test public void migration_should_be_reentrant() throws SQLException { createIndex.execute(); createIndex.execute(); db.assertIndex("ce_activity", "ce_activity_entity_uuid", "entity_uuid"); } }
1,794
34.9
121
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/CreateIndexEntityUuidInCeQueueTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class CreateIndexEntityUuidInCeQueueTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(CreateIndexEntityUuidInCeQueueTest.class, "schema.sql"); private final CreateIndexEntityUuidInCeQueue createIndex = new CreateIndexEntityUuidInCeQueue(db.database()); @Test public void migration_should_create_index() throws SQLException { db.assertIndexDoesNotExist("ce_queue", "ce_queue_entity_uuid"); createIndex.execute(); db.assertIndex("ce_queue", "ce_queue_entity_uuid", "entity_uuid"); } @Test public void migration_should_be_reentrant() throws SQLException { createIndex.execute(); createIndex.execute(); db.assertIndex("ce_queue", "ce_queue_entity_uuid", "entity_uuid"); } }
1,764
34.3
118
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/CreateIndexEntityUuidInGroupRolesTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class CreateIndexEntityUuidInGroupRolesTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(CreateIndexEntityUuidInGroupRolesTest.class, "schema.sql"); private final CreateIndexEntityUuidInGroupRoles createIndex = new CreateIndexEntityUuidInGroupRoles(db.database()); @Test public void migration_should_create_index() throws SQLException { db.assertIndexDoesNotExist("group_roles", "group_roles_entity_uuid"); createIndex.execute(); db.assertIndex("group_roles", "group_roles_entity_uuid", "entity_uuid"); } @Test public void migration_should_be_reentrant() throws SQLException { createIndex.execute(); createIndex.execute(); db.assertIndex("group_roles", "group_roles_entity_uuid", "entity_uuid"); } }
1,794
34.9
121
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/CreateIndexEntityUuidInUserRolesTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class CreateIndexEntityUuidInUserRolesTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(CreateIndexEntityUuidInUserRolesTest.class, "schema.sql"); private final CreateIndexEntityUuidInUserRoles createIndex = new CreateIndexEntityUuidInUserRoles(db.database()); @Test public void migration_should_create_index() throws SQLException { db.assertIndexDoesNotExist("user_roles", "user_roles_entity_uuid"); createIndex.execute(); db.assertIndex("user_roles", "user_roles_entity_uuid", "entity_uuid"); } @Test public void migration_should_be_reentrant() throws SQLException { createIndex.execute(); createIndex.execute(); db.assertIndex("user_roles", "user_roles_entity_uuid", "entity_uuid"); } }
1,784
34.7
120
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/CreateIndexProjectUuidInWebhookDeliveriesTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class CreateIndexProjectUuidInWebhookDeliveriesTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(CreateIndexProjectUuidInWebhookDeliveriesTest.class, "schema.sql"); private final CreateIndexProjectUuidInWebhookDeliveries createIndex = new CreateIndexProjectUuidInWebhookDeliveries(db.database()); @Test public void migration_should_create_index() throws SQLException { db.assertIndexDoesNotExist("webhook_deliveries", "wd_project_uuid"); createIndex.execute(); db.assertIndex("webhook_deliveries", "wd_project_uuid", "project_uuid"); } @Test public void migration_should_be_reentrant() throws SQLException { createIndex.execute(); createIndex.execute(); db.assertIndex("webhook_deliveries", "wd_project_uuid", "project_uuid"); } }
1,825
35.52
133
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/CreateIndexRootComponentUuidInSnapshotsTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class CreateIndexRootComponentUuidInSnapshotsTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(CreateIndexRootComponentUuidInSnapshotsTest.class, "schema.sql"); private final CreateIndexRootComponentUuidInSnapshots createIndex = new CreateIndexRootComponentUuidInSnapshots(db.database()); @Test public void migration_should_create_index() throws SQLException { db.assertIndexDoesNotExist("snapshots", "snapshots_root_component_uuid"); createIndex.execute(); db.assertIndex("snapshots", "snapshots_root_component_uuid", "root_component_uuid"); } @Test public void migration_should_be_reentrant() throws SQLException { createIndex.execute(); createIndex.execute(); db.assertIndex("snapshots", "snapshots_root_component_uuid", "root_component_uuid"); } }
1,846
35.94
129
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DbVersion102Test.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.version.v102; import org.junit.Test; import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMigrationNotEmpty; import static org.sonar.server.platform.db.migration.version.DbVersionTestUtils.verifyMinimumMigrationNumber; public class DbVersion102Test { private final DbVersion102 underTest = new DbVersion102(); @Test public void migrationNumber_starts_at_10_2_000() { verifyMinimumMigrationNumber(underTest, 10_2_000); } @Test public void verify_migration_is_not_empty() { verifyMigrationNotEmpty(underTest); } }
1,463
34.707317
109
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DropIndexComponentUuidInGroupRolesTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class DropIndexComponentUuidInGroupRolesTest { private static final String TABLE_NAME = "group_roles"; private static final String COLUMN_NAME = "component_uuid"; private static final String INDEX_NAME = "group_roles_component_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(RenameComponentUuidInGroupRolesTest.class, "schema.sql"); private final RenameComponentUuidInGroupRoles underTest = new RenameComponentUuidInGroupRoles(db.database()); @Test public void index_is_dropped() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } }
1,957
33.350877
119
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DropIndexComponentUuidInSnapshotsTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class DropIndexComponentUuidInSnapshotsTest { private static final String TABLE_NAME = "snapshots"; private static final String COLUMN_NAME = "component_uuid"; private static final String INDEX_NAME = "snapshot_component"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropIndexComponentUuidInSnapshotsTest.class, "schema.sql"); private final DropIndexComponentUuidInSnapshots underTest = new DropIndexComponentUuidInSnapshots(db.database()); @Test public void index_is_dropped() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } }
1,952
33.263158
121
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DropIndexComponentUuidInUserRolesTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class DropIndexComponentUuidInUserRolesTest { private static final String TABLE_NAME = "user_roles"; private static final String COLUMN_NAME = "component_uuid"; private static final String INDEX_NAME = "user_roles_component_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropIndexComponentUuidInUserRolesTest.class, "schema.sql"); private final RenameComponentUuidInUserRoles underTest = new RenameComponentUuidInUserRoles(db.database()); @Test public void index_is_dropped() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } }
1,954
33.298246
121
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DropIndexComponentUuidInWebhookDeliveriesTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class DropIndexComponentUuidInWebhookDeliveriesTest { private static final String TABLE_NAME = "webhook_deliveries"; private static final String COLUMN_NAME = "component_uuid"; private static final String INDEX_NAME = "component_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropIndexComponentUuidInWebhookDeliveriesTest.class, "schema.sql"); private final DropIndexComponentUuidInWebhookDeliveries underTest = new DropIndexComponentUuidInWebhookDeliveries(db.database()); @Test public void index_is_dropped() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } }
1,989
33.912281
131
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DropIndexMainComponentUuidInCeActivityTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class DropIndexMainComponentUuidInCeActivityTest { private static final String TABLE_NAME = "ce_activity"; private static final String COLUMN_NAME = "main_component_uuid"; private static final String INDEX_NAME = "ce_activity_main_component"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropIndexMainComponentUuidInCeActivityTest.class, "schema.sql"); private final DropIndexMainComponentUuidInCeActivity underTest = new DropIndexMainComponentUuidInCeActivity(db.database()); @Test public void index_is_dropped() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } }
1,987
33.877193
126
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DropIndexMainComponentUuidInCeQueueTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class DropIndexMainComponentUuidInCeQueueTest { private static final String TABLE_NAME = "ce_queue"; private static final String COLUMN_NAME = "main_component_uuid"; private static final String INDEX_NAME = "ce_queue_main_component"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropIndexMainComponentUuidInCeQueueTest.class, "schema.sql"); private final DropIndexMainComponentUuidInCeQueue underTest = new DropIndexMainComponentUuidInCeQueue(db.database()); @Test public void index_is_dropped() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, COLUMN_NAME); } }
1,969
33.561404
123
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DropIndexOnMainBranchProjectUuidTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DdlChange; public class DropIndexOnMainBranchProjectUuidTest { private static final String TABLE_NAME = "components"; private static final String COLUMN_NAME = "main_branch_project_uuid"; private static final String INDEX_NAME = "idx_main_branch_prj_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropIndexOnMainBranchProjectUuidTest.class, "schema.sql"); private final DdlChange underTest = new DropIndexOnMainBranchProjectUuid(db.database()); @Test public void drops_index() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertIndex(TABLE_NAME, INDEX_NAME, COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertIndexDoesNotExist(TABLE_NAME, INDEX_NAME); } }
1,991
37.307692
120
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DropMainBranchProjectUuidInComponentsTest.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.version.v102; import java.sql.SQLException; import java.sql.Types; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import org.sonar.server.platform.db.migration.step.DdlChange; import static org.sonar.server.platform.db.migration.version.v102.DropMainBranchProjectUuidInComponents.COLUMN_NAME; import static org.sonar.server.platform.db.migration.version.v102.DropMainBranchProjectUuidInComponents.TABLE_NAME; public class DropMainBranchProjectUuidInComponentsTest { @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropMainBranchProjectUuidInComponentsTest.class, "schema.sql"); private final DdlChange underTest = new DropMainBranchProjectUuidInComponents(db.database()); @Test public void drops_column() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 50, true); underTest.execute(); db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDefinition(TABLE_NAME, COLUMN_NAME, Types.VARCHAR, 50, true); underTest.execute(); underTest.execute(); db.assertColumnDoesNotExist(TABLE_NAME, COLUMN_NAME); } }
2,116
38.943396
125
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/DropTableProjectMappingsTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; public class DropTableProjectMappingsTest { public static final String TABLE_NAME = "project_mappings"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(DropTableProjectMappingsTest.class, "schema.sql"); private final DropTableProjectMappings underTest = new DropTableProjectMappings(db.database()); @Test public void execute_shouldDropTable() throws SQLException { db.assertTableExists(TABLE_NAME); underTest.execute(); db.assertTableDoesNotExist(TABLE_NAME); } @Test public void execute_shouldSupportReentrantMigrationExecution() throws SQLException { db.assertTableExists(TABLE_NAME); underTest.execute(); underTest.execute(); db.assertTableDoesNotExist(TABLE_NAME); } }
1,759
34.2
112
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/RenameComponentUuidInGroupRolesTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static java.sql.Types.VARCHAR; public class RenameComponentUuidInGroupRolesTest { public static final String TABLE_NAME = "group_roles"; public static final String NEW_COLUMN_NAME = "entity_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(RenameComponentUuidInGroupRolesTest.class, "schema.sql"); private final RenameComponentUuidInGroupRoles underTest = new RenameComponentUuidInGroupRoles(db.database()); @Test public void columnIsRenamed() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } }
1,967
36.132075
119
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/RenameComponentUuidInSnapshotsTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static java.sql.Types.VARCHAR; public class RenameComponentUuidInSnapshotsTest { public static final String TABLE_NAME = "snapshots"; public static final String NEW_COLUMN_NAME = "root_component_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(RenameComponentUuidInSnapshotsTest.class, "schema.sql"); private final RenameComponentUuidInSnapshots underTest = new RenameComponentUuidInSnapshots(db.database()); @Test public void columnIsRenamed() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 50, false); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 50, false); } }
1,971
36.207547
118
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/RenameComponentUuidInUserRolesTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static java.sql.Types.VARCHAR; public class RenameComponentUuidInUserRolesTest { public static final String TABLE_NAME = "user_roles"; public static final String NEW_COLUMN_NAME = "entity_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(RenameComponentUuidInUserRolesTest.class, "schema.sql"); private final RenameComponentUuidInUserRoles underTest = new RenameComponentUuidInUserRoles(db.database()); @Test public void columnIsRenamed() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } }
1,962
36.037736
118
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/RenameComponentUuidInWebhookDeliveriesTest.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.version.v102; import java.sql.SQLException; import org.junit.Test; import org.sonar.server.platform.db.migration.step.RenameVarcharColumnChange; import org.sonar.server.platform.db.migration.version.RenameVarcharColumnAbstractTest; public class RenameComponentUuidInWebhookDeliveriesTest extends RenameVarcharColumnAbstractTest { public RenameComponentUuidInWebhookDeliveriesTest() { super("webhook_deliveries", "project_uuid", false); } @Test public void migration_is_reentrant() throws SQLException { super.verifyMigrationIsReentrant(); } @Test public void column_is_renamed() throws SQLException { super.verifyColumnIsRenamed(); } @Override protected RenameVarcharColumnChange getClassUnderTest() { return new RenameComponentUuidInWebhookDeliveries(db.database()); } }
1,707
33.857143
97
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/RenameMainComponentUuidInCeActivityTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static java.sql.Types.VARCHAR; public class RenameMainComponentUuidInCeActivityTest { public static final String TABLE_NAME = "ce_activity"; public static final String NEW_COLUMN_NAME = "entity_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(RenameMainComponentUuidInCeActivityTest.class, "schema.sql"); private final RenameMainComponentUuidInCeActivity underTest = new RenameMainComponentUuidInCeActivity(db.database()); @Test public void column_is_renamed() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } }
1,985
36.471698
123
java
sonarqube
sonarqube-master/server/sonar-db-migration/src/test/java/org/sonar/server/platform/db/migration/version/v102/RenameMainComponentUuidInCeQueueTest.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.version.v102; import java.sql.SQLException; import org.junit.Rule; import org.junit.Test; import org.sonar.db.CoreDbTester; import static java.sql.Types.VARCHAR; public class RenameMainComponentUuidInCeQueueTest { public static final String TABLE_NAME = "ce_queue"; public static final String NEW_COLUMN_NAME = "entity_uuid"; @Rule public final CoreDbTester db = CoreDbTester.createForSchema(RenameMainComponentUuidInCeQueueTest.class, "schema.sql"); private final RenameMainComponentUuidInCeQueue underTest = new RenameMainComponentUuidInCeQueue(db.database()); @Test public void column_is_renamed() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } @Test public void migration_is_reentrant() throws SQLException { db.assertColumnDoesNotExist(TABLE_NAME, NEW_COLUMN_NAME); underTest.execute(); underTest.execute(); db.assertColumnDefinition(TABLE_NAME, NEW_COLUMN_NAME, VARCHAR, 40, true); } }
1,970
36.188679
120
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/AbstractStopRequestWatcher.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.application; import com.google.common.annotations.VisibleForTesting; import java.util.function.BooleanSupplier; public abstract class AbstractStopRequestWatcher extends Thread implements StopRequestWatcher { private static final long DEFAULT_WATCHER_DELAY_MS = 500L; private final BooleanSupplier stopRequestedTest; private final Runnable stopAction; private final long delayMs; protected AbstractStopRequestWatcher(String threadName, BooleanSupplier stopRequestedTest, Runnable stopAction) { this(threadName, stopRequestedTest, stopAction, DEFAULT_WATCHER_DELAY_MS); } @VisibleForTesting AbstractStopRequestWatcher(String threadName, BooleanSupplier stopRequestedTest, Runnable stopAction, long delayMs) { super(threadName); this.stopRequestedTest = stopRequestedTest; this.stopAction = stopAction; this.delayMs = delayMs; // safeguard, do not block the JVM if thread is not interrupted // (method stopWatching() never called). setDaemon(true); } @Override public void run() { try { while (true) { if (stopRequestedTest.getAsBoolean()) { stopAction.run(); return; } Thread.sleep(delayMs); } } catch (InterruptedException e) { interrupt(); // stop watching the commands } } @VisibleForTesting long getDelayMs() { return delayMs; } public void startWatching() { start(); } public void stopWatching() { // does nothing if not started interrupt(); } }
2,385
29.987013
119
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/AppFileSystem.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.application; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitOption; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.EnumSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.application.config.AppSettings; import org.sonar.core.util.FileUtils; import org.sonar.process.sharedmemoryfile.AllProcessesCommands; import static java.lang.String.format; import static java.nio.file.FileVisitResult.CONTINUE; import static org.apache.commons.io.FileUtils.forceMkdir; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.ProcessProperties.Property.PATH_WEB; public class AppFileSystem implements FileSystem { private static final Logger LOG = LoggerFactory.getLogger(AppFileSystem.class); private static final EnumSet<FileVisitOption> FOLLOW_LINKS = EnumSet.of(FileVisitOption.FOLLOW_LINKS); private final AppSettings settings; public AppFileSystem(AppSettings settings) { this.settings = settings; } @Override public void reset() throws IOException { createDirectory(PATH_DATA.getKey()); createDirectory(PATH_WEB.getKey()); createDirectory(PATH_LOGS.getKey()); File tempDir = createOrCleanTempDirectory(PATH_TEMP.getKey()); try (AllProcessesCommands allProcessesCommands = new AllProcessesCommands(tempDir)) { allProcessesCommands.clean(); } } @Override public File getTempDir() { return settings.getProps().nonNullValueAsFile(PATH_TEMP.getKey()); } private boolean createDirectory(String propKey) throws IOException { File dir = settings.getProps().nonNullValueAsFile(propKey); if (dir.exists()) { ensureIsNotAFile(propKey, dir); return false; } forceMkdir(dir); ensureIsNotAFile(propKey, dir); return true; } private static void ensureIsNotAFile(String propKey, File dir) { if (!dir.isDirectory()) { throw new IllegalStateException(format("Property '%s' is not valid, not a directory: %s", propKey, dir.getAbsolutePath())); } } private File createOrCleanTempDirectory(String propKey) throws IOException { File dir = settings.getProps().nonNullValueAsFile(propKey); LOG.info("Cleaning or creating temp directory {}", dir.getAbsolutePath()); if (!createDirectory(propKey)) { Files.walkFileTree(dir.toPath(), FOLLOW_LINKS, CleanTempDirFileVisitor.VISIT_MAX_DEPTH, new CleanTempDirFileVisitor(dir.toPath())); } return dir; } private static class CleanTempDirFileVisitor extends SimpleFileVisitor<Path> { private static final Path SHAREDMEMORY_FILE = Paths.get("sharedmemory"); static final int VISIT_MAX_DEPTH = 1; private final Path path; private final boolean symLink; CleanTempDirFileVisitor(Path path) { this.path = path; this.symLink = Files.isSymbolicLink(path); } @Override public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) { if (filePath.getFileName().equals(SHAREDMEMORY_FILE)) { return CONTINUE; } else if (!symLink || !filePath.equals(path)) { FileUtils.deleteQuietly(filePath); } return CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) { if (!dir.equals(path)) { FileUtils.deleteQuietly(dir); } return CONTINUE; } } }
4,580
33.443609
137
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/AppLogging.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.application; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.FileAppender; import ch.qos.logback.core.encoder.Encoder; import javax.annotation.CheckForNull; import org.sonar.application.config.AppSettings; import org.sonar.application.process.StreamGobbler; import org.sonar.process.ProcessId; import org.sonar.process.Props; import org.sonar.process.logging.LogLevelConfig; import org.sonar.process.logging.LogbackHelper; import org.sonar.process.logging.PatternLayoutEncoder; import org.sonar.process.logging.RootLoggerConfig; import static org.slf4j.Logger.ROOT_LOGGER_NAME; import static org.sonar.application.process.StreamGobbler.LOGGER_GOBBLER; import static org.sonar.application.process.StreamGobbler.LOGGER_STARTUP; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.logging.RootLoggerConfig.newRootLoggerConfigBuilder; /** * Configure logback for the APP process. * * <p> * SonarQube's logging use cases: * <ol> * <li> * SQ started as a background process (with {@code sonar.sh start}): * <ul> * <li> * logs produced by the JVM before logback is setup in the APP JVM or which can't be caught by logback * (such as JVM crash) must be written to sonar.log * </li> * <li> * logs produced by the sub process JVMs before logback is setup in the subprocess JVMs or which can't be caught * by logback (such as JVM crash) must be written to sonar.log * </li> * <li>each JVM writes its own logs into its dedicated file</li> * </ul> * </li> * <li> * SQ started in console with wrapper (ie. with {@code sonar.sh console}): * <ul> * <li> * logs produced by the APP JVM before logback is setup in the APP JVM or which can't be caught by logback * (such as JVM crash) must be written to sonar.log * </li> * <li> * logs produced by the sub process JVMs before logback is setup in the subprocess JVMs or which can't be caught * by logback (such as JVM crash) must be written to sonar.log * </li> * <li>each JVM writes its own logs into its dedicated file</li> * <li>APP JVM logs are written to the APP JVM {@code System.out}</li> * </ul> * </li> * <li> * SQ started from command line (ie. {@code java -jar sonar-application-X.Y.jar}): * <ul> * <li> * logs produced by the APP JVM before logback is setup in the APP JVM or which can't be caught by logback * (such as JVM crash) are the responsibility of the user to be dealt with * </li> * <li> * logs produced by the sub process JVMs before logback is setup in the subprocess JVMs or which can't be caught * by logback (such as JVM crash) must be written to APP's {@code System.out} * </li> * <li>each JVM writes its own logs into its dedicated file</li> * <li>APP JVM logs are written to the APP JVM {@code System.out}</li> * </ul> * </li> * <li> * SQ started from an IT (ie. from command line with {@code option -Dsonar.log.console=true}): * <ul> * <li> * logs produced by the APP JVM before logback is setup in the APP JVM or which can't be caught by logback * (such as JVM crash) are the responsibility of the developer or maven to be dealt with * </li> * <li> * logs produced by the sub process JVMs before logback is setup in the subprocess JVMs or which can't be caught * by logback (such as JVM crash) must be written to APP's {@code System.out} and are the responsibility of the * developer or maven to be dealt with * </li> * <li>each JVM writes its own logs into its dedicated file</li> * <li>logs of all 4 JVMs are also written to the APP JVM {@code System.out}</li> * </ul> * </li> * </ol> * </p> * */ public class AppLogging { private static final String CONSOLE_LOGGER = "console"; private static final String CONSOLE_PLAIN_APPENDER = "CONSOLE"; private static final String APP_CONSOLE_APPENDER = "APP_CONSOLE"; private static final String GOBBLER_PLAIN_CONSOLE = "GOBBLER_CONSOLE"; private final RootLoggerConfig rootLoggerConfig; private final LogbackHelper helper = new LogbackHelper(); private final AppSettings appSettings; public AppLogging(AppSettings appSettings) { this.appSettings = appSettings; rootLoggerConfig = newRootLoggerConfigBuilder() .setNodeNameField(getNodeNameWhenCluster(appSettings.getProps())) .setProcessId(ProcessId.APP) .build(); } @CheckForNull private static String getNodeNameWhenCluster(Props props) { boolean clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey(), Boolean.parseBoolean(CLUSTER_ENABLED.getDefaultValue())); return clusterEnabled ? props.value(CLUSTER_NODE_NAME.getKey(), CLUSTER_NODE_NAME.getDefaultValue()) : null; } public LoggerContext configure() { LoggerContext ctx = helper.getRootContext(); ctx.reset(); helper.enableJulChangePropagation(ctx); configureConsole(ctx); configureWithLogbackWritingToFile(ctx); helper.apply( LogLevelConfig.newBuilder(helper.getRootLoggerName()) .rootLevelFor(ProcessId.APP) .immutableLevel("com.hazelcast", Level.toLevel("WARN")) .build(), appSettings.getProps()); return ctx; } /** * Creates a non additive logger dedicated to printing message as is (ie. assuming they are already formatted). * * It creates a dedicated appender to the System.out which applies no formatting the logs it receives. */ private void configureConsole(LoggerContext loggerContext) { Encoder<ILoggingEvent> encoder = createGobblerEncoder(loggerContext); ConsoleAppender<ILoggingEvent> consoleAppender = helper.newConsoleAppender(loggerContext, CONSOLE_PLAIN_APPENDER, encoder); Logger consoleLogger = loggerContext.getLogger(CONSOLE_LOGGER); consoleLogger.setAdditive(false); consoleLogger.addAppender(consoleAppender); } /** * The process has been started by orchestrator (ie. via {@code java -jar} and optionally passing the option {@code -Dsonar.log.console=true}). * Therefor, APP's System.out (and System.err) are <strong>not</strong> copied to sonar.log by the wrapper and * printing to sonar.log must be done at logback level. */ private void configureWithLogbackWritingToFile(LoggerContext ctx) { Logger rootLogger = ctx.getLogger(ROOT_LOGGER_NAME); Encoder<ILoggingEvent> encoder = helper.createEncoder(appSettings.getProps(), rootLoggerConfig, ctx); FileAppender<ILoggingEvent> fileAppender = helper.newFileAppender(ctx, appSettings.getProps(), rootLoggerConfig, encoder); rootLogger.addAppender(fileAppender); rootLogger.addAppender(createAppConsoleAppender(ctx, encoder)); configureGobbler(ctx); configureStartupLogger(ctx, fileAppender, encoder); } private void configureStartupLogger(LoggerContext ctx, FileAppender<ILoggingEvent> fileAppender, Encoder<ILoggingEvent> encoder) { Logger startupLogger = ctx.getLogger(LOGGER_STARTUP); startupLogger.setAdditive(false); startupLogger.addAppender(fileAppender); startupLogger.addAppender(helper.newConsoleAppender(ctx, GOBBLER_PLAIN_CONSOLE, encoder)); } /** * Configure the logger to which logs from sub processes are written to * (called {@link StreamGobbler#LOGGER_GOBBLER}) by {@link StreamGobbler}, * to be: * <ol> * <li>non additive (ie. these logs will be output by the appender of {@link StreamGobbler#LOGGER_GOBBLER} and only this one)</li> * <li>write logs as is (ie. without any extra formatting)</li> * <li>write exclusively to App's System.out</li> * </ol> */ private void configureGobbler(LoggerContext ctx) { Logger gobblerLogger = ctx.getLogger(LOGGER_GOBBLER); gobblerLogger.setAdditive(false); Encoder<ILoggingEvent> encoder = createGobblerEncoder(ctx); gobblerLogger.addAppender(helper.newConsoleAppender(ctx, GOBBLER_PLAIN_CONSOLE, encoder)); } private ConsoleAppender<ILoggingEvent> createAppConsoleAppender(LoggerContext ctx, Encoder<ILoggingEvent> encoder) { return helper.newConsoleAppender(ctx, APP_CONSOLE_APPENDER, encoder); } /** * Simply displays the message received as input. */ private static Encoder<ILoggingEvent> createGobblerEncoder(LoggerContext context) { PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(context); encoder.setPattern("%msg%n"); encoder.start(); return encoder; } }
9,799
41.241379
145
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/AppReloader.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.application; import java.io.IOException; import org.sonar.application.config.AppSettings; /** * Reload settings, reset logging and file system when a * server restart has been requested. */ public interface AppReloader { /** * This method is called when server is down. */ void reload(AppSettings settings) throws IOException; }
1,207
31.648649
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/AppReloaderImpl.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.application; import java.io.IOException; import java.util.Objects; import org.sonar.application.config.AppSettings; import org.sonar.application.config.AppSettingsLoader; import org.sonar.application.config.ClusterSettings; import org.sonar.process.MessageException; import org.sonar.process.Props; import static java.lang.String.format; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.ProcessProperties.Property.PATH_WEB; public class AppReloaderImpl implements AppReloader { private final AppSettingsLoader settingsLoader; private final FileSystem fileSystem; private final AppState appState; private final AppLogging logging; public AppReloaderImpl(AppSettingsLoader settingsLoader, FileSystem fileSystem, AppState appState, AppLogging logging) { this.settingsLoader = settingsLoader; this.fileSystem = fileSystem; this.appState = appState; this.logging = logging; } @Override public void reload(AppSettings settings) throws IOException { if (ClusterSettings.isClusterEnabled(settings)) { throw new IllegalStateException("Restart is not possible with cluster mode"); } AppSettings reloaded = settingsLoader.load(); ensureUnchangedConfiguration(settings.getProps(), reloaded.getProps()); settings.reload(reloaded.getProps()); fileSystem.reset(); logging.configure(); appState.reset(); } private static void ensureUnchangedConfiguration(Props oldProps, Props newProps) { verifyUnchanged(oldProps, newProps, PATH_DATA.getKey()); verifyUnchanged(oldProps, newProps, PATH_WEB.getKey()); verifyUnchanged(oldProps, newProps, PATH_LOGS.getKey()); verifyUnchanged(oldProps, newProps, PATH_TEMP.getKey()); verifyUnchanged(oldProps, newProps, CLUSTER_ENABLED.getKey()); } private static void verifyUnchanged(Props initialProps, Props newProps, String propKey) { String initialValue = initialProps.nonNullValue(propKey); String newValue = newProps.nonNullValue(propKey); if (!Objects.equals(initialValue, newValue)) { throw new MessageException(format("Property [%s] cannot be changed on restart: [%s] => [%s]", propKey, initialValue, newValue)); } } }
3,307
39.341463
134
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/AppState.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.application; import java.util.Optional; import org.sonar.process.ProcessId; public interface AppState extends AutoCloseable { void addListener(AppStateListener listener); /** * Whether the process with the specified {@code processId} * has been marked as operational. * * If parameter {@code local} is {@code true}, then only the * process on the local node is requested. * * If parameter {@code local} is {@code false}, then only * the processes on remote nodes are requested, excluding * the local node. In this case at least one process must * be marked as operational. */ boolean isOperational(ProcessId processId, boolean local); /** * Mark local process as operational. In cluster mode, this * event is propagated to all nodes. */ void setOperational(ProcessId processId); boolean tryToLockWebLeader(); void reset(); void registerSonarQubeVersion(String sonarqubeVersion); void registerClusterName(String clusterName); Optional<String> getLeaderHostName(); @Override void close(); }
1,927
30.096774
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/AppStateFactory.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.application; import com.google.common.net.HostAndPort; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.sonar.application.cluster.AppNodesClusterHostsConsistency; import org.sonar.application.cluster.ClusterAppStateImpl; import org.sonar.application.config.AppSettings; import org.sonar.application.config.ClusterSettings; import org.sonar.application.es.EsConnector; import org.sonar.application.es.EsConnectorImpl; import org.sonar.process.ProcessId; import org.sonar.process.Props; import org.sonar.process.cluster.hz.HazelcastMember; import org.sonar.process.cluster.hz.HazelcastMemberBuilder; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE_PASSWORD; import static org.sonar.process.ProcessProperties.Property.CLUSTER_HZ_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_KUBERNETES; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_PASSWORD; import static org.sonar.process.cluster.hz.JoinConfigurationType.KUBERNETES; import static org.sonar.process.cluster.hz.JoinConfigurationType.TCP_IP; public class AppStateFactory { private final AppSettings settings; public AppStateFactory(AppSettings settings) { this.settings = settings; } public AppState create() { if (ClusterSettings.shouldStartHazelcast(settings)) { EsConnector esConnector = createEsConnector(settings.getProps()); HazelcastMember hzMember = createHzMember(settings.getProps()); AppNodesClusterHostsConsistency appNodesClusterHostsConsistency = AppNodesClusterHostsConsistency.setInstance(hzMember, settings); return new ClusterAppStateImpl(settings, hzMember, esConnector, appNodesClusterHostsConsistency); } return new AppStateImpl(); } private static HazelcastMember createHzMember(Props props) { boolean isRunningOnKubernetes = props.valueAsBoolean(CLUSTER_KUBERNETES.getKey(), Boolean.parseBoolean(CLUSTER_KUBERNETES.getDefaultValue())); HazelcastMemberBuilder builder = new HazelcastMemberBuilder(isRunningOnKubernetes ? KUBERNETES : TCP_IP) .setNetworkInterface(props.nonNullValue(CLUSTER_NODE_HOST.getKey())) .setMembers(props.nonNullValue(CLUSTER_HZ_HOSTS.getKey())) .setNodeName(props.nonNullValue(CLUSTER_NODE_NAME.getKey())) .setPort(Integer.parseInt(props.nonNullValue(CLUSTER_NODE_HZ_PORT.getKey()))) .setProcessId(ProcessId.APP); return builder.build(); } private static EsConnector createEsConnector(Props props) { String searchHosts = props.nonNullValue(CLUSTER_SEARCH_HOSTS.getKey()); Set<HostAndPort> hostAndPorts = Arrays.stream(searchHosts.split(",")) .map(HostAndPort::fromString) .collect(Collectors.toSet()); String searchPassword = props.value(CLUSTER_SEARCH_PASSWORD.getKey()); Path keyStorePath = Optional.ofNullable(props.value(CLUSTER_ES_HTTP_KEYSTORE.getKey())).map(Paths::get).orElse(null); String keyStorePassword = props.value(CLUSTER_ES_HTTP_KEYSTORE_PASSWORD.getKey()); return new EsConnectorImpl(hostAndPorts, searchPassword, keyStorePath, keyStorePassword); } }
4,489
48.340659
146
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/AppStateImpl.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.application; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.ProcessId; public class AppStateImpl implements AppState { private final Map<ProcessId, Boolean> processes = new EnumMap<>(ProcessId.class); private final List<AppStateListener> listeners = new ArrayList<>(); private final AtomicBoolean webLeaderLocked = new AtomicBoolean(false); @Override public void addListener(AppStateListener listener) { this.listeners.add(listener); } @Override public boolean isOperational(ProcessId processId, boolean local) { return processes.computeIfAbsent(processId, p -> false); } @Override public void setOperational(ProcessId processId) { processes.put(processId, true); listeners.forEach(l -> l.onAppStateOperational(processId)); } @Override public boolean tryToLockWebLeader() { return webLeaderLocked.compareAndSet(false, true); } @Override public void reset() { webLeaderLocked.set(false); processes.clear(); } @Override public void registerSonarQubeVersion(String sonarqubeVersion) { // Nothing to do on non clustered version } @Override public void registerClusterName(String clusterName) { // Nothing to do on non clustered version } @Override public Optional<String> getLeaderHostName() { return Optional.of(NetworkUtilsImpl.INSTANCE.getHostname()); } @Override public void close() { // nothing to do } }
2,480
28.535714
83
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/AppStateListener.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.application; import org.sonar.process.ProcessId; @FunctionalInterface public interface AppStateListener { /** * The method is called when the state is changed. When cluster * mode is enabled, the event may be raised from another node. * * Listener must subscribe to {@link AppState#addListener(AppStateListener)}. */ void onAppStateOperational(ProcessId processId); }
1,251
34.771429
79
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/FileSystem.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.application; import java.io.File; import java.io.IOException; public interface FileSystem { void reset() throws IOException; File getTempDir(); }
1,016
30.78125
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/HardStopRequestWatcherImpl.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.application; import com.google.common.annotations.VisibleForTesting; import org.sonar.process.ProcessId; import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import org.sonar.process.sharedmemoryfile.ProcessCommands; public class HardStopRequestWatcherImpl extends AbstractStopRequestWatcher { HardStopRequestWatcherImpl(Scheduler scheduler, ProcessCommands commands) { super("SQ Hard stop request watcher", commands::askedForHardStop, scheduler::hardStop); } @VisibleForTesting HardStopRequestWatcherImpl(Scheduler scheduler, ProcessCommands commands, long delayMs) { super("SQ Hard stop request watcher", commands::askedForHardStop, scheduler::hardStop, delayMs); } public static HardStopRequestWatcherImpl create(Scheduler scheduler, FileSystem fs) { DefaultProcessCommands commands = DefaultProcessCommands.secondary(fs.getTempDir(), ProcessId.APP.getIpcIndex()); return new HardStopRequestWatcherImpl(scheduler, commands); } }
1,842
40.886364
117
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/NodeLifecycle.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.application; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.EnumSet; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.Collections.emptySet; import static org.sonar.application.NodeLifecycle.State.FINALIZE_STOPPING; import static org.sonar.application.NodeLifecycle.State.HARD_STOPPING; import static org.sonar.application.NodeLifecycle.State.INIT; import static org.sonar.application.NodeLifecycle.State.OPERATIONAL; import static org.sonar.application.NodeLifecycle.State.RESTARTING; import static org.sonar.application.NodeLifecycle.State.STARTING; import static org.sonar.application.NodeLifecycle.State.STOPPED; import static org.sonar.application.NodeLifecycle.State.STOPPING; /** * ManagedProcessLifecycle of the cluster node, consolidating the states * of child processes. */ class NodeLifecycle { private static final Logger LOG = LoggerFactory.getLogger(NodeLifecycle.class); enum State { // initial state, does nothing INIT, // at least one process is still starting STARTING, // all the processes are started and operational OPERATIONAL, // at least one process is still stopping as part of a node restart RESTARTING, // at least one process is still stopping as part of a node graceful stop STOPPING, // at least one process is still stopping as part of a node hard stop HARD_STOPPING, // a hard stop or regular stop *not part of a restart* is being finalized (clean up and log) FINALIZE_STOPPING, // all processes are stopped STOPPED } private static final Map<State, Set<State>> TRANSITIONS = buildTransitions(); private State state = INIT; private static Map<State, Set<State>> buildTransitions() { Map<State, Set<State>> res = new EnumMap<>(State.class); res.put(INIT, toSet(STARTING)); res.put(STARTING, toSet(OPERATIONAL, RESTARTING, STOPPING, HARD_STOPPING)); res.put(OPERATIONAL, toSet(RESTARTING, STOPPING, HARD_STOPPING)); res.put(STOPPING, toSet(FINALIZE_STOPPING, HARD_STOPPING)); res.put(RESTARTING, toSet(STARTING, HARD_STOPPING)); res.put(HARD_STOPPING, toSet(FINALIZE_STOPPING)); res.put(FINALIZE_STOPPING, toSet(STOPPED)); res.put(STOPPED, emptySet()); return Collections.unmodifiableMap(res); } private static Set<State> toSet(State... states) { if (states.length == 0) { return emptySet(); } if (states.length == 1) { return Collections.singleton(states[0]); } return EnumSet.copyOf(Arrays.asList(states)); } State getState() { return state; } synchronized boolean tryToMoveTo(State to) { boolean res = false; State currentState = state; if (TRANSITIONS.get(currentState).contains(to)) { this.state = to; res = true; } LOG.debug("{} tryToMoveTo from {} to {} => {}", Thread.currentThread().getName(), currentState, to, res); return res; } }
3,882
32.474138
109
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/ProcessLauncher.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.application; import java.io.Closeable; import org.sonar.application.command.AbstractCommand; import org.sonar.application.process.ManagedProcess; public interface ProcessLauncher extends Closeable { @Override void close(); /** * Launch a command. * * @throws IllegalStateException if an error occurs */ ManagedProcess launch(AbstractCommand command); }
1,238
31.605263
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/ProcessLauncherImpl.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.application; import com.google.common.net.HostAndPort; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.application.command.AbstractCommand; import org.sonar.application.command.JavaCommand; import org.sonar.application.command.JvmOptions; import org.sonar.application.es.EsConnectorImpl; import org.sonar.application.es.EsInstallation; import org.sonar.application.es.EsKeyStoreCli; import org.sonar.application.process.EsManagedProcess; import org.sonar.application.process.ManagedProcess; import org.sonar.application.process.ProcessCommandsManagedProcess; import org.sonar.process.FileUtils2; import org.sonar.process.ProcessId; import org.sonar.process.sharedmemoryfile.AllProcessesCommands; import org.sonar.process.sharedmemoryfile.ProcessCommands; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Collections.singleton; import static org.sonar.application.es.EsKeyStoreCli.BOOTSTRAP_PASSWORD_PROPERTY_KEY; import static org.sonar.application.es.EsKeyStoreCli.HTTP_KEYSTORE_PASSWORD_PROPERTY_KEY; import static org.sonar.application.es.EsKeyStoreCli.KEYSTORE_PASSWORD_PROPERTY_KEY; import static org.sonar.application.es.EsKeyStoreCli.TRUSTSTORE_PASSWORD_PROPERTY_KEY; import static org.sonar.process.ProcessEntryPoint.PROPERTY_GRACEFUL_STOP_TIMEOUT_MS; import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX; import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_KEY; import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH; public class ProcessLauncherImpl implements ProcessLauncher { private static final Logger LOG = LoggerFactory.getLogger(ProcessLauncherImpl.class); private final File tempDir; private final AllProcessesCommands allProcessesCommands; private final Supplier<ProcessBuilder> processBuilderSupplier; public ProcessLauncherImpl(File tempDir) { this(tempDir, new AllProcessesCommands(tempDir), JavaLangProcessBuilder::new); } ProcessLauncherImpl(File tempDir, AllProcessesCommands allProcessesCommands, Supplier<ProcessBuilder> processBuilderSupplier) { this.tempDir = tempDir; this.allProcessesCommands = allProcessesCommands; this.processBuilderSupplier = processBuilderSupplier; } @Override public void close() { allProcessesCommands.close(); } public ManagedProcess launch(AbstractCommand command) { EsInstallation esInstallation = command.getEsInstallation(); if (esInstallation != null) { cleanupOutdatedEsData(esInstallation); writeConfFiles(esInstallation); } Process process; if (command instanceof JavaCommand<?> javaCommand) { process = launchJava(javaCommand); } else { throw new IllegalStateException("Unexpected type of command: " + command.getClass()); } ProcessId processId = command.getProcessId(); try { if (processId == ProcessId.ELASTICSEARCH) { checkArgument(esInstallation != null, "Incorrect configuration EsInstallation is null"); EsConnectorImpl esConnector = new EsConnectorImpl(singleton(HostAndPort.fromParts(esInstallation.getHost(), esInstallation.getHttpPort())), esInstallation.getBootstrapPassword(), esInstallation.getHttpKeyStoreLocation(), esInstallation.getHttpKeyStorePassword().orElse(null)); return new EsManagedProcess(process, processId, esConnector); } else { ProcessCommands commands = allProcessesCommands.createAfterClean(processId.getIpcIndex()); return new ProcessCommandsManagedProcess(process, processId, commands); } } catch (Exception e) { // just in case if (process != null) { process.destroyForcibly(); } throw new IllegalStateException(format("Fail to launch monitor of process [%s]", processId.getHumanReadableName()), e); } } private static void cleanupOutdatedEsData(EsInstallation esInstallation) { esInstallation.getOutdatedSearchDirectories() .forEach(outdatedDir -> { if (outdatedDir.exists()) { LOG.info("Deleting outdated search index data directory {}", outdatedDir.getAbsolutePath()); try { FileUtils2.deleteDirectory(outdatedDir); if (outdatedDir.exists()) { LOG.info("Failed to delete outdated search index data directory {}", outdatedDir); } } catch (IOException e) { LOG.info("Failed to delete outdated search index data directory {}", outdatedDir.getAbsolutePath(), e); } } }); } private void writeConfFiles(EsInstallation esInstallation) { File confDir = esInstallation.getConfDirectory(); pruneElasticsearchConfDirectory(confDir); createElasticsearchConfDirectory(confDir); setupElasticsearchSecurity(esInstallation); esInstallation.getEsYmlSettings().writeToYmlSettingsFile(esInstallation.getElasticsearchYml()); esInstallation.getEsJvmOptions().writeToJvmOptionFile(esInstallation.getJvmOptions()); storeElasticsearchLog4j2Properties(esInstallation); } private static void pruneElasticsearchConfDirectory(File confDir) { try { Files.deleteIfExists(confDir.toPath()); } catch (IOException e) { throw new IllegalStateException("Could not delete Elasticsearch temporary conf directory", e); } } private static void createElasticsearchConfDirectory(File confDir) { if (!confDir.mkdirs()) { String error = format("Failed to create temporary configuration directory [%s]", confDir.getAbsolutePath()); LOG.error(error); throw new IllegalStateException(error); } } private void setupElasticsearchSecurity(EsInstallation esInstallation) { if (esInstallation.isSecurityEnabled()) { EsKeyStoreCli keyStoreCli = EsKeyStoreCli.getInstance(esInstallation); setupElasticsearchAuthentication(esInstallation, keyStoreCli); setupElasticsearchHttpEncryption(esInstallation, keyStoreCli); keyStoreCli.executeWith(this::launchJava); } } private static void setupElasticsearchAuthentication(EsInstallation esInstallation, EsKeyStoreCli keyStoreCli) { keyStoreCli.store(BOOTSTRAP_PASSWORD_PROPERTY_KEY, esInstallation.getBootstrapPassword()); String esConfPath = esInstallation.getConfDirectory().getAbsolutePath(); Path trustStoreLocation = esInstallation.getTrustStoreLocation(); Path keyStoreLocation = esInstallation.getKeyStoreLocation(); if (trustStoreLocation.equals(keyStoreLocation)) { copyFile(trustStoreLocation, Paths.get(esConfPath, trustStoreLocation.toFile().getName())); } else { copyFile(trustStoreLocation, Paths.get(esConfPath, trustStoreLocation.toFile().getName())); copyFile(keyStoreLocation, Paths.get(esConfPath, keyStoreLocation.toFile().getName())); } esInstallation.getTrustStorePassword().ifPresent(s -> keyStoreCli.store(TRUSTSTORE_PASSWORD_PROPERTY_KEY, s)); esInstallation.getKeyStorePassword().ifPresent(s -> keyStoreCli.store(KEYSTORE_PASSWORD_PROPERTY_KEY, s)); } private static void setupElasticsearchHttpEncryption(EsInstallation esInstallation, EsKeyStoreCli keyStoreCli) { if (esInstallation.isHttpEncryptionEnabled()) { String esConfPath = esInstallation.getConfDirectory().getAbsolutePath(); Path httpKeyStoreLocation = esInstallation.getHttpKeyStoreLocation(); copyFile(httpKeyStoreLocation, Paths.get(esConfPath, httpKeyStoreLocation.toFile().getName())); esInstallation.getHttpKeyStorePassword().ifPresent(s -> keyStoreCli.store(HTTP_KEYSTORE_PASSWORD_PROPERTY_KEY, s)); } } private static void copyFile(Path from, Path to) { try { Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new IllegalStateException("Could not copy file: " + from, e); } } private static void storeElasticsearchLog4j2Properties(EsInstallation esInstallation) { try (FileOutputStream fileOutputStream = new FileOutputStream(esInstallation.getLog4j2PropertiesLocation())) { esInstallation.getLog4j2Properties().store(fileOutputStream, "log4j2 properties file for ES bundled in SonarQube"); } catch (IOException e) { throw new IllegalStateException("Failed to write ES configuration files", e); } } private <T extends JvmOptions> Process launchJava(JavaCommand<T> javaCommand) { ProcessId processId = javaCommand.getProcessId(); try { ProcessBuilder processBuilder = create(javaCommand); logLaunchedCommand(javaCommand, processBuilder); return processBuilder.start(); } catch (Exception e) { throw new IllegalStateException(format("Fail to launch process [%s]", processId.getHumanReadableName()), e); } } private static <T extends AbstractCommand> void logLaunchedCommand(AbstractCommand<T> command, ProcessBuilder processBuilder) { if (LOG.isInfoEnabled()) { LOG.info("Launch process[{}] from [{}]: {}", command.getProcessId(), command.getWorkDir().getAbsolutePath(), String.join(" ", processBuilder.command())); } } private <T extends JvmOptions> ProcessBuilder create(JavaCommand<T> javaCommand) { List<String> commands = new ArrayList<>(); commands.add(buildJavaPath()); commands.addAll(javaCommand.getJvmOptions().getAll()); commands.addAll(buildClasspath(javaCommand)); commands.add(javaCommand.getClassName()); commands.addAll(javaCommand.getParameters()); if (javaCommand.getReadsArgumentsFromFile()) { commands.add(buildPropertiesFile(javaCommand).getAbsolutePath()); } else { javaCommand.getArguments().forEach((key, value) -> { if (value != null && !value.isEmpty()) { commands.add("-E" + key + "=" + value); } }); } return create(javaCommand, commands); } private ProcessBuilder create(AbstractCommand<?> command, List<String> commands) { ProcessBuilder processBuilder = processBuilderSupplier.get(); processBuilder.command(commands); processBuilder.directory(command.getWorkDir()); Map<String, String> environment = processBuilder.environment(); environment.putAll(command.getEnvVariables()); command.getSuppressedEnvVariables().forEach(environment::remove); processBuilder.redirectErrorStream(true); return processBuilder; } private static String buildJavaPath() { String separator = System.getProperty("file.separator"); return new File(new File(System.getProperty("java.home")), "bin" + separator + "java").getAbsolutePath(); } private static <T extends JvmOptions> List<String> buildClasspath(JavaCommand<T> javaCommand) { String pathSeparator = System.getProperty("path.separator"); return Arrays.asList("-cp", String.join(pathSeparator, javaCommand.getClasspath())); } private File buildPropertiesFile(JavaCommand javaCommand) { File propertiesFile = null; try { propertiesFile = File.createTempFile("sq-process", "properties", tempDir); Properties props = new Properties(); props.putAll(javaCommand.getArguments()); props.setProperty(PROPERTY_PROCESS_KEY, javaCommand.getProcessId().getKey()); props.setProperty(PROPERTY_PROCESS_INDEX, Integer.toString(javaCommand.getProcessId().getIpcIndex())); props.setProperty(PROPERTY_GRACEFUL_STOP_TIMEOUT_MS, javaCommand.getGracefulStopTimeoutMs() + ""); props.setProperty(PROPERTY_SHARED_PATH, tempDir.getAbsolutePath()); try (OutputStream out = new FileOutputStream(propertiesFile)) { props.store(out, format("Temporary properties file for command [%s]", javaCommand.getProcessId().getKey())); } return propertiesFile; } catch (Exception e) { throw new IllegalStateException("Cannot write temporary settings to " + propertiesFile, e); } } /** * An interface of the methods of {@link java.lang.ProcessBuilder} that we use in {@link ProcessLauncherImpl}. * <p>Allows testing creating processes without actualling creating them at OS level</p> */ public interface ProcessBuilder { List<String> command(); ProcessBuilder command(List<String> commands); ProcessBuilder directory(File dir); Map<String, String> environment(); ProcessBuilder redirectErrorStream(boolean b); Process start() throws IOException; } private static class JavaLangProcessBuilder implements ProcessBuilder { private final java.lang.ProcessBuilder builder = new java.lang.ProcessBuilder(); /** * @see java.lang.ProcessBuilder#command() */ @Override public List<String> command() { return builder.command(); } /** * @see java.lang.ProcessBuilder#command(List) */ @Override public ProcessBuilder command(List<String> commands) { builder.command(commands); return this; } /** * @see java.lang.ProcessBuilder#directory(File) */ @Override public ProcessBuilder directory(File dir) { builder.directory(dir); return this; } /** * @see java.lang.ProcessBuilder#environment() */ @Override public Map<String, String> environment() { return builder.environment(); } /** * @see java.lang.ProcessBuilder#redirectErrorStream(boolean) */ @Override public ProcessBuilder redirectErrorStream(boolean b) { builder.redirectErrorStream(b); return this; } /** * @see java.lang.ProcessBuilder#start() */ @Override public Process start() throws IOException { return builder.start(); } } }
14,915
38.670213
129
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/Scheduler.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.application; public interface Scheduler { void schedule() throws InterruptedException; /** * Gracefully stops all processes and waits for them to be down. */ void stop(); /** * Stops all processes and waits for them to be down. */ void hardStop(); /** * Blocks until all processes are down */ void awaitTermination(); }
1,218
28.731707
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/SchedulerImpl.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.application; import java.util.EnumMap; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.application.command.AbstractCommand; import org.sonar.application.command.CommandFactory; import org.sonar.application.config.AppSettings; import org.sonar.application.config.ClusterSettings; import org.sonar.application.process.ManagedProcessEventListener; import org.sonar.application.process.ManagedProcessHandler; import org.sonar.application.process.ManagedProcessLifecycle; import org.sonar.application.process.ProcessLifecycleListener; import org.sonar.process.ProcessId; import org.sonar.process.ProcessProperties; import static org.sonar.application.NodeLifecycle.State.FINALIZE_STOPPING; import static org.sonar.application.NodeLifecycle.State.HARD_STOPPING; import static org.sonar.application.NodeLifecycle.State.RESTARTING; import static org.sonar.application.NodeLifecycle.State.STOPPED; import static org.sonar.application.NodeLifecycle.State.STOPPING; import static org.sonar.application.process.ManagedProcessHandler.Timeout.newTimeout; import static org.sonar.process.ProcessProperties.Property.CE_GRACEFUL_STOP_TIMEOUT; import static org.sonar.process.ProcessProperties.Property.WEB_GRACEFUL_STOP_TIMEOUT; import static org.sonar.process.ProcessProperties.parseTimeoutMs; public class SchedulerImpl implements Scheduler, ManagedProcessEventListener, ProcessLifecycleListener, AppStateListener { private static final Logger LOG = LoggerFactory.getLogger(SchedulerImpl.class); private static final ManagedProcessHandler.Timeout HARD_STOP_TIMEOUT = newTimeout(1, TimeUnit.MINUTES); private static int hardStopperThreadIndex = 0; private static int restartStopperThreadIndex = 0; private final AppSettings settings; private final AppReloader appReloader; private final CommandFactory commandFactory; private final ProcessLauncher processLauncher; private final AppState appState; private final NodeLifecycle nodeLifecycle = new NodeLifecycle(); private final CountDownLatch awaitTermination = new CountDownLatch(1); private final AtomicBoolean firstWaitingEsLog = new AtomicBoolean(true); private final EnumMap<ProcessId, ManagedProcessHandler> processesById = new EnumMap<>(ProcessId.class); private final AtomicInteger operationalCountDown = new AtomicInteger(); private final AtomicInteger stopCountDown = new AtomicInteger(0); private RestartStopperThread restartStopperThread; private HardStopperThread hardStopperThread; private RestarterThread restarterThread; private long processWatcherDelayMs = ManagedProcessHandler.DEFAULT_WATCHER_DELAY_MS; public SchedulerImpl(AppSettings settings, AppReloader appReloader, CommandFactory commandFactory, ProcessLauncher processLauncher, AppState appState) { this.settings = settings; this.appReloader = appReloader; this.commandFactory = commandFactory; this.processLauncher = processLauncher; this.appState = appState; this.appState.addListener(this); } SchedulerImpl setProcessWatcherDelayMs(long l) { this.processWatcherDelayMs = l; return this; } @Override public void schedule() throws InterruptedException { if (!nodeLifecycle.tryToMoveTo(NodeLifecycle.State.STARTING)) { return; } firstWaitingEsLog.set(true); processesById.clear(); for (ProcessId processId : ClusterSettings.getEnabledProcesses(settings)) { ManagedProcessHandler process = ManagedProcessHandler.builder(processId) .addProcessLifecycleListener(this) .addEventListener(this) .setWatcherDelayMs(processWatcherDelayMs) .setStopTimeout(stopTimeoutFor(processId, settings)) .setHardStopTimeout(HARD_STOP_TIMEOUT) .setAppSettings(settings) .build(); processesById.put(process.getProcessId(), process); } operationalCountDown.set(processesById.size()); tryToStartAll(); } private static ManagedProcessHandler.Timeout stopTimeoutFor(ProcessId processId, AppSettings settings) { return switch (processId) { case ELASTICSEARCH -> HARD_STOP_TIMEOUT; case WEB_SERVER -> newTimeout(getStopTimeoutMs(settings, WEB_GRACEFUL_STOP_TIMEOUT), TimeUnit.MILLISECONDS); case COMPUTE_ENGINE -> newTimeout(getStopTimeoutMs(settings, CE_GRACEFUL_STOP_TIMEOUT), TimeUnit.MILLISECONDS); default -> throw new IllegalArgumentException("Unsupported processId " + processId); }; } private static long getStopTimeoutMs(AppSettings settings, ProcessProperties.Property property) { String timeoutMs = settings.getValue(property.getKey()) .orElse(property.getDefaultValue()); // give some time to CE/Web to shutdown itself after "timeoutMs" long gracePeriod = HARD_STOP_TIMEOUT.getUnit().toMillis(HARD_STOP_TIMEOUT.getDuration()); return parseTimeoutMs(property, timeoutMs) + gracePeriod; } private void tryToStartAll() throws InterruptedException { tryToStartEs(); tryToStartWeb(); tryToStartCe(); } private void tryToStartEs() throws InterruptedException { ManagedProcessHandler process = processesById.get(ProcessId.ELASTICSEARCH); if (process != null) { tryToStartProcess(process, commandFactory::createEsCommand); } } private void tryToStartWeb() throws InterruptedException { ManagedProcessHandler process = processesById.get(ProcessId.WEB_SERVER); if (process == null) { return; } if (!isEsOperational()) { if (firstWaitingEsLog.getAndSet(false)) { LOG.info("Waiting for Elasticsearch to be up and running"); } return; } if (appState.isOperational(ProcessId.WEB_SERVER, false)) { tryToStartProcess(process, () -> commandFactory.createWebCommand(false)); } else if (appState.tryToLockWebLeader()) { tryToStartProcess(process, () -> commandFactory.createWebCommand(true)); } else { Optional<String> leader = appState.getLeaderHostName(); if (leader.isPresent()) { LOG.info("Waiting for initialization from {}", leader.get()); } else { LOG.error("Initialization failed. All nodes must be restarted"); } } } private void tryToStartCe() throws InterruptedException { ManagedProcessHandler process = processesById.get(ProcessId.COMPUTE_ENGINE); if (process != null && appState.isOperational(ProcessId.WEB_SERVER, true) && isEsOperational()) { tryToStartProcess(process, commandFactory::createCeCommand); } } private boolean isEsOperational() { boolean requireLocalEs = ClusterSettings.isLocalElasticsearchEnabled(settings); return appState.isOperational(ProcessId.ELASTICSEARCH, requireLocalEs); } private void tryToStartProcess(ManagedProcessHandler processHandler, Supplier<AbstractCommand> commandSupplier) throws InterruptedException { // starter or restarter thread was interrupted, we should not proceed with starting the process if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } try { processHandler.start(() -> { AbstractCommand command = commandSupplier.get(); return processLauncher.launch(command); }); } catch (RuntimeException e) { // failed to start command -> do nothing // the process failing to start will move directly to STOP state // this early stop of the process will be picked up by onProcessStop (which calls hardStopAsync) // through interface ProcessLifecycleListener#onProcessState implemented by SchedulerImpl LOG.trace("Failed to start process [{}] (currentThread={})", processHandler.getProcessId().getHumanReadableName(), Thread.currentThread().getName(), e); } } @Override public void stop() { if (nodeLifecycle.tryToMoveTo(STOPPING)) { LOG.info("Stopping SonarQube"); stopImpl(); } } private void stopImpl() { try { stopAll(); finalizeStop(); } catch (InterruptedException e) { LOG.debug("Stop interrupted", e); Thread.currentThread().interrupt(); } } private void stopAll() throws InterruptedException { // order is important for non-cluster mode LOG.info("Sonarqube has been requested to stop"); stopProcess(ProcessId.COMPUTE_ENGINE); stopProcess(ProcessId.WEB_SERVER); stopProcess(ProcessId.ELASTICSEARCH); } /** * Request for graceful stop then blocks until process is stopped. * Returns immediately if the process is disabled in configuration. * * @throws InterruptedException if {@link ManagedProcessHandler#hardStop()} throws a {@link InterruptedException} */ private void stopProcess(ProcessId processId) throws InterruptedException { ManagedProcessHandler process = processesById.get(processId); if (process != null) { LOG.info("Stopping [{}] process...", process.getProcessId().getHumanReadableName()); process.stop(); } } /** * Blocks until all processes are quickly stopped. Pending restart, if any, is disabled. */ @Override public void hardStop() { if (nodeLifecycle.tryToMoveTo(HARD_STOPPING)) { LOG.info("Hard stopping SonarQube"); hardStopImpl(); } } private void hardStopImpl() { try { hardStopAll(); finalizeStop(); } catch (InterruptedException e) { // ignore and assume SQ stop is handled by another thread LOG.debug("Stopping all processes was interrupted in the middle of a hard stop" + " (current thread name is \"{}\")", Thread.currentThread().getName()); Thread.currentThread().interrupt(); } } private void hardStopAll() throws InterruptedException { // order is important for non-cluster mode hardStopProcess(ProcessId.COMPUTE_ENGINE); hardStopProcess(ProcessId.WEB_SERVER); hardStopProcess(ProcessId.ELASTICSEARCH); } /** * This might be called twice: once by the state listener and once by the stop/hardStop implementations. * The reason is that if all process are already stopped (may occur, eg., when stopping because restart of 1st process failed), * the node state won't be updated on process stopped callback. */ private void finalizeStop() { if (nodeLifecycle.tryToMoveTo(FINALIZE_STOPPING)) { interrupt(restartStopperThread); interrupt(hardStopperThread); interrupt(restarterThread); if (nodeLifecycle.tryToMoveTo(STOPPED)) { LOG.info("SonarQube is stopped"); } awaitTermination.countDown(); } } private static void interrupt(@Nullable Thread thread) { Thread currentThread = Thread.currentThread(); // prevent current thread from interrupting itself if (thread != null && currentThread != thread) { thread.interrupt(); if (LOG.isTraceEnabled()) { Exception e = new Exception("(capturing stacktrace for debugging purpose)"); LOG.trace("{} interrupted {}", currentThread.getName(), thread.getName(), e); } } } /** * Request for graceful stop then blocks until process is stopped. * Returns immediately if the process is disabled in configuration. * * @throws InterruptedException if {@link ManagedProcessHandler#hardStop()} throws a {@link InterruptedException} */ private void hardStopProcess(ProcessId processId) throws InterruptedException { ManagedProcessHandler process = processesById.get(processId); if (process != null) { process.hardStop(); } } @Override public void awaitTermination() { try { awaitTermination.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } @Override public void onManagedProcessEvent(ProcessId processId, Type type) { if (type == Type.OPERATIONAL) { onProcessOperational(processId); } else if (type == Type.ASK_FOR_RESTART && nodeLifecycle.tryToMoveTo(RESTARTING)) { LOG.info("SQ restart requested by Process[{}]", processId.getHumanReadableName()); stopAsyncForRestart(); } } private void onProcessOperational(ProcessId processId) { LOG.info("Process[{}] is up", processId.getKey()); appState.setOperational(processId); boolean lastProcessStarted = operationalCountDown.decrementAndGet() == 0; if (lastProcessStarted && nodeLifecycle.tryToMoveTo(NodeLifecycle.State.OPERATIONAL)) { LOG.info("SonarQube is operational"); } } @Override public void onAppStateOperational(ProcessId processId) { if (nodeLifecycle.getState() == NodeLifecycle.State.STARTING) { try { tryToStartAll(); } catch (InterruptedException e) { // startup process was interrupted, let's assume it means shutdown was requested LOG.debug("Startup process was interrupted on notification that process [{}] was operational", processId.getHumanReadableName(), e); hardStopAsync(); Thread.currentThread().interrupt(); } } } @Override public void onProcessState(ProcessId processId, ManagedProcessLifecycle.State to) { switch (to) { case STOPPED: onProcessStop(processId); break; case STARTING: stopCountDown.incrementAndGet(); break; default: // Nothing to do break; } } private void onProcessStop(ProcessId processId) { LOG.info("Process[{}] is stopped", processId.getHumanReadableName()); boolean lastProcessStopped = stopCountDown.decrementAndGet() == 0; switch (nodeLifecycle.getState()) { case RESTARTING: if (lastProcessStopped) { LOG.info("SonarQube is restarting"); restartAsync(); } break; case HARD_STOPPING, STOPPING: if (lastProcessStopped) { finalizeStop(); } break; default: // a sub process disappeared while this wasn't requested, SQ should be shutdown completely hardStopAsync(); } } private void hardStopAsync() { if (hardStopperThread != null) { logThreadRecreated("Hard stopper", hardStopperThread); hardStopperThread.interrupt(); } hardStopperThread = new HardStopperThread(); hardStopperThread.start(); } private void stopAsyncForRestart() { if (restartStopperThread != null) { logThreadRecreated("Restart stopper", restartStopperThread); restartStopperThread.interrupt(); } restartStopperThread = new RestartStopperThread(); restartStopperThread.start(); } private static void logThreadRecreated(String threadType, Thread existingThread) { if (LOG.isDebugEnabled()) { Exception e = new Exception("(capturing stack trace for debugging purpose)"); LOG.debug("{} thread was not null (currentThread={},existingThread={})", threadType, Thread.currentThread().getName(), existingThread.getName(), e); } } private void restartAsync() { if (restarterThread != null) { LOG.debug("Restarter thread was not null (name is \"{}\")", restarterThread.getName(), new Exception()); restarterThread.interrupt(); } restarterThread = new RestarterThread(); restarterThread.start(); } private class RestarterThread extends Thread { private RestarterThread() { super("Restarter"); } @Override public void run() { try { appReloader.reload(settings); schedule(); } catch (InterruptedException e) { // restart was interrupted, most likely by a stop thread, restart must be aborted LOG.debug("{} thread was interrupted", getName(), e); super.interrupt(); } catch (Exception e) { LOG.error("Failed to restart", e); hardStop(); } } } private static int nextRestartStopperThreadIndex() { return restartStopperThreadIndex++; } private static int nextHardStopperThreadIndex() { return hardStopperThreadIndex++; } private class RestartStopperThread extends Thread { private RestartStopperThread() { super("RestartStopper-" + nextRestartStopperThreadIndex()); } @Override public void run() { stopImpl(); } } private class HardStopperThread extends Thread { private HardStopperThread() { super("HardStopper-" + nextHardStopperThreadIndex()); } @Override public void run() { if (nodeLifecycle.tryToMoveTo(HARD_STOPPING)) { hardStopImpl(); } } } }
17,550
35.039014
143
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/StopRequestWatcher.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.application; /** * Background thread that checks if a stop request * is sent, usually by Orchestrator */ public interface StopRequestWatcher { void startWatching(); void stopWatching(); }
1,060
31.151515
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/StopRequestWatcherImpl.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.application; import org.sonar.application.config.AppSettings; import org.sonar.process.ProcessId; import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import org.sonar.process.sharedmemoryfile.ProcessCommands; import static org.sonar.process.ProcessProperties.Property.ENABLE_STOP_COMMAND; public class StopRequestWatcherImpl extends AbstractStopRequestWatcher { private final AppSettings settings; StopRequestWatcherImpl(AppSettings settings, Scheduler scheduler, ProcessCommands commands) { super("SQ stop request watcher", commands::askedForStop, scheduler::stop); this.settings = settings; } public static StopRequestWatcherImpl create(AppSettings settings, Scheduler scheduler, FileSystem fs) { DefaultProcessCommands commands = DefaultProcessCommands.secondary(fs.getTempDir(), ProcessId.APP.getIpcIndex()); return new StopRequestWatcherImpl(settings, scheduler, commands); } @Override public void startWatching() { if (settings.getProps().valueAsBoolean(ENABLE_STOP_COMMAND.getKey())) { super.startWatching(); } } }
1,950
38.02
117
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/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.application; import javax.annotation.ParametersAreNonnullByDefault;
961
39.083333
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/cluster/AppNodesClusterHostsConsistency.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.application.cluster; import com.google.common.annotations.VisibleForTesting; import com.hazelcast.cluster.Address; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.MemberSelector; import com.hazelcast.cluster.memberselector.MemberSelectors; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import javax.annotation.CheckForNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.application.config.AppSettings; import org.sonar.process.ProcessId; import org.sonar.process.cluster.hz.DistributedCallback; import org.sonar.process.cluster.hz.HazelcastMember; import org.sonar.process.cluster.hz.HazelcastMemberSelectors; import static com.google.common.base.Preconditions.checkState; import static com.hazelcast.cluster.memberselector.MemberSelectors.NON_LOCAL_MEMBER_SELECTOR; import static org.sonar.process.ProcessProperties.Property.CLUSTER_HZ_HOSTS; public class AppNodesClusterHostsConsistency { private static final Logger LOG = LoggerFactory.getLogger(AppNodesClusterHostsConsistency.class); private static final AtomicReference<AppNodesClusterHostsConsistency> INSTANCE = new AtomicReference<>(); private final AppSettings settings; private final HazelcastMember hzMember; private final Consumer<String> logger; private AppNodesClusterHostsConsistency(HazelcastMember hzMember, AppSettings settings, Consumer<String> logger) { this.hzMember = hzMember; this.settings = settings; this.logger = logger; } public static AppNodesClusterHostsConsistency setInstance(HazelcastMember hzMember, AppSettings settings) { return setInstance(hzMember, settings, LOG::warn); } @VisibleForTesting public static AppNodesClusterHostsConsistency setInstance(HazelcastMember hzMember, AppSettings settings, Consumer<String> logger) { AppNodesClusterHostsConsistency instance = new AppNodesClusterHostsConsistency(hzMember, settings, logger); checkState(INSTANCE.compareAndSet(null, instance), "Instance is already set"); return instance; } @VisibleForTesting @CheckForNull protected static AppNodesClusterHostsConsistency clearInstance() { return INSTANCE.getAndSet(null); } public void check() { try { MemberSelector selector = MemberSelectors.and(NON_LOCAL_MEMBER_SELECTOR, HazelcastMemberSelectors.selectorForProcessIds(ProcessId.APP)); hzMember.callAsync(AppNodesClusterHostsConsistency::getConfiguredClusterHosts, selector, new Callback()); } catch (RejectedExecutionException e) { // no other node in the cluster yet, ignore } } private class Callback implements DistributedCallback<List<String>> { @Override public void onComplete(Map<Member, List<String>> hostsPerMember) { List<String> currentConfiguredHosts = getConfiguredClusterHosts(); boolean anyDifference = hostsPerMember.values().stream() .filter(v -> !v.isEmpty()) .anyMatch(hosts -> currentConfiguredHosts.size() != hosts.size() || !currentConfiguredHosts.containsAll(hosts)); if (anyDifference) { StringBuilder builder = new StringBuilder().append("The configuration of the current node doesn't match the list of hosts configured in " + "the application nodes that have already joined the cluster:\n"); logMemberSetting(builder, hzMember.getCluster().getLocalMember(), currentConfiguredHosts); for (Map.Entry<Member, List<String>> e : hostsPerMember.entrySet()) { if (e.getValue().isEmpty()) { continue; } logMemberSetting(builder, e.getKey(), e.getValue()); } builder.append("Make sure the configuration is consistent among all application nodes before you restart any node"); logger.accept(builder.toString()); } } private String toString(Address address) { return address.getHost() + ":" + address.getPort(); } private void logMemberSetting(StringBuilder builder, Member member, List<String> configuredHosts) { builder.append(toString(member.getAddress())); builder.append(" : "); builder.append(configuredHosts); if (member.localMember()) { builder.append(" (current)"); } builder.append("\n"); } } private static List<String> getConfiguredClusterHosts() { try { AppNodesClusterHostsConsistency instance = INSTANCE.get(); if (instance != null) { return Arrays.asList(instance.settings.getProps().nonNullValue(CLUSTER_HZ_HOSTS.getKey()).split(",")); } return Collections.emptyList(); } catch (Exception e) { LOG.error("Failed to get configured cluster nodes", e); return Collections.emptyList(); } } }
5,758
39.556338
145
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/cluster/ClusterAppState.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.application.cluster; import org.sonar.application.AppState; import org.sonar.process.cluster.hz.HazelcastMember; public interface ClusterAppState extends AppState { HazelcastMember getHazelcastMember(); }
1,070
37.25
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/cluster/ClusterAppStateImpl.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.application.cluster; import com.hazelcast.cluster.Member; import com.hazelcast.cluster.MembershipAdapter; import com.hazelcast.cluster.MembershipEvent; import com.hazelcast.core.EntryAdapter; import com.hazelcast.core.EntryEvent; import com.hazelcast.core.HazelcastInstanceNotActiveException; import com.hazelcast.cp.IAtomicReference; import com.hazelcast.replicatedmap.ReplicatedMap; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.application.AppStateListener; import org.sonar.application.cluster.health.HealthStateSharing; import org.sonar.application.cluster.health.HealthStateSharingImpl; import org.sonar.application.cluster.health.SearchNodeHealthProvider; import org.sonar.application.config.AppSettings; import org.sonar.application.config.ClusterSettings; import org.sonar.application.es.EsConnector; import org.sonar.process.MessageException; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.ProcessId; import org.sonar.process.cluster.hz.HazelcastMember; import static java.lang.String.format; import static org.sonar.process.cluster.hz.HazelcastObjects.CLUSTER_NAME; import static org.sonar.process.cluster.hz.HazelcastObjects.LEADER; import static org.sonar.process.cluster.hz.HazelcastObjects.OPERATIONAL_PROCESSES; import static org.sonar.process.cluster.hz.HazelcastObjects.SONARQUBE_VERSION; public class ClusterAppStateImpl implements ClusterAppState { private static final Logger LOGGER = LoggerFactory.getLogger(ClusterAppStateImpl.class); private final HazelcastMember hzMember; private final List<AppStateListener> listeners = new ArrayList<>(); private final Map<ProcessId, Boolean> operationalLocalProcesses = new EnumMap<>(ProcessId.class); private final AtomicBoolean esPoolingThreadRunning = new AtomicBoolean(false); private final ReplicatedMap<ClusterProcess, Boolean> operationalProcesses; private final UUID operationalProcessListenerUUID; private final UUID nodeDisconnectedListenerUUID; private final EsConnector esConnector; private HealthStateSharing healthStateSharing = null; public ClusterAppStateImpl(AppSettings settings, HazelcastMember hzMember, EsConnector esConnector, AppNodesClusterHostsConsistency appNodesClusterHostsConsistency) { this.hzMember = hzMember; // Get or create the replicated map operationalProcesses = (ReplicatedMap) hzMember.getReplicatedMap(OPERATIONAL_PROCESSES); operationalProcessListenerUUID = operationalProcesses.addEntryListener(new OperationalProcessListener()); nodeDisconnectedListenerUUID = hzMember.getCluster().addMembershipListener(new NodeDisconnectedListener()); appNodesClusterHostsConsistency.check(); if (ClusterSettings.isLocalElasticsearchEnabled(settings)) { this.healthStateSharing = new HealthStateSharingImpl(hzMember, new SearchNodeHealthProvider(settings.getProps(), this, NetworkUtilsImpl.INSTANCE)); this.healthStateSharing.start(); } this.esConnector = esConnector; } @Override public HazelcastMember getHazelcastMember() { return hzMember; } @Override public void addListener(AppStateListener listener) { listeners.add(listener); } @Override public boolean isOperational(ProcessId processId, boolean local) { if (local) { return operationalLocalProcesses.computeIfAbsent(processId, p -> false); } if (processId.equals(ProcessId.ELASTICSEARCH)) { boolean operational = isElasticSearchOperational(); if (!operational) { asyncWaitForEsToBecomeOperational(); } return operational; } for (Map.Entry<ClusterProcess, Boolean> entry : operationalProcesses.entrySet()) { if (entry.getKey().getProcessId().equals(processId) && entry.getValue()) { return true; } } return false; } @Override public void setOperational(ProcessId processId) { operationalLocalProcesses.put(processId, true); operationalProcesses.put(new ClusterProcess(hzMember.getUuid(), processId), Boolean.TRUE); } @Override public boolean tryToLockWebLeader() { IAtomicReference<UUID> leader = hzMember.getAtomicReference(LEADER); return leader.compareAndSet(null, hzMember.getUuid()); } @Override public void reset() { throw new IllegalStateException("state reset is not supported in cluster mode"); } @Override public void registerSonarQubeVersion(String sonarqubeVersion) { IAtomicReference<String> sqVersion = hzMember.getAtomicReference(SONARQUBE_VERSION); boolean wasSet = sqVersion.compareAndSet(null, sonarqubeVersion); if (!wasSet) { String clusterVersion = sqVersion.get(); if (!sqVersion.get().equals(sonarqubeVersion)) { throw new IllegalStateException( format("The local version %s is not the same as the cluster %s", sonarqubeVersion, clusterVersion)); } } } @Override public void registerClusterName(String clusterName) { IAtomicReference<String> property = hzMember.getAtomicReference(CLUSTER_NAME); boolean wasSet = property.compareAndSet(null, clusterName); if (!wasSet) { String clusterValue = property.get(); if (!property.get().equals(clusterName)) { throw new MessageException( format("This node has a cluster name [%s], which does not match [%s] from the cluster", clusterName, clusterValue)); } } } @Override public Optional<String> getLeaderHostName() { UUID leaderUuid = (UUID) hzMember.getAtomicReference(LEADER).get(); if (leaderUuid != null) { Optional<Member> leader = hzMember.getCluster().getMembers().stream().filter(m -> m.getUuid().equals(leaderUuid)).findFirst(); if (leader.isPresent()) { return Optional.of(leader.get().getAddress().getHost()); } } return Optional.empty(); } @Override public void close() { esConnector.stop(); if (hzMember != null) { if (healthStateSharing != null) { healthStateSharing.stop(); } try { // Removing listeners operationalProcesses.removeEntryListener(operationalProcessListenerUUID); hzMember.getCluster().removeMembershipListener(nodeDisconnectedListenerUUID); // Removing the operationalProcess from the replicated map operationalProcesses.keySet().forEach( clusterNodeProcess -> { if (clusterNodeProcess.getNodeUuid().equals(hzMember.getUuid())) { operationalProcesses.remove(clusterNodeProcess); } }); // Shutdown Hazelcast properly hzMember.close(); } catch (HazelcastInstanceNotActiveException e) { // hazelcastCluster may be already closed by the shutdown hook LOGGER.debug("Unable to close Hazelcast cluster", e); } } } private boolean isElasticSearchOperational() { return esConnector.getClusterHealthStatus() .filter(t -> ClusterHealthStatus.GREEN.equals(t) || ClusterHealthStatus.YELLOW.equals(t)) .isPresent(); } private void asyncWaitForEsToBecomeOperational() { if (esPoolingThreadRunning.compareAndSet(false, true)) { Thread thread = new EsPoolingThread(); thread.start(); } } private class EsPoolingThread extends Thread { private EsPoolingThread() { super("es-state-pooling"); this.setDaemon(true); } @Override public void run() { while (true) { if (isElasticSearchOperational()) { esPoolingThreadRunning.set(false); listeners.forEach(l -> l.onAppStateOperational(ProcessId.ELASTICSEARCH)); return; } try { Thread.sleep(5_000); } catch (InterruptedException e) { esPoolingThreadRunning.set(false); Thread.currentThread().interrupt(); return; } } } } private class OperationalProcessListener extends EntryAdapter<ClusterProcess, Boolean> { @Override public void entryAdded(EntryEvent<ClusterProcess, Boolean> event) { if (event.getValue()) { listeners.forEach(appStateListener -> appStateListener.onAppStateOperational(event.getKey().getProcessId())); } } @Override public void entryUpdated(EntryEvent<ClusterProcess, Boolean> event) { if (event.getValue()) { listeners.forEach(appStateListener -> appStateListener.onAppStateOperational(event.getKey().getProcessId())); } } } private class NodeDisconnectedListener extends MembershipAdapter { @Override public void memberRemoved(MembershipEvent membershipEvent) { removeOperationalProcess(membershipEvent.getMember().getUuid()); } private void removeOperationalProcess(UUID uuid) { for (ClusterProcess clusterProcess : operationalProcesses.keySet()) { if (clusterProcess.getNodeUuid().equals(uuid)) { LOGGER.debug("Set node process off for [{}:{}] : ", clusterProcess.getNodeUuid(), clusterProcess.getProcessId()); hzMember.getReplicatedMap(OPERATIONAL_PROCESSES).put(clusterProcess, Boolean.FALSE); } } } } }
10,224
35.648746
168
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/cluster/ClusterProcess.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.application.cluster; import java.io.Serializable; import java.util.Objects; import java.util.UUID; import org.sonar.process.ProcessId; import static java.util.Objects.requireNonNull; public class ClusterProcess implements Serializable { private final ProcessId processId; private final UUID nodeUuid; public ClusterProcess(UUID nodeUuid, ProcessId processId) { this.processId = requireNonNull(processId); this.nodeUuid = requireNonNull(nodeUuid); } public ProcessId getProcessId() { return processId; } public UUID getNodeUuid() { return nodeUuid; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ClusterProcess that = (ClusterProcess) o; if (processId != that.processId) { return false; } return nodeUuid.equals(that.nodeUuid); } @Override public int hashCode() { return Objects.hash(processId, nodeUuid); } }
1,870
27.348485
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/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.application.cluster; import javax.annotation.ParametersAreNonnullByDefault;
969
39.416667
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/cluster/health/DelegateHealthStateRefresherExecutorService.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.application.cluster.health; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.sonar.process.cluster.health.HealthStateRefresherExecutorService; class DelegateHealthStateRefresherExecutorService implements HealthStateRefresherExecutorService { private final ScheduledExecutorService delegate; DelegateHealthStateRefresherExecutorService(ScheduledExecutorService delegate) { this.delegate = delegate; } @Override public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return delegate.schedule(command, delay, unit); } @Override public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) { return delegate.schedule(callable, delay, unit); } @Override public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { return delegate.scheduleAtFixedRate(command, initialDelay, period, unit); } @Override public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit); } @Override public void shutdown() { delegate.shutdown(); } @Override public List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } @Override public <T> Future<T> submit(Callable<T> task) { return delegate.submit(task); } @Override public <T> Future<T> submit(Runnable task, T result) { return delegate.submit(task, result); } @Override public Future<?> submit(Runnable task) { return delegate.submit(task); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException { return delegate.invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return delegate.invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return delegate.invokeAny(tasks); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.invokeAny(tasks, timeout, unit); } @Override public void execute(Runnable command) { delegate.execute(command); } }
4,007
31.064
162
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/cluster/health/HealthStateSharing.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.application.cluster.health; public interface HealthStateSharing { void start(); void stop(); }
962
34.666667
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/cluster/health/HealthStateSharingImpl.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.application.cluster.health; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.cluster.health.HealthStateRefresher; import org.sonar.process.cluster.health.HealthStateRefresherExecutorService; import org.sonar.process.cluster.health.NodeHealthProvider; import org.sonar.process.cluster.health.SharedHealthStateImpl; import org.sonar.process.cluster.hz.HazelcastMember; public class HealthStateSharingImpl implements HealthStateSharing { private static final Logger LOG = LoggerFactory.getLogger(HealthStateSharingImpl.class); private final HazelcastMember hzMember; private final NodeHealthProvider nodeHealthProvider; private HealthStateRefresherExecutorService executorService; private HealthStateRefresher healthStateRefresher; public HealthStateSharingImpl(HazelcastMember hzMember, NodeHealthProvider nodeHealthProvider) { this.hzMember = hzMember; this.nodeHealthProvider = nodeHealthProvider; } @Override public void start() { executorService = new DelegateHealthStateRefresherExecutorService( Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setDaemon(false) .setNameFormat("health_state_refresh-%d") .build())); healthStateRefresher = new HealthStateRefresher(executorService, nodeHealthProvider, new SharedHealthStateImpl(hzMember)); healthStateRefresher.start(); } @Override public void stop() { healthStateRefresher.stop(); stopExecutorService(executorService); } private static void stopExecutorService(ScheduledExecutorService executorService) { // Disable new tasks from being submitted executorService.shutdown(); try { // Wait a while for existing tasks to terminate if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { // Cancel currently executing tasks executorService.shutdownNow(); // Wait a while for tasks to respond to being canceled if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { LOG.warn("Pool {} did not terminate", HealthStateSharingImpl.class.getSimpleName()); } } } catch (InterruptedException ie) { LOG.warn("Termination of pool {} failed", HealthStateSharingImpl.class.getSimpleName(), ie); // (Re-)Cancel if current thread also interrupted executorService.shutdownNow(); Thread.currentThread().interrupt(); } } }
3,502
39.264368
126
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/cluster/health/SearchNodeHealthProvider.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.application.cluster.health; import org.sonar.application.cluster.ClusterAppState; import org.sonar.process.NetworkUtils; import org.sonar.process.ProcessId; import org.sonar.process.Props; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import org.sonar.process.cluster.health.NodeHealthProvider; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT; public class SearchNodeHealthProvider implements NodeHealthProvider { private final ClusterAppState clusterAppState; private final NodeDetails nodeDetails; public SearchNodeHealthProvider(Props props, ClusterAppState clusterAppState, NetworkUtils networkUtils) { this(props, clusterAppState, networkUtils, new Clock()); } SearchNodeHealthProvider(Props props, ClusterAppState clusterAppState, NetworkUtils networkUtils, Clock clock) { this.clusterAppState = clusterAppState; this.nodeDetails = NodeDetails.newNodeDetailsBuilder() .setType(NodeDetails.Type.SEARCH) .setName(props.nonNullValue(CLUSTER_NODE_NAME.getKey())) .setHost(getHost(props, networkUtils)) .setPort(Integer.valueOf(props.nonNullValue(CLUSTER_NODE_HZ_PORT.getKey()))) .setStartedAt(clock.now()) .build(); } private static String getHost(Props props, NetworkUtils networkUtils) { String host = props.value(CLUSTER_NODE_HOST.getKey()); if (host != null && !host.isEmpty()) { return host; } return networkUtils.getHostname(); } @Override public NodeHealth get() { NodeHealth.Builder builder = NodeHealth.newNodeHealthBuilder(); if (clusterAppState.isOperational(ProcessId.ELASTICSEARCH, true)) { builder.setStatus(NodeHealth.Status.GREEN); } else { builder.setStatus(NodeHealth.Status.RED) .addCause("Elasticsearch is not operational"); } return builder .setDetails(nodeDetails) .build(); } static class Clock { long now() { return System.currentTimeMillis(); } } }
3,055
36.268293
114
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/cluster/health/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.application.cluster.health; import javax.annotation.ParametersAreNonnullByDefault;
976
39.708333
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/AbstractCommand.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.application.command; import java.io.File; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.annotation.CheckForNull; import org.sonar.application.es.EsInstallation; import org.sonar.process.ProcessId; import org.sonar.process.System2; import static java.util.Objects.requireNonNull; public abstract class AbstractCommand<T extends AbstractCommand> { // unique key among the group of commands to launch private final ProcessId id; private final Map<String, String> envVariables; private final Set<String> suppressedEnvVariables = new HashSet<>(); private final File workDir; private EsInstallation esInstallation; protected AbstractCommand(ProcessId id, File workDir, System2 system2) { this.id = requireNonNull(id, "ProcessId can't be null"); this.workDir = requireNonNull(workDir, "workDir can't be null"); this.envVariables = new HashMap<>(system2.getenv()); } public ProcessId getProcessId() { return id; } public File getWorkDir() { return workDir; } @SuppressWarnings("unchecked") private T castThis() { return (T) this; } public Map<String, String> getEnvVariables() { return envVariables; } public Set<String> getSuppressedEnvVariables() { return suppressedEnvVariables; } public T suppressEnvVariable(String key) { requireNonNull(key, "key can't be null"); suppressedEnvVariables.add(key); envVariables.remove(key); return castThis(); } public T setEnvVariable(String key, String value) { envVariables.put( requireNonNull(key, "key can't be null"), requireNonNull(value, "value can't be null")); return castThis(); } public T setEsInstallation(EsInstallation esInstallation) { this.esInstallation = esInstallation; return castThis(); } @CheckForNull public EsInstallation getEsInstallation() { return esInstallation; } }
2,799
28.787234
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/CeJvmOptions.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.application.command; import java.io.File; import java.util.LinkedHashMap; import java.util.Map; public class CeJvmOptions extends JvmOptions<CeJvmOptions> { public CeJvmOptions(File tmpDir) { super(mandatoryOptions(tmpDir)); } private static Map<String, String> mandatoryOptions(File tmpDir) { Map<String, String> res = new LinkedHashMap<>(3); res.put("-Djava.awt.headless=", "true"); res.put("-Dfile.encoding=", "UTF-8"); res.put("-Djava.io.tmpdir=", tmpDir.getAbsolutePath()); res.put("-XX:-OmitStackTraceInFastThrow", ""); // avoid illegal reflective access operations done by MyBatis res.put("--add-opens=java.base/java.util=ALL-UNNAMED", ""); // avoid illegal reflective access operations done by Hazelcast res.put("--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED", ""); res.put("--add-opens=java.base/java.lang=ALL-UNNAMED", ""); res.put("--add-opens=java.base/java.nio=ALL-UNNAMED", ""); res.put("--add-opens=java.base/sun.nio.ch=ALL-UNNAMED", ""); res.put("--add-opens=java.management/sun.management=ALL-UNNAMED", ""); res.put("--add-opens=jdk.management/com.sun.management.internal=ALL-UNNAMED", ""); // disable FIPS mode for the JVM so SonarQube can use certain algorithms res.put("-Dcom.redhat.fips=", "false"); return res; } }
2,196
38.945455
86
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/CommandFactory.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.application.command; public interface CommandFactory { JavaCommand<EsServerCliJvmOptions> createEsCommand(); JavaCommand<WebJvmOptions> createWebCommand(boolean leader); JavaCommand<CeJvmOptions> createCeCommand(); }
1,089
34.16129
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/CommandFactoryImpl.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.application.command; import java.io.File; import java.nio.file.Paths; import java.util.Map; import java.util.Optional; import org.slf4j.LoggerFactory; import org.sonar.api.internal.MetadataLoader; import org.sonar.api.utils.Version; import org.sonar.application.es.EsInstallation; import org.sonar.application.es.EsLogging; import org.sonar.application.es.EsSettings; import org.sonar.application.es.EsYmlSettings; import org.sonar.process.ProcessId; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; import org.sonar.process.System2; import static org.sonar.process.ProcessProperties.parseTimeoutMs; import static org.sonar.process.ProcessProperties.Property.CE_GRACEFUL_STOP_TIMEOUT; 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.HTTPS_PROXY_HOST; import static org.sonar.process.ProcessProperties.Property.HTTPS_PROXY_PORT; import static org.sonar.process.ProcessProperties.Property.HTTP_AUTH_NTLM_DOMAIN; import static org.sonar.process.ProcessProperties.Property.HTTP_NON_PROXY_HOSTS; import static org.sonar.process.ProcessProperties.Property.HTTP_PROXY_HOST; import static org.sonar.process.ProcessProperties.Property.HTTP_PROXY_PORT; import static org.sonar.process.ProcessProperties.Property.JDBC_DRIVER_PATH; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; 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.SOCKS_PROXY_HOST; import static org.sonar.process.ProcessProperties.Property.SOCKS_PROXY_PORT; import static org.sonar.process.ProcessProperties.Property.WEB_GRACEFUL_STOP_TIMEOUT; import static org.sonar.process.ProcessProperties.Property.WEB_JAVA_ADDITIONAL_OPTS; import static org.sonar.process.ProcessProperties.Property.WEB_JAVA_OPTS; public class CommandFactoryImpl implements CommandFactory { private static final String ENV_VAR_JAVA_TOOL_OPTIONS = "JAVA_TOOL_OPTIONS"; private static final String ENV_VAR_ES_JAVA_OPTS = "ES_JAVA_OPTS"; /** * Properties about proxy that must be set as system properties */ private static final String[] PROXY_PROPERTY_KEYS = new String[] { HTTP_PROXY_HOST.getKey(), HTTP_PROXY_PORT.getKey(), HTTP_NON_PROXY_HOSTS.getKey(), HTTPS_PROXY_HOST.getKey(), HTTPS_PROXY_PORT.getKey(), HTTP_AUTH_NTLM_DOMAIN.getKey(), SOCKS_PROXY_HOST.getKey(), SOCKS_PROXY_PORT.getKey()}; private static final Version SQ_VERSION = MetadataLoader.loadSQVersion(org.sonar.api.utils.System2.INSTANCE); private final Props props; private final File tempDir; public CommandFactoryImpl(Props props, File tempDir, System2 system2) { this.props = props; this.tempDir = tempDir; String javaToolOptions = system2.getenv(ENV_VAR_JAVA_TOOL_OPTIONS); if (javaToolOptions != null && !javaToolOptions.trim().isEmpty()) { LoggerFactory.getLogger(CommandFactoryImpl.class) .warn("JAVA_TOOL_OPTIONS is defined but will be ignored. " + "Use properties sonar.*.javaOpts and/or sonar.*.javaAdditionalOpts in sonar.properties to change SQ JVM processes options"); } String esJavaOpts = system2.getenv(ENV_VAR_ES_JAVA_OPTS); if (esJavaOpts != null && !esJavaOpts.trim().isEmpty()) { LoggerFactory.getLogger(CommandFactoryImpl.class) .warn("ES_JAVA_OPTS is defined but will be ignored. " + "Use properties sonar.search.javaOpts and/or sonar.search.javaAdditionalOpts in sonar.properties to change SQ JVM processes options"); } } @Override public JavaCommand<EsServerCliJvmOptions> createEsCommand() { EsInstallation esInstallation = createEsInstallation(); String esHomeDirectoryAbsolutePath = esInstallation.getHomeDirectory().getAbsolutePath(); return new JavaCommand<EsServerCliJvmOptions>(ProcessId.ELASTICSEARCH, esInstallation.getHomeDirectory()) .setEsInstallation(esInstallation) .setJvmOptions(new EsServerCliJvmOptions(esInstallation)) .setEnvVariable("ES_JAVA_HOME", System.getProperties().getProperty("java.home")) .setClassName("org.elasticsearch.launcher.CliToolLauncher") .addClasspath(Paths.get(esHomeDirectoryAbsolutePath, "lib").toAbsolutePath() + File.separator + "*") .addClasspath(Paths.get(esHomeDirectoryAbsolutePath, "lib", "cli-launcher").toAbsolutePath() + File.separator + "*"); } private EsInstallation createEsInstallation() { EsInstallation esInstallation = new EsInstallation(props); Map<String, String> settingsMap = new EsSettings(props, esInstallation, System2.INSTANCE).build(); esInstallation .setLog4j2Properties(new EsLogging().createProperties(props, esInstallation.getLogDirectory())) .setEsJvmOptions(new EsJvmOptions(props, tempDir) .addFromMandatoryProperty(props, SEARCH_JAVA_OPTS.getKey()) .addFromMandatoryProperty(props, SEARCH_JAVA_ADDITIONAL_OPTS.getKey())) .setEsYmlSettings(new EsYmlSettings(settingsMap)) .setHost(settingsMap.get("http.host")) .setHttpPort(Integer.parseInt(settingsMap.get("http.port"))); return esInstallation; } @Override public JavaCommand<WebJvmOptions> createWebCommand(boolean leader) { File homeDir = props.nonNullValueAsFile(PATH_HOME.getKey()); WebJvmOptions jvmOptions = new WebJvmOptions(tempDir) .addFromMandatoryProperty(props, WEB_JAVA_OPTS.getKey()) .addFromMandatoryProperty(props, WEB_JAVA_ADDITIONAL_OPTS.getKey()); addProxyJvmOptions(jvmOptions); JavaCommand<WebJvmOptions> command = new JavaCommand<WebJvmOptions>(ProcessId.WEB_SERVER, homeDir) .setReadsArgumentsFromFile(true) .setArguments(props.rawProperties()) .setJvmOptions(jvmOptions) .setGracefulStopTimeoutMs(getGracefulStopTimeoutMs(props, WEB_GRACEFUL_STOP_TIMEOUT)) // required for logback tomcat valve .setEnvVariable(PATH_LOGS.getKey(), props.nonNullValue(PATH_LOGS.getKey())) .setArgument("sonar.cluster.web.startupLeader", Boolean.toString(leader)) .setClassName("org.sonar.server.app.WebServer") .addClasspath("./lib/sonar-application-" + SQ_VERSION + ".jar"); String driverPath = props.value(JDBC_DRIVER_PATH.getKey()); if (driverPath != null) { command.addClasspath(driverPath); } command.suppressEnvVariable(ENV_VAR_JAVA_TOOL_OPTIONS); return command; } @Override public JavaCommand<CeJvmOptions> createCeCommand() { File homeDir = props.nonNullValueAsFile(PATH_HOME.getKey()); CeJvmOptions jvmOptions = new CeJvmOptions(tempDir) .addFromMandatoryProperty(props, CE_JAVA_OPTS.getKey()) .addFromMandatoryProperty(props, CE_JAVA_ADDITIONAL_OPTS.getKey()); addProxyJvmOptions(jvmOptions); JavaCommand<CeJvmOptions> command = new JavaCommand<CeJvmOptions>(ProcessId.COMPUTE_ENGINE, homeDir) .setReadsArgumentsFromFile(true) .setArguments(props.rawProperties()) .setJvmOptions(jvmOptions) .setGracefulStopTimeoutMs(getGracefulStopTimeoutMs(props, CE_GRACEFUL_STOP_TIMEOUT)) .setClassName("org.sonar.ce.app.CeServer") .addClasspath("./lib/sonar-application-" + SQ_VERSION + ".jar"); String driverPath = props.value(JDBC_DRIVER_PATH.getKey()); if (driverPath != null) { command.addClasspath(driverPath); } command.suppressEnvVariable(ENV_VAR_JAVA_TOOL_OPTIONS); return command; } private static long getGracefulStopTimeoutMs(Props props, ProcessProperties.Property property) { String value = Optional.ofNullable(props.value(property.getKey())) .orElse(property.getDefaultValue()); // give some time to CE/Web to shutdown itself after graceful stop timed out long gracePeriod = 30 * 1_000L; return parseTimeoutMs(property, value) + gracePeriod; } private <T extends JvmOptions> void addProxyJvmOptions(JvmOptions<T> jvmOptions) { for (String key : PROXY_PROPERTY_KEYS) { getPropsValue(key).ifPresent(val -> jvmOptions.add("-D" + key + "=" + val)); } // defaults of HTTPS are the same than HTTP defaults setSystemPropertyToDefaultIfNotSet(jvmOptions, HTTPS_PROXY_HOST.getKey(), HTTP_PROXY_HOST.getKey()); setSystemPropertyToDefaultIfNotSet(jvmOptions, HTTPS_PROXY_PORT.getKey(), HTTP_PROXY_PORT.getKey()); } private void setSystemPropertyToDefaultIfNotSet(JvmOptions jvmOptions, String httpsProperty, String httpProperty) { Optional<String> httpValue = getPropsValue(httpProperty); Optional<String> httpsValue = getPropsValue(httpsProperty); if (!httpsValue.isPresent() && httpValue.isPresent()) { jvmOptions.add("-D" + httpsProperty + "=" + httpValue.get()); } } private Optional<String> getPropsValue(String key) { return Optional.ofNullable(props.value(key)); } }
9,928
47.199029
144
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/EsJvmOptions.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.application.command; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import org.sonar.process.Props; public class EsJvmOptions extends JvmOptions<EsJvmOptions> { private static final String ELASTICSEARCH_JVM_OPTIONS_HEADER = """ # This file has been automatically generated by SonarQube during startup. # Please use sonar.search.javaOpts and/or sonar.search.javaAdditionalOpts in sonar.properties to specify jvm options for Elasticsearch # DO NOT EDIT THIS FILE """; public EsJvmOptions(Props props, File tmpDir) { super(mandatoryOptions(tmpDir, props)); } // this basically writes down the content of jvm.options file distributed in vanilla Elasticsearch package // with some changes to fit running bundled in SQ private static Map<String, String> mandatoryOptions(File tmpDir, Props props) { Map<String, String> res = new LinkedHashMap<>(30); fromJvmDotOptionsFile(tmpDir, res, props); fromSystemJvmOptionsClass(tmpDir, res); boolean defaultDisableBootstrapChecks = props.value("sonar.jdbc.url", "").contains("jdbc:h2"); if (!props.valueAsBoolean("sonar.es.bootstrap.checks.disable", defaultDisableBootstrapChecks)) { res.put("-Des.enforce.bootstrap.checks=", "true"); } return res; } private static void fromJvmDotOptionsFile(File tmpDir, Map<String, String> res, Props props) { // GC configuration res.put("-XX:+UseG1GC", ""); // (by default ES 6.6.1 uses variable ${ES_TMPDIR} which is replaced by start scripts. Since we start JAR file // directly on windows, we specify absolute file as URL (to support space in path) instead res.put("-Djava.io.tmpdir=", tmpDir.getAbsolutePath()); // heap dumps (enable by default in ES 6.6.1, we don't enable them, no one will analyze them anyway) // generate a heap dump when an allocation from the Java heap fails // heap dumps are created in the working directory of the JVM // res.put("-XX:+HeapDumpOnOutOfMemoryError", ""); // specify an alternative path for heap dumps; ensure the directory exists and // has sufficient space // res.put("-XX:HeapDumpPath", "data"); // specify an alternative path for JVM fatal error logs (ES 6.6.1 default is "logs/hs_err_pid%p.log") var path = Paths.get(props.value("sonar.path.logs", "logs"), "es_hs_err_pid%p.log"); res.put("-XX:ErrorFile=", path.toAbsolutePath().toString()); res.put("-Xlog:disable", ""); } /** * JVM options from class "org.elasticsearch.tools.launchers.SystemJvmOptions" */ private static void fromSystemJvmOptionsClass(File tmpDir, Map<String, String> res) { /* * Cache ttl in seconds for positive DNS lookups noting that this overrides the JDK security property networkaddress.cache.ttl; * can be set to -1 to cache forever. */ res.put("-Des.networkaddress.cache.ttl=", "60"); /* * Cache ttl in seconds for negative DNS lookups noting that this overrides the JDK security property * networkaddress.cache.negative ttl; set to -1 to cache forever. */ res.put("-Des.networkaddress.cache.negative.ttl=", "10"); // pre-touch JVM emory pages during initialization res.put("-XX:+AlwaysPreTouch", ""); // explicitly set the stack size res.put("-Xss1m", ""); // set to headless, just in case, res.put("-Djava.awt.headless=", "true"); // ensure UTF-8 encoding by default (e.g., filenames) res.put("-Dfile.encoding=", "UTF-8"); // use our provided JNA always versus the system one res.put("-Djna.nosys=", "true"); res.put("-Djna.tmpdir=", tmpDir.getAbsolutePath()); /* * Turn off a JDK optimization that throws away stack traces for common exceptions because stack traces are important for * debugging. */ res.put("-XX:-OmitStackTraceInFastThrow", ""); // flags to configure Netty res.put("-Dio.netty.noUnsafe=", "true"); res.put("-Dio.netty.noKeySetOptimization=", "true"); res.put("-Dio.netty.recycler.maxCapacityPerThread=", "0"); res.put("-Dio.netty.allocator.numDirectArenas=", "0"); // log4j 2 res.put("-Dlog4j.shutdownHookEnabled=", "false"); res.put("-Dlog4j2.disable.jmx=", "true"); res.put("-Dlog4j2.formatMsgNoLookups=", "true"); /* * Due to internationalization enhancements in JDK 9 Elasticsearch need to set the provider to COMPAT otherwise time/date * parsing will break in an incompatible way for some date patterns and locales. */ res.put("-Djava.locale.providers=", "COMPAT"); // disable FIPS mode for the JVM so SonarQube can use certain algorithms res.put("-Dcom.redhat.fips=", "false"); } public void writeToJvmOptionFile(File file) { String jvmOptions = getAll().stream().collect(Collectors.joining("\n")); String jvmOptionsContent = ELASTICSEARCH_JVM_OPTIONS_HEADER + jvmOptions; try { Files.write(file.toPath(), jvmOptionsContent.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new IllegalStateException("Cannot write Elasticsearch jvm options file", e); } } }
6,127
43.086331
138
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/EsServerCliJvmOptions.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.application.command; import java.util.LinkedHashMap; import java.util.Map; import org.sonar.application.es.EsInstallation; class EsServerCliJvmOptions extends JvmOptions<EsServerCliJvmOptions> { public EsServerCliJvmOptions(EsInstallation esInstallation) { super(mandatoryOptions(esInstallation)); } private static Map<String, String> mandatoryOptions(EsInstallation esInstallation) { Map<String, String> res = new LinkedHashMap<>(9); res.put("-Xms4m", ""); res.put("-Xmx64m", ""); res.put("-XX:+UseSerialGC", ""); res.put("-Dcli.name=", "server"); res.put("-Dcli.script=", "./bin/elasticsearch"); res.put("-Dcli.libs=", "lib/tools/server-cli"); res.put("-Des.path.home=", esInstallation.getHomeDirectory().getAbsolutePath()); res.put("-Des.path.conf=", esInstallation.getConfDirectory().getAbsolutePath()); res.put("-Des.distribution.type=", "tar"); return res; } }
1,788
37.891304
86
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/JavaCommand.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.application.command; import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import javax.annotation.Nullable; import org.sonar.process.ProcessId; import org.sonar.process.System2; import static java.util.Objects.requireNonNull; public class JavaCommand<T extends JvmOptions> extends AbstractCommand<JavaCommand<T>> { // program arguments private final Map<String, String> arguments = new LinkedHashMap<>(); private final List<String> parameters = new LinkedList<>(); // entry point private String className; private JvmOptions<T> jvmOptions; // relative path to JAR files private final List<String> classpath = new ArrayList<>(); private boolean readsArgumentsFromFile; private Long gracefulStopTimeoutMs; public JavaCommand(ProcessId id, File workDir) { super(id, workDir, System2.INSTANCE); } public Map<String, String> getArguments() { return arguments; } public JavaCommand<T> setArgument(String key, @Nullable String value) { if (value == null) { arguments.remove(key); } else { arguments.put(key, value); } return this; } public List<String> getParameters() { return parameters; } public JavaCommand<T> addParameter(@Nullable String parameter) { if (parameter == null) { parameters.remove(parameter); } else { parameters.add(parameter); } return this; } public String getClassName() { return className; } public JavaCommand<T> setClassName(String className) { this.className = className; return this; } public JvmOptions<T> getJvmOptions() { return jvmOptions; } public JavaCommand<T> setJvmOptions(JvmOptions<T> jvmOptions) { this.jvmOptions = jvmOptions; return this; } public List<String> getClasspath() { return classpath; } public JavaCommand<T> addClasspath(String s) { classpath.add(s); return this; } public boolean getReadsArgumentsFromFile() { return readsArgumentsFromFile; } public JavaCommand<T> setReadsArgumentsFromFile(boolean readsArgumentsFromFile) { this.readsArgumentsFromFile = readsArgumentsFromFile; return this; } public JavaCommand<T> setArguments(Properties args) { for (Map.Entry<Object, Object> entry : args.entrySet()) { setArgument(entry.getKey().toString(), entry.getValue() != null ? entry.getValue().toString() : null); } return this; } public long getGracefulStopTimeoutMs() { requireNonNull(gracefulStopTimeoutMs, "gracefulStopTimeoutMs has not been set"); return gracefulStopTimeoutMs; } public JavaCommand<T> setGracefulStopTimeoutMs(long gracefulStopTimeoutMs) { this.gracefulStopTimeoutMs = gracefulStopTimeoutMs; return this; } @Override public String toString() { return "JavaCommand{" + "workDir=" + getWorkDir() + ", arguments=" + arguments + ", className='" + className + '\'' + ", jvmOptions=" + jvmOptions + ", classpath=" + classpath + ", readsArgumentsFromFile=" + readsArgumentsFromFile + ", gracefulStopTimeoutMs=" + gracefulStopTimeoutMs + ", envVariables=" + getEnvVariables() + ", suppressedEnvVariables=" + getSuppressedEnvVariables() + '}'; } }
4,215
28.075862
108
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/JvmOptions.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.application.command; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.process.MessageException; import org.sonar.process.Props; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.joining; public class JvmOptions<T extends JvmOptions> { private static final String JVM_OPTION_NOT_NULL_ERROR_MESSAGE = "a JVM option can't be null"; private final HashMap<String, String> mandatoryOptions = new HashMap<>(); private final LinkedHashSet<String> options = new LinkedHashSet<>(); public JvmOptions() { this(Collections.emptyMap()); } public JvmOptions(Map<String, String> mandatoryJvmOptions) { requireNonNull(mandatoryJvmOptions, JVM_OPTION_NOT_NULL_ERROR_MESSAGE) .entrySet() .stream() .filter(e -> { requireNonNull(e.getKey(), "JVM option prefix can't be null"); if (e.getKey().trim().isEmpty()) { throw new IllegalArgumentException("JVM option prefix can't be empty"); } requireNonNull(e.getValue(), "JVM option value can't be null"); return true; }).forEach(e -> { String key = e.getKey().trim(); String value = e.getValue().trim(); mandatoryOptions.put(key, value); add(key + value); }); } public T addFromMandatoryProperty(Props props, String propertyName) { String value = props.nonNullValue(propertyName); if (!value.isEmpty()) { String splitRegex = " (?=-)"; List<String> jvmOptions = Arrays.stream(value.split(splitRegex)).map(String::trim).toList(); checkOptionFormat(propertyName, jvmOptions); checkMandatoryOptionOverwrite(propertyName, jvmOptions); options.addAll(jvmOptions); } return castThis(); } private static void checkOptionFormat(String propertyName, List<String> jvmOptionsFromProperty) { List<String> invalidOptions = jvmOptionsFromProperty.stream() .filter(JvmOptions::isInvalidOption) .toList(); if (!invalidOptions.isEmpty()) { throw new MessageException(format( "a JVM option can't be empty and must start with '-'. The following JVM options defined by property '%s' are invalid: %s", propertyName, invalidOptions.stream() .collect(joining(", ")))); } } private void checkMandatoryOptionOverwrite(String propertyName, List<String> jvmOptionsFromProperty) { List<Match> matches = jvmOptionsFromProperty.stream() .map(jvmOption -> new Match(jvmOption, mandatoryOptionFor(jvmOption))) .filter(match -> match.mandatoryOption() != null) .toList(); if (!matches.isEmpty()) { throw new MessageException(format( "a JVM option can't overwrite mandatory JVM options. The following JVM options defined by property '%s' are invalid: %s", propertyName, matches.stream() .map(m -> m.option() + " overwrites " + m.mandatoryOption.getKey() + m.mandatoryOption.getValue()) .collect(joining(", ")))); } } /** * Add an option. * Argument is trimmed before being added. * * @throws IllegalArgumentException if argument is empty or does not start with {@code -}. */ public T add(String str) { requireNonNull(str, JVM_OPTION_NOT_NULL_ERROR_MESSAGE); String value = str.trim(); if (isInvalidOption(value)) { throw new IllegalArgumentException("a JVM option can't be empty and must start with '-'"); } checkMandatoryOptionOverwrite(value); options.add(value); return castThis(); } private void checkMandatoryOptionOverwrite(String value) { Map.Entry<String, String> overriddenMandatoryOption = mandatoryOptionFor(value); if (overriddenMandatoryOption != null) { throw new MessageException(String.format( "a JVM option can't overwrite mandatory JVM options. %s overwrites %s", value, overriddenMandatoryOption.getKey() + overriddenMandatoryOption.getValue())); } } @CheckForNull private Map.Entry<String, String> mandatoryOptionFor(String jvmOption) { return mandatoryOptions.entrySet().stream() .filter(s -> jvmOption.startsWith(s.getKey()) && !jvmOption.equals(s.getKey() + s.getValue())) .findFirst() .orElse(null); } private static boolean isInvalidOption(String value) { return value.isEmpty() || !value.startsWith("-"); } @SuppressWarnings("unchecked") private T castThis() { return (T) this; } public List<String> getAll() { return new ArrayList<>(options); } @Override public String toString() { return options.toString(); } private record Match(String option, Map.Entry<String, String> mandatoryOption) { private Match(String option, @Nullable Map.Entry<String, String> mandatoryOption) { this.option = option; this.mandatoryOption = mandatoryOption; } } }
5,973
34.141176
130
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/WebJvmOptions.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.application.command; import java.io.File; import java.util.LinkedHashMap; import java.util.Map; public class WebJvmOptions extends JvmOptions<WebJvmOptions> { public WebJvmOptions(File tmpDir) { super(mandatoryOptions(tmpDir)); } private static Map<String, String> mandatoryOptions(File tmpDir) { Map<String, String> res = new LinkedHashMap<>(3); res.put("-Djava.awt.headless=", "true"); res.put("-Dfile.encoding=", "UTF-8"); res.put("-Djava.io.tmpdir=", tmpDir.getAbsolutePath()); res.put("-XX:-OmitStackTraceInFastThrow", ""); // avoid illegal reflective access operations done by MyBatis res.put("--add-opens=java.base/java.util=ALL-UNNAMED", ""); // avoid illegal reflective access operations done by Tomcat res.put("--add-opens=java.base/java.lang=ALL-UNNAMED", ""); res.put("--add-opens=java.base/java.io=ALL-UNNAMED", ""); res.put("--add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED", ""); // avoid illegal reflective access operations done by Hazelcast res.put("--add-exports=java.base/jdk.internal.ref=ALL-UNNAMED", ""); res.put("--add-opens=java.base/java.nio=ALL-UNNAMED", ""); res.put("--add-opens=java.base/sun.nio.ch=ALL-UNNAMED", ""); res.put("--add-opens=java.management/sun.management=ALL-UNNAMED", ""); res.put("--add-opens=jdk.management/com.sun.management.internal=ALL-UNNAMED", ""); // disable FIPS mode for the JVM so SonarQube can use certain algorithms res.put("-Dcom.redhat.fips=", "false"); return res; } }
2,398
39.661017
86
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/command/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.application.command; import javax.annotation.ParametersAreNonnullByDefault;
969
39.416667
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/AppSettings.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.application.config; import java.util.Optional; import org.sonar.process.Props; public interface AppSettings { Props getProps(); Optional<String> getValue(String key); void reload(Props copy); }
1,066
31.333333
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/AppSettingsImpl.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.application.config; import java.util.Optional; import org.sonar.process.Props; public class AppSettingsImpl implements AppSettings { private volatile Props props; AppSettingsImpl(Props props) { this.props = props; } @Override public Props getProps() { return props; } @Override public Optional<String> getValue(String key) { return Optional.ofNullable(props.value(key)); } @Override public void reload(Props copy) { this.props = copy; } }
1,347
27.083333
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/AppSettingsLoader.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.application.config; public interface AppSettingsLoader { AppSettings load(); }
945
34.037037
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/AppSettingsLoaderImpl.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.application.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.URISyntaxException; import java.util.HashSet; import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import org.slf4j.LoggerFactory; import org.sonar.core.extension.ServiceLoaderWrapper; import org.sonar.core.util.SettingFormatter; import org.sonar.process.ConfigurationUtils; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; import org.sonar.process.System2; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.stream; import static java.util.Optional.ofNullable; import static org.sonar.core.util.SettingFormatter.fromJavaPropertyToEnvVariable; import static org.sonar.process.ProcessProperties.Property.LDAP_SERVERS; import static org.sonar.process.ProcessProperties.Property.MULTI_SERVER_LDAP_SETTINGS; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; public class AppSettingsLoaderImpl implements AppSettingsLoader { private final System2 system; private final File homeDir; private final String[] cliArguments; private final Consumer<Props>[] consumers; private final ServiceLoaderWrapper serviceLoaderWrapper; public AppSettingsLoaderImpl(System2 system, String[] cliArguments, ServiceLoaderWrapper serviceLoaderWrapper) { this(system, cliArguments, detectHomeDir(), serviceLoaderWrapper, new FileSystemSettings(), new JdbcSettings(), new ClusterSettings(NetworkUtilsImpl.INSTANCE)); } @SafeVarargs AppSettingsLoaderImpl(System2 system, String[] cliArguments, File homeDir, ServiceLoaderWrapper serviceLoaderWrapper, Consumer<Props>... consumers) { this.system = system; this.cliArguments = cliArguments; this.homeDir = homeDir; this.serviceLoaderWrapper = serviceLoaderWrapper; this.consumers = consumers; } File getHomeDir() { return homeDir; } @Override public AppSettings load() { Properties p = loadPropertiesFile(homeDir); Set<String> keysOverridableFromEnv = stream(ProcessProperties.Property.values()).map(ProcessProperties.Property::getKey) .collect(Collectors.toSet()); keysOverridableFromEnv.addAll(p.stringPropertyNames()); // 1st pass to load static properties Props staticProps = reloadProperties(keysOverridableFromEnv, p); keysOverridableFromEnv.addAll(getDynamicPropertiesKeys(staticProps)); // 2nd pass to load dynamic properties like `ldap.*.url` or `ldap.*.baseDn` which keys depend on values of static // properties loaded in 1st step Props props = reloadProperties(keysOverridableFromEnv, p); new ProcessProperties(serviceLoaderWrapper).completeDefaults(props); stream(consumers).forEach(c -> c.accept(props)); return new AppSettingsImpl(props); } private static Set<String> getDynamicPropertiesKeys(Props p) { Set<String> dynamicPropertiesKeys = new HashSet<>(); String ldapServersValue = p.value(LDAP_SERVERS.getKey()); if (ldapServersValue != null) { stream(SettingFormatter.getStringArrayBySeparator(ldapServersValue, ",")).forEach( ldapServer -> MULTI_SERVER_LDAP_SETTINGS.forEach( multiLdapSetting -> dynamicPropertiesKeys.add(multiLdapSetting.replace("*", ldapServer)))); } return dynamicPropertiesKeys; } private Props reloadProperties(Set<String> keysOverridableFromEnv, Properties p) { loadPropertiesFromEnvironment(system, p, keysOverridableFromEnv); p.putAll(CommandLineParser.parseArguments(cliArguments)); p.setProperty(PATH_HOME.getKey(), homeDir.getAbsolutePath()); p = ConfigurationUtils.interpolateVariables(p, system.getenv()); // the difference between Properties and Props is that the latter // supports decryption of values, so it must be used when values // are accessed return new Props(p); } private static void loadPropertiesFromEnvironment(System2 system, Properties properties, Set<String> overridableSettings) { overridableSettings.forEach(key -> { String environmentVarName = fromJavaPropertyToEnvVariable(key); Optional<String> envVarValue = ofNullable(system.getenv(environmentVarName)); envVarValue.ifPresent(value -> properties.put(key, value)); }); } private static File detectHomeDir() { try { File appJar = new File(Class.forName("org.sonar.application.App").getProtectionDomain().getCodeSource().getLocation().toURI()); return appJar.getParentFile().getParentFile(); } catch (URISyntaxException | ClassNotFoundException e) { throw new IllegalStateException("Cannot detect path of main jar file", e); } } /** * Loads the configuration file ${homeDir}/conf/sonar.properties. * An empty {@link Properties} is returned if the file does not exist. */ private static Properties loadPropertiesFile(File homeDir) { Properties p = new Properties(); File propsFile = new File(homeDir, "conf/sonar.properties"); if (propsFile.exists()) { try (Reader reader = new InputStreamReader(new FileInputStream(propsFile), UTF_8)) { p.load(reader); } catch (IOException e) { throw new IllegalStateException("Cannot open file " + propsFile, e); } } else { LoggerFactory.getLogger(AppSettingsLoaderImpl.class).warn("Configuration file not found: {}", propsFile); } return p; } }
6,441
40.031847
151
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/ClusterSettings.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.application.config; import com.google.common.net.HostAndPort; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.process.MessageException; import org.sonar.process.NetworkUtils; import org.sonar.process.ProcessId; import org.sonar.process.ProcessProperties.Property; import org.sonar.process.Props; import org.sonar.process.cluster.NodeType; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; import static org.sonar.process.ProcessProperties.Property.AUTH_JWT_SECRET; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_HZ_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_ES_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_TYPE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_WEB_STARTUP_LEADER; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; import static org.sonar.process.ProcessProperties.Property.SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.SEARCH_PORT; public class ClusterSettings implements Consumer<Props> { private static final Set<Property> FORBIDDEN_SEARCH_NODE_SETTINGS = EnumSet.of(SEARCH_HOST, SEARCH_PORT); private final NetworkUtils network; public ClusterSettings(NetworkUtils network) { this.network = network; } @Override public void accept(Props props) { if (isClusterEnabled(props)) { checkClusterProperties(props); } } private void checkClusterProperties(Props props) { // for internal use if (props.value(CLUSTER_WEB_STARTUP_LEADER.getKey()) != null) { throw new MessageException(format("Property [%s] is forbidden", CLUSTER_WEB_STARTUP_LEADER.getKey())); } NodeType nodeType = toNodeType(props); switch (nodeType) { case APPLICATION: checkForApplicationNode(props); break; case SEARCH: checkForSearchNode(props); break; default: throw new UnsupportedOperationException("Unknown value: " + nodeType); } } private void checkForApplicationNode(Props props) { ensureNotH2(props); requireValue(props, AUTH_JWT_SECRET); Set<AddressAndPort> hzNodes = parseAndCheckHosts(CLUSTER_HZ_HOSTS, requireValue(props, CLUSTER_HZ_HOSTS)); ensureNotLoopbackAddresses(CLUSTER_HZ_HOSTS, hzNodes); checkClusterNodeHost(props); checkClusterSearchHosts(props); } private void checkForSearchNode(Props props) { ensureNoSearchNodeForbiddenSettings(props); AddressAndPort searchHost = parseAndCheckHost(CLUSTER_NODE_SEARCH_HOST, requireValue(props, CLUSTER_NODE_SEARCH_HOST)); ensureLocalButNotLoopbackAddress(CLUSTER_NODE_SEARCH_HOST, searchHost); AddressAndPort esHost = parseAndCheckHost(CLUSTER_NODE_ES_HOST, requireValue(props, CLUSTER_NODE_ES_HOST)); ensureLocalButNotLoopbackAddress(CLUSTER_NODE_ES_HOST, esHost); checkClusterEsHosts(props); } private void checkClusterNodeHost(Props props) { AddressAndPort clusterNodeHost = parseAndCheckHost(CLUSTER_NODE_HOST, requireValue(props, CLUSTER_NODE_HOST)); ensureLocalButNotLoopbackAddress(CLUSTER_NODE_HOST, clusterNodeHost); } private void checkClusterSearchHosts(Props props) { Set<AddressAndPort> searchHosts = parseAndCheckHosts(CLUSTER_SEARCH_HOSTS, requireValue(props, CLUSTER_SEARCH_HOSTS)); ensureNotLoopbackAddresses(CLUSTER_SEARCH_HOSTS, searchHosts); } private void checkClusterEsHosts(Props props) { Set<AddressAndPort> esHosts = parseHosts(requireValue(props, CLUSTER_ES_HOSTS)); ensureNotLoopbackAddresses(CLUSTER_ES_HOSTS, esHosts); ensureEitherPortsAreProvidedOrOnlyHosts(CLUSTER_ES_HOSTS, esHosts); } private static Set<AddressAndPort> parseHosts(String value) { return stream(value.split(",")) .filter(Objects::nonNull) .map(String::trim) .map(ClusterSettings::parseHost) .collect(toSet()); } private Set<AddressAndPort> parseAndCheckHosts(Property property, String value) { Set<AddressAndPort> res = parseHosts(value); checkValidHosts(property, res); return res; } private void checkValidHosts(Property property, Set<AddressAndPort> addressAndPorts) { List<String> invalidHosts = addressAndPorts.stream() .map(AddressAndPort::getHost) .filter(t -> !network.toInetAddress(t).isPresent()) .sorted() .toList(); if (!invalidHosts.isEmpty()) { throw new MessageException(format("Address in property %s is not a valid address: %s", property.getKey(), String.join(", ", invalidHosts))); } } private static AddressAndPort parseHost(String value) { HostAndPort hostAndPort = HostAndPort.fromString(value); return new AddressAndPort(hostAndPort.getHost(), hostAndPort.hasPort() ? hostAndPort.getPort() : null); } private AddressAndPort parseAndCheckHost(Property property, String value) { AddressAndPort addressAndPort = parseHost(value); checkValidHosts(property, singleton(addressAndPort)); return addressAndPort; } public static NodeType toNodeType(Props props) { String nodeTypeValue = requireValue(props, CLUSTER_NODE_TYPE); if (!NodeType.isValid(nodeTypeValue)) { throw new MessageException(format("Invalid value for property %s: [%s], only [%s] are allowed", CLUSTER_NODE_TYPE.getKey(), nodeTypeValue, Arrays.stream(NodeType.values()).map(NodeType::getValue).collect(joining(", ")))); } return NodeType.parse(nodeTypeValue); } private static String requireValue(Props props, Property property) { String key = property.getKey(); String value = props.value(key); String trimmedValue = value == null ? null : value.trim(); if (trimmedValue == null || trimmedValue.isEmpty()) { throw new MessageException(format("Property %s is mandatory", key)); } return trimmedValue; } private static void ensureNoSearchNodeForbiddenSettings(Props props) { List<String> violations = FORBIDDEN_SEARCH_NODE_SETTINGS.stream() .filter(setting -> props.value(setting.getKey()) != null) .map(Property::getKey) .toList(); if (!violations.isEmpty()) { throw new MessageException(format("Properties [%s] are not allowed when running SonarQube in cluster mode.", String.join(", ", violations))); } } private static void ensureNotH2(Props props) { String jdbcUrl = props.value(JDBC_URL.getKey()); String trimmedJdbcUrl = jdbcUrl == null ? null : jdbcUrl.trim(); if (trimmedJdbcUrl == null || trimmedJdbcUrl.isEmpty() || trimmedJdbcUrl.startsWith("jdbc:h2:")) { throw new MessageException("Embedded database is not supported in cluster mode"); } } private void ensureNotLoopbackAddresses(Property property, Set<AddressAndPort> hostAndPorts) { Set<AddressAndPort> loopbackAddresses = hostAndPorts.stream() .filter(t -> network.isLoopback(t.getHost())) .collect(toSet()); if (!loopbackAddresses.isEmpty()) { throw new MessageException(format("Property %s must not contain a loopback address: %s", property.getKey(), loopbackAddresses.stream().map(AddressAndPort::getHost).sorted().collect(Collectors.joining(", ")))); } } private void ensureLocalButNotLoopbackAddress(Property property, AddressAndPort addressAndPort) { String host = addressAndPort.getHost(); if (!network.isLocal(host) || network.isLoopback(host)) { throw new MessageException(format("Property %s must be a local non-loopback address: %s", property.getKey(), addressAndPort.getHost())); } } private static void ensureEitherPortsAreProvidedOrOnlyHosts(Property property, Set<AddressAndPort> addressAndPorts) { Set<AddressAndPort> hostsWithoutPort = addressAndPorts.stream() .filter(t -> !t.hasPort()) .collect(toSet()); if (!hostsWithoutPort.isEmpty() && hostsWithoutPort.size() != addressAndPorts.size()) { throw new MessageException(format("Entries in property %s must not mix 'host:port' and 'host'. Provide hosts without port only or hosts with port only.", property.getKey())); } } private static class AddressAndPort { private static final int NO_PORT = -1; /** * the host from setting, can be a hostname or an IP address */ private final String host; private final int port; private AddressAndPort(String host, @Nullable Integer port) { this.host = host; this.port = port == null ? NO_PORT : port; } public String getHost() { return host; } public boolean hasPort() { return port != NO_PORT; } } public static boolean isClusterEnabled(AppSettings settings) { return isClusterEnabled(settings.getProps()); } private static boolean isClusterEnabled(Props props) { return props.valueAsBoolean(CLUSTER_ENABLED.getKey()); } /** * Hazelcast must be started when cluster is activated on all nodes but search ones */ public static boolean shouldStartHazelcast(AppSettings appSettings) { return isClusterEnabled(appSettings.getProps()) && toNodeType(appSettings.getProps()).equals(NodeType.APPLICATION); } public static List<ProcessId> getEnabledProcesses(AppSettings settings) { if (!isClusterEnabled(settings)) { return asList(ProcessId.ELASTICSEARCH, ProcessId.WEB_SERVER, ProcessId.COMPUTE_ENGINE); } NodeType nodeType = NodeType.parse(settings.getValue(CLUSTER_NODE_TYPE.getKey()).orElse("")); switch (nodeType) { case APPLICATION: return asList(ProcessId.WEB_SERVER, ProcessId.COMPUTE_ENGINE); case SEARCH: return singletonList(ProcessId.ELASTICSEARCH); default: throw new IllegalArgumentException("Unexpected node type " + nodeType); } } public static boolean isLocalElasticsearchEnabled(AppSettings settings) { // elasticsearch is enabled on "search" nodes, but disabled on "application" nodes if (isClusterEnabled(settings.getProps())) { return NodeType.parse(settings.getValue(CLUSTER_NODE_TYPE.getKey()).orElse("")) == NodeType.SEARCH; } // elasticsearch is enabled in standalone mode return true; } }
11,808
39.441781
180
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/CommandLineParser.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.application.config; import org.apache.commons.lang.StringUtils; import java.util.Map; import java.util.Properties; public class CommandLineParser { private CommandLineParser() { // prevent instantiation } /** * Build properties from command-line arguments and system properties */ public static Properties parseArguments(String[] args) { Properties props = argumentsToProperties(args); // complete with only the system properties that start with "sonar." for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) { String key = entry.getKey().toString(); if (key.startsWith("sonar.")) { props.setProperty(key, entry.getValue().toString()); } } return props; } /** * Convert strings "-Dkey=value" to properties */ static Properties argumentsToProperties(String[] args) { Properties props = new Properties(); for (String arg : args) { if (!arg.startsWith("-D") || !arg.contains("=")) { throw new IllegalArgumentException(String.format( "Command-line argument must start with -D, for example -Dsonar.jdbc.username=sonar. Got: %s", arg)); } String key = StringUtils.substringBefore(arg, "=").substring(2); String value = StringUtils.substringAfter(arg, "="); props.setProperty(key, value); } return props; } }
2,232
32.833333
110
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/FileSystemSettings.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.application.config; import java.io.File; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.Props; 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_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; import static org.sonar.process.ProcessProperties.Property.PATH_WEB; public class FileSystemSettings implements Consumer<Props> { private static final Logger LOG = LoggerFactory.getLogger(FileSystemSettings.class); @Override public void accept(Props props) { ensurePropertyIsAbsolutePath(props, PATH_DATA.getKey()); ensurePropertyIsAbsolutePath(props, PATH_WEB.getKey()); ensurePropertyIsAbsolutePath(props, PATH_LOGS.getKey()); ensurePropertyIsAbsolutePath(props, PATH_TEMP.getKey()); } private static File ensurePropertyIsAbsolutePath(Props props, String propKey) { // default values are set by ProcessProperties String path = props.nonNullValue(propKey); File d = new File(path); if (!d.isAbsolute()) { File homeDir = props.nonNullValueAsFile(PATH_HOME.getKey()); d = new File(homeDir, path); LOG.trace("Overriding property {} from relative path '{}' to absolute path '{}'", propKey, path, d.getAbsolutePath()); props.set(propKey, d.getAbsolutePath()); } return d; } }
2,362
38.383333
124
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/JdbcSettings.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.application.config; import java.io.File; import java.net.Inet6Address; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.MessageException; import org.sonar.process.Props; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; import static org.sonar.process.ProcessProperties.Property.JDBC_DRIVER_PATH; import static org.sonar.process.ProcessProperties.Property.JDBC_EMBEDDED_PORT; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; public class JdbcSettings implements Consumer<Props> { private static final String IGNORED_KEYWORDS_OPTION = ";NON_KEYWORDS=VALUE"; private static final int JDBC_EMBEDDED_PORT_DEFAULT_VALUE = 9092; enum Provider { H2("lib/jdbc/h2"), SQLSERVER("lib/jdbc/mssql"), ORACLE("extensions/jdbc-driver/oracle"), POSTGRESQL("lib/jdbc/postgresql"); final String path; Provider(String path) { this.path = path; } } @Override public void accept(Props props) { File homeDir = props.nonNullValueAsFile(PATH_HOME.getKey()); Provider provider = resolveProviderAndEnforceNonnullJdbcUrl(props); String driverPath = driverPath(homeDir, provider); props.set(JDBC_DRIVER_PATH.getKey(), driverPath); } String driverPath(File homeDir, Provider provider) { String dirPath = provider.path; File dir = new File(homeDir, dirPath); if (!dir.exists()) { throw new MessageException("Directory does not exist: " + dirPath); } List<File> files = new ArrayList<>(FileUtils.listFiles(dir, new String[] {"jar"}, false)); if (files.isEmpty()) { throw new MessageException("Directory does not contain JDBC driver: " + dirPath); } if (files.size() > 1) { throw new MessageException("Directory must contain only one JAR file: " + dirPath); } return files.get(0).getAbsolutePath(); } Provider resolveProviderAndEnforceNonnullJdbcUrl(Props props) { String url = props.value(JDBC_URL.getKey()); Integer embeddedDatabasePort = props.valueAsInt(JDBC_EMBEDDED_PORT.getKey()); if (embeddedDatabasePort != null) { String correctUrl = buildH2JdbcUrl(embeddedDatabasePort); warnIfUrlIsSet(embeddedDatabasePort, url, correctUrl); props.set(JDBC_URL.getKey(), correctUrl); return Provider.H2; } if (isEmpty(url)) { props.set(JDBC_URL.getKey(), buildH2JdbcUrl(JDBC_EMBEDDED_PORT_DEFAULT_VALUE)); props.set(JDBC_EMBEDDED_PORT.getKey(), String.valueOf(JDBC_EMBEDDED_PORT_DEFAULT_VALUE)); return Provider.H2; } Pattern pattern = Pattern.compile("jdbc:(\\w+):.+"); Matcher matcher = pattern.matcher(url); if (!matcher.find()) { throw new MessageException(format("Bad format of JDBC URL: %s", url)); } String key = matcher.group(1); try { return Provider.valueOf(StringUtils.upperCase(key)); } catch (IllegalArgumentException e) { throw new MessageException(format("Unsupported JDBC driver provider: %s", key)); } } private static String buildH2JdbcUrl(int embeddedDatabasePort) { InetAddress ip = InetAddress.getLoopbackAddress(); String host; if (ip instanceof Inet6Address) { host = "[" + ip.getHostAddress() + "]"; } else { host = ip.getHostAddress(); } return format("jdbc:h2:tcp://%s:%d/sonar%s", host, embeddedDatabasePort, IGNORED_KEYWORDS_OPTION); } private static void warnIfUrlIsSet(int port, String existing, String expectedUrl) { if (isNotEmpty(existing)) { Logger logger = LoggerFactory.getLogger(JdbcSettings.class); if (expectedUrl.equals(existing)) { logger.warn("To change H2 database port, only property '" + JDBC_EMBEDDED_PORT + "' should be set (which current value is '{}'). " + "Remove property '" + JDBC_URL + "' from configuration to remove this warning.", port); } else { logger.warn("Both '" + JDBC_EMBEDDED_PORT + "' and '" + JDBC_URL + "' properties are set. " + "The value of property '" + JDBC_URL + "' ('{}') is not consistent with the value of property '" + JDBC_EMBEDDED_PORT + "' ('{}'). " + "The value of property '" + JDBC_URL + "' will be ignored and value '{}' will be used instead. " + "To remove this warning, either remove property '" + JDBC_URL + "' if your intent was to use the embedded H2 database, otherwise remove property '" + JDBC_EMBEDDED_PORT + "'.", existing, port, expectedUrl); } } } }
5,810
38.80137
114
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/SonarQubeVersionHelper.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.application.config; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import static java.lang.String.format; public class SonarQubeVersionHelper { private static final String SONARQUBE_VERSION_PATH = "/sq-version.txt"; private static String sonarqubeVersion; private SonarQubeVersionHelper() { // only static methods } public static String getSonarqubeVersion() { if (sonarqubeVersion == null) { loadVersion(); } return sonarqubeVersion; } private static synchronized void loadVersion() { try { try (BufferedReader in = new BufferedReader( new InputStreamReader( SonarQubeVersionHelper.class.getResourceAsStream(SONARQUBE_VERSION_PATH), StandardCharsets.UTF_8 ))) { sonarqubeVersion = in.readLine(); } } catch (IOException e) { throw new IllegalStateException(format("Cannot load %s from classpath", SONARQUBE_VERSION_PATH), e); } } }
1,900
31.220339
106
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/config/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.application.config; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/es/EsConnector.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.application.es; import java.util.Optional; import org.elasticsearch.cluster.health.ClusterHealthStatus; public interface EsConnector { Optional<ClusterHealthStatus> getClusterHealthStatus(); void stop(); }
1,074
34.833333
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/es/EsConnectorImpl.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.application.es; import com.google.common.net.HostAndPort; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.util.Arrays; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import javax.annotation.Nullable; import javax.net.ssl.SSLContext; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.elasticsearch.core.TimeValue.timeValueSeconds; public class EsConnectorImpl implements EsConnector { private static final String ES_USERNAME = "elastic"; private static final Logger LOG = LoggerFactory.getLogger(EsConnectorImpl.class); private final AtomicReference<RestHighLevelClient> restClient = new AtomicReference<>(null); private final Set<HostAndPort> hostAndPorts; private final String searchPassword; private final Path keyStorePath; private final String keyStorePassword; public EsConnectorImpl(Set<HostAndPort> hostAndPorts, @Nullable String searchPassword, @Nullable Path keyStorePath, @Nullable String keyStorePassword) { this.hostAndPorts = hostAndPorts; this.searchPassword = searchPassword; this.keyStorePath = keyStorePath; this.keyStorePassword = keyStorePassword; } @Override public Optional<ClusterHealthStatus> getClusterHealthStatus() { try { ClusterHealthResponse healthResponse = getRestHighLevelClient().cluster() .health(new ClusterHealthRequest().waitForYellowStatus().timeout(timeValueSeconds(30)), RequestOptions.DEFAULT); return Optional.of(healthResponse.getStatus()); } catch (IOException e) { LOG.trace("Failed to check health status ", e); return Optional.empty(); } } @Override public void stop() { RestHighLevelClient restHighLevelClient = restClient.get(); if (restHighLevelClient != null) { try { restHighLevelClient.close(); } catch (IOException e) { LOG.warn("Error occurred while closing Rest Client", e); } } } private RestHighLevelClient getRestHighLevelClient() { RestHighLevelClient res = this.restClient.get(); if (res != null) { return res; } RestHighLevelClient restHighLevelClient = buildRestHighLevelClient(); this.restClient.set(restHighLevelClient); return restHighLevelClient; } private RestHighLevelClient buildRestHighLevelClient() { HttpHost[] httpHosts = hostAndPorts.stream() .map(this::toHttpHost) .toArray(HttpHost[]::new); if (LOG.isDebugEnabled()) { String addresses = Arrays.stream(httpHosts) .map(t -> t.getHostName() + ":" + t.getPort()) .collect(Collectors.joining(", ")); LOG.debug("Connected to Elasticsearch node: [{}]", addresses); } RestClientBuilder builder = RestClient.builder(httpHosts) .setHttpClientConfigCallback(httpClientBuilder -> { if (searchPassword != null) { BasicCredentialsProvider provider = getBasicCredentialsProvider(searchPassword); httpClientBuilder.setDefaultCredentialsProvider(provider); } if (keyStorePath != null) { SSLContext sslContext = getSSLContext(keyStorePath, keyStorePassword); httpClientBuilder.setSSLContext(sslContext); } return httpClientBuilder; }); return new RestHighLevelClient(builder); } private HttpHost toHttpHost(HostAndPort host) { try { String scheme = keyStorePath != null ? "https" : HttpHost.DEFAULT_SCHEME_NAME; return new HttpHost(InetAddress.getByName(host.getHost()), host.getPortOrDefault(9001), scheme); } catch (UnknownHostException e) { throw new IllegalStateException("Can not resolve host [" + host + "]", e); } } private static BasicCredentialsProvider getBasicCredentialsProvider(String searchPassword) { BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(ES_USERNAME, searchPassword)); return provider; } private static SSLContext getSSLContext(Path keyStorePath, @Nullable String keyStorePassword) { try { KeyStore keyStore = KeyStore.getInstance("pkcs12"); try (InputStream is = Files.newInputStream(keyStorePath)) { keyStore.load(is, keyStorePassword == null ? null : keyStorePassword.toCharArray()); } SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(keyStore, null); return sslBuilder.build(); } catch (IOException | GeneralSecurityException e) { throw new IllegalStateException("Failed to setup SSL context on ES client", e); } } }
6,428
37.497006
120
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/es/EsInstallation.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.application.es; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.stream.Stream; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.application.command.EsJvmOptions; import org.sonar.process.Props; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE_PASSWORD; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_KEYSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_KEYSTORE_PASSWORD; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_TRUSTSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_TRUSTSTORE_PASSWORD; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_PASSWORD; 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_LOGS; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; /** * Holds {@link File} to the various directories of ElasticSearch distribution embedded in SonarQube and provides * {@link File} objects to the various files of it SonarQube cares about. * * <p> * This class does not ensure files nor directories actually exist. * </p> */ public class EsInstallation { private final File homeDirectory; private final List<File> outdatedSearchDirectories; private final File dataDirectory; private final File confDirectory; private final File logDirectory; private EsJvmOptions esJvmOptions; private EsYmlSettings esYmlSettings; private Properties log4j2Properties; private String host; private int httpPort; // ES authentication settings private final boolean securityEnabled; private final String bootstrapPassword; private final Path keyStoreLocation; private final Path trustStoreLocation; @Nullable private final String keyStorePassword; @Nullable private final String trustStorePassword; private final Path httpKeyStoreLocation; @Nullable private final String httpKeyStorePassword; private final boolean httpEncryptionEnabled; public EsInstallation(Props props) { File sqHomeDir = props.nonNullValueAsFile(PATH_HOME.getKey()); this.homeDirectory = new File(sqHomeDir, "elasticsearch"); this.outdatedSearchDirectories = buildOutdatedSearchDirs(props); this.dataDirectory = buildDataDir(props); this.confDirectory = buildConfDir(props); this.logDirectory = buildLogPath(props); this.bootstrapPassword = props.value(CLUSTER_SEARCH_PASSWORD.getKey()); this.securityEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey()) && StringUtils.isNotBlank(bootstrapPassword); this.keyStoreLocation = getPath(props.value(CLUSTER_ES_KEYSTORE.getKey())); this.keyStorePassword = props.value(CLUSTER_ES_KEYSTORE_PASSWORD.getKey()); this.trustStoreLocation = getPath(props.value(CLUSTER_ES_TRUSTSTORE.getKey())); this.trustStorePassword = props.value(CLUSTER_ES_TRUSTSTORE_PASSWORD.getKey()); this.httpKeyStoreLocation = getPath(props.value(CLUSTER_ES_HTTP_KEYSTORE.getKey())); this.httpKeyStorePassword = props.value(CLUSTER_ES_HTTP_KEYSTORE_PASSWORD.getKey()); this.httpEncryptionEnabled = securityEnabled && httpKeyStoreLocation != null; } private static Path getPath(@Nullable String path) { return Optional.ofNullable(path).map(Paths::get).orElse(null); } private static List<File> buildOutdatedSearchDirs(Props props) { String dataPath = props.nonNullValue(PATH_DATA.getKey()); return Stream.of("es", "es5", "es6", "es7") .map(t -> new File(dataPath, t)) .toList(); } private static File buildDataDir(Props props) { String dataPath = props.nonNullValue(PATH_DATA.getKey()); return new File(dataPath, "es8"); } private static File buildLogPath(Props props) { return props.nonNullValueAsFile(PATH_LOGS.getKey()); } private static File buildConfDir(Props props) { File tempPath = props.nonNullValueAsFile(PATH_TEMP.getKey()); return new File(new File(tempPath, "conf"), "es"); } public File getHomeDirectory() { return homeDirectory; } public List<File> getOutdatedSearchDirectories() { return Collections.unmodifiableList(outdatedSearchDirectories); } public File getDataDirectory() { return dataDirectory; } public File getConfDirectory() { return confDirectory; } public File getLogDirectory() { return logDirectory; } public File getExecutable() { return new File(homeDirectory, "bin/elasticsearch"); } public File getLog4j2PropertiesLocation() { return new File(confDirectory, "log4j2.properties"); } public File getElasticsearchYml() { return new File(confDirectory, "elasticsearch.yml"); } public File getJvmOptions() { return new File(confDirectory, "jvm.options"); } public File getLibDirectory() { return new File(homeDirectory, "lib"); } public EsJvmOptions getEsJvmOptions() { return esJvmOptions; } public EsInstallation setEsJvmOptions(EsJvmOptions esJvmOptions) { this.esJvmOptions = esJvmOptions; return this; } public EsYmlSettings getEsYmlSettings() { return esYmlSettings; } public EsInstallation setEsYmlSettings(EsYmlSettings esYmlSettings) { this.esYmlSettings = esYmlSettings; return this; } public Properties getLog4j2Properties() { return log4j2Properties; } public EsInstallation setLog4j2Properties(Properties log4j2Properties) { this.log4j2Properties = log4j2Properties; return this; } public String getHost() { return host; } public EsInstallation setHost(String host) { this.host = host; return this; } public int getHttpPort() { return httpPort; } public EsInstallation setHttpPort(int httpPort) { this.httpPort = httpPort; return this; } public boolean isSecurityEnabled() { return securityEnabled; } public String getBootstrapPassword() { return bootstrapPassword; } public Path getKeyStoreLocation() { return keyStoreLocation; } public Path getTrustStoreLocation() { return trustStoreLocation; } public Optional<String> getKeyStorePassword() { return Optional.ofNullable(keyStorePassword); } public Optional<String> getTrustStorePassword() { return Optional.ofNullable(trustStorePassword); } public Path getHttpKeyStoreLocation() { return httpKeyStoreLocation; } public Optional<String> getHttpKeyStorePassword() { return Optional.ofNullable(httpKeyStorePassword); } public boolean isHttpEncryptionEnabled() { return httpEncryptionEnabled; } }
7,895
30.83871
119
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/es/EsKeyStoreCli.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.application.es; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.sonar.application.command.JavaCommand; import org.sonar.application.command.JvmOptions; import org.sonar.process.ProcessId; import static java.util.Objects.requireNonNull; public class EsKeyStoreCli { public static final String BOOTSTRAP_PASSWORD_PROPERTY_KEY = "bootstrap.password"; public static final String KEYSTORE_PASSWORD_PROPERTY_KEY = "xpack.security.transport.ssl.keystore.secure_password"; public static final String TRUSTSTORE_PASSWORD_PROPERTY_KEY = "xpack.security.transport.ssl.truststore.secure_password"; public static final String HTTP_KEYSTORE_PASSWORD_PROPERTY_KEY = "xpack.security.http.ssl.keystore.secure_password"; private static final String MAIN_CLASS_NAME = "org.elasticsearch.launcher.CliToolLauncher"; private final Map<String, String> properties = new LinkedHashMap<>(); private final JavaCommand<EsKeyStoreJvmOptions> command; private EsKeyStoreCli(EsInstallation esInstallation) { String esHomeAbsolutePath = esInstallation.getHomeDirectory().getAbsolutePath(); command = new JavaCommand<EsKeyStoreJvmOptions>(ProcessId.ELASTICSEARCH, esInstallation.getHomeDirectory()) .setClassName(MAIN_CLASS_NAME) .setJvmOptions(new EsKeyStoreJvmOptions(esInstallation)) .addClasspath(Paths.get(esHomeAbsolutePath, "lib", "").toAbsolutePath() + File.separator + "*") .addClasspath(Paths.get(esHomeAbsolutePath, "lib", "cli-launcher", "").toAbsolutePath() + File.separator + "*") .addParameter("add") .addParameter("-x") .addParameter("-f"); } public static EsKeyStoreCli getInstance(EsInstallation esInstallation) { return new EsKeyStoreCli(esInstallation); } public EsKeyStoreCli store(String key, String value) { requireNonNull(key, "Property key cannot be null"); requireNonNull(value, "Property value cannot be null"); properties.computeIfAbsent(key, s -> { command.addParameter(key); return value; }); return this; } public Process executeWith(Function<JavaCommand<?>, Process> commandLauncher) { Process process = commandLauncher.apply(command); writeValues(process); waitFor(process); checkExitValue(process.exitValue()); return process; } private void writeValues(Process process) { try (OutputStream stdin = process.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin, StandardCharsets.UTF_8))) { for (Entry<String, String> entry : properties.entrySet()) { writer.write(entry.getValue()); writer.write("\n"); } writer.flush(); } catch (IOException e) { throw new IllegalStateException(e); } } private static void waitFor(Process process) { try { process.waitFor(1, TimeUnit.MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("EsKeyStoreCli has been interrupted", e); } } private static void checkExitValue(int code) { if (code != 0) { throw new IllegalStateException("Elasticsearch KeyStore tool exited with code: " + code); } } public static class EsKeyStoreJvmOptions extends JvmOptions<EsKeyStoreJvmOptions> { public EsKeyStoreJvmOptions(EsInstallation esInstallation) { super(mandatoryOptions(esInstallation)); } private static Map<String, String> mandatoryOptions(EsInstallation esInstallation) { Map<String, String> res = new LinkedHashMap<>(7); res.put("-Xms4m", ""); res.put("-Xmx64m", ""); res.put("-XX:+UseSerialGC", ""); res.put("-Dcli.name=", ""); res.put("-Dcli.script=", "bin/elasticsearch-keystore"); res.put("-Dcli.libs=", "lib/tools/keystore-cli"); res.put("-Des.path.home=", esInstallation.getHomeDirectory().getAbsolutePath()); res.put("-Des.path.conf=", esInstallation.getConfDirectory().getAbsolutePath()); return res; } } }
5,185
37.701493
122
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/es/EsLogging.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.application.es; import ch.qos.logback.classic.Level; import java.io.File; import java.util.Properties; import javax.annotation.CheckForNull; import org.sonar.process.ProcessId; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; import org.sonar.process.logging.Log4JPropertiesBuilder; import org.sonar.process.logging.LogLevelConfig; import org.sonar.process.logging.RootLoggerConfig; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.LOG_CONSOLE; import static org.sonar.process.ProcessProperties.Property.LOG_JSON_OUTPUT; import static org.sonar.process.logging.RootLoggerConfig.newRootLoggerConfigBuilder; public class EsLogging { public Properties createProperties(Props props, File logDir) { Log4JPropertiesBuilder log4JPropertiesBuilder = new Log4JPropertiesBuilder(props); RootLoggerConfig config = newRootLoggerConfigBuilder() .setNodeNameField(getNodeNameWhenCluster(props)) .setProcessId(ProcessId.ELASTICSEARCH) .build(); String logPattern = log4JPropertiesBuilder.buildLogPattern(config); return log4JPropertiesBuilder.internalLogLevel(Level.ERROR) .rootLoggerConfig(config) .logPattern(logPattern) .enableAllLogsToConsole(isAllLogsToConsoleEnabled(props)) .jsonOutput(isJsonOutput(props)) .logDir(logDir) .logLevelConfig( LogLevelConfig.newBuilder(log4JPropertiesBuilder.getRootLoggerName()) .rootLevelFor(ProcessId.ELASTICSEARCH) .build()) .build(); } private static boolean isJsonOutput(Props props) { return props.valueAsBoolean(LOG_JSON_OUTPUT.getKey(), Boolean.parseBoolean(LOG_JSON_OUTPUT.getDefaultValue())); } @CheckForNull private static String getNodeNameWhenCluster(Props props) { boolean clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey(), Boolean.parseBoolean(CLUSTER_ENABLED.getDefaultValue())); return clusterEnabled ? props.value(CLUSTER_NODE_NAME.getKey(), CLUSTER_NODE_NAME.getDefaultValue()) : null; } /** * Finds out whether we are in testing environment (usually ITs) and logs of all processes must be forward to * App's System.out. This is specified by the value of property {@link ProcessProperties.Property#LOG_CONSOLE}. */ private static boolean isAllLogsToConsoleEnabled(Props props) { return props.valueAsBoolean(LOG_CONSOLE.getKey(), false); } }
3,418
40.192771
113
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/es/EsSettings.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.application.es; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.MessageException; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; import org.sonar.process.System2; import static java.lang.String.valueOf; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_DISCOVERY_SEED_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HOSTS; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_HTTP_KEYSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_KEYSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ES_TRUSTSTORE; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_ES_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_ES_PORT; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_SEARCH_PORT; import static org.sonar.process.ProcessProperties.Property.CLUSTER_SEARCH_PASSWORD; import static org.sonar.process.ProcessProperties.Property.ES_PORT; import static org.sonar.process.ProcessProperties.Property.SEARCH_HOST; import static org.sonar.process.ProcessProperties.Property.SEARCH_INITIAL_STATE_TIMEOUT; import static org.sonar.process.ProcessProperties.Property.SEARCH_PORT; public class EsSettings { private static final String ES_HTTP_HOST_KEY = "http.host"; private static final String ES_HTTP_PORT_KEY = "http.port"; private static final String ES_TRANSPORT_HOST_KEY = "transport.host"; private static final String ES_TRANSPORT_PORT_KEY = "transport.port"; private static final String ES_NETWORK_HOST_KEY = "network.host"; private static final Logger LOGGER = LoggerFactory.getLogger(EsSettings.class); private static final String STANDALONE_NODE_NAME = "sonarqube"; private static final String SECCOMP_PROPERTY = "bootstrap.system_call_filter"; private static final String ALLOW_MMAP = "node.store.allow_mmap"; private static final String JAVA_ADDITIONAL_OPS_PROPERTY = "sonar.search.javaAdditionalOpts"; private final Props props; private final EsInstallation fileSystem; private final boolean clusterEnabled; private final String clusterName; private final String nodeName; private final InetAddress loopbackAddress; public EsSettings(Props props, EsInstallation fileSystem, System2 system2) { this.props = props; this.fileSystem = fileSystem; this.clusterName = props.nonNullValue(CLUSTER_NAME.getKey()); this.clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey()); if (this.clusterEnabled) { this.nodeName = props.value(CLUSTER_NODE_NAME.getKey(), "sonarqube-" + UUID.randomUUID()); } else { this.nodeName = STANDALONE_NODE_NAME; } this.loopbackAddress = InetAddress.getLoopbackAddress(); String esJvmOptions = system2.getenv("ES_JVM_OPTIONS"); if (esJvmOptions != null && !esJvmOptions.trim().isEmpty()) { LOGGER.warn("ES_JVM_OPTIONS is defined but will be ignored. " + "Use sonar.search.javaOpts and/or sonar.search.javaAdditionalOpts in sonar.properties to specify jvm options for Elasticsearch"); } } public Map<String, String> build() { Map<String, String> builder = new HashMap<>(); configureFileSystem(builder); configureNetwork(builder); configureCluster(builder); configureSecurity(builder); configureOthers(builder); LOGGER.info("Elasticsearch listening on [HTTP: {}:{}, TCP: {}:{}]", builder.get(ES_HTTP_HOST_KEY), builder.get(ES_HTTP_PORT_KEY), builder.get(ES_TRANSPORT_HOST_KEY), builder.get(ES_TRANSPORT_PORT_KEY)); return builder; } private void configureFileSystem(Map<String, String> builder) { builder.put("path.data", fileSystem.getDataDirectory().getAbsolutePath()); builder.put("path.logs", fileSystem.getLogDirectory().getAbsolutePath()); } private void configureSecurity(Map<String, String> builder) { if (clusterEnabled && props.value((CLUSTER_SEARCH_PASSWORD.getKey())) != null) { String clusterESKeystoreFileName = getFileNameFromPathProperty(CLUSTER_ES_KEYSTORE); String clusterESTruststoreFileName = getFileNameFromPathProperty(CLUSTER_ES_TRUSTSTORE); builder.put("xpack.security.enabled", "true"); builder.put("xpack.security.transport.ssl.enabled", "true"); builder.put("xpack.security.transport.ssl.supported_protocols", "TLSv1.3,TLSv1.2"); builder.put("xpack.security.transport.ssl.verification_mode", "certificate"); builder.put("xpack.security.transport.ssl.keystore.path", clusterESKeystoreFileName); builder.put("xpack.security.transport.ssl.truststore.path", clusterESTruststoreFileName); if (props.value(CLUSTER_ES_HTTP_KEYSTORE.getKey()) != null) { String clusterESHttpKeystoreFileName = getFileNameFromPathProperty(CLUSTER_ES_HTTP_KEYSTORE); builder.put("xpack.security.http.ssl.enabled", Boolean.TRUE.toString()); builder.put("xpack.security.http.ssl.keystore.path", clusterESHttpKeystoreFileName); } } else { builder.put("xpack.security.autoconfiguration.enabled", Boolean.FALSE.toString()); builder.put("xpack.security.enabled", Boolean.FALSE.toString()); } } private String getFileNameFromPathProperty(ProcessProperties.Property processProperty) { String processPropertyPath = props.value(processProperty.getKey()); if (processPropertyPath == null) { throw new MessageException(processProperty.name() + " property need to be set " + "when using elastic search authentication"); } Path path = Paths.get(processPropertyPath); if (!path.toFile().exists()) { throw new MessageException("Unable to configure: " + processProperty.getKey() + ". " + "File specified in [" + processPropertyPath + "] does not exist"); } if (!path.toFile().canRead()) { throw new MessageException("Unable to configure: " + processProperty.getKey() + ". " + "Could not get read access to [" + processPropertyPath + "]"); } return path.getFileName().toString(); } private void configureNetwork(Map<String, String> builder) { if (!clusterEnabled) { InetAddress searchHost = resolveAddress(SEARCH_HOST); int searchPort = Integer.parseInt(props.nonNullValue(SEARCH_PORT.getKey())); builder.put(ES_HTTP_HOST_KEY, searchHost.getHostAddress()); builder.put(ES_HTTP_PORT_KEY, valueOf(searchPort)); builder.put("discovery.type", "single-node"); int transportPort = Integer.parseInt(props.nonNullValue(ES_PORT.getKey())); // we have no use of transport port in non-DCE editions // but specified host must be the one listed in: discovery.seed_hosts // otherwise elasticsearch cannot elect master node // by default it will be localhost, see: org.sonar.process.ProcessProperties.completeDefaults builder.put(ES_TRANSPORT_HOST_KEY, searchHost.getHostAddress()); builder.put(ES_TRANSPORT_PORT_KEY, valueOf(transportPort)); } // see https://github.com/lmenezes/elasticsearch-kopf/issues/195 builder.put("http.cors.enabled", valueOf(true)); builder.put("http.cors.allow-origin", "*"); // Elasticsearch sets the default value of TCP reuse address to true only on non-MSWindows machines, but why ? builder.put("network.tcp.reuse_address", valueOf(true)); } private InetAddress resolveAddress(ProcessProperties.Property prop) { return resolveAddress(prop, null); } private InetAddress resolveAddress(ProcessProperties.Property prop, @Nullable InetAddress defaultAddress) { String address; if (defaultAddress == null) { address = props.nonNullValue(prop.getKey()); } else { address = props.value(prop.getKey()); if (address == null) { return defaultAddress; } } try { return InetAddress.getByName(address); } catch (UnknownHostException e) { throw new IllegalStateException("Can not resolve host [" + address + "]. Please check network settings and property " + prop.getKey(), e); } } private void configureCluster(Map<String, String> builder) { // Default value in a standalone mode, not overridable String initialStateTimeOut = "30s"; if (clusterEnabled) { initialStateTimeOut = props.value(SEARCH_INITIAL_STATE_TIMEOUT.getKey(), "120s"); String nodeSearchHost = resolveAddress(CLUSTER_NODE_SEARCH_HOST, loopbackAddress).getHostAddress(); int nodeSearchPort = props.valueAsInt(CLUSTER_NODE_SEARCH_PORT.getKey(), 9001); builder.put(ES_HTTP_HOST_KEY, nodeSearchHost); builder.put(ES_HTTP_PORT_KEY, valueOf(nodeSearchPort)); String nodeTransportHost = resolveAddress(CLUSTER_NODE_ES_HOST, loopbackAddress).getHostAddress(); int nodeTransportPort = props.valueAsInt(CLUSTER_NODE_ES_PORT.getKey(), 9002); builder.put(ES_TRANSPORT_HOST_KEY, nodeTransportHost); builder.put(ES_TRANSPORT_PORT_KEY, valueOf(nodeTransportPort)); builder.put(ES_NETWORK_HOST_KEY, nodeTransportHost); String hosts = props.value(CLUSTER_ES_HOSTS.getKey(), loopbackAddress.getHostAddress()); String discoveryHosts = props.value(CLUSTER_ES_DISCOVERY_SEED_HOSTS.getKey(), hosts); LOGGER.info("Elasticsearch cluster enabled. Connect to hosts [{}]", hosts); builder.put("discovery.seed_hosts", discoveryHosts); builder.put("cluster.initial_master_nodes", hosts); } builder.put("discovery.initial_state_timeout", initialStateTimeOut); builder.put("cluster.name", clusterName); builder.put("cluster.routing.allocation.awareness.attributes", "rack_id"); builder.put("node.attr.rack_id", nodeName); builder.put("node.name", nodeName); } private void configureOthers(Map<String, String> builder) { builder.put("action.auto_create_index", String.valueOf(false)); if (props.value(JAVA_ADDITIONAL_OPS_PROPERTY, "").contains("-D" + SECCOMP_PROPERTY + "=" + Boolean.FALSE)) { builder.put(SECCOMP_PROPERTY, Boolean.FALSE.toString()); } if (props.value(JAVA_ADDITIONAL_OPS_PROPERTY, "").contains("-Dnode.store.allow_mmapfs=" + Boolean.FALSE)) { throw new MessageException("Property 'node.store.allow_mmapfs' is no longer supported. Use 'node.store.allow_mmap' instead."); } if (props.value(JAVA_ADDITIONAL_OPS_PROPERTY, "").contains("-D" + ALLOW_MMAP + "=" + Boolean.FALSE)) { builder.put(ALLOW_MMAP, Boolean.FALSE.toString()); } } }
11,906
45.694118
144
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/es/EsYmlSettings.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.application.es; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Map; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import static org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK; public class EsYmlSettings { private static final String ELASTICSEARCH_YML_OPTIONS_HEADER = """ # This file has been automatically generated by SonarQube during startup. # DO NOT EDIT THIS FILE """; private final Map<String, String> elasticsearchSettings; public EsYmlSettings(Map<String, String> elasticsearchSettings) { this.elasticsearchSettings = elasticsearchSettings; } public void writeToYmlSettingsFile(File file) { DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setPrettyFlow(true); dumperOptions.setDefaultFlowStyle(BLOCK); Yaml yaml = new Yaml(dumperOptions); String output = ELASTICSEARCH_YML_OPTIONS_HEADER + yaml.dump(elasticsearchSettings); try { Files.write(file.toPath(), output.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new IllegalStateException("Cannot write Elasticsearch yml settings file", e); } } }
2,100
34.610169
89
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/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.application.es; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/AbstractManagedProcess.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.application.process; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.ProcessId; abstract class AbstractManagedProcess implements ManagedProcess { private static final Logger LOG = LoggerFactory.getLogger(AbstractManagedProcess.class); private static final int EXPECTED_EXIT_VALUE = 0; private final AtomicBoolean exitValueLogged = new AtomicBoolean(false); protected final Process process; private final ProcessId processId; protected AbstractManagedProcess(Process process, ProcessId processId) { this.process = process; this.processId = processId; } public InputStream getInputStream() { return process.getInputStream(); } public InputStream getErrorStream() { return process.getErrorStream(); } public void closeStreams() { closeQuietly(process.getInputStream()); closeQuietly(process.getOutputStream()); closeQuietly(process.getErrorStream()); } private static void closeQuietly(@Nullable Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (IOException ignored) { // ignore } } public boolean isAlive() { return process.isAlive(); } public void destroyForcibly() { process.destroyForcibly(); } public void waitFor() throws InterruptedException { int exitValue = process.waitFor(); if (exitValueLogged.compareAndSet(false, true)) { if (exitValue != EXPECTED_EXIT_VALUE) { LOG.warn("Process exited with exit value [{}]: {}", processId.getHumanReadableName(), exitValue); } else { LOG.debug("Process exited with exit value [{}]: {}", processId.getHumanReadableName(), exitValue); } } } public void waitFor(long timeout, TimeUnit unit) throws InterruptedException { process.waitFor(timeout, unit); } }
2,915
30.695652
106
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/EsManagedProcess.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.application.process; import java.net.ConnectException; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.application.es.EsConnector; import org.sonar.process.ProcessId; import static org.sonar.application.process.EsManagedProcess.Status.CONNECTION_REFUSED; import static org.sonar.application.process.EsManagedProcess.Status.GREEN; import static org.sonar.application.process.EsManagedProcess.Status.KO; import static org.sonar.application.process.EsManagedProcess.Status.RED; import static org.sonar.application.process.EsManagedProcess.Status.YELLOW; public class EsManagedProcess extends AbstractManagedProcess { private static final Logger LOG = LoggerFactory.getLogger(EsManagedProcess.class); private static final int WAIT_FOR_UP_DELAY_IN_MILLIS = 100; private volatile boolean nodeOperational = false; private final int waitForUpTimeout; private final EsConnector esConnector; public EsManagedProcess(Process process, ProcessId processId, EsConnector esConnector) { this(process, processId, esConnector, 10 * 60); } EsManagedProcess(Process process, ProcessId processId, EsConnector esConnector, int waitForUpTimeout) { super(process, processId); this.esConnector = esConnector; this.waitForUpTimeout = waitForUpTimeout; } @Override public boolean isOperational() { if (nodeOperational) { return true; } boolean flag = false; try { flag = checkOperational(); } catch (InterruptedException e) { LOG.trace("Interrupted while checking ES node is operational", e); Thread.currentThread().interrupt(); } finally { if (flag) { esConnector.stop(); nodeOperational = true; } } return nodeOperational; } private boolean checkOperational() throws InterruptedException { int i = 0; Status status = checkStatus(); do { if (status != Status.CONNECTION_REFUSED) { break; } else { Thread.sleep(WAIT_FOR_UP_DELAY_IN_MILLIS); i++; status = checkStatus(); } } while (i < waitForUpTimeout); return status == YELLOW || status == GREEN; } private Status checkStatus() { try { return esConnector.getClusterHealthStatus() .map(EsManagedProcess::convert) .orElse(CONNECTION_REFUSED); } catch (ElasticsearchException e) { if (e.getRootCause() instanceof ConnectException) { return CONNECTION_REFUSED; } LOG.error("Failed to check status", e); return KO; } catch (Exception e) { LOG.error("Failed to check status", e); return KO; } } private static Status convert(ClusterHealthStatus clusterHealthStatus) { switch (clusterHealthStatus) { case GREEN: return GREEN; case YELLOW: return YELLOW; case RED: return RED; default: return KO; } } enum Status { CONNECTION_REFUSED, KO, RED, YELLOW, GREEN } @Override public void askForStop() { askForHardStop(); } @Override public void askForHardStop() { process.destroy(); } @Override public boolean askedForRestart() { // ES does not support asking for restart return false; } @Override public void acknowledgeAskForRestart() { // nothing to do } }
4,287
28.572414
105
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/ManagedProcess.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.application.process; import java.io.InputStream; import java.util.concurrent.TimeUnit; public interface ManagedProcess { /** * @see Process#getInputStream() */ InputStream getInputStream(); /** * @see Process#getErrorStream() */ InputStream getErrorStream(); /** * Closes the streams {@link Process#getInputStream()}, {@link Process#getOutputStream()} * and {@link Process#getErrorStream()}. * * No exceptions are thrown in case of errors. */ void closeStreams(); /** * @see Process#isAlive() */ boolean isAlive(); /** * @see Process#destroyForcibly() */ void destroyForcibly(); /** * @see Process#waitFor() */ void waitFor() throws InterruptedException; /** * @see Process#waitFor(long, TimeUnit) */ void waitFor(long timeout, TimeUnit timeoutUnit) throws InterruptedException; /** * Whether the process has reach operational state after startup. */ boolean isOperational(); void askForStop(); /** * Send request to quick stop to the process */ void askForHardStop(); /** * Whether the process asked for a full restart */ boolean askedForRestart(); /** * Sends a signal to the process to acknowledge that the parent process received the request to restart from the * child process send via {@link #askedForRestart()}. * <br/> * Child process will typically stop sending the signal requesting restart from now on. */ void acknowledgeAskForRestart(); }
2,357
25.2
114
java
sonarqube
sonarqube-master/server/sonar-main/src/main/java/org/sonar/application/process/ManagedProcessEventListener.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.application.process; import org.sonar.process.ProcessId; @FunctionalInterface public interface ManagedProcessEventListener { enum Type { OPERATIONAL, ASK_FOR_RESTART } /** * This method is called when the process with the specified {@link ProcessId} * sends the event through the ipc shared memory. * Note that there can be a delay since the instant the process sets the flag * (see {@link ManagedProcessHandler#WATCHER_DELAY_MS}). * * Call blocks the process watcher. Implementations should be asynchronous and * fork a new thread if call can be long. */ void onManagedProcessEvent(ProcessId processId, Type type); }
1,524
33.659091
80
java