summaryrefslogtreecommitdiffstats
path: root/library/Director/Daemon/BackgroundDaemon.php
blob: 34cc28b768619007ee5ca7d648000a141cac9fa2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
<?php

namespace Icinga\Module\Director\Daemon;

use Exception;
use gipfl\Cli\Process;
use gipfl\IcingaCliDaemon\DbResourceConfigWatch;
use gipfl\SystemD\NotifySystemD;
use React\EventLoop\Factory as Loop;
use React\EventLoop\LoopInterface;
use Ramsey\Uuid\Uuid;

class BackgroundDaemon
{
    /** @var LoopInterface */
    private $loop;

    /** @var NotifySystemD|boolean */
    protected $systemd;

    /** @var JobRunner */
    protected $jobRunner;

    /** @var string|null */
    protected $dbResourceName;

    /** @var DaemonDb */
    protected $daemonDb;

    /** @var DaemonProcessState */
    protected $processState;

    /** @var DaemonProcessDetails */
    protected $processDetails;

    /** @var LogProxy */
    protected $logProxy;

    /** @var bool */
    protected $reloading = false;

    /** @var bool */
    protected $shuttingDown = false;

    public function run(LoopInterface $loop = null)
    {
        if ($ownLoop = ($loop === null)) {
            $loop = Loop::create();
        }
        $this->loop = $loop;
        $this->loop->futureTick(function () {
            $this->initialize();
        });
        if ($ownLoop) {
            $loop->run();
        }
    }

    public function setDbResourceName($name)
    {
        $this->dbResourceName = $name;

        return $this;
    }

    protected function initialize()
    {
        $this->registerSignalHandlers($this->loop);
        $this->processState = new DaemonProcessState('icinga::director');
        $this->jobRunner = new JobRunner($this->loop);
        $this->systemd = $this->eventuallyInitializeSystemd();
        $this->processState->setSystemd($this->systemd);
        if ($this->systemd) {
            $this->systemd->setReady();
        }
        $this->setState('ready');
        $this->processDetails = $this
            ->initializeProcessDetails($this->systemd)
            ->registerProcessList($this->jobRunner->getProcessList());
        $this->logProxy = new LogProxy($this->processDetails->getInstanceUuid());
        $this->jobRunner->forwardLog($this->logProxy);
        $this->daemonDb = $this->initializeDb(
            $this->processDetails,
            $this->processState,
            $this->dbResourceName
        );
        $this->daemonDb
            ->register($this->jobRunner)
            ->register($this->logProxy)
            ->register(new DeploymentChecker($this->loop))
            ->run($this->loop);
        $this->setState('running');
    }

    /**
     * @param NotifySystemD|false $systemd
     * @return DaemonProcessDetails
     */
    protected function initializeProcessDetails($systemd)
    {
        if ($systemd && $systemd->hasInvocationId()) {
            $uuid = $systemd->getInvocationId();
        } else {
            try {
                $uuid = \bin2hex(Uuid::uuid4()->getBytes());
            } catch (Exception $e) {
                $uuid = 'deadc0de' . \substr(\md5(\getmypid()), 0, 24);
            }
        }
        $processDetails = new DaemonProcessDetails($uuid);
        if ($systemd) {
            $processDetails->set('running_with_systemd', 'y');
        }

        return $processDetails;
    }

    protected function eventuallyInitializeSystemd()
    {
        $systemd = NotifySystemD::ifRequired($this->loop);
        if ($systemd) {
            Logger::replaceRunningInstance(new SystemdLogWriter());
            Logger::info(sprintf(
                "Started by systemd, notifying watchdog every %0.2Gs via %s",
                $systemd->getWatchdogInterval(),
                $systemd->getSocketPath()
            ));
        } else {
            Logger::debug('Running without systemd');
        }

        return $systemd;
    }

    /**
     * @return DaemonProcessDetails
     */
    public function getProcessDetails()
    {
        return $this->processDetails;
    }

    /**
     * @return DaemonProcessState
     */
    public function getProcessState()
    {
        return $this->processState;
    }

    protected function initializeDb(
        DaemonProcessDetails $processDetails,
        DaemonProcessState $processState,
        $dbResourceName = null
    ) {
        $db = new DaemonDb($processDetails);
        $db->on('state', function ($state, $level = null) use ($processState) {
            // TODO: level is sent but not used
            $processState->setComponentState('db', $state);
        });
        $db->on('schemaChange', function ($startupSchema, $dbSchema) {
            Logger::info(sprintf(
                "DB schema version changed. Started with %d, DB has %d. Restarting.",
                $startupSchema,
                $dbSchema
            ));
            $this->reload();
        });

        $db->setConfigWatch(
            $dbResourceName
            ? DbResourceConfigWatch::name($dbResourceName)
            : DbResourceConfigWatch::module('director')
        );

        return $db;
    }

    protected function registerSignalHandlers(LoopInterface $loop)
    {
        $func = function ($signal) use (&$func) {
            $this->shutdownWithSignal($signal, $func);
        };
        $funcReload = function () {
            $this->reload();
        };
        $loop->addSignal(SIGHUP, $funcReload);
        $loop->addSignal(SIGINT, $func);
        $loop->addSignal(SIGTERM, $func);
    }

    protected function shutdownWithSignal($signal, &$func)
    {
        $this->loop->removeSignal($signal, $func);
        $this->shutdown();
    }

    public function reload()
    {
        if ($this->reloading) {
            Logger::error('Ignoring reload request, reload is already in progress');
            return;
        }
        $this->reloading = true;
        Logger::info('Going gown for reload now');
        $this->setState('reloading the main process');
        $this->daemonDb->disconnect()->then(function () {
            Process::restart();
        });
    }

    protected function shutdown()
    {
        if ($this->shuttingDown) {
            Logger::error('Ignoring shutdown request, shutdown is already in progress');
            return;
        }
        Logger::info('Shutting down');
        $this->shuttingDown = true;
        $this->setState('shutting down');
        $this->daemonDb->disconnect()->then(function () {
            Logger::info('DB has been disconnected, shutdown finished');
            $this->loop->stop();
        });
    }

    protected function setState($state)
    {
        if ($this->processState) {
            $this->processState->setState($state);
        }

        return $this;
    }
}