Lines 0.00% 0 / 45
Functions and Methods 0.00% 0 / 6
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
RunCommand 0.00% 0 / 45 0.00% 0 / 6 240 0.00% 0 / 1
 __construct 0.00% 0 / 1 0.00% 0 / 1 2
 configure 0.00% 0 / 8 0.00% 0 / 1 2
 execute 0.00% 0 / 10 0.00% 0 / 1 30
 prepareDaemon 0.00% 0 / 23 0.00% 0 / 1 20
 noteMissingConfigFile 0.00% 0 / 2 0.00% 0 / 1 6
 logFormatFromOptions 0.00% 0 / 1 0.00% 0 / 1 6
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Console;
6
7use Psr\Log\LoggerInterface;
8use Stewart\Contracts\Exception\StewartException;
9use Stewart\Runtime\App\AppCatalogResolver;
10use Stewart\Runtime\App\AppDiscovery;
11use Stewart\Runtime\App\AppInstanceResolver;
12use Stewart\Runtime\App\CatalogWarnings;
13use Stewart\Runtime\Broker\DaemonLaunchOptions;
14use Stewart\Runtime\Config\ConfigLoader;
15use Stewart\Runtime\Kernel\BrokerKernel;
16use Stewart\Runtime\Lifecycle\BrokerStopOutcome;
17use Stewart\Runtime\Logging\LogFormat;
18use Stewart\Runtime\Logging\LoggerFactory;
19use Stewart\Runtime\Logging\LogVerbosityPolicy;
20use Symfony\Component\Console\Attribute\AsCommand;
21use Symfony\Component\Console\Command\Command;
22use Symfony\Component\Console\Input\InputInterface;
23use Symfony\Component\Console\Input\InputOption;
24use Symfony\Component\Console\Output\OutputInterface;
25use Throwable;
26
27#[AsCommand(name: self::NAME, description: 'Run the Stewart daemon')]
28final class RunCommand extends StewartCommand
29{
30    public const string NAME = 'run';
31
32    // sysexits EX_TEMPFAIL: the container entrypoint starts the daemon again on the staged release.
33    public const int RESTART_EXIT_CODE = 75;
34
35    public function __construct(
36        private readonly ConfigLoader $config,
37        private readonly AppDiscovery $discovery,
38        private readonly AppInstanceResolver $instances,
39        private readonly AppCatalogResolver $catalogs,
40        private readonly BrokerKernel $brokers,
41        private readonly LoggerFactory $loggers,
42        private readonly CatalogWarnings $catalogWarnings,
43    ) {
44        parent::__construct();
45    }
46
47    protected function configure(): void
48    {
49        parent::configure();
50        $this
51            ->addOption('log-level', 'l', InputOption::VALUE_REQUIRED, 'debug|info|notice|warning|error')
52            ->addOption('json-logs', null, InputOption::VALUE_NONE, 'Emit logs as JSON')
53            ->addOption('only', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Run only this automation, even if disabled; repeat for more')
54            ->addOption('trace', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Log TRACE lines for this automation at any log level; repeat for more')
55            ->addOption('watch', null, InputOption::VALUE_NONE, 'Reload after every saved change to the apps, services.php or stewart.yaml')
56            ->addOption('dry-run', null, InputOption::VALUE_NONE, 'Log actions, event fires and registry edits instead of sending them (ha_calls.dry_run)');
57    }
58
59    protected function execute(InputInterface $input, OutputInterface $output): int
60    {
61        try {
62            $daemon = $this->prepareDaemon($input);
63        } catch (StewartException $e) {
64            $output->writeln('<error>' . $e->getMessage() . '</error>');
65
66            return Command::FAILURE;
67        }
68
69        try {
70            $outcome = $daemon->broker->run();
71        } catch (Throwable $e) {
72            $daemon->logger->error('Stewart stopped', ['exception' => $e]);
73
74            return Command::FAILURE;
75        }
76
77        return match ($outcome) {
78            BrokerStopOutcome::Stopped => Command::SUCCESS,
79            BrokerStopOutcome::RestartRequested => self::RESTART_EXIT_CODE,
80        };
81    }
82
83    /** @throws StewartException */
84    private function prepareDaemon(InputInterface $input): PreparedDaemon
85    {
86        $launch = new DaemonLaunchOptions(
87            $this->findConfigOption($input),
88            $this->readAppSelectionOption($input),
89            $this->nonEmptyStringOption($input, 'log-level'),
90            $input->getOption('watch') === true,
91            $input->getOption('dry-run') === true,
92        );
93        $config = $this->config->loadConfig($launch->configFile, $launch->listConfigOverrides());
94        // Validated before the logger exists, so a missing home_assistant section fails as a config error.
95        $config->requireHomeAssistant();
96        $discovered = $this->instances->resolveInstances($this->discovery->discover(), $config->apps);
97        $selection = $launch->selection;
98        $apps = $this->catalogs->resolveCatalog($discovered, $config->apps, $config->workers, $selection);
99        $verbosity = new LogVerbosityPolicy($config->logLevel, $apps->enabled->listVerbositiesByAppId());
100        $logger = $this->loggers->createDaemonLogger($verbosity, $this->logFormatFromOptions($input, $config->logFormat));
101
102        $this->noteMissingConfigFile($this->config->findMissingDefaultFile($launch->configFile), $logger);
103        $this->catalogWarnings->logCatalogWarnings($discovered, $apps, $this->config->locateConfigFile($launch->configFile), $logger);
104
105        if ($config->haCalls->dryRun) {
106            $logger->warning('ha_calls.dry_run is on: actions, event fires and registry edits are logged, not sent to Home Assistant.');
107        }
108
109        if ($selection->onlyIds !== null) {
110            $logger->notice('Running only the automations named by --only.', ['apps' => $selection->onlyIds->toStrings()]);
111        }
112
113        if ($selection->tracedIds !== null) {
114            $logger->notice('Tracing the automations named by --trace.', ['apps' => $selection->tracedIds->toStrings()]);
115        }
116
117        return new PreparedDaemon($this->brokers->createBroker($config, $apps, $logger, $verbosity, $launch), $logger);
118    }
119
120    private function noteMissingConfigFile(?string $missingConfigFile, LoggerInterface $logger): void
121    {
122        if ($missingConfigFile !== null) {
123            $logger->info('No config file found; using the environment only.', ['config' => $missingConfigFile]);
124        }
125    }
126
127    private function logFormatFromOptions(InputInterface $input, LogFormat $configured): LogFormat
128    {
129        return $input->getOption('json-logs') === true ? LogFormat::Json : $configured;
130    }
131}