-
Notifications
You must be signed in to change notification settings - Fork 15
feat(search-index): add command to clean up unused indices #391
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cancan101
wants to merge
7
commits into
pimcore:2026.x
Choose a base branch
from
cancan101:feature/cleaup
base: 2026.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7aeb19f
feat(search-index): add command to clean up unused indices
cancan101 9c0c854
Apply suggestions from code review
kingjia90 40b752e
Update src/Command/CleanupUnusedIndicesCommand.php
cancan101 3a95672
doc: add cleanup command to index management docs
kingjia90 eebc7e7
Address PR #391 review comments on unused-index cleanup
claude 4997c52
Address review findings: min-age guard against concurrent reindex, re…
kingjia90 08998ac
Wrap long lines in cleanup command to satisfy SonarCloud 120-char limit
claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| <?php | ||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * This source file is available under the terms of the | ||
| * Pimcore Open Core License (POCL) | ||
| * Full copyright and license information is available in | ||
| * LICENSE.md which is distributed with this source code. | ||
| * | ||
| * @copyright Copyright (c) Pimcore GmbH (https://www.pimcore.com) | ||
| * @license Pimcore Open Core License (POCL) | ||
| */ | ||
|
|
||
| namespace Pimcore\Bundle\GenericDataIndexBundle\Command; | ||
|
|
||
| use Exception; | ||
| use Pimcore\Bundle\GenericDataIndexBundle\Exception\CommandAlreadyRunningException; | ||
| use Pimcore\Bundle\GenericDataIndexBundle\Service\SearchIndex\UnusedIndexCleanupService; | ||
| use Pimcore\Console\AbstractCommand; | ||
| use Symfony\Component\Console\Command\LockableTrait; | ||
| use Symfony\Component\Console\Input\InputInterface; | ||
| use Symfony\Component\Console\Input\InputOption; | ||
| use Symfony\Component\Console\Output\OutputInterface; | ||
|
|
||
| /** | ||
| * @internal | ||
| */ | ||
| final class CleanupUnusedIndicesCommand extends AbstractCommand | ||
| { | ||
| use LockableTrait; | ||
|
|
||
| private const OPTION_DRY_RUN = 'dry-run'; | ||
|
|
||
| private const OPTION_MIN_AGE = 'min-age'; | ||
|
|
||
| public function __construct( | ||
| private readonly UnusedIndexCleanupService $unusedIndexCleanupService, | ||
| ?string $name = null | ||
| ) { | ||
| parent::__construct($name); | ||
| } | ||
|
kingjia90 marked this conversation as resolved.
|
||
|
|
||
| protected function configure(): void | ||
| { | ||
| $this | ||
| ->setName('generic-data-index:cleanup:unused-indices') | ||
| ->addOption( | ||
| self::OPTION_DRY_RUN, | ||
| null, | ||
| InputOption::VALUE_NONE, | ||
| 'List unused indices without deleting them.' | ||
| ) | ||
| ->addOption( | ||
| self::OPTION_MIN_AGE, | ||
| null, | ||
| InputOption::VALUE_REQUIRED, | ||
| 'Minimum age in seconds an index must have before it is considered unused. ' | ||
| . 'Set to 0 to disable the age guard.', | ||
| (string) UnusedIndexCleanupService::DEFAULT_MIN_AGE_SECONDS | ||
| ) | ||
| ->setDescription( | ||
| 'Deletes managed Generic Data Index indices with the configured index prefix ' | ||
| . 'and a -odd/-even suffix that are not referenced by any alias.' | ||
| ) | ||
| ->setHelp( | ||
| 'This command only targets managed Generic Data Index indices that use the ' | ||
| . 'configured index prefix and end with -odd or -even. It does not consider other indices.' | ||
| . PHP_EOL | ||
| . 'A reindex creates and populates the new -odd/-even index before attaching it to its ' | ||
| . 'alias, so during that window the new index is not referenced by any alias. To avoid ' | ||
| . 'deleting an index that is actively being built, indices younger than --min-age seconds ' | ||
| . '(default: 86400) are never deleted. Only lower this threshold or disable it ' | ||
| . '(--min-age=0) when no reindex is or was recently running.' | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * @throws CommandAlreadyRunningException | ||
| */ | ||
| protected function execute(InputInterface $input, OutputInterface $output): int | ||
| { | ||
| if (!$this->lock()) { | ||
| throw new CommandAlreadyRunningException( | ||
| 'The command is already running in another process.' | ||
| ); | ||
| } | ||
|
|
||
| try { | ||
| $dryRun = (bool) $input->getOption(self::OPTION_DRY_RUN); | ||
|
|
||
| $minAge = $input->getOption(self::OPTION_MIN_AGE); | ||
| if (!is_numeric($minAge) || (int) $minAge < 0) { | ||
| $output->writeln('<error>The --min-age option must be a non-negative number of seconds.</error>'); | ||
|
|
||
| return self::FAILURE; | ||
| } | ||
|
|
||
| $unusedIndices = $this->unusedIndexCleanupService->cleanupUnusedIndices($dryRun, (int) $minAge); | ||
|
|
||
| if (empty($unusedIndices)) { | ||
| $output->writeln('<info>No unused indices found.</info>'); | ||
|
|
||
| return self::SUCCESS; | ||
| } | ||
|
|
||
| $output->writeln('<info>Unused indices:</info>'); | ||
| foreach ($unusedIndices as $indexName) { | ||
| $output->writeln(sprintf(' - %s', $indexName)); | ||
| } | ||
|
|
||
| if ($dryRun) { | ||
| $output->writeln( | ||
| sprintf('<comment>Dry run: %d indices would be deleted.</comment>', count($unusedIndices)) | ||
| ); | ||
| } else { | ||
| $output->writeln( | ||
| sprintf('<info>Deleted %d unused indices.</info>', count($unusedIndices)) | ||
| ); | ||
| } | ||
| } catch (Exception $e) { | ||
| $output->writeln('<error>' . $e->getMessage() . '</error>'); | ||
|
cancan101 marked this conversation as resolved.
|
||
|
|
||
| return self::FAILURE; | ||
| } finally { | ||
| $this->release(); | ||
| } | ||
|
|
||
| return self::SUCCESS; | ||
| } | ||
|
kingjia90 marked this conversation as resolved.
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| <?php | ||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * This source file is available under the terms of the | ||
| * Pimcore Open Core License (POCL) | ||
| * Full copyright and license information is available in | ||
| * LICENSE.md which is distributed with this source code. | ||
| * | ||
| * @copyright Copyright (c) Pimcore GmbH (https://www.pimcore.com) | ||
| * @license Pimcore Open Core License (POCL) | ||
| */ | ||
|
|
||
| namespace Pimcore\Bundle\GenericDataIndexBundle\Service\SearchIndex; | ||
|
|
||
| use Pimcore\Bundle\GenericDataIndexBundle\SearchIndexAdapter\DefaultSearch\DefaultSearchService; | ||
| use Pimcore\Bundle\GenericDataIndexBundle\SearchIndexAdapter\IndexAliasServiceInterface; | ||
| use Pimcore\Bundle\GenericDataIndexBundle\SearchIndexAdapter\SearchIndexServiceInterface; | ||
|
|
||
| /** | ||
| * @internal | ||
| */ | ||
| final readonly class UnusedIndexCleanupService | ||
| { | ||
| public const DEFAULT_MIN_AGE_SECONDS = 86400; | ||
|
|
||
| private const INDEX_SUFFIX_PATTERN = '/-(' | ||
| . DefaultSearchService::INDEX_VERSION_ODD | ||
| . '|' | ||
| . DefaultSearchService::INDEX_VERSION_EVEN | ||
| . ')$/'; | ||
|
|
||
| public function __construct( | ||
| private SearchIndexServiceInterface $searchIndexService, | ||
| private IndexAliasServiceInterface $indexAliasService, | ||
| private SearchIndexConfigServiceInterface $searchIndexConfigService, | ||
| ) { | ||
| } | ||
|
|
||
| /** | ||
| * @return string[] | ||
| */ | ||
| public function findUnusedIndices(int $minAgeSeconds = self::DEFAULT_MIN_AGE_SECONDS): array | ||
| { | ||
| $allManagedIndices = $this->getAllManagedIndices($minAgeSeconds); | ||
| if (empty($allManagedIndices)) { | ||
| return []; | ||
| } | ||
|
|
||
| $aliasedIndices = $this->getAliasedIndices(); | ||
| $unusedIndices = array_values(array_diff($allManagedIndices, $aliasedIndices)); | ||
| sort($unusedIndices); | ||
|
|
||
| return $unusedIndices; | ||
| } | ||
|
|
||
| /** | ||
| * @return string[] | ||
| */ | ||
| public function cleanupUnusedIndices( | ||
| bool $dryRun = false, | ||
| int $minAgeSeconds = self::DEFAULT_MIN_AGE_SECONDS | ||
| ): array { | ||
| $unusedIndices = $this->findUnusedIndices($minAgeSeconds); | ||
|
|
||
| if ($dryRun) { | ||
| return $unusedIndices; | ||
| } | ||
|
|
||
| foreach ($unusedIndices as $indexName) { | ||
| $this->searchIndexService->deleteIndex($indexName); | ||
| } | ||
|
kingjia90 marked this conversation as resolved.
|
||
|
|
||
| return $unusedIndices; | ||
| } | ||
|
|
||
| /** | ||
| * @return string[] | ||
| */ | ||
| private function getAllManagedIndices(int $minAgeSeconds): array | ||
| { | ||
| $indexPrefix = $this->searchIndexConfigService->getIndexPrefix(); | ||
| if ($indexPrefix === '') { | ||
| return []; | ||
| } | ||
|
|
||
| $settingsByIndex = $this->searchIndexService->getIndexSettings($indexPrefix . '*'); | ||
|
|
||
| $indexNames = []; | ||
| foreach ($settingsByIndex as $indexName => $indexSettings) { | ||
| if (!is_string($indexName) | ||
| || !str_starts_with($indexName, $indexPrefix) | ||
| || preg_match(self::INDEX_SUFFIX_PATTERN, $indexName) !== 1 | ||
| || !$this->isOldEnough($indexSettings, $minAgeSeconds) | ||
| ) { | ||
| continue; | ||
| } | ||
|
|
||
| $indexNames[] = $indexName; | ||
| } | ||
|
|
||
| return $indexNames; | ||
| } | ||
|
|
||
| /** | ||
| * A reindex creates and populates the new -odd/-even index before attaching it to its | ||
| * alias, so a recently created index without an alias may still be in that window. | ||
| * Indices with an unknown creation date never qualify for deletion unless the guard | ||
| * is disabled ($minAgeSeconds <= 0). | ||
| */ | ||
| private function isOldEnough(mixed $indexSettings, int $minAgeSeconds): bool | ||
| { | ||
| if ($minAgeSeconds <= 0) { | ||
| return true; | ||
| } | ||
|
|
||
| $creationDate = $indexSettings['settings']['index']['creation_date'] ?? null; | ||
| if (!is_numeric($creationDate)) { | ||
| return false; | ||
| } | ||
|
|
||
| $creationTimestamp = (int) ((float) $creationDate / 1000); | ||
|
|
||
| return time() - $creationTimestamp >= $minAgeSeconds; | ||
| } | ||
|
|
||
| /** | ||
| * @return string[] | ||
| */ | ||
| private function getAliasedIndices(): array | ||
| { | ||
| $indexPrefix = $this->searchIndexConfigService->getIndexPrefix(); | ||
| $aliases = $this->indexAliasService->getAllAliases(); | ||
|
|
||
| $aliasedIndexMap = []; | ||
| foreach ($aliases as $aliasData) { | ||
| if (!is_array($aliasData)) { | ||
| continue; | ||
| } | ||
|
|
||
| $indexName = $aliasData['index'] ?? null; | ||
| if (!is_string($indexName) || !str_starts_with($indexName, $indexPrefix)) { | ||
| continue; | ||
| } | ||
|
|
||
| $aliasedIndexMap[$indexName] = true; | ||
| } | ||
|
|
||
| return array_keys($aliasedIndexMap); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.