Merge pull request #5983 from Icinga/feature/initializer-lists

Use initializer lists for arrays and dictionaries
This commit is contained in:
Gunnar Beutner 2018-01-16 12:40:29 +01:00 committed by GitHub
commit d591cca701
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
113 changed files with 1675 additions and 1733 deletions

View File

@ -400,24 +400,24 @@ pid_t Application::StartReloadProcess()
Log(LogInformation, "Application", "Got reload command: Starting new instance."); Log(LogInformation, "Application", "Got reload command: Starting new instance.");
// prepare arguments // prepare arguments
Array::Ptr args = new Array(); ArrayData args;
args->Add(GetExePath(m_ArgV[0])); args.push_back(GetExePath(m_ArgV[0]));
for (int i=1; i < Application::GetArgC(); i++) { for (int i=1; i < Application::GetArgC(); i++) {
if (std::string(Application::GetArgV()[i]) != "--reload-internal") if (std::string(Application::GetArgV()[i]) != "--reload-internal")
args->Add(Application::GetArgV()[i]); args.push_back(Application::GetArgV()[i]);
else else
i++; // the next parameter after --reload-internal is the pid, remove that too i++; // the next parameter after --reload-internal is the pid, remove that too
} }
#ifndef _WIN32 #ifndef _WIN32
args->Add("--reload-internal"); args.push_back("--reload-internal");
args->Add(Convert::ToString(Utility::GetPid())); args.push_back(Convert::ToString(Utility::GetPid()));
#else /* _WIN32 */ #else /* _WIN32 */
args->Add("--validate"); args.push_back("--validate");
#endif /* _WIN32 */ #endif /* _WIN32 */
Process::Ptr process = new Process(Process::PrepareCommand(args)); Process::Ptr process = new Process(Process::PrepareCommand(new Array(std::move(args))));
process->SetTimeout(300); process->SetTimeout(300);
process->Run(&ReloadProcessCallback); process->Run(&ReloadProcessCallback);

View File

@ -147,14 +147,14 @@ static Array::Ptr ArrayMap(const Function::Ptr& function)
if (vframe->Sandboxed && !function->IsSideEffectFree()) if (vframe->Sandboxed && !function->IsSideEffectFree())
BOOST_THROW_EXCEPTION(ScriptError("Map function must be side-effect free.")); BOOST_THROW_EXCEPTION(ScriptError("Map function must be side-effect free."));
Array::Ptr result = new Array(); ArrayData result;
ObjectLock olock(self); ObjectLock olock(self);
for (const Value& item : self) { for (const Value& item : self) {
result->Add(function->Invoke({ item })); result.push_back(function->Invoke({ item }));
} }
return result; return new Array(std::move(result));
} }
static Value ArrayReduce(const Function::Ptr& function) static Value ArrayReduce(const Function::Ptr& function)
@ -186,15 +186,15 @@ static Array::Ptr ArrayFilter(const Function::Ptr& function)
if (vframe->Sandboxed && !function->IsSideEffectFree()) if (vframe->Sandboxed && !function->IsSideEffectFree())
BOOST_THROW_EXCEPTION(ScriptError("Filter function must be side-effect free.")); BOOST_THROW_EXCEPTION(ScriptError("Filter function must be side-effect free."));
Array::Ptr result = new Array(); ArrayData result;
ObjectLock olock(self); ObjectLock olock(self);
for (const Value& item : self) { for (const Value& item : self) {
if (function->Invoke({ item })) if (function->Invoke({ item }))
result->Add(item); result.push_back(item);
} }
return result; return new Array(std::move(result));
} }
static bool ArrayAny(const Function::Ptr& function) static bool ArrayAny(const Function::Ptr& function)
@ -247,28 +247,25 @@ static Array::Ptr ArrayUnique()
Object::Ptr Array::GetPrototype() Object::Ptr Array::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "len", new Function("Array#len", ArrayLen, {}, true) },
if (!prototype) { { "set", new Function("Array#set", ArraySet, { "index", "value" }) },
prototype = new Dictionary(); { "get", new Function("Array#get", ArrayGet, { "index" }) },
prototype->Set("len", new Function("Array#len", ArrayLen, {}, true)); { "add", new Function("Array#add", ArrayAdd, { "value" }) },
prototype->Set("set", new Function("Array#set", ArraySet, { "index", "value" })); { "remove", new Function("Array#remove", ArrayRemove, { "index" }) },
prototype->Set("get", new Function("Array#get", ArrayGet, { "index" })); { "contains", new Function("Array#contains", ArrayContains, { "value" }, true) },
prototype->Set("add", new Function("Array#add", ArrayAdd, { "value" })); { "clear", new Function("Array#clear", ArrayClear) },
prototype->Set("remove", new Function("Array#remove", ArrayRemove, { "index" })); { "sort", new Function("Array#sort", ArraySort, { "less_cmp" }, true) },
prototype->Set("contains", new Function("Array#contains", ArrayContains, { "value" }, true)); { "shallow_clone", new Function("Array#shallow_clone", ArrayShallowClone, {}, true) },
prototype->Set("clear", new Function("Array#clear", ArrayClear)); { "join", new Function("Array#join", ArrayJoin, { "separator" }, true) },
prototype->Set("sort", new Function("Array#sort", ArraySort, { "less_cmp" }, true)); { "reverse", new Function("Array#reverse", ArrayReverse, {}, true) },
prototype->Set("shallow_clone", new Function("Array#shallow_clone", ArrayShallowClone, {}, true)); { "map", new Function("Array#map", ArrayMap, { "func" }, true) },
prototype->Set("join", new Function("Array#join", ArrayJoin, { "separator" }, true)); { "reduce", new Function("Array#reduce", ArrayReduce, { "reduce" }, true) },
prototype->Set("reverse", new Function("Array#reverse", ArrayReverse, {}, true)); { "filter", new Function("Array#filter", ArrayFilter, { "func" }, true) },
prototype->Set("map", new Function("Array#map", ArrayMap, { "func" }, true)); { "any", new Function("Array#any", ArrayAny, { "func" }, true) },
prototype->Set("reduce", new Function("Array#reduce", ArrayReduce, { "reduce" }, true)); { "all", new Function("Array#all", ArrayAll, { "func" }, true) },
prototype->Set("filter", new Function("Array#filter", ArrayFilter, { "func" }, true)); { "unique", new Function("Array#unique", ArrayUnique, {}, true) }
prototype->Set("any", new Function("Array#any", ArrayAny, { "func" }, true)); });
prototype->Set("all", new Function("Array#all", ArrayAll, { "func" }, true));
prototype->Set("unique", new Function("Array#unique", ArrayUnique, {}, true));
}
return prototype; return prototype;
} }

View File

@ -32,6 +32,14 @@ template class std::vector<Value>;
REGISTER_PRIMITIVE_TYPE(Array, Object, Array::GetPrototype()); REGISTER_PRIMITIVE_TYPE(Array, Object, Array::GetPrototype());
Array::Array(const ArrayData& other)
: m_Data(other)
{ }
Array::Array(ArrayData&& other)
: m_Data(std::move(other))
{ }
Array::Array(std::initializer_list<Value> init) Array::Array(std::initializer_list<Value> init)
: m_Data(init) : m_Data(init)
{ } { }
@ -228,14 +236,14 @@ Array::Ptr Array::ShallowClone() const
*/ */
Object::Ptr Array::Clone() const Object::Ptr Array::Clone() const
{ {
Array::Ptr arr = new Array(); ArrayData arr;
ObjectLock olock(this); ObjectLock olock(this);
for (const Value& val : m_Data) { for (const Value& val : m_Data) {
arr->Add(val.Clone()); arr.push_back(val.Clone());
} }
return arr; return new Array(std::move(arr));
} }
Array::Ptr Array::Reverse() const Array::Ptr Array::Reverse() const
@ -305,4 +313,3 @@ Array::Iterator icinga::end(const Array::Ptr& x)
{ {
return x->End(); return x->End();
} }

View File

@ -30,6 +30,8 @@
namespace icinga namespace icinga
{ {
typedef std::vector<Value> ArrayData;
/** /**
* An array of Value items. * An array of Value items.
* *
@ -48,6 +50,8 @@ public:
typedef std::vector<Value>::size_type SizeType; typedef std::vector<Value>::size_type SizeType;
Array() = default; Array() = default;
Array(const ArrayData& other);
Array(ArrayData&& other);
Array(std::initializer_list<Value> init); Array(std::initializer_list<Value> init);
Value Get(SizeType index) const; Value Get(SizeType index) const;

View File

@ -34,12 +34,9 @@ static String BooleanToString()
Object::Ptr Boolean::GetPrototype() Object::Ptr Boolean::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "to_string", new Function("Boolean#to_string", BooleanToString, {}, true) }
if (!prototype) { });
prototype = new Dictionary();
prototype->Set("to_string", new Function("Boolean#to_string", BooleanToString, {}, true));
}
return prototype; return prototype;
} }

View File

@ -41,13 +41,10 @@ static void ConfigObjectRestoreAttribute(const String& attr)
Object::Ptr ConfigObject::GetPrototype() Object::Ptr ConfigObject::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "modify_attribute", new Function("ConfigObject#modify_attribute", ConfigObjectModifyAttribute, { "attr", "value" }, false) },
if (!prototype) { { "restore_attribute", new Function("ConfigObject#restore_attribute", ConfigObjectRestoreAttribute, { "attr", "value" }, false) }
prototype = new Dictionary(); });
prototype->Set("modify_attribute", new Function("ConfigObject#modify_attribute", ConfigObjectModifyAttribute, { "attr", "value" }, false));
prototype->Set("restore_attribute", new Function("ConfigObject#restore_attribute", ConfigObjectRestoreAttribute, { "attr", "value" }, false));
}
return prototype; return prototype;
} }

View File

@ -506,17 +506,16 @@ void ConfigObject::DumpObjects(const String& filename, int attributeTypes)
continue; continue;
for (const ConfigObject::Ptr& object : dtype->GetObjects()) { for (const ConfigObject::Ptr& object : dtype->GetObjects()) {
Dictionary::Ptr persistentObject = new Dictionary();
persistentObject->Set("type", type->GetName());
persistentObject->Set("name", object->GetName());
Dictionary::Ptr update = Serialize(object, attributeTypes); Dictionary::Ptr update = Serialize(object, attributeTypes);
if (!update) if (!update)
continue; continue;
persistentObject->Set("update", update); Dictionary::Ptr persistentObject = new Dictionary({
{ "type", type->GetName() },
{ "name", object->GetName() },
{ "update", update }
});
String json = JsonEncode(persistentObject); String json = JsonEncode(persistentObject);
@ -717,13 +716,13 @@ Dictionary::Ptr ConfigObject::GetSourceLocation() const
{ {
DebugInfo di = GetDebugInfo(); DebugInfo di = GetDebugInfo();
Dictionary::Ptr result = new Dictionary(); return new Dictionary({
result->Set("path", di.Path); { "path", di.Path },
result->Set("first_line", di.FirstLine); { "first_line", di.FirstLine },
result->Set("first_column", di.FirstColumn); { "first_column", di.FirstColumn },
result->Set("last_line", di.LastLine); { "last_line", di.LastLine },
result->Set("last_column", di.LastColumn); { "last_column", di.LastColumn }
return result; });
} }
NameComposer::~NameComposer() NameComposer::~NameComposer()

View File

@ -35,12 +35,9 @@ static String DateTimeFormat(const String& format)
Object::Ptr DateTime::GetPrototype() Object::Ptr DateTime::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "format", new Function("DateTime#format", DateTimeFormat, { "format" }) }
if (!prototype) { });
prototype = new Dictionary();
prototype->Set("format", new Function("DateTime#format", DateTimeFormat, { "format" }));
}
return prototype; return prototype;
} }

View File

@ -71,41 +71,38 @@ static Array::Ptr DictionaryKeys()
{ {
ScriptFrame *vframe = ScriptFrame::GetCurrentFrame(); ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
Dictionary::Ptr self = static_cast<Dictionary::Ptr>(vframe->Self); Dictionary::Ptr self = static_cast<Dictionary::Ptr>(vframe->Self);
Array::Ptr keys = new Array(); ArrayData keys;
ObjectLock olock(self); ObjectLock olock(self);
for (const Dictionary::Pair& kv : self) { for (const Dictionary::Pair& kv : self) {
keys->Add(kv.first); keys.push_back(kv.first);
} }
return keys; return new Array(std::move(keys));
} }
static Array::Ptr DictionaryValues() static Array::Ptr DictionaryValues()
{ {
ScriptFrame *vframe = ScriptFrame::GetCurrentFrame(); ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
Dictionary::Ptr self = static_cast<Dictionary::Ptr>(vframe->Self); Dictionary::Ptr self = static_cast<Dictionary::Ptr>(vframe->Self);
Array::Ptr keys = new Array(); ArrayData values;
ObjectLock olock(self); ObjectLock olock(self);
for (const Dictionary::Pair& kv : self) { for (const Dictionary::Pair& kv : self) {
keys->Add(kv.second); values.push_back(kv.second);
} }
return keys; return new Array(std::move(values));
} }
Object::Ptr Dictionary::GetPrototype() Object::Ptr Dictionary::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "len", new Function("Dictionary#len", DictionaryLen, {}, true) },
if (!prototype) { { "set", new Function("Dictionary#set", DictionarySet, { "key", "value" }) },
prototype = new Dictionary(); { "get", new Function("Dictionary#get", DictionaryGet, { "key" }) },
prototype->Set("len", new Function("Dictionary#len", DictionaryLen, {}, true)); { "remove", new Function("Dictionary#remove", DictionaryRemove, { "key" }) },
prototype->Set("set", new Function("Dictionary#set", DictionarySet, { "key", "value" })); { "contains", new Function("Dictionary#contains", DictionaryContains, { "key" }, true) },
prototype->Set("get", new Function("Dictionary#get", DictionaryGet, { "key" })); { "shallow_clone", new Function("Dictionary#shallow_clone", DictionaryShallowClone, {}, true) },
prototype->Set("remove", new Function("Dictionary#remove", DictionaryRemove, { "key" })); { "keys", new Function("Dictionary#keys", DictionaryKeys, {}, true) },
prototype->Set("contains", new Function("Dictionary#contains", DictionaryContains, { "key" }, true)); { "values", new Function("Dictionary#values", DictionaryValues, {}, true) }
prototype->Set("shallow_clone", new Function("Dictionary#shallow_clone", DictionaryShallowClone, {}, true)); });
prototype->Set("keys", new Function("Dictionary#keys", DictionaryKeys, {}, true));
prototype->Set("values", new Function("Dictionary#values", DictionaryValues, {}, true));
}
return prototype; return prototype;
} }

View File

@ -29,6 +29,22 @@ template class std::map<String, Value>;
REGISTER_PRIMITIVE_TYPE(Dictionary, Object, Dictionary::GetPrototype()); REGISTER_PRIMITIVE_TYPE(Dictionary, Object, Dictionary::GetPrototype());
Dictionary::Dictionary(const DictionaryData& other)
{
for (const auto& kv : other)
m_Data.emplace(kv);
}
Dictionary::Dictionary(DictionaryData&& other)
{
for (auto& kv : other)
m_Data.emplace(std::move(kv));
}
Dictionary::Dictionary(std::initializer_list<Dictionary::Pair> init)
: m_Data(init)
{ }
/** /**
* Retrieves a value from a dictionary. * Retrieves a value from a dictionary.
* *
@ -202,14 +218,19 @@ Dictionary::Ptr Dictionary::ShallowClone() const
*/ */
Object::Ptr Dictionary::Clone() const Object::Ptr Dictionary::Clone() const
{ {
Dictionary::Ptr dict = new Dictionary(); DictionaryData dict;
{
ObjectLock olock(this); ObjectLock olock(this);
dict.reserve(GetLength());
for (const Dictionary::Pair& kv : m_Data) { for (const Dictionary::Pair& kv : m_Data) {
dict->Set(kv.first, kv.second.Clone()); dict.emplace_back(kv.first, kv.second.Clone());
}
} }
return dict; return new Dictionary(std::move(dict));
} }
/** /**

View File

@ -30,6 +30,8 @@
namespace icinga namespace icinga
{ {
typedef std::vector<std::pair<String, Value> > DictionaryData;
/** /**
* A container that holds key-value pairs. * A container that holds key-value pairs.
* *
@ -49,6 +51,11 @@ public:
typedef std::map<String, Value>::value_type Pair; typedef std::map<String, Value>::value_type Pair;
Dictionary() = default;
Dictionary(const DictionaryData& other);
Dictionary(DictionaryData&& other);
Dictionary(std::initializer_list<Pair> init);
Value Get(const String& key) const; Value Get(const String& key) const;
bool Get(const String& key, Value *result) const; bool Get(const String& key, Value *result) const;
void Set(const String& key, Value value); void Set(const String& key, Value value);

View File

@ -32,13 +32,13 @@ REGISTER_STATSFUNCTION(FileLogger, &FileLogger::StatsFunc);
void FileLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) void FileLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const FileLogger::Ptr& filelogger : ConfigType::GetObjectsByType<FileLogger>()) { for (const FileLogger::Ptr& filelogger : ConfigType::GetObjectsByType<FileLogger>()) {
nodes->Set(filelogger->GetName(), 1); //add more stats nodes.emplace_back(filelogger->GetName(), 1); //add more stats
} }
status->Set("filelogger", nodes); status->Set("filelogger", new Dictionary(std::move(nodes)));
} }
/** /**

View File

@ -55,13 +55,10 @@ static Value FunctionCallV(const Value& thisArg, const Array::Ptr& args)
Object::Ptr Function::GetPrototype() Object::Ptr Function::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "call", new Function("Function#call", FunctionCall) },
if (!prototype) { { "callv", new Function("Function#callv", FunctionCallV) }
prototype = new Dictionary(); });
prototype->Set("call", new Function("Function#call", FunctionCall));
prototype->Set("callv", new Function("Function#callv", FunctionCallV));
}
return prototype; return prototype;
} }

View File

@ -32,11 +32,11 @@ static String JsonEncodeShim(const Value& value)
} }
INITIALIZE_ONCE([]() { INITIALIZE_ONCE([]() {
Dictionary::Ptr jsonObj = new Dictionary(); Dictionary::Ptr jsonObj = new Dictionary({
/* Methods */ /* Methods */
jsonObj->Set("encode", new Function("Json#encode", JsonEncodeShim, { "value" }, true)); { "encode", new Function("Json#encode", JsonEncodeShim, { "value" }, true) },
jsonObj->Set("decode", new Function("Json#decode", JsonDecode, { "value" }, true)); { "decode", new Function("Json#decode", JsonDecode, { "value" }, true) }
});
ScriptGlobal::Set("Json", jsonObj); ScriptGlobal::Set("Json", jsonObj);
}); });

View File

@ -158,40 +158,40 @@ static double MathSign(double x)
} }
INITIALIZE_ONCE([]() { INITIALIZE_ONCE([]() {
Dictionary::Ptr mathObj = new Dictionary(); Dictionary::Ptr mathObj = new Dictionary({
/* Constants */ /* Constants */
mathObj->Set("E", 2.71828182845904523536); { "E", 2.71828182845904523536 },
mathObj->Set("LN2", 0.693147180559945309417); { "LN2", 0.693147180559945309417 },
mathObj->Set("LN10", 2.30258509299404568402); { "LN10", 2.30258509299404568402 },
mathObj->Set("LOG2E", 1.44269504088896340736); { "LOG2E", 1.44269504088896340736 },
mathObj->Set("LOG10E", 0.434294481903251827651); { "LOG10E", 0.434294481903251827651 },
mathObj->Set("PI", 3.14159265358979323846); { "PI", 3.14159265358979323846 },
mathObj->Set("SQRT1_2", 0.707106781186547524401); { "SQRT1_2", 0.707106781186547524401 },
mathObj->Set("SQRT2", 1.41421356237309504880); { "SQRT2", 1.41421356237309504880 },
/* Methods */ /* Methods */
mathObj->Set("abs", new Function("Math#abs", MathAbs, { "x" }, true)); { "abs", new Function("Math#abs", MathAbs, { "x" }, true) },
mathObj->Set("acos", new Function("Math#acos", MathAcos, { "x" }, true)); { "acos", new Function("Math#acos", MathAcos, { "x" }, true) },
mathObj->Set("asin", new Function("Math#asin", MathAsin, { "x" }, true)); { "asin", new Function("Math#asin", MathAsin, { "x" }, true) },
mathObj->Set("atan", new Function("Math#atan", MathAtan, { "x" }, true)); { "atan", new Function("Math#atan", MathAtan, { "x" }, true) },
mathObj->Set("atan2", new Function("Math#atan2", MathAtan2, { "x", "y" }, true)); { "atan2", new Function("Math#atan2", MathAtan2, { "x", "y" }, true) },
mathObj->Set("ceil", new Function("Math#ceil", MathCeil, { "x" }, true)); { "ceil", new Function("Math#ceil", MathCeil, { "x" }, true) },
mathObj->Set("cos", new Function("Math#cos", MathCos, { "x" }, true)); { "cos", new Function("Math#cos", MathCos, { "x" }, true) },
mathObj->Set("exp", new Function("Math#exp", MathExp, { "x" }, true)); { "exp", new Function("Math#exp", MathExp, { "x" }, true) },
mathObj->Set("floor", new Function("Math#floor", MathFloor, { "x" }, true)); { "floor", new Function("Math#floor", MathFloor, { "x" }, true) },
mathObj->Set("log", new Function("Math#log", MathLog, { "x" }, true)); { "log", new Function("Math#log", MathLog, { "x" }, true) },
mathObj->Set("max", new Function("Math#max", MathMax, {}, true)); { "max", new Function("Math#max", MathMax, {}, true) },
mathObj->Set("min", new Function("Math#min", MathMin, {}, true)); { "min", new Function("Math#min", MathMin, {}, true) },
mathObj->Set("pow", new Function("Math#pow", MathPow, { "x", "y" }, true)); { "pow", new Function("Math#pow", MathPow, { "x", "y" }, true) },
mathObj->Set("random", new Function("Math#random", MathRandom, {}, true)); { "random", new Function("Math#random", MathRandom, {}, true) },
mathObj->Set("round", new Function("Math#round", MathRound, { "x" }, true)); { "round", new Function("Math#round", MathRound, { "x" }, true) },
mathObj->Set("sin", new Function("Math#sin", MathSin, { "x" }, true)); { "sin", new Function("Math#sin", MathSin, { "x" }, true) },
mathObj->Set("sqrt", new Function("Math#sqrt", MathSqrt, { "x" }, true)); { "sqrt", new Function("Math#sqrt", MathSqrt, { "x" }, true) },
mathObj->Set("tan", new Function("Math#tan", MathTan, { "x" }, true)); { "tan", new Function("Math#tan", MathTan, { "x" }, true) },
mathObj->Set("isnan", new Function("Math#isnan", MathIsnan, { "x" }, true)); { "isnan", new Function("Math#isnan", MathIsnan, { "x" }, true) },
mathObj->Set("isinf", new Function("Math#isinf", MathIsinf, { "x" }, true)); { "isinf", new Function("Math#isinf", MathIsinf, { "x" }, true) },
mathObj->Set("sign", new Function("Math#sign", MathSign, { "x" }, true)); { "sign", new Function("Math#sign", MathSign, { "x" }, true) }
});
ScriptGlobal::Set("Math", mathObj); ScriptGlobal::Set("Math", mathObj);
}); });

View File

@ -33,12 +33,9 @@ static String NumberToString()
Object::Ptr Number::GetPrototype() Object::Ptr Number::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "to_string", new Function("Number#to_string", NumberToString, {}, true) }
if (!prototype) { });
prototype = new Dictionary();
prototype->Set("to_string", new Function("Number#to_string", NumberToString, {}, true));
}
return prototype; return prototype;
} }

View File

@ -48,14 +48,11 @@ static Object::Ptr ObjectClone()
Object::Ptr Object::GetPrototype() Object::Ptr Object::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "to_string", new Function("Object#to_string", ObjectToString, {}, true) },
if (!prototype) { { "notify_attribute", new Function("Object#notify_attribute", ObjectNotifyAttribute, { "attribute" }, false) },
prototype = new Dictionary(); { "clone", new Function("Object#clone", ObjectClone, {}, true) }
prototype->Set("to_string", new Function("Object#to_string", ObjectToString, {}, true)); });
prototype->Set("notify_attribute", new Function("Object#notify_attribute", ObjectNotifyAttribute, { "attribute" }, false));
prototype->Set("clone", new Function("Object#clone", ObjectClone, {}, true));
}
return prototype; return prototype;
} }

View File

@ -201,10 +201,11 @@ static Value ProcessSpawnImpl(struct msghdr *msgh, const Dictionary::Ptr& reques
delete[] envp; delete[] envp;
Dictionary::Ptr response = new Dictionary(); Dictionary::Ptr response = new Dictionary({
response->Set("rc", pid); { "rc", pid },
if (errorCode) { "errno", errorCode }
response->Set("errno", errorCode); });
return response; return response;
} }
@ -217,8 +218,9 @@ static Value ProcessKillImpl(struct msghdr *msgh, const Dictionary::Ptr& request
kill(pid, signum); kill(pid, signum);
int error = errno; int error = errno;
Dictionary::Ptr response = new Dictionary(); Dictionary::Ptr response = new Dictionary({
response->Set("errno", error); { "errno", error }
});
return response; return response;
} }
@ -230,9 +232,10 @@ static Value ProcessWaitPIDImpl(struct msghdr *msgh, const Dictionary::Ptr& requ
int status; int status;
int rc = waitpid(pid, &status, 0); int rc = waitpid(pid, &status, 0);
Dictionary::Ptr response = new Dictionary(); Dictionary::Ptr response = new Dictionary({
response->Set("status", status); { "status", status },
response->Set("rc", rc); { "rc", rc }
});
return response; return response;
} }
@ -375,11 +378,12 @@ static void StartSpawnProcessHelper()
static pid_t ProcessSpawn(const std::vector<String>& arguments, const Dictionary::Ptr& extraEnvironment, bool adjustPriority, int fds[3]) static pid_t ProcessSpawn(const std::vector<String>& arguments, const Dictionary::Ptr& extraEnvironment, bool adjustPriority, int fds[3])
{ {
Dictionary::Ptr request = new Dictionary(); Dictionary::Ptr request = new Dictionary({
request->Set("command", "spawn"); { "command", "spawn" },
request->Set("arguments", Array::FromVector(arguments)); { "arguments", Array::FromVector(arguments) },
request->Set("extraEnvironment", extraEnvironment); { "extraEnvironment", extraEnvironment },
request->Set("adjustPriority", adjustPriority); { "adjustPriority", adjustPriority }
});
String jrequest = JsonEncode(request); String jrequest = JsonEncode(request);
size_t length = jrequest.GetLength(); size_t length = jrequest.GetLength();
@ -435,10 +439,11 @@ send_message:
static int ProcessKill(pid_t pid, int signum) static int ProcessKill(pid_t pid, int signum)
{ {
Dictionary::Ptr request = new Dictionary(); Dictionary::Ptr request = new Dictionary({
request->Set("command", "kill"); { "command", "kill" },
request->Set("pid", pid); { "pid", pid },
request->Set("signum", signum); { "signum", signum }
});
String jrequest = JsonEncode(request); String jrequest = JsonEncode(request);
size_t length = jrequest.GetLength(); size_t length = jrequest.GetLength();
@ -467,9 +472,10 @@ send_message:
static int ProcessWaitPID(pid_t pid, int *status) static int ProcessWaitPID(pid_t pid, int *status)
{ {
Dictionary::Ptr request = new Dictionary(); Dictionary::Ptr request = new Dictionary({
request->Set("command", "waitpid"); { "command", "waitpid" },
request->Set("pid", pid); { "pid", pid }
});
String jrequest = JsonEncode(request); String jrequest = JsonEncode(request);
size_t length = jrequest.GetLength(); size_t length = jrequest.GetLength();

View File

@ -105,16 +105,15 @@ void ScriptGlobal::WriteToFile(const String& filename)
ObjectLock olock(m_Globals); ObjectLock olock(m_Globals);
for (const Dictionary::Pair& kv : m_Globals) { for (const Dictionary::Pair& kv : m_Globals) {
Dictionary::Ptr persistentVariable = new Dictionary();
persistentVariable->Set("name", kv.first);
Value value = kv.second; Value value = kv.second;
if (value.IsObject()) if (value.IsObject())
value = Convert::ToString(value); value = Convert::ToString(value);
persistentVariable->Set("value", value); Dictionary::Ptr persistentVariable = new Dictionary({
{ "name", kv.first },
{ "value", value }
});
String json = JsonEncode(persistentVariable); String json = JsonEncode(persistentVariable);

View File

@ -267,12 +267,7 @@ Array::Ptr ScriptUtils::Union(const std::vector<Value>& arguments)
} }
} }
Array::Ptr result = new Array(); return Array::FromSet(values);
for (const Value& value : values) {
result->Add(value);
}
return result;
} }
Array::Ptr ScriptUtils::Intersection(const std::vector<Value>& arguments) Array::Ptr ScriptUtils::Intersection(const std::vector<Value>& arguments)
@ -370,16 +365,16 @@ Array::Ptr ScriptUtils::Range(const std::vector<Value>& arguments)
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid number of arguments for range()")); BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid number of arguments for range()"));
} }
Array::Ptr result = new Array(); ArrayData result;
if ((start < end && increment <= 0) || if ((start < end && increment <= 0) ||
(start > end && increment >= 0)) (start > end && increment >= 0))
return result; return new Array();
for (double i = start; (increment > 0 ? i < end : i > end); i += increment) for (double i = start; (increment > 0 ? i < end : i > end); i += increment)
result->Add(i); result.push_back(i);
return result; return new Array(std::move(result));
} }
Type::Ptr ScriptUtils::TypeOf(const Value& value) Type::Ptr ScriptUtils::TypeOf(const Value& value)
@ -389,16 +384,16 @@ Type::Ptr ScriptUtils::TypeOf(const Value& value)
Array::Ptr ScriptUtils::Keys(const Dictionary::Ptr& dict) Array::Ptr ScriptUtils::Keys(const Dictionary::Ptr& dict)
{ {
Array::Ptr result = new Array(); ArrayData result;
if (dict) { if (dict) {
ObjectLock olock(dict); ObjectLock olock(dict);
for (const Dictionary::Pair& kv : dict) { for (const Dictionary::Pair& kv : dict) {
result->Add(kv.first); result.push_back(kv.first);
} }
} }
return result; return new Array(std::move(result));
} }
ConfigObject::Ptr ScriptUtils::GetObject(const Value& vtype, const String& name) ConfigObject::Ptr ScriptUtils::GetObject(const Value& vtype, const String& name)
@ -428,12 +423,12 @@ Array::Ptr ScriptUtils::GetObjects(const Type::Ptr& type)
if (!ctype) if (!ctype)
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid type: Type must inherit from 'ConfigObject'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid type: Type must inherit from 'ConfigObject'"));
Array::Ptr result = new Array(); ArrayData result;
for (const ConfigObject::Ptr& object : ctype->GetObjects()) for (const ConfigObject::Ptr& object : ctype->GetObjects())
result->Add(object); result.push_back(object);
return result; return new Array(std::move(result));
} }
void ScriptUtils::Assert(const Value& arg) void ScriptUtils::Assert(const Value& arg)

