From e87de2811801b19cb76675e53174f5a90fdd205f Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 28 Jun 2022 16:30:05 +0200 Subject: [PATCH 01/27] add skeleton --- config/routes/Centreon/platform.yaml | 6 + .../WriteVersionRepositoryInterface.php | 27 +++++ .../UseCase/UpdateVersions/UpdateVersions.php | 108 ++++++++++++++++++ .../UpdateVersionsPresenterInterface.php | 29 +++++ .../UpdateVersions/UpdateVersionsRequest.php | 32 ++++++ .../UpdateVersionsController.php | 74 ++++++++++++ .../UpdateVersionsPresenter.php | 31 +++++ .../UpdateVersions/UpdateVersionsSchema.json | 15 +++ 8 files changed, 322 insertions(+) create mode 100644 src/Core/Platform/Application/Repository/WriteVersionRepositoryInterface.php create mode 100644 src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php create mode 100644 src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsPresenterInterface.php create mode 100644 src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsRequest.php create mode 100644 src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php create mode 100644 src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsPresenter.php create mode 100644 src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsSchema.json diff --git a/config/routes/Centreon/platform.yaml b/config/routes/Centreon/platform.yaml index a521348ecbf..8348ae14d73 100644 --- a/config/routes/Centreon/platform.yaml +++ b/config/routes/Centreon/platform.yaml @@ -4,6 +4,12 @@ centreon_application_platform_getversion: controller: 'Centreon\Application\Controller\PlatformController::getVersions' condition: "request.attributes.get('version') >= 21.10" +centreon_application_platform_updateversions: + methods: PATCH + path: /platform/versions + controller: 'Core\Platform\Infrastructure\Api\UpdateVersions\UpdateVersions' + condition: "request.attributes.get('version') >= 22.04" + centreon_application_platformtopology_addplatformtotopology: methods: POST path: /platform/topology diff --git a/src/Core/Platform/Application/Repository/WriteVersionRepositoryInterface.php b/src/Core/Platform/Application/Repository/WriteVersionRepositoryInterface.php new file mode 100644 index 00000000000..47b09fab203 --- /dev/null +++ b/src/Core/Platform/Application/Repository/WriteVersionRepositoryInterface.php @@ -0,0 +1,27 @@ +info('Updating versions'); + + try { + $updates = $this->getAvailableUpdates(); + + $this->runUpdates($updates); + } catch (\Throwable $e) { + $presenter->setResponseStatus(new ErrorResponse($e->getMessage())); + return; + } + + $presenter->setResponseStatus(new NoContentResponse()); + } + + /** + * Get available updates + * + * @return string[] + */ + private function getAvailableUpdates(): array + { + try { + $this->info('Getting available updates'); + + return $this->repository->getAvailableUpdates(); + } catch (\Throwable $e) { + $this->error( + 'An error occurred when getting available updates', + ['trace' => $e->getTraceAsString()], + ); + + throw $e; + } + } + + /** + * Run given updates + * + * @param string[] $updates + */ + private function runUpdates(array $updates): void + { + try { + foreach ($updates as $update) { + $this->repository->runUpdate($update); + } + } catch (\Throwable $e) { + $this->error( + 'An error occurred when applying update', + [ + 'update' => $update, + 'trace' => $e->getTraceAsString(), + ], + ); + + throw $e; + } + } +} diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsPresenterInterface.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsPresenterInterface.php new file mode 100644 index 00000000000..efc7cc4a107 --- /dev/null +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsPresenterInterface.php @@ -0,0 +1,29 @@ +denyAccessUnlessGrantedForApiConfiguration(); + + $this->info('Validating request body...'); + $this->validateDataSent($request, __DIR__ . '/UpdateVersionsSchema.json'); + + $updateVersionsRequest = $this->createUpdateVersionsRequest($request); + $useCase($presenter, $updateVersionsRequest); + + return $presenter->show(); + } + + /** + * @param Request $request + * @return UpdateVersionsRequest + */ + private function createUpdateVersionsRequest(Request $request): UpdateVersionsRequest + { + $requestData = json_decode((string) $request->getContent(), true); + + $updateVersionsRequest = new UpdateVersionsRequest(); + $updateVersionsRequest->centreonWebVersion = $requestData['centreon-web']; + + return $updateVersionsRequest; + } +} diff --git a/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsPresenter.php b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsPresenter.php new file mode 100644 index 00000000000..a27dcfad745 --- /dev/null +++ b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsPresenter.php @@ -0,0 +1,31 @@ + Date: Tue, 28 Jun 2022 17:15:01 +0200 Subject: [PATCH 02/27] split interfaces --- .../ReadVersionRepositoryInterface.php | 33 +++++++++++++++++++ .../WriteVersionRepositoryInterface.php | 8 ++++- .../UseCase/UpdateVersions/UpdateVersions.php | 5 ++- 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php diff --git a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php new file mode 100644 index 00000000000..d0397ecbe2a --- /dev/null +++ b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php @@ -0,0 +1,33 @@ + Date: Wed, 29 Jun 2022 08:50:34 +0200 Subject: [PATCH 03/27] implement use case --- config/routes/Centreon/platform.yaml | 2 +- .../UseCase/UpdateVersions/UpdateVersions.php | 60 ++++++++++++++----- .../Repository/DbReadVersionRepository.php | 40 +++++++++++++ .../Repository/DbWriteVersionRepository.php | 39 ++++++++++++ 4 files changed, 125 insertions(+), 16 deletions(-) create mode 100644 src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php create mode 100644 src/Core/Platform/Infrastructure/Repository/DbWriteVersionRepository.php diff --git a/config/routes/Centreon/platform.yaml b/config/routes/Centreon/platform.yaml index 8348ae14d73..80a0930f3f8 100644 --- a/config/routes/Centreon/platform.yaml +++ b/config/routes/Centreon/platform.yaml @@ -7,7 +7,7 @@ centreon_application_platform_getversion: centreon_application_platform_updateversions: methods: PATCH path: /platform/versions - controller: 'Core\Platform\Infrastructure\Api\UpdateVersions\UpdateVersions' + controller: 'Core\Platform\Infrastructure\Api\UpdateVersions\UpdateVersionsController' condition: "request.attributes.get('version') >= 22.04" centreon_application_platformtopology_addplatformtotopology: diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index 3cf2e83ccb3..2410795b558 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -53,9 +53,11 @@ public function __invoke( $this->info('Updating versions'); try { - $updates = $this->getAvailableUpdates(); + $availableUpdates = $this->getAvailableUpdates(); - $this->runUpdates($updates); + $desiredUpdates = $this->filterUpdatesUntil($request->centreonWebVersion, $availableUpdates); + + $this->runUpdates($desiredUpdates); } catch (\Throwable $e) { $presenter->setResponseStatus(new ErrorResponse($e->getMessage())); return; @@ -74,7 +76,7 @@ private function getAvailableUpdates(): array try { $this->info('Getting available updates'); - return $this->repository->getAvailableUpdates(); + return $this->readVersionRepository->getAvailableUpdates(); } catch (\Throwable $e) { $this->error( 'An error occurred when getting available updates', @@ -92,20 +94,48 @@ private function getAvailableUpdates(): array */ private function runUpdates(array $updates): void { - try { - foreach ($updates as $update) { - $this->repository->runUpdate($update); + foreach ($updates as $update) { + try { + $this->writeVersionRepository->runUpdate($update); + } catch (\Throwable $e) { + $this->error( + 'An error occurred when applying update', + [ + 'update' => $update, + 'trace' => $e->getTraceAsString(), + ], + ); + + throw $e; } - } catch (\Throwable $e) { - $this->error( - 'An error occurred when applying update', - [ - 'update' => $update, - 'trace' => $e->getTraceAsString(), - ], - ); + } + } - throw $e; + /** + * filter updates which are anterior to given version + * + * @param string $version + * @param string[] $updates + * @return array + * + * @throws \Exception + */ + private function filterUpdatesUntil(string $version, array $updates): array + { + $filteredUpdates = []; + foreach ($updates as $update) { + $filteredUpdates[] = $update; + if ($update === $version) { + return $filteredUpdates; + } } + + $errorMessage = "Update to $version is not available"; + $this->error( + $errorMessage, + ['available_versions' => implode(', ', $updates)], + ); + + throw new \Exception($errorMessage); } } diff --git a/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php new file mode 100644 index 00000000000..0abd177a07b --- /dev/null +++ b/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php @@ -0,0 +1,40 @@ + Date: Wed, 29 Jun 2022 09:05:12 +0200 Subject: [PATCH 04/27] move into repository --- .../ReadVersionRepositoryInterface.php | 11 +++++++ .../UseCase/UpdateVersions/UpdateVersions.php | 33 +++---------------- .../Repository/DbReadVersionRepository.php | 30 +++++++++++++++++ 3 files changed, 45 insertions(+), 29 deletions(-) diff --git a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php index d0397ecbe2a..1fb1fc32ad7 100644 --- a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php +++ b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php @@ -30,4 +30,15 @@ interface ReadVersionRepositoryInterface * @return string[] */ public function getAvailableUpdates(): array; + + /** + * filter updates which are anterior to given version + * + * @param string $version + * @param string[] $updates + * @return array + * + * @throws \Exception + */ + public function filterUpdatesUntil(string $version, array $updates): array; } diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index 2410795b558..8e658f6e12d 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -55,7 +55,10 @@ public function __invoke( try { $availableUpdates = $this->getAvailableUpdates(); - $desiredUpdates = $this->filterUpdatesUntil($request->centreonWebVersion, $availableUpdates); + $desiredUpdates = $this->readVersionRepository->filterUpdatesUntil( + $request->centreonWebVersion, + $availableUpdates + ); $this->runUpdates($desiredUpdates); } catch (\Throwable $e) { @@ -110,32 +113,4 @@ private function runUpdates(array $updates): void } } } - - /** - * filter updates which are anterior to given version - * - * @param string $version - * @param string[] $updates - * @return array - * - * @throws \Exception - */ - private function filterUpdatesUntil(string $version, array $updates): array - { - $filteredUpdates = []; - foreach ($updates as $update) { - $filteredUpdates[] = $update; - if ($update === $version) { - return $filteredUpdates; - } - } - - $errorMessage = "Update to $version is not available"; - $this->error( - $errorMessage, - ['available_versions' => implode(', ', $updates)], - ); - - throw new \Exception($errorMessage); - } } diff --git a/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php index 0abd177a07b..b79965b2f5b 100644 --- a/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php @@ -30,6 +30,8 @@ class DbReadVersionRepository extends AbstractRepositoryDRB implements ReadVersionRepositoryInterface { + use LoggerTrait; + /** * @inheritDoc */ @@ -37,4 +39,32 @@ public function getAvailableUpdates(): array { return []; } + + /** + * filter updates which are anterior to given version + * + * @param string $version + * @param string[] $updates + * @return array + * + * @throws \Exception + */ + public function filterUpdatesUntil(string $version, array $updates): array + { + $filteredUpdates = []; + foreach ($updates as $update) { + $filteredUpdates[] = $update; + if ($update === $version) { + return $filteredUpdates; + } + } + + $errorMessage = "Update to $version is not available"; + $this->error( + $errorMessage, + ['available_versions' => implode(', ', $updates)], + ); + + throw new \Exception($errorMessage); + } } From 2fe87c6961c0b2e5d7a790312eb3edba256cf38f Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Wed, 29 Jun 2022 15:42:30 +0200 Subject: [PATCH 05/27] read updates --- config/routes/Centreon/platform.yaml | 4 +- .../ReadVersionRepositoryInterface.php | 12 +- .../UseCase/UpdateVersions/UpdateVersions.php | 32 ++++- .../Repository/DbReadVersionRepository.php | 70 --------- .../LegacyReadVersionRepository.php | 133 ++++++++++++++++++ ...y.php => LegacyWriteVersionRepository.php} | 2 +- 6 files changed, 175 insertions(+), 78 deletions(-) delete mode 100644 src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php create mode 100644 src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php rename src/Core/Platform/Infrastructure/Repository/{DbWriteVersionRepository.php => LegacyWriteVersionRepository.php} (90%) diff --git a/config/routes/Centreon/platform.yaml b/config/routes/Centreon/platform.yaml index 80a0930f3f8..bc1c86678a5 100644 --- a/config/routes/Centreon/platform.yaml +++ b/config/routes/Centreon/platform.yaml @@ -5,8 +5,8 @@ centreon_application_platform_getversion: condition: "request.attributes.get('version') >= 21.10" centreon_application_platform_updateversions: - methods: PATCH - path: /platform/versions + methods: PUT + path: /platform/updates/centreon-web controller: 'Core\Platform\Infrastructure\Api\UpdateVersions\UpdateVersionsController' condition: "request.attributes.get('version') >= 22.04" diff --git a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php index 1fb1fc32ad7..89fc4f62734 100644 --- a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php +++ b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php @@ -25,11 +25,19 @@ interface ReadVersionRepositoryInterface { /** - * Get available updates + * Get current version * + * @return string|null + */ + public function getCurrentVersion(): ?string; + + /** + * Get ordered available updates + * + * @param string $currentVersion * @return string[] */ - public function getAvailableUpdates(): array; + public function getOrderedAvailableUpdates(string $currentVersion): array; /** * filter updates which are anterior to given version diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index 8e658f6e12d..071d357e496 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -53,7 +53,9 @@ public function __invoke( $this->info('Updating versions'); try { - $availableUpdates = $this->getAvailableUpdates(); + $currentVersion = $this->getCurrentVersion(); + + $availableUpdates = $this->getAvailableUpdates($currentVersion); $desiredUpdates = $this->readVersionRepository->filterUpdatesUntil( $request->centreonWebVersion, @@ -63,23 +65,46 @@ public function __invoke( $this->runUpdates($desiredUpdates); } catch (\Throwable $e) { $presenter->setResponseStatus(new ErrorResponse($e->getMessage())); + return; } $presenter->setResponseStatus(new NoContentResponse()); } + /** + * Get current version or fail + * + * @return string + * @throws \Exception + */ + private function getCurrentVersion(): string + { + $this->info('Getting current version'); + $currentVersion = $this->readVersionRepository->getCurrentVersion(); + + if ($currentVersion === null) { + $errorMessage = 'Cannot retrieve current version'; + $this->error($errorMessage); + + throw new \Exception($errorMessage); + } + + return $currentVersion; + } + /** * Get available updates * + * @param string $currentVersion * @return string[] */ - private function getAvailableUpdates(): array + private function getAvailableUpdates(string $currentVersion): array { try { $this->info('Getting available updates'); - return $this->readVersionRepository->getAvailableUpdates(); + return $this->readVersionRepository->getOrderedAvailableUpdates($currentVersion); } catch (\Throwable $e) { $this->error( 'An error occurred when getting available updates', @@ -99,6 +124,7 @@ private function runUpdates(array $updates): void { foreach ($updates as $update) { try { + $this->info("Running update $update"); $this->writeVersionRepository->runUpdate($update); } catch (\Throwable $e) { $this->error( diff --git a/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php deleted file mode 100644 index b79965b2f5b..00000000000 --- a/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php +++ /dev/null @@ -1,70 +0,0 @@ -error( - $errorMessage, - ['available_versions' => implode(', ', $updates)], - ); - - throw new \Exception($errorMessage); - } -} diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php new file mode 100644 index 00000000000..b6babda9822 --- /dev/null +++ b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php @@ -0,0 +1,133 @@ +db = $db; + } + + /** + * @inheritDoc + */ + public function getCurrentVersion(): ?string + { + $currentVersion = null; + + $statement = $this->db->query( + "SELECT `value` FROM `informations` WHERE `key` = 'version'" + ); + if ($statement !== false && is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) { + $currentVersion = $result['value']; + } + + return $currentVersion; + } + + /** + * @inheritDoc + */ + public function getOrderedAvailableUpdates(string $currentVersion): array + { + $availableUpdates = $this->getAvailableUpdates($currentVersion); + + return $this->orderUpdates($availableUpdates); + } + + /** + * filter updates which are anterior to given version + * + * @param string $version + * @param string[] $updates + * @return array + * + * @throws \Exception + */ + public function filterUpdatesUntil(string $version, array $updates): array + { + $filteredUpdates = []; + foreach ($updates as $update) { + $filteredUpdates[] = $update; + if ($update === $version) { + return $filteredUpdates; + } + } + + $errorMessage = "Update to $version is not available"; + $this->error( + $errorMessage, + ['available_versions' => implode(', ', $updates)], + ); + + throw new \Exception($errorMessage); + } + + /** + * Get available updates + * + * @param string $currentVersion + * @return string[] + */ + private function getAvailableUpdates(string $currentVersion): array + { + $availableUpdates = []; + if ($handle = opendir(__DIR__ . '/../../../../../www/install/php')) { + while (false !== ($file = readdir($handle))) { + if (preg_match('/Update-(?[a-zA-Z0-9\-\.]+)\.php/', $file, $matches)) { + if (version_compare($matches['version'], $currentVersion, '>')) { + $availableUpdates[] = $matches['version']; + } + } + } + closedir($handle); + } + + return $availableUpdates; + } + + /** + * Order updates + * + * @param string[] $updates + * @return string[] + */ + private function orderUpdates(array $updates): array + { + usort($updates, 'version_compare'); + + return $updates; + } +} diff --git a/src/Core/Platform/Infrastructure/Repository/DbWriteVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php similarity index 90% rename from src/Core/Platform/Infrastructure/Repository/DbWriteVersionRepository.php rename to src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php index a8bf3895fa4..c4f2eb3e459 100644 --- a/src/Core/Platform/Infrastructure/Repository/DbWriteVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php @@ -28,7 +28,7 @@ use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Platform\Application\Repository\WriteVersionRepositoryInterface; -class DbWriteVersionRepository extends AbstractRepositoryDRB implements WriteVersionRepositoryInterface +class LegacyWriteVersionRepository extends AbstractRepositoryDRB implements WriteVersionRepositoryInterface { /** * @inheritDoc From 38c013aa1b2b8aed2c6139875a47a20ebe4eb5ef Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Wed, 29 Jun 2022 16:33:36 +0200 Subject: [PATCH 06/27] apply php upgrades --- .../LegacyWriteVersionRepository.php | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php index c4f2eb3e459..4b0a44267e4 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php @@ -30,10 +30,91 @@ class LegacyWriteVersionRepository extends AbstractRepositoryDRB implements WriteVersionRepositoryInterface { + use LoggerTrait; + + /** + * @param DatabaseConnection $db + */ + public function __construct(DatabaseConnection $db) + { + $this->db = $db; + } + /** * @inheritDoc */ public function runUpdate(string $update): void { + $this->runMonitoringSql($update); + $this->runScript($update); + $this->runConfigurationSql($update); + $this->runPostScript($update); + $this->updateVersionInformation($update); + } + + /** + * Run sql queries on monitoring database + * + * @param string $version + */ + private function runMonitoringSql(string $version): void + { + $upgradeFilePath = __DIR__ . '/../../../../../www/install/sql/centstorage/Update-CSTG-' . $version . '.sql'; + if (is_file($upgradeFilePath)) { + } + } + + /** + * Run php upgrade script + * + * @param string $version + */ + private function runScript(string $version): void + { + $upgradeFilePath = __DIR__ . '/../../../../../www/install/php/Update-' . $version . '.php'; + if (is_file($upgradeFilePath)) { + include_once $upgradeFilePath; + } + } + + /** + * Run sql queries on configuration database + * + * @param string $version + */ + private function runConfigurationSql(string $version): void + { + $upgradeFilePath = __DIR__ . '/../../../../../www/install/sql/centreon/Update-DB-' . $version . '.sql'; + if (is_file($upgradeFilePath)) { + } + } + + /** + * Run php post upgrade script + * + * @param string $version + */ + private function runPostScript(string $version): void + { + $upgradeFilePath = __DIR__ . '/../../../../../www/install/php/Update-' . $version . '.post.php'; + if (is_file($upgradeFilePath)) { + include_once $upgradeFilePath; + } + } + + /** + * Update version information + * + * @param string $version + */ + private function updateVersionInformation(string $version): void + { + $statement = $this->db->prepare( + $this->translateDbName( + "UPDATE `:db`.`informations` SET `value` = :version WHERE `key` = 'version'" + ) + ); + $statement->bindValue(':version', $version, \PDO::PARAM_STR); + //$statement->execute(); } } From 97501238af3c36aa0d97011740b1b0c5b45d9db4 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Wed, 29 Jun 2022 17:04:38 +0200 Subject: [PATCH 07/27] manage sql upgrades --- .../Infrastructure/DatabaseConnection.php | 10 ++++ .../Repository/AbstractRepositoryDRB.php | 4 +- .../LegacyWriteVersionRepository.php | 51 +++++++++++++++++++ 3 files changed, 63 insertions(+), 2 deletions(-) diff --git a/src/Centreon/Infrastructure/DatabaseConnection.php b/src/Centreon/Infrastructure/DatabaseConnection.php index 404ada96717..39263cc0cff 100644 --- a/src/Centreon/Infrastructure/DatabaseConnection.php +++ b/src/Centreon/Infrastructure/DatabaseConnection.php @@ -91,4 +91,14 @@ public function setStorageDbName(string $storageDbName) { $this->storageDbName = $storageDbName; } + + /** + * switch connection to another database + * + * @param string $dbName + */ + public function switchToDb(string $dbName): void + { + $this->query('use ' . $dbName); + } } diff --git a/src/Centreon/Infrastructure/Repository/AbstractRepositoryDRB.php b/src/Centreon/Infrastructure/Repository/AbstractRepositoryDRB.php index c8ccf79ea23..27e68c256fd 100644 --- a/src/Centreon/Infrastructure/Repository/AbstractRepositoryDRB.php +++ b/src/Centreon/Infrastructure/Repository/AbstractRepositoryDRB.php @@ -48,8 +48,8 @@ class AbstractRepositoryDRB protected function translateDbName(string $request): string { return str_replace( - array(':dbstg', ':db'), - array($this->db->getStorageDbName(), $this->db->getCentreonDbName()), + [':dbstg', ':db'], + [$this->db->getStorageDbName(), $this->db->getCentreonDbName()], $request ); } diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php index 4b0a44267e4..d9b2fd8fcd0 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php @@ -61,6 +61,8 @@ private function runMonitoringSql(string $version): void { $upgradeFilePath = __DIR__ . '/../../../../../www/install/sql/centstorage/Update-CSTG-' . $version . '.sql'; if (is_file($upgradeFilePath)) { + $this->db->switchToDb($this->db->getStorageDbName()); + $this->runSqlFile($upgradeFilePath); } } @@ -86,6 +88,8 @@ private function runConfigurationSql(string $version): void { $upgradeFilePath = __DIR__ . '/../../../../../www/install/sql/centreon/Update-DB-' . $version . '.sql'; if (is_file($upgradeFilePath)) { + $this->db->switchToDb($this->db->getCentreonDbName()); + $this->runSqlFile($upgradeFilePath); } } @@ -117,4 +121,51 @@ private function updateVersionInformation(string $version): void $statement->bindValue(':version', $version, \PDO::PARAM_STR); //$statement->execute(); } + + private function runSqlFile(string $filePath): void + { + set_time_limit(0); + $count = 0; + $start = 0; + $fileName = basename($filePath); + $tmpFile = __DIR__ . '/../../../../../www/install/tmp/' . $fileName; + if (is_file($tmpFile)) { + $start = file_get_contents($tmpFile); + } + if (is_file($filePath)) { + $file = fopen($filePath, 'r'); + if (is_resource($file)) { + $query = []; + $line = 0; + while (! feof($file)) { + $line++; + $currentLine = fgets($file); + if (substr(trim($currentLine), 0, 2) !== '--') { + $query[] = $currentLine; + } + if (preg_match('~' . preg_quote(';', '~') . '\s*$~iS', end($query))) { + $query = trim(implode('', $query)); + $count++; + if ($count > $start) { + try { + $this->db->query($query); + } catch (\Exception $e) { + $this->error('Cannot execute query : ' . $query); + throw $e; + } + while (ob_get_level() > 0) { + ob_end_flush(); + } + flush(); + dump(file_put_contents($tmpFile, $count)); + } + } + if (is_string($query)) { + $query = []; + } + } + fclose($file); + } + } + } } From a21a5430d33c0174528ee46d022ac9127eed096e Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Thu, 30 Jun 2022 08:21:33 +0200 Subject: [PATCH 08/27] check user is admin --- .../Api/UpdateVersions/UpdateVersionsController.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php index 120f633a11a..b3570d7156d 100644 --- a/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php +++ b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php @@ -26,11 +26,13 @@ use Symfony\Component\HttpFoundation\Request; use Centreon\Application\Controller\AbstractController; use Centreon\Domain\Log\LoggerTrait; +use Centreon\Domain\Contact\Contact; use Core\Platform\Application\UseCase\UpdateVersions\{ UpdateVersions, UpdateVersionsRequest, UpdateVersionsPresenterInterface }; +use Core\Application\Common\UseCase\UnauthorizedResponse; class UpdateVersionsController extends AbstractController { @@ -49,6 +51,16 @@ public function __invoke( ): object { $this->denyAccessUnlessGrantedForApiConfiguration(); + /** + * @var Contact $contact + */ + $contact = $this->getUser(); + if (! $contact->isAdmin()) { + $presenter->setResponseStatus(new UnauthorizedResponse('Only admin user can perform upgrade')); + + return $presenter->show(); + } + $this->info('Validating request body...'); $this->validateDataSent($request, __DIR__ . '/UpdateVersionsSchema.json'); From c63153d3a515c52742848e2234fcd0b4f08a178e Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Thu, 30 Jun 2022 08:43:34 +0200 Subject: [PATCH 09/27] phpdoc --- .../Repository/ReadVersionRepositoryInterface.php | 4 ++-- .../UseCase/UpdateVersions/UpdateVersions.php | 2 +- .../Repository/LegacyReadVersionRepository.php | 10 ++-------- .../Repository/LegacyWriteVersionRepository.php | 8 +++++++- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php index 89fc4f62734..1528fb7328c 100644 --- a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php +++ b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php @@ -40,7 +40,7 @@ public function getCurrentVersion(): ?string; public function getOrderedAvailableUpdates(string $currentVersion): array; /** - * filter updates which are anterior to given version + * Get updates which are anterior to given version * * @param string $version * @param string[] $updates @@ -48,5 +48,5 @@ public function getOrderedAvailableUpdates(string $currentVersion): array; * * @throws \Exception */ - public function filterUpdatesUntil(string $version, array $updates): array; + public function getUpdatesUntil(string $version, array $updates): array; } diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index 071d357e496..9e425f039de 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -57,7 +57,7 @@ public function __invoke( $availableUpdates = $this->getAvailableUpdates($currentVersion); - $desiredUpdates = $this->readVersionRepository->filterUpdatesUntil( + $desiredUpdates = $this->readVersionRepository->getUpdatesUntil( $request->centreonWebVersion, $availableUpdates ); diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php index b6babda9822..9dad1f4aef6 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php @@ -68,15 +68,9 @@ public function getOrderedAvailableUpdates(string $currentVersion): array } /** - * filter updates which are anterior to given version - * - * @param string $version - * @param string[] $updates - * @return array - * - * @throws \Exception + * @inheritDoc */ - public function filterUpdatesUntil(string $version, array $updates): array + public function getUpdatesUntil(string $version, array $updates): array { $filteredUpdates = []; foreach ($updates as $update) { diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php index d9b2fd8fcd0..d9403ffc59b 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php @@ -119,9 +119,15 @@ private function updateVersionInformation(string $version): void ) ); $statement->bindValue(':version', $version, \PDO::PARAM_STR); - //$statement->execute(); + $statement->execute(); } + /** + * Run sql file and use temporary file to store last executed line + * + * @param string $filePath + * @return void + */ private function runSqlFile(string $filePath): void { set_time_limit(0); From bfd16a7e275d8eca1093d5d001571f14d632118e Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Fri, 1 Jul 2022 09:31:02 +0200 Subject: [PATCH 10/27] refacto --- .../Repository/LegacyWriteVersionRepository.php | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php index d9403ffc59b..39516540a43 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php @@ -141,16 +141,15 @@ private function runSqlFile(string $filePath): void if (is_file($filePath)) { $file = fopen($filePath, 'r'); if (is_resource($file)) { - $query = []; + $query = ''; $line = 0; while (! feof($file)) { $line++; $currentLine = fgets($file); - if (substr(trim($currentLine), 0, 2) !== '--') { - $query[] = $currentLine; + if ($currentLine && ! str_starts_with('--', trim($currentLine))) { + $query .= ' ' . trim($currentLine); } - if (preg_match('~' . preg_quote(';', '~') . '\s*$~iS', end($query))) { - $query = trim(implode('', $query)); + if (! empty($query) && preg_match('/;\s*$/', $query)) { $count++; if ($count > $start) { try { @@ -163,12 +162,10 @@ private function runSqlFile(string $filePath): void ob_end_flush(); } flush(); - dump(file_put_contents($tmpFile, $count)); + $query = ''; + file_put_contents($tmpFile, $count); } } - if (is_string($query)) { - $query = []; - } } fclose($file); } From 7255ca93f2b95c0f57a769cc7f4ad260e2f5c654 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Fri, 1 Jul 2022 09:56:26 +0200 Subject: [PATCH 11/27] use symfony finder --- config/services.yaml | 3 +++ .../ReadVersionRepositoryInterface.php | 2 +- .../LegacyReadVersionRepository.php | 26 ++++++++++++------- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/config/services.yaml b/config/services.yaml index 41975cd9de1..d1ca3a46121 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -66,6 +66,9 @@ services: decorates: router arguments: ['@.inner'] + Symfony\Component\Finder\Finder: + shared: false + # Security Security\Domain\Authentication\Interfaces\AuthenticationRepositoryInterface: diff --git a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php index 1528fb7328c..c4814a38de1 100644 --- a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php +++ b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php @@ -44,7 +44,7 @@ public function getOrderedAvailableUpdates(string $currentVersion): array; * * @param string $version * @param string[] $updates - * @return array + * @return string[] * * @throws \Exception */ diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php index 9dad1f4aef6..aea3b08fa9c 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php @@ -27,16 +27,20 @@ use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Platform\Application\Repository\ReadVersionRepositoryInterface; +use Symfony\Component\Finder\Finder; class LegacyReadVersionRepository extends AbstractRepositoryDRB implements ReadVersionRepositoryInterface { use LoggerTrait; /** + * @param Finder $finder * @param DatabaseConnection $db */ - public function __construct(DatabaseConnection $db) - { + public function __construct( + private Finder $finder, + DatabaseConnection $db, + ) { $this->db = $db; } @@ -97,18 +101,22 @@ public function getUpdatesUntil(string $version, array $updates): array */ private function getAvailableUpdates(string $currentVersion): array { + $fileNameVersionRegex = '/Update-(?[a-zA-Z0-9\-\.]+)\.php/'; $availableUpdates = []; - if ($handle = opendir(__DIR__ . '/../../../../../www/install/php')) { - while (false !== ($file = readdir($handle))) { - if (preg_match('/Update-(?[a-zA-Z0-9\-\.]+)\.php/', $file, $matches)) { - if (version_compare($matches['version'], $currentVersion, '>')) { - $availableUpdates[] = $matches['version']; - } + $updateFiles = $this->finder->files() + ->in(__DIR__ . '/../../../../../www/install/php') + ->name($fileNameVersionRegex); + + foreach ($updateFiles as $updateFile) { + if (preg_match($fileNameVersionRegex, $updateFile->getFilename(), $matches)) { + if (version_compare($matches['version'], $currentVersion, '>')) { + $availableUpdates[] = $matches['version']; } } - closedir($handle); } + dump($availableUpdates); + return $availableUpdates; } From 12bf4be0719248fa00ef3396c76e2fa7e1196c11 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Fri, 1 Jul 2022 11:25:38 +0200 Subject: [PATCH 12/27] legacy use new repository --- config/packages/Centreon.yaml | 8 ++ .../step_upgrade/process/process_step4.php | 128 ++++-------------- 2 files changed, 33 insertions(+), 103 deletions(-) diff --git a/config/packages/Centreon.yaml b/config/packages/Centreon.yaml index 2773911706c..711eda42ca7 100644 --- a/config/packages/Centreon.yaml +++ b/config/packages/Centreon.yaml @@ -220,6 +220,14 @@ services: class: Core\Infrastructure\Platform\Repository\FileReadPlatformRepository arguments: ['%centreon_etc_path%', '%centreon_install_path%'] + Core\Platform\Application\Repository\ReadVersionRepositoryInterface: + class: Core\Platform\Infrastructure\Repository\LegacyReadVersionRepository + public: true + + Core\Platform\Application\Repository\WriteVersionRepositoryInterface: + class: Core\Platform\Infrastructure\Repository\LegacyWriteVersionRepository + public: true + # Monitoring resources _instanceof: Centreon\Infrastructure\Monitoring\Resource\Provider\ProviderInterface: diff --git a/www/install/step_upgrade/process/process_step4.php b/www/install/step_upgrade/process/process_step4.php index 308c61a21af..97d95199b8c 100644 --- a/www/install/step_upgrade/process/process_step4.php +++ b/www/install/step_upgrade/process/process_step4.php @@ -1,128 +1,50 @@ . + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * Linking this program statically or dynamically with other modules is making a - * combined work based on this program. Thus, the terms and conditions of the GNU - * General Public License cover the whole combination. + * http://www.apache.org/licenses/LICENSE-2.0 * - * As a special exception, the copyright holders of this program give Centreon - * permission to link this program with independent modules to produce an executable, - * regardless of the license terms of these independent modules, and to copy and - * distribute the resulting executable under terms of Centreon choice, provided that - * Centreon also meet, for each linked independent module, the terms and conditions - * of the license of that module. An independent module is a module which is not - * derived from this program. If you modify this program, you may extend this - * exception to your version of the program, but you are not obliged to do so. If you - * do not wish to do so, delete this exception statement from your version. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. * * For more information : contact@centreon.com * */ session_start(); -require_once realpath(dirname(__FILE__) . "/../../../../config/centreon.config.php"); -require_once _CENTREON_PATH_ . '/www/class/centreonDB.class.php'; -require_once '../../steps/functions.php'; +require_once __DIR__ . '/../../../../bootstrap.php'; +require_once __DIR__ . '/../../../class/centreonDB.class.php'; +require_once __DIR__ . '/../../steps/functions.php'; + +use Core\Platform\Application\Repository\WriteVersionRepositoryInterface; $current = $_POST['current']; $next = $_POST['next']; $status = 0; -/** - * Variables for upgrade scripts - */ +$kernel = \App\Kernel::createForWeb(); +$upgradeWriteRepository = $kernel->getContainer()->get(WriteVersionRepositoryInterface::class); try { - $pearDB = new CentreonDB('centreon', 3); - $pearDBO = new CentreonDB('centstorage', 3); -} catch (Exception $e) { + $upgradeWriteRepository->runUpdate($next); +} catch (\Throwable $e) { exitUpgradeProcess(1, $current, $next, $e->getMessage()); } -/** - * Upgrade storage sql - */ -$storageSql = '../../sql/centstorage/Update-CSTG-' . $next . '.sql'; -if (is_file($storageSql)) { - $result = splitQueries($storageSql, ';', $pearDBO, '../../tmp/Update-CSTG-' . $next); - if ("0" != $result) { - exitUpgradeProcess(1, $current, $next, $result); - } -} - -/** - * Pre upgrade PHP - */ -$prePhp = '../../php/Update-' . $next . '.php'; -if (is_file($prePhp)) { - try { - include_once $prePhp; - } catch (Exception $e) { - exitUpgradeProcess(1, $current, $next, $e->getMessage()); - } -} - -/** - * Upgrade configuration sql - */ -$confSql = '../../sql/centreon/Update-DB-' . $next . '.sql'; -if (is_file($confSql)) { - $result = splitQueries($confSql, ';', $pearDB, '../../tmp/Update-DB-' . $next); - if ("0" != $result) { - exitUpgradeProcess(1, $current, $next, $result); - } -} - -/** - * Post upgrade PHP - */ -$postPhp = '../../php/Update-' . $next . '.post.php'; -if (is_file($postPhp)) { - try { - include_once $postPhp; - } catch (Exception $e) { - exitUpgradeProcess(1, $current, $next, $e->getMessage()); - } -} - -/** - * Update version in database. - */ -$res = $pearDB->prepare("UPDATE `informations` SET `value` = ? WHERE `key` = 'version'"); -$res->execute(array($next)); $current = $next; -/* -** To find the next version that we should update to, we will look in -** the www/install/php directory where all PHP update scripts are -** stored. We will extract the target version from the filename and find -** the closest version to the current version. -*/ -$next = ''; -if ($handle = opendir('../../php')) { - while (false !== ($file = readdir($handle))) { - if (preg_match('/Update-([a-zA-Z0-9\-\.]+)\.php/', $file, $matches)) { - if ((version_compare($current, $matches[1]) < 0) && - (empty($next) || (version_compare($matches[1], $next) < 0))) { - $next = $matches[1]; - } - } - } - closedir($handle); -} +$upgradeReadRepository = $kernel->getContainer()->get(ReadVersionRepositoryInterface::class); +$availableUpdates = $upgradeReadRepository->getOrderedAvailableUpdates($current); +$next = empty($availableUpdates) ? '' : array_shift($availableUpdates); + $_SESSION['CURRENT_VERSION'] = $current; $okMsg = "OK"; + exitUpgradeProcess($status, $current, $next, $okMsg); From 66f63a08535ab83be4dce131e5a049e6356035b4 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Fri, 1 Jul 2022 11:47:29 +0200 Subject: [PATCH 13/27] continue --- config/routes/Centreon/platform.yaml | 4 ++-- .../UpdateVersionsController.php | 2 +- .../UpdateVersions/UpdateVersionsSchema.json | 22 ++++++++++++++----- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/config/routes/Centreon/platform.yaml b/config/routes/Centreon/platform.yaml index bc1c86678a5..d77666e43f6 100644 --- a/config/routes/Centreon/platform.yaml +++ b/config/routes/Centreon/platform.yaml @@ -5,8 +5,8 @@ centreon_application_platform_getversion: condition: "request.attributes.get('version') >= 21.10" centreon_application_platform_updateversions: - methods: PUT - path: /platform/updates/centreon-web + methods: PATCH + path: /platform/updates controller: 'Core\Platform\Infrastructure\Api\UpdateVersions\UpdateVersionsController' condition: "request.attributes.get('version') >= 22.04" diff --git a/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php index b3570d7156d..54950e5a0c7 100644 --- a/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php +++ b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsController.php @@ -79,7 +79,7 @@ private function createUpdateVersionsRequest(Request $request): UpdateVersionsRe $requestData = json_decode((string) $request->getContent(), true); $updateVersionsRequest = new UpdateVersionsRequest(); - $updateVersionsRequest->centreonWebVersion = $requestData['centreon-web']; + $updateVersionsRequest->centreonWebVersion = $requestData['components']['centreon-web']; return $updateVersionsRequest; } diff --git a/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsSchema.json b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsSchema.json index 17591d3c750..cc89c07f7ea 100644 --- a/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsSchema.json +++ b/src/Core/Platform/Infrastructure/Api/UpdateVersions/UpdateVersionsSchema.json @@ -3,13 +3,23 @@ "title": "Update platform versions", "type": "object", "additionalProperties": false, - "required": [ - "centreon-web" - ], + "required": ["components"], "properties": { - "centreon-web": { - "type": "string", - "pattern": "^\\d+\\.\\d+\\.\\d+$" + "components": { + "type": "array", + "minItems": 1, + "maxItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["name"], + "properties": { + "name": { + "type": "string", + "enum": ["centreon-web"] + } + } + } } } } \ No newline at end of file From 31a7a22e9e092a0c42ff93df08e41ba506a22ccc Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Fri, 1 Jul 2022 14:23:37 +0200 Subject: [PATCH 14/27] remove request --- .../ReadVersionRepositoryInterface.php | 11 ------- .../UseCase/UpdateVersions/UpdateVersions.php | 9 +----- .../UpdateVersions/UpdateVersionsRequest.php | 32 ------------------- .../UpdateVersionsController.php | 17 +--------- .../LegacyReadVersionRepository.php | 30 +++-------------- 5 files changed, 7 insertions(+), 92 deletions(-) delete mode 100644 src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsRequest.php diff --git a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php index c4814a38de1..434283ce8ea 100644 --- a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php +++ b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php @@ -38,15 +38,4 @@ public function getCurrentVersion(): ?string; * @return string[] */ public function getOrderedAvailableUpdates(string $currentVersion): array; - - /** - * Get updates which are anterior to given version - * - * @param string $version - * @param string[] $updates - * @return string[] - * - * @throws \Exception - */ - public function getUpdatesUntil(string $version, array $updates): array; } diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index 9e425f039de..24a11d71a8d 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -44,11 +44,9 @@ public function __construct( /** * @param UpdateVersionsPresenterInterface $presenter - * @param UpdateVersionsRequest $request */ public function __invoke( UpdateVersionsPresenterInterface $presenter, - UpdateVersionsRequest $request, ): void { $this->info('Updating versions'); @@ -57,12 +55,7 @@ public function __invoke( $availableUpdates = $this->getAvailableUpdates($currentVersion); - $desiredUpdates = $this->readVersionRepository->getUpdatesUntil( - $request->centreonWebVersion, - $availableUpdates - ); - - $this->runUpdates($desiredUpdates); + $this->runUpdates($availableUpdates); } catch (\Throwable $e) { $presenter->setResponseStatus(new ErrorResponse($e->getMessage())); diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsRequest.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsRequest.php deleted file mode 100644 index bed3bdd3abe..00000000000 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsRequest.php +++ /dev/null @@ -1,32 +0,0 @@ -info('Validating request body...'); $this->validateDataSent($request, __DIR__ . '/UpdateVersionsSchema.json'); - $updateVersionsRequest = $this->createUpdateVersionsRequest($request); - $useCase($presenter, $updateVersionsRequest); + $useCase($presenter); return $presenter->show(); } - - /** - * @param Request $request - * @return UpdateVersionsRequest - */ - private function createUpdateVersionsRequest(Request $request): UpdateVersionsRequest - { - $requestData = json_decode((string) $request->getContent(), true); - - $updateVersionsRequest = new UpdateVersionsRequest(); - $updateVersionsRequest->centreonWebVersion = $requestData['components']['centreon-web']; - - return $updateVersionsRequest; - } } diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php index aea3b08fa9c..674b28aebb3 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php @@ -71,28 +71,6 @@ public function getOrderedAvailableUpdates(string $currentVersion): array return $this->orderUpdates($availableUpdates); } - /** - * @inheritDoc - */ - public function getUpdatesUntil(string $version, array $updates): array - { - $filteredUpdates = []; - foreach ($updates as $update) { - $filteredUpdates[] = $update; - if ($update === $version) { - return $filteredUpdates; - } - } - - $errorMessage = "Update to $version is not available"; - $this->error( - $errorMessage, - ['available_versions' => implode(', ', $updates)], - ); - - throw new \Exception($errorMessage); - } - /** * Get available updates * @@ -110,13 +88,12 @@ private function getAvailableUpdates(string $currentVersion): array foreach ($updateFiles as $updateFile) { if (preg_match($fileNameVersionRegex, $updateFile->getFilename(), $matches)) { if (version_compare($matches['version'], $currentVersion, '>')) { + $this->error('Update version found: ' . $matches['version']); $availableUpdates[] = $matches['version']; } } } - dump($availableUpdates); - return $availableUpdates; } @@ -128,7 +105,10 @@ private function getAvailableUpdates(string $currentVersion): array */ private function orderUpdates(array $updates): array { - usort($updates, 'version_compare'); + usort( + $updates, + fn (string $versionA, string $versionB) => version_compare($versionA, $versionB), + ); return $updates; } From 13d168f3fb15734ad7e2fbdc2102dc5c87be5d61 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Fri, 1 Jul 2022 15:46:34 +0200 Subject: [PATCH 15/27] add unit tests --- .../UpdateVersions/UpdateVersionsTest.php | 84 +++++++++++++++++++ .../LegacyReadVersionRepositoryTest.php | 71 ++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php create mode 100644 tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php diff --git a/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php b/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php new file mode 100644 index 00000000000..c9f1e2bf4b4 --- /dev/null +++ b/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php @@ -0,0 +1,84 @@ +readVersionRepository = $this->createMock(ReadVersionRepositoryInterface::class); + $this->writeVersionRepository = $this->createMock(WriteVersionRepositoryInterface::class); + $this->presenter = $this->createMock(UpdateVersionsPresenterInterface::class); +}); + +it('should present an error response if current version is not found', function () { + $updateVersions = new UpdateVersions($this->readVersionRepository, $this->writeVersionRepository); + + $this->readVersionRepository + ->expects($this->once()) + ->method('getCurrentVersion') + ->willReturn(null); + + $this->presenter + ->expects($this->once()) + ->method('setResponseStatus') + ->with(new ErrorResponse('Cannot retrieve current version')); + + $updateVersions($this->presenter); +}); + +it('should run found updates', function () { + $updateVersions = new UpdateVersions($this->readVersionRepository, $this->writeVersionRepository); + + $this->readVersionRepository + ->expects($this->once()) + ->method('getCurrentVersion') + ->willReturn('22.04.0'); + + $this->readVersionRepository + ->expects($this->once()) + ->method('getOrderedAvailableUpdates') + ->with('22.04.0') + ->willReturn(['22.10.0-beta.1', '22.10.0', '22.10.1']); + + $this->writeVersionRepository + ->expects($this->exactly(3)) + ->method('runUpdate') + ->withConsecutive( + [$this->equalTo('22.10.0-beta.1')], + [$this->equalTo('22.10.0')], + [$this->equalTo('22.10.1')], + ); + + $this->presenter + ->expects($this->once()) + ->method('setResponseStatus') + ->with(new NoContentResponse()); + + $updateVersions($this->presenter); +}); diff --git a/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php b/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php new file mode 100644 index 00000000000..88ac8a4f21c --- /dev/null +++ b/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php @@ -0,0 +1,71 @@ +finder = $this->createMock(Finder::class); + $this->db = $this->createMock(DatabaseConnection::class); +}); + +it('should order found updates', function () { + $repository = new LegacyReadVersionRepository($this->finder, $this->db); + + $this->finder + ->expects($this->once()) + ->method('files') + ->willReturn($this->finder); + + $this->finder + ->expects($this->once()) + ->method('in') + ->willReturn($this->finder); + + $this->finder + ->expects($this->once()) + ->method('name') + ->willReturn( + [ + new \SplFileInfo('Update-21.10.0.php'), + new \SplFileInfo('Update-22.04.0.php'), + new \SplFileInfo('Update-22.10.11.php'), + new \SplFileInfo('Update-22.10.1.php'), + new \SplFileInfo('Update-22.10.0-beta.3.php'), + new \SplFileInfo('Update-22.10.0-alpha.1.php'), + ] + ); + + $availableUpdates = $repository->getOrderedAvailableUpdates('22.04.0'); + expect($availableUpdates)->toEqual([ + '22.10.0-alpha.1', + '22.10.0-beta.3', + '22.10.1', + '22.10.11' + ]); +}); From e70406a5c6312138a49ad6421fcd1f1130d3280a Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Mon, 4 Jul 2022 13:46:12 +0200 Subject: [PATCH 16/27] take into accounts tamaz feedbacks --- .../UseCase/UpdateVersions/UpdateVersions.php | 10 +++--- .../LegacyReadVersionRepository.php | 2 +- .../LegacyWriteVersionRepository.php | 31 ++++++++++++------- 3 files changed, 26 insertions(+), 17 deletions(-) diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index 24a11d71a8d..b39a9784bd6 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -57,6 +57,11 @@ public function __invoke( $this->runUpdates($availableUpdates); } catch (\Throwable $e) { + $this->error( + $e->getMessage(), + ['trace' => $e->getTraceAsString()], + ); + $presenter->setResponseStatus(new ErrorResponse($e->getMessage())); return; @@ -77,10 +82,7 @@ private function getCurrentVersion(): string $currentVersion = $this->readVersionRepository->getCurrentVersion(); if ($currentVersion === null) { - $errorMessage = 'Cannot retrieve current version'; - $this->error($errorMessage); - - throw new \Exception($errorMessage); + throw new \Exception('Cannot retrieve current version'); } return $currentVersion; diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php index 674b28aebb3..53adf8b640f 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php @@ -88,7 +88,7 @@ private function getAvailableUpdates(string $currentVersion): array foreach ($updateFiles as $updateFile) { if (preg_match($fileNameVersionRegex, $updateFile->getFilename(), $matches)) { if (version_compare($matches['version'], $currentVersion, '>')) { - $this->error('Update version found: ' . $matches['version']); + $this->info('Update version found: ' . $matches['version']); $availableUpdates[] = $matches['version']; } } diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php index 39516540a43..42076609fb0 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php @@ -32,6 +32,8 @@ class LegacyWriteVersionRepository extends AbstractRepositoryDRB implements Writ { use LoggerTrait; + private const INSTALL_DIR = __DIR__ . '/../../../../../www/install'; + /** * @param DatabaseConnection $db */ @@ -59,8 +61,8 @@ public function runUpdate(string $update): void */ private function runMonitoringSql(string $version): void { - $upgradeFilePath = __DIR__ . '/../../../../../www/install/sql/centstorage/Update-CSTG-' . $version . '.sql'; - if (is_file($upgradeFilePath)) { + $upgradeFilePath = self::INSTALL_DIR . '/sql/centstorage/Update-CSTG-' . $version . '.sql'; + if (is_readable($upgradeFilePath)) { $this->db->switchToDb($this->db->getStorageDbName()); $this->runSqlFile($upgradeFilePath); } @@ -73,8 +75,8 @@ private function runMonitoringSql(string $version): void */ private function runScript(string $version): void { - $upgradeFilePath = __DIR__ . '/../../../../../www/install/php/Update-' . $version . '.php'; - if (is_file($upgradeFilePath)) { + $upgradeFilePath = self::INSTALL_DIR . '/php/Update-' . $version . '.php'; + if (is_readable($upgradeFilePath)) { include_once $upgradeFilePath; } } @@ -86,8 +88,8 @@ private function runScript(string $version): void */ private function runConfigurationSql(string $version): void { - $upgradeFilePath = __DIR__ . '/../../../../../www/install/sql/centreon/Update-DB-' . $version . '.sql'; - if (is_file($upgradeFilePath)) { + $upgradeFilePath = self::INSTALL_DIR . '/sql/centreon/Update-DB-' . $version . '.sql'; + if (is_readable($upgradeFilePath)) { $this->db->switchToDb($this->db->getCentreonDbName()); $this->runSqlFile($upgradeFilePath); } @@ -100,8 +102,8 @@ private function runConfigurationSql(string $version): void */ private function runPostScript(string $version): void { - $upgradeFilePath = __DIR__ . '/../../../../../www/install/php/Update-' . $version . '.post.php'; - if (is_file($upgradeFilePath)) { + $upgradeFilePath = self::INSTALL_DIR . '/php/Update-' . $version . '.post.php'; + if (is_readable($upgradeFilePath)) { include_once $upgradeFilePath; } } @@ -134,11 +136,11 @@ private function runSqlFile(string $filePath): void $count = 0; $start = 0; $fileName = basename($filePath); - $tmpFile = __DIR__ . '/../../../../../www/install/tmp/' . $fileName; - if (is_file($tmpFile)) { + $tmpFile = self::INSTALL_DIR . '/tmp/' . $fileName; + if (is_readable($tmpFile)) { $start = file_get_contents($tmpFile); } - if (is_file($filePath)) { + if (is_readable($filePath)) { $file = fopen($filePath, 'r'); if (is_resource($file)) { $query = ''; @@ -163,7 +165,12 @@ private function runSqlFile(string $filePath): void } flush(); $query = ''; - file_put_contents($tmpFile, $count); + if (is_writable($tmpFile)) { + $this->warning('Writing in temporary file : ' . $tmpFile); + file_put_contents($tmpFile, $count); + } else { + $this->warning('Cannot write in temporary file : ' . $tmpFile); + } } } } From 15077f493e7507a146a86fcd7852e05c28d3d25b Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Mon, 4 Jul 2022 15:07:42 +0200 Subject: [PATCH 17/27] begin refacto --- .../LegacyWriteVersionRepository.php | 67 +++++++++++++------ 1 file changed, 47 insertions(+), 20 deletions(-) diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php index 42076609fb0..8680c6324ba 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php @@ -133,27 +133,26 @@ private function updateVersionInformation(string $version): void private function runSqlFile(string $filePath): void { set_time_limit(0); - $count = 0; - $start = 0; + $fileName = basename($filePath); $tmpFile = self::INSTALL_DIR . '/tmp/' . $fileName; - if (is_readable($tmpFile)) { - $start = file_get_contents($tmpFile); - } + + $alreadyExecutedQueriesCount = $this->getAlreadyExecutedQueriesCount($tmpFile); + if (is_readable($filePath)) { - $file = fopen($filePath, 'r'); - if (is_resource($file)) { + $fileStream = fopen($filePath, 'r'); + if (is_resource($fileStream)) { $query = ''; - $line = 0; - while (! feof($file)) { - $line++; - $currentLine = fgets($file); + $currentLineNumber = 0; + $executedQueriesCount = 0; + while (! feof($fileStream)) { + $currentLineNumber++; + $currentLine = fgets($fileStream); if ($currentLine && ! str_starts_with('--', trim($currentLine))) { $query .= ' ' . trim($currentLine); } if (! empty($query) && preg_match('/;\s*$/', $query)) { - $count++; - if ($count > $start) { + if ($executedQueriesCount > $alreadyExecutedQueriesCount) { try { $this->db->query($query); } catch (\Exception $e) { @@ -165,17 +164,45 @@ private function runSqlFile(string $filePath): void } flush(); $query = ''; - if (is_writable($tmpFile)) { - $this->warning('Writing in temporary file : ' . $tmpFile); - file_put_contents($tmpFile, $count); - } else { - $this->warning('Cannot write in temporary file : ' . $tmpFile); - } + $executedQueriesCount++; + $this->writeExecutedQueriesCountInTemporaryFile($tmpFile, $executedQueriesCount); } } } - fclose($file); + fclose($fileStream); } } } + + /** + * Get stored executed queries count in temporary file to retrieve next query to run in case of an error occurred + * + * @param string $tmpFile + * @return int + */ + private function getAlreadyExecutedQueriesCount(string $tmpFile): int + { + $startLineNumber = 0; + if (is_readable($tmpFile)) { + $startLineNumber = file_get_contents($tmpFile); + } + + return $startLineNumber; + } + + /** + * Write executed queries count in temporary file to retrieve upgrade when an error occurred + * + * @param string $tmpFile + * @param int $count + */ + private function writeExecutedQueriesCountInTemporaryFile(string $tmpFile, int $count): void + { + if (is_writable($tmpFile)) { + $this->warning('Writing in temporary file : ' . $tmpFile); + file_put_contents($tmpFile, $count); + } else { + $this->warning('Cannot write in temporary file : ' . $tmpFile); + } + } } From b2e77833a7d1800b63bb7df08fce037ec29bed2c Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Mon, 4 Jul 2022 15:41:45 +0200 Subject: [PATCH 18/27] refacto sql upgrade method --- .../LegacyWriteVersionRepository.php | 82 +++++++++++++++---- 1 file changed, 65 insertions(+), 17 deletions(-) diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php index 8680c6324ba..4f09f44f67c 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php @@ -148,25 +148,20 @@ private function runSqlFile(string $filePath): void while (! feof($fileStream)) { $currentLineNumber++; $currentLine = fgets($fileStream); - if ($currentLine && ! str_starts_with('--', trim($currentLine))) { + if ($currentLine && ! $this->isSqlComment($currentLine)) { $query .= ' ' . trim($currentLine); } - if (! empty($query) && preg_match('/;\s*$/', $query)) { + + if ($this->isSqlCompleteQuery($query)) { + $executedQueriesCount++; if ($executedQueriesCount > $alreadyExecutedQueriesCount) { - try { - $this->db->query($query); - } catch (\Exception $e) { - $this->error('Cannot execute query : ' . $query); - throw $e; - } - while (ob_get_level() > 0) { - ob_end_flush(); - } - flush(); - $query = ''; - $executedQueriesCount++; + $this->executeQuery($query); + + $this->flushFileBuffer(); + $this->writeExecutedQueriesCountInTemporaryFile($tmpFile, $executedQueriesCount); } + $query = ''; } } fclose($fileStream); @@ -184,7 +179,10 @@ private function getAlreadyExecutedQueriesCount(string $tmpFile): int { $startLineNumber = 0; if (is_readable($tmpFile)) { - $startLineNumber = file_get_contents($tmpFile); + $lineNumber = file_get_contents($tmpFile); + if (is_numeric($lineNumber)) { + $startLineNumber = (int) $lineNumber; + } } return $startLineNumber; @@ -198,11 +196,61 @@ private function getAlreadyExecutedQueriesCount(string $tmpFile): int */ private function writeExecutedQueriesCountInTemporaryFile(string $tmpFile, int $count): void { - if (is_writable($tmpFile)) { - $this->warning('Writing in temporary file : ' . $tmpFile); + if (! file_exists($tmpFile) || is_writable($tmpFile)) { + $this->info('Writing in temporary file : ' . $tmpFile); file_put_contents($tmpFile, $count); } else { $this->warning('Cannot write in temporary file : ' . $tmpFile); } } + + /** + * Check if a line a sql comment + * + * @param string $line + * @return bool + */ + private function isSqlComment(string $line): bool + { + return str_starts_with('--', trim($line)); + } + + /** + * Check if a query is complete (trailing semicolon) + * + * @param string $query + * @return bool + */ + private function isSqlCompleteQuery(string $query): bool + { + return ! empty(trim($query)) && preg_match('/;\s*$/', $query); + } + + /** + * Execute sql query + * + * @param string $query + * + * @throws \Exception + */ + private function executeQuery(string $query): void + { + try { + $this->db->query($query); + } catch (\Exception $e) { + $this->error('Cannot execute query : ' . $query); + throw $e; + } + } + + /** + * Flush system output buffer + */ + private function flushFileBuffer(): void + { + while (ob_get_level() > 0) { + ob_end_flush(); + } + flush(); + } } From 733899079dc42b51d6188ab2c4031a3677c253a9 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 5 Jul 2022 08:29:59 +0200 Subject: [PATCH 19/27] rename repository and handle feedbacks --- .../ReadUpdateRepositoryInterface.php | 34 +++++++++++ .../ReadVersionRepositoryInterface.php | 8 --- ...php => WriteUpdateRepositoryInterface.php} | 8 +-- .../UseCase/UpdateVersions/UpdateVersions.php | 40 ++++++------- .../Repository/DbReadVersionRepository.php | 60 +++++++++++++++++++ ...sitory.php => DbWriteUpdateRepository.php} | 16 ++--- ...ository.php => FsReadUpdateRepository.php} | 26 +------- 7 files changed, 127 insertions(+), 65 deletions(-) create mode 100644 src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php rename src/Core/Platform/Application/Repository/{WriteVersionRepositoryInterface.php => WriteUpdateRepositoryInterface.php} (82%) create mode 100644 src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php rename src/Core/Platform/Infrastructure/Repository/{LegacyWriteVersionRepository.php => DbWriteUpdateRepository.php} (94%) rename src/Core/Platform/Infrastructure/Repository/{LegacyReadVersionRepository.php => FsReadUpdateRepository.php} (75%) diff --git a/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php new file mode 100644 index 00000000000..f75a476bd93 --- /dev/null +++ b/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php @@ -0,0 +1,34 @@ +info('Getting current version'); - $currentVersion = $this->readVersionRepository->getCurrentVersion(); + + try { + $currentVersion = $this->readVersionRepository->getCurrentVersion(); + } catch (\Exception $e) { + throw new \Exception('An error occurred when retrieving current version', 0, $e); + } if ($currentVersion === null) { throw new \Exception('Cannot retrieve current version'); @@ -99,14 +108,9 @@ private function getAvailableUpdates(string $currentVersion): array try { $this->info('Getting available updates'); - return $this->readVersionRepository->getOrderedAvailableUpdates($currentVersion); + return $this->readUpdateRepository->getOrderedAvailableUpdates($currentVersion); } catch (\Throwable $e) { - $this->error( - 'An error occurred when getting available updates', - ['trace' => $e->getTraceAsString()], - ); - - throw $e; + throw new \Exception('An error occurred when getting available updates', 0, $e); } } @@ -114,23 +118,17 @@ private function getAvailableUpdates(string $currentVersion): array * Run given updates * * @param string[] $updates + * + * @throws \Throwable */ private function runUpdates(array $updates): void { foreach ($updates as $update) { try { $this->info("Running update $update"); - $this->writeVersionRepository->runUpdate($update); + $this->writeUpdateRepository->runUpdate($update); } catch (\Throwable $e) { - $this->error( - 'An error occurred when applying update', - [ - 'update' => $update, - 'trace' => $e->getTraceAsString(), - ], - ); - - throw $e; + throw new \Exception('An error occurred when applying update: ' . $update, 0, $e); } } } diff --git a/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php new file mode 100644 index 00000000000..97805feb36f --- /dev/null +++ b/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php @@ -0,0 +1,60 @@ +db = $db; + } + + /** + * @inheritDoc + */ + public function getCurrentVersion(): ?string + { + $currentVersion = null; + + $statement = $this->db->query( + "SELECT `value` FROM `informations` WHERE `key` = 'version'" + ); + if ($statement !== false && is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) { + $currentVersion = $result['value']; + } + + return $currentVersion; + } +} diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php similarity index 94% rename from src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php rename to src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php index 4f09f44f67c..81872bebd6f 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyWriteVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php @@ -26,9 +26,9 @@ use Centreon\Domain\Log\LoggerTrait; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; -use Core\Platform\Application\Repository\WriteVersionRepositoryInterface; +use Core\Platform\Application\Repository\WriteUpdateRepositoryInterface; -class LegacyWriteVersionRepository extends AbstractRepositoryDRB implements WriteVersionRepositoryInterface +class DbWriteUpdateRepository extends AbstractRepositoryDRB implements WriteUpdateRepositoryInterface { use LoggerTrait; @@ -45,13 +45,13 @@ public function __construct(DatabaseConnection $db) /** * @inheritDoc */ - public function runUpdate(string $update): void + public function runUpdate(string $version): void { - $this->runMonitoringSql($update); - $this->runScript($update); - $this->runConfigurationSql($update); - $this->runPostScript($update); - $this->updateVersionInformation($update); + $this->runMonitoringSql($version); + $this->runScript($version); + $this->runConfigurationSql($version); + $this->runPostScript($version); + $this->updateVersionInformation($version); } /** diff --git a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php similarity index 75% rename from src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php rename to src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php index 53adf8b640f..3bf61b69a8e 100644 --- a/src/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php @@ -24,41 +24,19 @@ namespace Core\Platform\Infrastructure\Repository; use Centreon\Domain\Log\LoggerTrait; -use Centreon\Infrastructure\DatabaseConnection; -use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; -use Core\Platform\Application\Repository\ReadVersionRepositoryInterface; +use Core\Platform\Application\Repository\ReadUpdateRepositoryInterface; use Symfony\Component\Finder\Finder; -class LegacyReadVersionRepository extends AbstractRepositoryDRB implements ReadVersionRepositoryInterface +class FsReadUpdateRepository implements ReadUpdateRepositoryInterface { use LoggerTrait; /** * @param Finder $finder - * @param DatabaseConnection $db */ public function __construct( private Finder $finder, - DatabaseConnection $db, ) { - $this->db = $db; - } - - /** - * @inheritDoc - */ - public function getCurrentVersion(): ?string - { - $currentVersion = null; - - $statement = $this->db->query( - "SELECT `value` FROM `informations` WHERE `key` = 'version'" - ); - if ($statement !== false && is_array($result = $statement->fetch(\PDO::FETCH_ASSOC))) { - $currentVersion = $result['value']; - } - - return $currentVersion; } /** From 84b03fcf8de84653e5b0d3ebf5ba0eb715589222 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 5 Jul 2022 08:34:00 +0200 Subject: [PATCH 20/27] fix tests --- .../UpdateVersions/UpdateVersionsTest.php | 22 ++++++++++++++----- .../LegacyReadVersionRepositoryTest.php | 8 ++----- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php b/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php index c9f1e2bf4b4..1d3ee805b7b 100644 --- a/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php +++ b/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php @@ -26,18 +26,24 @@ use Core\Platform\Application\UseCase\UpdateVersions\UpdateVersions; use Core\Platform\Application\UseCase\UpdateVersions\UpdateVersionsPresenterInterface; use Core\Platform\Application\Repository\ReadVersionRepositoryInterface; -use Core\Platform\Application\Repository\WriteVersionRepositoryInterface; +use Core\Platform\Application\Repository\ReadUpdateRepositoryInterface; +use Core\Platform\Application\Repository\WriteUpdateRepositoryInterface; use Core\Application\Common\UseCase\ErrorResponse; use Core\Application\Common\UseCase\NoContentResponse; beforeEach(function () { $this->readVersionRepository = $this->createMock(ReadVersionRepositoryInterface::class); - $this->writeVersionRepository = $this->createMock(WriteVersionRepositoryInterface::class); + $this->readUpdateRepository = $this->createMock(ReadUpdateRepositoryInterface::class); + $this->writeUpdateRepository = $this->createMock(WriteUpdateRepositoryInterface::class); $this->presenter = $this->createMock(UpdateVersionsPresenterInterface::class); }); it('should present an error response if current version is not found', function () { - $updateVersions = new UpdateVersions($this->readVersionRepository, $this->writeVersionRepository); + $updateVersions = new UpdateVersions( + $this->readVersionRepository, + $this->readUpdateRepository, + $this->writeUpdateRepository, + ); $this->readVersionRepository ->expects($this->once()) @@ -53,20 +59,24 @@ }); it('should run found updates', function () { - $updateVersions = new UpdateVersions($this->readVersionRepository, $this->writeVersionRepository); + $updateVersions = new UpdateVersions( + $this->readVersionRepository, + $this->readUpdateRepository, + $this->writeUpdateRepository, + ); $this->readVersionRepository ->expects($this->once()) ->method('getCurrentVersion') ->willReturn('22.04.0'); - $this->readVersionRepository + $this->readUpdateRepository ->expects($this->once()) ->method('getOrderedAvailableUpdates') ->with('22.04.0') ->willReturn(['22.10.0-beta.1', '22.10.0', '22.10.1']); - $this->writeVersionRepository + $this->writeUpdateRepository ->expects($this->exactly(3)) ->method('runUpdate') ->withConsecutive( diff --git a/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php b/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php index 88ac8a4f21c..27de7f6bfea 100644 --- a/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php +++ b/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php @@ -23,19 +23,15 @@ namespace Tests\Core\Platform\Infrastructure\Repository; -use Core\Platform\Infrastructure\Repository\LegacyReadVersionRepository; -use Centreon\Domain\Log\LoggerTrait; -use Centreon\Infrastructure\DatabaseConnection; -use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; +use Core\Platform\Infrastructure\Repository\FsReadUpdateRepository; use Symfony\Component\Finder\Finder; beforeEach(function () { $this->finder = $this->createMock(Finder::class); - $this->db = $this->createMock(DatabaseConnection::class); }); it('should order found updates', function () { - $repository = new LegacyReadVersionRepository($this->finder, $this->db); + $repository = new FsReadUpdateRepository($this->finder); $this->finder ->expects($this->once()) From ed2f423dbd34193476c7b5a8d0bea6ea411f84ff Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 5 Jul 2022 09:09:59 +0200 Subject: [PATCH 21/27] fix --- config/packages/Centreon.yaml | 10 +++++++--- www/install/step_upgrade/process/process_step4.php | 7 ++++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/config/packages/Centreon.yaml b/config/packages/Centreon.yaml index 711eda42ca7..18b44c439f6 100644 --- a/config/packages/Centreon.yaml +++ b/config/packages/Centreon.yaml @@ -221,11 +221,15 @@ services: arguments: ['%centreon_etc_path%', '%centreon_install_path%'] Core\Platform\Application\Repository\ReadVersionRepositoryInterface: - class: Core\Platform\Infrastructure\Repository\LegacyReadVersionRepository + class: Core\Platform\Infrastructure\Repository\DbReadVersionRepository public: true - Core\Platform\Application\Repository\WriteVersionRepositoryInterface: - class: Core\Platform\Infrastructure\Repository\LegacyWriteVersionRepository + Core\Platform\Application\Repository\ReadUpdateRepositoryInterface: + class: Core\Platform\Infrastructure\Repository\FsReadUpdateRepository + public: true + + Core\Platform\Application\Repository\WriteUpdateRepositoryInterface: + class: Core\Platform\Infrastructure\Repository\DbWriteUpdateRepository public: true # Monitoring resources diff --git a/www/install/step_upgrade/process/process_step4.php b/www/install/step_upgrade/process/process_step4.php index 97d95199b8c..5f9f6b94a93 100644 --- a/www/install/step_upgrade/process/process_step4.php +++ b/www/install/step_upgrade/process/process_step4.php @@ -24,14 +24,15 @@ require_once __DIR__ . '/../../../class/centreonDB.class.php'; require_once __DIR__ . '/../../steps/functions.php'; -use Core\Platform\Application\Repository\WriteVersionRepositoryInterface; +use Core\Platform\Application\Repository\ReadUpdateRepositoryInterface; +use Core\Platform\Application\Repository\WriteUpdateRepositoryInterface; $current = $_POST['current']; $next = $_POST['next']; $status = 0; $kernel = \App\Kernel::createForWeb(); -$upgradeWriteRepository = $kernel->getContainer()->get(WriteVersionRepositoryInterface::class); +$upgradeWriteRepository = $kernel->getContainer()->get(WriteUpdateRepositoryInterface::class); try { $upgradeWriteRepository->runUpdate($next); } catch (\Throwable $e) { @@ -40,7 +41,7 @@ $current = $next; -$upgradeReadRepository = $kernel->getContainer()->get(ReadVersionRepositoryInterface::class); +$upgradeReadRepository = $kernel->getContainer()->get(ReadUpdateRepositoryInterface::class); $availableUpdates = $upgradeReadRepository->getOrderedAvailableUpdates($current); $next = empty($availableUpdates) ? '' : array_shift($availableUpdates); From 9bb95e4f5ca5f13e7205c42aedf6d4b7c27b0447 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 5 Jul 2022 11:16:42 +0200 Subject: [PATCH 22/27] handle feedbacks --- .../Repository/ReadUpdateRepositoryInterface.php | 2 +- .../Repository/ReadVersionRepositoryInterface.php | 2 +- .../UseCase/UpdateVersions/UpdateVersions.php | 12 ++++++------ .../Repository/DbReadVersionRepository.php | 2 +- .../Repository/FsReadUpdateRepository.php | 6 +++--- .../UseCase/UpdateVersions/UpdateVersionsTest.php | 6 +++--- .../Repository/LegacyReadVersionRepositoryTest.php | 2 +- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php index f75a476bd93..db999e5fa71 100644 --- a/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php +++ b/src/Core/Platform/Application/Repository/ReadUpdateRepositoryInterface.php @@ -30,5 +30,5 @@ interface ReadUpdateRepositoryInterface * @param string $currentVersion * @return string[] */ - public function getOrderedAvailableUpdates(string $currentVersion): array; + public function findOrderedAvailableUpdates(string $currentVersion): array; } diff --git a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php index c7c9ee4ee26..00d400ebc68 100644 --- a/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php +++ b/src/Core/Platform/Application/Repository/ReadVersionRepositoryInterface.php @@ -29,5 +29,5 @@ interface ReadVersionRepositoryInterface * * @return string|null */ - public function getCurrentVersion(): ?string; + public function findCurrentVersion(): ?string; } diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index 892826d83e7..d8690be94d4 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -54,9 +54,9 @@ public function __invoke( $this->info('Updating versions'); try { - $currentVersion = $this->getCurrentVersion(); + $currentVersion = $this->getCurrentVersionOrFail(); - $availableUpdates = $this->getAvailableUpdates($currentVersion); + $availableUpdates = $this->getAvailableUpdatesOrFail($currentVersion); $this->runUpdates($availableUpdates); } catch (\Throwable $e) { @@ -80,12 +80,12 @@ public function __invoke( * * @throws \Exception */ - private function getCurrentVersion(): string + private function getCurrentVersionOrFail(): string { $this->info('Getting current version'); try { - $currentVersion = $this->readVersionRepository->getCurrentVersion(); + $currentVersion = $this->readVersionRepository->findCurrentVersion(); } catch (\Exception $e) { throw new \Exception('An error occurred when retrieving current version', 0, $e); } @@ -103,12 +103,12 @@ private function getCurrentVersion(): string * @param string $currentVersion * @return string[] */ - private function getAvailableUpdates(string $currentVersion): array + private function getAvailableUpdatesOrFail(string $currentVersion): array { try { $this->info('Getting available updates'); - return $this->readUpdateRepository->getOrderedAvailableUpdates($currentVersion); + return $this->readUpdateRepository->findOrderedAvailableUpdates($currentVersion); } catch (\Throwable $e) { throw new \Exception('An error occurred when getting available updates', 0, $e); } diff --git a/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php b/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php index 97805feb36f..f33662a7d5e 100644 --- a/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/DbReadVersionRepository.php @@ -44,7 +44,7 @@ public function __construct( /** * @inheritDoc */ - public function getCurrentVersion(): ?string + public function findCurrentVersion(): ?string { $currentVersion = null; diff --git a/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php b/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php index 3bf61b69a8e..dc15f27f654 100644 --- a/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/FsReadUpdateRepository.php @@ -42,9 +42,9 @@ public function __construct( /** * @inheritDoc */ - public function getOrderedAvailableUpdates(string $currentVersion): array + public function findOrderedAvailableUpdates(string $currentVersion): array { - $availableUpdates = $this->getAvailableUpdates($currentVersion); + $availableUpdates = $this->findAvailableUpdates($currentVersion); return $this->orderUpdates($availableUpdates); } @@ -55,7 +55,7 @@ public function getOrderedAvailableUpdates(string $currentVersion): array * @param string $currentVersion * @return string[] */ - private function getAvailableUpdates(string $currentVersion): array + private function findAvailableUpdates(string $currentVersion): array { $fileNameVersionRegex = '/Update-(?[a-zA-Z0-9\-\.]+)\.php/'; $availableUpdates = []; diff --git a/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php b/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php index 1d3ee805b7b..a772a21169b 100644 --- a/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php +++ b/tests/php/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersionsTest.php @@ -47,7 +47,7 @@ $this->readVersionRepository ->expects($this->once()) - ->method('getCurrentVersion') + ->method('findCurrentVersion') ->willReturn(null); $this->presenter @@ -67,12 +67,12 @@ $this->readVersionRepository ->expects($this->once()) - ->method('getCurrentVersion') + ->method('findCurrentVersion') ->willReturn('22.04.0'); $this->readUpdateRepository ->expects($this->once()) - ->method('getOrderedAvailableUpdates') + ->method('findOrderedAvailableUpdates') ->with('22.04.0') ->willReturn(['22.10.0-beta.1', '22.10.0', '22.10.1']); diff --git a/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php b/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php index 27de7f6bfea..2064430fe22 100644 --- a/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php +++ b/tests/php/Core/Platform/Infrastructure/Repository/LegacyReadVersionRepositoryTest.php @@ -57,7 +57,7 @@ ] ); - $availableUpdates = $repository->getOrderedAvailableUpdates('22.04.0'); + $availableUpdates = $repository->findOrderedAvailableUpdates('22.04.0'); expect($availableUpdates)->toEqual([ '22.10.0-alpha.1', '22.10.0-beta.3', From 1aff44209c600ac463d3004da4558df34015159b Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 5 Jul 2022 13:47:06 +0200 Subject: [PATCH 23/27] remove useless import --- .../Repository/FsUpdateLockerRepository.php | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 src/Core/Platform/Infrastructure/Repository/FsUpdateLockerRepository.php diff --git a/src/Core/Platform/Infrastructure/Repository/FsUpdateLockerRepository.php b/src/Core/Platform/Infrastructure/Repository/FsUpdateLockerRepository.php new file mode 100644 index 00000000000..14f76de3ea2 --- /dev/null +++ b/src/Core/Platform/Infrastructure/Repository/FsUpdateLockerRepository.php @@ -0,0 +1,82 @@ +lock = $lockFactory->createLock(self::LOCK_NAME); + } + + /** + * {@inheritDoc} + * + * @throws UpdateLockerException + */ + public function lock(): bool + { + $this->info('Locking centreon update process on filesystem...'); + + try { + return $this->lock->acquire(); + } catch (\Throwable $e) { + throw UpdateLockerException::errorWhileLockingUpdate($e); + } + } + + /** + * {@inheritDoc} + * + * @throws UpdateLockerException + */ + public function unlock(): void + { + $this->info('Unlocking centreon update process from filesystem...'); + + try { + $this->lock->release(); + } catch (\Throwable $e) { + throw UpdateLockerException::errorWhileUnlockingUpdate($e); + } + } +} From 535fca5a018c15c4ad55c619cba7af25ed402cdb Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 5 Jul 2022 13:49:47 +0200 Subject: [PATCH 24/27] remove locker --- .../Repository/FsUpdateLockerRepository.php | 82 ------------------- 1 file changed, 82 deletions(-) delete mode 100644 src/Core/Platform/Infrastructure/Repository/FsUpdateLockerRepository.php diff --git a/src/Core/Platform/Infrastructure/Repository/FsUpdateLockerRepository.php b/src/Core/Platform/Infrastructure/Repository/FsUpdateLockerRepository.php deleted file mode 100644 index 14f76de3ea2..00000000000 --- a/src/Core/Platform/Infrastructure/Repository/FsUpdateLockerRepository.php +++ /dev/null @@ -1,82 +0,0 @@ -lock = $lockFactory->createLock(self::LOCK_NAME); - } - - /** - * {@inheritDoc} - * - * @throws UpdateLockerException - */ - public function lock(): bool - { - $this->info('Locking centreon update process on filesystem...'); - - try { - return $this->lock->acquire(); - } catch (\Throwable $e) { - throw UpdateLockerException::errorWhileLockingUpdate($e); - } - } - - /** - * {@inheritDoc} - * - * @throws UpdateLockerException - */ - public function unlock(): void - { - $this->info('Unlocking centreon update process from filesystem...'); - - try { - $this->lock->release(); - } catch (\Throwable $e) { - throw UpdateLockerException::errorWhileUnlockingUpdate($e); - } - } -} From 5416212c9f93ba8d4e4896291188e891fc21aeae Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 5 Jul 2022 14:57:46 +0200 Subject: [PATCH 25/27] handle properly exceptions --- .../UseCase/UpdateVersions/UpdateVersions.php | 25 ++++--- .../Repository/DbWriteUpdateRepository.php | 67 ++++++++++--------- 2 files changed, 54 insertions(+), 38 deletions(-) diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index d8690be94d4..616fa323e37 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -106,7 +106,12 @@ private function getCurrentVersionOrFail(): string private function getAvailableUpdatesOrFail(string $currentVersion): array { try { - $this->info('Getting available updates'); + $this->info( + 'Getting available updates', + [ + 'current_version' => $currentVersion, + ], + ); return $this->readUpdateRepository->findOrderedAvailableUpdates($currentVersion); } catch (\Throwable $e) { @@ -115,20 +120,24 @@ private function getAvailableUpdatesOrFail(string $currentVersion): array } /** - * Run given updates + * Run given version updates * - * @param string[] $updates + * @param string[] $versions * * @throws \Throwable */ - private function runUpdates(array $updates): void + private function runUpdates(array $versions): void { - foreach ($updates as $update) { + foreach ($versions as $version) { try { - $this->info("Running update $update"); - $this->writeUpdateRepository->runUpdate($update); + $this->info("Running update $version"); + $this->writeUpdateRepository->runUpdate($version); } catch (\Throwable $e) { - throw new \Exception('An error occurred when applying update: ' . $update, 0, $e); + throw new \Exception( + 'An error occurred when applying update ' . $version . ': ' . $e->getMessage(), + 0, + $e, + ); } } } diff --git a/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php b/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php index 81872bebd6f..3fe397f02f5 100644 --- a/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php +++ b/src/Core/Platform/Infrastructure/Repository/DbWriteUpdateRepository.php @@ -23,10 +23,12 @@ namespace Core\Platform\Infrastructure\Repository; +use Pimple\Container; use Centreon\Domain\Log\LoggerTrait; use Centreon\Infrastructure\DatabaseConnection; use Centreon\Infrastructure\Repository\AbstractRepositoryDRB; use Core\Platform\Application\Repository\WriteUpdateRepositoryInterface; +use Centreon\Domain\Repository\RepositoryException; class DbWriteUpdateRepository extends AbstractRepositoryDRB implements WriteUpdateRepositoryInterface { @@ -35,10 +37,13 @@ class DbWriteUpdateRepository extends AbstractRepositoryDRB implements WriteUpda private const INSTALL_DIR = __DIR__ . '/../../../../../www/install'; /** + * @param Container $dependencyInjector * @param DatabaseConnection $db */ - public function __construct(DatabaseConnection $db) - { + public function __construct( + private Container $dependencyInjector, + DatabaseConnection $db, + ) { $this->db = $db; } @@ -75,6 +80,9 @@ private function runMonitoringSql(string $version): void */ private function runScript(string $version): void { + $pearDB = $this->dependencyInjector['configuration_db']; + $pearDBO = $this->dependencyInjector['realtime_db']; + $upgradeFilePath = self::INSTALL_DIR . '/php/Update-' . $version . '.php'; if (is_readable($upgradeFilePath)) { include_once $upgradeFilePath; @@ -102,6 +110,9 @@ private function runConfigurationSql(string $version): void */ private function runPostScript(string $version): void { + $pearDB = $this->dependencyInjector['configuration_db']; + $pearDBO = $this->dependencyInjector['realtime_db']; + $upgradeFilePath = self::INSTALL_DIR . '/php/Update-' . $version . '.post.php'; if (is_readable($upgradeFilePath)) { include_once $upgradeFilePath; @@ -145,26 +156,34 @@ private function runSqlFile(string $filePath): void $query = ''; $currentLineNumber = 0; $executedQueriesCount = 0; - while (! feof($fileStream)) { - $currentLineNumber++; - $currentLine = fgets($fileStream); - if ($currentLine && ! $this->isSqlComment($currentLine)) { - $query .= ' ' . trim($currentLine); - } - - if ($this->isSqlCompleteQuery($query)) { - $executedQueriesCount++; - if ($executedQueriesCount > $alreadyExecutedQueriesCount) { - $this->executeQuery($query); + try { + while (! feof($fileStream)) { + $currentLineNumber++; + $currentLine = fgets($fileStream); + if ($currentLine && ! $this->isSqlComment($currentLine)) { + $query .= ' ' . trim($currentLine); + } - $this->flushFileBuffer(); + if ($this->isSqlCompleteQuery($query)) { + $executedQueriesCount++; + if ($executedQueriesCount > $alreadyExecutedQueriesCount) { + try { + $this->executeQuery($query); + } catch (RepositoryException $e) { + throw $e; + } - $this->writeExecutedQueriesCountInTemporaryFile($tmpFile, $executedQueriesCount); + $this->writeExecutedQueriesCountInTemporaryFile($tmpFile, $executedQueriesCount); + } + $query = ''; } - $query = ''; } + } catch (\Throwable $e) { + $this->error($e->getMessage(), ['trace' => $e->getTraceAsString()]); + throw $e; + } finally { + fclose($fileStream); } - fclose($fileStream); } } } @@ -238,19 +257,7 @@ private function executeQuery(string $query): void try { $this->db->query($query); } catch (\Exception $e) { - $this->error('Cannot execute query : ' . $query); - throw $e; - } - } - - /** - * Flush system output buffer - */ - private function flushFileBuffer(): void - { - while (ob_get_level() > 0) { - ob_end_flush(); + throw new RepositoryException('Cannot execute query: ' . $query, 0, $e); } - flush(); } } From 725f746dd16f818cbb09705f1d73d13d0faee63d Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 5 Jul 2022 15:29:15 +0200 Subject: [PATCH 26/27] Update src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php Co-authored-by: Laurent Calvet --- .../Application/UseCase/UpdateVersions/UpdateVersions.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index 616fa323e37..d1b174409e9 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -134,7 +134,11 @@ private function runUpdates(array $versions): void $this->writeUpdateRepository->runUpdate($version); } catch (\Throwable $e) { throw new \Exception( - 'An error occurred when applying update ' . $version . ': ' . $e->getMessage(), + sprintf( + 'An error occurred when applying update %s (%s)', + $version, + $e->getMessage() + ), 0, $e, ); From 2be64c5347bedd1f47911fd10899a475b1533f07 Mon Sep 17 00:00:00 2001 From: Kevin Duret Date: Tue, 5 Jul 2022 16:13:59 +0200 Subject: [PATCH 27/27] Update src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php --- .../UseCase/UpdateVersions/UpdateVersions.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php index d1b174409e9..67b7eb73ae4 100644 --- a/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php +++ b/src/Core/Platform/Application/UseCase/UpdateVersions/UpdateVersions.php @@ -134,11 +134,11 @@ private function runUpdates(array $versions): void $this->writeUpdateRepository->runUpdate($version); } catch (\Throwable $e) { throw new \Exception( - sprintf( - 'An error occurred when applying update %s (%s)', - $version, - $e->getMessage() - ), + sprintf( + 'An error occurred when applying update %s (%s)', + $version, + $e->getMessage(), + ), 0, $e, );