Skip to content

Commit

Permalink
TASK: Inject logger instead of retrieving it by deployment
Browse files Browse the repository at this point in the history
  • Loading branch information
sabbelasichon committed Feb 22, 2023
1 parent ba4c9c2 commit e95b76a
Show file tree
Hide file tree
Showing 28 changed files with 110 additions and 64 deletions.
8 changes: 8 additions & 0 deletions src/Cli/Symfony/ConsoleKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace TYPO3\Surf\Cli\Symfony;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand Down Expand Up @@ -57,6 +59,12 @@ protected function build(ContainerBuilder $container): void
'setShellCommandService',
[new Reference(ShellCommandService::class)]
);
$container->registerForAutoconfiguration(
LoggerAwareInterface::class
)->addMethodCall(
'setLogger',
[new Reference(LoggerInterface::class)]
);
}

public function getCacheDir(): string
Expand Down
5 changes: 0 additions & 5 deletions src/Domain/Model/Deployment.php
Original file line number Diff line number Diff line change
Expand Up @@ -292,11 +292,6 @@ public function setLogger(LoggerInterface $logger): self
return $this;
}

public function getLogger(): LoggerInterface
{
return $this->logger;
}

/**
* Get the deployment release identifier
*
Expand Down
6 changes: 3 additions & 3 deletions src/Domain/Model/RollbackWorkflow.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ public function run(Deployment $deployment): void
$this->configureRollbackTasks($deployment);

foreach ($this->stages as $stage) {
$deployment->getLogger()->notice('Stage ' . $stage);
$this->logger->notice('Stage ' . $stage);
foreach ($nodes as $node) {
$deployment->getLogger()->debug('Node ' . $node->getName());
$this->logger->debug('Node ' . $node->getName());
foreach ($applications as $application) {
if (! $application->hasNode($node)) {
continue;
}

$deployment->getLogger()->debug('Application ' . $application->getName());
$this->logger->debug('Application ' . $application->getName());

try {
$this->executeStage($stage, $node, $application, $deployment);
Expand Down
14 changes: 7 additions & 7 deletions src/Domain/Model/SimpleWorkflow.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,21 @@ public function run(Deployment $deployment): void
}

foreach ($this->stages as $stage) {
$deployment->getLogger()->notice('Stage ' . $stage);
$this->logger->notice('Stage ' . $stage);
foreach ($nodes as $node) {
$deployment->getLogger()->debug('Node ' . $node->getName());
$this->logger->debug('Node ' . $node->getName());
foreach ($applications as $application) {
if (! $application->hasNode($node)) {
continue;
}

$deployment->getLogger()->debug('Application ' . $application->getName());
$this->logger->debug('Application ' . $application->getName());

try {
$this->executeStage($stage, $node, $application, $deployment);
} catch (DeploymentLockedException $exception) {
$deployment->setStatus(DeploymentStatus::CANCELLED());
$deployment->getLogger()->info($exception->getMessage());
$this->logger->info($exception->getMessage());
if ($this->enableRollback) {
$this->taskManager->rollback();
}
Expand All @@ -81,14 +81,14 @@ public function run(Deployment $deployment): void
$deployment->setStatus(DeploymentStatus::FAILED());
if ($this->enableRollback) {
if (array_search($stage, $this->stages, false) <= array_search(SimpleWorkflowStage::STEP_09_SWITCH, $this->stages, false)) {
$deployment->getLogger()->error('Got exception "' . $exception->getMessage() . '" rolling back.');
$this->logger->error('Got exception "' . $exception->getMessage() . '" rolling back.');
$this->taskManager->rollback();
} else {
$deployment->getLogger()->error('Got exception "' . $exception->getMessage() . '" but after switch stage, no rollback necessary.');
$this->logger->error('Got exception "' . $exception->getMessage() . '" but after switch stage, no rollback necessary.');
$this->taskManager->reset();
}
} else {
$deployment->getLogger()->error('Got exception "' . $exception->getMessage() . '" but rollback disabled. Stopping.');
$this->logger->error('Got exception "' . $exception->getMessage() . '" but rollback disabled. Stopping.');
}

return;
Expand Down
12 changes: 11 additions & 1 deletion src/Domain/Model/Task.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

namespace TYPO3\Surf\Domain\Model;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Symfony\Component\OptionsResolver\Exception\ExceptionInterface;
use Symfony\Component\OptionsResolver\Exception\InvalidOptionsException;
use Symfony\Component\OptionsResolver\Exception\MissingOptionsException;
Expand All @@ -21,8 +24,15 @@
use Symfony\Component\OptionsResolver\OptionsResolver;
use TYPO3\Surf\Exception\InvalidConfigurationException;

abstract class Task
abstract class Task implements LoggerAwareInterface
{
use LoggerAwareTrait;

/**
* @var LoggerInterface
*/
protected $logger;

