Skip to content

Commit

Permalink
feat(exit-code): configure exit code on warning
Browse files Browse the repository at this point in the history
  • Loading branch information
tuxes3 committed Jul 4, 2023
1 parent 034110f commit 3d9a88f
Show file tree
Hide file tree
Showing 26 changed files with 150 additions and 61 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
matrix:
operating-system: [ ubuntu-latest ]
php: [ '8.1', '8.2' ]
symfony: ['5.3.*', '5.4.*', '6.0.*', '6.1.*', '6.2.*']
symfony: ['6.3.*']

steps:
- uses: actions/checkout@master
Expand Down
14 changes: 7 additions & 7 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,23 @@
],
"require": {
"php": ">=8.1",
"symfony/framework-bundle": "^5.3|^6.0",
"symfony/serializer": "^5.3|^6.0"
"symfony/framework-bundle": "^6.3",
"symfony/serializer": "^6.3"
},
"require-dev": {
"nyholm/symfony-bundle-test": "^2.0",
"zenstruck/console-test": "^v1.1.0",
"whatwedo/php-coding-standard": "^1.0",
"phpstan/phpstan": "^1.7",
"phpunit/phpunit": "^9.5",
"symfony/browser-kit": "^5.3|^6.0",
"symfony/css-selector": "^5.3|^6.0",
"symfony/phpunit-bridge": "^6.2",
"symfony/browser-kit": "^6.3",
"symfony/css-selector": "^6.3",
"symfony/phpunit-bridge": "^6.3",
"doctrine/doctrine-bundle": "^2.7",
"doctrine/doctrine-migrations-bundle": "^3.2",
"doctrine/orm": "^2.14",
"symfony/twig-bundle": "^5.3|^6.0",
"symfony/messenger": "^5.3|^6.0",
"symfony/twig-bundle": "^6.3",
"symfony/messenger": "^6.3",
"symfony/mercure-bundle": "^0.3"
},
"autoload": {
Expand Down
2 changes: 1 addition & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ parameters:
- src
- tests
bootstrapFiles:
- vendor/bin/.phpunit/phpunit-9.5-0/vendor/autoload.php
- vendor/bin/.phpunit/phpunit-9.6-0/vendor/autoload.php
8 changes: 7 additions & 1 deletion src/Command/CheckCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
class CheckCommand extends Command
{
public function __construct(
protected int $warningExitCode,
protected MonitoringManager $monitoringManager
) {
parent::__construct();
Expand All @@ -30,7 +31,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$io = new SymfonyStyle($input, $output);
$this->printResult($io, $this->monitoringManager->getResult());

return $this->monitoringManager->isSuccessful() ? static::SUCCESS : static::FAILURE;
if ($this->monitoringManager->isSuccessful() && $this->monitoringManager->isWarning()) {
return $this->warningExitCode;
} elseif ($this->monitoringManager->isSuccessful()) {
return self::SUCCESS;
}
return self::FAILURE;
}

private function printResult(SymfonyStyle $io, $result, $previousGroup = null, $level = 0): void
Expand Down
4 changes: 2 additions & 2 deletions src/Controller/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public function __construct(

public function __invoke(Request $request, MonitoringManager $monitoringManager, SerializerInterface $serializer): Response
{
if ($this->authToken !== null &&
$request->headers->get('X-Auth-Token', '') !== $this->authToken) {
if ($this->authToken !== null
&& $request->headers->get('X-Auth-Token', '') !== $this->authToken) {
return new Response('Unauthorized', 401);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

class AttributeCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
public function process(ContainerBuilder $container): void
{
$definition = $container->getDefinition(MonitoringManager::class);

Expand Down
4 changes: 4 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ public function getConfigTreeBuilder(): TreeBuilder
->end()
->end()
->end()
->integerNode('warning_exit_code')
->defaultValue(1)
->info('Exit code for warning state (default 1)')
->end()
->end()
;

Expand Down
13 changes: 9 additions & 4 deletions src/DependencyInjection/whatwedoMonitorExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace whatwedo\MonitorBundle\DependencyInjection;

use PHPUnit\Framework\MockObject\Api;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
Expand All @@ -23,12 +22,12 @@
*/
class whatwedoMonitorExtension extends Extension implements PrependExtensionInterface
{
public function load(array $configs, ContainerBuilder $container)
public function load(array $configs, ContainerBuilder $container): void
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yaml');

// tag monitoring attributes (sensors and metrics)
Expand Down Expand Up @@ -68,9 +67,15 @@ public function configureMonitoring(ContainerBuilder $container, array $config)
$container->findDefinition(QueuedMessages::class)
->setArgument(0, $config['monitoring']['metric']['messenger']['queued_messages']['warning_threshold'] ?? 5)
->setArgument(1, $config['monitoring']['metric']['messenger']['queued_messages']['critical_threshold'] ?? 10);
if (!(isset($config['endpoint']['command']['enabled'])
&& ! $config['endpoint']['command']['enabled'])) {
$container->findDefinition(CheckCommand::class)
->setArgument(0, $config['warning_exit_code'] ?? 1)
;
}
}

public function prepend(ContainerBuilder $container)
public function prepend(ContainerBuilder $container): void
{
}
}
37 changes: 32 additions & 5 deletions src/Manager/MonitoringManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
use whatwedo\MonitorBundle\Enum\MetricStateEnum;
use whatwedo\MonitorBundle\Enum\SensorStateEnum;
use whatwedo\MonitorBundle\Monitoring\AttributeInterface;
use whatwedo\MonitorBundle\Monitoring\Metric\AbstractMetric;
use whatwedo\MonitorBundle\Monitoring\Sensor\AbstractSensor;

class MonitoringManager
Expand All @@ -19,19 +18,24 @@ class MonitoringManager

protected ?bool $isSuccessful = null;

protected ?bool $hasWarnings = null;

public function run(): void
{
$this->isSuccessful = true;
$this->hasWarnings = false;

foreach ($this->attributes as $attribute) {
if ($attribute->isEnabled()) {
$attribute->run();
if (($attribute instanceof AbstractSensor
&& $attribute->getState() !== SensorStateEnum::SUCCESSFUL)
|| ($attribute instanceof AbstractMetric
&& $attribute->getState() !== MetricStateEnum::OK)) {
$wasSuccessful = $this->wasSuccessful($attribute);
$wasWarning = $this->wasWarning($attribute);
if (!$wasSuccessful && !$wasWarning) {
$this->isSuccessful = false;
}
if ($wasWarning) {
$this->hasWarnings = true;
}
}
}
}
Expand Down Expand Up @@ -81,6 +85,15 @@ public function isSuccessful(): bool
return $this->isSuccessful;
}

public function isWarning(): bool
{
if ($this->hasWarnings === null) {
$this->run();
}

return $this->hasWarnings;
}

public function addAttribute(AttributeInterface $attribute): void
{
$this->attributes[$attribute::class] = $attribute;
Expand All @@ -90,4 +103,18 @@ public function getAttribute(string $className): AttributeInterface
{
return $this->attributes[$className];
}

private function wasSuccessful(AttributeInterface $attribute): bool
{
return $attribute instanceof AbstractSensor
? $attribute->getState() === SensorStateEnum::SUCCESSFUL
: $attribute->getState() === MetricStateEnum::OK;
}

private function wasWarning(AttributeInterface $abstract): bool
{
return $abstract instanceof AbstractSensor
? $abstract->getState() === SensorStateEnum::WARNING
: $abstract->getState() === MetricStateEnum::WARNING;
}
}
2 changes: 1 addition & 1 deletion src/Monitoring/Metric/AbstractMetric.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ abstract class AbstractMetric implements AttributeInterface
public function getState(): MetricStateEnum
{
if ($this->state === null) {
throw new \RuntimeException(__CLASS__ . '::$state is not set.');
throw new \RuntimeException(__CLASS__.'::$state is not set.');
}

return $this->state;
Expand Down
2 changes: 1 addition & 1 deletion src/Monitoring/Sensor/AbstractSensor.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ abstract class AbstractSensor implements AttributeInterface
public function getState(): SensorStateEnum
{
if ($this->state === null) {
throw new \RuntimeException(__CLASS__ . '::$state is not set.');
throw new \RuntimeException(__CLASS__.'::$state is not set.');
}

return $this->state;
Expand Down
2 changes: 1 addition & 1 deletion src/Monitoring/Sensor/Database/DoctrineDbal.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public function run(): void
public static function getSubscribedServices(): array
{
return [
'?' . ManagerRegistry::class,
'?'.ManagerRegistry::class,
];
}
}
8 changes: 5 additions & 3 deletions src/Normalizer/AttributeNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use whatwedo\MonitorBundle\Monitoring\Metric\AbstractMetric;
use whatwedo\MonitorBundle\Monitoring\Sensor\AbstractSensor;

class AttributeNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
class AttributeNormalizer implements NormalizerInterface
{
/**
* @param AttributeInterface $object
Expand Down Expand Up @@ -39,8 +39,10 @@ public function supportsNormalization($data, string $format = null, array $conte
return $data instanceof AttributeInterface;
}

public function hasCacheableSupportsMethod(): bool
public function getSupportedTypes(?string $format): array
{
return true;
return [
AttributeInterface::class => true,
];
}
}
16 changes: 7 additions & 9 deletions src/Normalizer/EnumNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,11 @@

namespace whatwedo\MonitorBundle\Normalizer;

use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use whatwedo\MonitorBundle\Enum\MetricStateEnum;
use whatwedo\MonitorBundle\Enum\SensorStateEnum;

/**
* symfony 5.3 compatibility (https://github.com/symfony/symfony/pull/40830 has been merged into 5.4)
*/
class EnumNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface
class EnumNormalizer implements NormalizerInterface
{
/**
* @param MetricStateEnum|SensorStateEnum $object
Expand All @@ -24,12 +20,14 @@ public function normalize($object, string $format = null, array $context = []):

public function supportsNormalization($data, string $format = null, array $context = []): bool
{
return ! class_exists('Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer')
&& ($data instanceof MetricStateEnum || $data instanceof SensorStateEnum);
return $data instanceof MetricStateEnum || $data instanceof SensorStateEnum;
}

public function hasCacheableSupportsMethod(): bool
public function getSupportedTypes(?string $format): array
{
return true;
return [
MetricStateEnum::class => true,
SensorStateEnum::class => true,
];
}
}
2 changes: 1 addition & 1 deletion src/whatwedoMonitorBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

class whatwedoMonitorBundle extends Bundle
{
public function build(ContainerBuilder $container)
public function build(ContainerBuilder $container): void
{
parent::build($container);

Expand Down
6 changes: 3 additions & 3 deletions tests/BundleInitializationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function testDisabledApi(): void
{
$kernel = self::bootKernel([
'config' => static function (TestKernel $kernel) {
$kernel->addTestConfig(__DIR__ . '/config/disabled_api.yml');
$kernel->addTestConfig(__DIR__.'/config/disabled_api.yml');
},
]);

Expand All @@ -38,7 +38,7 @@ public function testDisabledController(): void
{
$kernel = self::bootKernel([
'config' => static function (TestKernel $kernel) {
$kernel->addTestConfig(__DIR__ . '/config/disabled_controller.yml');
$kernel->addTestConfig(__DIR__.'/config/disabled_controller.yml');
},
]);

Expand All @@ -49,7 +49,7 @@ public function testDisabledCommand(): void
{
$kernel = self::bootKernel([
'config' => static function (TestKernel $kernel) {
$kernel->addTestConfig(__DIR__ . '/config/disabled_command.yml');
$kernel->addTestConfig(__DIR__.'/config/disabled_command.yml');
},
]);

Expand Down
34 changes: 33 additions & 1 deletion tests/Command/CheckCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public function testSuccessful(): void
{
$kernel = self::bootKernel([
'config' => static function (TestKernel $kernel) {
$kernel->addTestConfig(__DIR__ . '/../config/dummy_successful.yml');
$kernel->addTestConfig(__DIR__.'/../config/dummy_successful.yml');
},
]);

Expand All @@ -29,4 +29,36 @@ public function testSuccessful(): void
$commandTester->execute([]);
self::assertEquals(0, $commandTester->getStatusCode());
}

public function testWarning(): void
{
$kernel = self::bootKernel([
'config' => static function (TestKernel $kernel) {
$kernel->addTestConfig(__DIR__.'/../config/dummy_warning.yml');
},
]);

$application = new Application($kernel);
$command = $application->find('whatwedo:monitor:check');

$commandTester = new CommandTester($command);
$commandTester->execute([]);
self::assertEquals(1, $commandTester->getStatusCode());
}

public function testWarningCustomExitCode(): void
{
$kernel = self::bootKernel([
'config' => static function (TestKernel $kernel) {
$kernel->addTestConfig(__DIR__.'/../config/dummy_warning_custom_exit_code.yml');
},
]);

$application = new Application($kernel);
$command = $application->find('whatwedo:monitor:check');

$commandTester = new CommandTester($command);
$commandTester->execute([]);
self::assertEquals(2, $commandTester->getStatusCode());
}
}
Loading

0 comments on commit 3d9a88f

Please sign in to comment.