icingaweb2-module-director/library/Director/Import/Sync.php

985 lines
32 KiB
PHP
Raw Permalink Normal View History

<?php
namespace Icinga\Module\Director\Import;
use Exception;
use Icinga\Application\Benchmark;
use Icinga\Data\Filter\Filter;
use Icinga\Module\Director\Application\MemoryLimit;
2017-08-21 21:53:19 +02:00
use Icinga\Module\Director\Data\Db\DbObject;
2022-07-01 08:36:01 +02:00
use Icinga\Module\Director\Data\Db\DbObjectStore;
use Icinga\Module\Director\Data\Db\DbObjectTypeRegistry;
use Icinga\Module\Director\Db;
use Icinga\Module\Director\Db\Branch\BranchSupport;
2016-10-31 17:20:17 +01:00
use Icinga\Module\Director\Db\Cache\PrefetchCache;
use Icinga\Module\Director\Objects\HostGroupMembershipResolver;
use Icinga\Module\Director\Objects\IcingaHost;
use Icinga\Module\Director\Objects\IcingaHostGroup;
use Icinga\Module\Director\Objects\IcingaObject;
use Icinga\Module\Director\Objects\IcingaObjectGroup;
use Icinga\Module\Director\Objects\ImportSource;
use Icinga\Module\Director\Objects\IcingaService;
use Icinga\Module\Director\Objects\SyncProperty;
use Icinga\Module\Director\Objects\SyncRule;
2016-02-24 12:24:19 +01:00
use Icinga\Module\Director\Objects\SyncRun;
2015-10-20 22:21:48 +02:00
use Icinga\Exception\IcingaException;
use Icinga\Module\Director\Repository\IcingaTemplateRepository;
use InvalidArgumentException;
use RuntimeException;
class Sync
{
/** @var SyncRule */
protected $rule;
/** @var Db */
protected $db;
/** @var array Related ImportSource objects */
protected $sources;
/** @var array Source columns we want to fetch from our sources */
2016-02-23 21:05:09 +01:00
protected $sourceColumns;
/** @var array Imported data */
2016-02-23 17:35:47 +01:00
protected $imported;
/** @var IcingaObject[] Objects to work with */
2016-02-23 17:47:18 +01:00
protected $objects;
/** @var array<mixed, array<int, string>> key => [property, property]*/
protected $setNull = [];
/** @var array<mixed, array<string, mixed>> key => [propertyName, newValue]*/
protected $newProperties = [];
/** @var bool Whether we already prepared your sync */
2016-02-24 12:24:19 +01:00
protected $isPrepared = false;
/** @var bool Whether we applied strtolower() to existing object keys */
protected $usedLowerCasedKeys = false;
protected $modify = [];
2015-12-23 15:10:37 +01:00
protected $remove = [];
2015-12-23 15:10:37 +01:00
protected $create = [];
2015-12-23 15:10:37 +01:00
protected $errors = [];
2015-12-23 15:10:37 +01:00
/** @var SyncProperty[] */
protected $syncProperties;
protected $replaceVars = false;
protected $hasPropertyDisabled = false;
protected $serviceOverrideKeyName;
/**
* @var SyncRun
*/
2016-02-24 12:24:19 +01:00
protected $run;
protected $runStartTime;
/** @var Filter[] */
protected $columnFilters = [];
/** @var HostGroupMembershipResolver|bool */
protected $hostGroupMembershipResolver;
2022-07-01 08:36:01 +02:00
/** @var ?DbObjectStore */
protected $store;
/** @var IcingaObjectGroup[] */
protected $modifiedGroups = [];
/** @var IcingaObject[] */
protected $modifiedGroupObjects = [];
/**
* @param SyncRule $rule
2022-07-01 08:36:01 +02:00
* @param ?DbObjectStore $store
*/
2022-07-01 08:36:01 +02:00
public function __construct(SyncRule $rule, DbObjectStore $store = null)
{
$this->rule = $rule;
$this->db = $rule->getConnection();
2022-07-01 08:36:01 +02:00
$this->store = $store;
}
/**
* Whether the given sync rule would apply modifications
*
* @return boolean
* @throws Exception
*/
public function hasModifications()
{
return count($this->getExpectedModifications()) > 0;
}
/**
* Retrieve modifications a given SyncRule would apply
*
* @return array Array of IcingaObject elements
* @throws \Icinga\Exception\NotFoundError
* @throws \Icinga\Module\Director\Exception\DuplicateKeyException
*/
public function getExpectedModifications()
{
$modified = [];
$objects = $this->prepare();
$updateOnly = $this->rule->get('update_policy') === 'update-only';
$allowCreate = ! $updateOnly;
foreach ($objects as $object) {
if ($object->hasBeenModified()) {
if ($allowCreate || $object->hasBeenLoadedFromDb()) {
$modified[] = $object;
}
} elseif (! $updateOnly && $object->shouldBeRemoved()) {
2016-04-22 14:47:49 +02:00
$modified[] = $object;
}
}
return $modified;
}
/**
* Raise PHP resource limits
*
* @return self;
*/
protected function raiseLimits()
{
MemoryLimit::raiseTo('1024M');
ini_set('max_execution_time', '0');
return $this;
}
2016-02-24 12:24:19 +01:00
/**
* Initialize run summary measurements
*
* @return self;
*/
protected function startMeasurements()
{
$this->run = SyncRun::start($this->rule);
$this->runStartTime = microtime(true);
Benchmark::measure('Starting sync');
2016-02-24 12:24:19 +01:00
return $this;
}
/**
* Fetch the configured properties involved in this sync
*
* @return self
*/
protected function fetchSyncProperties()
{
$this->syncProperties = $this->rule->getSyncProperties();
foreach ($this->syncProperties as $key => $prop) {
$destinationField = $prop->get('destination_field');
if ($destinationField === 'vars' && $prop->get('merge_policy') === 'override') {
$this->replaceVars = true;
}
if ($destinationField === 'disabled') {
$this->hasPropertyDisabled = true;
}
2021-11-28 11:13:08 +01:00
if ($prop->get('filter_expression') === null || strlen($prop->get('filter_expression')) === 0) {
continue;
}
$this->columnFilters[$key] = Filter::fromQueryString(
$prop->get('filter_expression')
);
}
2016-02-24 12:24:19 +01:00
return $this;
}
protected function rowMatchesPropertyFilter($row, $key)
{
if (!array_key_exists($key, $this->columnFilters)) {
return true;
}
return $this->columnFilters[$key]->matches($row);
}
/**
* Instantiates all related ImportSource objects
*
2016-02-23 17:35:47 +01:00
* @return self
* @throws \Icinga\Exception\NotFoundError
*/
protected function prepareRelatedImportSources()
{
$this->sources = [];
foreach ($this->syncProperties as $p) {
$id = $p->get('source_id');
2016-02-23 17:47:18 +01:00
if (! array_key_exists($id, $this->sources)) {
$this->sources[$id] = ImportSource::loadWithAutoIncId(
(int) $id,
$this->db
);
}
}
2016-02-23 17:35:47 +01:00
return $this;
}
2016-02-23 21:05:09 +01:00
/**
* Prepare the source columns we want to fetch
*
* @return self
*/
protected function prepareSourceColumns()
{
// $fieldMap = [];
$this->sourceColumns = [];
foreach ($this->syncProperties as $p) {
$sourceId = $p->get('source_id');
2016-02-23 21:05:09 +01:00
if (! array_key_exists($sourceId, $this->sourceColumns)) {
$this->sourceColumns[$sourceId] = [];
}
foreach (SyncUtils::extractVariableNames($p->get('source_expression')) as $varname) {
2016-02-23 21:05:09 +01:00
$this->sourceColumns[$sourceId][$varname] = $varname;
// -> ? $fieldMap[
}
}
2016-02-23 21:05:09 +01:00
return $this;
}
2016-02-23 17:35:47 +01:00
/**
* Fetch latest imported data rows from all involved import sources
* @return Sync
* @throws \Icinga\Exception\NotFoundError
2016-02-23 17:35:47 +01:00
*/
protected function fetchImportedData()
{
Benchmark::measure('Begin loading imported data');
if ($this->rule->get('object_type') === 'host') {
$this->serviceOverrideKeyName = $this->db->settings()->override_services_varname;
}
$this->imported = [];
$sourceKeyPattern = $this->rule->getSourceKeyPattern();
$combinedKey = $this->rule->hasCombinedKey();
2016-02-23 17:35:47 +01:00
foreach ($this->sources as $source) {
/** @var ImportSource $source */
$sourceId = $source->get('id');
2016-02-23 21:05:09 +01:00
// Provide an alias column for our key. TODO: double-check this!
$key = $source->key_column;
2016-02-23 21:05:09 +01:00
$this->sourceColumns[$sourceId][$key] = $key;
$run = $source->fetchLastRun(true);
$usedColumns = SyncUtils::getRootVariables($this->sourceColumns[$sourceId]);
$filterColumns = [];
foreach ($this->columnFilters as $filter) {
foreach ($filter->listFilteredColumns() as $column) {
$filterColumns[$column] = $column;
}
}
if (($ruleFilter = $this->rule->filter()) !== null) {
foreach ($ruleFilter->listFilteredColumns() as $column) {
$filterColumns[$column] = $column;
}
}
if (! empty($filterColumns)) {
foreach (SyncUtils::getRootVariables($filterColumns) as $column) {
$usedColumns[$column] = $column;
}
}
Benchmark::measure(sprintf('Done pre-processing columns for source %s', $source->source_name));
$rows = $run->fetchRows($usedColumns);
Benchmark::measure(sprintf('Fetched source %s', $source->source_name));
$this->imported[$sourceId] = [];
foreach ($rows as $row) {
if ($combinedKey) {
$key = SyncUtils::fillVariables($sourceKeyPattern, $row);
if ($this->usedLowerCasedKeys) {
$key = strtolower($key);
}
2016-07-13 13:52:15 +02:00
2016-02-23 17:35:47 +01:00
if (array_key_exists($key, $this->imported[$sourceId])) {
throw new InvalidArgumentException(sprintf(
'Trying to import row "%s" (%s) twice: %s VS %s',
$key,
$sourceKeyPattern,
2016-02-23 17:35:47 +01:00
json_encode($this->imported[$sourceId][$key]),
json_encode($row)
));
}
} else {
if (! property_exists($row, $key)) {
throw new InvalidArgumentException(sprintf(
'There is no key column "%s" in this row from "%s": %s',
$key,
$source->source_name,
json_encode($row)
));
}
}
2016-02-23 21:05:09 +01:00
if (! $this->rule->matches($row)) {
2015-12-04 10:59:25 +01:00
continue;
}
if ($combinedKey) {
2016-02-23 17:35:47 +01:00
$this->imported[$sourceId][$key] = $row;
} else {
if ($this->usedLowerCasedKeys) {
$this->imported[$sourceId][strtolower($row->$key)] = $row;
} else {
$this->imported[$sourceId][$row->$key] = $row;
}
}
}
unset($rows);
}
Benchmark::measure('Done loading imported data');
2016-02-23 17:35:47 +01:00
return $this;
}
/**
* TODO: This is rubbish, we need to filter at fetch time
*/
2016-02-23 17:47:18 +01:00
protected function removeForeignListEntries()
2016-02-19 12:42:02 +01:00
{
$listId = null;
foreach ($this->syncProperties as $prop) {
if ($prop->get('destination_field') === 'list_id') {
$listId = (int) $prop->get('source_expression');
2016-02-19 12:42:02 +01:00
}
}
if ($listId === null) {
throw new InvalidArgumentException(
2022-08-29 08:53:49 +02:00
'Cannot sync datalist entry without list_id'
2016-02-19 12:42:02 +01:00
);
}
$no = [];
2016-02-23 17:47:18 +01:00
foreach ($this->objects as $k => $o) {
2022-08-29 08:53:49 +02:00
if ((int) $o->get('list_id') !== $listId) {
2016-02-19 12:42:02 +01:00
$no[] = $k;
}
}
foreach ($no as $k) {
2016-02-23 17:47:18 +01:00
unset($this->objects[$k]);
2016-02-19 12:42:02 +01:00
}
}
/**
* @return $this
*/
2016-02-23 17:47:18 +01:00
protected function loadExistingObjects()
{
Benchmark::measure('Begin loading existing objects');
$ruleObjectType = $this->rule->get('object_type');
$useLowerCaseKeys = $ruleObjectType !== 'datalistEntry';
2016-02-23 17:47:18 +01:00
// TODO: Make object_type (template, object...) and object_name mandatory?
if ($this->rule->hasCombinedKey()) {
$this->objects = [];
$destinationKeyPattern = $this->rule->getDestinationKeyPattern();
$table = DbObjectTypeRegistry::tableNameByType($ruleObjectType);
if ($this->store && BranchSupport::existsForTableName($table)) {
$objects = $this->store->loadAll($table);
2022-07-01 08:36:01 +02:00
} else {
$objects = IcingaObject::loadAllByType($ruleObjectType, $this->db);
}
2022-07-01 08:36:01 +02:00
foreach ($objects as $object) {
if ($object instanceof IcingaService) {
2024-10-22 14:31:14 +02:00
if (
strstr($destinationKeyPattern, '${host}')
&& $object->get('host_id') === null
) {
continue;
2024-10-22 14:31:14 +02:00
} elseif (
strstr($destinationKeyPattern, '${service_set}')
&& $object->get('service_set_id') === null
) {
2016-02-26 11:58:37 +01:00
continue;
}
}
2016-07-13 13:52:15 +02:00
$key = SyncUtils::fillVariables(
$destinationKeyPattern,
$object
);
if ($useLowerCaseKeys) {
$key = strtolower($key);
}
if (array_key_exists($key, $this->objects)) {
throw new InvalidArgumentException(sprintf(
'Combined destination key "%s" is not unique, got "%s" twice',
$destinationKeyPattern,
$key
));
}
$this->objects[$key] = $object;
}
} else {
2022-07-01 08:36:01 +02:00
if ($this->store) {
$objects = $this->store->loadAll(DbObjectTypeRegistry::tableNameByType($ruleObjectType), 'object_name');
} else {
$keyColumn = null;
$query = null;
// We enforce named index for combined-key templates (Services and Sets) and applied Sets
if ($ruleObjectType === 'service' || $ruleObjectType === 'serviceSet') {
foreach ($this->syncProperties as $prop) {
$configuredObjectType = $prop->get('source_expression');
2024-10-22 14:31:14 +02:00
if (
$prop->get('destination_field') === 'object_type'
&& (
$configuredObjectType === 'template'
|| ($configuredObjectType === 'apply' && $ruleObjectType === 'serviceSet')
)
) {
$keyColumn = 'object_name';
$table = $ruleObjectType === 'service'
? BranchSupport::TABLE_ICINGA_SERVICE
: BranchSupport::TABLE_ICINGA_SERVICE_SET;
$query = $this->db->getDbAdapter()->select()
->from($table)->where('object_type = ?', $configuredObjectType);
}
}
}
$objects = IcingaObject::loadAllByType($ruleObjectType, $this->db, $query, $keyColumn);
}
if ($useLowerCaseKeys) {
$this->objects = [];
foreach ($objects as $key => $object) {
$this->objects[strtolower($key)] = $object;
}
2022-07-01 08:36:01 +02:00
} else {
$this->objects = $objects;
2022-07-01 08:36:01 +02:00
}
}
2016-02-23 17:47:18 +01:00
$this->usedLowerCasedKeys = $useLowerCaseKeys;
2016-02-23 17:47:18 +01:00
// TODO: should be obsoleted by a better "loadFiltered" method
if ($ruleObjectType === 'datalistEntry') {
$this->removeForeignListEntries();
2016-02-23 17:47:18 +01:00
}
Benchmark::measure('Done loading existing objects');
2016-02-23 17:47:18 +01:00
return $this;
}
/**
* @return array
* @throws \Icinga\Exception\NotFoundError
* @throws \Icinga\Module\Director\Exception\DuplicateKeyException
*/
2016-02-23 17:35:47 +01:00
protected function prepareNewObjects()
{
$objects = [];
$ruleObjectType = $this->rule->get('object_type');
2016-02-23 17:35:47 +01:00
foreach ($this->sources as $source) {
$sourceId = $source->id;
$keyColumn = $source->get('key_column');
2016-02-23 17:35:47 +01:00
foreach ($this->imported[$sourceId] as $key => $row) {
2019-05-22 17:06:24 +02:00
// Workaround: $a["10"] = "val"; -> array_keys($a) = [(int) 10]
$key = (string) $key;
$originalKey = $row->$keyColumn;
if ($this->usedLowerCasedKeys) {
$key = strtolower($key);
}
if (! array_key_exists($key, $objects)) {
// Safe default values for object_type and object_name
if ($ruleObjectType === 'datalistEntry') {
$props = [];
} else {
$props = [
'object_type' => 'object',
'object_name' => $originalKey,
];
}
$objects[$key] = IcingaObject::createByType(
$ruleObjectType,
$props,
$this->db
2015-12-10 12:57:11 +01:00
);
}
$object = $objects[$key];
$this->prepareNewObject($row, $object, $key, $sourceId);
}
}
2015-12-10 12:57:11 +01:00
return $objects;
}
/**
* @param $row
* @param DbObject $object
* @param $sourceId
* @throws \Icinga\Exception\NotFoundError
* @throws \Icinga\Module\Director\Exception\DuplicateKeyException
*/
protected function prepareNewObject($row, DbObject $object, $objectKey, $sourceId)
{
if (!isset($this->newProperties[$objectKey])) {
$this->newProperties[$objectKey] = [];
}
// TODO: some more improvements are possible here. First, no need to instantiate
// all new objects, we could stick with the newProperties array. Next, we
// should be more correct when respecting sync property order. Right now,
// a property from another Import Source might win, even if property order
// tells something different. This is a very rare case, but still incorrect.
$properties = &$this->newProperties[$objectKey];
foreach ($this->syncProperties as $propertyKey => $p) {
if ($p->get('source_id') !== $sourceId) {
continue;
}
if (! $this->rowMatchesPropertyFilter($row, $propertyKey)) {
continue;
}
$prop = $p->get('destination_field');
$val = SyncUtils::fillVariables($p->get('source_expression'), $row);
if ($object instanceof IcingaObject) {
if ($prop === 'import') {
if ($val !== null) {
$object->imports()->add($val);
}
} elseif ($prop === 'groups') {
if ($val !== null) {
$object->groups()->add($val);
}
} elseif (substr($prop, 0, 5) === 'vars.') {
$varName = substr($prop, 5);
if (substr($varName, -2) === '[]') {
$varName = substr($varName, 0, -2);
$object->vars()->$varName = array_merge(
2023-08-22 10:32:19 +02:00
(array) ($object->vars()->$varName),
(array) $val
);
} else {
$this->setPropertyWithNullLogic($object, $objectKey, $prop, $val, $properties);
}
} else {
$this->setPropertyWithNullLogic($object, $objectKey, $prop, $val, $properties);
}
} else {
$this->setPropertyWithNullLogic($object, $objectKey, $prop, $val, $properties);
}
}
}
protected function setPropertyWithNullLogic(DbObject $object, $objectKey, $property, $value, &$allProps)
{
if ($value === null) {
if (! array_key_exists($property, $allProps) || $allProps[$property] === null) {
$this->setNull[$objectKey][$property] = $property;
}
} else {
unset($this->setNull[$objectKey][$property]);
$object->set($property, $value);
}
$allProps[$property] = $value;
}
/**
* @return $this
*/
protected function deferResolvers()
{
if (in_array($this->rule->get('object_type'), ['host', 'hostgroup'])) {
$resolver = $this->getHostGroupMembershipResolver();
$resolver->defer()->setUseTransactions(false);
}
return $this;
}
/**
2017-08-21 21:53:19 +02:00
* @param DbObject $object
* @return $this
*/
protected function setResolver($object)
{
if (! ($object instanceof IcingaHost || $object instanceof IcingaHostGroup)) {
return $this;
}
if ($resolver = $this->getHostGroupMembershipResolver()) {
$object->setHostGroupMembershipResolver($resolver);
}
return $this;
}
/**
* @return $this
* @throws \Zend_Db_Adapter_Exception
*/
protected function notifyResolvers()
{
if ($resolver = $this->getHostGroupMembershipResolver()) {
if ($this->rule->get('object_type') === 'hostgroup') {
$resolver->setGroups($this->modifiedGroups);
}
$resolver->refreshDb(true);
}
return $this;
}
/**
* @return bool|HostGroupMembershipResolver
*/
protected function getHostGroupMembershipResolver()
{
if ($this->hostGroupMembershipResolver === null) {
2024-10-22 14:31:14 +02:00
if (
in_array(
$this->rule->get('object_type'),
['host', 'hostgroup']
)
) {
$this->hostGroupMembershipResolver = new HostGroupMembershipResolver(
$this->db
);
} else {
$this->hostGroupMembershipResolver = false;
}
}
return $this->hostGroupMembershipResolver;
}
/**
* Evaluates a SyncRule and returns a list of modified objects
*
* TODO: Split this into smaller methods
*
* @return DbObject|IcingaObject[] List of modified IcingaObjects
* @throws \Icinga\Exception\NotFoundError
* @throws \Icinga\Module\Director\Exception\DuplicateKeyException
*/
protected function prepare()
{
2016-02-24 12:24:19 +01:00
if ($this->isPrepared) {
return $this->objects;
}
$this->raiseLimits()
2016-02-24 12:24:19 +01:00
->startMeasurements()
->prepareCache()
2016-02-24 12:24:19 +01:00
->fetchSyncProperties()
->prepareRelatedImportSources()
2016-02-23 21:05:09 +01:00
->prepareSourceColumns()
->loadExistingObjects()
->fetchImportedData()
->deferResolvers();
Benchmark::measure('Begin preparing updated objects');
$newObjects = $this->prepareNewObjects();
Benchmark::measure('Ready to process objects');
/** @var DbObject|IcingaObject $object */
foreach ($newObjects as $key => $object) {
$this->processObject($key, $object);
}
Benchmark::measure('Modified objects are ready, applying purge strategy');
$noAction = [];
$purgeAction = $this->rule->get('purge_action');
foreach ($this->rule->purgeStrategy()->listObjectsToPurge() as $key) {
$key = strtolower($key);
2016-02-22 11:01:37 +01:00
if (array_key_exists($key, $newObjects)) {
// Object has been touched, do not delete
continue;
}
if (array_key_exists($key, $this->objects)) {
$object = $this->objects[$key];
if (! $object->hasBeenModified()) {
switch ($purgeAction) {
case 'delete':
$object->markForRemoval();
break;
case 'disable':
$object->set('disabled', 'y');
break;
default:
throw new RuntimeException(
"Unsupported purge action: '$purgeAction'"
);
}
}
}
}
2016-02-22 11:01:37 +01:00
Benchmark::measure('Done marking objects for purge');
foreach ($this->objects as $key => $object) {
if (! $object->hasBeenModified() && ! $object->shouldBeRemoved()) {
2016-02-22 11:01:37 +01:00
$noAction[] = $key;
}
}
2016-02-22 11:01:37 +01:00
foreach ($noAction as $key) {
2016-02-23 17:47:18 +01:00
unset($this->objects[$key]);
2016-02-22 11:01:37 +01:00
}
2016-02-24 12:24:19 +01:00
$this->isPrepared = true;
Benchmark::measure('Done preparing objects');
2016-02-23 17:47:18 +01:00
return $this->objects;
}
/**
* @param $key
* @param DbObject|IcingaObject $object
* @throws \Icinga\Exception\NotFoundError
*/
protected function processObject($key, $object)
{
if (array_key_exists($key, $this->objects)) {
$this->refreshObject($key, $object);
} else {
$this->addNewObject($key, $object);
}
}
protected function optionallyTellResolverAboutModifiedGroup(IcingaObjectGroup $group)
{
if (in_array('assign_filter', $group->getModifiedProperties())) {
$this->modifiedGroups[] = $group;
}
}
/**
* @param $key
* @param DbObject|IcingaObject $object
* @throws \Icinga\Exception\NotFoundError
*/
protected function refreshObject($key, $object)
{
$policy = $this->rule->get('update_policy');
switch ($policy) {
case 'override':
2024-10-22 14:31:14 +02:00
if (
$object instanceof IcingaHost
&& !in_array('api_key', $this->rule->getSyncProperties())
) {
$this->objects[$key]->replaceWith($object, ['api_key']);
} else {
$this->objects[$key]->replaceWith($object);
}
break;
case 'merge':
case 'update-only':
// TODO: re-evaluate merge settings. vars.x instead of
// just "vars" might suffice.
$this->objects[$key]->merge($object, $this->replaceVars);
if (! $this->hasPropertyDisabled && $object->hasProperty('disabled')) {
$this->objects[$key]->resetProperty('disabled');
}
break;
default:
// policy 'ignore', no action
}
if ($policy === 'override' || $policy === 'merge') {
if ($object instanceof IcingaHost) {
$keyName = $this->serviceOverrideKeyName;
if (! $object->hasInitializedVars() || ! isset($object->vars()->$key)) {
$this->objects[$key]->vars()->restoreStoredVar($keyName);
}
}
}
// Hint: in theory, NULL should be set on new objects, but this has no effect
// anyway, and we also do not store vars.something = null, this would
// instead delete the variable. So here we do not need to check for new
// objects, and skip all null values with update policy = 'ignore'
if ($policy !== 'ignore' && isset($this->setNull[$key])) {
foreach ($this->setNull[$key] as $property) {
$this->objects[$key]->set($property, null);
}
}
}
/**
* @param $key
* @param DbObject|IcingaObject $object
*/
protected function addNewObject($key, $object)
{
$this->objects[$key] = $object;
}
/**
* Runs a SyncRule and applies all resulting changes
* @return int
* @throws Exception
* @throws IcingaException
*/
public function apply()
{
Benchmark::measure('Begin applying objects');
2016-02-23 13:41:19 +01:00
$objects = $this->prepare();
2016-02-24 12:24:19 +01:00
$db = $this->db;
$dba = $db->getDbAdapter();
2022-07-01 08:36:01 +02:00
if (! $this->store) { // store has it's own transaction
$dba->beginTransaction();
}
$object = null;
$updateOnly = $this->rule->get('update_policy') === 'update-only';
$allowCreate = ! $updateOnly;
try {
$formerActivityChecksum = hex2bin(
$db->getLastActivityChecksum()
);
$created = 0;
$modified = 0;
$deleted = 0;
// TODO: Count also failed ones, once we allow such
// $failed = 0;
foreach ($objects as $object) {
$this->setResolver($object);
if (! $updateOnly && $object->shouldBeRemoved()) {
2022-07-01 08:36:01 +02:00
if ($this->store) {
$this->store->delete($object);
} else {
$object->delete();
}
$deleted++;
continue;
}
2015-12-04 10:24:54 +01:00
if ($object->hasBeenModified()) {
if ($object instanceof IcingaObjectGroup) {
$this->optionallyTellResolverAboutModifiedGroup($object);
}
$existing = $object->hasBeenLoadedFromDb();
if ($existing) {
2022-07-01 08:36:01 +02:00
if ($this->store) {
$this->store->store($object);
} else {
$object->store($db);
}
$modified++;
} elseif ($allowCreate) {
2022-07-01 08:36:01 +02:00
if ($this->store) {
$this->store->store($object);
} else {
$object->store($db);
}
$created++;
}
2016-02-24 12:24:19 +01:00
}
2015-11-02 09:29:03 +01:00
}
2015-10-20 22:22:58 +02:00
$runProperties = [
'objects_created' => $created,
'objects_deleted' => $deleted,
'objects_modified' => $modified,
];
2016-02-24 12:24:19 +01:00
if ($created + $deleted + $modified > 0) {
// TODO: What if this has been the very first activity?
$runProperties['last_former_activity'] = $db->quoteBinary($formerActivityChecksum);
$runProperties['last_related_activity'] = $db->quoteBinary(hex2bin(
$db->getLastActivityChecksum()
));
}
$this->run->setProperties($runProperties);
if (!$this->store || !$this->store->getBranch()->isBranch()) {
$this->run->store();
}
$this->notifyResolvers();
2022-07-01 08:36:01 +02:00
if (! $this->store) {
$dba->commit();
}
2016-02-24 12:24:19 +01:00
// Store duration after commit, as the commit might take some time
$this->run->set('duration_ms', (int) round(
(microtime(true) - $this->runStartTime) * 1000
));
if (!$this->store || !$this->store->getBranch()->isBranch()) {
$this->run->store();
}
Benchmark::measure('Done applying objects');
} catch (Exception $e) {
2022-07-01 08:36:01 +02:00
if (! $this->store) {
$dba->rollBack();
}
2022-07-01 08:36:01 +02:00
if ($object instanceof IcingaObject) {
throw new IcingaException(
'Exception while syncing %s %s: %s',
2017-01-13 19:47:54 +01:00
get_class($object),
2022-07-01 08:36:01 +02:00
$object->getObjectName(),
2017-01-13 19:47:54 +01:00
$e->getMessage(),
$e
);
2017-01-13 19:47:54 +01:00
} else {
throw $e;
}
}
2016-02-24 12:24:19 +01:00
return $this->run->get('id');
}
protected function prepareCache()
{
2022-07-01 08:36:01 +02:00
if ($this->store) {
return $this;
}
PrefetchCache::initialize($this->db);
IcingaTemplateRepository::clear();
$ruleObjectType = $this->rule->get('object_type');
$dummy = IcingaObject::createByType($ruleObjectType);
if ($dummy instanceof IcingaObject) {
IcingaObject::prefetchAllRelationsByType($ruleObjectType, $this->db);
}
return $this;
}
}