View File

@ -26,28 +26,32 @@ using namespace icinga;
static Array::Ptr SerializeArray(const Array::Ptr& input, int attributeTypes) static Array::Ptr SerializeArray(const Array::Ptr& input, int attributeTypes)
{ {
Array::Ptr result = new Array(); ArrayData result;
result.reserve(input->GetLength());
ObjectLock olock(input); ObjectLock olock(input);
for (const Value& value : input) { for (const Value& value : input) {
result->Add(Serialize(value, attributeTypes)); result.emplace_back(Serialize(value, attributeTypes));
} }
return result; return new Array(std::move(result));
} }
static Dictionary::Ptr SerializeDictionary(const Dictionary::Ptr& input, int attributeTypes) static Dictionary::Ptr SerializeDictionary(const Dictionary::Ptr& input, int attributeTypes)
{ {
Dictionary::Ptr result = new Dictionary(); DictionaryData result;
result.reserve(input->GetLength());
ObjectLock olock(input); ObjectLock olock(input);
for (const Dictionary::Pair& kv : input) { for (const Dictionary::Pair& kv : input) {
result->Set(kv.first, Serialize(kv.second, attributeTypes)); result.emplace_back(kv.first, Serialize(kv.second, attributeTypes));
} }
return result; return new Dictionary(std::move(result));
} }
static Object::Ptr SerializeObject(const Object::Ptr& input, int attributeTypes) static Object::Ptr SerializeObject(const Object::Ptr& input, int attributeTypes)
@ -57,7 +61,8 @@ static Object::Ptr SerializeObject(const Object::Ptr& input, int attributeTypes)
if (!type) if (!type)
return nullptr; return nullptr;
Dictionary::Ptr fields = new Dictionary(); DictionaryData fields;
fields.reserve(type->GetFieldCount() + 1);
for (int i = 0; i < type->GetFieldCount(); i++) { for (int i = 0; i < type->GetFieldCount(); i++) {
Field field = type->GetFieldInfo(i); Field field = type->GetFieldInfo(i);
@ -65,38 +70,45 @@ static Object::Ptr SerializeObject(const Object::Ptr& input, int attributeTypes)
if (attributeTypes != 0 && (field.Attributes & attributeTypes) == 0) if (attributeTypes != 0 && (field.Attributes & attributeTypes) == 0)
continue; continue;
fields->Set(field.Name, Serialize(input->GetField(i), attributeTypes)); if (strcmp(field.Name, "type") == 0)
continue;
fields.emplace_back(field.Name, Serialize(input->GetField(i), attributeTypes));
} }
fields->Set("type", type->GetName()); fields.emplace_back("type", type->GetName());
return fields; return new Dictionary(std::move(fields));
} }
static Array::Ptr DeserializeArray(const Array::Ptr& input, bool safe_mode, int attributeTypes) static Array::Ptr DeserializeArray(const Array::Ptr& input, bool safe_mode, int attributeTypes)
{ {
Array::Ptr result = new Array(); ArrayData result;
result.reserve(input->GetLength());
ObjectLock olock(input); ObjectLock olock(input);
for (const Value& value : input) { for (const Value& value : input) {
result->Add(Deserialize(value, safe_mode, attributeTypes)); result.emplace_back(Deserialize(value, safe_mode, attributeTypes));
} }
return result; return new Array(std::move(result));
} }
static Dictionary::Ptr DeserializeDictionary(const Dictionary::Ptr& input, bool safe_mode, int attributeTypes) static Dictionary::Ptr DeserializeDictionary(const Dictionary::Ptr& input, bool safe_mode, int attributeTypes)
{ {
Dictionary::Ptr result = new Dictionary(); DictionaryData result;
result.reserve(input->GetLength());
ObjectLock olock(input); ObjectLock olock(input);
for (const Dictionary::Pair& kv : input) { for (const Dictionary::Pair& kv : input) {
result->Set(kv.first, Deserialize(kv.second, safe_mode, attributeTypes)); result.emplace_back(kv.first, Deserialize(kv.second, safe_mode, attributeTypes));
} }
return result; return new Dictionary(std::move(result));
} }
static Object::Ptr DeserializeObject(const Object::Ptr& object, const Dictionary::Ptr& input, bool safe_mode, int attributeTypes) static Object::Ptr DeserializeObject(const Object::Ptr& object, const Dictionary::Ptr& input, bool safe_mode, int attributeTypes)

View File

@ -78,11 +78,7 @@ static Array::Ptr StringSplit(const String& delims)
std::vector<String> tokens; std::vector<String> tokens;
boost::algorithm::split(tokens, self, boost::is_any_of(delims)); boost::algorithm::split(tokens, self, boost::is_any_of(delims));
Array::Ptr result = new Array(); return Array::FromVector(tokens);
for (const String& token : tokens) {
result->Add(token);
}
return result;
} }
static int StringFind(const std::vector<Value>& args) static int StringFind(const std::vector<Value>& args)
@ -141,22 +137,19 @@ static String StringTrim()
Object::Ptr String::GetPrototype() Object::Ptr String::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "len", new Function("String#len", StringLen, {}, true) },
if (!prototype) { { "to_string", new Function("String#to_string", StringToString, {}, true) },
prototype = new Dictionary(); { "substr", new Function("String#substr", StringSubstr, { "start", "len" }, true) },
prototype->Set("len", new Function("String#len", StringLen, {}, true)); { "upper", new Function("String#upper", StringUpper, {}, true) },
prototype->Set("to_string", new Function("String#to_string", StringToString, {}, true)); { "lower", new Function("String#lower", StringLower, {}, true) },
prototype->Set("substr", new Function("String#substr", StringSubstr, { "start", "len" }, true)); { "split", new Function("String#split", StringSplit, { "delims" }, true) },
prototype->Set("upper", new Function("String#upper", StringUpper, {}, true)); { "find", new Function("String#find", StringFind, { "str", "start" }, true) },
prototype->Set("lower", new Function("String#lower", StringLower, {}, true)); { "contains", new Function("String#contains", StringContains, { "str" }, true) },
prototype->Set("split", new Function("String#split", StringSplit, { "delims" }, true)); { "replace", new Function("String#replace", StringReplace, { "search", "replacement" }, true) },
prototype->Set("find", new Function("String#find", StringFind, { "str", "start" }, true)); { "reverse", new Function("String#reverse", StringReverse, {}, true) },
prototype->Set("contains", new Function("String#contains", StringContains, { "str" }, true)); { "trim", new Function("String#trim", StringTrim, {}, true) }
prototype->Set("replace", new Function("String#replace", StringReplace, { "search", "replacement" }, true)); });
prototype->Set("reverse", new Function("String#reverse", StringReverse, {}, true));
prototype->Set("trim", new Function("String#trim", StringTrim, {}, true));
}
return prototype; return prototype;
} }

View File

@ -80,13 +80,13 @@ void SyslogLogger::StaticInitialize()
void SyslogLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) void SyslogLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const SyslogLogger::Ptr& sysloglogger : ConfigType::GetObjectsByType<SyslogLogger>()) { for (const SyslogLogger::Ptr& sysloglogger : ConfigType::GetObjectsByType<SyslogLogger>()) {
nodes->Set(sysloglogger->GetName(), 1); //add more stats nodes.emplace_back(sysloglogger->GetName(), 1); //add more stats
} }
status->Set("sysloglogger", nodes); status->Set("sysloglogger", new Dictionary(std::move(nodes)));
} }
void SyslogLogger::OnConfigLoaded() void SyslogLogger::OnConfigLoaded()

View File

@ -42,12 +42,9 @@ static void TypeRegisterAttributeHandler(const String& fieldName, const Function
Object::Ptr TypeType::GetPrototype() Object::Ptr TypeType::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "register_attribute_handler", new Function("Type#register_attribute_handler", TypeRegisterAttributeHandler, { "field", "callback" }, false) }
if (!prototype) { });
prototype = new Dictionary();
prototype->Set("register_attribute_handler", new Function("Type#register_attribute_handler", TypeRegisterAttributeHandler, { "field", "callback" }, false));
}
return prototype; return prototype;
} }

View File

@ -285,7 +285,7 @@ Value icinga::operator-(const Value& lhs, const Value& rhs)
if (lhs.IsEmpty()) if (lhs.IsEmpty())
return new Array(); return new Array();
Array::Ptr result = new Array(); ArrayData result;
Array::Ptr left = lhs; Array::Ptr left = lhs;
Array::Ptr right = rhs; Array::Ptr right = rhs;
@ -303,10 +303,10 @@ Value icinga::operator-(const Value& lhs, const Value& rhs)
if (found) if (found)
continue; continue;
result->Add(lv); result.push_back(lv);
} }
return result; return new Array(std::move(result));
} else } else
BOOST_THROW_EXCEPTION(std::invalid_argument("Operator - cannot be applied to values of type '" + lhs.GetTypeName() + "' and '" + rhs.GetTypeName() + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Operator - cannot be applied to values of type '" + lhs.GetTypeName() + "' and '" + rhs.GetTypeName() + "'"));
} }

View File

@ -39,24 +39,23 @@ REGISTER_STATSFUNCTION(CheckerComponent, &CheckerComponent::StatsFunc);
void CheckerComponent::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata) void CheckerComponent::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const CheckerComponent::Ptr& checker : ConfigType::GetObjectsByType<CheckerComponent>()) { for (const CheckerComponent::Ptr& checker : ConfigType::GetObjectsByType<CheckerComponent>()) {
unsigned long idle = checker->GetIdleCheckables(); unsigned long idle = checker->GetIdleCheckables();
unsigned long pending = checker->GetPendingCheckables(); unsigned long pending = checker->GetPendingCheckables();
Dictionary::Ptr stats = new Dictionary(); nodes.emplace_back(checker->GetName(), new Dictionary({
stats->Set("idle", idle); { "idle", idle },
stats->Set("pending", pending); { "pending", pending }
}));
nodes->Set(checker->GetName(), stats);
String perfdata_prefix = "checkercomponent_" + checker->GetName() + "_"; String perfdata_prefix = "checkercomponent_" + checker->GetName() + "_";
perfdata->Add(new PerfdataValue(perfdata_prefix + "idle", Convert::ToDouble(idle))); perfdata->Add(new PerfdataValue(perfdata_prefix + "idle", Convert::ToDouble(idle)));
perfdata->Add(new PerfdataValue(perfdata_prefix + "pending", Convert::ToDouble(pending))); perfdata->Add(new PerfdataValue(perfdata_prefix + "pending", Convert::ToDouble(pending)));
} }
status->Set("checkercomponent", nodes); status->Set("checkercomponent", new Dictionary(std::move(nodes)));
} }
void CheckerComponent::OnConfigLoaded() void CheckerComponent::OnConfigLoaded()

View File

