Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Fixed

- Uninstalling an ExApp in the app management and removing its deploy daemon also remove the ExApp's Kubernetes resources. #1210
- Registry mappings of a deploy daemon (`occ app_api:daemon:registry:add`) are applied by the Kubernetes backend too; before, ExApp images were always taken from the registry in `info.xml`. A `local` mapping sets `imagePullPolicy: Never` with HaRP newer than 0.4.5, so the image must be present on every node. #1046
- Updating a deploy daemon that does not exist answers `success: false` instead of a server error. #1082
- The ExApp proxy also refuses `.` path segments and `..` segments followed by `;`, `%3F` or `%23`. #1163
Expand Down
19 changes: 1 addition & 18 deletions lib/Command/ExApp/Unregister.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use OCA\AppAPI\DeployActions\KubernetesActions;
use OCA\AppAPI\Service\AppAPIService;
use OCA\AppAPI\Service\DaemonConfigService;
use OCA\AppAPI\Service\ExAppDeployOptionsService;
use OCA\AppAPI\Service\ExAppService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
Expand All @@ -29,7 +28,6 @@ public function __construct(
private readonly DockerActions $dockerActions,
private readonly KubernetesActions $kubernetesActions,
private readonly ExAppService $exAppService,
private readonly ExAppDeployOptionsService $exAppDeployOptionsService,
) {
parent::__construct();
}
Expand Down Expand Up @@ -153,22 +151,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
}
} elseif ($daemonConfig->getAcceptsDeployId() === $this->kubernetesActions->getAcceptsDeployId()) {
$this->kubernetesActions->initGuzzleClient($daemonConfig);
$harpK8sUrl = $this->kubernetesActions->buildHarpK8sUrl($daemonConfig);

// Check for stored multi-role configuration
$rolesOption = $this->exAppDeployOptionsService->getDeployOption($exApp->getAppid(), 'k8s_service_roles');
$roles = $rolesOption !== null ? $rolesOption->getValue() : [];

if (!empty($roles) && is_array($roles)) {
$removeResult = $this->kubernetesActions->removeAllRoles(
$harpK8sUrl, $exApp->getAppid(), $roles, removeData: $rmData
);
} else {
$removeResult = $this->kubernetesActions->removeExApp(
$harpK8sUrl, $exApp->getAppid(), removeData: $rmData
);
}
$removeResult = $this->kubernetesActions->removeExAppResources($daemonConfig, $exApp->getAppid(), removeData: $rmData);
if ($removeResult) {
if (!$silent) {
$output->writeln(sprintf('Failed to remove K8s ExApp %s: %s', $appId, $removeResult));
Expand Down
7 changes: 7 additions & 0 deletions lib/Controller/ExAppsPageController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use OC\App\Platform;
use OCA\AppAPI\AppInfo\Application;
use OCA\AppAPI\DeployActions\DockerActions;
use OCA\AppAPI\DeployActions\KubernetesActions;
use OCA\AppAPI\Fetcher\ExAppFetcher;
use OCA\AppAPI\ResponseDefinitions;
use OCA\AppAPI\Service\AppAPIService;
Expand Down Expand Up @@ -52,6 +53,7 @@ public function __construct(
private readonly AppAPIService $service,
private readonly DaemonConfigService $daemonConfigService,
private readonly DockerActions $dockerActions,
private readonly KubernetesActions $kubernetesActions,
private readonly CategoryFetcher $categoryFetcher,
private readonly IFactory $l10nFactory,
private readonly ExAppFetcher $exAppFetcher,
Expand Down Expand Up @@ -512,6 +514,11 @@ public function uninstallApp(string $appId, bool $removeContainer = true, bool $
}
}
}
} elseif ($daemonConfig->getAcceptsDeployId() === $this->kubernetesActions->getAcceptsDeployId()) {
$removeError = $this->kubernetesActions->removeExAppResources($daemonConfig, $exApp->getAppid(), removeData: $removeData);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Honor removeContainer before deleting Kubernetes deployments.

uninstallApp() documents $removeContainer as whether to remove the ExApp container. The Kubernetes branch removes the ExApp deployments without checking that flag. A caller that passes removeContainer: false still loses the running workload.

The non-harp Docker branch guards its container removal with $removeContainer. Apply the same guard to the Kubernetes branch.

Suggested fix

--- "a/lib/Controller/ExAppsPageController.php"
+++ "b/lib/Controller/ExAppsPageController.php"
@@ -514,12 +514,14 @@
 						}
 					}
 				}
 			} elseif ($daemonConfig->getAcceptsDeployId() === $this->kubernetesActions->getAcceptsDeployId()) {
-				$removeError = $this->kubernetesActions->removeExAppResources($daemonConfig, $exApp->getAppid(), removeData: $removeData);
-				if ($removeData && $removeError === '') {
-					$this->exAppService->logExAppDataDeleted($exApp);
-				}
+				if ($removeContainer) {
+					$removeError = $this->kubernetesActions->removeExAppResources($daemonConfig, $exApp->getAppid(), removeData: $removeData);
+					if ($removeData && $removeError === '') {
+						$this->exAppService->logExAppDataDeleted($exApp);
+					}
+				}
 			}
 			$this->exAppService->unregisterExApp($appId);
 		}
 		return new JSONResponse();

