summaryrefslogtreecommitdiffstats
path: root/library/Director/Deployment/ConditionalDeployment.php
blob: 0f64028fe4056cd96f2c08c1be4ce8c525bb0bfc (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
<?php

namespace Icinga\Module\Director\Deployment;

use Icinga\Exception\IcingaException;
use Icinga\Module\Director\Core\CoreApi;
use Icinga\Module\Director\Db;
use Icinga\Module\Director\IcingaConfig\IcingaConfig;
use Icinga\Module\Director\Objects\DirectorDeploymentLog;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;

class ConditionalDeployment implements LoggerAwareInterface
{
    use LoggerAwareTrait;

    /** @var Db */
    protected $db;

    /** @var CoreApi */
    protected $api;

    /** @var ?DeploymentGracePeriod */
    protected $gracePeriod = null;

    protected $force = false;

    protected $hasBeenForced = false;

    /** @var ?string */
    protected $noDeploymentReason = null;

    public function __construct(Db $connection, CoreApi $api = null)
    {
        $this->setLogger(new NullLogger());
        $this->db = $connection;
        if ($api === null) {
            $this->api = $connection->getDeploymentEndpoint()->api();
        } else {
            $this->api = $api;
        }
        $this->refresh();
    }

    /**
     * @param IcingaConfig $config
     * @return ?DirectorDeploymentLog
     */
    public function deploy(IcingaConfig $config)
    {
        $this->hasBeenForced = false;
        if ($this->shouldDeploy($config)) {
            return $this->reallyDeploy($config);
        } elseif ($this->force) {
            $deployment = $this->reallyDeploy($config);
            $this->hasBeenForced = true;

            return $deployment;
        }

        return null;
    }

    /**
     * @param bool $force
     * @return $this
     */
    public function force($force = true)
    {
        $this->force = $force;
        return $this;
    }

    public function setGracePeriod(DeploymentGracePeriod $gracePeriod)
    {
        $this->gracePeriod = $gracePeriod;
        return $this;
    }

    public function refresh()
    {
        $this->api->collectLogFiles($this->db);
        $this->api->wipeInactiveStages($this->db);
    }

    public function waitForStartupAfterDeploy(DirectorDeploymentLog $deploymentLog, $timeout)
    {
        $startTime = time();
        while ((time() - $startTime) <= $timeout) {
            $deploymentFromDB = DirectorDeploymentLog::load($deploymentLog->getId(), $this->db);
            $stageCollected = $deploymentFromDB->get('stage_collected');
            if ($stageCollected === null) {
                usleep(500000);
                continue;
            }
            if ($stageCollected === 'n') {
                return 'stage has not been collected (Icinga "lost" the deployment)';
            }
            if ($deploymentFromDB->get('startup_succeeded') === 'y') {
                return true;
            }
            return 'deployment failed during startup (usually a Configuration Error)';
        }
        return 'deployment timed out (while waiting for an Icinga restart)';
    }

    /**
     * @return string|null
     */
    public function getNoDeploymentReason()
    {
        return $this->noDeploymentReason;
    }

    public function hasBeenForced()
    {
        return $this->hasBeenForced;
    }

    protected function shouldDeploy(IcingaConfig $config)
    {
        $this->noDeploymentReason = null;
        if ($this->hasNeverDeployed()) {
            return true;
        }

        if ($this->isWithinGracePeriod()) {
            $this->noDeploymentReason = 'Grace period is active';
            return false;
        }

        if ($this->deployedConfigMatches($config)) {
            $this->noDeploymentReason = 'Config matches last deployed one';
            return false;
        }

        if ($this->getActiveChecksum() === $config->getHexChecksum()) {
            $this->noDeploymentReason = 'Config matches active stage';
            return false;
        }

        return true;
    }

    protected function hasNeverDeployed()
    {
        return !DirectorDeploymentLog::hasDeployments($this->db);
    }

    protected function isWithinGracePeriod()
    {
        return $this->gracePeriod && $this->gracePeriod->isActive();
    }

    protected function deployedConfigMatches(IcingaConfig $config)
    {
        if ($deployment = DirectorDeploymentLog::optionalLatest($this->db)) {
            return $deployment->getConfigHexChecksum() === $config->getHexChecksum();
        }

        return false;
    }

    protected function getActiveChecksum()
    {
        return DirectorDeploymentLog::getConfigChecksumForStageName(
            $this->db,
            $this->api->getActiveStageName()
        );
    }

    /**
     * @param IcingaConfig $config
     * @return bool|DirectorDeploymentLog
     * @throws IcingaException
     * @throws \Icinga\Module\Director\Exception\DuplicateKeyException
     */
    protected function reallyDeploy(IcingaConfig $config)
    {
        $checksum = $config->getHexChecksum();
        $this->logger->info(sprintf('Director ConfigJob ready to deploy "%s"', $checksum));
        if ($deployment = $this->api->dumpConfig($config, $this->db)) {
            $this->logger->notice(sprintf('Director ConfigJob deployed config "%s"', $checksum));
            return $deployment;
        } else {
            throw new IcingaException('Failed to deploy config "%s"', $checksum);
        }
    }
}