summaryrefslogtreecommitdiffstats
path: root/library/Director/DirectorObject/ObjectPurgeHelper.php
blob: a043965d6a15006024f605e9b87026eae85b4738 (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
<?php

namespace Icinga\Module\Director\DirectorObject;

use Icinga\Module\Director\Db;
use Icinga\Module\Director\Objects\IcingaObject;
use InvalidArgumentException;

class ObjectPurgeHelper
{
    protected $db;

    protected $force = false;

    public function __construct(Db $db)
    {
        $this->db = $db;
    }

    public function force($force = true)
    {
        $this->force = $force;
        return $this;
    }

    public function purge(array $keep, $class, $objectType = null)
    {
        if (empty($keep) && ! $this->force) {
            throw new InvalidArgumentException('I will NOT purge all object unless being forced to do so');
        }
        $db = $this->db->getDbAdapter();
        /** @var IcingaObject $class cheating, it's a class name, not an object */
        $dummy = $class::create();
        assert($dummy instanceof IcingaObject);
        $keyCols = (array) $dummy->getKeyName();
        if ($objectType !== null) {
            $keyCols[] = 'object_type';
        }

        $keepKeys = [];
        foreach ($keep as $object) {
            if ($object instanceof \stdClass) {
                $properties = (array) $object;
                // TODO: this is object-specific and to be found in the ::import() function!
                unset($properties['fields']);
                $object = $class::fromPlainObject($properties);
            } elseif (\get_class($object) !== $class) {
                throw new InvalidArgumentException(
                    'Can keep only matching objects, expected "%s", got "%s',
                    $class,
                    \get_class($keep)
                );
            }
            $key = [];
            foreach ($keyCols as $col) {
                $key[$col] = $object->get($col);
            }
            $keepKeys[$this->makeRowKey($key)] = true;
        }

        $query = $db->select()->from(['o' => $dummy->getTableName()], $keyCols);
        if ($objectType !== null) {
            $query->where('object_type = ?', $objectType);
        }
        $allExisting = [];
        foreach ($db->fetchAll($query) as $row) {
            $allExisting[$this->makeRowKey($row)] = $row;
        }
        $remove = [];
        foreach ($allExisting as $key => $keyProperties) {
            if (! isset($keepKeys[$key])) {
                $remove[] = $keyProperties;
            }
        }
        $db->beginTransaction();
        foreach ($remove as $keyProperties) {
            $keyColumn = $class::getKeyColumnName();
            if (is_array($keyColumn)) {
                $object = $class::load((array) $keyProperties, $this->db);
            } else {
                $object = $class::load($keyProperties->$keyColumn, $this->db);
            }
            $object->delete();
        }
        $db->commit();
    }

    public static function listObjectTypesAvailableForPurge()
    {
        return [
            'Basket',
            'Command',
            'CommandTemplate',
            'Dependency',
            'DirectorJob',
            'ExternalCommand',
            'HostGroup',
            'HostTemplate',
            'IcingaTemplateChoiceHost',
            'IcingaTemplateChoiceService',
            'ImportSource',
            'Notification',
            'NotificationTemplate',
            'ServiceGroup',
            'ServiceSet',
            'ServiceTemplate',
            'SyncRule',
            'TimePeriod',
        ];
    }

    public static function objectTypeIsEligibleForPurge($type)
    {
        return in_array($type, static::listObjectTypesAvailableForPurge(), true);
    }

    public static function assertObjectTypesAreEligibleForPurge($types)
    {
        $invalid = [];
        foreach ($types as $type) {
            if (! static::objectTypeIsEligibleForPurge($type)) {
                $invalid[] = $type;
            }
        }

        if (empty($invalid)) {
            return;
        }

        if (count($invalid) === 1) {
            $message = sprintf('"%s" is not eligible for purge', $invalid[0]);
        } else {
            $message = 'The following types are not eligible for purge: '
                . implode(', ', $invalid);
        }

        throw new InvalidArgumentException(
            "$message. Valid types: "
            . implode(', ', static::listObjectTypesAvailableForPurge())
        );
    }

    protected function makeRowKey($row)
    {
        $row = (array) $row;
        ksort($row);
        return json_encode($row, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }
}