@ -86,8 +86,9 @@ extern "C" void dbg_eval_with_value(const Value& value, const char *text)
try { try {
ScriptFrame frame(true); ScriptFrame frame(true);
frame.Locals = new Dictionary(); frame.Locals = new Dictionary({
frame.Locals->Set("arg", value); { "arg", value }
});
expr = ConfigCompiler::CompileText("<dbg>", text); expr = ConfigCompiler::CompileText("<dbg>", text);
Value result = Serialize(expr->Evaluate(frame), 0); Value result = Serialize(expr->Evaluate(frame), 0);
dbg_inspect_value(result); dbg_inspect_value(result);
@ -102,8 +103,9 @@ extern "C" void dbg_eval_with_object(Object *object, const char *text)
try { try {
ScriptFrame frame(true); ScriptFrame frame(true);
frame.Locals = new Dictionary(); frame.Locals = new Dictionary({
frame.Locals->Set("arg", object); { "arg", object }
});
expr = ConfigCompiler::CompileText("<dbg>", text); expr = ConfigCompiler::CompileText("<dbg>", text);
Value result = Serialize(expr->Evaluate(frame), 0); Value result = Serialize(expr->Evaluate(frame), 0);
dbg_inspect_value(result); dbg_inspect_value(result);

View File

@ -56,13 +56,11 @@ int NodeUtility::GenerateNodeIcingaConfig(const std::vector<std::string>& endpoi
{ {
Array::Ptr my_config = new Array(); Array::Ptr my_config = new Array();
Dictionary::Ptr my_master_zone = new Dictionary();
Array::Ptr my_master_zone_members = new Array(); Array::Ptr my_master_zone_members = new Array();
String master_zone_name = "master"; //TODO: Find a better name. String master_zone_name = "master"; //TODO: Find a better name.
for (const std::string& endpoint : endpoints) { for (const std::string& endpoint : endpoints) {
/* extract all --endpoint arguments and store host,port info */ /* extract all --endpoint arguments and store host,port info */
std::vector<String> tokens; std::vector<String> tokens;
boost::algorithm::split(tokens, endpoint, boost::is_any_of(",")); boost::algorithm::split(tokens, endpoint, boost::is_any_of(","));
@ -94,42 +92,33 @@ int NodeUtility::GenerateNodeIcingaConfig(const std::vector<std::string>& endpoi
} }
/* add the master zone to the config */ /* add the master zone to the config */
my_master_zone->Set("__name", master_zone_name); my_config->Add(new Dictionary({
my_master_zone->Set("__type", "Zone"); { "__name", master_zone_name },
my_master_zone->Set("endpoints", my_master_zone_members); { "__type", "Zone" },
{ "endpoints", my_master_zone_members }
my_config->Add(my_master_zone); }));
/* store the local generated node configuration */ /* store the local generated node configuration */
Dictionary::Ptr my_endpoint = new Dictionary(); my_config->Add(new Dictionary({
Dictionary::Ptr my_zone = new Dictionary(); { "__name", new ConfigIdentifier("NodeName") },
{ "__type", "Endpoint" }
}));
my_endpoint->Set("__name", new ConfigIdentifier("NodeName")); my_config->Add(new Dictionary({
my_endpoint->Set("__type", "Endpoint"); { "__name", new ConfigIdentifier("ZoneName") },
{ "__type", "Zone" },
Array::Ptr my_zone_members = new Array(); { "parent", master_zone_name }, //set the master zone as parent
my_zone_members->Add(new ConfigIdentifier("NodeName")); { "endpoints", new Array({ new ConfigIdentifier("ZoneName") }) }
}));
my_zone->Set("__name", new ConfigIdentifier("ZoneName"));
my_zone->Set("__type", "Zone");
my_zone->Set("parent", master_zone_name); //set the master zone as parent
my_zone->Set("endpoints", my_zone_members);
for (const String& globalzone : globalZones) { for (const String& globalzone : globalZones) {
Dictionary::Ptr myGlobalZone = new Dictionary(); my_config->Add(new Dictionary({
{ "__name", globalzone },
myGlobalZone->Set("__name", globalzone); { "__type", "Zone" },
myGlobalZone->Set("__type", "Zone"); { "global", true }
myGlobalZone->Set("global", true); }));
my_config->Add(myGlobalZone);
} }
/* store the local config */
my_config->Add(my_endpoint);
my_config->Add(my_zone);
/* write the newly generated configuration */ /* write the newly generated configuration */
String zones_path = Application::GetSysconfDir() + "/icinga2/zones.conf"; String zones_path = Application::GetSysconfDir() + "/icinga2/zones.conf";
@ -143,32 +132,23 @@ int NodeUtility::GenerateNodeMasterIcingaConfig(const std::vector<String>& globa
Array::Ptr my_config = new Array(); Array::Ptr my_config = new Array();
/* store the local generated node master configuration */ /* store the local generated node master configuration */
Dictionary::Ptr my_master_endpoint = new Dictionary(); my_config->Add(new Dictionary({
Dictionary::Ptr my_master_zone = new Dictionary(); { "__name", new ConfigIdentifier("NodeName") },
{ "__type", "Endpoint" }
}));
Array::Ptr my_master_zone_members = new Array(); my_config->Add(new Dictionary({
{ "__name", new ConfigIdentifier("ZoneName") },
my_master_endpoint->Set("__name", new ConfigIdentifier("NodeName")); { "__type", "Zone" },
my_master_endpoint->Set("__type", "Endpoint"); { "endpoints", new Array({ new ConfigIdentifier("NodeName") }) }
}));
my_master_zone_members->Add(new ConfigIdentifier("NodeName"));
my_master_zone->Set("__name", new ConfigIdentifier("ZoneName"));
my_master_zone->Set("__type", "Zone");
my_master_zone->Set("endpoints", my_master_zone_members);
/* store the local config */
my_config->Add(my_master_endpoint);
my_config->Add(my_master_zone);
for (const String& globalzone : globalZones) { for (const String& globalzone : globalZones) {
Dictionary::Ptr myGlobalZone = new Dictionary(); my_config->Add(new Dictionary({
{ "__name", globalzone },
myGlobalZone->Set("__name", globalzone); { "__type", "Zone" },
myGlobalZone->Set("__type", "Zone"); { "global", true }
myGlobalZone->Set("global", true); }));
my_config->Add(myGlobalZone);
} }
/* write the newly generated configuration */ /* write the newly generated configuration */

View File

@ -42,13 +42,13 @@ REGISTER_STATSFUNCTION(CheckResultReader, &CheckResultReader::StatsFunc);
void CheckResultReader::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) void CheckResultReader::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const CheckResultReader::Ptr& checkresultreader : ConfigType::GetObjectsByType<CheckResultReader>()) { for (const CheckResultReader::Ptr& checkresultreader : ConfigType::GetObjectsByType<CheckResultReader>()) {
nodes->Set(checkresultreader->GetName(), 1); //add more stats nodes.emplace_back(checkresultreader->GetName(), 1); //add more stats
} }
status->Set("checkresultreader", nodes); status->Set("checkresultreader", new Dictionary(std::move(nodes)));
} }
/** /**

View File

@ -44,13 +44,13 @@ REGISTER_STATSFUNCTION(CompatLogger, &CompatLogger::StatsFunc);
void CompatLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) void CompatLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const CompatLogger::Ptr& compat_logger : ConfigType::GetObjectsByType<CompatLogger>()) { for (const CompatLogger::Ptr& compat_logger : ConfigType::GetObjectsByType<CompatLogger>()) {
nodes->Set(compat_logger->GetName(), 1); //add more stats nodes.emplace_back(compat_logger->GetName(), 1); // add more stats
} }
status->Set("compatlogger", nodes); status->Set("compatlogger", new Dictionary(std::move(nodes)));
} }
/** /**

View File

@ -34,13 +34,13 @@ REGISTER_STATSFUNCTION(ExternalCommandListener, &ExternalCommandListener::StatsF
void ExternalCommandListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) void ExternalCommandListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const ExternalCommandListener::Ptr& externalcommandlistener : ConfigType::GetObjectsByType<ExternalCommandListener>()) { for (const ExternalCommandListener::Ptr& externalcommandlistener : ConfigType::GetObjectsByType<ExternalCommandListener>()) {
nodes->Set(externalcommandlistener->GetName(), 1); //add more stats nodes.emplace_back(externalcommandlistener->GetName(), 1); //add more stats
} }
status->Set("externalcommandlistener", nodes); status->Set("externalcommandlistener", new Dictionary(std::move(nodes)));
} }
/** /**

View File

@ -52,13 +52,13 @@ REGISTER_STATSFUNCTION(StatusDataWriter, &StatusDataWriter::StatsFunc);
void StatusDataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) void StatusDataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const StatusDataWriter::Ptr& statusdatawriter : ConfigType::GetObjectsByType<StatusDataWriter>()) { for (const StatusDataWriter::Ptr& statusdatawriter : ConfigType::GetObjectsByType<StatusDataWriter>()) {
nodes->Set(statusdatawriter->GetName(), 1); //add more stats nodes.emplace_back(statusdatawriter->GetName(), 1); //add more stats
} }
status->Set("statusdatawriter", nodes); status->Set("statusdatawriter", new Dictionary(std::move(nodes)));
} }
/** /**

View File

@ -288,26 +288,25 @@ ConfigObject::Ptr ConfigItem::Commit(bool discard)
throw; throw;
} }
Dictionary::Ptr persistentItem = new Dictionary(); Dictionary::Ptr persistentItem = new Dictionary({
{ "type", GetType()->GetName() },
{ "name", GetName() },
{ "properties", Serialize(dobj, FAConfig) },
{ "debug_hints", dhint },
{ "debug_info", new Array({
m_DebugInfo.Path,
m_DebugInfo.FirstLine,
m_DebugInfo.FirstColumn,
m_DebugInfo.LastLine,
m_DebugInfo.LastColumn,
}) }
});
persistentItem->Set("type", GetType()->GetName()); dhint.reset();
persistentItem->Set("name", GetName());
persistentItem->Set("properties", Serialize(dobj, FAConfig));
persistentItem->Set("debug_hints", dhint);
Array::Ptr di = new Array();
di->Add(m_DebugInfo.Path);
di->Add(m_DebugInfo.FirstLine);
di->Add(m_DebugInfo.FirstColumn);
di->Add(m_DebugInfo.LastLine);
di->Add(m_DebugInfo.LastColumn);
persistentItem->Set("debug_info", di);
ConfigCompilerContext::GetInstance()->WriteObject(persistentItem); ConfigCompilerContext::GetInstance()->WriteObject(persistentItem);
persistentItem.reset(); persistentItem.reset();
dhint.reset();
dobj->Register(); dobj->Register();
m_Object = dobj; m_Object = dobj;

View File

@ -103,8 +103,7 @@ ConfigItem::Ptr ConfigItemBuilder::Compile()
std::vector<std::unique_ptr<Expression> > exprs; std::vector<std::unique_ptr<Expression> > exprs;
Array::Ptr templateArray = new Array(); Array::Ptr templateArray = new Array({ m_Name });
templateArray->Add(m_Name);
exprs.emplace_back(new SetExpression(MakeIndexer(ScopeThis, "templates"), OpSetAdd, exprs.emplace_back(new SetExpression(MakeIndexer(ScopeThis, "templates"), OpSetAdd,
std::unique_ptr<LiteralExpression>(new LiteralExpression(templateArray)), m_DebugInfo)); std::unique_ptr<LiteralExpression>(new LiteralExpression(templateArray)), m_DebugInfo));

View File

@ -461,17 +461,17 @@ ExpressionResult FunctionCallExpression::DoEvaluate(ScriptFrame& frame, DebugHin
ExpressionResult ArrayExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const ExpressionResult ArrayExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{ {
Array::Ptr result = new Array(); ArrayData result;
result->Reserve(m_Expressions.size()); result.reserve(m_Expressions.size());
for (const auto& aexpr : m_Expressions) { for (const auto& aexpr : m_Expressions) {
ExpressionResult element = aexpr->Evaluate(frame); ExpressionResult element = aexpr->Evaluate(frame);
CHECK_RESULT(element); CHECK_RESULT(element);
result->Add(element.GetValue()); result.push_back(element.GetValue());
} }
return result; return new Array(std::move(result));
} }
ExpressionResult DictExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const ExpressionResult DictExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const

View File

@ -255,17 +255,15 @@ public:
private: private:
static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, const std::map<String, std::unique_ptr<Expression> >& closedVars) static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, const std::map<String, std::unique_ptr<Expression> >& closedVars)
{ {
Dictionary::Ptr locals; if (closedVars.empty())
return nullptr;
if (!closedVars.empty()) { DictionaryData locals;
locals = new Dictionary();
for (const auto& cvar : closedVars) { for (const auto& cvar : closedVars)
locals->Set(cvar.first, cvar.second->Evaluate(frame)); locals.emplace_back(cvar.first, cvar.second->Evaluate(frame));
}
}
return locals; return new Dictionary(std::move(locals));
} }
}; };

View File

@ -35,12 +35,11 @@ CommandDbObject::CommandDbObject(const DbType::Ptr& type, const String& name1, c
Dictionary::Ptr CommandDbObject::GetConfigFields() const Dictionary::Ptr CommandDbObject::GetConfigFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
Command::Ptr command = static_pointer_cast<Command>(GetObject()); Command::Ptr command = static_pointer_cast<Command>(GetObject());
fields->Set("command_line", CompatUtility::GetCommandLine(command)); return new Dictionary({
{ "command_line", CompatUtility::GetCommandLine(command) }
return fields; });
} }
Dictionary::Ptr CommandDbObject::GetStatusFields() const Dictionary::Ptr CommandDbObject::GetStatusFields() const

View File

@ -109,12 +109,14 @@ void DbConnection::Pause()
query1.IdColumn = "programstatus_id"; query1.IdColumn = "programstatus_id";
query1.Type = DbQueryUpdate; query1.Type = DbQueryUpdate;
query1.Category = DbCatProgramStatus; query1.Category = DbCatProgramStatus;
query1.WhereCriteria = new Dictionary(); query1.WhereCriteria = new Dictionary({
query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 } /* DbConnection class fills in real ID */
});
query1.Fields = new Dictionary(); query1.Fields = new Dictionary({
query1.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 }, /* DbConnection class fills in real ID */
query1.Fields->Set("program_end_time", DbValue::FromTimestamp(Utility::GetTime())); { "program_end_time", DbValue::FromTimestamp(Utility::GetTime()) }
});
query1.Priority = PriorityHigh; query1.Priority = PriorityHigh;
@ -137,10 +139,11 @@ void DbConnection::InsertRuntimeVariable(const String& key, const Value& value)
query.Table = "runtimevariables"; query.Table = "runtimevariables";
query.Type = DbQueryInsert; query.Type = DbQueryInsert;
query.Category = DbCatProgramStatus; query.Category = DbCatProgramStatus;
query.Fields = new Dictionary(); query.Fields = new Dictionary({
query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 }, /* DbConnection class fills in real ID */
query.Fields->Set("varname", key); { "varname", key },
query.Fields->Set("varvalue", value); { "varvalue", value }
});
DbObject::OnQuery(query); DbObject::OnQuery(query);
} }
@ -157,26 +160,30 @@ void DbConnection::UpdateProgramStatus()
query1.Type = DbQueryInsert | DbQueryUpdate; query1.Type = DbQueryInsert | DbQueryUpdate;
query1.Category = DbCatProgramStatus; query1.Category = DbCatProgramStatus;
query1.Fields = new Dictionary(); query1.Fields = new Dictionary({
query1.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 }, /* DbConnection class fills in real ID */
query1.Fields->Set("program_version", Application::GetAppVersion()); { "program_version", Application::GetAppVersion() },
query1.Fields->Set("status_update_time", DbValue::FromTimestamp(Utility::GetTime())); { "status_update_time", DbValue::FromTimestamp(Utility::GetTime()) },
query1.Fields->Set("program_start_time", DbValue::FromTimestamp(Application::GetStartTime())); { "program_start_time", DbValue::FromTimestamp(Application::GetStartTime()) },
query1.Fields->Set("is_currently_running", 1); { "is_currently_running", 1 },
query1.Fields->Set("endpoint_name", IcingaApplication::GetInstance()->GetNodeName()); { "endpoint_name", IcingaApplication::GetInstance()->GetNodeName() },
query1.Fields->Set("process_id", Utility::GetPid()); { "process_id", Utility::GetPid() },
query1.Fields->Set("daemon_mode", 1); { "daemon_mode", 1 },
query1.Fields->Set("last_command_check", DbValue::FromTimestamp(Utility::GetTime())); { "last_command_check", DbValue::FromTimestamp(Utility::GetTime()) },
query1.Fields->Set("notifications_enabled", (IcingaApplication::GetInstance()->GetEnableNotifications() ? 1 : 0)); { "notifications_enabled", (IcingaApplication::GetInstance()->GetEnableNotifications() ? 1 : 0) },
query1.Fields->Set("active_host_checks_enabled", (IcingaApplication::GetInstance()->GetEnableHostChecks() ? 1 : 0)); { "active_host_checks_enabled", (IcingaApplication::GetInstance()->GetEnableHostChecks() ? 1 : 0) },
query1.Fields->Set("passive_host_checks_enabled", 1); { "passive_host_checks_enabled", 1 },
query1.Fields->Set("active_service_checks_enabled", (IcingaApplication::GetInstance()->GetEnableServiceChecks() ? 1 : 0)); { "active_service_checks_enabled", (IcingaApplication::GetInstance()->GetEnableServiceChecks() ? 1 : 0) },
query1.Fields->Set("passive_service_checks_enabled", 1); { "passive_service_checks_enabled", 1 },
query1.Fields->Set("event_handlers_enabled", (IcingaApplication::GetInstance()->GetEnableEventHandlers() ? 1 : 0)); { "event_handlers_enabled", (IcingaApplication::GetInstance()->GetEnableEventHandlers() ? 1 : 0) },
query1.Fields->Set("flap_detection_enabled", (IcingaApplication::GetInstance()->GetEnableFlapping() ? 1 : 0)); { "flap_detection_enabled", (IcingaApplication::GetInstance()->GetEnableFlapping() ? 1 : 0) },
query1.Fields->Set("process_performance_data", (IcingaApplication::GetInstance()->GetEnablePerfdata() ? 1 : 0)); { "process_performance_data", (IcingaApplication::GetInstance()->GetEnablePerfdata() ? 1 : 0) }
query1.WhereCriteria = new Dictionary(); });
query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */
query1.WhereCriteria = new Dictionary({
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
query1.Priority = PriorityHigh; query1.Priority = PriorityHigh;
queries.emplace_back(std::move(query1)); queries.emplace_back(std::move(query1));
@ -190,8 +197,9 @@ void DbConnection::UpdateProgramStatus()
query3.Table = "runtimevariables"; query3.Table = "runtimevariables";
query3.Type = DbQueryDelete; query3.Type = DbQueryDelete;
query3.Category = DbCatProgramStatus; query3.Category = DbCatProgramStatus;
query3.WhereCriteria = new Dictionary(); query3.WhereCriteria = new Dictionary({
query3.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 } /* DbConnection class fills in real ID */
});
DbObject::OnQuery(query3); DbObject::OnQuery(query3);
InsertRuntimeVariable("total_services", ConfigType::Get<Service>()->GetObjectCount()); InsertRuntimeVariable("total_services", ConfigType::Get<Service>()->GetObjectCount());

View File

@ -37,20 +37,19 @@ abstract class DbConnection : ConfigObject
[config] Array::Ptr categories { [config] Array::Ptr categories {
default {{{ default {{{
Array::Ptr cat = new Array(); return new Array({
cat->Add("DbCatConfig"); "DbCatConfig",
cat->Add("DbCatState"); "DbCatState",
cat->Add("DbCatAcknowledgement"); "DbCatAcknowledgement",
cat->Add("DbCatComment"); "DbCatComment",
cat->Add("DbCatDowntime"); "DbCatDowntime",
cat->Add("DbCatEventHandler"); "DbCatEventHandler",
cat->Add("DbCatFlapping"); "DbCatFlapping",
cat->Add("DbCatNotification"); "DbCatNotification",
cat->Add("DbCatProgramStatus"); "DbCatProgramStatus",
cat->Add("DbCatRetention"); "DbCatRetention",
cat->Add("DbCatStateHistory"); "DbCatStateHistory"
});
return cat;
}}} }}}
}; };
[no_user_view, no_user_modify] int categories_filter_real (CategoryFilter); [no_user_view, no_user_modify] int categories_filter_real (CategoryFilter);

View File

@ -111,10 +111,9 @@ void DbEvents::NextCheckUpdatedHandler(const Checkable::Ptr& checkable)
query1.StatusUpdate = true; query1.StatusUpdate = true;
query1.Object = DbObject::GetOrCreateByObject(checkable); query1.Object = DbObject::GetOrCreateByObject(checkable);
Dictionary::Ptr fields1 = new Dictionary(); query1.Fields = new Dictionary({
fields1->Set("next_check", DbValue::FromTimestamp(checkable->GetNextCheck())); { "next_check", DbValue::FromTimestamp(checkable->GetNextCheck()) }
});
query1.Fields = fields1;
DbObject::OnQuery(query1); DbObject::OnQuery(query1);
} }
@ -145,7 +144,11 @@ void DbEvents::FlappingChangedHandler(const Checkable::Ptr& checkable)
fields1->Set("is_flapping", checkable->IsFlapping()); fields1->Set("is_flapping", checkable->IsFlapping());
fields1->Set("percent_state_change", checkable->GetFlappingCurrent()); fields1->Set("percent_state_change", checkable->GetFlappingCurrent());
query1.Fields = fields1; query1.Fields = new Dictionary({
{ "is_flapping", checkable->IsFlapping() },
{ "percent_state_change", checkable->GetFlappingCurrent() }
});
query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbObject::OnQuery(query1); DbObject::OnQuery(query1);
@ -176,12 +179,12 @@ void DbEvents::LastNotificationChangedHandler(const Notification::Ptr& notificat
query1.StatusUpdate = true; query1.StatusUpdate = true;
query1.Object = DbObject::GetOrCreateByObject(checkable); query1.Object = DbObject::GetOrCreateByObject(checkable);
Dictionary::Ptr fields1 = new Dictionary(); query1.Fields = new Dictionary({
fields1->Set("last_notification", DbValue::FromTimestamp(now_bag.first)); { "last_notification", DbValue::FromTimestamp(now_bag.first) },
fields1->Set("next_notification", DbValue::FromTimestamp(timeBag.first)); { "next_notification", DbValue::FromTimestamp(timeBag.first) },
fields1->Set("current_notification_number", notification->GetNotificationNumber()); { "current_notification_number", notification->GetNotificationNumber() }
});
query1.Fields = fields1;
query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbObject::OnQuery(query1); DbObject::OnQuery(query1);
@ -221,10 +224,10 @@ void DbEvents::ReachabilityChangedHandler(const Checkable::Ptr& checkable, const
query1.StatusUpdate = true; query1.StatusUpdate = true;
query1.Object = DbObject::GetOrCreateByObject(child); query1.Object = DbObject::GetOrCreateByObject(child);
Dictionary::Ptr fields1 = new Dictionary(); query1.Fields = new Dictionary({
fields1->Set("is_reachable", is_reachable); { "is_reachable", is_reachable }
});
query1.Fields = fields1;
query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbObject::OnQuery(query1); DbObject::OnQuery(query1);
@ -279,10 +282,10 @@ void DbEvents::EnableChangedHandlerInternal(const Checkable::Ptr& checkable, con
query1.StatusUpdate = true; query1.StatusUpdate = true;
query1.Object = DbObject::GetOrCreateByObject(checkable); query1.Object = DbObject::GetOrCreateByObject(checkable);
Dictionary::Ptr fields1 = new Dictionary(); query1.Fields = new Dictionary({
fields1->Set(fieldName, enabled); { fieldName, enabled }
});
query1.Fields = fields1;
query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbObject::OnQuery(query1); DbObject::OnQuery(query1);
@ -365,10 +368,11 @@ void DbEvents::AddCommentInternal(std::vector<DbQuery>& queries, const Comment::
fields1->Set("session_token", 0); /* DbConnection class fills in real ID */ fields1->Set("session_token", 0); /* DbConnection class fills in real ID */
query1.WhereCriteria = new Dictionary(); query1.WhereCriteria = new Dictionary({
query1.WhereCriteria->Set("object_id", checkable); { "object_id", checkable },
query1.WhereCriteria->Set("name", comment->GetName()); { "name", comment->GetName() },
query1.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(timeBag.first)); { "entry_time", DbValue::FromTimestamp(timeBag.first) }
});
} else { } else {
query1.Table = "commenthistory"; query1.Table = "commenthistory";
query1.Type = DbQueryInsert; query1.Type = DbQueryInsert;
@ -398,10 +402,12 @@ void DbEvents::RemoveCommentInternal(std::vector<DbQuery>& queries, const Commen
query1.Type = DbQueryDelete; query1.Type = DbQueryDelete;
query1.Category = DbCatComment; query1.Category = DbCatComment;
query1.WhereCriteria = new Dictionary(); query1.WhereCriteria = new Dictionary({
query1.WhereCriteria->Set("object_id", checkable); { "object_id", checkable },
query1.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(timeBag.first)); { "entry_time", DbValue::FromTimestamp(timeBag.first) },
query1.WhereCriteria->Set("name", comment->GetName()); { "name", comment->GetName() }
});
queries.emplace_back(std::move(query1)); queries.emplace_back(std::move(query1));
/* History - update deletion time for service/host */ /* History - update deletion time for service/host */
@ -412,15 +418,16 @@ void DbEvents::RemoveCommentInternal(std::vector<DbQuery>& queries, const Commen
query2.Type = DbQueryUpdate; query2.Type = DbQueryUpdate;
query2.Category = DbCatComment; query2.Category = DbCatComment;
Dictionary::Ptr fields2 = new Dictionary(); query2.Fields = new Dictionary({
fields2->Set("deletion_time", DbValue::FromTimestamp(timeBagNow.first)); { "deletion_time", DbValue::FromTimestamp(timeBagNow.first) },
fields2->Set("deletion_time_usec", timeBagNow.second); { "deletion_time_usec", timeBagNow.second }
query2.Fields = fields2; });
query2.WhereCriteria = new Dictionary(); query2.WhereCriteria = new Dictionary({
query2.WhereCriteria->Set("object_id", checkable); { "object_id", checkable },
query2.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(timeBag.first)); { "entry_time", DbValue::FromTimestamp(timeBag.first) },
query2.WhereCriteria->Set("name", comment->GetName()); { "name", comment->GetName() }
});
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
} }
@ -509,10 +516,11 @@ void DbEvents::AddDowntimeInternal(std::vector<DbQuery>& queries, const Downtime
fields1->Set("session_token", 0); /* DbConnection class fills in real ID */ fields1->Set("session_token", 0); /* DbConnection class fills in real ID */
query1.WhereCriteria = new Dictionary(); query1.WhereCriteria = new Dictionary({
query1.WhereCriteria->Set("object_id", checkable); { "object_id", checkable },
query1.WhereCriteria->Set("name", downtime->GetName()); { "name", downtime->GetName() },
query1.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(downtime->GetEntryTime())); { "entry_time", DbValue::FromTimestamp(downtime->GetEntryTime()) }
});
} else { } else {
query1.Table = "downtimehistory"; query1.Table = "downtimehistory";
query1.Type = DbQueryInsert; query1.Type = DbQueryInsert;
@ -599,13 +607,15 @@ void DbEvents::RemoveDowntimeInternal(std::vector<DbQuery>& queries, const Downt
fields3->Set("is_in_effect", 0); fields3->Set("is_in_effect", 0);
query3.Fields = fields3; query3.Fields = fields3;
query3.WhereCriteria = new Dictionary(); query3.WhereCriteria = new Dictionary({
query3.WhereCriteria->Set("object_id", checkable); { "object_id", checkable },
query3.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(downtime->GetEntryTime())); { "entry_time", DbValue::FromTimestamp(downtime->GetEntryTime()) },
query3.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 }, /* DbConnection class fills in real ID */
query3.WhereCriteria->Set("scheduled_start_time", DbValue::FromTimestamp(downtime->GetStartTime())); { "scheduled_start_time", DbValue::FromTimestamp(downtime->GetStartTime()) },
query3.WhereCriteria->Set("scheduled_end_time", DbValue::FromTimestamp(downtime->GetEndTime())); { "scheduled_end_time", DbValue::FromTimestamp(downtime->GetEndTime()) },
query3.WhereCriteria->Set("name", downtime->GetName()); { "name", downtime->GetName() }
});
queries.emplace_back(std::move(query3)); queries.emplace_back(std::move(query3));
/* host/service status */ /* host/service status */
@ -650,23 +660,24 @@ void DbEvents::TriggerDowntime(const Downtime::Ptr& downtime)
query1.Type = DbQueryUpdate; query1.Type = DbQueryUpdate;
query1.Category = DbCatDowntime; query1.Category = DbCatDowntime;
Dictionary::Ptr fields1 = new Dictionary(); query1.Fields = new Dictionary({
fields1->Set("was_started", 1); { "was_started", 1 },
fields1->Set("actual_start_time", DbValue::FromTimestamp(timeBag.first)); { "actual_start_time", DbValue::FromTimestamp(timeBag.first) },
fields1->Set("actual_start_time_usec", timeBag.second); { "actual_start_time_usec", timeBag.second },
fields1->Set("is_in_effect", (downtime->IsInEffect() ? 1 : 0)); { "is_in_effect", (downtime->IsInEffect() ? 1 : 0) },
fields1->Set("trigger_time", DbValue::FromTimestamp(downtime->GetTriggerTime())); { "trigger_time", DbValue::FromTimestamp(downtime->GetTriggerTime()) },
fields1->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 } /* DbConnection class fills in real ID */
});
query1.WhereCriteria = new Dictionary(); query1.WhereCriteria = new Dictionary({
query1.WhereCriteria->Set("object_id", checkable); { "object_id", checkable },
query1.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(downtime->GetEntryTime())); { "entry_time", DbValue::FromTimestamp(downtime->GetEntryTime()) },
query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 }, /* DbConnection class fills in real ID */
query1.WhereCriteria->Set("scheduled_start_time", DbValue::FromTimestamp(downtime->GetStartTime())); { "scheduled_start_time", DbValue::FromTimestamp(downtime->GetStartTime()) },
query1.WhereCriteria->Set("scheduled_end_time", DbValue::FromTimestamp(downtime->GetEndTime())); { "scheduled_end_time", DbValue::FromTimestamp(downtime->GetEndTime()) },
query1.WhereCriteria->Set("name", downtime->GetName()); { "name", downtime->GetName() }
});
query1.Fields = fields1;
DbObject::OnQuery(query1); DbObject::OnQuery(query1);
/* History - downtime was started for service (and host in case) */ /* History - downtime was started for service (and host in case) */
@ -675,13 +686,13 @@ void DbEvents::TriggerDowntime(const Downtime::Ptr& downtime)
query3.Type = DbQueryUpdate; query3.Type = DbQueryUpdate;
query3.Category = DbCatDowntime; query3.Category = DbCatDowntime;
Dictionary::Ptr fields3 = new Dictionary(); query3.Fields = new Dictionary({
fields3->Set("was_started", 1); { "was_started", 1 },
fields3->Set("is_in_effect", 1); { "is_in_effect", 1 },
fields3->Set("actual_start_time", DbValue::FromTimestamp(timeBag.first)); { "actual_start_time", DbValue::FromTimestamp(timeBag.first) },
fields3->Set("actual_start_time_usec", timeBag.second); { "actual_start_time_usec", timeBag.second },
fields3->Set("trigger_time", DbValue::FromTimestamp(downtime->GetTriggerTime())); { "trigger_time", DbValue::FromTimestamp(downtime->GetTriggerTime()) }
query3.Fields = fields3; });
query3.WhereCriteria = query1.WhereCriteria; query3.WhereCriteria = query1.WhereCriteria;
@ -708,10 +719,9 @@ void DbEvents::TriggerDowntime(const Downtime::Ptr& downtime)
query4.StatusUpdate = true; query4.StatusUpdate = true;
query4.Object = DbObject::GetOrCreateByObject(checkable); query4.Object = DbObject::GetOrCreateByObject(checkable);
Dictionary::Ptr fields4 = new Dictionary(); query4.Fields = new Dictionary({
fields4->Set("scheduled_downtime_depth", checkable->GetDowntimeDepth()); { "scheduled_downtime_depth", checkable->GetDowntimeDepth() }
});
query4.Fields = fields4;
query4.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ query4.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbObject::OnQuery(query4); DbObject::OnQuery(query4);
@ -801,11 +811,11 @@ void DbEvents::AddAcknowledgementInternal(const Checkable::Ptr& checkable, Ackno
query1.StatusUpdate = true; query1.StatusUpdate = true;
query1.Object = DbObject::GetOrCreateByObject(checkable); query1.Object = DbObject::GetOrCreateByObject(checkable);
Dictionary::Ptr fields1 = new Dictionary(); query1.Fields = new Dictionary({
fields1->Set("acknowledgement_type", type); { "acknowledgement_type", type },
fields1->Set("problem_has_been_acknowledged", add ? 1 : 0); { "problem_has_been_acknowledged", add ? 1 : 0 }
});
query1.Fields = fields1;
query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbObject::OnQuery(query1); DbObject::OnQuery(query1);
@ -873,17 +883,16 @@ void DbEvents::AddNotificationHistory(const Notification::Ptr& notification, con
query2.Type = DbQueryInsert; query2.Type = DbQueryInsert;
query2.Category = DbCatNotification; query2.Category = DbCatNotification;
Dictionary::Ptr fields2 = new Dictionary(); query2.Fields = new Dictionary({
fields2->Set("contact_object_id", user); { "contact_object_id", user },
fields2->Set("start_time", DbValue::FromTimestamp(timeBag.first)); { "start_time", DbValue::FromTimestamp(timeBag.first) },
fields2->Set("start_time_usec", timeBag.second); { "start_time_usec", timeBag.second },
fields2->Set("end_time", DbValue::FromTimestamp(timeBag.first)); { "end_time", DbValue::FromTimestamp(timeBag.first) },
fields2->Set("end_time_usec", timeBag.second); { "end_time_usec", timeBag.second },
{ "notification_id", query1.NotificationInsertID },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
fields2->Set("notification_id", query1.NotificationInsertID);
fields2->Set("instance_id", 0); /* DbConnection class fills in real ID */
query2.Fields = fields2;
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
} }

View File

@ -146,8 +146,9 @@ void DbObject::SendConfigUpdateHeavy(const Dictionary::Ptr& configFields)
query.Fields->Set(GetType()->GetIDColumn(), object); query.Fields->Set(GetType()->GetIDColumn(), object);
query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */
query.Fields->Set("config_type", 1); query.Fields->Set("config_type", 1);
query.WhereCriteria = new Dictionary(); query.WhereCriteria = new Dictionary({
query.WhereCriteria->Set(GetType()->GetIDColumn(), object); { GetType()->GetIDColumn(), object }
});
query.Object = this; query.Object = this;
query.ConfigUpdate = true; query.ConfigUpdate = true;
OnQuery(query); OnQuery(query);
@ -189,8 +190,9 @@ void DbObject::SendStatusUpdate()
query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */
query.Fields->Set("status_update_time", DbValue::FromTimestamp(Utility::GetTime())); query.Fields->Set("status_update_time", DbValue::FromTimestamp(Utility::GetTime()));
query.WhereCriteria = new Dictionary(); query.WhereCriteria = new Dictionary({
query.WhereCriteria->Set(GetType()->GetIDColumn(), GetObject()); { GetType()->GetIDColumn(), GetObject() }
});
query.Object = this; query.Object = this;
query.StatusUpdate = true; query.StatusUpdate = true;
OnQuery(query); OnQuery(query);
@ -215,16 +217,18 @@ void DbObject::SendVarsConfigUpdateHeavy()
query1.Table = "customvariables"; query1.Table = "customvariables";
query1.Type = DbQueryDelete; query1.Type = DbQueryDelete;
query1.Category = DbCatConfig; query1.Category = DbCatConfig;
query1.WhereCriteria = new Dictionary(); query1.WhereCriteria = new Dictionary({
query1.WhereCriteria->Set("object_id", obj); { "object_id", obj }
});
queries.emplace_back(std::move(query1)); queries.emplace_back(std::move(query1));
DbQuery query2; DbQuery query2;
query2.Table = "customvariablestatus"; query2.Table = "customvariablestatus";
query2.Type = DbQueryDelete; query2.Type = DbQueryDelete;
query2.Category = DbCatConfig; query2.Category = DbCatConfig;
query2.WhereCriteria = new Dictionary(); query2.WhereCriteria = new Dictionary({
query2.WhereCriteria->Set("object_id", obj); { "object_id", obj }
});
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
Dictionary::Ptr vars = custom_var_object->GetVars(); Dictionary::Ptr vars = custom_var_object->GetVars();
@ -245,19 +249,18 @@ void DbObject::SendVarsConfigUpdateHeavy()
} else } else
value = kv.second; value = kv.second;
Dictionary::Ptr fields = new Dictionary();
fields->Set("varname", kv.first);
fields->Set("varvalue", value);
fields->Set("is_json", is_json);
fields->Set("config_type", 1);
fields->Set("object_id", obj);
fields->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query3; DbQuery query3;
query3.Table = "customvariables"; query3.Table = "customvariables";
query3.Type = DbQueryInsert; query3.Type = DbQueryInsert;
query3.Category = DbCatConfig; query3.Category = DbCatConfig;
query3.Fields = fields; query3.Fields = new Dictionary({
{ "varname", kv.first },
{ "varvalue", value },
{ "is_json", is_json },
{ "config_type", 1 },
{ "object_id", obj },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
queries.emplace_back(std::move(query3)); queries.emplace_back(std::move(query3));
} }
} }
@ -293,23 +296,25 @@ void DbObject::SendVarsStatusUpdate()
} else } else
value = kv.second; value = kv.second;
Dictionary::Ptr fields = new Dictionary();
fields->Set("varname", kv.first);
fields->Set("varvalue", value);
fields->Set("is_json", is_json);
fields->Set("status_update_time", DbValue::FromTimestamp(Utility::GetTime()));
fields->Set("object_id", obj);
fields->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query; DbQuery query;
query.Table = "customvariablestatus"; query.Table = "customvariablestatus";
query.Type = DbQueryInsert | DbQueryUpdate; query.Type = DbQueryInsert | DbQueryUpdate;
query.Category = DbCatState; query.Category = DbCatState;
query.Fields = fields;
query.WhereCriteria = new Dictionary(); query.Fields = new Dictionary({
query.WhereCriteria->Set("object_id", obj); { "varname", kv.first },
query.WhereCriteria->Set("varname", kv.first); { "varvalue", value },
{ "is_json", is_json },
{ "status_update_time", DbValue::FromTimestamp(Utility::GetTime()) },
{ "object_id", obj },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
query.WhereCriteria = new Dictionary({
{ "object_id", obj },
{ "varname", kv.first }
});
queries.emplace_back(std::move(query)); queries.emplace_back(std::move(query));
} }

View File

@ -46,30 +46,29 @@ EndpointDbObject::EndpointDbObject(const DbType::Ptr& type, const String& name1,
Dictionary::Ptr EndpointDbObject::GetConfigFields() const Dictionary::Ptr EndpointDbObject::GetConfigFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
Endpoint::Ptr endpoint = static_pointer_cast<Endpoint>(GetObject()); Endpoint::Ptr endpoint = static_pointer_cast<Endpoint>(GetObject());
fields->Set("identity", endpoint->GetName()); return new Dictionary({
fields->Set("node", IcingaApplication::GetInstance()->GetNodeName()); { "identity", endpoint->GetName() },
fields->Set("zone_object_id", endpoint->GetZone()); { "node", IcingaApplication::GetInstance()->GetNodeName() },
{ "zone_object_id", endpoint->GetZone() }
return fields; });
} }
Dictionary::Ptr EndpointDbObject::GetStatusFields() const Dictionary::Ptr EndpointDbObject::GetStatusFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
Endpoint::Ptr endpoint = static_pointer_cast<Endpoint>(GetObject()); Endpoint::Ptr endpoint = static_pointer_cast<Endpoint>(GetObject());
Log(LogDebug, "EndpointDbObject") Log(LogDebug, "EndpointDbObject")
<< "update status for endpoint '" << endpoint->GetName() << "'"; << "update status for endpoint '" << endpoint->GetName() << "'";
fields->Set("identity", endpoint->GetName()); return new Dictionary({
fields->Set("node", IcingaApplication::GetInstance()->GetNodeName()); { "identity", endpoint->GetName() },
fields->Set("zone_object_id", endpoint->GetZone()); { "node", IcingaApplication::GetInstance()->GetNodeName() },
fields->Set("is_connected", EndpointIsConnected(endpoint)); { "zone_object_id", endpoint->GetZone() },
{ "is_connected", EndpointIsConnected(endpoint) }
return fields; });
} }
void EndpointDbObject::UpdateConnectedStatus(const Endpoint::Ptr& endpoint) void EndpointDbObject::UpdateConnectedStatus(const Endpoint::Ptr& endpoint)
@ -84,14 +83,15 @@ void EndpointDbObject::UpdateConnectedStatus(const Endpoint::Ptr& endpoint)
query1.Type = DbQueryUpdate; query1.Type = DbQueryUpdate;
query1.Category = DbCatState; query1.Category = DbCatState;
Dictionary::Ptr fields1 = new Dictionary(); query1.Fields = new Dictionary({
fields1->Set("is_connected", (connected ? 1 : 0)); { "is_connected", (connected ? 1 : 0) },
fields1->Set("status_update_time", DbValue::FromTimestamp(Utility::GetTime())); { "status_update_time", DbValue::FromTimestamp(Utility::GetTime()) }
query1.Fields = fields1; });
query1.WhereCriteria = new Dictionary(); query1.WhereCriteria = new Dictionary({
query1.WhereCriteria->Set("endpoint_object_id", endpoint); { "endpoint_object_id", endpoint },
query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 } /* DbConnection class fills in real ID */
});
OnQuery(query1); OnQuery(query1);
} }

View File

