icinga2/lib/base/configobject.cpp

724 lines
17 KiB
C++
Raw Normal View History

/******************************************************************************
* Icinga 2 *
2018-10-18 03:27:04 -04:00
* Copyright (C) 2012-2018 Icinga Development Team (https://icinga.com/) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software Foundation *
2012-05-11 07:33:57 -04:00
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
#include "base/configobject.hpp"
2018-01-18 07:50:38 -05:00
#include "base/configobject-ti.cpp"
#include "base/configtype.hpp"
2014-05-25 10:23:35 -04:00
#include "base/serializer.hpp"
#include "base/netstring.hpp"
2014-10-26 14:59:49 -04:00
#include "base/json.hpp"
2014-05-25 10:23:35 -04:00
#include "base/stdiostream.hpp"
#include "base/debug.hpp"
#include "base/objectlock.hpp"
2014-10-19 08:21:12 -04:00
#include "base/logger.hpp"
2014-05-25 10:23:35 -04:00
#include "base/exception.hpp"
#include "base/function.hpp"
2014-05-25 10:23:35 -04:00
#include "base/initialize.hpp"
#include "base/workqueue.hpp"
#include "base/context.hpp"
#include "base/application.hpp"
2013-03-16 16:18:53 -04:00
#include <fstream>
2013-03-18 12:04:22 -04:00
#include <boost/exception/errinfo_api_function.hpp>
#include <boost/exception/errinfo_errno.hpp>
#include <boost/exception/errinfo_file_name.hpp>
using namespace icinga;
REGISTER_TYPE_WITH_PROTOTYPE(ConfigObject, ConfigObject::GetPrototype());
boost::signals2::signal<void (const ConfigObject::Ptr&)> ConfigObject::OnStateChanged;
bool ConfigObject::IsActive() const
{
2013-10-26 03:41:45 -04:00
return GetActive();
2013-09-12 04:03:48 -04:00
}
bool ConfigObject::IsPaused() const
{
return GetPaused();
}
void ConfigObject::SetExtension(const String& key, const Value& value)
{
2013-10-26 03:41:45 -04:00
Dictionary::Ptr extensions = GetExtensions();
if (!extensions) {
extensions = new Dictionary();
2013-10-26 03:41:45 -04:00
SetExtensions(extensions);
}
extensions->Set(key, value);
}
Value ConfigObject::GetExtension(const String& key)
{
2013-10-26 03:41:45 -04:00
Dictionary::Ptr extensions = GetExtensions();
if (!extensions)
return Empty;
return extensions->Get(key);
}
void ConfigObject::ClearExtension(const String& key)
{
2013-10-26 03:41:45 -04:00
Dictionary::Ptr extensions = GetExtensions();
if (!extensions)
return;
extensions->Remove(key);
}
2018-01-04 00:11:04 -05:00
class ModAttrValidationUtils final : public ValidationUtils
{
public:
bool ValidateName(const String& type, const String& name) const override
{
Type::Ptr ptype = Type::GetByName(type);
auto *dtype = dynamic_cast<ConfigType *>(ptype.get());
if (!dtype)
return false;
if (!dtype->GetObject(name))
return false;
return true;
}
};
void ConfigObject::ModifyAttribute(const String& attr, const Value& value, bool updateVersion)
{
Dictionary::Ptr original_attributes = GetOriginalAttributes();
bool updated_original_attributes = false;
Type::Ptr type = GetReflectionType();
2015-09-18 07:04:09 -04:00
2018-01-04 12:24:45 -05:00
std::vector<String> tokens = attr.Split(".");
2015-09-18 07:04:09 -04:00
String fieldName = tokens[0];
2015-09-18 07:04:09 -04:00
int fid = type->GetFieldId(fieldName);
Field field = type->GetFieldInfo(fid);
2015-09-18 07:04:09 -04:00
if (field.Attributes & FANoUserModify)
BOOST_THROW_EXCEPTION(std::invalid_argument("Attribute cannot be modified."));
if (field.Attributes & FAConfig) {
if (!original_attributes) {
original_attributes = new Dictionary();
SetOriginalAttributes(original_attributes, true);
}
}
2015-09-18 07:04:09 -04:00
Value oldValue = GetField(fid);
Value newValue;
2015-09-18 07:04:09 -04:00
if (tokens.size() > 1) {
newValue = oldValue.Clone();
Value current = newValue;
2015-09-18 07:04:09 -04:00
if (current.IsEmpty()) {
current = new Dictionary();
newValue = current;
}
2015-09-18 07:04:09 -04:00
String prefix = tokens[0];
for (std::vector<String>::size_type i = 1; i < tokens.size() - 1; i++) {
if (!current.IsObjectType<Dictionary>())
BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary."));
Dictionary::Ptr dict = current;
const String& key = tokens[i];
prefix += "." + key;
2015-09-18 07:04:09 -04:00
if (!dict->Get(key, &current)) {
current = new Dictionary();
dict->Set(key, current);
}
}
2015-09-18 07:04:09 -04:00
if (!current.IsObjectType<Dictionary>())
BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary."));
2015-09-18 07:04:09 -04:00
Dictionary::Ptr dict = current;
const String& key = tokens[tokens.size() - 1];
prefix += "." + key;
/* clone it for original attributes */
oldValue = dict->Get(key).Clone();
if (field.Attributes & FAConfig) {
updated_original_attributes = true;
if (oldValue.IsObjectType<Dictionary>()) {
Dictionary::Ptr oldDict = oldValue;
ObjectLock olock(oldDict);
for (const auto& kv : oldDict) {
String key = prefix + "." + kv.first;
if (!original_attributes->Contains(key))
original_attributes->Set(key, kv.second);
}
/* store the new value as null */
if (value.IsObjectType<Dictionary>()) {
Dictionary::Ptr valueDict = value;
ObjectLock olock(valueDict);
for (const auto& kv : valueDict) {
String key = attr + "." + kv.first;
if (!original_attributes->Contains(key))
original_attributes->Set(key, Empty);
}
}
} else if (!original_attributes->Contains(attr))
original_attributes->Set(attr, oldValue);
}
2015-09-18 07:04:09 -04:00
dict->Set(key, value);
} else {
newValue = value;
if (field.Attributes & FAConfig) {
if (!original_attributes->Contains(attr)) {
updated_original_attributes = true;
original_attributes->Set(attr, oldValue);
}
}
}
ModAttrValidationUtils utils;
ValidateField(fid, Lazy<Value>{newValue}, utils);
SetField(fid, newValue);
if (updateVersion && (field.Attributes & FAConfig))
SetVersion(Utility::GetTime());
if (updated_original_attributes)
NotifyOriginalAttributes();
}
void ConfigObject::RestoreAttribute(const String& attr, bool updateVersion)
{
Type::Ptr type = GetReflectionType();
2018-01-04 12:24:45 -05:00
std::vector<String> tokens = attr.Split(".");
String fieldName = tokens[0];
int fid = type->GetFieldId(fieldName);
Value currentValue = GetField(fid);
Dictionary::Ptr original_attributes = GetOriginalAttributes();
if (!original_attributes)
return;
Value oldValue = original_attributes->Get(attr);
Value newValue;
if (tokens.size() > 1) {
newValue = currentValue.Clone();
Value current = newValue;
if (current.IsEmpty())
2016-02-09 09:53:40 -05:00
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot restore non-existent object attribute"));
String prefix = tokens[0];
for (std::vector<String>::size_type i = 1; i < tokens.size() - 1; i++) {
if (!current.IsObjectType<Dictionary>())
BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary."));
Dictionary::Ptr dict = current;
const String& key = tokens[i];
prefix += "." + key;
if (!dict->Contains(key))
2016-02-09 09:53:40 -05:00
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot restore non-existent object attribute"));
current = dict->Get(key);
}
if (!current.IsObjectType<Dictionary>())
BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary."));
Dictionary::Ptr dict = current;
const String& key = tokens[tokens.size() - 1];
prefix += "." + key;
std::vector<String> restoredAttrs;
{
ObjectLock olock(original_attributes);
for (const auto& kv : original_attributes) {
2018-01-04 12:24:45 -05:00
std::vector<String> originalTokens = String(kv.first).Split(".");
if (tokens.size() > originalTokens.size())
continue;
bool match = true;
for (std::vector<String>::size_type i = 0; i < tokens.size(); i++) {
if (tokens[i] != originalTokens[i]) {
match = false;
break;
}
}
if (!match)
continue;
Dictionary::Ptr dict;
if (tokens.size() == originalTokens.size())
dict = current;
else {
Value currentSub = current;
for (std::vector<String>::size_type i = tokens.size() - 1; i < originalTokens.size() - 1; i++) {
dict = currentSub;
currentSub = dict->Get(originalTokens[i]);
if (!currentSub.IsObjectType<Dictionary>()) {
currentSub = new Dictionary();
dict->Set(originalTokens[i], currentSub);
}
}
dict = currentSub;
}
dict->Set(originalTokens[originalTokens.size() - 1], kv.second);
restoredAttrs.push_back(kv.first);
}
}
for (const String& attr : restoredAttrs)
original_attributes->Remove(attr);
} else {
newValue = oldValue;
}
original_attributes->Remove(attr);
SetField(fid, newValue);
if (updateVersion)
SetVersion(Utility::GetTime());
}
bool ConfigObject::IsAttributeModified(const String& attr) const
{
Dictionary::Ptr original_attributes = GetOriginalAttributes();
if (!original_attributes)
return false;
return original_attributes->Contains(attr);
}
void ConfigObject::Register()
{
ASSERT(!OwnsLock());
2013-03-01 06:07:52 -05:00
TypeImpl<ConfigObject>::Ptr type = static_pointer_cast<TypeImpl<ConfigObject> >(GetReflectionType());
type->RegisterObject(this);
}
void ConfigObject::Unregister()
{
ASSERT(!OwnsLock());
TypeImpl<ConfigObject>::Ptr type = static_pointer_cast<TypeImpl<ConfigObject> >(GetReflectionType());
type->UnregisterObject(this);
}
void ConfigObject::Start(bool runtimeCreated)
{
ObjectImpl<ConfigObject>::Start(runtimeCreated);
ObjectLock olock(this);
2013-03-01 06:07:52 -05:00
SetStartCalled(true);
}
void ConfigObject::PreActivate()
{
CONTEXT("Setting 'active' to true for object '" + GetName() + "' of type '" + GetReflectionType()->GetName() + "'");
ASSERT(!IsActive());
SetActive(true, true);
}
void ConfigObject::Activate(bool runtimeCreated)
{
CONTEXT("Activating object '" + GetName() + "' of type '" + GetReflectionType()->GetName() + "'");
{
ObjectLock olock(this);
Start(runtimeCreated);
ASSERT(GetStartCalled());
if (GetHAMode() == HARunEverywhere)
SetAuthority(true);
}
2015-09-18 07:04:09 -04:00
NotifyActive();
}
void ConfigObject::Stop(bool runtimeRemoved)
{
ObjectImpl<ConfigObject>::Stop(runtimeRemoved);
ObjectLock olock(this);
SetStopCalled(true);
}
void ConfigObject::Deactivate(bool runtimeRemoved)
{
CONTEXT("Deactivating object '" + GetName() + "' of type '" + GetReflectionType()->GetName() + "'");
{
ObjectLock olock(this);
if (!IsActive())
return;
SetActive(false, true);
SetAuthority(false);
Stop(runtimeRemoved);
}
2013-03-02 03:07:47 -05:00
ASSERT(GetStopCalled());
NotifyActive();
}
void ConfigObject::OnConfigLoaded()
{
/* Nothing to do here. */
}
void ConfigObject::OnAllConfigLoaded()
{
static ConfigType *ctype;
if (!ctype) {
Type::Ptr type = Type::GetByName("Zone");
ctype = dynamic_cast<ConfigType *>(type.get());
}
String zoneName = GetZoneName();
if (!zoneName.IsEmpty())
m_Zone = ctype->GetObject(zoneName);
}
void ConfigObject::CreateChildObjects(const Type::Ptr& childType)
{
/* Nothing to do here. */
}
void ConfigObject::OnStateLoaded()
{
/* Nothing to do here. */
}
void ConfigObject::Pause()
{
SetPauseCalled(true);
}
void ConfigObject::Resume()
{
SetResumeCalled(true);
}
void ConfigObject::SetAuthority(bool authority)
{
ObjectLock olock(this);
if (authority && GetPaused()) {
SetResumeCalled(false);
Resume();
ASSERT(GetResumeCalled());
SetPaused(false);
} else if (!authority && !GetPaused()) {
SetPaused(true);
SetPauseCalled(false);
Pause();
ASSERT(GetPauseCalled());
}
}
void ConfigObject::DumpObjects(const String& filename, int attributeTypes)
2012-07-24 07:13:02 -04:00
{
Log(LogInformation, "ConfigObject")
<< "Dumping program state to file '" << filename << "'";
2012-07-24 07:13:02 -04:00
2013-03-16 16:18:53 -04:00
std::fstream fp;
String tempFilename = Utility::CreateTempFile(filename + ".XXXXXX", 0600, fp);
fp.exceptions(std::ofstream::failbit | std::ofstream::badbit);
2012-07-24 07:13:02 -04:00
if (!fp)
BOOST_THROW_EXCEPTION(std::runtime_error("Could not open '" + tempFilename + "' file"));
2012-07-24 07:13:02 -04:00
StdioStream::Ptr sfp = new StdioStream(&fp, false);
2012-07-24 07:13:02 -04:00
for (const Type::Ptr& type : Type::GetAllTypes()) {
auto *dtype = dynamic_cast<ConfigType *>(type.get());
if (!dtype)
continue;
for (const ConfigObject::Ptr& object : dtype->GetObjects()) {
Dictionary::Ptr update = Serialize(object, attributeTypes);
if (!update)
continue;
Dictionary::Ptr persistentObject = new Dictionary({
{ "type", type->GetName() },
{ "name", object->GetName() },
{ "update", update }
});
2012-07-24 07:13:02 -04:00
2014-10-26 14:59:49 -04:00
String json = JsonEncode(persistentObject);
2012-07-24 07:13:02 -04:00
NetString::WriteStringToStream(sfp, json);
2012-07-24 07:13:02 -04:00
}
}
sfp->Close();
2012-11-22 06:04:32 -05:00
fp.close();
#ifdef _WIN32
_unlink(filename.CStr());
#endif /* _WIN32 */
2013-03-11 08:45:08 -04:00
if (rename(tempFilename.CStr(), filename.CStr()) < 0) {
BOOST_THROW_EXCEPTION(posix_error()
<< boost::errinfo_api_function("rename")
<< boost::errinfo_errno(errno)
<< boost::errinfo_file_name(tempFilename));
2013-03-11 08:45:08 -04:00
}
2012-07-24 07:13:02 -04:00
}
void ConfigObject::RestoreObject(const String& message, int attributeTypes)
{
2014-10-26 14:59:49 -04:00
Dictionary::Ptr persistentObject = JsonDecode(message);
String type = persistentObject->Get("type");
String name = persistentObject->Get("name");
ConfigObject::Ptr object = GetObject(type, name);
if (!object)
return;
2014-12-19 06:19:28 -05:00
#ifdef I2_DEBUG
Log(LogDebug, "ConfigObject")
<< "Restoring object '" << name << "' of type '" << type << "'.";
2014-12-19 06:19:28 -05:00
#endif /* I2_DEBUG */
Dictionary::Ptr update = persistentObject->Get("update");
Deserialize(object, update, false, attributeTypes);
object->OnStateLoaded();
object->SetStateLoaded(true);
}
void ConfigObject::RestoreObjects(const String& filename, int attributeTypes)
2012-07-24 07:13:02 -04:00
{
if (!Utility::PathExists(filename))
return;
Log(LogInformation, "ConfigObject")
<< "Restoring program state from file '" << filename << "'";
2012-07-24 07:13:02 -04:00
std::fstream fp;
fp.open(filename.CStr(), std::ios_base::in);
2012-07-24 07:13:02 -04:00
StdioStream::Ptr sfp = new StdioStream (&fp, false);
2012-07-24 07:13:02 -04:00
unsigned long restored = 0;
2018-08-09 09:37:23 -04:00
WorkQueue upq(25000, Configuration::Concurrency);
upq.SetName("ConfigObject::RestoreObjects");
String message;
StreamReadContext src;
for (;;) {
StreamReadStatus srs = NetString::ReadStringFromStream(sfp, &message, src);
if (srs == StatusEof)
break;
if (srs != StatusNewItem)
continue;
upq.Enqueue(std::bind(&ConfigObject::RestoreObject, message, attributeTypes));
restored++;
2012-07-24 07:13:02 -04:00
}
2012-11-22 06:04:32 -05:00
sfp->Close();
upq.Join();
unsigned long no_state = 0;
for (const Type::Ptr& type : Type::GetAllTypes()) {
auto *dtype = dynamic_cast<ConfigType *>(type.get());
if (!dtype)
continue;
for (const ConfigObject::Ptr& object : dtype->GetObjects()) {
if (!object->GetStateLoaded()) {
object->OnStateLoaded();
object->SetStateLoaded(true);
no_state++;
}
}
}
Log(LogInformation, "ConfigObject")
<< "Restored " << restored << " objects. Loaded " << no_state << " new objects without state.";
2012-07-24 07:13:02 -04:00
}
void ConfigObject::StopObjects()
{
for (const Type::Ptr& type : Type::GetAllTypes()) {
auto *dtype = dynamic_cast<ConfigType *>(type.get());
if (!dtype)
continue;
for (const ConfigObject::Ptr& object : dtype->GetObjects()) {
object->Deactivate();
}
}
}
void ConfigObject::DumpModifiedAttributes(const std::function<void(const ConfigObject::Ptr&, const String&, const Value&)>& callback)
{
for (const Type::Ptr& type : Type::GetAllTypes()) {
auto *dtype = dynamic_cast<ConfigType *>(type.get());
if (!dtype)
continue;
for (const ConfigObject::Ptr& object : dtype->GetObjects()) {
Dictionary::Ptr originalAttributes = object->GetOriginalAttributes();
if (!originalAttributes)
continue;
ObjectLock olock(originalAttributes);
for (const Dictionary::Pair& kv : originalAttributes) {
String key = kv.first;
Type::Ptr type = object->GetReflectionType();
2018-01-04 12:24:45 -05:00
std::vector<String> tokens = key.Split(".");
String fieldName = tokens[0];
int fid = type->GetFieldId(fieldName);
Value currentValue = object->GetField(fid);
Value modifiedValue;
if (tokens.size() > 1) {
Value current = currentValue;
for (std::vector<String>::size_type i = 1; i < tokens.size() - 1; i++) {
if (!current.IsObjectType<Dictionary>())
BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary."));
Dictionary::Ptr dict = current;
const String& key = tokens[i];
if (!dict->Contains(key))
break;
current = dict->Get(key);
}
if (!current.IsObjectType<Dictionary>())
BOOST_THROW_EXCEPTION(std::invalid_argument("Value must be a dictionary."));
Dictionary::Ptr dict = current;
const String& key = tokens[tokens.size() - 1];
modifiedValue = dict->Get(key);
} else
modifiedValue = currentValue;
callback(object, key, modifiedValue);
}
}
}
}
ConfigObject::Ptr ConfigObject::GetObject(const String& type, const String& name)
{
Type::Ptr ptype = Type::GetByName(type);
auto *ctype = dynamic_cast<ConfigType *>(ptype.get());
if (!ctype)
2017-11-30 02:36:35 -05:00
return nullptr;
return ctype->GetObject(name);
}
ConfigObject::Ptr ConfigObject::GetZone() const
{
return m_Zone;
}
Dictionary::Ptr ConfigObject::GetSourceLocation() const
{
DebugInfo di = GetDebugInfo();
return new Dictionary({
{ "path", di.Path },
{ "first_line", di.FirstLine },
{ "first_column", di.FirstColumn },
{ "last_line", di.LastLine },
{ "last_column", di.LastColumn }
});
}
NameComposer::~NameComposer()
{ }