summaryrefslogtreecommitdiffstats
path: root/application/clicommands/JobsCommand.php
blob: 0e1d599c1ef4b65d5743e1ab2388e6b8ad0416f7 (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
<?php
// Icinga Web 2 X.509 Module | (c) 2018 Icinga GmbH | GPLv2

namespace Icinga\Module\X509\Clicommands;

use Icinga\Application\Logger;
use Icinga\Module\X509\CertificateUtils;
use Icinga\Module\X509\Command;
use Icinga\Module\X509\Hook\SniHook;
use Icinga\Module\X509\Job;
use Icinga\Module\X509\Scheduler;

class JobsCommand extends Command
{
    /**
     * Run all configured jobs based on their schedule
     *
     * USAGE:
     *
     *   icingacli x509 jobs run
     */
    public function runAction()
    {
        $parallel = (int) $this->Config()->get('scan', 'parallel', 256);

        if ($parallel <= 0) {
            $this->fail("The 'parallel' option must be set to at least 1.");
        }

        $scheduler = new Scheduler();

        $defaultSchedule = $this->Config()->get('jobs', 'default_schedule');

        $db = $this->getDb();

        foreach ($this->Config('jobs') as $name => $jobDescription) {
            $schedule = $jobDescription->get('schedule', $defaultSchedule);

            if (! $schedule) {
                Logger::debug("The job '%s' is not scheduled.", $name);
                continue;
            }

            $job = new Job($name, $db, $jobDescription, SniHook::getAll(), $parallel);

            $scheduler->add($name, $schedule, function () use ($job, $name, $db) {
                if (! $db->ping()) {
                    Logger::error('Lost connection to database and failed to re-connect. Skipping this job run.');
                    return;
                }

                $finishedTargets = $job->run();

                if ($finishedTargets === null) {
                    Logger::warning("The job '%s' does not have any targets.", $name);
                } else {
                    Logger::info(
                        "Scanned %s target%s in job '%s'.\n",
                        $finishedTargets,
                        $finishedTargets != 1 ? 's' : '',
                        $name
                    );

                    $verified = CertificateUtils::verifyCertificates($db);

                    Logger::info("Checked %d certificate chain%s.", $verified, $verified !== 1 ? 's' : '');
                }
            });
        }

        $scheduler->run();
    }
}