/**
* @return mixed|void
*/
Expand Down
19 changes: 14 additions & 5 deletions src/Domain/Model/Workflow.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,24 @@

namespace TYPO3\Surf\Domain\Model;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use TYPO3\Surf\Domain\Service\TaskManager;
use TYPO3\Surf\Exception as SurfException;
use TYPO3\Surf\Exception\TaskExecutionException;

/**
* A Workflow
*/
abstract class Workflow
abstract class Workflow implements LoggerAwareInterface
{
use LoggerAwareTrait;

/**
* @var LoggerInterface
*/
protected $logger;
protected TaskManager $taskManager;

protected array $tasks = [];
Expand All @@ -34,7 +43,7 @@ public function run(Deployment $deployment): void
if (!$deployment->isInitialized()) {
throw new SurfException('Deployment must be initialized before running it', 1335976529);
}
$deployment->getLogger()->debug('Using workflow "' . $this->getName() . '"');
$this->logger->debug('Using workflow "' . $this->getName() . '"');
}

abstract public function getName(): string;
Expand Down Expand Up @@ -253,7 +262,7 @@ protected function executeStage(string $stage, Node $node, Application $applicat
$label = $applicationName === '_' ? 'for all' : 'for application ' . $applicationName;

if (isset($this->tasks['stage'][$applicationName][$stage][$stageStep])) {
$deployment->getLogger()->debug('Executing stage "' . $stage . '" (step "' . $stageStep . '") on "' . $node->getName() . '" ' . $label);
$this->logger->debug('Executing stage "' . $stage . '" (step "' . $stageStep . '") on "' . $node->getName() . '" ' . $label);
foreach ($this->tasks['stage'][$applicationName][$stage][$stageStep] as $task) {
$this->executeTask($task, $node, $application, $deployment, $stage);
}
Expand All @@ -272,7 +281,7 @@ protected function executeTask(string $task, Node $node, Application $applicatio
foreach (['_', $application->getName()] as $applicationName) {
if (isset($this->tasks['before'][$applicationName][$task])) {
foreach ($this->tasks['before'][$applicationName][$task] as $beforeTask) {
$deployment->getLogger()->debug('Task "' . $beforeTask . '" before "' . $task);
$this->logger->debug('Task "' . $beforeTask . '" before "' . $task);
$this->executeTask($beforeTask, $node, $application, $deployment, $stage, $callstack);
}
}
Expand All @@ -290,7 +299,7 @@ protected function executeTask(string $task, Node $node, Application $applicatio
$label = $applicationName === '_' ? 'for all' : 'for application ' . $applicationName;
if (isset($this->tasks['after'][$applicationName][$task])) {
foreach ($this->tasks['after'][$applicationName][$task] as $beforeTask) {
$deployment->getLogger()->debug('Task "' . $beforeTask . '" after "' . $task . '" ' . $label);
$this->logger->debug('Task "' . $beforeTask . '" after "' . $task . '" ' . $label);
$this->executeTask($beforeTask, $node, $application, $deployment, $stage, $callstack);
}
}
Expand Down
28 changes: 19 additions & 9 deletions src/Domain/Service/ShellCommandService.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@

namespace TYPO3\Surf\Domain\Service;

use Monolog\Logger;
use Phar;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Symfony\Component\Process\Process;
use TYPO3\Flow\Utility\Files;
use TYPO3\Surf\Domain\Model\Deployment;
Expand All @@ -21,8 +24,15 @@
/**
* A shell command service
*/
class ShellCommandService
class ShellCommandService implements LoggerAwareInterface
{
/**
* @var Logger
*/
protected $logger;

use LoggerAwareTrait;

/**
* Execute a shell command (locally or remote depending on the node hostname)
*
Expand All @@ -39,7 +49,7 @@ public function execute($command, Node $node, Deployment $deployment, bool $igno
[$exitCode, $returnedOutput] = $this->executeRemoteCommand($command, $node, $deployment, $logOutput);
}
if (!$ignoreErrors && $exitCode !== 0) {
$deployment->getLogger()->warning(rtrim($returnedOutput));
$this->logger->warning(rtrim($returnedOutput));
throw new TaskExecutionException('Command returned non-zero return code: ' . $exitCode, 1311007746);
}
return $exitCode === 0 ? $returnedOutput : false;
Expand All @@ -54,10 +64,10 @@ public function simulate($command, Node $node, Deployment $deployment): bool
{
if ($node->isLocalhost()) {
$command = $this->prepareCommand($command);
$deployment->getLogger()->debug('... (localhost): "' . $command . '"');
$this->logger->debug('... (localhost): "' . $command . '"');
} else {
$command = $this->prepareCommand($command);
$deployment->getLogger()->debug('... $' . $node->getName() . ': "' . $command . '"');
$this->logger->debug('... $' . $node->getName() . ': "' . $command . '"');
}
return true;
}
Expand Down Expand Up @@ -87,7 +97,7 @@ public function executeOrSimulate($command, Node $node, Deployment $deployment,
protected function executeLocalCommand($command, Deployment $deployment, bool $logOutput = true): array
{
$command = $this->prepareCommand($command);
$deployment->getLogger()->debug('(localhost): "' . $command . '"');
$this->logger->debug('(localhost): "' . $command . '"');

return $this->executeProcess($deployment, $command, $logOutput, '> ');
}
Expand All @@ -102,7 +112,7 @@ protected function executeLocalCommand($command, Deployment $deployment, bool $l
protected function executeRemoteCommand($command, Node $node, Deployment $deployment, bool $logOutput = true)
{
$command = $this->prepareCommand($command);
$deployment->getLogger()->debug('$' . $node->getName() . ': "' . $command . '"');
$this->logger->debug('$' . $node->getName() . ': "' . $command . '"');

if ($node->hasOption('remoteCommandExecutionHandler')) {
$remoteCommandExecutionHandler = $node->getOption('remoteCommandExecutionHandler');
Expand Down Expand Up @@ -162,11 +172,11 @@ public function executeProcess(Deployment $deployment, string $command, bool $lo
$process->setTimeout(null);
$callback = null;
if ($logOutput) {
$callback = static function ($type, $data) use ($deployment, $logPrefix): void {
$callback = function ($type, $data) use ($logPrefix): void {
if ($type === Process::OUT) {
$deployment->getLogger()->debug($logPrefix . trim($data));
$this->logger->debug($logPrefix . trim($data));
} elseif ($type === Process::ERR) {
$deployment->getLogger()->error($logPrefix . trim($data));
$this->logger->error($logPrefix . trim($data));
}
};
}
Expand Down
16 changes: 13 additions & 3 deletions src/Domain/Service/TaskManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

namespace TYPO3\Surf\Domain\Service;

use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use TYPO3\Surf\Domain\Model\Application;
use TYPO3\Surf\Domain\Model\Deployment;
use TYPO3\Surf\Domain\Model\Node;
Expand All @@ -19,8 +22,15 @@
/**
* @final
*/
class TaskManager
class TaskManager implements LoggerAwareInterface
{
use LoggerAwareTrait;

/**
* @var LoggerInterface
*/
protected $logger;

/**
* @var TaskInHistory[]
*/
Expand All @@ -36,7 +46,7 @@ public function __construct(TaskFactory $taskFactory)
public function execute(string $taskName, Node $node, Application $application, Deployment $deployment, string $stage, array $options = [], string $definedTaskName = ''): void
{
$definedTaskName = $definedTaskName ?: $taskName;
$deployment->getLogger()->info($node->getName() . ' (' . $application->getName() . ') ' . $definedTaskName);
$this->logger->info($node->getName() . ' (' . $application->getName() . ') ' . $definedTaskName);

$task = $this->taskFactory->createTaskInstance($taskName);

Expand All @@ -57,7 +67,7 @@ public function execute(string $taskName, Node $node, Application $application,
public function rollback(): void
{
foreach (array_reverse($this->taskHistory) as $historicTask) {
$historicTask->deployment()->getLogger()->info('Rolling back ' . get_class($historicTask->task()));
$this->logger->info('Rolling back ' . get_class($historicTask->task()));
if (!$historicTask->deployment()->isDryRun()) {
$historicTask->task()->rollback($historicTask->node(), $historicTask->application(), $historicTask->deployment(), $historicTask->options());
}
Expand Down
6 changes: 3 additions & 3 deletions src/Task/CleanupReleasesTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function __construct(ClockInterface $clock)
public function execute(Node $node, Application $application, Deployment $deployment, array $options = []): void
{
if (! isset($options['keepReleases']) && ! isset($options['onlyRemoveReleasesOlderThan'])) {
$deployment->getLogger()->debug(($deployment->isDryRun() ? 'Would keep' : 'Keeping') . ' all releases for "' . $application->getName() . '"');
$this->logger->debug(($deployment->isDryRun() ? 'Would keep' : 'Keeping') . ' all releases for "' . $application->getName() . '"');

return;
}
Expand All @@ -80,10 +80,10 @@ public function execute(Node $node, Application $application, Deployment $deploy
$removeCommand .= "rm -rf {$releasesPath}/{$removeRelease};rm -f {$releasesPath}/{$removeRelease}REVISION;";
}
if (count($removeReleases) > 0) {
$deployment->getLogger()->info(($deployment->isDryRun() ? 'Would remove' : 'Removing') . ' releases ' . implode(', ', $removeReleases));
$this->logger->info(($deployment->isDryRun() ? 'Would remove' : 'Removing') . ' releases ' . implode(', ', $removeReleases));
$this->shell->executeOrSimulate($removeCommand, $node, $deployment);
} else {
$deployment->getLogger()->info('No releases to remove');
$this->logger->info('No releases to remove');
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Task/Composer/AbstractComposerTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ private function composerManifestExists(string $path, Node $node, Deployment $de
$composerJsonPath = Files::concatenatePaths([$path, 'composer.json']);
$composerJsonExists = $this->shell->executeOrSimulate('test -f ' . escapeshellarg($composerJsonPath), $node, $deployment, true);
if ($composerJsonExists === false) {
$deployment->getLogger()->debug('No composer.json found in path "' . $composerJsonPath . '"');
$this->logger->debug('No composer.json found in path "' . $composerJsonPath . '"');

return false;
}
Expand Down
14 changes: 7 additions & 7 deletions src/Task/Generic/RollbackTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,31 +41,31 @@ public function execute(Node $node, Application $application, Deployment $deploy
$currentReleaseIdentifier = findCurrentReleaseIdentifier($deployment, $node, $application, $this->shell);

// Symlink to old release.
$deployment->getLogger()->info(($deployment->isDryRun() ? 'Would symlink current to' : 'Symlink current to') . ' release ' . $previousReleaseIdentifier);
$this->logger->info(($deployment->isDryRun() ? 'Would symlink current to' : 'Symlink current to') . ' release ' . $previousReleaseIdentifier);
$symlinkCommand = sprintf('cd %1$s && ln -sfn ./%2$s current', $releasesPath, $previousReleaseIdentifier);
$deployment->getLogger()->info($symlinkCommand);
$this->logger->info($symlinkCommand);
$this->shell->executeOrSimulate($symlinkCommand, $node, $deployment);

// Remove current release
$deployment->getLogger()->info(($deployment->isDryRun() ? 'Would remove' : 'Removing') . ' old current release ' . $currentReleaseIdentifier);
$this->logger->info(($deployment->isDryRun() ? 'Would remove' : 'Removing') . ' old current release ' . $currentReleaseIdentifier);
$removeCommand = sprintf('rm -rf %1$s/%2$s; rm -rf %1$s/%2$sREVISION;', $releasesPath, $currentReleaseIdentifier);
$this->shell->executeOrSimulate($removeCommand, $node, $deployment);

if ($numberOfReleases > 2) {
[$penultimateRelease] = array_slice($releases, -3, 1);
// Symlink previous to penultimate release
$deployment->getLogger()->info(($deployment->isDryRun() ? 'Would symlink previous to' : 'Symlink previous to') . ' release ' . $penultimateRelease);
$this->logger->info(($deployment->isDryRun() ? 'Would symlink previous to' : 'Symlink previous to') . ' release ' . $penultimateRelease);
$symlinkCommand = sprintf('cd %1$s && ln -sfn ./%2$s previous', $releasesPath, $penultimateRelease);
$deployment->getLogger()->info($symlinkCommand);
$this->logger->info($symlinkCommand);
$this->shell->executeOrSimulate($symlinkCommand, $node, $deployment);
} else {
// Remove previous symlink
$removeCommand = sprintf('rm -rf %1$s/previous', $node->getReleasesPath());
$deployment->getLogger()->info(($deployment->isDryRun() ? 'Would remove' : 'Removing') . ' previous symlink: ' . $removeCommand);
$this->logger->info(($deployment->isDryRun() ? 'Would remove' : 'Removing') . ' previous symlink: ' . $removeCommand);
$this->shell->executeOrSimulate($removeCommand, $node, $deployment);
}
} else {
$deployment->getLogger()->notice('No more releases you can revert to.');
$this->logger->notice('No more releases you can revert to.');
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/Task/LockDeploymentTask.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function execute(Node $node, Application $application, Deployment $deploy
if (! $deployment->isDryRun()) {
$this->shell->execute(sprintf('echo %s > %s', escapeshellarg($deployment->getDeploymentLockIdentifier()), $deploymentLockFile), $node, $deployment);
} else {
$deployment->getLogger()->info(sprintf('Create lock file %s with identifier %s', $deploymentLockFile, $deployment->getDeploymentLockIdentifier()));
$this->logger->info(sprintf('Create lock file %s with identifier %s', $deploymentLockFile, $deployment->getDeploymentLockIdentifier()));
}
}

Expand Down

0 comments on commit e95b76a

Please sign in to comment.