@ -51,50 +51,42 @@ Dictionary::Ptr HostDbObject::GetConfigFields() const
/* Compatibility fallback. */ /* Compatibility fallback. */
String displayName = host->GetDisplayName(); String displayName = host->GetDisplayName();
if (!displayName.IsEmpty())
fields->Set("alias", displayName);
else
fields->Set("alias", host->GetName());
fields->Set("display_name", displayName);
fields->Set("address", host->GetAddress());
fields->Set("address6", host->GetAddress6());
fields->Set("check_command_object_id", host->GetCheckCommand());
fields->Set("eventhandler_command_object_id", host->GetEventCommand());
fields->Set("check_timeperiod_object_id", host->GetCheckPeriod());
fields->Set("check_interval", host->GetCheckInterval() / 60.0);
fields->Set("retry_interval", host->GetRetryInterval() / 60.0);
fields->Set("max_check_attempts", host->GetMaxCheckAttempts());
fields->Set("flap_detection_enabled", host->GetEnableFlapping());
fields->Set("low_flap_threshold", host->GetFlappingThresholdLow());
fields->Set("high_flap_threshold", host->GetFlappingThresholdLow());
fields->Set("process_performance_data", host->GetEnablePerfdata());
fields->Set("freshness_checks_enabled", 1);
fields->Set("freshness_threshold", Convert::ToLong(host->GetCheckInterval()));
fields->Set("event_handler_enabled", host->GetEnableEventHandler());
fields->Set("passive_checks_enabled", host->GetEnablePassiveChecks());
fields->Set("active_checks_enabled", host->GetEnableActiveChecks());
fields->Set("notifications_enabled", host->GetEnableNotifications());
fields->Set("notes", host->GetNotes());
fields->Set("notes_url", host->GetNotesUrl());
fields->Set("action_url", host->GetActionUrl());
fields->Set("icon_image", host->GetIconImage());
fields->Set("icon_image_alt", host->GetIconImageAlt());
fields->Set("notification_interval", CompatUtility::GetCheckableNotificationNotificationInterval(host));
unsigned long notificationStateFilter = CompatUtility::GetCheckableNotificationTypeFilter(host); unsigned long notificationStateFilter = CompatUtility::GetCheckableNotificationTypeFilter(host);
unsigned long notificationTypeFilter = CompatUtility::GetCheckableNotificationTypeFilter(host); unsigned long notificationTypeFilter = CompatUtility::GetCheckableNotificationTypeFilter(host);
fields->Set("notify_on_down", (notificationStateFilter & ServiceWarning) || (notificationStateFilter && ServiceCritical)); return new Dictionary({
fields->Set("notify_on_unreachable", 1); /* We don't have this filter and state, and as such we don't filter such notifications. */ { "alias", !displayName.IsEmpty() ? displayName : host->GetName() },
fields->Set("notify_on_recovery", notificationTypeFilter & NotificationRecovery); { "display_name", displayName },
fields->Set("notify_on_flapping", (notificationTypeFilter & NotificationFlappingStart) || { "address", host->GetAddress() },
(notificationTypeFilter & NotificationFlappingEnd)); { "address6", host->GetAddress6() },
fields->Set("notify_on_downtime", (notificationTypeFilter & NotificationDowntimeStart) || { "check_command_object_id", host->GetCheckCommand() },
(notificationTypeFilter & NotificationDowntimeEnd) || (notificationTypeFilter & NotificationDowntimeRemoved)); { "eventhandler_command_object_id", host->GetEventCommand() },
{ "check_timeperiod_object_id", host->GetCheckPeriod() },
return fields; { "check_interval", host->GetCheckInterval() / 60.0 },
{ "retry_interval", host->GetRetryInterval() / 60.0 },
{ "max_check_attempts", host->GetMaxCheckAttempts() },
{ "flap_detection_enabled", host->GetEnableFlapping() },
{ "low_flap_threshold", host->GetFlappingThresholdLow() },
{ "high_flap_threshold", host->GetFlappingThresholdLow() },
{ "process_performance_data", host->GetEnablePerfdata() },
{ "freshness_checks_enabled", 1 },
{ "freshness_threshold", Convert::ToLong(host->GetCheckInterval()) },
{ "event_handler_enabled", host->GetEnableEventHandler() },
{ "passive_checks_enabled", host->GetEnablePassiveChecks() },
{ "active_checks_enabled", host->GetEnableActiveChecks() },
{ "notifications_enabled", host->GetEnableNotifications() },
{ "notes", host->GetNotes() },
{ "notes_url", host->GetNotesUrl() },
{ "action_url", host->GetActionUrl() },
{ "icon_image", host->GetIconImage() },
{ "icon_image_alt", host->GetIconImageAlt() },
{ "notification_interval", CompatUtility::GetCheckableNotificationNotificationInterval(host) },
{ "notify_on_down", (notificationStateFilter & ServiceWarning) || (notificationStateFilter && ServiceCritical) },
{ "notify_on_unreachable", 1 }, /* We don't have this filter and state, and as such we don't filter such notifications. */
{ "notify_on_recovery", notificationTypeFilter & NotificationRecovery },
{ "notify_on_flapping", (notificationTypeFilter & NotificationFlappingStart) || (notificationTypeFilter & NotificationFlappingEnd) },
{ "notify_on_downtime", (notificationTypeFilter & NotificationDowntimeStart) || (notificationTypeFilter & NotificationDowntimeEnd) || (notificationTypeFilter & NotificationDowntimeRemoved) }
});
} }
Dictionary::Ptr HostDbObject::GetStatusFields() const Dictionary::Ptr HostDbObject::GetStatusFields() const
@ -193,14 +185,16 @@ void HostDbObject::OnConfigUpdateHeavy()
query2.Table = DbType::GetByName("HostGroup")->GetTable() + "_members"; query2.Table = DbType::GetByName("HostGroup")->GetTable() + "_members";
query2.Type = DbQueryInsert; query2.Type = DbQueryInsert;
query2.Category = DbCatConfig; query2.Category = DbCatConfig;
query2.Fields = new Dictionary(); query2.Fields = new Dictionary({
query2.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 }, /* DbConnection class fills in real ID */
query2.Fields->Set("hostgroup_id", DbValue::FromObjectInsertID(group)); { "hostgroup_id", DbValue::FromObjectInsertID(group) },
query2.Fields->Set("host_object_id", host); { "host_object_id", host }
query2.WhereCriteria = new Dictionary(); });
query2.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ query2.WhereCriteria = new Dictionary({
query2.WhereCriteria->Set("hostgroup_id", DbValue::FromObjectInsertID(group)); { "instance_id", 0 }, /* DbConnection class fills in real ID */
query2.WhereCriteria->Set("host_object_id", host); { "hostgroup_id", DbValue::FromObjectInsertID(group) },
{ "host_object_id", host }
});
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
} }
} }
@ -213,8 +207,9 @@ void HostDbObject::OnConfigUpdateHeavy()
query2.Table = GetType()->GetTable() + "_parenthosts"; query2.Table = GetType()->GetTable() + "_parenthosts";
query2.Type = DbQueryDelete; query2.Type = DbQueryDelete;
query2.Category = DbCatConfig; query2.Category = DbCatConfig;
query2.WhereCriteria = new Dictionary(); query2.WhereCriteria = new Dictionary({
query2.WhereCriteria->Set(GetType()->GetTable() + "_id", DbValue::FromObjectInsertID(GetObject())); { GetType()->GetTable() + "_id", DbValue::FromObjectInsertID(GetObject()) }
});
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
/* parents */ /* parents */
@ -228,16 +223,15 @@ void HostDbObject::OnConfigUpdateHeavy()
<< "host parents: " << parent->GetName(); << "host parents: " << parent->GetName();
/* parents: host_id, parent_host_object_id */ /* parents: host_id, parent_host_object_id */
Dictionary::Ptr fields1 = new Dictionary();
fields1->Set(GetType()->GetTable() + "_id", DbValue::FromObjectInsertID(GetObject()));
fields1->Set("parent_host_object_id", parent);
fields1->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query1; DbQuery query1;
query1.Table = GetType()->GetTable() + "_parenthosts"; query1.Table = GetType()->GetTable() + "_parenthosts";
query1.Type = DbQueryInsert; query1.Type = DbQueryInsert;
query1.Category = DbCatConfig; query1.Category = DbCatConfig;
query1.Fields = fields1; query1.Fields = new Dictionary({
{ GetType()->GetTable() + "_id", DbValue::FromObjectInsertID(GetObject()) },
{ "parent_host_object_id", parent },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
queries.emplace_back(std::move(query1)); queries.emplace_back(std::move(query1));
} }
@ -253,8 +247,9 @@ void HostDbObject::OnConfigUpdateHeavy()
query3.Table = GetType()->GetTable() + "dependencies"; query3.Table = GetType()->GetTable() + "dependencies";
query3.Type = DbQueryDelete; query3.Type = DbQueryDelete;
query3.Category = DbCatConfig; query3.Category = DbCatConfig;
query3.WhereCriteria = new Dictionary(); query3.WhereCriteria = new Dictionary({
query3.WhereCriteria->Set("dependent_host_object_id", host); { "dependent_host_object_id", host }
});
queries.emplace_back(std::move(query3)); queries.emplace_back(std::move(query3));
for (const Dependency::Ptr& dep : host->GetDependencies()) { for (const Dependency::Ptr& dep : host->GetDependencies()) {
@ -271,20 +266,19 @@ void HostDbObject::OnConfigUpdateHeavy()
Log(LogDebug, "HostDbObject") Log(LogDebug, "HostDbObject")
<< "parent host: " << parent->GetName(); << "parent host: " << parent->GetName();
Dictionary::Ptr fields2 = new Dictionary();
fields2->Set("host_object_id", parent);
fields2->Set("dependent_host_object_id", host);
fields2->Set("inherits_parent", 1);
fields2->Set("timeperiod_object_id", dep->GetPeriod());
fields2->Set("fail_on_up", stateFilter & StateFilterUp);
fields2->Set("fail_on_down", stateFilter & StateFilterDown);
fields2->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query2; DbQuery query2;
query2.Table = GetType()->GetTable() + "dependencies"; query2.Table = GetType()->GetTable() + "dependencies";
query2.Type = DbQueryInsert; query2.Type = DbQueryInsert;
query2.Category = DbCatConfig; query2.Category = DbCatConfig;
query2.Fields = fields2; query2.Fields = new Dictionary({
{ "host_object_id", parent },
{ "dependent_host_object_id", host },
{ "inherits_parent", 1 },
{ "timeperiod_object_id", dep->GetPeriod() },
{ "fail_on_up", stateFilter & StateFilterUp },
{ "fail_on_down", stateFilter & StateFilterDown },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
} }
@ -299,24 +293,24 @@ void HostDbObject::OnConfigUpdateHeavy()
query4.Table = GetType()->GetTable() + "_contacts"; query4.Table = GetType()->GetTable() + "_contacts";
query4.Type = DbQueryDelete; query4.Type = DbQueryDelete;
query4.Category = DbCatConfig; query4.Category = DbCatConfig;
query4.WhereCriteria = new Dictionary(); query4.WhereCriteria = new Dictionary({
query4.WhereCriteria->Set("host_id", DbValue::FromObjectInsertID(host)); { "host_id", DbValue::FromObjectInsertID(host) }
});
queries.emplace_back(std::move(query4)); queries.emplace_back(std::move(query4));
for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(host)) { for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(host)) {
Log(LogDebug, "HostDbObject") Log(LogDebug, "HostDbObject")
<< "host contacts: " << user->GetName(); << "host contacts: " << user->GetName();
Dictionary::Ptr fields_contact = new Dictionary();
fields_contact->Set("host_id", DbValue::FromObjectInsertID(host));
fields_contact->Set("contact_object_id", user);
fields_contact->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query_contact; DbQuery query_contact;
query_contact.Table = GetType()->GetTable() + "_contacts"; query_contact.Table = GetType()->GetTable() + "_contacts";
query_contact.Type = DbQueryInsert; query_contact.Type = DbQueryInsert;
query_contact.Category = DbCatConfig; query_contact.Category = DbCatConfig;
query_contact.Fields = fields_contact; query_contact.Fields = new Dictionary({
{ "host_id", DbValue::FromObjectInsertID(host) },
{ "contact_object_id", user },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
queries.emplace_back(std::move(query_contact)); queries.emplace_back(std::move(query_contact));
} }
@ -331,24 +325,24 @@ void HostDbObject::OnConfigUpdateHeavy()
query5.Table = GetType()->GetTable() + "_contactgroups"; query5.Table = GetType()->GetTable() + "_contactgroups";
query5.Type = DbQueryDelete; query5.Type = DbQueryDelete;
query5.Category = DbCatConfig; query5.Category = DbCatConfig;
query5.WhereCriteria = new Dictionary(); query5.WhereCriteria = new Dictionary({
query5.WhereCriteria->Set("host_id", DbValue::FromObjectInsertID(host)); { "host_id", DbValue::FromObjectInsertID(host) }
});
queries.emplace_back(std::move(query5)); queries.emplace_back(std::move(query5));
for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(host)) { for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(host)) {
Log(LogDebug, "HostDbObject") Log(LogDebug, "HostDbObject")
<< "host contactgroups: " << usergroup->GetName(); << "host contactgroups: " << usergroup->GetName();
Dictionary::Ptr fields_contact = new Dictionary();
fields_contact->Set("host_id", DbValue::FromObjectInsertID(host));
fields_contact->Set("contactgroup_object_id", usergroup);
fields_contact->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query_contact; DbQuery query_contact;
query_contact.Table = GetType()->GetTable() + "_contactgroups"; query_contact.Table = GetType()->GetTable() + "_contactgroups";
query_contact.Type = DbQueryInsert; query_contact.Type = DbQueryInsert;
query_contact.Category = DbCatConfig; query_contact.Category = DbCatConfig;
query_contact.Fields = fields_contact; query_contact.Fields = new Dictionary({
{ "host_id", DbValue::FromObjectInsertID(host) },
{ "contactgroup_object_id", usergroup },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
queries.emplace_back(std::move(query_contact)); queries.emplace_back(std::move(query_contact));
} }
@ -382,7 +376,7 @@ String HostDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields) co
if (groups) if (groups)
hashData += DbObject::HashValue(groups); hashData += DbObject::HashValue(groups);
Array::Ptr parents = new Array(); ArrayData parents;
/* parents */ /* parents */
for (const Checkable::Ptr& checkable : host->GetParents()) { for (const Checkable::Ptr& checkable : host->GetParents()) {
@ -391,14 +385,14 @@ String HostDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields) co
if (!parent) if (!parent)
continue; continue;
parents->Add(parent->GetName()); parents.push_back(parent->GetName());
} }
parents->Sort(); std::sort(parents.begin(), parents.end());
hashData += DbObject::HashValue(parents); hashData += DbObject::HashValue(new Array(std::move(parents)));
Array::Ptr dependencies = new Array(); ArrayData dependencies;
/* dependencies */ /* dependencies */
for (const Dependency::Ptr& dep : host->GetDependencies()) { for (const Dependency::Ptr& dep : host->GetDependencies()) {
@ -407,37 +401,36 @@ String HostDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields) co
if (!parent) if (!parent)
continue; continue;
Array::Ptr depInfo = new Array(); dependencies.push_back(new Array({
depInfo->Add(parent->GetName()); parent->GetName(),
depInfo->Add(dep->GetStateFilter()); dep->GetStateFilter(),
depInfo->Add(dep->GetPeriodRaw()); dep->GetPeriodRaw()
}));
dependencies->Add(depInfo);
} }
dependencies->Sort(); std::sort(dependencies.begin(), dependencies.end());
hashData += DbObject::HashValue(dependencies); hashData += DbObject::HashValue(new Array(std::move(dependencies)));
Array::Ptr users = new Array(); ArrayData users;
for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(host)) { for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(host)) {
users->Add(user->GetName()); users.push_back(user->GetName());
} }
users->Sort(); std::sort(users.begin(), users.end());
hashData += DbObject::HashValue(users); hashData += DbObject::HashValue(new Array(std::move(users)));
Array::Ptr userGroups = new Array(); ArrayData userGroups;
for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(host)) { for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(host)) {
userGroups->Add(usergroup->GetName()); userGroups.push_back(usergroup->GetName());
} }
userGroups->Sort(); std::sort(userGroups.begin(), userGroups.end());
hashData += DbObject::HashValue(userGroups); hashData += DbObject::HashValue(new Array(std::move(userGroups)));
return SHA256(hashData); return SHA256(hashData);
} }

View File

@ -34,15 +34,14 @@ HostGroupDbObject::HostGroupDbObject(const DbType::Ptr& type, const String& name
Dictionary::Ptr HostGroupDbObject::GetConfigFields() const Dictionary::Ptr HostGroupDbObject::GetConfigFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
HostGroup::Ptr group = static_pointer_cast<HostGroup>(GetObject()); HostGroup::Ptr group = static_pointer_cast<HostGroup>(GetObject());
fields->Set("alias", group->GetDisplayName()); return new Dictionary({
fields->Set("notes", group->GetNotes()); { "alias", group->GetDisplayName() },
fields->Set("notes_url", group->GetNotesUrl()); { "notes", group->GetNotes() },
fields->Set("action_url", group->GetActionUrl()); { "notes_url", group->GetNotesUrl() },
{ "action_url", group->GetActionUrl() }
return fields; });
} }
Dictionary::Ptr HostGroupDbObject::GetStatusFields() const Dictionary::Ptr HostGroupDbObject::GetStatusFields() const

View File

@ -181,14 +181,13 @@ void IdoCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const CheckResult
cr->SetOutput(msgbuf.str()); cr->SetOutput(msgbuf.str());
Array::Ptr perfdata = new Array(); cr->SetPerformanceData(new Array({
perfdata->Add(new PerfdataValue("queries", qps, false, "", queriesWarning, queriesCritical)); { new PerfdataValue("queries", qps, false, "", queriesWarning, queriesCritical) },
perfdata->Add(new PerfdataValue("queries_1min", conn->GetQueryCount(60))); { new PerfdataValue("queries_1min", conn->GetQueryCount(60)) },
perfdata->Add(new PerfdataValue("queries_5mins", conn->GetQueryCount(5 * 60))); { new PerfdataValue("queries_5mins", conn->GetQueryCount(5 * 60)) },
perfdata->Add(new PerfdataValue("queries_15mins", conn->GetQueryCount(15 * 60))); { new PerfdataValue("queries_15mins", conn->GetQueryCount(15 * 60)) },
perfdata->Add(new PerfdataValue("pending_queries", pendingQueries, false, "", pendingQueriesWarning, pendingQueriesCritical)); { new PerfdataValue("pending_queries", pendingQueries, false, "", pendingQueriesWarning, pendingQueriesCritical) }
}));
cr->SetPerformanceData(perfdata);
checkable->ProcessCheckResult(cr); checkable->ProcessCheckResult(cr);
} }

View File

@ -50,50 +50,45 @@ ServiceDbObject::ServiceDbObject(const DbType::Ptr& type, const String& name1, c
Dictionary::Ptr ServiceDbObject::GetConfigFields() const Dictionary::Ptr ServiceDbObject::GetConfigFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
Service::Ptr service = static_pointer_cast<Service>(GetObject()); Service::Ptr service = static_pointer_cast<Service>(GetObject());
Host::Ptr host = service->GetHost(); Host::Ptr host = service->GetHost();
fields->Set("host_object_id", host);
fields->Set("display_name", service->GetDisplayName());
fields->Set("check_command_object_id", service->GetCheckCommand());
fields->Set("eventhandler_command_object_id", service->GetEventCommand());
fields->Set("check_timeperiod_object_id", service->GetCheckPeriod());
fields->Set("check_interval", service->GetCheckInterval() / 60.0);
fields->Set("retry_interval", service->GetRetryInterval() / 60.0);
fields->Set("max_check_attempts", service->GetMaxCheckAttempts());
fields->Set("is_volatile", service->GetVolatile());
fields->Set("flap_detection_enabled", service->GetEnableFlapping());
fields->Set("low_flap_threshold", service->GetFlappingThresholdLow());
fields->Set("high_flap_threshold", service->GetFlappingThresholdLow());
fields->Set("process_performance_data", service->GetEnablePerfdata());
fields->Set("freshness_checks_enabled", 1);
fields->Set("freshness_threshold", Convert::ToLong(service->GetCheckInterval()));
fields->Set("event_handler_enabled", service->GetEnableEventHandler());
fields->Set("passive_checks_enabled", service->GetEnablePassiveChecks());
fields->Set("active_checks_enabled", service->GetEnableActiveChecks());
fields->Set("notifications_enabled", service->GetEnableNotifications());
fields->Set("notes", service->GetNotes());
fields->Set("notes_url", service->GetNotesUrl());
fields->Set("action_url", service->GetActionUrl());
fields->Set("icon_image", service->GetIconImage());
fields->Set("icon_image_alt", service->GetIconImageAlt());
fields->Set("notification_interval", CompatUtility::GetCheckableNotificationNotificationInterval(service));
unsigned long notificationStateFilter = CompatUtility::GetCheckableNotificationTypeFilter(service); unsigned long notificationStateFilter = CompatUtility::GetCheckableNotificationTypeFilter(service);
unsigned long notificationTypeFilter = CompatUtility::GetCheckableNotificationTypeFilter(service); unsigned long notificationTypeFilter = CompatUtility::GetCheckableNotificationTypeFilter(service);
fields->Set("notify_on_warning", notificationStateFilter & ServiceWarning); return new Dictionary({
fields->Set("notify_on_unknown", notificationStateFilter & ServiceUnknown); { "host_object_id", host },
fields->Set("notify_on_critical", notificationStateFilter & ServiceCritical); { "display_name", service->GetDisplayName() },
fields->Set("notify_on_recovery", notificationTypeFilter & NotificationRecovery); { "check_command_object_id", service->GetCheckCommand() },
fields->Set("notify_on_flapping", (notificationTypeFilter & NotificationFlappingStart) || { "eventhandler_command_object_id", service->GetEventCommand() },
(notificationTypeFilter & NotificationFlappingEnd)); { "check_timeperiod_object_id", service->GetCheckPeriod() },
fields->Set("notify_on_downtime", (notificationTypeFilter & NotificationDowntimeStart) || { "check_interval", service->GetCheckInterval() / 60.0 },
(notificationTypeFilter & NotificationDowntimeEnd) || (notificationTypeFilter & NotificationDowntimeRemoved)); { "retry_interval", service->GetRetryInterval() / 60.0 },
{ "max_check_attempts", service->GetMaxCheckAttempts() },
return fields; { "is_volatile", service->GetVolatile() },
{ "flap_detection_enabled", service->GetEnableFlapping() },
{ "low_flap_threshold", service->GetFlappingThresholdLow() },
{ "high_flap_threshold", service->GetFlappingThresholdLow() },
{ "process_performance_data", service->GetEnablePerfdata() },
{ "freshness_checks_enabled", 1 },
{ "freshness_threshold", Convert::ToLong(service->GetCheckInterval()) },
{ "event_handler_enabled", service->GetEnableEventHandler() },
{ "passive_checks_enabled", service->GetEnablePassiveChecks() },
{ "active_checks_enabled", service->GetEnableActiveChecks() },
{ "notifications_enabled", service->GetEnableNotifications() },
{ "notes", service->GetNotes() },
{ "notes_url", service->GetNotesUrl() },
{ "action_url", service->GetActionUrl() },
{ "icon_image", service->GetIconImage() },
{ "icon_image_alt", service->GetIconImageAlt() },
{ "notification_interval", CompatUtility::GetCheckableNotificationNotificationInterval(service) },
{ "notify_on_warning", notificationStateFilter & ServiceWarning },
{ "notify_on_unknown", notificationStateFilter & ServiceUnknown },
{ "notify_on_critical", notificationStateFilter & ServiceCritical },
{ "notify_on_recovery", notificationTypeFilter & NotificationRecovery },
{ "notify_on_flapping", (notificationTypeFilter & NotificationFlappingStart) || (notificationTypeFilter & NotificationFlappingEnd) },
{ "notify_on_downtime", (notificationTypeFilter & NotificationDowntimeStart) || (notificationTypeFilter & NotificationDowntimeEnd) || (notificationTypeFilter & NotificationDowntimeRemoved) }
});
} }
Dictionary::Ptr ServiceDbObject::GetStatusFields() const Dictionary::Ptr ServiceDbObject::GetStatusFields() const
@ -174,8 +169,9 @@ void ServiceDbObject::OnConfigUpdateHeavy()
query1.Table = DbType::GetByName("ServiceGroup")->GetTable() + "_members"; query1.Table = DbType::GetByName("ServiceGroup")->GetTable() + "_members";
query1.Type = DbQueryDelete; query1.Type = DbQueryDelete;
query1.Category = DbCatConfig; query1.Category = DbCatConfig;
query1.WhereCriteria = new Dictionary(); query1.WhereCriteria = new Dictionary({
query1.WhereCriteria->Set("service_object_id", service); { "service_object_id", service }
});
queries.emplace_back(std::move(query1)); queries.emplace_back(std::move(query1));
if (groups) { if (groups) {
@ -187,14 +183,16 @@ void ServiceDbObject::OnConfigUpdateHeavy()
query2.Table = DbType::GetByName("ServiceGroup")->GetTable() + "_members"; query2.Table = DbType::GetByName("ServiceGroup")->GetTable() + "_members";
query2.Type = DbQueryInsert; query2.Type = DbQueryInsert;
query2.Category = DbCatConfig; query2.Category = DbCatConfig;
query2.Fields = new Dictionary(); query2.Fields = new Dictionary({
query2.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 }, /* DbConnection class fills in real ID */
query2.Fields->Set("servicegroup_id", DbValue::FromObjectInsertID(group)); { "servicegroup_id", DbValue::FromObjectInsertID(group) },
query2.Fields->Set("service_object_id", service); { "service_object_id", service }
query2.WhereCriteria = new Dictionary(); });
query2.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ query2.WhereCriteria = new Dictionary({
query2.WhereCriteria->Set("servicegroup_id", DbValue::FromObjectInsertID(group)); { "instance_id", 0 }, /* DbConnection class fills in real ID */
query2.WhereCriteria->Set("service_object_id", service); { "servicegroup_id", DbValue::FromObjectInsertID(group) },
{ "service_object_id", service }
});
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
} }
} }
@ -211,8 +209,9 @@ void ServiceDbObject::OnConfigUpdateHeavy()
query2.Table = GetType()->GetTable() + "dependencies"; query2.Table = GetType()->GetTable() + "dependencies";
query2.Type = DbQueryDelete; query2.Type = DbQueryDelete;
query2.Category = DbCatConfig; query2.Category = DbCatConfig;
query2.WhereCriteria = new Dictionary(); query2.WhereCriteria = new Dictionary({
query2.WhereCriteria->Set("dependent_service_object_id", service); { "dependent_service_object_id", service }
});
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
for (const Dependency::Ptr& dep : service->GetDependencies()) { for (const Dependency::Ptr& dep : service->GetDependencies()) {
@ -230,22 +229,21 @@ void ServiceDbObject::OnConfigUpdateHeavy()
int stateFilter = dep->GetStateFilter(); int stateFilter = dep->GetStateFilter();
/* service dependencies */ /* service dependencies */
Dictionary::Ptr fields1 = new Dictionary();
fields1->Set("service_object_id", parent);
fields1->Set("dependent_service_object_id", service);
fields1->Set("inherits_parent", 1);
fields1->Set("timeperiod_object_id", dep->GetPeriod());
fields1->Set("fail_on_ok", stateFilter & StateFilterOK);
fields1->Set("fail_on_warning", stateFilter & StateFilterWarning);
fields1->Set("fail_on_critical", stateFilter & StateFilterCritical);
fields1->Set("fail_on_unknown", stateFilter & StateFilterUnknown);
fields1->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query1; DbQuery query1;
query1.Table = GetType()->GetTable() + "dependencies"; query1.Table = GetType()->GetTable() + "dependencies";
query1.Type = DbQueryInsert; query1.Type = DbQueryInsert;
query1.Category = DbCatConfig; query1.Category = DbCatConfig;
query1.Fields = fields1; query1.Fields = new Dictionary({
{ "service_object_id", parent },
{ "dependent_service_object_id", service },
{ "inherits_parent", 1 },
{ "timeperiod_object_id", dep->GetPeriod() },
{ "fail_on_ok", stateFilter & StateFilterOK },
{ "fail_on_warning", stateFilter & StateFilterWarning },
{ "fail_on_critical", stateFilter & StateFilterCritical },
{ "fail_on_unknown", stateFilter & StateFilterUnknown },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
queries.emplace_back(std::move(query1)); queries.emplace_back(std::move(query1));
} }
@ -261,24 +259,25 @@ void ServiceDbObject::OnConfigUpdateHeavy()
query3.Table = GetType()->GetTable() + "_contacts"; query3.Table = GetType()->GetTable() + "_contacts";
query3.Type = DbQueryDelete; query3.Type = DbQueryDelete;
query3.Category = DbCatConfig; query3.Category = DbCatConfig;
query3.WhereCriteria = new Dictionary(); query3.WhereCriteria = new Dictionary({
query3.WhereCriteria->Set("service_id", DbValue::FromObjectInsertID(service)); { "service_id", DbValue::FromObjectInsertID(service) }
});
queries.emplace_back(std::move(query3)); queries.emplace_back(std::move(query3));
for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(service)) { for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(service)) {
Log(LogDebug, "ServiceDbObject") Log(LogDebug, "ServiceDbObject")
<< "service contacts: " << user->GetName(); << "service contacts: " << user->GetName();
Dictionary::Ptr fields_contact = new Dictionary();
fields_contact->Set("service_id", DbValue::FromObjectInsertID(service));
fields_contact->Set("contact_object_id", user);
fields_contact->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query_contact; DbQuery query_contact;
query_contact.Table = GetType()->GetTable() + "_contacts"; query_contact.Table = GetType()->GetTable() + "_contacts";
query_contact.Type = DbQueryInsert; query_contact.Type = DbQueryInsert;
query_contact.Category = DbCatConfig; query_contact.Category = DbCatConfig;
query_contact.Fields = fields_contact; query_contact.Fields = new Dictionary({
{ "service_id", DbValue::FromObjectInsertID(service) },
{ "contact_object_id", user },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
queries.emplace_back(std::move(query_contact)); queries.emplace_back(std::move(query_contact));
} }
@ -293,24 +292,24 @@ void ServiceDbObject::OnConfigUpdateHeavy()
query4.Table = GetType()->GetTable() + "_contactgroups"; query4.Table = GetType()->GetTable() + "_contactgroups";
query4.Type = DbQueryDelete; query4.Type = DbQueryDelete;
query4.Category = DbCatConfig; query4.Category = DbCatConfig;
query4.WhereCriteria = new Dictionary(); query4.WhereCriteria = new Dictionary({
query4.WhereCriteria->Set("service_id", DbValue::FromObjectInsertID(service)); { "service_id", DbValue::FromObjectInsertID(service) }
});
queries.emplace_back(std::move(query4)); queries.emplace_back(std::move(query4));
for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(service)) { for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(service)) {
Log(LogDebug, "ServiceDbObject") Log(LogDebug, "ServiceDbObject")
<< "service contactgroups: " << usergroup->GetName(); << "service contactgroups: " << usergroup->GetName();
Dictionary::Ptr fields_contact = new Dictionary();
fields_contact->Set("service_id", DbValue::FromObjectInsertID(service));
fields_contact->Set("contactgroup_object_id", usergroup);
fields_contact->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query_contact; DbQuery query_contact;
query_contact.Table = GetType()->GetTable() + "_contactgroups"; query_contact.Table = GetType()->GetTable() + "_contactgroups";
query_contact.Type = DbQueryInsert; query_contact.Type = DbQueryInsert;
query_contact.Category = DbCatConfig; query_contact.Category = DbCatConfig;
query_contact.Fields = fields_contact; query_contact.Fields = new Dictionary({
{ "service_id", DbValue::FromObjectInsertID(service) },
{ "contactgroup_object_id", usergroup },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
queries.emplace_back(std::move(query_contact)); queries.emplace_back(std::move(query_contact));
} }
@ -344,7 +343,7 @@ String ServiceDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields)
if (groups) if (groups)
hashData += DbObject::HashValue(groups); hashData += DbObject::HashValue(groups);
Array::Ptr dependencies = new Array(); ArrayData dependencies;
/* dependencies */ /* dependencies */
for (const Dependency::Ptr& dep : service->GetDependencies()) { for (const Dependency::Ptr& dep : service->GetDependencies()) {
@ -353,37 +352,36 @@ String ServiceDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields)
if (!parent) if (!parent)
continue; continue;
Array::Ptr depInfo = new Array(); dependencies.push_back(new Array({
depInfo->Add(parent->GetName()); parent->GetName(),
depInfo->Add(dep->GetStateFilter()); dep->GetStateFilter(),
depInfo->Add(dep->GetPeriodRaw()); dep->GetPeriodRaw()
}));
dependencies->Add(depInfo);
} }
dependencies->Sort(); std::sort(dependencies.begin(), dependencies.end());
hashData += DbObject::HashValue(dependencies); hashData += DbObject::HashValue(new Array(std::move(dependencies)));
Array::Ptr users = new Array(); ArrayData users;
for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(service)) { for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(service)) {
users->Add(user->GetName()); users.push_back(user->GetName());
} }
users->Sort(); std::sort(users.begin(), users.end());
hashData += DbObject::HashValue(users); hashData += DbObject::HashValue(new Array(std::move(users)));
Array::Ptr userGroups = new Array(); ArrayData userGroups;
for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(service)) { for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(service)) {
userGroups->Add(usergroup->GetName()); userGroups.push_back(usergroup->GetName());
} }
userGroups->Sort(); std::sort(userGroups.begin(), userGroups.end());
hashData += DbObject::HashValue(userGroups); hashData += DbObject::HashValue(new Array(std::move(userGroups)));
return SHA256(hashData); return SHA256(hashData);
} }

View File

@ -33,15 +33,14 @@ ServiceGroupDbObject::ServiceGroupDbObject(const DbType::Ptr& type, const String
Dictionary::Ptr ServiceGroupDbObject::GetConfigFields() const Dictionary::Ptr ServiceGroupDbObject::GetConfigFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
ServiceGroup::Ptr group = static_pointer_cast<ServiceGroup>(GetObject()); ServiceGroup::Ptr group = static_pointer_cast<ServiceGroup>(GetObject());
fields->Set("alias", group->GetDisplayName()); return new Dictionary({
fields->Set("notes", group->GetNotes()); { "alias", group->GetDisplayName() },
fields->Set("notes_url", group->GetNotesUrl()); { "notes", group->GetNotes() },
fields->Set("action_url", group->GetActionUrl()); { "notes_url", group->GetNotesUrl() },
{ "action_url", group->GetActionUrl() }
return fields; });
} }
Dictionary::Ptr ServiceGroupDbObject::GetStatusFields() const Dictionary::Ptr ServiceGroupDbObject::GetStatusFields() const

View File

@ -36,12 +36,11 @@ TimePeriodDbObject::TimePeriodDbObject(const DbType::Ptr& type, const String& na
Dictionary::Ptr TimePeriodDbObject::GetConfigFields() const Dictionary::Ptr TimePeriodDbObject::GetConfigFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
TimePeriod::Ptr tp = static_pointer_cast<TimePeriod>(GetObject()); TimePeriod::Ptr tp = static_pointer_cast<TimePeriod>(GetObject());
fields->Set("alias", tp->GetDisplayName()); return new Dictionary({
{ "alias", tp->GetDisplayName() }
return fields; });
} }
Dictionary::Ptr TimePeriodDbObject::GetStatusFields() const Dictionary::Ptr TimePeriodDbObject::GetStatusFields() const
@ -57,8 +56,9 @@ void TimePeriodDbObject::OnConfigUpdateHeavy()
query_del1.Table = GetType()->GetTable() + "_timeranges"; query_del1.Table = GetType()->GetTable() + "_timeranges";
query_del1.Type = DbQueryDelete; query_del1.Type = DbQueryDelete;
query_del1.Category = DbCatConfig; query_del1.Category = DbCatConfig;
query_del1.WhereCriteria = new Dictionary(); query_del1.WhereCriteria = new Dictionary({
query_del1.WhereCriteria->Set("timeperiod_id", DbValue::FromObjectInsertID(tp)); { "timeperiod_id", DbValue::FromObjectInsertID(tp) }
});
OnQuery(query_del1); OnQuery(query_del1);
Dictionary::Ptr ranges = tp->GetRanges(); Dictionary::Ptr ranges = tp->GetRanges();
@ -89,12 +89,13 @@ void TimePeriodDbObject::OnConfigUpdateHeavy()
query.Table = GetType()->GetTable() + "_timeranges"; query.Table = GetType()->GetTable() + "_timeranges";
query.Type = DbQueryInsert; query.Type = DbQueryInsert;
query.Category = DbCatConfig; query.Category = DbCatConfig;
query.Fields = new Dictionary(); query.Fields = new Dictionary({
query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 }, /* DbConnection class fills in real ID */
query.Fields->Set("timeperiod_id", DbValue::FromObjectInsertID(tp)); { "timeperiod_id", DbValue::FromObjectInsertID(tp) },
query.Fields->Set("day", wday); { "day", wday },
query.Fields->Set("start_sec", begin % 86400); { "start_sec", begin % 86400 },
query.Fields->Set("end_sec", end % 86400); { "end_sec", end % 86400 }
});
OnQuery(query); OnQuery(query);
} }
} }

View File

