From cec69f63a41c3ce331ac0f16a318007da2062dbc Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Tue, 17 May 2022 12:26:16 +0200 Subject: [PATCH] Introduce class `Icinga\Application\Daemon` --- library/Icinga/Application/Daemon.php | 113 ++++++++++++++++++ .../Icinga/Application/Daemon/DaemonJob.php | 27 +++++ 2 files changed, 140 insertions(+) create mode 100644 library/Icinga/Application/Daemon.php create mode 100644 library/Icinga/Application/Daemon/DaemonJob.php diff --git a/library/Icinga/Application/Daemon.php b/library/Icinga/Application/Daemon.php new file mode 100644 index 000000000..b02c004e5 --- /dev/null +++ b/library/Icinga/Application/Daemon.php @@ -0,0 +1,113 @@ +loop = $loop ?? Loop::get(); + } + + /** + * Initialize the daemon + * + * @return void + */ + protected function initialize(): void + { + $this->registerSignals(); + } + + /** + * Register signals + * + * @return void + */ + protected function registerSignals(): void + { + $this->loop->addSignal(SIGTERM, [$this, 'shutdown']); + $this->loop->addSignal(SIGINT, [$this, 'shutdown']); + } + + /** + * Deregister signals + * + * @return void + */ + protected function deregisterSignals(): void + { + $this->loop->removeSignal(SIGTERM, [$this, 'shutdown']); + $this->loop->removeSignal(SIGINT, [$this, 'shutdown']); + } + + /** + * Launch the daemon + * + * @return void + */ + public function run(): void + { + if (empty($this->jobs)) { + throw new LogicException('No jobs added'); + } + + $this->loop->futureTick(function () { + $this->initialize(); + }); + } + + /** + * Stop the daemon + * + * @return void + */ + public function shutdown(): void + { + if ($this->shuttingDown) { + return; + } + + $this->shuttingDown = true; + $this->deregisterSignals(); + + foreach ($this->jobs as $job) { + $job->cancel(); + } + } + + /** + * Add a job to this daemon + * + * @param DaemonJob $job + * + * @return $this + */ + public function addJob(DaemonJob $job): self + { + $this->jobs[] = $job; + $job->attach($this->loop); + + return $this; + } +} diff --git a/library/Icinga/Application/Daemon/DaemonJob.php b/library/Icinga/Application/Daemon/DaemonJob.php new file mode 100644 index 000000000..b94336cd9 --- /dev/null +++ b/library/Icinga/Application/Daemon/DaemonJob.php @@ -0,0 +1,27 @@ +