Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DeployActions code fixes #46

Merged
merged 4 commits into from
Aug 21, 2023
Merged
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
18 changes: 6 additions & 12 deletions lib/Command/ExApp/Deploy.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,25 +93,19 @@ protected function execute(InputInterface $input, OutputInterface $output): int
return 1;
}

// TODO: Remove resultOutput
$resultOutput = [
'appid' => $appId,
'name' => (string) $infoXml->name,
'daemon_config_name' => $daemonConfigName,
'version' => (string) $infoXml->version,
'secret' => explode('=', $deployParams['container_params']['env'][1])[1],
$exAppUrlParams = [
'protocol' => (string) ($infoXml->xpath('ex-app/protocol')[0] ?? 'http'),
'host' => $this->dockerActions->resolveDeployExAppHost($appId, $daemonConfig),
'port' => explode('=', $deployParams['container_params']['env'][7])[1],
'protocol' => (string) ($infoXml->xpath('ex-app/protocol')[0] ?? 'http'),
'system_app' => (bool) ($infoXml->xpath('ex-app/system')[0] ?? false),
];

if ($this->service->heartbeatExApp($resultOutput)) {
$output->writeln(json_encode($resultOutput, JSON_UNESCAPED_SLASHES));
if (!$this->service->heartbeatExApp($exAppUrlParams)) {
$output->writeln(sprintf('ExApp %s heartbeat check failed. Make sure container started and initialized correctly.', $appId));
return 0;
}

$output->writeln(sprintf('ExApp %s heartbeat check failed. Make sure container started and initialized correctly.', $appId));
$output->writeln(sprintf('ExApp %s deployed successfully', $appId));
return 0;
} else {
$output->writeln(sprintf('ExApp %s deployment failed. Error: %s', $appId, $startResult['error'] ?? $createResult['error']));
}
Expand Down
42 changes: 40 additions & 2 deletions lib/Command/ExApp/Unregister.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

namespace OCA\AppEcosystemV2\Command\ExApp;

use OCA\AppEcosystemV2\DeployActions\DockerActions;
use OCA\AppEcosystemV2\Service\AppEcosystemV2Service;

use OCA\AppEcosystemV2\Service\DaemonConfigService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
Expand All @@ -14,11 +16,19 @@

class Unregister extends Command {
private AppEcosystemV2Service $service;

public function __construct(AppEcosystemV2Service $service) {
private DockerActions $dockerActions;
private DaemonConfigService $daemonConfigService;

public function __construct(
AppEcosystemV2Service $service,
DaemonConfigService $daemonConfigService,
DockerActions $dockerActions,
) {
parent::__construct();

$this->service = $service;
$this->daemonConfigService = $daemonConfigService;
$this->dockerActions = $dockerActions;
}

protected function configure() {
Expand All @@ -28,9 +38,12 @@ protected function configure() {
$this->addArgument('appid', InputArgument::REQUIRED);

$this->addOption('silent', null, InputOption::VALUE_NONE, 'Unregister only from Nextcloud. Do not send request to external app.');
$this->addOption('rm-container', null, InputOption::VALUE_NONE, 'Remove ExApp container');
$this->addOption('rm-data', null, InputOption::VALUE_NONE, 'Remove ExApp data (volume)');

$this->addUsage('test_app');
$this->addUsage('test_app --silent');
$this->addUsage('test_app --rm');
}

protected function execute(InputInterface $input, OutputInterface $output): int {
Expand Down Expand Up @@ -59,6 +72,31 @@ protected function execute(InputInterface $input, OutputInterface $output): int
return 1;
}

$rmContainer = $input->getOption('rm-container');
if ($rmContainer) {
$daemonConfig = $this->daemonConfigService->getDaemonConfigByName($exApp->getDaemonConfigName());
if ($daemonConfig === null) {
$output->writeln(sprintf('Failed to get ExApp %s DaemonConfig by name %s', $appId, $exApp->getDaemonConfigName()));
return 1;
}
if ($daemonConfig->getAcceptsDeployId() === $this->dockerActions->getAcceptsDeployId()) {
$this->dockerActions->initGuzzleClient($daemonConfig);
[$stopResult, $removeResult] = $this->dockerActions->removePrevExAppContainer($this->dockerActions->buildDockerUrl($daemonConfig), $appId);
if (isset($stopResult['error']) || isset($removeResult['error'])) {
$output->writeln(sprintf('Failed to remove ExApp %s container', $appId));
} else {
$rmData = $input->getOption('rm-data');
if ($rmData) {
$removeVolumeResult = $this->dockerActions->removeVolume($this->dockerActions->buildDockerUrl($daemonConfig), $appId . '_data');
if (isset($removeVolumeResult['error'])) {
$output->writeln(sprintf('Failed to remove ExApp %s volume %s', $appId, $appId . '_data'));
}
}
$output->writeln(sprintf('ExApp %s container successfully removed', $appId));
}
}
}

$output->writeln(sprintf('ExApp %s successfully unregistered.', $appId));
return 0;
}
Expand Down
22 changes: 16 additions & 6 deletions lib/Command/ExApp/Update.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,20 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$output->writeln(sprintf('ExApp %s not found.', $appId));
return 1;
}
if (!$exApp->getEnabled()) {
$output->writeln(sprintf('ExApp %s already disabled.', $appId));
return 1;
}

$newVersion = (string) $infoXml->version;
if ($exApp->getVersion() === $newVersion) {
$output->writeln(sprintf('ExApp %s already on %s version', $appId, $newVersion));
$output->writeln(sprintf('ExApp %s already updated (%s)', $appId, $newVersion));
return 2;
}

if ($exApp->getEnabled()) {
if (!$this->service->disableExApp($exApp)) {
$output->writeln(sprintf('Failed to disable ExApp %s.', $appId));
return 1;
} else {
$output->writeln(sprintf('ExApp %s disabled.', $appId));
}
}

$daemonConfig = $this->daemonConfigService->getDaemonConfigByName($exApp->getDaemonConfigName());
Expand Down Expand Up @@ -117,6 +123,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int

$this->dockerActions->initGuzzleClient($daemonConfig); // Required init
$containerInfo = $this->dockerActions->inspectContainer($this->dockerActions->buildDockerUrl($daemonConfig), $appId);
if (isset($containerInfo['error'])) {
$output->writeln(sprintf('Failed to inspect old ExApp %s container. Error: %s', $appId, $containerInfo['error']));
return 1;
}
$deployParams = $this->dockerActions->buildDeployParams($daemonConfig, $infoXml, [
'container_info' => $containerInfo,
]);
Expand Down Expand Up @@ -196,7 +206,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
}

if (!$confirmRequiredScopes && count($newExAppScopes['required']) > 0) {
if (!$confirmRequiredScopes && count($requiredScopes) > 0) {
$output->writeln(sprintf('ExApp %s required scopes not approved. Failed to finish ExApp update.', $appId));
return 1;
}
Expand Down
4 changes: 2 additions & 2 deletions lib/Db/ExAppMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,9 @@ public function updateExAppVersion(ExApp $exApp): int {
public function updateExAppName(ExApp $exApp): int {
$qb = $this->db->getQueryBuilder();
return $qb->update($this->tableName)
->set('name', $qb->createNamedParameter($exApp->getVersion(), IQueryBuilder::PARAM_STR))
->set('name', $qb->createNamedParameter($exApp->getName(), IQueryBuilder::PARAM_STR))
->where(
$qb->expr()->eq('name', $qb->createNamedParameter($exApp->getName()))
$qb->expr()->eq('appid', $qb->createNamedParameter($exApp->getAppid()))
)->executeStatement();
}
}
45 changes: 38 additions & 7 deletions lib/DeployActions/DockerActions.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public function buildImageName(array $imageParams): string {
}

public function createContainer(string $dockerUrl, array $imageParams, array $params = []): array {
$createVolumeResult = $this->createVolume($dockerUrl, $params['hostname']);
$createVolumeResult = $this->createVolume($dockerUrl, $params['name'] . '_data');
if (isset($createVolumeResult['error'])) {
return $createVolumeResult;
}
Expand Down Expand Up @@ -227,17 +227,17 @@ public function inspectContainer(string $dockerUrl, string $containerId): array
$response = $this->guzzleClient->get($url);
return json_decode((string) $response->getBody(), true);
} catch (GuzzleException $e) {
$this->logger->error('Failed to inspect container', ['exception' => $e]);
error_log($e->getMessage());
return ['error' => 'Failed to inspect container'];
//$this->logger->error('Failed to inspect container', ['exception' => $e]);
//error_log($e->getMessage());
return ['error' => $e->getMessage(), 'exception' => $e];
}
}

public function createVolume(string $dockerUrl, string $volume): array {
$url = $this->buildApiUrl($dockerUrl, 'volumes/create');
try {
$options['json'] = [
'name' => $volume . '_data',
'name' => $volume,
];
$response = $this->guzzleClient->post($url, $options);
$result = json_decode((string) $response->getBody(), true);
Expand All @@ -255,6 +255,35 @@ public function createVolume(string $dockerUrl, string $volume): array {
return ['error' => 'Failed to create volume'];
}

public function removeVolume(string $dockerUrl, string $volume): array {
$url = $this->buildApiUrl($dockerUrl, sprintf('volumes/%s', $volume));
try {
$options['json'] = [
'name' => $volume,
];
$response = $this->guzzleClient->delete($url, $options);
if ($response->getStatusCode() === 204) {
return ['success' => true];
}
if ($response->getStatusCode() === 404) {
error_log('Volume not found.');
return ['error' => 'Volume not found.'];
}
if ($response->getStatusCode() === 409) {
error_log('Volume is in use.');
return ['error' => 'Volume is in use.'];
}
if ($response->getStatusCode() === 500) {
error_log('Something went wrong.');
return ['error' => 'Something went wrong.'];
}
} catch (GuzzleException $e) {
$this->logger->error('Failed to create volume', ['exception' => $e]);
error_log($e->getMessage());
}
return ['error' => 'Failed to remove volume'];
}

/**
* @param DaemonConfig $daemonConfig
* @param array $params Deploy params (image_params, container_params)
Expand Down Expand Up @@ -286,7 +315,7 @@ public function updateExApp(DaemonConfig $daemonConfig, array $params = []): arr
return [$pullResult, $stopResult, $removeResult, $createResult, $startResult];
}

private function removePrevExAppContainer(string $dockerUrl, string $containerId): array {
public function removePrevExAppContainer(string $dockerUrl, string $containerId): array {
$stopResult = $this->stopContainer($dockerUrl, $containerId);
if (isset($stopResult['error'])) {
return [$stopResult, null];
Expand All @@ -305,6 +334,7 @@ public function buildDeployParams(DaemonConfig $daemonConfig, \SimpleXMLElement
$containerInfo = $params['container_info'];
$oldEnvs = $this->extractDeployEnvs((array) $containerInfo['Config']['Env']);
$port = $oldEnvs['APP_PORT'] ?? $this->service->getExAppRandomPort();
$secret = $oldEnvs['APP_SECRET'];
// Preserve previous devices or use from params (if any)
$devices = array_map(function (array $device) {
return $device['PathOnHost'];
Expand All @@ -328,6 +358,7 @@ public function buildDeployParams(DaemonConfig $daemonConfig, \SimpleXMLElement
'host' => $this->service->buildExAppHost($deployConfig),
'port' => $port,
'system_app' => (bool) ($infoXml->xpath('ex-app/system')[0] ?? false),
'secret' => $secret ?? $this->random->generate(128),
], $params['env_options'] ?? [], $deployConfig);

$containerParams = [
Expand Down Expand Up @@ -359,7 +390,7 @@ private function extractDeployEnvs(array $envs): array {
public function buildDeployEnvs(array $params, array $envOptions, array $deployConfig): array {
$autoEnvs = [
sprintf('AE_VERSION=%s', $this->appManager->getAppVersion(Application::APP_ID, false)),
sprintf('APP_SECRET=%s', $this->random->generate(128)),
sprintf('APP_SECRET=%s', $params['secret']),
sprintf('APP_ID=%s', $params['appid']),
sprintf('APP_DISPLAY_NAME=%s', $params['name']),
sprintf('APP_VERSION=%s', $params['version']),
Expand Down
9 changes: 5 additions & 4 deletions lib/Service/AppEcosystemV2Service.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ public function unregisterExApp(string $appId): ?ExApp {
$this->exAppScopesService->removeExAppScopes($exApp);
$this->exAppUsersService->removeExAppUsers($exApp);
$this->cache->remove('/exApp_' . $appId);
// TODO: Do we need to remove ExApp container
return $exApp;
} catch (Exception $e) {
$this->logger->error(sprintf('Error while unregistering ExApp: %s', $e->getMessage()), ['exception' => $e]);
Expand Down Expand Up @@ -348,13 +349,13 @@ public function getExAppRequestedScopes(ExApp $exApp, ?\SimpleXMLElement $infoXm
$scopes = (array) $scopes[0];
$required = array_map(function (string $scopeGroup) {
return intval($scopeGroup);
}, (array) $scopes['required']);
}, (array) $scopes['required']->value);
$optional = array_map(function (string $scopeGroup) {
return intval($scopeGroup);
}, (array) $scopes['optional']);
}, (array) $scopes['optional']->value);
return [
'required' => $required,
'optional' => $optional,
'required' => array_values($required),
'optional' => array_values($optional),
];
}
} elseif (isset($jsonInfo['scopes'])) {
Expand Down
4 changes: 3 additions & 1 deletion lib/Service/ExAppScopesService.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,9 @@ public function removeExAppScope(ExApp $exApp, int $apiScope): bool {
* @return bool
*/
public function updateExAppScopes(ExApp $exApp, array $newExAppScopes): bool {
$currentExAppScopes = $this->getExAppScopes($exApp);
$currentExAppScopes = array_map(function (ExAppScope $exAppScope) {
return $exAppScope->getScopeGroup();
}, $this->getExAppScopes($exApp));
$newScopes = array_values(array_diff($newExAppScopes, $currentExAppScopes));
$removedScopes = array_values(array_diff($currentExAppScopes, $newExAppScopes));

Expand Down