@ -37,46 +37,43 @@ UserDbObject::UserDbObject(const DbType::Ptr& type, const String& name1, const S
Dictionary::Ptr UserDbObject::GetConfigFields() const Dictionary::Ptr UserDbObject::GetConfigFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
User::Ptr user = static_pointer_cast<User>(GetObject()); User::Ptr user = static_pointer_cast<User>(GetObject());
fields->Set("alias", user->GetDisplayName());
fields->Set("email_address", user->GetEmail());
fields->Set("pager_address", user->GetPager());
fields->Set("host_timeperiod_object_id", user->GetPeriod());
fields->Set("service_timeperiod_object_id", user->GetPeriod());
fields->Set("host_notifications_enabled", user->GetEnableNotifications());
fields->Set("service_notifications_enabled", user->GetEnableNotifications());
fields->Set("can_submit_commands", 1);
int typeFilter = user->GetTypeFilter(); int typeFilter = user->GetTypeFilter();
int stateFilter = user->GetStateFilter(); int stateFilter = user->GetStateFilter();
fields->Set("notify_service_recovery", (typeFilter & NotificationRecovery) != 0); return new Dictionary({
fields->Set("notify_service_warning", (stateFilter & StateFilterWarning) != 0); { "alias", user->GetDisplayName() },
fields->Set("notify_service_unknown", (stateFilter & StateFilterUnknown) != 0); { "email_address", user->GetEmail() },
fields->Set("notify_service_critical", (stateFilter & StateFilterCritical) != 0); { "pager_address", user->GetPager() },
fields->Set("notify_service_flapping", (typeFilter & (NotificationFlappingStart | NotificationFlappingEnd)) != 0); { "host_timeperiod_object_id", user->GetPeriod() },
fields->Set("notify_service_downtime", (typeFilter & (NotificationDowntimeStart | NotificationDowntimeEnd | NotificationDowntimeRemoved)) != 0); { "service_timeperiod_object_id", user->GetPeriod() },
fields->Set("notify_host_recovery", (typeFilter & NotificationRecovery) != 0); { "host_notifications_enabled", user->GetEnableNotifications() },
fields->Set("notify_host_down", (stateFilter & StateFilterDown) != 0); { "service_notifications_enabled", user->GetEnableNotifications() },
fields->Set("notify_host_flapping", (typeFilter & (NotificationFlappingStart | NotificationFlappingEnd)) != 0); { "can_submit_commands", 1 },
fields->Set("notify_host_downtime", (typeFilter & (NotificationDowntimeStart | NotificationDowntimeEnd | NotificationDowntimeRemoved)) != 0); { "notify_service_recovery", (typeFilter & NotificationRecovery) != 0 },
{ "notify_service_warning", (stateFilter & StateFilterWarning) != 0 },
return fields; { "notify_service_unknown", (stateFilter & StateFilterUnknown) != 0 },
{ "notify_service_critical", (stateFilter & StateFilterCritical) != 0 },
{ "notify_service_flapping", (typeFilter & (NotificationFlappingStart | NotificationFlappingEnd)) != 0 },
{ "notify_service_downtime", (typeFilter & (NotificationDowntimeStart | NotificationDowntimeEnd | NotificationDowntimeRemoved)) != 0 },
{ "notify_host_recovery", (typeFilter & NotificationRecovery) != 0 },
{ "notify_host_down", (stateFilter & StateFilterDown) != 0 },
{ "notify_host_flapping", (typeFilter & (NotificationFlappingStart | NotificationFlappingEnd)) != 0 },
{ "notify_host_downtime", (typeFilter & (NotificationDowntimeStart | NotificationDowntimeEnd | NotificationDowntimeRemoved)) != 0 }
});
} }
Dictionary::Ptr UserDbObject::GetStatusFields() const Dictionary::Ptr UserDbObject::GetStatusFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
User::Ptr user = static_pointer_cast<User>(GetObject()); User::Ptr user = static_pointer_cast<User>(GetObject());
fields->Set("host_notifications_enabled", user->GetEnableNotifications()); return new Dictionary({
fields->Set("service_notifications_enabled", user->GetEnableNotifications()); { "host_notifications_enabled", user->GetEnableNotifications() },
fields->Set("last_host_notification", DbValue::FromTimestamp(user->GetLastNotification())); { "service_notifications_enabled", user->GetEnableNotifications() },
fields->Set("last_service_notification", DbValue::FromTimestamp(user->GetLastNotification())); { "last_host_notification", DbValue::FromTimestamp(user->GetLastNotification()) },
{ "last_service_notification", DbValue::FromTimestamp(user->GetLastNotification()) }
return fields; });
} }
void UserDbObject::OnConfigUpdateHeavy() void UserDbObject::OnConfigUpdateHeavy()
@ -92,8 +89,9 @@ void UserDbObject::OnConfigUpdateHeavy()
query1.Table = DbType::GetByName("UserGroup")->GetTable() + "_members"; query1.Table = DbType::GetByName("UserGroup")->GetTable() + "_members";
query1.Type = DbQueryDelete; query1.Type = DbQueryDelete;
query1.Category = DbCatConfig; query1.Category = DbCatConfig;
query1.WhereCriteria = new Dictionary(); query1.WhereCriteria = new Dictionary({
query1.WhereCriteria->Set("contact_object_id", user); { "contact_object_id", user }
});
queries.emplace_back(std::move(query1)); queries.emplace_back(std::move(query1));
if (groups) { if (groups) {
@ -105,14 +103,16 @@ void UserDbObject::OnConfigUpdateHeavy()
query2.Table = DbType::GetByName("UserGroup")->GetTable() + "_members"; query2.Table = DbType::GetByName("UserGroup")->GetTable() + "_members";
query2.Type = DbQueryInsert | DbQueryUpdate; query2.Type = DbQueryInsert | DbQueryUpdate;
query2.Category = DbCatConfig; query2.Category = DbCatConfig;
query2.Fields = new Dictionary(); query2.Fields = new Dictionary({
query2.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ { "instance_id", 0 }, /* DbConnection class fills in real ID */
query2.Fields->Set("contactgroup_id", DbValue::FromObjectInsertID(group)); { "contactgroup_id", DbValue::FromObjectInsertID(group) },
query2.Fields->Set("contact_object_id", user); { "contact_object_id", user }
query2.WhereCriteria = new Dictionary(); });
query2.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ query2.WhereCriteria = new Dictionary({
query2.WhereCriteria->Set("contactgroup_id", DbValue::FromObjectInsertID(group)); { "instance_id", 0 }, /* DbConnection class fills in real ID */
query2.WhereCriteria->Set("contact_object_id", user); { "contactgroup_id", DbValue::FromObjectInsertID(group) },
{ "contact_object_id", user }
});
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
} }
} }
@ -125,16 +125,15 @@ void UserDbObject::OnConfigUpdateHeavy()
query2.Table = "contact_addresses"; query2.Table = "contact_addresses";
query2.Type = DbQueryDelete; query2.Type = DbQueryDelete;
query2.Category = DbCatConfig; query2.Category = DbCatConfig;
query2.WhereCriteria = new Dictionary(); query2.WhereCriteria = new Dictionary({
query2.WhereCriteria->Set("contact_id", DbValue::FromObjectInsertID(user)); { "contact_id", DbValue::FromObjectInsertID(user) }
});
queries.emplace_back(std::move(query2)); queries.emplace_back(std::move(query2));
Dictionary::Ptr vars = user->GetVars(); Dictionary::Ptr vars = user->GetVars();
if (vars) { /* This is sparta. */ if (vars) { /* This is sparta. */
for (int i = 1; i <= 6; i++) { for (int i = 1; i <= 6; i++) {
Dictionary::Ptr fields = new Dictionary();
String key = "address" + Convert::ToString(i); String key = "address" + Convert::ToString(i);
if (!vars->Contains(key)) if (!vars->Contains(key))
@ -142,16 +141,17 @@ void UserDbObject::OnConfigUpdateHeavy()
String val = vars->Get(key); String val = vars->Get(key);
fields->Set("contact_id", DbValue::FromObjectInsertID(user));
fields->Set("address_number", i);
fields->Set("address", val);
fields->Set("instance_id", 0); /* DbConnection class fills in real ID */
DbQuery query; DbQuery query;
query.Type = DbQueryInsert; query.Type = DbQueryInsert;
query.Table = "contact_addresses"; query.Table = "contact_addresses";
query.Category = DbCatConfig; query.Category = DbCatConfig;
query.Fields = fields; query.Fields = new Dictionary({
{ "contact_id", DbValue::FromObjectInsertID(user) },
{ "address_number", i },
{ "address", val },
{ "instance_id", 0 } /* DbConnection class fills in real ID */
});
queries.emplace_back(std::move(query)); queries.emplace_back(std::move(query));
} }
} }

View File

@ -34,12 +34,11 @@ UserGroupDbObject::UserGroupDbObject(const DbType::Ptr& type, const String& name
Dictionary::Ptr UserGroupDbObject::GetConfigFields() const Dictionary::Ptr UserGroupDbObject::GetConfigFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
UserGroup::Ptr group = static_pointer_cast<UserGroup>(GetObject()); UserGroup::Ptr group = static_pointer_cast<UserGroup>(GetObject());
fields->Set("alias", group->GetDisplayName()); return new Dictionary({
{ "alias", group->GetDisplayName() }
return fields; });
} }
Dictionary::Ptr UserGroupDbObject::GetStatusFields() const Dictionary::Ptr UserGroupDbObject::GetStatusFields() const

View File

@ -33,13 +33,13 @@ ZoneDbObject::ZoneDbObject(const DbType::Ptr& type, const String& name1, const S
Dictionary::Ptr ZoneDbObject::GetConfigFields() const Dictionary::Ptr ZoneDbObject::GetConfigFields() const
{ {
Dictionary::Ptr fields = new Dictionary();
Zone::Ptr zone = static_pointer_cast<Zone>(GetObject()); Zone::Ptr zone = static_pointer_cast<Zone>(GetObject());
fields->Set("is_global", zone->IsGlobal() ? 1 : 0); return new Dictionary({
fields->Set("parent_zone_object_id", zone->GetParent()); { "is_global", zone->IsGlobal() ? 1 : 0 },
{ "parent_zone_object_id", zone->GetParent() }
return fields; });
} }
Dictionary::Ptr ZoneDbObject::GetStatusFields() const Dictionary::Ptr ZoneDbObject::GetStatusFields() const
@ -49,8 +49,7 @@ Dictionary::Ptr ZoneDbObject::GetStatusFields() const
Log(LogDebug, "ZoneDbObject") Log(LogDebug, "ZoneDbObject")
<< "update status for zone '" << zone->GetName() << "'"; << "update status for zone '" << zone->GetName() << "'";
Dictionary::Ptr fields = new Dictionary(); return new Dictionary({
fields->Set("parent_zone_object_id", zone->GetParent()); { "parent_zone_object_id", zone->GetParent() }
});
return fields;
} }

View File

@ -55,20 +55,19 @@ void IdoMysqlConnection::OnConfigLoaded()
void IdoMysqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata) void IdoMysqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const IdoMysqlConnection::Ptr& idomysqlconnection : ConfigType::GetObjectsByType<IdoMysqlConnection>()) { for (const IdoMysqlConnection::Ptr& idomysqlconnection : ConfigType::GetObjectsByType<IdoMysqlConnection>()) {
size_t queryQueueItems = idomysqlconnection->m_QueryQueue.GetLength(); size_t queryQueueItems = idomysqlconnection->m_QueryQueue.GetLength();
double queryQueueItemRate = idomysqlconnection->m_QueryQueue.GetTaskCount(60) / 60.0; double queryQueueItemRate = idomysqlconnection->m_QueryQueue.GetTaskCount(60) / 60.0;
Dictionary::Ptr stats = new Dictionary(); nodes.emplace_back(idomysqlconnection->GetName(), new Dictionary({
stats->Set("version", idomysqlconnection->GetSchemaVersion()); { "version", idomysqlconnection->GetSchemaVersion() },
stats->Set("instance_name", idomysqlconnection->GetInstanceName()); { "instance_name", idomysqlconnection->GetInstanceName() },
stats->Set("connected", idomysqlconnection->GetConnected()); { "connected", idomysqlconnection->GetConnected() },
stats->Set("query_queue_items", queryQueueItems); { "query_queue_items", queryQueueItems },
stats->Set("query_queue_item_rate", queryQueueItemRate); { "query_queue_item_rate", queryQueueItemRate }
}));
nodes->Set(idomysqlconnection->GetName(), stats);
perfdata->Add(new PerfdataValue("idomysqlconnection_" + idomysqlconnection->GetName() + "_queries_rate", idomysqlconnection->GetQueryCount(60) / 60.0)); perfdata->Add(new PerfdataValue("idomysqlconnection_" + idomysqlconnection->GetName() + "_queries_rate", idomysqlconnection->GetQueryCount(60) / 60.0));
perfdata->Add(new PerfdataValue("idomysqlconnection_" + idomysqlconnection->GetName() + "_queries_1min", idomysqlconnection->GetQueryCount(60))); perfdata->Add(new PerfdataValue("idomysqlconnection_" + idomysqlconnection->GetName() + "_queries_1min", idomysqlconnection->GetQueryCount(60)));
@ -78,7 +77,7 @@ void IdoMysqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::P
perfdata->Add(new PerfdataValue("idomysqlconnection_" + idomysqlconnection->GetName() + "_query_queue_item_rate", queryQueueItemRate)); perfdata->Add(new PerfdataValue("idomysqlconnection_" + idomysqlconnection->GetName() + "_query_queue_item_rate", queryQueueItemRate));
} }
status->Set("idomysqlconnection", nodes); status->Set("idomysqlconnection", new Dictionary(std::move(nodes)));
} }
void IdoMysqlConnection::Resume() void IdoMysqlConnection::Resume()

View File

@ -62,20 +62,19 @@ void IdoPgsqlConnection::OnConfigLoaded()
void IdoPgsqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata) void IdoPgsqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const IdoPgsqlConnection::Ptr& idopgsqlconnection : ConfigType::GetObjectsByType<IdoPgsqlConnection>()) { for (const IdoPgsqlConnection::Ptr& idopgsqlconnection : ConfigType::GetObjectsByType<IdoPgsqlConnection>()) {
size_t queryQueueItems = idopgsqlconnection->m_QueryQueue.GetLength(); size_t queryQueueItems = idopgsqlconnection->m_QueryQueue.GetLength();
double queryQueueItemRate = idopgsqlconnection->m_QueryQueue.GetTaskCount(60) / 60.0; double queryQueueItemRate = idopgsqlconnection->m_QueryQueue.GetTaskCount(60) / 60.0;
Dictionary::Ptr stats = new Dictionary(); nodes.emplace_back(idopgsqlconnection->GetName(), new Dictionary({
stats->Set("version", idopgsqlconnection->GetSchemaVersion()); { "version", idopgsqlconnection->GetSchemaVersion() },
stats->Set("instance_name", idopgsqlconnection->GetInstanceName()); { "instance_name", idopgsqlconnection->GetInstanceName() },
stats->Set("connected", idopgsqlconnection->GetConnected()); { "connected", idopgsqlconnection->GetConnected() },
stats->Set("query_queue_items", queryQueueItems); { "query_queue_items", queryQueueItems },
stats->Set("query_queue_item_rate", queryQueueItemRate); { "query_queue_item_rate", queryQueueItemRate }
}));
nodes->Set(idopgsqlconnection->GetName(), stats);
perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_rate", idopgsqlconnection->GetQueryCount(60) / 60.0)); perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_rate", idopgsqlconnection->GetQueryCount(60) / 60.0));
perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_1min", idopgsqlconnection->GetQueryCount(60))); perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_1min", idopgsqlconnection->GetQueryCount(60)));
@ -85,7 +84,7 @@ void IdoPgsqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::P
perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_item_rate", queryQueueItemRate)); perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_item_rate", queryQueueItemRate));
} }
status->Set("idopgsqlconnection", nodes); status->Set("idopgsqlconnection", new Dictionary(std::move(nodes)));
} }
void IdoPgsqlConnection::Resume() void IdoPgsqlConnection::Resume()
@ -534,7 +533,7 @@ Dictionary::Ptr IdoPgsqlConnection::FetchRow(const IdoPgsqlResult& result, int r
int columns = m_Pgsql->nfields(result.get()); int columns = m_Pgsql->nfields(result.get());
Dictionary::Ptr dict = new Dictionary(); DictionaryData dict;
for (int column = 0; column < columns; column++) { for (int column = 0; column < columns; column++) {
Value value; Value value;
@ -542,10 +541,10 @@ Dictionary::Ptr IdoPgsqlConnection::FetchRow(const IdoPgsqlResult& result, int r
if (!m_Pgsql->getisnull(result.get(), row, column)) if (!m_Pgsql->getisnull(result.get(), row, column))
value = m_Pgsql->getvalue(result.get(), row, column); value = m_Pgsql->getvalue(result.get(), row, column);
dict->Set(m_Pgsql->fname(result.get(), column), value); dict.emplace_back(m_Pgsql->fname(result.get(), column), value);
} }
return dict; return new Dictionary(std::move(dict));
} }
void IdoPgsqlConnection::ActivateObject(const DbObject::Ptr& dbobj) void IdoPgsqlConnection::ActivateObject(const DbObject::Ptr& dbobj)

View File

@ -52,9 +52,10 @@ REGISTER_APIACTION(generate_ticket, "", &ApiActions::GenerateTicket);
Dictionary::Ptr ApiActions::CreateResult(int code, const String& status, Dictionary::Ptr ApiActions::CreateResult(int code, const String& status,
const Dictionary::Ptr& additional) const Dictionary::Ptr& additional)
{ {
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("code", code); { "code", code },
result->Set("status", status); { "status", status }
});
if (additional) if (additional)
additional->CopyTo(result); additional->CopyTo(result);
@ -275,9 +276,10 @@ Dictionary::Ptr ApiActions::AddComment(const ConfigObject::Ptr& object,
Comment::Ptr comment = Comment::GetByName(commentName); Comment::Ptr comment = Comment::GetByName(commentName);
Dictionary::Ptr additional = new Dictionary(); Dictionary::Ptr additional = new Dictionary({
additional->Set("name", commentName); { "name", commentName },
additional->Set("legacy_id", comment->GetLegacyId()); { "legacy_id", comment->GetLegacyId() }
});
return ApiActions::CreateResult(200, "Successfully added comment '" return ApiActions::CreateResult(200, "Successfully added comment '"
+ commentName + "' for object '" + checkable->GetName() + commentName + "' for object '" + checkable->GetName()
@ -350,9 +352,10 @@ Dictionary::Ptr ApiActions::ScheduleDowntime(const ConfigObject::Ptr& object,
Downtime::Ptr downtime = Downtime::GetByName(downtimeName); Downtime::Ptr downtime = Downtime::GetByName(downtimeName);
Dictionary::Ptr additional = new Dictionary(); Dictionary::Ptr additional = new Dictionary({
additional->Set("name", downtimeName); { "name", downtimeName },
additional->Set("legacy_id", downtime->GetLegacyId()); { "legacy_id", downtime->GetLegacyId() }
});
/* Schedule downtime for all child objects. */ /* Schedule downtime for all child objects. */
int childOptions = 0; int childOptions = 0;
@ -366,11 +369,11 @@ Dictionary::Ptr ApiActions::ScheduleDowntime(const ConfigObject::Ptr& object,
if (childOptions == 1) if (childOptions == 1)
triggerName = downtimeName; triggerName = downtimeName;
Array::Ptr childDowntimes = new Array();
Log(LogCritical, "ApiActions") Log(LogCritical, "ApiActions")
<< "Processing child options " << childOptions << " for downtime " << downtimeName; << "Processing child options " << childOptions << " for downtime " << downtimeName;
ArrayData childDowntimes;
for (const Checkable::Ptr& child : checkable->GetAllChildren()) { for (const Checkable::Ptr& child : checkable->GetAllChildren()) {
Log(LogCritical, "ApiActions") Log(LogCritical, "ApiActions")
<< "Scheduling downtime for child object " << child->GetName(); << "Scheduling downtime for child object " << child->GetName();
@ -383,13 +386,13 @@ Dictionary::Ptr ApiActions::ScheduleDowntime(const ConfigObject::Ptr& object,
Downtime::Ptr childDowntime = Downtime::GetByName(childDowntimeName); Downtime::Ptr childDowntime = Downtime::GetByName(childDowntimeName);
Dictionary::Ptr additionalChild = new Dictionary(); childDowntimes.push_back(new Dictionary({
additionalChild->Set("name", childDowntimeName); { "name", childDowntimeName },
additionalChild->Set("legacy_id", childDowntime->GetLegacyId()); { "legacy_id", childDowntime->GetLegacyId() }
childDowntimes->Add(additionalChild); }));
} }
additional->Set("child_downtimes", childDowntimes); additional->Set("child_downtimes", new Array(std::move(childDowntimes)));
} }
return ApiActions::CreateResult(200, "Successfully scheduled downtime '" + return ApiActions::CreateResult(200, "Successfully scheduled downtime '" +
@ -455,8 +458,9 @@ Dictionary::Ptr ApiActions::GenerateTicket(const ConfigObject::Ptr&,
String ticket = PBKDF2_SHA1(cn, salt, 50000); String ticket = PBKDF2_SHA1(cn, salt, 50000);
Dictionary::Ptr additional = new Dictionary(); Dictionary::Ptr additional = new Dictionary({
additional->Set("ticket", ticket); { "ticket", ticket }
});
return ApiActions::CreateResult(200, "Generated PKI ticket '" + ticket + "' for common name '" return ApiActions::CreateResult(200, "Generated PKI ticket '" + ticket + "' for common name '"
+ cn + "'.", additional); + cn + "'.", additional);

View File

@ -129,13 +129,13 @@ void ApiEvents::NotificationSentToAllUsersHandler(const Notification::Ptr& notif
if (service) if (service)
result->Set("service", service->GetShortName()); result->Set("service", service->GetShortName());
Array::Ptr userNames = new Array(); ArrayData userNames;
for (const User::Ptr& user : users) { for (const User::Ptr& user : users) {
userNames->Add(user->GetName()); userNames.push_back(user->GetName());
} }
result->Set("users", userNames); result->Set("users", new Array(std::move(userNames)));
result->Set("notification_type", Notification::NotificationTypeToString(type)); result->Set("notification_type", Notification::NotificationTypeToString(type));
result->Set("author", author); result->Set("author", author);
result->Set("text", text); result->Set("text", text);
@ -257,11 +257,11 @@ void ApiEvents::CommentAddedHandler(const Comment::Ptr& comment)
Log(LogDebug, "ApiEvents", "Processing event type 'CommentAdded'."); Log(LogDebug, "ApiEvents", "Processing event type 'CommentAdded'.");
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("type", "CommentAdded"); { "type", "CommentAdded" },
result->Set("timestamp", Utility::GetTime()); { "timestamp", Utility::GetTime() },
{ "comment", Serialize(comment, FAConfig | FAState) }
result->Set("comment", Serialize(comment, FAConfig | FAState)); });
for (const EventQueue::Ptr& queue : queues) { for (const EventQueue::Ptr& queue : queues) {
queue->ProcessEvent(result); queue->ProcessEvent(result);
@ -277,11 +277,11 @@ void ApiEvents::CommentRemovedHandler(const Comment::Ptr& comment)
Log(LogDebug, "ApiEvents", "Processing event type 'CommentRemoved'."); Log(LogDebug, "ApiEvents", "Processing event type 'CommentRemoved'.");
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("type", "CommentRemoved"); { "type", "CommentRemoved" },
result->Set("timestamp", Utility::GetTime()); { "timestamp", Utility::GetTime() },
{ "comment", Serialize(comment, FAConfig | FAState) }
result->Set("comment", Serialize(comment, FAConfig | FAState)); });
for (const EventQueue::Ptr& queue : queues) { for (const EventQueue::Ptr& queue : queues) {
queue->ProcessEvent(result); queue->ProcessEvent(result);
@ -297,11 +297,11 @@ void ApiEvents::DowntimeAddedHandler(const Downtime::Ptr& downtime)
Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeAdded'."); Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeAdded'.");
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("type", "DowntimeAdded"); { "type", "DowntimeAdded" },
result->Set("timestamp", Utility::GetTime()); { "timestamp", Utility::GetTime() },
{ "downtime", Serialize(downtime, FAConfig | FAState) }
result->Set("downtime", Serialize(downtime, FAConfig | FAState)); });
for (const EventQueue::Ptr& queue : queues) { for (const EventQueue::Ptr& queue : queues) {
queue->ProcessEvent(result); queue->ProcessEvent(result);
@ -317,11 +317,11 @@ void ApiEvents::DowntimeRemovedHandler(const Downtime::Ptr& downtime)
Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeRemoved'."); Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeRemoved'.");
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("type", "DowntimeRemoved"); { "type", "DowntimeRemoved" },
result->Set("timestamp", Utility::GetTime()); { "timestamp", Utility::GetTime() },
{ "downtime", Serialize(downtime, FAConfig | FAState) }
result->Set("downtime", Serialize(downtime, FAConfig | FAState)); });
for (const EventQueue::Ptr& queue : queues) { for (const EventQueue::Ptr& queue : queues) {
queue->ProcessEvent(result); queue->ProcessEvent(result);
@ -337,11 +337,11 @@ void ApiEvents::DowntimeStartedHandler(const Downtime::Ptr& downtime)
Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeStarted'."); Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeStarted'.");
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("type", "DowntimeStarted"); { "type", "DowntimeStarted" },
result->Set("timestamp", Utility::GetTime()); { "timestamp", Utility::GetTime() },
{ "downtime", Serialize(downtime, FAConfig | FAState) }
result->Set("downtime", Serialize(downtime, FAConfig | FAState)); });
for (const EventQueue::Ptr& queue : queues) { for (const EventQueue::Ptr& queue : queues) {
queue->ProcessEvent(result); queue->ProcessEvent(result);
@ -357,11 +357,11 @@ void ApiEvents::DowntimeTriggeredHandler(const Downtime::Ptr& downtime)
Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeTriggered'."); Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeTriggered'.");
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("type", "DowntimeTriggered"); { "type", "DowntimeTriggered" },
result->Set("timestamp", Utility::GetTime()); { "timestamp", Utility::GetTime() },
{ "downtime", Serialize(downtime, FAConfig | FAState) }
result->Set("downtime", Serialize(downtime, FAConfig | FAState)); });
for (const EventQueue::Ptr& queue : queues) { for (const EventQueue::Ptr& queue : queues) {
queue->ProcessEvent(result); queue->ProcessEvent(result);

View File

@ -301,11 +301,12 @@ void Checkable::ProcessCheckResult(const CheckResult::Ptr& cr, const MessageOrig
if (remove_acknowledgement_comments) if (remove_acknowledgement_comments)
RemoveCommentsByType(CommentAcknowledgement); RemoveCommentsByType(CommentAcknowledgement);
Dictionary::Ptr vars_after = new Dictionary(); Dictionary::Ptr vars_after = new Dictionary({
vars_after->Set("state", new_state); { "state", new_state },
vars_after->Set("state_type", GetStateType()); { "state_type", GetStateType() },
vars_after->Set("attempt", GetCheckAttempt()); { "attempt", GetCheckAttempt() },
vars_after->Set("reachable", reachable); { "reachable", reachable }
});
if (old_cr) if (old_cr)
cr->SetVarsBefore(old_cr->GetVarsAfter()); cr->SetVarsBefore(old_cr->GetVarsAfter());

View File

@ -35,12 +35,9 @@ static void CheckableProcessCheckResult(const CheckResult::Ptr& cr)
Object::Ptr Checkable::GetPrototype() Object::Ptr Checkable::GetPrototype()
{ {
static Dictionary::Ptr prototype; static Dictionary::Ptr prototype = new Dictionary({
{ "process_check_result", new Function("Checkable#process_check_result", CheckableProcessCheckResult, { "cr" }, false) }
if (!prototype) { });
prototype = new Dictionary();
prototype->Set("process_check_result", new Function("Checkable#process_check_result", CheckableProcessCheckResult, { "cr" }, false));
}
return prototype; return prototype;
} }

View File

@ -137,7 +137,7 @@ Value ClusterEvents::CheckResultAPIHandler(const MessageOrigin::Ptr& origin, con
if (!cr) if (!cr)
return Empty; return Empty;
Array::Ptr rperf = new Array(); ArrayData rperf;
if (vperf) { if (vperf) {
ObjectLock olock(vperf); ObjectLock olock(vperf);
@ -147,13 +147,13 @@ Value ClusterEvents::CheckResultAPIHandler(const MessageOrigin::Ptr& origin, con
if (vp.IsObjectType<Dictionary>()) { if (vp.IsObjectType<Dictionary>()) {
PerfdataValue::Ptr val = new PerfdataValue(); PerfdataValue::Ptr val = new PerfdataValue();
Deserialize(val, vp, true); Deserialize(val, vp, true);
rperf->Add(val); rperf.push_back(val);
} else } else
rperf->Add(vp); rperf.push_back(vp);
} }
} }
cr->SetPerformanceData(rperf); cr->SetPerformanceData(new Array(std::move(rperf)));
Host::Ptr host = Host::GetByName(params->Get("host")); Host::Ptr host = Host::GetByName(params->Get("host"));
@ -892,11 +892,11 @@ void ClusterEvents::NotificationSentToAllUsersHandler(const Notification::Ptr& n
params->Set("service", service->GetShortName()); params->Set("service", service->GetShortName());
params->Set("notification", notification->GetName()); params->Set("notification", notification->GetName());
Array::Ptr ausers = new Array(); ArrayData ausers;
for (const User::Ptr& user : users) { for (const User::Ptr& user : users) {
ausers->Add(user->GetName()); ausers.push_back(user->GetName());
} }
params->Set("users", ausers); params->Set("users", new Array(std::move(ausers)));
params->Set("type", notificationType); params->Set("type", notificationType);
params->Set("cr", Serialize(cr)); params->Set("cr", Serialize(cr));
@ -1003,12 +1003,12 @@ Value ClusterEvents::NotificationSentToAllUsersAPIHandler(const MessageOrigin::P
notification->SetLastProblemNotification(params->Get("last_problem_notification")); notification->SetLastProblemNotification(params->Get("last_problem_notification"));
notification->SetNoMoreNotifications(params->Get("no_more_notifications")); notification->SetNoMoreNotifications(params->Get("no_more_notifications"));
Array::Ptr notifiedProblemUsers = new Array(); ArrayData notifiedProblemUsers;
for (const User::Ptr& user : users) { for (const User::Ptr& user : users) {
notifiedProblemUsers->Add(user->GetName()); notifiedProblemUsers.push_back(user->GetName());
} }
notification->SetNotifiedProblemUsers(notifiedProblemUsers); notification->SetNotifiedProblemUsers(new Array(std::move(notifiedProblemUsers)));
Checkable::OnNotificationSentToAllUsers(notification, checkable, users, type, cr, author, text, origin); Checkable::OnNotificationSentToAllUsers(notification, checkable, users, type, cr, author, text, origin);

View File

@ -108,9 +108,7 @@ bool Dependency::EvaluateApplyRule(const Checkable::Ptr& checkable, const ApplyR
return false; return false;
} }
} else { } else {
Array::Ptr instances = new Array(); vinstances = new Array({ "" });
instances->Add("");
vinstances = instances;
} }
bool match = false; bool match = false;

View File

@ -65,25 +65,24 @@ REGISTER_STATSFUNCTION(IcingaApplication, &IcingaApplication::StatsFunc);
void IcingaApplication::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata) void IcingaApplication::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const IcingaApplication::Ptr& icingaapplication : ConfigType::GetObjectsByType<IcingaApplication>()) { for (const IcingaApplication::Ptr& icingaapplication : ConfigType::GetObjectsByType<IcingaApplication>()) {
Dictionary::Ptr stats = new Dictionary(); nodes.emplace_back(icingaapplication->GetName(), new Dictionary({
stats->Set("node_name", icingaapplication->GetNodeName()); { "node_name", icingaapplication->GetNodeName() },
stats->Set("enable_notifications", icingaapplication->GetEnableNotifications()); { "enable_notifications", icingaapplication->GetEnableNotifications() },
stats->Set("enable_event_handlers", icingaapplication->GetEnableEventHandlers()); { "enable_event_handlers", icingaapplication->GetEnableEventHandlers() },
stats->Set("enable_flapping", icingaapplication->GetEnableFlapping()); { "enable_flapping", icingaapplication->GetEnableFlapping() },
stats->Set("enable_host_checks", icingaapplication->GetEnableHostChecks()); { "enable_host_checks", icingaapplication->GetEnableHostChecks() },
stats->Set("enable_service_checks", icingaapplication->GetEnableServiceChecks()); { "enable_service_checks", icingaapplication->GetEnableServiceChecks() },
stats->Set("enable_perfdata", icingaapplication->GetEnablePerfdata()); { "enable_perfdata", icingaapplication->GetEnablePerfdata() },
stats->Set("pid", Utility::GetPid()); { "pid", Utility::GetPid() },
stats->Set("program_start", Application::GetStartTime()); { "program_start", Application::GetStartTime() },
stats->Set("version", Application::GetAppVersion()); { "version", Application::GetAppVersion() }
}));
nodes->Set(icingaapplication->GetName(), stats);
} }
status->Set("icingaapplication", nodes); status->Set("icingaapplication", new Dictionary(std::move(nodes)));
} }
/** /**
@ -129,9 +128,10 @@ static void PersistModAttrHelper(std::fstream& fp, ConfigObject::Ptr& previousOb
ConfigWriter::EmitRaw(fp, "var obj = "); ConfigWriter::EmitRaw(fp, "var obj = ");
Array::Ptr args1 = new Array(); Array::Ptr args1 = new Array({
args1->Add(object->GetReflectionType()->GetName()); object->GetReflectionType()->GetName(),
args1->Add(object->GetName()); object->GetName()
});
ConfigWriter::EmitFunctionCall(fp, "get_object", args1); ConfigWriter::EmitFunctionCall(fp, "get_object", args1);
ConfigWriter::EmitRaw(fp, "\nif (obj) {\n"); ConfigWriter::EmitRaw(fp, "\nif (obj) {\n");
@ -139,9 +139,10 @@ static void PersistModAttrHelper(std::fstream& fp, ConfigObject::Ptr& previousOb
ConfigWriter::EmitRaw(fp, "\tobj."); ConfigWriter::EmitRaw(fp, "\tobj.");
Array::Ptr args2 = new Array(); Array::Ptr args2 = new Array({
args2->Add(attr); attr,
args2->Add(value); value
});
ConfigWriter::EmitFunctionCall(fp, "modify_attribute", args2); ConfigWriter::EmitFunctionCall(fp, "modify_attribute", args2);
ConfigWriter::EmitRaw(fp, "\n"); ConfigWriter::EmitRaw(fp, "\n");

View File

@ -374,10 +374,10 @@ Dictionary::Ptr LegacyTimePeriod::ProcessTimeRange(const String& timestamp, tm *
ProcessTimeRangeRaw(timestamp, reference, &begin, &end); ProcessTimeRangeRaw(timestamp, reference, &begin, &end);
Dictionary::Ptr segment = new Dictionary(); return new Dictionary({
segment->Set("begin", (long)mktime(&begin)); { "begin", (long)mktime(&begin) },
segment->Set("end", (long)mktime(&end)); { "end", (long)mktime(&end) }
return segment; });
} }
void LegacyTimePeriod::ProcessTimeRanges(const String& timeranges, tm *reference, const Array::Ptr& result) void LegacyTimePeriod::ProcessTimeRanges(const String& timeranges, tm *reference, const Array::Ptr& result)

View File

@ -48,7 +48,7 @@ Value MacroProcessor::ResolveMacros(const Value& str, const ResolverList& resolv
result = InternalResolveMacros(str, resolvers, cr, missingMacro, escapeFn, result = InternalResolveMacros(str, resolvers, cr, missingMacro, escapeFn,
resolvedMacros, useResolvedMacros, recursionLevel + 1); resolvedMacros, useResolvedMacros, recursionLevel + 1);
} else if (str.IsObjectType<Array>()) { } else if (str.IsObjectType<Array>()) {
Array::Ptr resultArr = new Array(); ArrayData resultArr;;
Array::Ptr arr = str; Array::Ptr arr = str;
ObjectLock olock(arr); ObjectLock olock(arr);
@ -59,12 +59,12 @@ Value MacroProcessor::ResolveMacros(const Value& str, const ResolverList& resolv
EscapeCallback(), resolvedMacros, useResolvedMacros, recursionLevel + 1); EscapeCallback(), resolvedMacros, useResolvedMacros, recursionLevel + 1);
if (value.IsObjectType<Array>()) if (value.IsObjectType<Array>())
resultArr->Add(Utility::Join(value, ';')); resultArr.push_back(Utility::Join(value, ';'));
else else
resultArr->Add(value); resultArr.push_back(value);
} }
result = resultArr; result = new Array(std::move(resultArr));
} else if (str.IsObjectType<Dictionary>()) { } else if (str.IsObjectType<Dictionary>()) {
Dictionary::Ptr resultDict = new Dictionary(); Dictionary::Ptr resultDict = new Dictionary();
Dictionary::Ptr dict = str; Dictionary::Ptr dict = str;
@ -275,19 +275,19 @@ Value MacroProcessor::InternalResolveMacros(const String& str, const ResolverLis
if (recursive_macro) { if (recursive_macro) {
if (resolved_macro.IsObjectType<Array>()) { if (resolved_macro.IsObjectType<Array>()) {
Array::Ptr arr = resolved_macro; Array::Ptr arr = resolved_macro;
Array::Ptr resolved_arr = new Array(); ArrayData resolved_arr;
ObjectLock olock(arr); ObjectLock olock(arr);
for (const Value& value : arr) { for (const Value& value : arr) {
if (value.IsScalar()) { if (value.IsScalar()) {
resolved_arr->Add(InternalResolveMacros(value, resolved_arr.push_back(InternalResolveMacros(value,
resolvers, cr, missingMacro, EscapeCallback(), nullptr, resolvers, cr, missingMacro, EscapeCallback(), nullptr,
false, recursionLevel + 1)); false, recursionLevel + 1));
} else } else
resolved_arr->Add(value); resolved_arr.push_back(value);
} }
resolved_macro = resolved_arr; resolved_macro = new Array(std::move(resolved_arr));
} else if (resolved_macro.IsString()) { } else if (resolved_macro.IsString()) {
resolved_macro = InternalResolveMacros(resolved_macro, resolved_macro = InternalResolveMacros(resolved_macro,
resolvers, cr, missingMacro, EscapeCallback(), nullptr, resolvers, cr, missingMacro, EscapeCallback(), nullptr,
@ -444,9 +444,7 @@ Value MacroProcessor::ResolveArguments(const Value& command, const Dictionary::P
resolvedCommand = MacroProcessor::ResolveMacros(command, resolvers, cr, nullptr, resolvedCommand = MacroProcessor::ResolveMacros(command, resolvers, cr, nullptr,
EscapeMacroShellArg, resolvedMacros, useResolvedMacros, recursionLevel + 1); EscapeMacroShellArg, resolvedMacros, useResolvedMacros, recursionLevel + 1);
else { else {
Array::Ptr arr = new Array(); resolvedCommand = new Array({ command });
arr->Add(command);
resolvedCommand = arr;
} }
if (arguments) { if (arguments) {
@ -562,4 +560,3 @@ Value MacroProcessor::ResolveArguments(const Value& command, const Dictionary::P
return resolvedCommand; return resolvedCommand;
} }

View File

@ -107,9 +107,7 @@ bool Notification::EvaluateApplyRule(const Checkable::Ptr& checkable, const Appl
return false; return false;
} }
} else { } else {
Array::Ptr instances = new Array(); vinstances = new Array({ "" });
instances->Add("");
vinstances = instances;
} }
bool match = false; bool match = false;

View File

@ -145,7 +145,7 @@ std::pair<String, String> PluginUtility::ParseCheckOutput(const String& output)
Array::Ptr PluginUtility::SplitPerfdata(const String& perfdata) Array::Ptr PluginUtility::SplitPerfdata(const String& perfdata)
{ {
Array::Ptr result = new Array(); ArrayData result;
size_t begin = 0; size_t begin = 0;
String multi_prefix; String multi_prefix;
@ -182,7 +182,7 @@ Array::Ptr PluginUtility::SplitPerfdata(const String& perfdata)
else else
pdv = label + "=" + value; pdv = label + "=" + value;
result->Add(pdv); result.emplace_back(std::move(pdv));
if (multi_index != String::NPos) if (multi_index != String::NPos)
multi_prefix = label.SubStr(0, multi_index); multi_prefix = label.SubStr(0, multi_index);
@ -190,7 +190,7 @@ Array::Ptr PluginUtility::SplitPerfdata(const String& perfdata)
begin = spq + 1; begin = spq + 1;
} }
return result; return new Array(std::move(result));
} }
String PluginUtility::FormatPerfdata(const Array::Ptr& perfdata) String PluginUtility::FormatPerfdata(const Array::Ptr& perfdata)

View File

@ -106,9 +106,7 @@ bool ScheduledDowntime::EvaluateApplyRule(const Checkable::Ptr& checkable, const
return false; return false;
} }
} else { } else {
Array::Ptr instances = new Array(); vinstances = new Array({ "" });
instances->Add("");
vinstances = instances;
} }
bool match = false; bool match = false;

View File

@ -95,9 +95,7 @@ bool Service::EvaluateApplyRule(const Host::Ptr& host, const ApplyRule& rule)
return false; return false;
} }
} else { } else {
Array::Ptr instances = new Array(); vinstances = new Array({ "" });
instances->Add("");
vinstances = instances;
} }
bool match = false; bool match = false;

View File

@ -50,11 +50,10 @@ Dictionary::Ptr ServiceNameComposer::ParseName(const String& name) const
if (tokens.size() < 2) if (tokens.size() < 2)
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid Service name.")); BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid Service name."));
Dictionary::Ptr result = new Dictionary(); return new Dictionary({
result->Set("host_name", tokens[0]); { "host_name", tokens[0] },
result->Set("name", tokens[1]); { "name", tokens[1] }
});
return result;
} }
void Service::OnAllConfigLoaded() void Service::OnAllConfigLoaded()

View File

@ -98,9 +98,10 @@ void TimePeriod::AddSegment(double begin, double end)
} }
/* Create new segment if we weren't able to merge this into an existing segment. */ /* Create new segment if we weren't able to merge this into an existing segment. */
Dictionary::Ptr segment = new Dictionary(); Dictionary::Ptr segment = new Dictionary({
segment->Set("begin", begin); { "begin", begin },
segment->Set("end", end); { "end", end }
});
if (!segments) { if (!segments) {
segments = new Array(); segments = new Array();
@ -152,17 +153,15 @@ void TimePeriod::RemoveSegment(double begin, double end)
/* Cut between */ /* Cut between */
if (segment->Get("begin") < begin && segment->Get("end") > end) { if (segment->Get("begin") < begin && segment->Get("end") > end) {
Dictionary::Ptr firstsegment = new Dictionary(); newSegments->Add(new Dictionary({
firstsegment->Set("begin", segment->Get("begin")); { "begin", segment->Get("begin") },
firstsegment->Set("end", begin); { "end", begin }
}));
Dictionary::Ptr secondsegment = new Dictionary(); newSegments->Add(new Dictionary({
secondsegment->Set("begin", end); { "begin", end },
secondsegment->Set("end", segment->Get("end")); { "end", segment->Get("end") }
}));
newSegments->Add(firstsegment);
newSegments->Add(secondsegment);
continue;
} }
/* Adjust the begin/end timestamps so as to not overlap with the specified range. */ /* Adjust the begin/end timestamps so as to not overlap with the specified range. */

View File

@ -101,19 +101,16 @@ Value CommandsTable::CustomVariableNamesAccessor(const Value& row)
Dictionary::Ptr vars = command->GetVars(); Dictionary::Ptr vars = command->GetVars();
Array::Ptr cv = new Array(); ArrayData keys;
if (!vars) if (vars) {
return cv;
{
ObjectLock xlock(vars); ObjectLock xlock(vars);
for (const auto& kv : vars) { for (const auto& kv : vars) {
cv->Add(kv.first); keys.push_back(kv.first);
} }
} }
return cv; return new Array(std::move(keys));
} }
Value CommandsTable::CustomVariableValuesAccessor(const Value& row) Value CommandsTable::CustomVariableValuesAccessor(const Value& row)
@ -125,19 +122,16 @@ Value CommandsTable::CustomVariableValuesAccessor(const Value& row)
Dictionary::Ptr vars = command->GetVars(); Dictionary::Ptr vars = command->GetVars();
Array::Ptr cv = new Array(); ArrayData keys;
if (!vars) if (vars) {
return cv;
{
ObjectLock xlock(vars); ObjectLock xlock(vars);
for (const auto& kv : vars) { for (const auto& kv : vars) {
cv->Add(kv.second); keys.push_back(kv.second);
} }
} }
return cv; return new Array(std::move(keys));
} }
Value CommandsTable::CustomVariablesAccessor(const Value& row) Value CommandsTable::CustomVariablesAccessor(const Value& row)
@ -149,20 +143,17 @@ Value CommandsTable::CustomVariablesAccessor(const Value& row)
Dictionary::Ptr vars = command->GetVars(); Dictionary::Ptr vars = command->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars) if (vars) {
return cv;
{
ObjectLock xlock(vars); ObjectLock xlock(vars);
for (const auto& kv : vars) { for (const auto& kv : vars) {
Array::Ptr key_val = new Array(); result.push_back(new Array({
key_val->Add(kv.first); kv.first,
key_val->Add(kv.second); kv.second
cv->Add(key_val); }));
} }
} }
return cv; return new Array(std::move(result));
} }

