summaryrefslogtreecommitdiffstats
path: root/library/Director/Db/Branch/BranchActivity.php
blob: 3812e753d2957fda277fb99693615615de45910c (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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php

namespace Icinga\Module\Director\Db\Branch;

use Icinga\Authentication\Auth;
use Icinga\Exception\NotFoundError;
use Icinga\Module\Director\Data\Db\DbObject;
use Icinga\Module\Director\Data\Db\DbObjectTypeRegistry;
use Icinga\Module\Director\Data\Json;
use Icinga\Module\Director\Data\SerializableValue;
use Icinga\Module\Director\Db;
use Icinga\Module\Director\Objects\DirectorActivityLog;
use Icinga\Module\Director\Objects\IcingaObject;
use InvalidArgumentException;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use RuntimeException;

class BranchActivity
{
    const DB_TABLE = 'director_branch_activity';

    const ACTION_CREATE = DirectorActivityLog::ACTION_CREATE;
    const ACTION_MODIFY = DirectorActivityLog::ACTION_MODIFY;
    const ACTION_DELETE = DirectorActivityLog::ACTION_DELETE;

    /** @var int */
    protected $timestampNs;

    /** @var UuidInterface */
    protected $objectUuid;

    /** @var UuidInterface */
    protected $branchUuid;

    /** @var string create, modify, delete */
    protected $action;

    /** @var string */
    protected $objectTable;

    /** @var string */
    protected $author;

    /** @var SerializableValue */
    protected $modifiedProperties;

    /** @var ?SerializableValue */
    protected $formerProperties;

    public function __construct(
        UuidInterface     $objectUuid,
        UuidInterface     $branchUuid,
        $action,
        $objectType,
        $author,
        SerializableValue $modifiedProperties,
        SerializableValue $formerProperties
    ) {
        $this->objectUuid = $objectUuid;
        $this->branchUuid = $branchUuid;
        $this->action = $action;
        $this->objectTable = $objectType;
        $this->author = $author;
        $this->modifiedProperties = $modifiedProperties;
        $this->formerProperties = $formerProperties;
    }

    public static function deleteObject(DbObject $object, Branch $branch)
    {
        return new static(
            $object->getUniqueId(),
            $branch->getUuid(),
            self::ACTION_DELETE,
            $object->getTableName(),
            Auth::getInstance()->getUser()->getUsername(),
            SerializableValue::fromSerialization(null),
            SerializableValue::fromSerialization(self::getFormerObjectProperties($object))
        );
    }

    public static function forDbObject(DbObject $object, Branch $branch)
    {
        if (! $object->hasBeenModified()) {
            throw new InvalidArgumentException('Cannot get modifications for unmodified object');
        }
        if (! $branch->isBranch()) {
            throw new InvalidArgumentException('Branch activity requires an active branch');
        }

        $author = Auth::getInstance()->getUser()->getUsername();
        if ($object instanceof IcingaObject && $object->shouldBeRemoved()) {
            $action = self::ACTION_DELETE;
            $old = self::getFormerObjectProperties($object);
            $new = null;
        } elseif ($object->hasBeenLoadedFromDb()) {
            $action = self::ACTION_MODIFY;
            $old = self::getFormerObjectProperties($object);
            $new = self::getObjectProperties($object);
        } else {
            $action = self::ACTION_CREATE;
            $old = null;
            $new = self::getObjectProperties($object);
        }

        if ($new !== null) {
            $new = PlainObjectPropertyDiff::calculate(
                $old,
                $new
            );
        }

        return new static(
            $object->getUniqueId(),
            $branch->getUuid(),
            $action,
            $object->getTableName(),
            $author,
            SerializableValue::fromSerialization($new),
            SerializableValue::fromSerialization($old)
        );
    }

    public static function fixFakeTimestamp($timestampNs)
    {
        if ($timestampNs < 1600000000 * 1000000) {
            // fake TS for cloned branch in sync preview
            return (int) $timestampNs * 1000000;
        }

        return $timestampNs;
    }

    public function applyToDbObject(DbObject $object)
    {
        if (!$this->isActionModify()) {
            throw new RuntimeException('Only BranchActivity instances with action=modify can be applied');
        }

        foreach ($this->getModifiedProperties()->jsonSerialize() as $key => $value) {
            $object->set($key, $value);
        }

        return $object;
    }

    /**
     * Hint: $connection is required, because setting groups triggered loading them.
     *       Should be investigated, as in theory $hostWithoutConnection->groups = 'group'
     *       is expected to work
     * @param Db $connection
     * @return DbObject|string
     */
    public function createDbObject(Db $connection)
    {
        if (!$this->isActionCreate()) {
            throw new RuntimeException('Only BranchActivity instances with action=create can create objects');
        }

        $class = DbObjectTypeRegistry::classByType($this->getObjectTable());
        $object = $class::create([], $connection);
        $object->setUniqueId($this->getObjectUuid());
        foreach ($this->getModifiedProperties()->jsonSerialize() as $key => $value) {
            $object->set($key, $value);
        }

        return $object;
    }

    public function deleteDbObject(DbObject $object)
    {
        if (!$this->isActionDelete()) {
            throw new RuntimeException('Only BranchActivity instances with action=delete can delete objects');
        }

        return $object->delete();
    }

    public static function load($ts, Db $connection)
    {
        $db = $connection->getDbAdapter();
        $row = $db->fetchRow(
            $db->select()->from('director_branch_activity')->where('timestamp_ns = ?', $ts)
        );

        if ($row) {
            return static::fromDbRow($row);
        }

        throw new NotFoundError('Not found');
    }

    protected static function fixPgResource(&$value)
    {
        if (is_resource($value)) {
            $value = stream_get_contents($value);
        }
    }

    public static function fromDbRow($row)
    {
        static::fixPgResource($row->object_uuid);
        static::fixPgResource($row->branch_uuid);
        $activity = new static(
            Uuid::fromBytes($row->object_uuid),
            Uuid::fromBytes($row->branch_uuid),
            $row->action,
            $row->object_table,
            $row->author,
            SerializableValue::fromSerialization(Json::decodeOptional($row->modified_properties)),
            SerializableValue::fromSerialization(Json::decodeOptional($row->former_properties))
        );
        $activity->timestampNs = $row->timestamp_ns;

        return $activity;
    }

    /**
     * Must be run in a transaction! Repeatable read?
     * @param Db $connection
     * @throws \Icinga\Module\Director\Exception\JsonEncodeException
     * @throws \Zend_Db_Adapter_Exception
     */
    public function store(Db $connection)
    {
        if ($this->timestampNs !== null) {
            throw new InvalidArgumentException(sprintf(
                'Cannot store activity with a given timestamp: %s',
                $this->timestampNs
            ));
        }
        $db = $connection->getDbAdapter();
        $last = $db->fetchRow(
            $db->select()->from('director_branch_activity', ['timestamp_ns' => 'MAX(timestamp_ns)'])
        );
        if (PHP_INT_SIZE !== 8) {
            throw new RuntimeException('PHP with 64bit integer support is required');
        }
        $timestampNs = (int) floor(microtime(true) * 1000000);
        if ($last) {
            if ($last->timestamp_ns >= $timestampNs) {
                $timestampNs = $last + 1;
            }
        }
        $old = Json::encode($this->formerProperties);
        $new = Json::encode($this->modifiedProperties);

        $db->insert(self::DB_TABLE, [
            'timestamp_ns'    => $timestampNs,
            'object_uuid'     => $connection->quoteBinary($this->objectUuid->getBytes()),
            'branch_uuid'     => $connection->quoteBinary($this->branchUuid->getBytes()),
            'action'          => $this->action,
            'object_table'    => $this->objectTable,
            'author'          => $this->author,
            'former_properties'   => $old,
            'modified_properties' => $new,
        ]);
    }

    /**
     * @return int
     */
    public function getTimestampNs()
    {
        return $this->timestampNs;
    }

    /**
     * @return int
     */
    public function getTimestamp()
    {
        return (int) floor(BranchActivity::fixFakeTimestamp($this->timestampNs) / 1000000);
    }

    /**
     * @return UuidInterface
     */
    public function getObjectUuid()
    {
        return $this->objectUuid;
    }

    /**
     * @return UuidInterface
     */
    public function getBranchUuid()
    {
        return $this->branchUuid;
    }

    /**
     * @return string
     */
    public function getObjectName()
    {
        return $this->getProperty('object_name', 'unknown object name');
    }

    /**
     * @return string
     */
    public function getAction()
    {
        return $this->action;
    }

    public function isActionDelete()
    {
        return $this->action === self::ACTION_DELETE;
    }

    public function isActionCreate()
    {
        return $this->action === self::ACTION_CREATE;
    }

    public function isActionModify()
    {
        return $this->action === self::ACTION_MODIFY;
    }

    /**
     * @return string
     */
    public function getObjectTable()
    {
        return $this->objectTable;
    }

    /**
     * @return string
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * @return ?SerializableValue
     */
    public function getModifiedProperties()
    {
        return $this->modifiedProperties;
    }

    /**
     * @return ?SerializableValue
     */
    public function getFormerProperties()
    {
        return $this->formerProperties;
    }

    public function getProperty($key, $default = null)
    {
        if ($this->modifiedProperties) {
            $properties = $this->modifiedProperties->jsonSerialize();
            if (isset($properties->$key)) {
                return $properties->$key;
            }
        }
        if ($this->formerProperties) {
            $properties = $this->formerProperties->jsonSerialize();
            if (isset($properties->$key)) {
                return $properties->$key;
            }
        }

        return $default;
    }

    protected static function getFormerObjectProperties(DbObject $object)
    {
        if (! $object instanceof IcingaObject) {
            throw new RuntimeException('Plain object helpers for DbObject must be implemented');
        }

        return (array) $object->getPlainUnmodifiedObject();
    }

    protected static function getObjectProperties(DbObject $object)
    {
        if (! $object instanceof IcingaObject) {
            throw new RuntimeException('Plain object helpers for DbObject must be implemented');
        }

        return (array) $object->toPlainObject(false, true);
    }
}