if ($removeData && $removeError === '') {
$this->exAppService->logExAppDataDeleted($exApp);
}
Comment on lines +519 to +521

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Data Integrity & Integration · Quick win

Preserve the registration when Kubernetes cleanup fails.

If HaRP is unavailable or one role cannot be removed, $removeError is nonempty. The controller still calls unregisterExApp() at Line 523 and returns success. ExAppService::unregisterExApp() also deletes k8s_service_roles, so remaining deployments lose their cleanup metadata and the administrator cannot retry removal through AppAPI.

Return an error before unregistration when cleanup fails. Retain the registration and deployment options for a retry.

}
$this->exAppService->unregisterExApp($appId);
}
Expand Down
27 changes: 24 additions & 3 deletions lib/DeployActions/KubernetesActions.php
Original file line number Diff line number Diff line change
Expand Up @@ -287,14 +287,35 @@ public function stopAllRoles(string $harpUrl, string $exAppName, array $roles):
return '';
}

/**
* Remove the deployment of every role, also after a failed one
*
* @return string the first error, empty on success
*/
public function removeAllRoles(string $harpUrl, string $exAppName, array $roles, bool $removeData = false): string {
$firstError = '';
foreach ($roles as $role) {
$error = $this->removeExApp($harpUrl, $exAppName, removeData: $removeData, roleSuffix: $role['name']);
if ($error) {
return $error;
if ($firstError === '') {
$firstError = $error;
}
}
return '';
return $firstError;
}

/**
* Remove the Kubernetes resources of an ExApp, of every role for a multi-role ExApp
*
* @return string the error, empty on success
*/
public function removeExAppResources(DaemonConfig $daemonConfig, string $exAppName, bool $removeData = false): string {
$this->initGuzzleClient($daemonConfig);
$harpK8sUrl = $this->buildHarpK8sUrl($daemonConfig);
$roles = $this->exAppDeployOptionsService->getDeployOption($exAppName, 'k8s_service_roles')?->getValue() ?? [];
if ($roles !== []) {
return $this->removeAllRoles($harpK8sUrl, $exAppName, $roles, removeData: $removeData);
}
return $this->removeExApp($harpK8sUrl, $exAppName, removeData: $removeData);
}

private function buildNamePayload(string $exAppName, string $instanceId = '', string $roleSuffix = ''): array {
Expand Down
4 changes: 4 additions & 0 deletions lib/Service/AppAPIService.php
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,10 @@ public function removeExAppsByDaemonConfigName(DaemonConfig $daemonConfig): void
if ($dataDeleted) {
$this->exAppService->logExAppDataDeleted($exApp);
}
} elseif ($daemonConfig->getAcceptsDeployId() === $this->kubernetesActions->getAcceptsDeployId()) {
if ($this->kubernetesActions->removeExAppResources($daemonConfig, $exApp->getAppid(), true) === '') {
$this->exAppService->logExAppDataDeleted($exApp);
}
Comment on lines +871 to +873

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Data Integrity & Integration · Heavy lift

Keep failed Kubernetes ExApps and their role list when cleanup fails.

When removeExAppResources() returns an error, the loop skips logExAppDataDeleted(), but the following unregisterExApp() still runs. That call removes the ExApp's deploy options, including k8s_service_roles, and the ExApp row. A partial multi-role failure can leave role resources in the cluster with no record of their roles. unregisterDaemonConfig() then deletes the daemon config and reports success, so the failure is silent.

Keeping the ExApp registered alone does not allow a retry, because the daemon config is also deleted. A safe fix needs these changes:

  • Skip unregisterExApp() for an ExApp whose removal returned an error, so its deploy options stay in place.
  • Return the failure from removeExAppsByDaemonConfigName() instead of void. The controller must not delete the daemon config or report success when a cleanup failed.
  • Decide whether the Docker branches need the same rule, because they also unregister after a failed removal.

}
$this->exAppService->unregisterExApp($exApp->getAppid());
}
Expand Down
5 changes: 2 additions & 3 deletions tests/php/Command/ExApp/UnregisterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
use OCA\AppAPI\DeployActions\KubernetesActions;
use OCA\AppAPI\Service\AppAPIService;
use OCA\AppAPI\Service\DaemonConfigService;
use OCA\AppAPI\Service\ExAppDeployOptionsService;
use OCA\AppAPI\Service\ExAppService;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\MockObject\MockObject;
Expand Down Expand Up @@ -47,7 +46,6 @@ protected function setUp(): void {
$this->dockerActions,
$this->kubernetesActions,
$this->exAppService,
$this->createMock(ExAppDeployOptionsService::class),
));
}