View File

@ -81,11 +81,11 @@ Value ContactGroupsTable::MembersAccessor(const Value& row)
if (!user_group) if (!user_group)
return Empty; return Empty;
Array::Ptr members = new Array(); ArrayData result;
for (const User::Ptr& user : user_group->GetMembers()) { for (const User::Ptr& user : user_group->GetMembers()) {
members->Add(user->GetName()); result.push_back(user->GetName());
} }
return members; return new Array(std::move(result));
} }

View File

@ -205,17 +205,16 @@ Value ContactsTable::CustomVariableNamesAccessor(const Value& row)
Dictionary::Ptr vars = user->GetVars(); Dictionary::Ptr vars = user->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars)
return cv;
if (vars) {
ObjectLock olock(vars); ObjectLock olock(vars);
for (const Dictionary::Pair& kv : vars) { for (const Dictionary::Pair& kv : vars) {
cv->Add(kv.first); result.push_back(kv.first);
}
} }
return cv; return new Array(std::move(result));
} }
Value ContactsTable::CustomVariableValuesAccessor(const Value& row) Value ContactsTable::CustomVariableValuesAccessor(const Value& row)
@ -227,20 +226,19 @@ Value ContactsTable::CustomVariableValuesAccessor(const Value& row)
Dictionary::Ptr vars = user->GetVars(); Dictionary::Ptr vars = user->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars)
return cv;
if (vars) {
ObjectLock olock(vars); ObjectLock olock(vars);
for (const Dictionary::Pair& kv : vars) { for (const Dictionary::Pair& kv : vars) {
if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>()) if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>())
cv->Add(JsonEncode(kv.second)); result.push_back(JsonEncode(kv.second));
else else
cv->Add(kv.second); result.push_back(kv.second);
}
} }
return cv; return new Array(std::move(result));
} }
Value ContactsTable::CustomVariablesAccessor(const Value& row) Value ContactsTable::CustomVariablesAccessor(const Value& row)
@ -252,25 +250,26 @@ Value ContactsTable::CustomVariablesAccessor(const Value& row)
Dictionary::Ptr vars = user->GetVars(); Dictionary::Ptr vars = user->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars)
return cv;
if (vars) {
ObjectLock olock(vars); ObjectLock olock(vars);
for (const Dictionary::Pair& kv : vars) { for (const Dictionary::Pair& kv : vars) {
Array::Ptr key_val = new Array(); Value val;
key_val->Add(kv.first);
if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>()) if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>())
key_val->Add(JsonEncode(kv.second)); val = JsonEncode(kv.second);
else else
key_val->Add(kv.second); val = kv.second;
cv->Add(key_val); result.push_back(new Array({
kv.first,
val
}));
}
} }
return cv; return new Array(std::move(result));
} }
Value ContactsTable::CVIsJsonAccessor(const Value& row) Value ContactsTable::CVIsJsonAccessor(const Value& row)

View File

@ -135,13 +135,13 @@ Value HostGroupsTable::MembersAccessor(const Value& row)
if (!hg) if (!hg)
return Empty; return Empty;
Array::Ptr members = new Array(); ArrayData members;
for (const Host::Ptr& host : hg->GetMembers()) { for (const Host::Ptr& host : hg->GetMembers()) {
members->Add(host->GetName()); members.push_back(host->GetName());
} }
return members; return new Array(std::move(members));
} }
Value HostGroupsTable::MembersWithStateAccessor(const Value& row) Value HostGroupsTable::MembersWithStateAccessor(const Value& row)
@ -151,16 +151,16 @@ Value HostGroupsTable::MembersWithStateAccessor(const Value& row)
if (!hg) if (!hg)
return Empty; return Empty;
Array::Ptr members = new Array(); ArrayData members;
for (const Host::Ptr& host : hg->GetMembers()) { for (const Host::Ptr& host : hg->GetMembers()) {
Array::Ptr member_state = new Array(); members.push_back(new Array({
member_state->Add(host->GetName()); host->GetName(),
member_state->Add(host->GetState()); host->GetState()
members->Add(member_state); }));
} }
return members; return new Array(std::move(members));
} }
Value HostGroupsTable::WorstHostStateAccessor(const Value& row) Value HostGroupsTable::WorstHostStateAccessor(const Value& row)

View File

@ -912,13 +912,13 @@ Value HostsTable::ContactsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Array::Ptr contact_names = new Array(); ArrayData result;
for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(host)) { for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(host)) {
contact_names->Add(user->GetName()); result.push_back(user->GetName());
} }
return contact_names; return new Array(std::move(result));
} }
Value HostsTable::DowntimesAccessor(const Value& row) Value HostsTable::DowntimesAccessor(const Value& row)
@ -928,16 +928,16 @@ Value HostsTable::DowntimesAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Downtime::Ptr& downtime : host->GetDowntimes()) { for (const Downtime::Ptr& downtime : host->GetDowntimes()) {
if (downtime->IsExpired()) if (downtime->IsExpired())
continue; continue;
results->Add(downtime->GetLegacyId()); result.push_back(downtime->GetLegacyId());
} }
return results; return new Array(std::move(result));
} }
Value HostsTable::DowntimesWithInfoAccessor(const Value& row) Value HostsTable::DowntimesWithInfoAccessor(const Value& row)
@ -947,20 +947,20 @@ Value HostsTable::DowntimesWithInfoAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Downtime::Ptr& downtime : host->GetDowntimes()) { for (const Downtime::Ptr& downtime : host->GetDowntimes()) {
if (downtime->IsExpired()) if (downtime->IsExpired())
continue; continue;
Array::Ptr downtime_info = new Array(); result.push_back(new Array({
downtime_info->Add(downtime->GetLegacyId()); downtime->GetLegacyId(),
downtime_info->Add(downtime->GetAuthor()); downtime->GetAuthor(),
downtime_info->Add(downtime->GetComment()); downtime->GetComment()
results->Add(downtime_info); }));
} }
return results; return new Array(std::move(result));
} }
Value HostsTable::CommentsAccessor(const Value& row) Value HostsTable::CommentsAccessor(const Value& row)
@ -970,15 +970,16 @@ Value HostsTable::CommentsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Comment::Ptr& comment : host->GetComments()) { for (const Comment::Ptr& comment : host->GetComments()) {
if (comment->IsExpired()) if (comment->IsExpired())
continue; continue;
results->Add(comment->GetLegacyId()); result.push_back(comment->GetLegacyId());
} }
return results; return new Array(std::move(result));
} }
Value HostsTable::CommentsWithInfoAccessor(const Value& row) Value HostsTable::CommentsWithInfoAccessor(const Value& row)
@ -988,20 +989,20 @@ Value HostsTable::CommentsWithInfoAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Comment::Ptr& comment : host->GetComments()) { for (const Comment::Ptr& comment : host->GetComments()) {
if (comment->IsExpired()) if (comment->IsExpired())
continue; continue;
Array::Ptr comment_info = new Array(); result.push_back(new Array({
comment_info->Add(comment->GetLegacyId()); comment->GetLegacyId(),
comment_info->Add(comment->GetAuthor()); comment->GetAuthor(),
comment_info->Add(comment->GetText()); comment->GetText()
results->Add(comment_info); }));
} }
return results; return new Array(std::move(result));
} }
Value HostsTable::CommentsWithExtraInfoAccessor(const Value& row) Value HostsTable::CommentsWithExtraInfoAccessor(const Value& row)
@ -1011,22 +1012,22 @@ Value HostsTable::CommentsWithExtraInfoAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Comment::Ptr& comment : host->GetComments()) { for (const Comment::Ptr& comment : host->GetComments()) {
if (comment->IsExpired()) if (comment->IsExpired())
continue; continue;
Array::Ptr comment_info = new Array(); result.push_back(new Array({
comment_info->Add(comment->GetLegacyId()); comment->GetLegacyId(),
comment_info->Add(comment->GetAuthor()); comment->GetAuthor(),
comment_info->Add(comment->GetText()); comment->GetText(),
comment_info->Add(comment->GetEntryType()); comment->GetEntryType(),
comment_info->Add(static_cast<int>(comment->GetEntryTime())); static_cast<int>(comment->GetEntryTime())
results->Add(comment_info); }));
} }
return results; return new Array(std::move(result));
} }
Value HostsTable::CustomVariableNamesAccessor(const Value& row) Value HostsTable::CustomVariableNamesAccessor(const Value& row)
@ -1038,17 +1039,16 @@ Value HostsTable::CustomVariableNamesAccessor(const Value& row)
Dictionary::Ptr vars = host->GetVars(); Dictionary::Ptr vars = host->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars)
return cv;
if (vars) {
ObjectLock olock(vars); ObjectLock olock(vars);
for (const Dictionary::Pair& kv : vars) { for (const Dictionary::Pair& kv : vars) {
cv->Add(kv.first); result.push_back(kv.first);
}
} }
return cv; return new Array(std::move(result));
} }
Value HostsTable::CustomVariableValuesAccessor(const Value& row) Value HostsTable::CustomVariableValuesAccessor(const Value& row)
@ -1060,20 +1060,19 @@ Value HostsTable::CustomVariableValuesAccessor(const Value& row)
Dictionary::Ptr vars = host->GetVars(); Dictionary::Ptr vars = host->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars)
return cv;
if (vars) {
ObjectLock olock(vars); ObjectLock olock(vars);
for (const Dictionary::Pair& kv : vars) { for (const Dictionary::Pair& kv : vars) {
if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>()) if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>())
cv->Add(JsonEncode(kv.second)); result.push_back(JsonEncode(kv.second));
else else
cv->Add(kv.second); result.push_back(kv.second);
}
} }
return cv; return new Array(std::move(result));
} }
Value HostsTable::CustomVariablesAccessor(const Value& row) Value HostsTable::CustomVariablesAccessor(const Value& row)
@ -1085,25 +1084,26 @@ Value HostsTable::CustomVariablesAccessor(const Value& row)
Dictionary::Ptr vars = host->GetVars(); Dictionary::Ptr vars = host->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars)
return cv;
if (vars) {
ObjectLock olock(vars); ObjectLock olock(vars);
for (const Dictionary::Pair& kv : vars) { for (const Dictionary::Pair& kv : vars) {
Array::Ptr key_val = new Array(); Value val;
key_val->Add(kv.first);
if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>()) if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>())
key_val->Add(JsonEncode(kv.second)); val = JsonEncode(kv.second);
else else
key_val->Add(kv.second); val = kv.second;
cv->Add(key_val); result.push_back(new Array({
kv.first,
val
}));
}
} }
return cv; return new Array(std::move(result));
} }
Value HostsTable::CVIsJsonAccessor(const Value& row) Value HostsTable::CVIsJsonAccessor(const Value& row)
@ -1136,7 +1136,7 @@ Value HostsTable::ParentsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Array::Ptr parents = new Array(); ArrayData result;
for (const Checkable::Ptr& parent : host->GetParents()) { for (const Checkable::Ptr& parent : host->GetParents()) {
Host::Ptr parent_host = dynamic_pointer_cast<Host>(parent); Host::Ptr parent_host = dynamic_pointer_cast<Host>(parent);
@ -1144,10 +1144,10 @@ Value HostsTable::ParentsAccessor(const Value& row)
if (!parent_host) if (!parent_host)
continue; continue;
parents->Add(parent_host->GetName()); result.push_back(parent_host->GetName());
} }
return parents; return new Array(std::move(result));
} }
Value HostsTable::ChildsAccessor(const Value& row) Value HostsTable::ChildsAccessor(const Value& row)
@ -1157,7 +1157,7 @@ Value HostsTable::ChildsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Array::Ptr childs = new Array(); ArrayData result;
for (const Checkable::Ptr& child : host->GetChildren()) { for (const Checkable::Ptr& child : host->GetChildren()) {
Host::Ptr child_host = dynamic_pointer_cast<Host>(child); Host::Ptr child_host = dynamic_pointer_cast<Host>(child);
@ -1165,10 +1165,10 @@ Value HostsTable::ChildsAccessor(const Value& row)
if (!child_host) if (!child_host)
continue; continue;
childs->Add(child_host->GetName()); result.push_back(child_host->GetName());
} }
return childs; return new Array(std::move(result));
} }
Value HostsTable::NumServicesAccessor(const Value& row) Value HostsTable::NumServicesAccessor(const Value& row)
@ -1421,13 +1421,13 @@ Value HostsTable::ContactGroupsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Array::Ptr contactgroup_names = new Array(); ArrayData result;
for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(host)) { for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(host)) {
contactgroup_names->Add(usergroup->GetName()); result.push_back(usergroup->GetName());
} }
return contactgroup_names; return new Array(std::move(result));
} }
Value HostsTable::ServicesAccessor(const Value& row) Value HostsTable::ServicesAccessor(const Value& row)
@ -1439,14 +1439,14 @@ Value HostsTable::ServicesAccessor(const Value& row)
std::vector<Service::Ptr> rservices = host->GetServices(); std::vector<Service::Ptr> rservices = host->GetServices();
Array::Ptr services = new Array(); ArrayData result;
services->Reserve(rservices.size()); result.reserve(rservices.size());
for (const Service::Ptr& service : rservices) { for (const Service::Ptr& service : rservices) {
services->Add(service->GetShortName()); result.push_back(service->GetShortName());
} }
return services; return new Array(std::move(result));
} }
Value HostsTable::ServicesWithStateAccessor(const Value& row) Value HostsTable::ServicesWithStateAccessor(const Value& row)
@ -1458,19 +1458,18 @@ Value HostsTable::ServicesWithStateAccessor(const Value& row)
std::vector<Service::Ptr> rservices = host->GetServices(); std::vector<Service::Ptr> rservices = host->GetServices();
Array::Ptr services = new Array(); ArrayData result;
services->Reserve(rservices.size()); result.reserve(rservices.size());
for (const Service::Ptr& service : rservices) { for (const Service::Ptr& service : rservices) {
Array::Ptr svc_add = new Array(); result.push_back(new Array({
service->GetShortName(),
svc_add->Add(service->GetShortName()); service->GetState(),
svc_add->Add(service->GetState()); service->HasBeenChecked() ? 1 : 0
svc_add->Add(service->HasBeenChecked() ? 1 : 0); }));
services->Add(svc_add);
} }
return services; return new Array(std::move(result));
} }
Value HostsTable::ServicesWithInfoAccessor(const Value& row) Value HostsTable::ServicesWithInfoAccessor(const Value& row)
@ -1482,27 +1481,25 @@ Value HostsTable::ServicesWithInfoAccessor(const Value& row)
std::vector<Service::Ptr> rservices = host->GetServices(); std::vector<Service::Ptr> rservices = host->GetServices();
Array::Ptr services = new Array(); ArrayData result;
services->Reserve(rservices.size()); result.reserve(rservices.size());
for (const Service::Ptr& service : rservices) { for (const Service::Ptr& service : rservices) {
Array::Ptr svc_add = new Array();
svc_add->Add(service->GetShortName());
svc_add->Add(service->GetState());
svc_add->Add(service->HasBeenChecked() ? 1 : 0);
String output; String output;
CheckResult::Ptr cr = service->GetLastCheckResult(); CheckResult::Ptr cr = service->GetLastCheckResult();
if (cr) if (cr)
output = CompatUtility::GetCheckResultOutput(cr); output = CompatUtility::GetCheckResultOutput(cr);
svc_add->Add(output); result.push_back(new Array({
services->Add(svc_add); service->GetShortName(),
service->GetState(),
service->HasBeenChecked() ? 1 : 0,
output
}));
} }
return services; return new Array(std::move(result));
} }
Value HostsTable::CheckSourceAccessor(const Value& row) Value HostsTable::CheckSourceAccessor(const Value& row)

View File

