summaryrefslogtreecommitdiffstats
path: root/library/Director/Daemon/DaemonProcessState.php
blob: 6ae3cd2e8a4f075cae7140e6df74fc153db5aa36 (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
<?php

namespace Icinga\Module\Director\Daemon;

use gipfl\Cli\Process;
use gipfl\SystemD\NotifySystemD;

class DaemonProcessState
{
    /** @var NotifySystemD|null */
    protected $systemd;

    protected $components = [];

    protected $currentMessage;

    protected $processTitle;

    protected $state;

    public function __construct($processTitle)
    {
        $this->processTitle = $processTitle;
        $this->refreshMessage();
    }

    /**
     * @param NotifySystemD|false $systemd
     * @return $this
     */
    public function setSystemd($systemd)
    {
        if ($systemd) {
            $this->systemd = $systemd;
        } else {
            $this->systemd = null;
        }

        return $this;
    }

    public function setState($message)
    {
        $this->state = $message;
        $this->refreshMessage();

        return $this;
    }

    public function setComponentState($name, $stateMessage)
    {
        if ($stateMessage === null) {
            unset($this->components[$name]);
        } else {
            $this->components[$name] = $stateMessage;
        }
        $this->refreshMessage();
    }

    protected function refreshMessage()
    {
        $messageParts = [];
        if ($this->state !== null && \strlen($this->state)) {
            $messageParts[] = $this->state;
        }
        foreach ($this->components as $component => $message) {
            $messageParts[] = "$component: $message";
        }

        $message = \implode(', ', $messageParts);

        if ($message !== $this->currentMessage) {
            $this->currentMessage = $message;
            if (\strlen($message) === 0) {
                Process::setTitle($this->processTitle);
            } else {
                Process::setTitle($this->processTitle . ": $message");
            }

            if ($this->systemd) {
                $this->systemd->setStatus($message);
            }
        }
    }
}