Expand Down Expand Up @@ -118,7 +116,8 @@ public static function kubernetesProvider(): array {
#[DataProvider('kubernetesProvider')]
public function testKubernetesExAppDataDeletionIsLogged(bool $rmData, string $removeError, bool $logged): void {
$exApp = $this->registerExApp('kubernetes-install', true);
$this->kubernetesActions->method('removeExApp')->willReturn($removeError);
$this->kubernetesActions->expects(self::once())->method('removeExAppResources')
->with(self::isInstanceOf(DaemonConfig::class), 'test_app', $rmData)->willReturn($removeError);
$this->exAppService->expects($logged ? self::once() : self::never())->method('logExAppDataDeleted')->with($exApp);

$this->commandTester->execute(['appid' => 'test_app', '--rm-data' => $rmData, '--force' => true, '--silent' => true]);
Expand Down
29 changes: 29 additions & 0 deletions tests/php/Controller/ExAppsPageControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use OCA\AppAPI\Db\DaemonConfig;
use OCA\AppAPI\Db\ExApp;
use OCA\AppAPI\DeployActions\DockerActions;
use OCA\AppAPI\DeployActions\KubernetesActions;
use OCA\AppAPI\Fetcher\ExAppFetcher;
use OCA\AppAPI\Service\AppAPIService;
use OCA\AppAPI\Service\DaemonConfigService;
Expand All @@ -40,6 +41,7 @@ class ExAppsPageControllerTest extends TestCase {
private IConfig&MockObject $config;
private IAppManager&MockObject $appManager;
private DockerActions&MockObject $dockerActions;
private KubernetesActions&MockObject $kubernetesActions;
private AppAPIService&MockObject $service;

protected function setUp(): void {
Expand All @@ -50,6 +52,8 @@ protected function setUp(): void {
$this->service = $this->createMock(AppAPIService::class);
$this->daemonConfigService = $this->createMock(DaemonConfigService::class);
$this->dockerActions = $this->createMock(DockerActions::class);
$this->kubernetesActions = $this->createMock(KubernetesActions::class);
$this->kubernetesActions->method('getAcceptsDeployId')->willReturn('kubernetes-install');
$categoryFetcher = $this->createMock(CategoryFetcher::class);
$this->l10nFactory = $this->createMock(IFactory::class);
$this->exAppFetcher = $this->createMock(ExAppFetcher::class);
Expand All @@ -65,6 +69,7 @@ protected function setUp(): void {
$this->service,
$this->daemonConfigService,
$this->dockerActions,
$this->kubernetesActions,
$categoryFetcher,
$this->l10nFactory,
$this->exAppFetcher,
Expand Down Expand Up @@ -266,6 +271,30 @@ public function testUninstallAppLogsTheDeletedData(bool $isHarp, bool $removeDat
$this->controller->uninstallApp('fake_app', true, $removeData);
}

public static function uninstallKubernetesProvider(): array {
return [
'data removed' => [true, '', true],
'data kept' => [false, '', false],
'removal failed' => [true, 'Failed to remove K8s ExApp', false],
];
}

#[DataProvider('uninstallKubernetesProvider')]
public function testUninstallAppRemovesTheKubernetesResources(bool $removeData, string $removeError, bool $logged): void {
$exApp = new ExApp(['appid' => 'fake_app', 'daemon_config_name' => 'k8s_daemon', 'enabled' => 0]);
$daemonConfig = new DaemonConfig(['name' => 'k8s_daemon', 'accepts_deploy_id' => 'kubernetes-install', 'deploy_config' => ['harp' => ['exapp_direct' => true]]]);
$this->exAppService->method('getExApp')->with('fake_app')->willReturn($exApp);
$this->daemonConfigService->method('getDaemonConfigByName')->willReturn($daemonConfig);
$this->dockerActions->method('getAcceptsDeployId')->willReturn('docker-install');
$this->dockerActions->expects(self::never())->method('removeExApp');
$this->kubernetesActions->expects(self::once())->method('removeExAppResources')
->with($daemonConfig, 'fake_app', $removeData)->willReturn($removeError);
$this->exAppService->expects($logged ? self::once() : self::never())->method('logExAppDataDeleted')->with($exApp);
$this->exAppService->expects(self::once())->method('unregisterExApp')->with('fake_app');

$this->controller->uninstallApp('fake_app', true, $removeData);
}

public function testEnableAppLogsTheInstallationWithoutTheValuesOfTheEnvironmentVariables(): void {
$this->exAppService->method('getExApp')->with('fake_app')->willReturn(null);
$this->exAppService->expects(self::once())->method('logExAppInstallRequested')
Expand Down
67 changes: 67 additions & 0 deletions tests/php/DeployActions/KubernetesActionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use GuzzleHttp\Psr7\Response;
use OCA\AppAPI\Db\DaemonConfig;
use OCA\AppAPI\Db\ExApp;
use OCA\AppAPI\Db\ExAppDeployOption;
use OCA\AppAPI\DeployActions\KubernetesActions;
use OCA\AppAPI\Service\AppAPICommonService;
use OCA\AppAPI\Service\ExAppDeployOptionsService;
Expand Down Expand Up @@ -237,4 +238,70 @@ public function testRemoveExAppRemovesTheDataOfAGoneDeployment(bool $removeData,
self::assertTrue(json_decode((string)$removes[0]['request']->getBody(), true)['remove_data']);
}
}

public static function removeExAppResourcesProvider(): array {
return [
'single deployment' => [null, ['']],
'multi-role ExApp' => [[['name' => 'web'], ['name' => 'worker']], ['web', 'worker']],
];
}

#[DataProvider('removeExAppResourcesProvider')]
public function testRemoveExAppResourcesRemovesEveryDeploymentOfTheExApp(?array $roles, array $roleSuffixes): void {
$exAppDeployOptionsService = $this->createMock(ExAppDeployOptionsService::class);
$exAppDeployOptionsService->method('getDeployOption')->with('test-deploy', 'k8s_service_roles')
->willReturn($roles === null ? null : new ExAppDeployOption(['appid' => 'test-deploy', 'type' => 'k8s_service_roles', 'value' => $roles]));
$kubernetesActions = $this->getMockBuilder(KubernetesActions::class)
->setConstructorArgs([
$this->createMock(LoggerInterface::class),
$this->createMock(IConfig::class),
$this->createMock(ICertificateManager::class),
$this->createMock(IAppManager::class),
$this->createMock(IURLGenerator::class),
$this->createMock(AppAPICommonService::class),
$this->createMock(ExAppService::class),
$this->createMock(ICrypto::class),
$exAppDeployOptionsService,
])
->onlyMethods(['initGuzzleClient', 'removeExApp'])
->getMock();
$removed = [];
$kubernetesActions->expects(self::exactly(count($roleSuffixes)))->method('removeExApp')
->willReturnCallback(static function (string $harpUrl, string $exAppName, bool $removeData, string $roleSuffix = '') use (&$removed): string {
$removed[] = [$exAppName, $removeData, $roleSuffix];
return '';
});
$daemonConfig = new DaemonConfig(['accepts_deploy_id' => KubernetesActions::DEPLOY_ID, 'protocol' => 'http', 'host' => 'harp:8780', 'deploy_config' => []]);

self::assertSame('', $kubernetesActions->removeExAppResources($daemonConfig, 'test-deploy', removeData: true));
self::assertSame(array_map(static fn (string $roleSuffix): array => ['test-deploy', true, $roleSuffix], $roleSuffixes), $removed);
}

public function testRemoveAllRolesRemovesTheOtherRolesAfterAFailure(): void {
$kubernetesActions = $this->getMockBuilder(KubernetesActions::class)
->setConstructorArgs([
$this->createMock(LoggerInterface::class),
$this->createMock(IConfig::class),
$this->createMock(ICertificateManager::class),
$this->createMock(IAppManager::class),
$this->createMock(IURLGenerator::class),
$this->createMock(AppAPICommonService::class),
$this->createMock(ExAppService::class),
$this->createMock(ICrypto::class),
$this->createMock(ExAppDeployOptionsService::class),
])
->onlyMethods(['removeExApp'])
->getMock();
$removed = [];
$kubernetesActions->method('removeExApp')
->willReturnCallback(static function (string $harpUrl, string $exAppName, bool $removeData, string $roleSuffix = '') use (&$removed): string {
$removed[] = $roleSuffix;
return $roleSuffix === 'worker' ? '' : sprintf('Failed to remove role %s', $roleSuffix);
});

$error = $kubernetesActions->removeAllRoles('http://harp:8780/exapps/app_api/k8s', 'test-deploy', [['name' => 'api'], ['name' => 'worker'], ['name' => 'cron']]);

self::assertSame('Failed to remove role api', $error);
self::assertSame(['api', 'worker', 'cron'], $removed);
}
}
14 changes: 14 additions & 0 deletions tests/php/Service/AppAPIServiceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,20 @@ public function testRemoveExAppsByDaemonConfigNameLogsTheDeletedData(bool $isHar
$this->service->removeExAppsByDaemonConfigName($daemonConfig);
}

public function testRemoveExAppsByDaemonConfigNameRemovesTheKubernetesResources(): void {
$exApp = $this->createExApp();
$exApp->setAcceptsDeployId('kubernetes-install');
$daemonConfig = new DaemonConfig(['name' => 'test_daemon', 'accepts_deploy_id' => 'kubernetes-install', 'deploy_config' => ['harp' => ['exapp_direct' => true]]]);
$this->setupReachableManualExApp($exApp, '{}');
$this->exAppService->method('getExAppsByDaemonName')->with('test_daemon')->willReturn([$exApp]);
$this->exAppService->method('disableExAppInternal')->willReturn(true);
$this->kubernetesActions->expects(self::once())->method('removeExAppResources')->with($daemonConfig, 'test_app', true)->willReturn('');
$this->exAppService->expects(self::once())->method('logExAppDataDeleted')->with($exApp);
$this->exAppService->expects(self::once())->method('unregisterExApp')->with('test_app');

$this->service->removeExAppsByDaemonConfigName($daemonConfig);
}

private function createRequestForUser(string $appId, string $userId, string $secret): MockObject&\OCP\IRequest {
$request = $this->createMock(\OCP\IRequest::class);
$request->method('getRemoteAddress')->willReturn('127.0.0.1');
Expand Down
6 changes: 0 additions & 6 deletions tests/psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,6 @@
<code><![CDATA[$output]]></code>
</NullableReturnStatement>
</file>
<file src="lib/Command/ExApp/Unregister.php">
<RedundantCondition>
<code><![CDATA[!empty($roles) && is_array($roles)]]></code>
<code><![CDATA[is_array($roles)]]></code>
</RedundantCondition>
</file>
<file src="lib/Service/ExAppService.php">
<UndefinedClass>
<code><![CDATA[\OC\Memcache\APCu]]></code>
Expand Down
Loading