@ -45,18 +45,17 @@ REGISTER_STATSFUNCTION(LivestatusListener, &LivestatusListener::StatsFunc);
void LivestatusListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata) void LivestatusListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const LivestatusListener::Ptr& livestatuslistener : ConfigType::GetObjectsByType<LivestatusListener>()) { for (const LivestatusListener::Ptr& livestatuslistener : ConfigType::GetObjectsByType<LivestatusListener>()) {
Dictionary::Ptr stats = new Dictionary(); nodes.emplace_back(livestatuslistener->GetName(), new Dictionary({
stats->Set("connections", l_Connections); { "connections", l_Connections }
}));
nodes->Set(livestatuslistener->GetName(), stats);
perfdata->Add(new PerfdataValue("livestatuslistener_" + livestatuslistener->GetName() + "_connections", l_Connections)); perfdata->Add(new PerfdataValue("livestatuslistener_" + livestatuslistener->GetName() + "_connections", l_Connections));
} }
status->Set("livestatuslistener", nodes); status->Set("livestatuslistener", new Dictionary(std::move(nodes)));
} }
/** /**

View File

@ -482,8 +482,6 @@ void LivestatusQuery::ExecuteGetHelper(const Stream::Ptr& stream)
BeginResultSet(result); BeginResultSet(result);
if (m_Aggregators.empty()) { if (m_Aggregators.empty()) {
Array::Ptr header = new Array();
typedef std::pair<String, Column> ColumnPair; typedef std::pair<String, Column> ColumnPair;
std::vector<ColumnPair> column_objs; std::vector<ColumnPair> column_objs;
@ -492,24 +490,26 @@ void LivestatusQuery::ExecuteGetHelper(const Stream::Ptr& stream)
for (const String& columnName : columns) for (const String& columnName : columns)
column_objs.emplace_back(columnName, table->GetColumn(columnName)); column_objs.emplace_back(columnName, table->GetColumn(columnName));
for (const LivestatusRowValue& object : objects) { ArrayData header;
Array::Ptr row = new Array();
row->Reserve(column_objs.size()); for (const LivestatusRowValue& object : objects) {
ArrayData row;
row.reserve(column_objs.size());
for (const ColumnPair& cv : column_objs) { for (const ColumnPair& cv : column_objs) {
if (m_ColumnHeaders) if (m_ColumnHeaders)
header->Add(cv.first); header.push_back(cv.first);
row->Add(cv.second.ExtractValue(object.Row, object.GroupByType, object.GroupByObject)); row.push_back(cv.second.ExtractValue(object.Row, object.GroupByType, object.GroupByObject));
} }
if (m_ColumnHeaders) { if (m_ColumnHeaders) {
AppendResultRow(result, header, first_row); AppendResultRow(result, new Array(std::move(header)), first_row);
m_ColumnHeaders = false; m_ColumnHeaders = false;
} }
AppendResultRow(result, row, first_row); AppendResultRow(result, new Array(std::move(row)), first_row);
} }
} else { } else {
std::map<std::vector<Value>, std::vector<AggregatorState *> > allStats; std::map<std::vector<Value>, std::vector<AggregatorState *> > allStats;
@ -542,45 +542,47 @@ void LivestatusQuery::ExecuteGetHelper(const Stream::Ptr& stream)
/* add column headers both for raw and aggregated data */ /* add column headers both for raw and aggregated data */
if (m_ColumnHeaders) { if (m_ColumnHeaders) {
Array::Ptr header = new Array(); ArrayData header;
for (const String& columnName : m_Columns) { for (const String& columnName : m_Columns) {
header->Add(columnName); header.push_back(columnName);
} }
for (size_t i = 1; i <= m_Aggregators.size(); i++) { for (size_t i = 1; i <= m_Aggregators.size(); i++) {
header->Add("stats_" + Convert::ToString(i)); header.push_back("stats_" + Convert::ToString(i));
} }
AppendResultRow(result, header, first_row); AppendResultRow(result, new Array(std::move(header)), first_row);
} }
for (const auto& kv : allStats) { for (const auto& kv : allStats) {
Array::Ptr row = new Array(); ArrayData row;
row->Reserve(m_Columns.size() + m_Aggregators.size()); row.reserve(m_Columns.size() + m_Aggregators.size());
for (const Value& keyPart : kv.first) { for (const Value& keyPart : kv.first) {
row->Add(keyPart); row.push_back(keyPart);
} }
auto& stats = kv.second; auto& stats = kv.second;
for (size_t i = 0; i < m_Aggregators.size(); i++) for (size_t i = 0; i < m_Aggregators.size(); i++)
row->Add(m_Aggregators[i]->GetResultAndFreeState(stats[i])); row.push_back(m_Aggregators[i]->GetResultAndFreeState(stats[i]));
AppendResultRow(result, row, first_row); AppendResultRow(result, new Array(std::move(row)), first_row);
} }
/* add a bogus zero value if aggregated is empty*/ /* add a bogus zero value if aggregated is empty*/
if (allStats.empty()) { if (allStats.empty()) {
Array::Ptr row = new Array(); ArrayData row;
row.reserve(m_Aggregators.size());
for (size_t i = 1; i <= m_Aggregators.size(); i++) { for (size_t i = 1; i <= m_Aggregators.size(); i++) {
row->Add(0); row.push_back(0);
} }
AppendResultRow(result, row, first_row); AppendResultRow(result, new Array(std::move(row)), first_row);
} }
} }

View File

@ -126,16 +126,16 @@ Value ServiceGroupsTable::MembersAccessor(const Value& row)
if (!sg) if (!sg)
return Empty; return Empty;
Array::Ptr members = new Array(); ArrayData result;
for (const Service::Ptr& service : sg->GetMembers()) { for (const Service::Ptr& service : sg->GetMembers()) {
Array::Ptr host_svc = new Array(); result.push_back(new Array({
host_svc->Add(service->GetHost()->GetName()); service->GetHost()->GetName(),
host_svc->Add(service->GetShortName()); service->GetShortName()
members->Add(host_svc); }));
} }
return members; return new Array(std::move(result));
} }
Value ServiceGroupsTable::MembersWithStateAccessor(const Value& row) Value ServiceGroupsTable::MembersWithStateAccessor(const Value& row)
@ -145,18 +145,18 @@ Value ServiceGroupsTable::MembersWithStateAccessor(const Value& row)
if (!sg) if (!sg)
return Empty; return Empty;
Array::Ptr members = new Array(); ArrayData result;
for (const Service::Ptr& service : sg->GetMembers()) { for (const Service::Ptr& service : sg->GetMembers()) {
Array::Ptr host_svc = new Array(); result.push_back(new Array({
host_svc->Add(service->GetHost()->GetName()); service->GetHost()->GetName(),
host_svc->Add(service->GetShortName()); service->GetShortName(),
host_svc->Add(service->GetHost()->GetState()); service->GetHost()->GetState(),
host_svc->Add(service->GetState()); service->GetState()
members->Add(host_svc); }));
} }
return members; return new Array(std::move(result));
} }
Value ServiceGroupsTable::WorstServiceStateAccessor(const Value& row) Value ServiceGroupsTable::WorstServiceStateAccessor(const Value& row)

View File

@ -933,13 +933,13 @@ Value ServicesTable::ContactsAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
Array::Ptr contact_names = new Array(); ArrayData result;
for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(service)) { for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(service)) {
contact_names->Add(user->GetName()); result.push_back(user->GetName());
} }
return contact_names; return new Array(std::move(result));
} }
Value ServicesTable::DowntimesAccessor(const Value& row) Value ServicesTable::DowntimesAccessor(const Value& row)
@ -949,16 +949,16 @@ Value ServicesTable::DowntimesAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Downtime::Ptr& downtime : service->GetDowntimes()) { for (const Downtime::Ptr& downtime : service->GetDowntimes()) {
if (downtime->IsExpired()) if (downtime->IsExpired())
continue; continue;
results->Add(downtime->GetLegacyId()); result.push_back(downtime->GetLegacyId());
} }
return results; return new Array(std::move(result));
} }
Value ServicesTable::DowntimesWithInfoAccessor(const Value& row) Value ServicesTable::DowntimesWithInfoAccessor(const Value& row)
@ -968,20 +968,20 @@ Value ServicesTable::DowntimesWithInfoAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Downtime::Ptr& downtime : service->GetDowntimes()) { for (const Downtime::Ptr& downtime : service->GetDowntimes()) {
if (downtime->IsExpired()) if (downtime->IsExpired())
continue; continue;
Array::Ptr downtime_info = new Array(); result.push_back(new Array({
downtime_info->Add(downtime->GetLegacyId()); downtime->GetLegacyId(),
downtime_info->Add(downtime->GetAuthor()); downtime->GetAuthor(),
downtime_info->Add(downtime->GetComment()); downtime->GetComment()
results->Add(downtime_info); }));
} }
return results; return new Array(std::move(result));
} }
Value ServicesTable::CommentsAccessor(const Value& row) Value ServicesTable::CommentsAccessor(const Value& row)
@ -991,16 +991,16 @@ Value ServicesTable::CommentsAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Comment::Ptr& comment : service->GetComments()) { for (const Comment::Ptr& comment : service->GetComments()) {
if (comment->IsExpired()) if (comment->IsExpired())
continue; continue;
results->Add(comment->GetLegacyId()); result.push_back(comment->GetLegacyId());
} }
return results; return new Array(std::move(result));
} }
Value ServicesTable::CommentsWithInfoAccessor(const Value& row) Value ServicesTable::CommentsWithInfoAccessor(const Value& row)
@ -1010,20 +1010,20 @@ Value ServicesTable::CommentsWithInfoAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Comment::Ptr& comment : service->GetComments()) { for (const Comment::Ptr& comment : service->GetComments()) {
if (comment->IsExpired()) if (comment->IsExpired())
continue; continue;
Array::Ptr comment_info = new Array(); result.push_back(new Array({
comment_info->Add(comment->GetLegacyId()); comment->GetLegacyId(),
comment_info->Add(comment->GetAuthor()); comment->GetAuthor(),
comment_info->Add(comment->GetText()); comment->GetText()
results->Add(comment_info); }));
} }
return results; return new Array(std::move(result));
} }
Value ServicesTable::CommentsWithExtraInfoAccessor(const Value& row) Value ServicesTable::CommentsWithExtraInfoAccessor(const Value& row)
@ -1033,22 +1033,22 @@ Value ServicesTable::CommentsWithExtraInfoAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
Array::Ptr results = new Array(); ArrayData result;
for (const Comment::Ptr& comment : service->GetComments()) { for (const Comment::Ptr& comment : service->GetComments()) {
if (comment->IsExpired()) if (comment->IsExpired())
continue; continue;
Array::Ptr comment_info = new Array(); result.push_back(new Array({
comment_info->Add(comment->GetLegacyId()); comment->GetLegacyId(),
comment_info->Add(comment->GetAuthor()); comment->GetAuthor(),
comment_info->Add(comment->GetText()); comment->GetText(),
comment_info->Add(comment->GetEntryType()); comment->GetEntryType(),
comment_info->Add(static_cast<int>(comment->GetEntryTime())); static_cast<int>(comment->GetEntryTime())
results->Add(comment_info); }));
} }
return results; return new Array(std::move(result));
} }
Value ServicesTable::CustomVariableNamesAccessor(const Value& row) Value ServicesTable::CustomVariableNamesAccessor(const Value& row)
@ -1060,17 +1060,16 @@ Value ServicesTable::CustomVariableNamesAccessor(const Value& row)
Dictionary::Ptr vars = service->GetVars(); Dictionary::Ptr vars = service->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars)
return cv;
if (vars) {
ObjectLock olock(vars); ObjectLock olock(vars);
for (const Dictionary::Pair& kv : vars) { for (const Dictionary::Pair& kv : vars) {
cv->Add(kv.first); result.push_back(kv.first);
}
} }
return cv; return new Array(std::move(result));
} }
Value ServicesTable::CustomVariableValuesAccessor(const Value& row) Value ServicesTable::CustomVariableValuesAccessor(const Value& row)
@ -1082,20 +1081,19 @@ Value ServicesTable::CustomVariableValuesAccessor(const Value& row)
Dictionary::Ptr vars = service->GetVars(); Dictionary::Ptr vars = service->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars)
return cv;
if (vars) {
ObjectLock olock(vars); ObjectLock olock(vars);
for (const Dictionary::Pair& kv : vars) { for (const Dictionary::Pair& kv : vars) {
if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>()) if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>())
cv->Add(JsonEncode(kv.second)); result.push_back(JsonEncode(kv.second));
else else
cv->Add(kv.second); result.push_back(kv.second);
}
} }
return cv; return new Array(std::move(result));
} }
Value ServicesTable::CustomVariablesAccessor(const Value& row) Value ServicesTable::CustomVariablesAccessor(const Value& row)
@ -1107,25 +1105,26 @@ Value ServicesTable::CustomVariablesAccessor(const Value& row)
Dictionary::Ptr vars = service->GetVars(); Dictionary::Ptr vars = service->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars)
return cv;
if (vars) {
ObjectLock olock(vars); ObjectLock olock(vars);
for (const Dictionary::Pair& kv : vars) { for (const Dictionary::Pair& kv : vars) {
Array::Ptr key_val = new Array(); Value val;
key_val->Add(kv.first);
if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>()) if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>())
key_val->Add(JsonEncode(kv.second)); val = JsonEncode(kv.second);
else else
key_val->Add(kv.second); val = kv.second;
cv->Add(key_val); result.push_back(new Array({
kv.first,
val
}));
}
} }
return cv; return new Array(std::move(result));
} }
Value ServicesTable::CVIsJsonAccessor(const Value& row) Value ServicesTable::CVIsJsonAccessor(const Value& row)
@ -1173,13 +1172,13 @@ Value ServicesTable::ContactGroupsAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
Array::Ptr contactgroup_names = new Array(); ArrayData result;
for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(service)) { for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(service)) {
contactgroup_names->Add(usergroup->GetName()); result.push_back(usergroup->GetName());
} }
return contactgroup_names; return new Array(std::move(result));
} }
Value ServicesTable::CheckSourceAccessor(const Value& row) Value ServicesTable::CheckSourceAccessor(const Value& row)

View File

@ -233,58 +233,49 @@ Value StatusTable::CustomVariableNamesAccessor(const Value&)
{ {
Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars(); Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars) if (vars) {
return cv;
{
ObjectLock olock(vars); ObjectLock olock(vars);
for (const auto& kv : vars) { for (const auto& kv : vars) {
cv->Add(kv.first); result.push_back(kv.first);
} }
} }
return cv; return new Array(std::move(result));
} }
Value StatusTable::CustomVariableValuesAccessor(const Value&) Value StatusTable::CustomVariableValuesAccessor(const Value&)
{ {
Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars(); Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars) if (vars) {
return cv;
{
ObjectLock olock(vars); ObjectLock olock(vars);
for (const auto& kv : vars) { for (const auto& kv : vars) {
cv->Add(kv.second); result.push_back(kv.second);
} }
} }
return cv; return new Array(std::move(result));
} }
Value StatusTable::CustomVariablesAccessor(const Value&) Value StatusTable::CustomVariablesAccessor(const Value&)
{ {
Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars(); Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars();
Array::Ptr cv = new Array(); ArrayData result;
if (!vars) if (vars) {
return cv;
{
ObjectLock olock(vars); ObjectLock olock(vars);
for (const auto& kv : vars) { for (const auto& kv : vars) {
Array::Ptr key_val = new Array(); result.push_back(new Array({
key_val->Add(kv.first); kv.first,
key_val->Add(kv.second); kv.second
cv->Add(key_val); }));
} }
} }
return cv; return new Array(std::move(result));
} }

View File

@ -89,16 +89,13 @@ Value ZonesTable::EndpointsAccessor(const Value& row)
std::set<Endpoint::Ptr> endpoints = zone->GetEndpoints(); std::set<Endpoint::Ptr> endpoints = zone->GetEndpoints();
Array::Ptr endpoint_names = new Array(); ArrayData result;
for (const Endpoint::Ptr& endpoint : endpoints) { for (const Endpoint::Ptr& endpoint : endpoints) {
endpoint_names->Add(endpoint->GetName()); result.push_back(endpoint->GetName());
} }
if (!endpoint_names) return new Array(std::move(result));
return Empty;
return endpoint_names;
} }
Value ZonesTable::GlobalAccessor(const Value& row) Value ZonesTable::GlobalAccessor(const Value& row)

View File

@ -138,15 +138,15 @@ void ClusterZoneCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const Che
+ " greater than warning threshold: " + Utility::FormatDuration(lagWarning)); + " greater than warning threshold: " + Utility::FormatDuration(lagWarning));
} }
Array::Ptr perfdata = new Array(); cr->SetPerformanceData(new Array({
perfdata->Add(new PerfdataValue("slave_lag", zoneLag, false, "s", lagWarning, lagCritical)); new PerfdataValue("slave_lag", zoneLag, false, "s", lagWarning, lagCritical),
perfdata->Add(new PerfdataValue("last_messages_sent", lastMessageSent)); new PerfdataValue("last_messages_sent", lastMessageSent),
perfdata->Add(new PerfdataValue("last_messages_received", lastMessageReceived)); new PerfdataValue("last_messages_received", lastMessageReceived),
perfdata->Add(new PerfdataValue("sum_messages_sent_per_second", messagesSentPerSecond)); new PerfdataValue("sum_messages_sent_per_second", messagesSentPerSecond),
perfdata->Add(new PerfdataValue("sum_messages_received_per_second", messagesReceivedPerSecond)); new PerfdataValue("sum_messages_received_per_second", messagesReceivedPerSecond),
perfdata->Add(new PerfdataValue("sum_bytes_sent_per_second", bytesSentPerSecond)); new PerfdataValue("sum_bytes_sent_per_second", bytesSentPerSecond),
perfdata->Add(new PerfdataValue("sum_bytes_received_per_second", bytesReceivedPerSecond)); new PerfdataValue("sum_bytes_received_per_second", bytesReceivedPerSecond)
cr->SetPerformanceData(perfdata); }));
checkable->ProcessCheckResult(cr); checkable->ProcessCheckResult(cr);
} }

View File

@ -41,11 +41,10 @@ void NullCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult:
String output = "Hello from "; String output = "Hello from ";
output += IcingaApplication::GetInstance()->GetNodeName(); output += IcingaApplication::GetInstance()->GetNodeName();
Array::Ptr perfdata = new Array();
perfdata->Add(new PerfdataValue("time", Convert::ToDouble(Utility::GetTime())));
cr->SetOutput(output); cr->SetOutput(output);
cr->SetPerformanceData(perfdata); cr->SetPerformanceData(new Array({
new PerfdataValue("time", Convert::ToDouble(Utility::GetTime()))
}));
cr->SetState(ServiceOK); cr->SetState(ServiceOK);
service->ProcessCheckResult(cr); service->ProcessCheckResult(cr);

View File

@ -45,10 +45,11 @@ void PluginNotificationTask::ScriptFunc(const Notification::Ptr& notification,
Checkable::Ptr checkable = notification->GetCheckable(); Checkable::Ptr checkable = notification->GetCheckable();
Dictionary::Ptr notificationExtra = new Dictionary(); Dictionary::Ptr notificationExtra = new Dictionary({
notificationExtra->Set("type", Notification::NotificationTypeToString(type)); { "type", Notification::NotificationTypeToString(type) },
notificationExtra->Set("author", author); { "author", author },
notificationExtra->Set("comment", comment); { "comment", comment }
});
Host::Ptr host; Host::Ptr host;
Service::Ptr service; Service::Ptr service;

View File

@ -41,11 +41,10 @@ void RandomCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResul
String output = "Hello from "; String output = "Hello from ";
output += IcingaApplication::GetInstance()->GetNodeName(); output += IcingaApplication::GetInstance()->GetNodeName();
Array::Ptr perfdata = new Array();
perfdata->Add(new PerfdataValue("time", Convert::ToDouble(Utility::GetTime())));
cr->SetOutput(output); cr->SetOutput(output);
cr->SetPerformanceData(perfdata); cr->SetPerformanceData(new Array({
new PerfdataValue("time", Convert::ToDouble(Utility::GetTime()))
}));
cr->SetState(static_cast<ServiceState>(Utility::Random() % 4)); cr->SetState(static_cast<ServiceState>(Utility::Random() % 4));
service->ProcessCheckResult(cr); service->ProcessCheckResult(cr);

View File

@ -33,17 +33,16 @@ Array::Ptr TimePeriodTask::EmptyTimePeriodUpdate(const TimePeriod::Ptr&, double,
Array::Ptr TimePeriodTask::EvenMinutesTimePeriodUpdate(const TimePeriod::Ptr&, double begin, double end) Array::Ptr TimePeriodTask::EvenMinutesTimePeriodUpdate(const TimePeriod::Ptr&, double begin, double end)
{ {
Array::Ptr segments = new Array(); ArrayData segments;
for (long t = begin / 60 - 1; t * 60 < end; t++) { for (long t = begin / 60 - 1; t * 60 < end; t++) {
if ((t % 2) == 0) { if ((t % 2) == 0) {
Dictionary::Ptr segment = new Dictionary(); segments.push_back(new Dictionary({
segment->Set("begin", t * 60); { "begin", t * 60 },
segment->Set("end", (t + 1) * 60); { "end", (t + 1) * 60 }
}));
segments->Add(segment);
} }
} }
return segments; return new Array(std::move(segments));
} }

View File

@ -36,13 +36,13 @@ REGISTER_STATSFUNCTION(NotificationComponent, &NotificationComponent::StatsFunc)
void NotificationComponent::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) void NotificationComponent::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const NotificationComponent::Ptr& notification_component : ConfigType::GetObjectsByType<NotificationComponent>()) { for (const NotificationComponent::Ptr& notification_component : ConfigType::GetObjectsByType<NotificationComponent>()) {
nodes->Set(notification_component->GetName(), 1); //add more stats nodes.emplace_back(notification_component->GetName(), 1); //add more stats
} }
status->Set("notificationcomponent", nodes); status->Set("notificationcomponent", new Dictionary(std::move(nodes)));
} }
/** /**

View File

@ -53,23 +53,22 @@ void ElasticsearchWriter::OnConfigLoaded()
void ElasticsearchWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata) void ElasticsearchWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const ElasticsearchWriter::Ptr& elasticsearchwriter : ConfigType::GetObjectsByType<ElasticsearchWriter>()) { for (const ElasticsearchWriter::Ptr& elasticsearchwriter : ConfigType::GetObjectsByType<ElasticsearchWriter>()) {
size_t workQueueItems = elasticsearchwriter->m_WorkQueue.GetLength(); size_t workQueueItems = elasticsearchwriter->m_WorkQueue.GetLength();
double workQueueItemRate = elasticsearchwriter->m_WorkQueue.GetTaskCount(60) / 60.0; double workQueueItemRate = elasticsearchwriter->m_WorkQueue.GetTaskCount(60) / 60.0;
Dictionary::Ptr stats = new Dictionary(); nodes.emplace_back(elasticsearchwriter->GetName(), new Dictionary({
stats->Set("work_queue_items", workQueueItems); { "work_queue_items", workQueueItems },
stats->Set("work_queue_item_rate", workQueueItemRate); { "work_queue_item_rate", workQueueItemRate }
}));
nodes->Set(elasticsearchwriter->GetName(), stats);
perfdata->Add(new PerfdataValue("elasticsearchwriter_" + elasticsearchwriter->GetName() + "_work_queue_items", workQueueItems)); perfdata->Add(new PerfdataValue("elasticsearchwriter_" + elasticsearchwriter->GetName() + "_work_queue_items", workQueueItems));
perfdata->Add(new PerfdataValue("elasticsearchwriter_" + elasticsearchwriter->GetName() + "_work_queue_item_rate", workQueueItemRate)); perfdata->Add(new PerfdataValue("elasticsearchwriter_" + elasticsearchwriter->GetName() + "_work_queue_item_rate", workQueueItemRate));
} }
status->Set("elasticsearchwriter", nodes); status->Set("elasticsearchwriter", new Dictionary(std::move(nodes)));
} }
void ElasticsearchWriter::Start(bool runtimeCreated) void ElasticsearchWriter::Start(bool runtimeCreated)
@ -312,13 +311,13 @@ void ElasticsearchWriter::NotificationSentToAllUsersHandlerInternal(const Notifi
fields->Set("host", host->GetName()); fields->Set("host", host->GetName());
Array::Ptr userNames = new Array(); ArrayData userNames;
for (const User::Ptr& user : users) { for (const User::Ptr& user : users) {
userNames->Add(user->GetName()); userNames.push_back(user->GetName());
} }
fields->Set("users", userNames); fields->Set("users", new Array(std::move(userNames)));
fields->Set("notification_type", notificationTypeString); fields->Set("notification_type", notificationTypeString);
fields->Set("author", author); fields->Set("author", author);
fields->Set("text", text); fields->Set("text", text);

View File

@ -55,25 +55,24 @@ void GelfWriter::OnConfigLoaded()
void GelfWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata) void GelfWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const GelfWriter::Ptr& gelfwriter : ConfigType::GetObjectsByType<GelfWriter>()) { for (const GelfWriter::Ptr& gelfwriter : ConfigType::GetObjectsByType<GelfWriter>()) {
size_t workQueueItems = gelfwriter->m_WorkQueue.GetLength(); size_t workQueueItems = gelfwriter->m_WorkQueue.GetLength();
double workQueueItemRate = gelfwriter->m_WorkQueue.GetTaskCount(60) / 60.0; double workQueueItemRate = gelfwriter->m_WorkQueue.GetTaskCount(60) / 60.0;
Dictionary::Ptr stats = new Dictionary(); nodes.emplace_back(gelfwriter->GetName(), new Dictionary({
stats->Set("work_queue_items", workQueueItems); { "work_queue_items", workQueueItems },
stats->Set("work_queue_item_rate", workQueueItemRate); { "work_queue_item_rate", workQueueItemRate },
stats->Set("connected", gelfwriter->GetConnected()); { "connected", gelfwriter->GetConnected() },
stats->Set("source", gelfwriter->GetSource()); { "source", gelfwriter->GetSource() }
}));
nodes->Set(gelfwriter->GetName(), stats);
perfdata->Add(new PerfdataValue("gelfwriter_" + gelfwriter->GetName() + "_work_queue_items", workQueueItems)); perfdata->Add(new PerfdataValue("gelfwriter_" + gelfwriter->GetName() + "_work_queue_items", workQueueItems));
perfdata->Add(new PerfdataValue("gelfwriter_" + gelfwriter->GetName() + "_work_queue_item_rate", workQueueItemRate)); perfdata->Add(new PerfdataValue("gelfwriter_" + gelfwriter->GetName() + "_work_queue_item_rate", workQueueItemRate));
} }
status->Set("gelfwriter", nodes); status->Set("gelfwriter", new Dictionary(std::move(nodes)));
} }
void GelfWriter::Start(bool runtimeCreated) void GelfWriter::Start(bool runtimeCreated)

View File

@ -55,24 +55,23 @@ void GraphiteWriter::OnConfigLoaded()
void GraphiteWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata) void GraphiteWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const GraphiteWriter::Ptr& graphitewriter : ConfigType::GetObjectsByType<GraphiteWriter>()) { for (const GraphiteWriter::Ptr& graphitewriter : ConfigType::GetObjectsByType<GraphiteWriter>()) {
size_t workQueueItems = graphitewriter->m_WorkQueue.GetLength(); size_t workQueueItems = graphitewriter->m_WorkQueue.GetLength();
double workQueueItemRate = graphitewriter->m_WorkQueue.GetTaskCount(60) / 60.0; double workQueueItemRate = graphitewriter->m_WorkQueue.GetTaskCount(60) / 60.0;
Dictionary::Ptr stats = new Dictionary(); nodes.emplace_back(graphitewriter->GetName(), new Dictionary({
stats->Set("work_queue_items", workQueueItems); { "work_queue_items", workQueueItems },
stats->Set("work_queue_item_rate", workQueueItemRate); { "work_queue_item_rate", workQueueItemRate },
stats->Set("connected", graphitewriter->GetConnected()); { "connected", graphitewriter->GetConnected() }
}));
nodes->Set(graphitewriter->GetName(), stats);
perfdata->Add(new PerfdataValue("graphitewriter_" + graphitewriter->GetName() + "_work_queue_items", workQueueItems)); perfdata->Add(new PerfdataValue("graphitewriter_" + graphitewriter->GetName() + "_work_queue_items", workQueueItems));
perfdata->Add(new PerfdataValue("graphitewriter_" + graphitewriter->GetName() + "_work_queue_item_rate", workQueueItemRate)); perfdata->Add(new PerfdataValue("graphitewriter_" + graphitewriter->GetName() + "_work_queue_item_rate", workQueueItemRate));
} }
status->Set("graphitewriter", nodes); status->Set("graphitewriter", new Dictionary(std::move(nodes)));
} }
void GraphiteWriter::Start(bool runtimeCreated) void GraphiteWriter::Start(bool runtimeCreated)
@ -330,14 +329,14 @@ Value GraphiteWriter::EscapeMacroMetric(const Value& value)
{ {
if (value.IsObjectType<Array>()) { if (value.IsObjectType<Array>()) {
Array::Ptr arr = value; Array::Ptr arr = value;
Array::Ptr result = new Array(); ArrayData result;
ObjectLock olock(arr); ObjectLock olock(arr);
for (const Value& arg : arr) { for (const Value& arg : arr) {
result->Add(EscapeMetric(arg)); result.push_back(EscapeMetric(arg));
} }
return Utility::Join(result, '.'); return Utility::Join(new Array(std::move(result)), '.');
} else } else
return EscapeMetric(value); return EscapeMetric(value);
} }

View File

@ -81,26 +81,25 @@ void InfluxdbWriter::OnConfigLoaded()
void InfluxdbWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata) void InfluxdbWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const InfluxdbWriter::Ptr& influxdbwriter : ConfigType::GetObjectsByType<InfluxdbWriter>()) { for (const InfluxdbWriter::Ptr& influxdbwriter : ConfigType::GetObjectsByType<InfluxdbWriter>()) {
size_t workQueueItems = influxdbwriter->m_WorkQueue.GetLength(); size_t workQueueItems = influxdbwriter->m_WorkQueue.GetLength();
double workQueueItemRate = influxdbwriter->m_WorkQueue.GetTaskCount(60) / 60.0; double workQueueItemRate = influxdbwriter->m_WorkQueue.GetTaskCount(60) / 60.0;
size_t dataBufferItems = influxdbwriter->m_DataBuffer.size(); size_t dataBufferItems = influxdbwriter->m_DataBuffer.size();
Dictionary::Ptr stats = new Dictionary(); nodes.emplace_back(influxdbwriter->GetName(), new Dictionary({
stats->Set("work_queue_items", workQueueItems); { "work_queue_items", workQueueItems },
stats->Set("work_queue_item_rate", workQueueItemRate); { "work_queue_item_rate", workQueueItemRate },
stats->Set("data_buffer_items", dataBufferItems); { "data_buffer_items", dataBufferItems }
}));
nodes->Set(influxdbwriter->GetName(), stats);
perfdata->Add(new PerfdataValue("influxdbwriter_" + influxdbwriter->GetName() + "_work_queue_items", workQueueItems)); perfdata->Add(new PerfdataValue("influxdbwriter_" + influxdbwriter->GetName() + "_work_queue_items", workQueueItems));
perfdata->Add(new PerfdataValue("influxdbwriter_" + influxdbwriter->GetName() + "_work_queue_item_rate", workQueueItemRate)); perfdata->Add(new PerfdataValue("influxdbwriter_" + influxdbwriter->GetName() + "_work_queue_item_rate", workQueueItemRate));
perfdata->Add(new PerfdataValue("influxdbwriter_" + influxdbwriter->GetName() + "_data_queue_items", dataBufferItems)); perfdata->Add(new PerfdataValue("influxdbwriter_" + influxdbwriter->GetName() + "_data_queue_items", dataBufferItems));
} }
status->Set("influxdbwriter", nodes); status->Set("influxdbwriter", new Dictionary(std::move(nodes)));
} }
void InfluxdbWriter::Start(bool runtimeCreated) void InfluxdbWriter::Start(bool runtimeCreated)

View File

@ -55,27 +55,23 @@ class InfluxdbWriter : ConfigObject
}; };
[config, required] Dictionary::Ptr host_template { [config, required] Dictionary::Ptr host_template {
default {{{ default {{{
Dictionary::Ptr tags = new Dictionary(); return new Dictionary({
tags->Set("hostname", "$host.name$"); { "measurement", "$host.check_command$" },
{ "tags", new Dictionary({
Dictionary::Ptr tmpl = new Dictionary(); { "hostname", "$host.name$" }
tmpl->Set("measurement", "$host.check_command$"); }) }
tmpl->Set("tags", tags); });
return tmpl;
}}} }}}
}; };
[config, required] Dictionary::Ptr service_template { [config, required] Dictionary::Ptr service_template {
default {{{ default {{{
Dictionary::Ptr tags = new Dictionary(); return new Dictionary({
tags->Set("hostname", "$host.name$"); { "measurement", "$service.check_command$" },
tags->Set("service", "$service.name$"); { "tags", new Dictionary({
{ "hostname", "$host.name" },
Dictionary::Ptr tmpl = new Dictionary(); { "service", "$service.name$" }
tmpl->Set("measurement", "$service.check_command$"); }) }
tmpl->Set("tags", tags); });
return tmpl;
}}} }}}
}; };
[config] bool enable_send_thresholds { [config] bool enable_send_thresholds {

View File

@ -48,13 +48,13 @@ REGISTER_STATSFUNCTION(OpenTsdbWriter, &OpenTsdbWriter::StatsFunc);
void OpenTsdbWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) void OpenTsdbWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const OpenTsdbWriter::Ptr& opentsdbwriter : ConfigType::GetObjectsByType<OpenTsdbWriter>()) { for (const OpenTsdbWriter::Ptr& opentsdbwriter : ConfigType::GetObjectsByType<OpenTsdbWriter>()) {
nodes->Set(opentsdbwriter->GetName(), 1); //add more stats nodes.emplace_back(opentsdbwriter->GetName(), 1); //add more stats
} }
status->Set("opentsdbwriter", nodes); status->Set("opentsdbwriter", new Dictionary(std::move(nodes)));
} }
void OpenTsdbWriter::Start(bool runtimeCreated) void OpenTsdbWriter::Start(bool runtimeCreated)

View File

@ -40,13 +40,13 @@ REGISTER_STATSFUNCTION(PerfdataWriter, &PerfdataWriter::StatsFunc);
void PerfdataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) void PerfdataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{ {
Dictionary::Ptr nodes = new Dictionary(); DictionaryData nodes;
for (const PerfdataWriter::Ptr& perfdatawriter : ConfigType::GetObjectsByType<PerfdataWriter>()) { for (const PerfdataWriter::Ptr& perfdatawriter : ConfigType::GetObjectsByType<PerfdataWriter>()) {
nodes->Set(perfdatawriter->GetName(), 1); //add more stats nodes.emplace_back(perfdatawriter->GetName(), 1); //add more stats
} }
status->Set("perfdatawriter", nodes); status->Set("perfdatawriter", new Dictionary(std::move(nodes)));
} }
void PerfdataWriter::Start(bool runtimeCreated) void PerfdataWriter::Start(bool runtimeCreated)

View File

@ -72,30 +72,33 @@ bool ActionsHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& reques
objs.emplace_back(nullptr); objs.emplace_back(nullptr);
} }
Array::Ptr results = new Array(); ArrayData results;
Log(LogNotice, "ApiActionHandler") Log(LogNotice, "ApiActionHandler")
<< "Running action " << actionName; << "Running action " << actionName;
for (const ConfigObject::Ptr& obj : objs) { for (const ConfigObject::Ptr& obj : objs) {
try { try {
results->Add(action->Invoke(obj, params)); results.emplace_back(action->Invoke(obj, params));
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
Dictionary::Ptr fail = new Dictionary(); Dictionary::Ptr fail = new Dictionary({
fail->Set("code", 500); { "code", 500 },
fail->Set("status", "Action execution failed: '" + DiagnosticInformation(ex, false) + "'."); { "status", "Action execution failed: '" + DiagnosticInformation(ex, false) + "'." }
});
if (HttpUtility::GetLastParameter(params, "verboseErrors")) if (HttpUtility::GetLastParameter(params, "verboseErrors"))
fail->Set("diagnostic information", DiagnosticInformation(ex)); fail->Set("diagnostic information", DiagnosticInformation(ex));
results->Add(fail);
results.emplace_back(std::move(fail));
} }
} }
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("results", results); { "results", new Array(std::move(results)) }
});
response.SetStatus(200, "OK"); response.SetStatus(200, "OK");
HttpUtility::SendJsonBody(response, params, result); HttpUtility::SendJsonBody(response, params, result);
return true; return true;
} }

View File

@ -289,11 +289,14 @@ void ApiListener::UpdateConfigObject(const ConfigObject::Ptr& object, const Mess
if (object->GetPackage() != "_api" && object->GetVersion() == 0) if (object->GetPackage() != "_api" && object->GetVersion() == 0)
return; return;
Dictionary::Ptr message = new Dictionary();
message->Set("jsonrpc", "2.0");
message->Set("method", "config::UpdateObject");
Dictionary::Ptr params = new Dictionary(); Dictionary::Ptr params = new Dictionary();
Dictionary::Ptr message = new Dictionary({
{ "jsonrpc", "2.0" },
{ "method", "config::UpdateObject" },
{ "params", params }
});
params->Set("name", object->GetName()); params->Set("name", object->GetName());
params->Set("type", object->GetReflectionType()->GetName()); params->Set("type", object->GetReflectionType()->GetName());
params->Set("version", object->GetVersion()); params->Set("version", object->GetVersion());
@ -311,7 +314,7 @@ void ApiListener::UpdateConfigObject(const ConfigObject::Ptr& object, const Mess
Dictionary::Ptr original_attributes = object->GetOriginalAttributes(); Dictionary::Ptr original_attributes = object->GetOriginalAttributes();
Dictionary::Ptr modified_attributes = new Dictionary(); Dictionary::Ptr modified_attributes = new Dictionary();
Array::Ptr newOriginalAttributes = new Array(); ArrayData newOriginalAttributes;
if (original_attributes) { if (original_attributes) {
ObjectLock olock(original_attributes); ObjectLock olock(original_attributes);
@ -326,16 +329,14 @@ void ApiListener::UpdateConfigObject(const ConfigObject::Ptr& object, const Mess
modified_attributes->Set(kv.first, value); modified_attributes->Set(kv.first, value);
newOriginalAttributes->Add(kv.first); newOriginalAttributes.push_back(kv.first);
} }
} }
params->Set("modified_attributes", modified_attributes); params->Set("modified_attributes", modified_attributes);
/* only send the original attribute keys */ /* only send the original attribute keys */
params->Set("original_attributes", newOriginalAttributes); params->Set("original_attributes", new Array(std::move(newOriginalAttributes)));
message->Set("params", params);
#ifdef I2_DEBUG #ifdef I2_DEBUG
Log(LogDebug, "ApiListener") Log(LogDebug, "ApiListener")
@ -374,16 +375,18 @@ void ApiListener::DeleteConfigObject(const ConfigObject::Ptr& object, const Mess
} }
} }
Dictionary::Ptr message = new Dictionary();
message->Set("jsonrpc", "2.0");
message->Set("method", "config::DeleteObject");
Dictionary::Ptr params = new Dictionary(); Dictionary::Ptr params = new Dictionary();
Dictionary::Ptr message = new Dictionary({
{ "jsonrpc", "2.0" },
{ "method", "config::DeleteObject" },
{ "params", params }
});
params->Set("name", object->GetName()); params->Set("name", object->GetName());
params->Set("type", object->GetReflectionType()->GetName()); params->Set("type", object->GetReflectionType()->GetName());
params->Set("version", object->GetVersion()); params->Set("version", object->GetVersion());
message->Set("params", params);
#ifdef I2_DEBUG #ifdef I2_DEBUG
Log(LogDebug, "ApiListener") Log(LogDebug, "ApiListener")

View File

@ -260,14 +260,14 @@ void ApiListener::SendConfigUpdate(const JsonRpcConnection::Ptr& aclient)
configUpdateV2->Set(zone->GetName(), config.UpdateV2); configUpdateV2->Set(zone->GetName(), config.UpdateV2);
} }
Dictionary::Ptr params = new Dictionary(); Dictionary::Ptr message = new Dictionary({
params->Set("update", configUpdateV1); { "jsonrpc", "2.0" },
params->Set("update_v2", configUpdateV2); { "method", "config::Update" },
{ "params", new Dictionary({
Dictionary::Ptr message = new Dictionary(); { "update", configUpdateV1 },
message->Set("jsonrpc", "2.0"); { "update_v2", configUpdateV2 }
message->Set("method", "config::Update"); }) }
message->Set("params", params); });
aclient->SendMessage(message); aclient->SendMessage(message);
} }

View File

@ -503,10 +503,12 @@ void ApiListener::NewClientHandlerInternal(const Socket::Ptr& client, const Stri
ClientType ctype; ClientType ctype;
if (role == RoleClient) { if (role == RoleClient) {
Dictionary::Ptr message = new Dictionary(); Dictionary::Ptr message = new Dictionary({
message->Set("jsonrpc", "2.0"); { "jsonrpc", "2.0" },
message->Set("method", "icinga::Hello"); { "method", "icinga::Hello" },
message->Set("params", new Dictionary()); { "params", new Dictionary() }
});
JsonRpc::SendMessage(tlsStream, message); JsonRpc::SendMessage(tlsStream, message);
ctype = ClientJsonRpc; ctype = ClientJsonRpc;
} else { } else {
@ -666,13 +668,13 @@ void ApiListener::ApiTimerHandler()
if (ts == 0) if (ts == 0)
continue; continue;
Dictionary::Ptr lparams = new Dictionary(); Dictionary::Ptr lmessage = new Dictionary({
lparams->Set("log_position", ts); { "jsonrpc", "2.0" },
{ "method", "log::SetLogPosition" },
Dictionary::Ptr lmessage = new Dictionary(); { "params", new Dictionary({
lmessage->Set("jsonrpc", "2.0"); { "log_position", ts }
lmessage->Set("method", "log::SetLogPosition"); }) }
lmessage->Set("params", lparams); });
double maxTs = 0; double maxTs = 0;
@ -1161,13 +1163,13 @@ void ApiListener::ReplayLog(const JsonRpcConnection::Ptr& client)
if (ts > logpos_ts + 10) { if (ts > logpos_ts + 10) {
logpos_ts = ts; logpos_ts = ts;
Dictionary::Ptr lparams = new Dictionary(); Dictionary::Ptr lmessage = new Dictionary({
lparams->Set("log_position", logpos_ts); { "jsonrpc", "2.0" },
{ "method", "log::SetLogPosition" },
Dictionary::Ptr lmessage = new Dictionary(); { "params", new Dictionary({
lmessage->Set("jsonrpc", "2.0"); { "log_position", logpos_ts }
lmessage->Set("method", "log::SetLogPosition"); }) }
lmessage->Set("params", lparams); });
size_t bytesSent = JsonRpc::SendMessage(client->GetStream(), lmessage); size_t bytesSent = JsonRpc::SendMessage(client->GetStream(), lmessage);
endpoint->AddMessageSent(bytesSent); endpoint->AddMessageSent(bytesSent);
@ -1218,11 +1220,9 @@ void ApiListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& per
std::pair<Dictionary::Ptr, Dictionary::Ptr> ApiListener::GetStatus() std::pair<Dictionary::Ptr, Dictionary::Ptr> ApiListener::GetStatus()
{ {
Dictionary::Ptr status = new Dictionary();
Dictionary::Ptr perfdata = new Dictionary(); Dictionary::Ptr perfdata = new Dictionary();
/* cluster stats */ /* cluster stats */
status->Set("identity", GetIdentity());
double allEndpoints = 0; double allEndpoints = 0;
Array::Ptr allNotConnectedEndpoints = new Array(); Array::Ptr allNotConnectedEndpoints = new Array();
@ -1244,10 +1244,10 @@ std::pair<Dictionary::Ptr, Dictionary::Ptr> ApiListener::GetStatus()
int countZoneEndpoints = 0; int countZoneEndpoints = 0;
double zoneLag = 0; double zoneLag = 0;
Array::Ptr zoneEndpoints = new Array(); ArrayData zoneEndpoints;
for (const Endpoint::Ptr& endpoint : zone->GetEndpoints()) { for (const Endpoint::Ptr& endpoint : zone->GetEndpoints()) {
zoneEndpoints->Add(endpoint->GetName()); zoneEndpoints.emplace_back(endpoint->GetName());
if (endpoint->GetName() == GetIdentity()) if (endpoint->GetName() == GetIdentity())
continue; continue;
@ -1272,29 +1272,21 @@ std::pair<Dictionary::Ptr, Dictionary::Ptr> ApiListener::GetStatus()
if (zone->GetEndpoints().size() == 1 && countZoneEndpoints == 0) if (zone->GetEndpoints().size() == 1 && countZoneEndpoints == 0)
zoneConnected = true; zoneConnected = true;
Dictionary::Ptr zoneStats = new Dictionary();
zoneStats->Set("connected", zoneConnected);
zoneStats->Set("client_log_lag", zoneLag);
zoneStats->Set("endpoints", zoneEndpoints);
String parentZoneName; String parentZoneName;
Zone::Ptr parentZone = zone->GetParent(); Zone::Ptr parentZone = zone->GetParent();
if (parentZone) if (parentZone)
parentZoneName = parentZone->GetName(); parentZoneName = parentZone->GetName();
zoneStats->Set("parent_zone", parentZoneName); Dictionary::Ptr zoneStats = new Dictionary({
{ "connected", zoneConnected },
{ "client_log_lag", zoneLag },
{ "endpoints", new Array(std::move(zoneEndpoints)) },
{ "parent_zone", parentZoneName }
});
connectedZones->Set(zone->GetName(), zoneStats); connectedZones->Set(zone->GetName(), zoneStats);
} }
status->Set("num_endpoints", allEndpoints);
status->Set("num_conn_endpoints", allConnectedEndpoints->GetLength());
status->Set("num_not_conn_endpoints", allNotConnectedEndpoints->GetLength());
status->Set("conn_endpoints", allConnectedEndpoints);
status->Set("not_conn_endpoints", allNotConnectedEndpoints);
status->Set("zones", connectedZones);
/* connection stats */ /* connection stats */
size_t jsonRpcClients = GetAnonymousClients().size(); size_t jsonRpcClients = GetAnonymousClients().size();
size_t httpClients = GetHttpClients().size(); size_t httpClients = GetHttpClients().size();
@ -1306,22 +1298,31 @@ std::pair<Dictionary::Ptr, Dictionary::Ptr> ApiListener::GetStatus()
double syncQueueItemRate = m_SyncQueue.GetTaskCount(60) / 60.0; double syncQueueItemRate = m_SyncQueue.GetTaskCount(60) / 60.0;
double relayQueueItemRate = m_RelayQueue.GetTaskCount(60) / 60.0; double relayQueueItemRate = m_RelayQueue.GetTaskCount(60) / 60.0;
Dictionary::Ptr jsonRpc = new Dictionary(); Dictionary::Ptr status = new Dictionary({
jsonRpc->Set("clients", jsonRpcClients); { "identity", GetIdentity() },
jsonRpc->Set("work_queue_items", workQueueItems); { "num_endpoints", allEndpoints },
jsonRpc->Set("work_queue_count", workQueueCount); { "num_conn_endpoints", allConnectedEndpoints->GetLength() },
jsonRpc->Set("sync_queue_items", syncQueueItems); { "num_not_conn_endpoints", allNotConnectedEndpoints->GetLength() },
jsonRpc->Set("relay_queue_items", relayQueueItems); { "conn_endpoints", allConnectedEndpoints },
{ "not_conn_endpoints", allNotConnectedEndpoints },
jsonRpc->Set("work_queue_item_rate", workQueueItemRate); { "zones", connectedZones },
jsonRpc->Set("sync_queue_item_rate", syncQueueItemRate);
jsonRpc->Set("relay_queue_item_rate", relayQueueItemRate);
Dictionary::Ptr http = new Dictionary(); { "json_rpc", new Dictionary({
http->Set("clients", httpClients); { "clients", jsonRpcClients },
{ "work_queue_items", workQueueItems },
{ "work_queue_count", workQueueCount },
{ "sync_queue_items", syncQueueItems },
{ "relay_queue_items", relayQueueItems },
{ "work_queue_item_rate", workQueueItemRate },
{ "sync_queue_item_rate", syncQueueItemRate },
{ "relay_queue_item_rate", relayQueueItemRate }
}) },
status->Set("json_rpc", jsonRpc); { "http", new Dictionary({
status->Set("http", http); { "clients", httpClients }
}) }
});
/* performance data */ /* performance data */
perfdata->Set("num_endpoints", allEndpoints); perfdata->Set("num_endpoints", allEndpoints);

View File

@ -51,21 +51,22 @@ void ConfigPackagesHandler::HandleGet(const ApiUser::Ptr& user, HttpRequest& req
std::vector<String> packages = ConfigPackageUtility::GetPackages(); std::vector<String> packages = ConfigPackageUtility::GetPackages();
Array::Ptr results = new Array(); ArrayData results;
{ {
boost::mutex::scoped_lock lock(ConfigPackageUtility::GetStaticMutex()); boost::mutex::scoped_lock lock(ConfigPackageUtility::GetStaticMutex());
for (const String& package : packages) { for (const String& package : packages) {
Dictionary::Ptr packageInfo = new Dictionary(); results.emplace_back(new Dictionary({
packageInfo->Set("name", package); { "name", package },
packageInfo->Set("stages", Array::FromVector(ConfigPackageUtility::GetStages(package))); { "stages", Array::FromVector(ConfigPackageUtility::GetStages(package)) },
packageInfo->Set("active-stage", ConfigPackageUtility::GetActiveStage(package)); { "active-stage", ConfigPackageUtility::GetActiveStage(package) }
results->Add(packageInfo); }));
} }
} }
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("results", results); { "results", new Array(std::move(results)) }
});
response.SetStatus(200, "OK"); response.SetStatus(200, "OK");
HttpUtility::SendJsonBody(response, params, result); HttpUtility::SendJsonBody(response, params, result);
@ -85,8 +86,6 @@ void ConfigPackagesHandler::HandlePost(const ApiUser::Ptr& user, HttpRequest& re
return; return;
} }
Dictionary::Ptr result1 = new Dictionary();
try { try {
boost::mutex::scoped_lock lock(ConfigPackageUtility::GetStaticMutex()); boost::mutex::scoped_lock lock(ConfigPackageUtility::GetStaticMutex());
ConfigPackageUtility::CreatePackage(packageName); ConfigPackageUtility::CreatePackage(packageName);
@ -96,14 +95,14 @@ void ConfigPackagesHandler::HandlePost(const ApiUser::Ptr& user, HttpRequest& re
return; return;
} }
result1->Set("code", 200); Dictionary::Ptr result1 = new Dictionary({
result1->Set("status", "Created package."); { "code", 200 },
{ "status", "Created package." }
});
Array::Ptr results = new Array(); Dictionary::Ptr result = new Dictionary({
results->Add(result1); { "results", new Array({ result1 }) }
});
Dictionary::Ptr result = new Dictionary();
result->Set("results", results);
response.SetStatus(200, "OK"); response.SetStatus(200, "OK");
HttpUtility::SendJsonBody(response, params, result); HttpUtility::SendJsonBody(response, params, result);
@ -125,7 +124,7 @@ void ConfigPackagesHandler::HandleDelete(const ApiUser::Ptr& user, HttpRequest&
int code = 200; int code = 200;
String status = "Deleted package."; String status = "Deleted package.";
Dictionary::Ptr result1 = new Dictionary(); DictionaryData result1;
try { try {
ConfigPackageUtility::DeletePackage(packageName); ConfigPackageUtility::DeletePackage(packageName);
@ -133,21 +132,17 @@ void ConfigPackagesHandler::HandleDelete(const ApiUser::Ptr& user, HttpRequest&
code = 500; code = 500;
status = "Failed to delete package."; status = "Failed to delete package.";
if (HttpUtility::GetLastParameter(params, "verboseErrors")) if (HttpUtility::GetLastParameter(params, "verboseErrors"))
result1->Set("diagnostic information", DiagnosticInformation(ex)); result1.emplace_back("diagnostic information", DiagnosticInformation(ex));
} }
result1.emplace_back("package", packageName);
result1.emplace_back("code", code);
result1.emplace_back("status", status);
result1->Set("package", packageName); Dictionary::Ptr result = new Dictionary({
result1->Set("code", code); { "results", new Array({ new Dictionary(std::move(result1)) }) }
result1->Set("status", status); });
Array::Ptr results = new Array();
results->Add(result1);
Dictionary::Ptr result = new Dictionary();
result->Set("results", results);
response.SetStatus(code, (code == 200) ? "OK" : "Internal Server Error"); response.SetStatus(code, (code == 200) ? "OK" : "Internal Server Error");
HttpUtility::SendJsonBody(response, params, result); HttpUtility::SendJsonBody(response, params, result);
} }

View File

@ -208,12 +208,13 @@ void ConfigPackageUtility::AsyncTryActivateStage(const String& packageName, cons
VERIFY(Application::GetArgC() >= 1); VERIFY(Application::GetArgC() >= 1);
// prepare arguments // prepare arguments
Array::Ptr args = new Array(); Array::Ptr args = new Array({
args->Add(Application::GetExePath(Application::GetArgV()[0])); Application::GetExePath(Application::GetArgV()[0]),
args->Add("daemon"); "daemon",
args->Add("--validate"); "--validate",
args->Add("--define"); "--define",
args->Add("ActiveStageOverride=" + packageName + ":" + stageName); "ActiveStageOverride=" + packageName + ":" + stageName
});
Process::Ptr process = new Process(Process::PrepareCommand(args)); Process::Ptr process = new Process(Process::PrepareCommand(args));
process->SetTimeout(300); process->SetTimeout(300);

View File

@ -65,22 +65,22 @@ void ConfigStagesHandler::HandleGet(const ApiUser::Ptr& user, HttpRequest& reque
if (!ConfigPackageUtility::ValidateName(stageName)) if (!ConfigPackageUtility::ValidateName(stageName))
return HttpUtility::SendJsonError(response, params, 400, "Invalid stage name."); return HttpUtility::SendJsonError(response, params, 400, "Invalid stage name.");
Array::Ptr results = new Array(); ArrayData results;
std::vector<std::pair<String, bool> > paths = ConfigPackageUtility::GetFiles(packageName, stageName); std::vector<std::pair<String, bool> > paths = ConfigPackageUtility::GetFiles(packageName, stageName);
String prefixPath = ConfigPackageUtility::GetPackageDir() + "/" + packageName + "/" + stageName + "/"; String prefixPath = ConfigPackageUtility::GetPackageDir() + "/" + packageName + "/" + stageName + "/";
typedef std::pair<String, bool> kv_pair; for (const auto& kv : paths) {
for (const kv_pair& kv : paths) { results.push_back(new Dictionary({
Dictionary::Ptr stageInfo = new Dictionary(); { "type", kv.second ? "directory" : "file" },
stageInfo->Set("type", (kv.second ? "directory" : "file")); { "name", kv.first.SubStr(prefixPath.GetLength()) }
stageInfo->Set("name", kv.first.SubStr(prefixPath.GetLength())); }));
results->Add(stageInfo);
} }
Dictionary::Ptr result = new Dictionary(); Dictionary::Ptr result = new Dictionary({
result->Set("results", results); { "results", new Array(std::move(results)) }
});
response.SetStatus(200, "OK"); response.SetStatus(200, "OK");
HttpUtility::SendJsonBody(response, params, result); HttpUtility::SendJsonBody(response, params, result);
@ -121,21 +121,20 @@ void ConfigStagesHandler::HandlePost(const ApiUser::Ptr& user, HttpRequest& requ
HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : ""); HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
} }
Dictionary::Ptr result1 = new Dictionary();
String responseStatus = "Created stage. "; String responseStatus = "Created stage. ";
responseStatus += (reload ? " Icinga2 will reload." : " Icinga2 reload skipped."); responseStatus += (reload ? " Icinga2 will reload." : " Icinga2 reload skipped.");
result1->Set("package", packageName); Dictionary::Ptr result1 = new Dictionary({
result1->Set("stage", stageName); { "package", packageName },
result1->Set("code", 200); { "stage", stageName },
result1->Set("status", responseStatus); { "code", 200 },
{ "status", responseStatus }
});
Array::Ptr results = new Array(); Dictionary::Ptr result = new Dictionary({
results->Add(result1); { "results", new Array({ result1 }) }
});
Dictionary::Ptr result = new Dictionary();
result->Set("results", results);
response.SetStatus(200, "OK"); response.SetStatus(200, "OK");
HttpUtility::SendJsonBody(response, params, result); HttpUtility::SendJsonBody(response, params, result);
@ -168,16 +167,14 @@ void ConfigStagesHandler::HandleDelete(const ApiUser::Ptr& user, HttpRequest& re
HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : ""); HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : "");
} }
Dictionary::Ptr result1 = new Dictionary(); Dictionary::Ptr result1 = new Dictionary({
{ "code", 200 },
{ "status", "Stage deleted." }
});
result1->Set("code", 200); Dictionary::Ptr result = new Dictionary({
result1->Set("status", "Stage deleted."); { "results", new Array({ result1 }) }
});
Array::Ptr results = new Array();
results->Add(result1);
Dictionary::Ptr result = new Dictionary();
result->Set("results", results);
response.SetStatus(200, "OK"); response.SetStatus(200, "OK");
HttpUtility::SendJsonBody(response, params, result); HttpUtility::SendJsonBody(response, params, result);

View File

@ -121,8 +121,7 @@ bool ConsoleHandler::ExecuteScriptHelper(HttpRequest& request, HttpResponse& res
lsf.Lines[fileName] = command; lsf.Lines[fileName] = command;
Array::Ptr results = new Array(); Dictionary::Ptr resultInfo;
Dictionary::Ptr resultInfo = new Dictionary();
std::unique_ptr<Expression> expr; std::unique_ptr<Expression> expr;
Value exprResult; Value exprResult;
@ -136,9 +135,11 @@ bool ConsoleHandler::ExecuteScriptHelper(HttpRequest& request, HttpResponse& res
exprResult = expr->Evaluate(frame); exprResult = expr->Evaluate(frame);
resultInfo->Set("code", 200); resultInfo = new Dictionary({
resultInfo->Set("status", "Executed successfully."); { "code", 200 },
resultInfo->Set("result", Serialize(exprResult, 0)); { "status", "Executed successfully." },
{ "result", Serialize(exprResult, 0) }
});
} catch (const ScriptError& ex) { } catch (const ScriptError& ex) {
DebugInfo di = ex.GetDebugInfo(); DebugInfo di = ex.GetDebugInfo();
@ -149,23 +150,23 @@ bool ConsoleHandler::ExecuteScriptHelper(HttpRequest& request, HttpResponse& res
<< String(di.FirstColumn, ' ') << String(di.LastColumn - di.FirstColumn + 1, '^') << "\n" << String(di.FirstColumn, ' ') << String(di.LastColumn - di.FirstColumn + 1, '^') << "\n"
<< ex.what() << "\n"; << ex.what() << "\n";
resultInfo->Set("code", 500); resultInfo = new Dictionary({
resultInfo->Set("status", String(msgbuf.str())); { "code", 500 },
resultInfo->Set("incomplete_expression", ex.IsIncompleteExpression()); { "status", String(msgbuf.str()) },
{ "incomplete_expression", ex.IsIncompleteExpression() },
Dictionary::Ptr debugInfo = new Dictionary(); { "debug_info", new Dictionary({
debugInfo->Set("path", di.Path); { "path", di.Path },
debugInfo->Set("first_line", di.FirstLine); { "first_line", di.FirstLine },
debugInfo->Set("first_column", di.FirstColumn); { "first_column", di.FirstColumn },
debugInfo->Set("last_line", di.LastLine); { "last_line", di.LastLine },
debugInfo->Set("last_column", di.LastColumn); { "last_column", di.LastColumn }
resultInfo->Set("debug_info", debugInfo); }) }
});
} }
results->Add(resultInfo); Dictionary::Ptr result = new Dictionary({
{ "results", new Array({ resultInfo }) }
Dictionary::Ptr result = new Dictionary(); });
result->Set("results", results);
response.SetStatus(200, "OK"); response.SetStatus(200, "OK");
HttpUtility::SendJsonBody(response, params, result); HttpUtility::SendJsonBody(response, params, result);
@ -187,22 +188,21 @@ bool ConsoleHandler::AutocompleteScriptHelper(HttpRequest& request, HttpResponse
if (!lsf.Locals) if (!lsf.Locals)
lsf.Locals = new Dictionary(); lsf.Locals = new Dictionary();
Array::Ptr results = new Array();
Dictionary::Ptr resultInfo = new Dictionary();
ScriptFrame frame(true); ScriptFrame frame(true);
frame.Locals = lsf.Locals; frame.Locals = lsf.Locals;
frame.Self = lsf.Locals; frame.Self = lsf.Locals;
frame.Sandboxed = sandboxed; frame.Sandboxed = sandboxed;
resultInfo->Set("code", 200); Dictionary::Ptr result1 = new Dictionary({
resultInfo->Set("status", "Auto-completed successfully."); { "code", 200 },
resultInfo->Set("suggestions", Array::FromVector(GetAutocompletionSuggestions(command, frame))); { "status", "Auto-completed successfully." },
{ "suggestions", Array::FromVector(GetAutocompletionSuggestions(command, frame)) }
});
results->Add(resultInfo); Dictionary::Ptr result = new Dictionary({
{ "results", new Array({ result1 }) }
Dictionary::Ptr result = new Dictionary(); });
result->Set("results", results);
response.SetStatus(200, "OK"); response.SetStatus(200, "OK");
HttpUtility::SendJsonBody(response, params, result); HttpUtility::SendJsonBody(response, params, result);

Some files were not shown because too many files have changed in this diff Show More