From: Gunnar Beutner Date: Thu, 11 Jan 2018 10:17:38 +0000 (+0100) Subject: Use initializer lists for arrays and dictionaries X-Git-Tag: v2.9.0~217^2 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=refs%2Fpull%2F5983%2Fhead;p=icinga2 Use initializer lists for arrays and dictionaries --- diff --git a/lib/base/application.cpp b/lib/base/application.cpp index 0c325c728..e1717522c 100644 --- a/lib/base/application.cpp +++ b/lib/base/application.cpp @@ -400,24 +400,24 @@ pid_t Application::StartReloadProcess() Log(LogInformation, "Application", "Got reload command: Starting new instance."); // prepare arguments - Array::Ptr args = new Array(); - args->Add(GetExePath(m_ArgV[0])); + ArrayData args; + args.push_back(GetExePath(m_ArgV[0])); for (int i=1; i < Application::GetArgC(); i++) { if (std::string(Application::GetArgV()[i]) != "--reload-internal") - args->Add(Application::GetArgV()[i]); + args.push_back(Application::GetArgV()[i]); else i++; // the next parameter after --reload-internal is the pid, remove that too } #ifndef _WIN32 - args->Add("--reload-internal"); - args->Add(Convert::ToString(Utility::GetPid())); + args.push_back("--reload-internal"); + args.push_back(Convert::ToString(Utility::GetPid())); #else /* _WIN32 */ - args->Add("--validate"); + args.push_back("--validate"); #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->Run(&ReloadProcessCallback); diff --git a/lib/base/array-script.cpp b/lib/base/array-script.cpp index 9bfec4130..3f7278ff6 100644 --- a/lib/base/array-script.cpp +++ b/lib/base/array-script.cpp @@ -147,14 +147,14 @@ static Array::Ptr ArrayMap(const Function::Ptr& function) if (vframe->Sandboxed && !function->IsSideEffectFree()) BOOST_THROW_EXCEPTION(ScriptError("Map function must be side-effect free.")); - Array::Ptr result = new Array(); + ArrayData result; ObjectLock olock(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) @@ -186,15 +186,15 @@ static Array::Ptr ArrayFilter(const Function::Ptr& function) if (vframe->Sandboxed && !function->IsSideEffectFree()) BOOST_THROW_EXCEPTION(ScriptError("Filter function must be side-effect free.")); - Array::Ptr result = new Array(); + ArrayData result; ObjectLock olock(self); for (const Value& item : self) { 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) @@ -247,28 +247,25 @@ static Array::Ptr ArrayUnique() Object::Ptr Array::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - prototype->Set("len", new Function("Array#len", ArrayLen, {}, true)); - prototype->Set("set", new Function("Array#set", ArraySet, { "index", "value" })); - prototype->Set("get", new Function("Array#get", ArrayGet, { "index" })); - prototype->Set("add", new Function("Array#add", ArrayAdd, { "value" })); - prototype->Set("remove", new Function("Array#remove", ArrayRemove, { "index" })); - prototype->Set("contains", new Function("Array#contains", ArrayContains, { "value" }, true)); - prototype->Set("clear", new Function("Array#clear", ArrayClear)); - prototype->Set("sort", new Function("Array#sort", ArraySort, { "less_cmp" }, true)); - prototype->Set("shallow_clone", new Function("Array#shallow_clone", ArrayShallowClone, {}, true)); - prototype->Set("join", new Function("Array#join", ArrayJoin, { "separator" }, true)); - prototype->Set("reverse", new Function("Array#reverse", ArrayReverse, {}, true)); - prototype->Set("map", new Function("Array#map", ArrayMap, { "func" }, true)); - prototype->Set("reduce", new Function("Array#reduce", ArrayReduce, { "reduce" }, true)); - prototype->Set("filter", new Function("Array#filter", ArrayFilter, { "func" }, 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)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "len", new Function("Array#len", ArrayLen, {}, true) }, + { "set", new Function("Array#set", ArraySet, { "index", "value" }) }, + { "get", new Function("Array#get", ArrayGet, { "index" }) }, + { "add", new Function("Array#add", ArrayAdd, { "value" }) }, + { "remove", new Function("Array#remove", ArrayRemove, { "index" }) }, + { "contains", new Function("Array#contains", ArrayContains, { "value" }, true) }, + { "clear", new Function("Array#clear", ArrayClear) }, + { "sort", new Function("Array#sort", ArraySort, { "less_cmp" }, true) }, + { "shallow_clone", new Function("Array#shallow_clone", ArrayShallowClone, {}, true) }, + { "join", new Function("Array#join", ArrayJoin, { "separator" }, true) }, + { "reverse", new Function("Array#reverse", ArrayReverse, {}, true) }, + { "map", new Function("Array#map", ArrayMap, { "func" }, true) }, + { "reduce", new Function("Array#reduce", ArrayReduce, { "reduce" }, true) }, + { "filter", new Function("Array#filter", ArrayFilter, { "func" }, true) }, + { "any", new Function("Array#any", ArrayAny, { "func" }, true) }, + { "all", new Function("Array#all", ArrayAll, { "func" }, true) }, + { "unique", new Function("Array#unique", ArrayUnique, {}, true) } + }); return prototype; } diff --git a/lib/base/array.cpp b/lib/base/array.cpp index 2a00d3b29..d6e8ee03e 100644 --- a/lib/base/array.cpp +++ b/lib/base/array.cpp @@ -32,6 +32,14 @@ template class std::vector; 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 init) : m_Data(init) { } @@ -228,14 +236,14 @@ Array::Ptr Array::ShallowClone() const */ Object::Ptr Array::Clone() const { - Array::Ptr arr = new Array(); + ArrayData arr; ObjectLock olock(this); 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 @@ -305,4 +313,3 @@ Array::Iterator icinga::end(const Array::Ptr& x) { return x->End(); } - diff --git a/lib/base/array.hpp b/lib/base/array.hpp index 36f4f62f9..6fd1abae5 100644 --- a/lib/base/array.hpp +++ b/lib/base/array.hpp @@ -30,6 +30,8 @@ namespace icinga { +typedef std::vector ArrayData; + /** * An array of Value items. * @@ -48,6 +50,8 @@ public: typedef std::vector::size_type SizeType; Array() = default; + Array(const ArrayData& other); + Array(ArrayData&& other); Array(std::initializer_list init); Value Get(SizeType index) const; diff --git a/lib/base/boolean-script.cpp b/lib/base/boolean-script.cpp index e0da2e9bc..1116cc250 100644 --- a/lib/base/boolean-script.cpp +++ b/lib/base/boolean-script.cpp @@ -34,12 +34,9 @@ static String BooleanToString() Object::Ptr Boolean::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - prototype->Set("to_string", new Function("Boolean#to_string", BooleanToString, {}, true)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "to_string", new Function("Boolean#to_string", BooleanToString, {}, true) } + }); return prototype; } diff --git a/lib/base/configobject-script.cpp b/lib/base/configobject-script.cpp index 7321e3bf5..d2cdba45b 100644 --- a/lib/base/configobject-script.cpp +++ b/lib/base/configobject-script.cpp @@ -41,13 +41,10 @@ static void ConfigObjectRestoreAttribute(const String& attr) Object::Ptr ConfigObject::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - 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)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "modify_attribute", new Function("ConfigObject#modify_attribute", ConfigObjectModifyAttribute, { "attr", "value" }, false) }, + { "restore_attribute", new Function("ConfigObject#restore_attribute", ConfigObjectRestoreAttribute, { "attr", "value" }, false) } + }); return prototype; } diff --git a/lib/base/configobject.cpp b/lib/base/configobject.cpp index 824ec2630..8fe176b31 100644 --- a/lib/base/configobject.cpp +++ b/lib/base/configobject.cpp @@ -506,17 +506,16 @@ void ConfigObject::DumpObjects(const String& filename, int attributeTypes) continue; 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); if (!update) continue; - persistentObject->Set("update", update); + Dictionary::Ptr persistentObject = new Dictionary({ + { "type", type->GetName() }, + { "name", object->GetName() }, + { "update", update } + }); String json = JsonEncode(persistentObject); @@ -717,13 +716,13 @@ Dictionary::Ptr ConfigObject::GetSourceLocation() const { DebugInfo di = GetDebugInfo(); - Dictionary::Ptr result = new Dictionary(); - result->Set("path", di.Path); - result->Set("first_line", di.FirstLine); - result->Set("first_column", di.FirstColumn); - result->Set("last_line", di.LastLine); - result->Set("last_column", di.LastColumn); - return result; + return new Dictionary({ + { "path", di.Path }, + { "first_line", di.FirstLine }, + { "first_column", di.FirstColumn }, + { "last_line", di.LastLine }, + { "last_column", di.LastColumn } + }); } NameComposer::~NameComposer() diff --git a/lib/base/datetime-script.cpp b/lib/base/datetime-script.cpp index 9c8f422c1..4a16a0aa2 100644 --- a/lib/base/datetime-script.cpp +++ b/lib/base/datetime-script.cpp @@ -35,12 +35,9 @@ static String DateTimeFormat(const String& format) Object::Ptr DateTime::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - prototype->Set("format", new Function("DateTime#format", DateTimeFormat, { "format" })); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "format", new Function("DateTime#format", DateTimeFormat, { "format" }) } + }); return prototype; } diff --git a/lib/base/dictionary-script.cpp b/lib/base/dictionary-script.cpp index ffa256f6b..a45afa826 100644 --- a/lib/base/dictionary-script.cpp +++ b/lib/base/dictionary-script.cpp @@ -71,41 +71,38 @@ static Array::Ptr DictionaryKeys() { ScriptFrame *vframe = ScriptFrame::GetCurrentFrame(); Dictionary::Ptr self = static_cast(vframe->Self); - Array::Ptr keys = new Array(); + ArrayData keys; ObjectLock olock(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() { ScriptFrame *vframe = ScriptFrame::GetCurrentFrame(); Dictionary::Ptr self = static_cast(vframe->Self); - Array::Ptr keys = new Array(); + ArrayData values; ObjectLock olock(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() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - prototype->Set("len", new Function("Dictionary#len", DictionaryLen, {}, true)); - prototype->Set("set", new Function("Dictionary#set", DictionarySet, { "key", "value" })); - prototype->Set("get", new Function("Dictionary#get", DictionaryGet, { "key" })); - prototype->Set("remove", new Function("Dictionary#remove", DictionaryRemove, { "key" })); - prototype->Set("contains", new Function("Dictionary#contains", DictionaryContains, { "key" }, 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)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "len", new Function("Dictionary#len", DictionaryLen, {}, true) }, + { "set", new Function("Dictionary#set", DictionarySet, { "key", "value" }) }, + { "get", new Function("Dictionary#get", DictionaryGet, { "key" }) }, + { "remove", new Function("Dictionary#remove", DictionaryRemove, { "key" }) }, + { "contains", new Function("Dictionary#contains", DictionaryContains, { "key" }, true) }, + { "shallow_clone", new Function("Dictionary#shallow_clone", DictionaryShallowClone, {}, true) }, + { "keys", new Function("Dictionary#keys", DictionaryKeys, {}, true) }, + { "values", new Function("Dictionary#values", DictionaryValues, {}, true) } + }); return prototype; } diff --git a/lib/base/dictionary.cpp b/lib/base/dictionary.cpp index da80220b1..d4ac10b50 100644 --- a/lib/base/dictionary.cpp +++ b/lib/base/dictionary.cpp @@ -29,6 +29,22 @@ template class std::map; 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 init) + : m_Data(init) +{ } + /** * Retrieves a value from a dictionary. * @@ -202,14 +218,19 @@ Dictionary::Ptr Dictionary::ShallowClone() const */ Object::Ptr Dictionary::Clone() const { - Dictionary::Ptr dict = new Dictionary(); + DictionaryData dict; - ObjectLock olock(this); - for (const Dictionary::Pair& kv : m_Data) { - dict->Set(kv.first, kv.second.Clone()); + { + ObjectLock olock(this); + + dict.reserve(GetLength()); + + for (const Dictionary::Pair& kv : m_Data) { + dict.emplace_back(kv.first, kv.second.Clone()); + } } - return dict; + return new Dictionary(std::move(dict)); } /** diff --git a/lib/base/dictionary.hpp b/lib/base/dictionary.hpp index c1bd42c6f..7854573a6 100644 --- a/lib/base/dictionary.hpp +++ b/lib/base/dictionary.hpp @@ -30,6 +30,8 @@ namespace icinga { +typedef std::vector > DictionaryData; + /** * A container that holds key-value pairs. * @@ -49,6 +51,11 @@ public: typedef std::map::value_type Pair; + Dictionary() = default; + Dictionary(const DictionaryData& other); + Dictionary(DictionaryData&& other); + Dictionary(std::initializer_list init); + Value Get(const String& key) const; bool Get(const String& key, Value *result) const; void Set(const String& key, Value value); diff --git a/lib/base/filelogger.cpp b/lib/base/filelogger.cpp index 3216ae1ec..b1c8b0ad1 100644 --- a/lib/base/filelogger.cpp +++ b/lib/base/filelogger.cpp @@ -32,13 +32,13 @@ REGISTER_STATSFUNCTION(FileLogger, &FileLogger::StatsFunc); void FileLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) { - Dictionary::Ptr nodes = new Dictionary(); + DictionaryData nodes; for (const FileLogger::Ptr& filelogger : ConfigType::GetObjectsByType()) { - 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))); } /** diff --git a/lib/base/function-script.cpp b/lib/base/function-script.cpp index 7f8a0aeec..757eb4e2d 100644 --- a/lib/base/function-script.cpp +++ b/lib/base/function-script.cpp @@ -55,13 +55,10 @@ static Value FunctionCallV(const Value& thisArg, const Array::Ptr& args) Object::Ptr Function::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - prototype->Set("call", new Function("Function#call", FunctionCall)); - prototype->Set("callv", new Function("Function#callv", FunctionCallV)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "call", new Function("Function#call", FunctionCall) }, + { "callv", new Function("Function#callv", FunctionCallV) } + }); return prototype; } diff --git a/lib/base/json-script.cpp b/lib/base/json-script.cpp index cf598490e..9df6ee783 100644 --- a/lib/base/json-script.cpp +++ b/lib/base/json-script.cpp @@ -32,11 +32,11 @@ static String JsonEncodeShim(const Value& value) } INITIALIZE_ONCE([]() { - Dictionary::Ptr jsonObj = new Dictionary(); - - /* Methods */ - jsonObj->Set("encode", new Function("Json#encode", JsonEncodeShim, { "value" }, true)); - jsonObj->Set("decode", new Function("Json#decode", JsonDecode, { "value" }, true)); + Dictionary::Ptr jsonObj = new Dictionary({ + /* Methods */ + { "encode", new Function("Json#encode", JsonEncodeShim, { "value" }, true) }, + { "decode", new Function("Json#decode", JsonDecode, { "value" }, true) } + }); ScriptGlobal::Set("Json", jsonObj); }); diff --git a/lib/base/math-script.cpp b/lib/base/math-script.cpp index f6f05ece8..dab48a5df 100644 --- a/lib/base/math-script.cpp +++ b/lib/base/math-script.cpp @@ -158,40 +158,40 @@ static double MathSign(double x) } INITIALIZE_ONCE([]() { - Dictionary::Ptr mathObj = new Dictionary(); - - /* Constants */ - mathObj->Set("E", 2.71828182845904523536); - mathObj->Set("LN2", 0.693147180559945309417); - mathObj->Set("LN10", 2.30258509299404568402); - mathObj->Set("LOG2E", 1.44269504088896340736); - mathObj->Set("LOG10E", 0.434294481903251827651); - mathObj->Set("PI", 3.14159265358979323846); - mathObj->Set("SQRT1_2", 0.707106781186547524401); - mathObj->Set("SQRT2", 1.41421356237309504880); - - /* Methods */ - mathObj->Set("abs", new Function("Math#abs", MathAbs, { "x" }, true)); - mathObj->Set("acos", new Function("Math#acos", MathAcos, { "x" }, true)); - mathObj->Set("asin", new Function("Math#asin", MathAsin, { "x" }, true)); - mathObj->Set("atan", new Function("Math#atan", MathAtan, { "x" }, true)); - mathObj->Set("atan2", new Function("Math#atan2", MathAtan2, { "x", "y" }, true)); - mathObj->Set("ceil", new Function("Math#ceil", MathCeil, { "x" }, true)); - mathObj->Set("cos", new Function("Math#cos", MathCos, { "x" }, true)); - mathObj->Set("exp", new Function("Math#exp", MathExp, { "x" }, true)); - mathObj->Set("floor", new Function("Math#floor", MathFloor, { "x" }, true)); - mathObj->Set("log", new Function("Math#log", MathLog, { "x" }, true)); - mathObj->Set("max", new Function("Math#max", MathMax, {}, true)); - mathObj->Set("min", new Function("Math#min", MathMin, {}, true)); - mathObj->Set("pow", new Function("Math#pow", MathPow, { "x", "y" }, true)); - mathObj->Set("random", new Function("Math#random", MathRandom, {}, true)); - mathObj->Set("round", new Function("Math#round", MathRound, { "x" }, true)); - mathObj->Set("sin", new Function("Math#sin", MathSin, { "x" }, true)); - mathObj->Set("sqrt", new Function("Math#sqrt", MathSqrt, { "x" }, true)); - mathObj->Set("tan", new Function("Math#tan", MathTan, { "x" }, true)); - mathObj->Set("isnan", new Function("Math#isnan", MathIsnan, { "x" }, true)); - mathObj->Set("isinf", new Function("Math#isinf", MathIsinf, { "x" }, true)); - mathObj->Set("sign", new Function("Math#sign", MathSign, { "x" }, true)); + Dictionary::Ptr mathObj = new Dictionary({ + /* Constants */ + { "E", 2.71828182845904523536 }, + { "LN2", 0.693147180559945309417 }, + { "LN10", 2.30258509299404568402 }, + { "LOG2E", 1.44269504088896340736 }, + { "LOG10E", 0.434294481903251827651 }, + { "PI", 3.14159265358979323846 }, + { "SQRT1_2", 0.707106781186547524401 }, + { "SQRT2", 1.41421356237309504880 }, + + /* Methods */ + { "abs", new Function("Math#abs", MathAbs, { "x" }, true) }, + { "acos", new Function("Math#acos", MathAcos, { "x" }, true) }, + { "asin", new Function("Math#asin", MathAsin, { "x" }, true) }, + { "atan", new Function("Math#atan", MathAtan, { "x" }, true) }, + { "atan2", new Function("Math#atan2", MathAtan2, { "x", "y" }, true) }, + { "ceil", new Function("Math#ceil", MathCeil, { "x" }, true) }, + { "cos", new Function("Math#cos", MathCos, { "x" }, true) }, + { "exp", new Function("Math#exp", MathExp, { "x" }, true) }, + { "floor", new Function("Math#floor", MathFloor, { "x" }, true) }, + { "log", new Function("Math#log", MathLog, { "x" }, true) }, + { "max", new Function("Math#max", MathMax, {}, true) }, + { "min", new Function("Math#min", MathMin, {}, true) }, + { "pow", new Function("Math#pow", MathPow, { "x", "y" }, true) }, + { "random", new Function("Math#random", MathRandom, {}, true) }, + { "round", new Function("Math#round", MathRound, { "x" }, true) }, + { "sin", new Function("Math#sin", MathSin, { "x" }, true) }, + { "sqrt", new Function("Math#sqrt", MathSqrt, { "x" }, true) }, + { "tan", new Function("Math#tan", MathTan, { "x" }, true) }, + { "isnan", new Function("Math#isnan", MathIsnan, { "x" }, true) }, + { "isinf", new Function("Math#isinf", MathIsinf, { "x" }, true) }, + { "sign", new Function("Math#sign", MathSign, { "x" }, true) } + }); ScriptGlobal::Set("Math", mathObj); }); diff --git a/lib/base/number-script.cpp b/lib/base/number-script.cpp index 8458f8d21..8ec9ae554 100644 --- a/lib/base/number-script.cpp +++ b/lib/base/number-script.cpp @@ -33,12 +33,9 @@ static String NumberToString() Object::Ptr Number::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - prototype->Set("to_string", new Function("Number#to_string", NumberToString, {}, true)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "to_string", new Function("Number#to_string", NumberToString, {}, true) } + }); return prototype; } diff --git a/lib/base/object-script.cpp b/lib/base/object-script.cpp index 3adf20d00..8c42314d6 100644 --- a/lib/base/object-script.cpp +++ b/lib/base/object-script.cpp @@ -48,14 +48,11 @@ static Object::Ptr ObjectClone() Object::Ptr Object::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - 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)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "to_string", new Function("Object#to_string", ObjectToString, {}, true) }, + { "notify_attribute", new Function("Object#notify_attribute", ObjectNotifyAttribute, { "attribute" }, false) }, + { "clone", new Function("Object#clone", ObjectClone, {}, true) } + }); return prototype; } diff --git a/lib/base/process.cpp b/lib/base/process.cpp index 4f87ab3b5..d5d3d69d2 100644 --- a/lib/base/process.cpp +++ b/lib/base/process.cpp @@ -201,10 +201,11 @@ static Value ProcessSpawnImpl(struct msghdr *msgh, const Dictionary::Ptr& reques delete[] envp; - Dictionary::Ptr response = new Dictionary(); - response->Set("rc", pid); - if (errorCode) - response->Set("errno", errorCode); + Dictionary::Ptr response = new Dictionary({ + { "rc", pid }, + { "errno", errorCode } + }); + return response; } @@ -217,8 +218,9 @@ static Value ProcessKillImpl(struct msghdr *msgh, const Dictionary::Ptr& request kill(pid, signum); int error = errno; - Dictionary::Ptr response = new Dictionary(); - response->Set("errno", error); + Dictionary::Ptr response = new Dictionary({ + { "errno", error } + }); return response; } @@ -230,9 +232,10 @@ static Value ProcessWaitPIDImpl(struct msghdr *msgh, const Dictionary::Ptr& requ int status; int rc = waitpid(pid, &status, 0); - Dictionary::Ptr response = new Dictionary(); - response->Set("status", status); - response->Set("rc", rc); + Dictionary::Ptr response = new Dictionary({ + { "status", status }, + { "rc", rc } + }); return response; } @@ -375,11 +378,12 @@ static void StartSpawnProcessHelper() static pid_t ProcessSpawn(const std::vector& arguments, const Dictionary::Ptr& extraEnvironment, bool adjustPriority, int fds[3]) { - Dictionary::Ptr request = new Dictionary(); - request->Set("command", "spawn"); - request->Set("arguments", Array::FromVector(arguments)); - request->Set("extraEnvironment", extraEnvironment); - request->Set("adjustPriority", adjustPriority); + Dictionary::Ptr request = new Dictionary({ + { "command", "spawn" }, + { "arguments", Array::FromVector(arguments) }, + { "extraEnvironment", extraEnvironment }, + { "adjustPriority", adjustPriority } + }); String jrequest = JsonEncode(request); size_t length = jrequest.GetLength(); @@ -435,10 +439,11 @@ send_message: static int ProcessKill(pid_t pid, int signum) { - Dictionary::Ptr request = new Dictionary(); - request->Set("command", "kill"); - request->Set("pid", pid); - request->Set("signum", signum); + Dictionary::Ptr request = new Dictionary({ + { "command", "kill" }, + { "pid", pid }, + { "signum", signum } + }); String jrequest = JsonEncode(request); size_t length = jrequest.GetLength(); @@ -467,9 +472,10 @@ send_message: static int ProcessWaitPID(pid_t pid, int *status) { - Dictionary::Ptr request = new Dictionary(); - request->Set("command", "waitpid"); - request->Set("pid", pid); + Dictionary::Ptr request = new Dictionary({ + { "command", "waitpid" }, + { "pid", pid } + }); String jrequest = JsonEncode(request); size_t length = jrequest.GetLength(); diff --git a/lib/base/scriptglobal.cpp b/lib/base/scriptglobal.cpp index dccaf758c..dc7bb3296 100644 --- a/lib/base/scriptglobal.cpp +++ b/lib/base/scriptglobal.cpp @@ -105,16 +105,15 @@ void ScriptGlobal::WriteToFile(const String& filename) ObjectLock olock(m_Globals); for (const Dictionary::Pair& kv : m_Globals) { - Dictionary::Ptr persistentVariable = new Dictionary(); - - persistentVariable->Set("name", kv.first); - Value value = kv.second; if (value.IsObject()) value = Convert::ToString(value); - persistentVariable->Set("value", value); + Dictionary::Ptr persistentVariable = new Dictionary({ + { "name", kv.first }, + { "value", value } + }); String json = JsonEncode(persistentVariable); diff --git a/lib/base/scriptutils.cpp b/lib/base/scriptutils.cpp index 6dd27b464..cbedd9f97 100644 --- a/lib/base/scriptutils.cpp +++ b/lib/base/scriptutils.cpp @@ -267,12 +267,7 @@ Array::Ptr ScriptUtils::Union(const std::vector& arguments) } } - Array::Ptr result = new Array(); - for (const Value& value : values) { - result->Add(value); - } - - return result; + return Array::FromSet(values); } Array::Ptr ScriptUtils::Intersection(const std::vector& arguments) @@ -370,16 +365,16 @@ Array::Ptr ScriptUtils::Range(const std::vector& arguments) BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid number of arguments for range()")); } - Array::Ptr result = new Array(); + ArrayData result; if ((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) - result->Add(i); + result.push_back(i); - return result; + return new Array(std::move(result)); } 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 result = new Array(); + ArrayData result; if (dict) { ObjectLock olock(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) @@ -428,12 +423,12 @@ Array::Ptr ScriptUtils::GetObjects(const Type::Ptr& type) if (!ctype) 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()) - result->Add(object); + result.push_back(object); - return result; + return new Array(std::move(result)); } void ScriptUtils::Assert(const Value& arg) diff --git a/lib/base/serializer.cpp b/lib/base/serializer.cpp index 73ab6a356..7296ec3ce 100644 --- a/lib/base/serializer.cpp +++ b/lib/base/serializer.cpp @@ -26,28 +26,32 @@ using namespace icinga; static Array::Ptr SerializeArray(const Array::Ptr& input, int attributeTypes) { - Array::Ptr result = new Array(); + ArrayData result; + + result.reserve(input->GetLength()); ObjectLock olock(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) { - Dictionary::Ptr result = new Dictionary(); + DictionaryData result; + + result.reserve(input->GetLength()); ObjectLock olock(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) @@ -57,7 +61,8 @@ static Object::Ptr SerializeObject(const Object::Ptr& input, int attributeTypes) if (!type) return nullptr; - Dictionary::Ptr fields = new Dictionary(); + DictionaryData fields; + fields.reserve(type->GetFieldCount() + 1); for (int i = 0; i < type->GetFieldCount(); 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) 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) { - Array::Ptr result = new Array(); + ArrayData result; + + result.reserve(input->GetLength()); ObjectLock olock(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) { - Dictionary::Ptr result = new Dictionary(); + DictionaryData result; + + result.reserve(input->GetLength()); ObjectLock olock(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) diff --git a/lib/base/string-script.cpp b/lib/base/string-script.cpp index ee975abff..83cc9c3fa 100644 --- a/lib/base/string-script.cpp +++ b/lib/base/string-script.cpp @@ -78,11 +78,7 @@ static Array::Ptr StringSplit(const String& delims) std::vector tokens; boost::algorithm::split(tokens, self, boost::is_any_of(delims)); - Array::Ptr result = new Array(); - for (const String& token : tokens) { - result->Add(token); - } - return result; + return Array::FromVector(tokens); } static int StringFind(const std::vector& args) @@ -141,22 +137,19 @@ static String StringTrim() Object::Ptr String::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - prototype->Set("len", new Function("String#len", StringLen, {}, true)); - prototype->Set("to_string", new Function("String#to_string", StringToString, {}, true)); - prototype->Set("substr", new Function("String#substr", StringSubstr, { "start", "len" }, true)); - prototype->Set("upper", new Function("String#upper", StringUpper, {}, true)); - prototype->Set("lower", new Function("String#lower", StringLower, {}, true)); - prototype->Set("split", new Function("String#split", StringSplit, { "delims" }, true)); - prototype->Set("find", new Function("String#find", StringFind, { "str", "start" }, true)); - prototype->Set("contains", new Function("String#contains", StringContains, { "str" }, 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)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "len", new Function("String#len", StringLen, {}, true) }, + { "to_string", new Function("String#to_string", StringToString, {}, true) }, + { "substr", new Function("String#substr", StringSubstr, { "start", "len" }, true) }, + { "upper", new Function("String#upper", StringUpper, {}, true) }, + { "lower", new Function("String#lower", StringLower, {}, true) }, + { "split", new Function("String#split", StringSplit, { "delims" }, true) }, + { "find", new Function("String#find", StringFind, { "str", "start" }, true) }, + { "contains", new Function("String#contains", StringContains, { "str" }, true) }, + { "replace", new Function("String#replace", StringReplace, { "search", "replacement" }, true) }, + { "reverse", new Function("String#reverse", StringReverse, {}, true) }, + { "trim", new Function("String#trim", StringTrim, {}, true) } + }); return prototype; } diff --git a/lib/base/sysloglogger.cpp b/lib/base/sysloglogger.cpp index fb719997c..e7e17a92f 100644 --- a/lib/base/sysloglogger.cpp +++ b/lib/base/sysloglogger.cpp @@ -80,13 +80,13 @@ void SyslogLogger::StaticInitialize() void SyslogLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) { - Dictionary::Ptr nodes = new Dictionary(); + DictionaryData nodes; for (const SyslogLogger::Ptr& sysloglogger : ConfigType::GetObjectsByType()) { - 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() diff --git a/lib/base/typetype-script.cpp b/lib/base/typetype-script.cpp index d47a76f27..0a6cfbc1d 100644 --- a/lib/base/typetype-script.cpp +++ b/lib/base/typetype-script.cpp @@ -42,12 +42,9 @@ static void TypeRegisterAttributeHandler(const String& fieldName, const Function Object::Ptr TypeType::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - prototype->Set("register_attribute_handler", new Function("Type#register_attribute_handler", TypeRegisterAttributeHandler, { "field", "callback" }, false)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "register_attribute_handler", new Function("Type#register_attribute_handler", TypeRegisterAttributeHandler, { "field", "callback" }, false) } + }); return prototype; } diff --git a/lib/base/value-operators.cpp b/lib/base/value-operators.cpp index 78fd0757b..9ce5a2d24 100644 --- a/lib/base/value-operators.cpp +++ b/lib/base/value-operators.cpp @@ -285,7 +285,7 @@ Value icinga::operator-(const Value& lhs, const Value& rhs) if (lhs.IsEmpty()) return new Array(); - Array::Ptr result = new Array(); + ArrayData result; Array::Ptr left = lhs; Array::Ptr right = rhs; @@ -303,10 +303,10 @@ Value icinga::operator-(const Value& lhs, const Value& rhs) if (found) continue; - result->Add(lv); + result.push_back(lv); } - return result; + return new Array(std::move(result)); } else BOOST_THROW_EXCEPTION(std::invalid_argument("Operator - cannot be applied to values of type '" + lhs.GetTypeName() + "' and '" + rhs.GetTypeName() + "'")); } diff --git a/lib/checker/checkercomponent.cpp b/lib/checker/checkercomponent.cpp index bb30b6836..f2027e9ea 100644 --- a/lib/checker/checkercomponent.cpp +++ b/lib/checker/checkercomponent.cpp @@ -39,24 +39,23 @@ REGISTER_STATSFUNCTION(CheckerComponent, &CheckerComponent::StatsFunc); 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()) { unsigned long idle = checker->GetIdleCheckables(); unsigned long pending = checker->GetPendingCheckables(); - Dictionary::Ptr stats = new Dictionary(); - stats->Set("idle", idle); - stats->Set("pending", pending); - - nodes->Set(checker->GetName(), stats); + nodes.emplace_back(checker->GetName(), new Dictionary({ + { "idle", idle }, + { "pending", pending } + })); String perfdata_prefix = "checkercomponent_" + checker->GetName() + "_"; perfdata->Add(new PerfdataValue(perfdata_prefix + "idle", Convert::ToDouble(idle))); 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() diff --git a/lib/cli/consolecommand.cpp b/lib/cli/consolecommand.cpp index 9225fd6d2..c102452dc 100644 --- a/lib/cli/consolecommand.cpp +++ b/lib/cli/consolecommand.cpp @@ -86,8 +86,9 @@ extern "C" void dbg_eval_with_value(const Value& value, const char *text) try { ScriptFrame frame(true); - frame.Locals = new Dictionary(); - frame.Locals->Set("arg", value); + frame.Locals = new Dictionary({ + { "arg", value } + }); expr = ConfigCompiler::CompileText("", text); Value result = Serialize(expr->Evaluate(frame), 0); dbg_inspect_value(result); @@ -102,8 +103,9 @@ extern "C" void dbg_eval_with_object(Object *object, const char *text) try { ScriptFrame frame(true); - frame.Locals = new Dictionary(); - frame.Locals->Set("arg", object); + frame.Locals = new Dictionary({ + { "arg", object } + }); expr = ConfigCompiler::CompileText("", text); Value result = Serialize(expr->Evaluate(frame), 0); dbg_inspect_value(result); diff --git a/lib/cli/nodeutility.cpp b/lib/cli/nodeutility.cpp index 1a028f9f1..0157d6d23 100644 --- a/lib/cli/nodeutility.cpp +++ b/lib/cli/nodeutility.cpp @@ -56,13 +56,11 @@ int NodeUtility::GenerateNodeIcingaConfig(const std::vector& endpoi { Array::Ptr my_config = new Array(); - Dictionary::Ptr my_master_zone = new Dictionary(); Array::Ptr my_master_zone_members = new Array(); String master_zone_name = "master"; //TODO: Find a better name. for (const std::string& endpoint : endpoints) { - /* extract all --endpoint arguments and store host,port info */ std::vector tokens; boost::algorithm::split(tokens, endpoint, boost::is_any_of(",")); @@ -94,42 +92,33 @@ int NodeUtility::GenerateNodeIcingaConfig(const std::vector& endpoi } /* add the master zone to the config */ - my_master_zone->Set("__name", master_zone_name); - my_master_zone->Set("__type", "Zone"); - my_master_zone->Set("endpoints", my_master_zone_members); - - my_config->Add(my_master_zone); + my_config->Add(new Dictionary({ + { "__name", master_zone_name }, + { "__type", "Zone" }, + { "endpoints", my_master_zone_members } + })); /* store the local generated node configuration */ - Dictionary::Ptr my_endpoint = new Dictionary(); - Dictionary::Ptr my_zone = new Dictionary(); - - my_endpoint->Set("__name", new ConfigIdentifier("NodeName")); - my_endpoint->Set("__type", "Endpoint"); - - Array::Ptr my_zone_members = new Array(); - my_zone_members->Add(new ConfigIdentifier("NodeName")); - - 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); + my_config->Add(new Dictionary({ + { "__name", new ConfigIdentifier("NodeName") }, + { "__type", "Endpoint" } + })); + + my_config->Add(new Dictionary({ + { "__name", new ConfigIdentifier("ZoneName") }, + { "__type", "Zone" }, + { "parent", master_zone_name }, //set the master zone as parent + { "endpoints", new Array({ new ConfigIdentifier("ZoneName") }) } + })); for (const String& globalzone : globalZones) { - Dictionary::Ptr myGlobalZone = new Dictionary(); - - myGlobalZone->Set("__name", globalzone); - myGlobalZone->Set("__type", "Zone"); - myGlobalZone->Set("global", true); - - my_config->Add(myGlobalZone); + my_config->Add(new Dictionary({ + { "__name", globalzone }, + { "__type", "Zone" }, + { "global", true } + })); } - /* store the local config */ - my_config->Add(my_endpoint); - my_config->Add(my_zone); - /* write the newly generated configuration */ String zones_path = Application::GetSysconfDir() + "/icinga2/zones.conf"; @@ -143,32 +132,23 @@ int NodeUtility::GenerateNodeMasterIcingaConfig(const std::vector& globa Array::Ptr my_config = new Array(); /* store the local generated node master configuration */ - Dictionary::Ptr my_master_endpoint = new Dictionary(); - Dictionary::Ptr my_master_zone = new Dictionary(); - - Array::Ptr my_master_zone_members = new Array(); - - my_master_endpoint->Set("__name", new ConfigIdentifier("NodeName")); - my_master_endpoint->Set("__type", "Endpoint"); + my_config->Add(new Dictionary({ + { "__name", new ConfigIdentifier("NodeName") }, + { "__type", "Endpoint" } + })); - 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); + my_config->Add(new Dictionary({ + { "__name", new ConfigIdentifier("ZoneName") }, + { "__type", "Zone" }, + { "endpoints", new Array({ new ConfigIdentifier("NodeName") }) } + })); for (const String& globalzone : globalZones) { - Dictionary::Ptr myGlobalZone = new Dictionary(); - - myGlobalZone->Set("__name", globalzone); - myGlobalZone->Set("__type", "Zone"); - myGlobalZone->Set("global", true); - - my_config->Add(myGlobalZone); + my_config->Add(new Dictionary({ + { "__name", globalzone }, + { "__type", "Zone" }, + { "global", true } + })); } /* write the newly generated configuration */ diff --git a/lib/compat/checkresultreader.cpp b/lib/compat/checkresultreader.cpp index 40bcbad06..01e35dbd8 100644 --- a/lib/compat/checkresultreader.cpp +++ b/lib/compat/checkresultreader.cpp @@ -42,13 +42,13 @@ REGISTER_STATSFUNCTION(CheckResultReader, &CheckResultReader::StatsFunc); void CheckResultReader::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) { - Dictionary::Ptr nodes = new Dictionary(); + DictionaryData nodes; for (const CheckResultReader::Ptr& checkresultreader : ConfigType::GetObjectsByType()) { - 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))); } /** diff --git a/lib/compat/compatlogger.cpp b/lib/compat/compatlogger.cpp index 253a557e2..58b97af69 100644 --- a/lib/compat/compatlogger.cpp +++ b/lib/compat/compatlogger.cpp @@ -44,13 +44,13 @@ REGISTER_STATSFUNCTION(CompatLogger, &CompatLogger::StatsFunc); 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()) { - 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))); } /** diff --git a/lib/compat/externalcommandlistener.cpp b/lib/compat/externalcommandlistener.cpp index 66452c2d4..5843bfd32 100644 --- a/lib/compat/externalcommandlistener.cpp +++ b/lib/compat/externalcommandlistener.cpp @@ -34,13 +34,13 @@ REGISTER_STATSFUNCTION(ExternalCommandListener, &ExternalCommandListener::StatsF void ExternalCommandListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) { - Dictionary::Ptr nodes = new Dictionary(); + DictionaryData nodes; for (const ExternalCommandListener::Ptr& externalcommandlistener : ConfigType::GetObjectsByType()) { - 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))); } /** diff --git a/lib/compat/statusdatawriter.cpp b/lib/compat/statusdatawriter.cpp index f81a8d5ef..90b8ef131 100644 --- a/lib/compat/statusdatawriter.cpp +++ b/lib/compat/statusdatawriter.cpp @@ -52,13 +52,13 @@ REGISTER_STATSFUNCTION(StatusDataWriter, &StatusDataWriter::StatsFunc); void StatusDataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) { - Dictionary::Ptr nodes = new Dictionary(); + DictionaryData nodes; for (const StatusDataWriter::Ptr& statusdatawriter : ConfigType::GetObjectsByType()) { - 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))); } /** diff --git a/lib/config/configitem.cpp b/lib/config/configitem.cpp index e1b9da781..1f125be44 100644 --- a/lib/config/configitem.cpp +++ b/lib/config/configitem.cpp @@ -288,26 +288,25 @@ ConfigObject::Ptr ConfigItem::Commit(bool discard) throw; } - Dictionary::Ptr persistentItem = new Dictionary(); - - persistentItem->Set("type", GetType()->GetName()); - persistentItem->Set("name", GetName()); - persistentItem->Set("properties", Serialize(dobj, FAConfig)); - persistentItem->Set("debug_hints", dhint); + 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, + }) } + }); - 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); + dhint.reset(); ConfigCompilerContext::GetInstance()->WriteObject(persistentItem); persistentItem.reset(); - dhint.reset(); - dobj->Register(); m_Object = dobj; diff --git a/lib/config/configitembuilder.cpp b/lib/config/configitembuilder.cpp index e37430dea..d81b595d2 100644 --- a/lib/config/configitembuilder.cpp +++ b/lib/config/configitembuilder.cpp @@ -103,8 +103,7 @@ ConfigItem::Ptr ConfigItemBuilder::Compile() std::vector > exprs; - Array::Ptr templateArray = new Array(); - templateArray->Add(m_Name); + Array::Ptr templateArray = new Array({ m_Name }); exprs.emplace_back(new SetExpression(MakeIndexer(ScopeThis, "templates"), OpSetAdd, std::unique_ptr(new LiteralExpression(templateArray)), m_DebugInfo)); diff --git a/lib/config/expression.cpp b/lib/config/expression.cpp index f355509e5..938deb69b 100644 --- a/lib/config/expression.cpp +++ b/lib/config/expression.cpp @@ -461,17 +461,17 @@ ExpressionResult FunctionCallExpression::DoEvaluate(ScriptFrame& frame, DebugHin ExpressionResult ArrayExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const { - Array::Ptr result = new Array(); - result->Reserve(m_Expressions.size()); + ArrayData result; + result.reserve(m_Expressions.size()); for (const auto& aexpr : m_Expressions) { ExpressionResult element = aexpr->Evaluate(frame); 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 diff --git a/lib/config/vmops.hpp b/lib/config/vmops.hpp index 68b4b663b..503381730 100644 --- a/lib/config/vmops.hpp +++ b/lib/config/vmops.hpp @@ -255,17 +255,15 @@ public: private: static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, const std::map >& closedVars) { - Dictionary::Ptr locals; + if (closedVars.empty()) + return nullptr; - if (!closedVars.empty()) { - locals = new Dictionary(); + DictionaryData locals; - for (const auto& cvar : closedVars) { - locals->Set(cvar.first, cvar.second->Evaluate(frame)); - } - } + for (const auto& cvar : closedVars) + locals.emplace_back(cvar.first, cvar.second->Evaluate(frame)); - return locals; + return new Dictionary(std::move(locals)); } }; diff --git a/lib/db_ido/commanddbobject.cpp b/lib/db_ido/commanddbobject.cpp index b770a0b62..b097bed33 100644 --- a/lib/db_ido/commanddbobject.cpp +++ b/lib/db_ido/commanddbobject.cpp @@ -35,12 +35,11 @@ CommandDbObject::CommandDbObject(const DbType::Ptr& type, const String& name1, c Dictionary::Ptr CommandDbObject::GetConfigFields() const { - Dictionary::Ptr fields = new Dictionary(); Command::Ptr command = static_pointer_cast(GetObject()); - fields->Set("command_line", CompatUtility::GetCommandLine(command)); - - return fields; + return new Dictionary({ + { "command_line", CompatUtility::GetCommandLine(command) } + }); } Dictionary::Ptr CommandDbObject::GetStatusFields() const diff --git a/lib/db_ido/dbconnection.cpp b/lib/db_ido/dbconnection.cpp index 7202a2447..79d058614 100644 --- a/lib/db_ido/dbconnection.cpp +++ b/lib/db_ido/dbconnection.cpp @@ -109,12 +109,14 @@ void DbConnection::Pause() query1.IdColumn = "programstatus_id"; query1.Type = DbQueryUpdate; query1.Category = DbCatProgramStatus; - 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.Fields = new Dictionary(); - query1.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query1.Fields->Set("program_end_time", DbValue::FromTimestamp(Utility::GetTime())); + query1.Fields = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "program_end_time", DbValue::FromTimestamp(Utility::GetTime()) } + }); query1.Priority = PriorityHigh; @@ -137,10 +139,11 @@ void DbConnection::InsertRuntimeVariable(const String& key, const Value& value) query.Table = "runtimevariables"; query.Type = DbQueryInsert; query.Category = DbCatProgramStatus; - query.Fields = new Dictionary(); - query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query.Fields->Set("varname", key); - query.Fields->Set("varvalue", value); + query.Fields = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "varname", key }, + { "varvalue", value } + }); DbObject::OnQuery(query); } @@ -157,26 +160,30 @@ void DbConnection::UpdateProgramStatus() query1.Type = DbQueryInsert | DbQueryUpdate; query1.Category = DbCatProgramStatus; - query1.Fields = new Dictionary(); - query1.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query1.Fields->Set("program_version", Application::GetAppVersion()); - query1.Fields->Set("status_update_time", DbValue::FromTimestamp(Utility::GetTime())); - query1.Fields->Set("program_start_time", DbValue::FromTimestamp(Application::GetStartTime())); - query1.Fields->Set("is_currently_running", 1); - query1.Fields->Set("endpoint_name", IcingaApplication::GetInstance()->GetNodeName()); - query1.Fields->Set("process_id", Utility::GetPid()); - query1.Fields->Set("daemon_mode", 1); - query1.Fields->Set("last_command_check", DbValue::FromTimestamp(Utility::GetTime())); - query1.Fields->Set("notifications_enabled", (IcingaApplication::GetInstance()->GetEnableNotifications() ? 1 : 0)); - query1.Fields->Set("active_host_checks_enabled", (IcingaApplication::GetInstance()->GetEnableHostChecks() ? 1 : 0)); - query1.Fields->Set("passive_host_checks_enabled", 1); - query1.Fields->Set("active_service_checks_enabled", (IcingaApplication::GetInstance()->GetEnableServiceChecks() ? 1 : 0)); - query1.Fields->Set("passive_service_checks_enabled", 1); - query1.Fields->Set("event_handlers_enabled", (IcingaApplication::GetInstance()->GetEnableEventHandlers() ? 1 : 0)); - query1.Fields->Set("flap_detection_enabled", (IcingaApplication::GetInstance()->GetEnableFlapping() ? 1 : 0)); - query1.Fields->Set("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.Fields = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "program_version", Application::GetAppVersion() }, + { "status_update_time", DbValue::FromTimestamp(Utility::GetTime()) }, + { "program_start_time", DbValue::FromTimestamp(Application::GetStartTime()) }, + { "is_currently_running", 1 }, + { "endpoint_name", IcingaApplication::GetInstance()->GetNodeName() }, + { "process_id", Utility::GetPid() }, + { "daemon_mode", 1 }, + { "last_command_check", DbValue::FromTimestamp(Utility::GetTime()) }, + { "notifications_enabled", (IcingaApplication::GetInstance()->GetEnableNotifications() ? 1 : 0) }, + { "active_host_checks_enabled", (IcingaApplication::GetInstance()->GetEnableHostChecks() ? 1 : 0) }, + { "passive_host_checks_enabled", 1 }, + { "active_service_checks_enabled", (IcingaApplication::GetInstance()->GetEnableServiceChecks() ? 1 : 0) }, + { "passive_service_checks_enabled", 1 }, + { "event_handlers_enabled", (IcingaApplication::GetInstance()->GetEnableEventHandlers() ? 1 : 0) }, + { "flap_detection_enabled", (IcingaApplication::GetInstance()->GetEnableFlapping() ? 1 : 0) }, + { "process_performance_data", (IcingaApplication::GetInstance()->GetEnablePerfdata() ? 1 : 0) } + }); + + query1.WhereCriteria = new Dictionary({ + { "instance_id", 0 } /* DbConnection class fills in real ID */ + }); + query1.Priority = PriorityHigh; queries.emplace_back(std::move(query1)); @@ -190,8 +197,9 @@ void DbConnection::UpdateProgramStatus() query3.Table = "runtimevariables"; query3.Type = DbQueryDelete; query3.Category = DbCatProgramStatus; - query3.WhereCriteria = new Dictionary(); - query3.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ + query3.WhereCriteria = new Dictionary({ + { "instance_id", 0 } /* DbConnection class fills in real ID */ + }); DbObject::OnQuery(query3); InsertRuntimeVariable("total_services", ConfigType::Get()->GetObjectCount()); diff --git a/lib/db_ido/dbconnection.ti b/lib/db_ido/dbconnection.ti index 4a2e2f488..2f6e60d02 100644 --- a/lib/db_ido/dbconnection.ti +++ b/lib/db_ido/dbconnection.ti @@ -37,20 +37,19 @@ abstract class DbConnection : ConfigObject [config] Array::Ptr categories { default {{{ - Array::Ptr cat = new Array(); - cat->Add("DbCatConfig"); - cat->Add("DbCatState"); - cat->Add("DbCatAcknowledgement"); - cat->Add("DbCatComment"); - cat->Add("DbCatDowntime"); - cat->Add("DbCatEventHandler"); - cat->Add("DbCatFlapping"); - cat->Add("DbCatNotification"); - cat->Add("DbCatProgramStatus"); - cat->Add("DbCatRetention"); - cat->Add("DbCatStateHistory"); - - return cat; + return new Array({ + "DbCatConfig", + "DbCatState", + "DbCatAcknowledgement", + "DbCatComment", + "DbCatDowntime", + "DbCatEventHandler", + "DbCatFlapping", + "DbCatNotification", + "DbCatProgramStatus", + "DbCatRetention", + "DbCatStateHistory" + }); }}} }; [no_user_view, no_user_modify] int categories_filter_real (CategoryFilter); diff --git a/lib/db_ido/dbevents.cpp b/lib/db_ido/dbevents.cpp index 1e5ec1bd2..97709793b 100644 --- a/lib/db_ido/dbevents.cpp +++ b/lib/db_ido/dbevents.cpp @@ -111,10 +111,9 @@ void DbEvents::NextCheckUpdatedHandler(const Checkable::Ptr& checkable) query1.StatusUpdate = true; query1.Object = DbObject::GetOrCreateByObject(checkable); - Dictionary::Ptr fields1 = new Dictionary(); - fields1->Set("next_check", DbValue::FromTimestamp(checkable->GetNextCheck())); - - query1.Fields = fields1; + query1.Fields = new Dictionary({ + { "next_check", DbValue::FromTimestamp(checkable->GetNextCheck()) } + }); DbObject::OnQuery(query1); } @@ -145,7 +144,11 @@ void DbEvents::FlappingChangedHandler(const Checkable::Ptr& checkable) fields1->Set("is_flapping", checkable->IsFlapping()); 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 */ DbObject::OnQuery(query1); @@ -176,12 +179,12 @@ void DbEvents::LastNotificationChangedHandler(const Notification::Ptr& notificat query1.StatusUpdate = true; query1.Object = DbObject::GetOrCreateByObject(checkable); - Dictionary::Ptr fields1 = new Dictionary(); - fields1->Set("last_notification", DbValue::FromTimestamp(now_bag.first)); - fields1->Set("next_notification", DbValue::FromTimestamp(timeBag.first)); - fields1->Set("current_notification_number", notification->GetNotificationNumber()); + query1.Fields = new Dictionary({ + { "last_notification", DbValue::FromTimestamp(now_bag.first) }, + { "next_notification", DbValue::FromTimestamp(timeBag.first) }, + { "current_notification_number", notification->GetNotificationNumber() } + }); - query1.Fields = fields1; query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ DbObject::OnQuery(query1); @@ -221,10 +224,10 @@ void DbEvents::ReachabilityChangedHandler(const Checkable::Ptr& checkable, const query1.StatusUpdate = true; query1.Object = DbObject::GetOrCreateByObject(child); - Dictionary::Ptr fields1 = new Dictionary(); - fields1->Set("is_reachable", is_reachable); + query1.Fields = new Dictionary({ + { "is_reachable", is_reachable } + }); - query1.Fields = fields1; query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ DbObject::OnQuery(query1); @@ -279,10 +282,10 @@ void DbEvents::EnableChangedHandlerInternal(const Checkable::Ptr& checkable, con query1.StatusUpdate = true; query1.Object = DbObject::GetOrCreateByObject(checkable); - Dictionary::Ptr fields1 = new Dictionary(); - fields1->Set(fieldName, enabled); + query1.Fields = new Dictionary({ + { fieldName, enabled } + }); - query1.Fields = fields1; query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ DbObject::OnQuery(query1); @@ -365,10 +368,11 @@ void DbEvents::AddCommentInternal(std::vector& queries, const Comment:: fields1->Set("session_token", 0); /* DbConnection class fills in real ID */ - query1.WhereCriteria = new Dictionary(); - query1.WhereCriteria->Set("object_id", checkable); - query1.WhereCriteria->Set("name", comment->GetName()); - query1.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(timeBag.first)); + query1.WhereCriteria = new Dictionary({ + { "object_id", checkable }, + { "name", comment->GetName() }, + { "entry_time", DbValue::FromTimestamp(timeBag.first) } + }); } else { query1.Table = "commenthistory"; query1.Type = DbQueryInsert; @@ -398,10 +402,12 @@ void DbEvents::RemoveCommentInternal(std::vector& queries, const Commen query1.Type = DbQueryDelete; query1.Category = DbCatComment; - query1.WhereCriteria = new Dictionary(); - query1.WhereCriteria->Set("object_id", checkable); - query1.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(timeBag.first)); - query1.WhereCriteria->Set("name", comment->GetName()); + query1.WhereCriteria = new Dictionary({ + { "object_id", checkable }, + { "entry_time", DbValue::FromTimestamp(timeBag.first) }, + { "name", comment->GetName() } + }); + queries.emplace_back(std::move(query1)); /* History - update deletion time for service/host */ @@ -412,15 +418,16 @@ void DbEvents::RemoveCommentInternal(std::vector& queries, const Commen query2.Type = DbQueryUpdate; query2.Category = DbCatComment; - Dictionary::Ptr fields2 = new Dictionary(); - fields2->Set("deletion_time", DbValue::FromTimestamp(timeBagNow.first)); - fields2->Set("deletion_time_usec", timeBagNow.second); - query2.Fields = fields2; + query2.Fields = new Dictionary({ + { "deletion_time", DbValue::FromTimestamp(timeBagNow.first) }, + { "deletion_time_usec", timeBagNow.second } + }); - query2.WhereCriteria = new Dictionary(); - query2.WhereCriteria->Set("object_id", checkable); - query2.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(timeBag.first)); - query2.WhereCriteria->Set("name", comment->GetName()); + query2.WhereCriteria = new Dictionary({ + { "object_id", checkable }, + { "entry_time", DbValue::FromTimestamp(timeBag.first) }, + { "name", comment->GetName() } + }); queries.emplace_back(std::move(query2)); } @@ -509,10 +516,11 @@ void DbEvents::AddDowntimeInternal(std::vector& queries, const Downtime fields1->Set("session_token", 0); /* DbConnection class fills in real ID */ - query1.WhereCriteria = new Dictionary(); - query1.WhereCriteria->Set("object_id", checkable); - query1.WhereCriteria->Set("name", downtime->GetName()); - query1.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(downtime->GetEntryTime())); + query1.WhereCriteria = new Dictionary({ + { "object_id", checkable }, + { "name", downtime->GetName() }, + { "entry_time", DbValue::FromTimestamp(downtime->GetEntryTime()) } + }); } else { query1.Table = "downtimehistory"; query1.Type = DbQueryInsert; @@ -599,13 +607,15 @@ void DbEvents::RemoveDowntimeInternal(std::vector& queries, const Downt fields3->Set("is_in_effect", 0); query3.Fields = fields3; - query3.WhereCriteria = new Dictionary(); - query3.WhereCriteria->Set("object_id", checkable); - query3.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(downtime->GetEntryTime())); - query3.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query3.WhereCriteria->Set("scheduled_start_time", DbValue::FromTimestamp(downtime->GetStartTime())); - query3.WhereCriteria->Set("scheduled_end_time", DbValue::FromTimestamp(downtime->GetEndTime())); - query3.WhereCriteria->Set("name", downtime->GetName()); + query3.WhereCriteria = new Dictionary({ + { "object_id", checkable }, + { "entry_time", DbValue::FromTimestamp(downtime->GetEntryTime()) }, + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "scheduled_start_time", DbValue::FromTimestamp(downtime->GetStartTime()) }, + { "scheduled_end_time", DbValue::FromTimestamp(downtime->GetEndTime()) }, + { "name", downtime->GetName() } + }); + queries.emplace_back(std::move(query3)); /* host/service status */ @@ -650,23 +660,24 @@ void DbEvents::TriggerDowntime(const Downtime::Ptr& downtime) query1.Type = DbQueryUpdate; query1.Category = DbCatDowntime; - Dictionary::Ptr fields1 = new Dictionary(); - fields1->Set("was_started", 1); - fields1->Set("actual_start_time", DbValue::FromTimestamp(timeBag.first)); - fields1->Set("actual_start_time_usec", timeBag.second); - fields1->Set("is_in_effect", (downtime->IsInEffect() ? 1 : 0)); - fields1->Set("trigger_time", DbValue::FromTimestamp(downtime->GetTriggerTime())); - fields1->Set("instance_id", 0); /* DbConnection class fills in real ID */ + query1.Fields = new Dictionary({ + { "was_started", 1 }, + { "actual_start_time", DbValue::FromTimestamp(timeBag.first) }, + { "actual_start_time_usec", timeBag.second }, + { "is_in_effect", (downtime->IsInEffect() ? 1 : 0) }, + { "trigger_time", DbValue::FromTimestamp(downtime->GetTriggerTime()) }, + { "instance_id", 0 } /* DbConnection class fills in real ID */ + }); + + query1.WhereCriteria = new Dictionary({ + { "object_id", checkable }, + { "entry_time", DbValue::FromTimestamp(downtime->GetEntryTime()) }, + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "scheduled_start_time", DbValue::FromTimestamp(downtime->GetStartTime()) }, + { "scheduled_end_time", DbValue::FromTimestamp(downtime->GetEndTime()) }, + { "name", downtime->GetName() } + }); - query1.WhereCriteria = new Dictionary(); - query1.WhereCriteria->Set("object_id", checkable); - query1.WhereCriteria->Set("entry_time", DbValue::FromTimestamp(downtime->GetEntryTime())); - query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query1.WhereCriteria->Set("scheduled_start_time", DbValue::FromTimestamp(downtime->GetStartTime())); - query1.WhereCriteria->Set("scheduled_end_time", DbValue::FromTimestamp(downtime->GetEndTime())); - query1.WhereCriteria->Set("name", downtime->GetName()); - - query1.Fields = fields1; DbObject::OnQuery(query1); /* 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.Category = DbCatDowntime; - Dictionary::Ptr fields3 = new Dictionary(); - fields3->Set("was_started", 1); - fields3->Set("is_in_effect", 1); - fields3->Set("actual_start_time", DbValue::FromTimestamp(timeBag.first)); - fields3->Set("actual_start_time_usec", timeBag.second); - fields3->Set("trigger_time", DbValue::FromTimestamp(downtime->GetTriggerTime())); - query3.Fields = fields3; + query3.Fields = new Dictionary({ + { "was_started", 1 }, + { "is_in_effect", 1 }, + { "actual_start_time", DbValue::FromTimestamp(timeBag.first) }, + { "actual_start_time_usec", timeBag.second }, + { "trigger_time", DbValue::FromTimestamp(downtime->GetTriggerTime()) } + }); query3.WhereCriteria = query1.WhereCriteria; @@ -708,10 +719,9 @@ void DbEvents::TriggerDowntime(const Downtime::Ptr& downtime) query4.StatusUpdate = true; query4.Object = DbObject::GetOrCreateByObject(checkable); - Dictionary::Ptr fields4 = new Dictionary(); - fields4->Set("scheduled_downtime_depth", checkable->GetDowntimeDepth()); - - query4.Fields = fields4; + query4.Fields = new Dictionary({ + { "scheduled_downtime_depth", checkable->GetDowntimeDepth() } + }); query4.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ DbObject::OnQuery(query4); @@ -801,11 +811,11 @@ void DbEvents::AddAcknowledgementInternal(const Checkable::Ptr& checkable, Ackno query1.StatusUpdate = true; query1.Object = DbObject::GetOrCreateByObject(checkable); - Dictionary::Ptr fields1 = new Dictionary(); - fields1->Set("acknowledgement_type", type); - fields1->Set("problem_has_been_acknowledged", add ? 1 : 0); + query1.Fields = new Dictionary({ + { "acknowledgement_type", type }, + { "problem_has_been_acknowledged", add ? 1 : 0 } + }); - query1.Fields = fields1; query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ DbObject::OnQuery(query1); @@ -873,17 +883,16 @@ void DbEvents::AddNotificationHistory(const Notification::Ptr& notification, con query2.Type = DbQueryInsert; query2.Category = DbCatNotification; - Dictionary::Ptr fields2 = new Dictionary(); - fields2->Set("contact_object_id", user); - fields2->Set("start_time", DbValue::FromTimestamp(timeBag.first)); - fields2->Set("start_time_usec", timeBag.second); - fields2->Set("end_time", DbValue::FromTimestamp(timeBag.first)); - fields2->Set("end_time_usec", timeBag.second); - - fields2->Set("notification_id", query1.NotificationInsertID); - fields2->Set("instance_id", 0); /* DbConnection class fills in real ID */ + query2.Fields = new Dictionary({ + { "contact_object_id", user }, + { "start_time", DbValue::FromTimestamp(timeBag.first) }, + { "start_time_usec", timeBag.second }, + { "end_time", DbValue::FromTimestamp(timeBag.first) }, + { "end_time_usec", timeBag.second }, + { "notification_id", query1.NotificationInsertID }, + { "instance_id", 0 } /* DbConnection class fills in real ID */ + }); - query2.Fields = fields2; queries.emplace_back(std::move(query2)); } diff --git a/lib/db_ido/dbobject.cpp b/lib/db_ido/dbobject.cpp index b9c14d528..9ab72ec1d 100644 --- a/lib/db_ido/dbobject.cpp +++ b/lib/db_ido/dbobject.cpp @@ -146,8 +146,9 @@ void DbObject::SendConfigUpdateHeavy(const Dictionary::Ptr& configFields) query.Fields->Set(GetType()->GetIDColumn(), object); query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ query.Fields->Set("config_type", 1); - query.WhereCriteria = new Dictionary(); - query.WhereCriteria->Set(GetType()->GetIDColumn(), object); + query.WhereCriteria = new Dictionary({ + { GetType()->GetIDColumn(), object } + }); query.Object = this; query.ConfigUpdate = true; OnQuery(query); @@ -189,8 +190,9 @@ void DbObject::SendStatusUpdate() query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ query.Fields->Set("status_update_time", DbValue::FromTimestamp(Utility::GetTime())); - query.WhereCriteria = new Dictionary(); - query.WhereCriteria->Set(GetType()->GetIDColumn(), GetObject()); + query.WhereCriteria = new Dictionary({ + { GetType()->GetIDColumn(), GetObject() } + }); query.Object = this; query.StatusUpdate = true; OnQuery(query); @@ -215,16 +217,18 @@ void DbObject::SendVarsConfigUpdateHeavy() query1.Table = "customvariables"; query1.Type = DbQueryDelete; query1.Category = DbCatConfig; - query1.WhereCriteria = new Dictionary(); - query1.WhereCriteria->Set("object_id", obj); + query1.WhereCriteria = new Dictionary({ + { "object_id", obj } + }); queries.emplace_back(std::move(query1)); DbQuery query2; query2.Table = "customvariablestatus"; query2.Type = DbQueryDelete; query2.Category = DbCatConfig; - query2.WhereCriteria = new Dictionary(); - query2.WhereCriteria->Set("object_id", obj); + query2.WhereCriteria = new Dictionary({ + { "object_id", obj } + }); queries.emplace_back(std::move(query2)); Dictionary::Ptr vars = custom_var_object->GetVars(); @@ -245,19 +249,18 @@ void DbObject::SendVarsConfigUpdateHeavy() } else 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; query3.Table = "customvariables"; query3.Type = DbQueryInsert; 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)); } } @@ -293,23 +296,25 @@ void DbObject::SendVarsStatusUpdate() } else 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; query.Table = "customvariablestatus"; query.Type = DbQueryInsert | DbQueryUpdate; query.Category = DbCatState; - query.Fields = fields; - query.WhereCriteria = new Dictionary(); - query.WhereCriteria->Set("object_id", obj); - query.WhereCriteria->Set("varname", kv.first); + query.Fields = new Dictionary({ + { "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)); } diff --git a/lib/db_ido/endpointdbobject.cpp b/lib/db_ido/endpointdbobject.cpp index 2402cadaf..ed9b27fb3 100644 --- a/lib/db_ido/endpointdbobject.cpp +++ b/lib/db_ido/endpointdbobject.cpp @@ -46,30 +46,29 @@ EndpointDbObject::EndpointDbObject(const DbType::Ptr& type, const String& name1, Dictionary::Ptr EndpointDbObject::GetConfigFields() const { - Dictionary::Ptr fields = new Dictionary(); Endpoint::Ptr endpoint = static_pointer_cast(GetObject()); - fields->Set("identity", endpoint->GetName()); - fields->Set("node", IcingaApplication::GetInstance()->GetNodeName()); - fields->Set("zone_object_id", endpoint->GetZone()); - - return fields; + return new Dictionary({ + { "identity", endpoint->GetName() }, + { "node", IcingaApplication::GetInstance()->GetNodeName() }, + { "zone_object_id", endpoint->GetZone() } + }); } Dictionary::Ptr EndpointDbObject::GetStatusFields() const { - Dictionary::Ptr fields = new Dictionary(); Endpoint::Ptr endpoint = static_pointer_cast(GetObject()); + Log(LogDebug, "EndpointDbObject") << "update status for endpoint '" << endpoint->GetName() << "'"; - fields->Set("identity", endpoint->GetName()); - fields->Set("node", IcingaApplication::GetInstance()->GetNodeName()); - fields->Set("zone_object_id", endpoint->GetZone()); - fields->Set("is_connected", EndpointIsConnected(endpoint)); - - return fields; + return new Dictionary({ + { "identity", endpoint->GetName() }, + { "node", IcingaApplication::GetInstance()->GetNodeName() }, + { "zone_object_id", endpoint->GetZone() }, + { "is_connected", EndpointIsConnected(endpoint) } + }); } void EndpointDbObject::UpdateConnectedStatus(const Endpoint::Ptr& endpoint) @@ -84,14 +83,15 @@ void EndpointDbObject::UpdateConnectedStatus(const Endpoint::Ptr& endpoint) query1.Type = DbQueryUpdate; query1.Category = DbCatState; - Dictionary::Ptr fields1 = new Dictionary(); - fields1->Set("is_connected", (connected ? 1 : 0)); - fields1->Set("status_update_time", DbValue::FromTimestamp(Utility::GetTime())); - query1.Fields = fields1; + query1.Fields = new Dictionary({ + { "is_connected", (connected ? 1 : 0) }, + { "status_update_time", DbValue::FromTimestamp(Utility::GetTime()) } + }); - query1.WhereCriteria = new Dictionary(); - query1.WhereCriteria->Set("endpoint_object_id", endpoint); - query1.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ + query1.WhereCriteria = new Dictionary({ + { "endpoint_object_id", endpoint }, + { "instance_id", 0 } /* DbConnection class fills in real ID */ + }); OnQuery(query1); } diff --git a/lib/db_ido/hostdbobject.cpp b/lib/db_ido/hostdbobject.cpp index e339b5e70..3c8c42058 100644 --- a/lib/db_ido/hostdbobject.cpp +++ b/lib/db_ido/hostdbobject.cpp @@ -51,50 +51,42 @@ Dictionary::Ptr HostDbObject::GetConfigFields() const /* Compatibility fallback. */ 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 notificationTypeFilter = CompatUtility::GetCheckableNotificationTypeFilter(host); - fields->Set("notify_on_down", (notificationStateFilter & ServiceWarning) || (notificationStateFilter && ServiceCritical)); - fields->Set("notify_on_unreachable", 1); /* We don't have this filter and state, and as such we don't filter such notifications. */ - fields->Set("notify_on_recovery", notificationTypeFilter & NotificationRecovery); - fields->Set("notify_on_flapping", (notificationTypeFilter & NotificationFlappingStart) || - (notificationTypeFilter & NotificationFlappingEnd)); - fields->Set("notify_on_downtime", (notificationTypeFilter & NotificationDowntimeStart) || - (notificationTypeFilter & NotificationDowntimeEnd) || (notificationTypeFilter & NotificationDowntimeRemoved)); - - return fields; + return new Dictionary({ + { "alias", !displayName.IsEmpty() ? displayName : host->GetName() }, + { "display_name", displayName }, + { "address", host->GetAddress() }, + { "address6", host->GetAddress6() }, + { "check_command_object_id", host->GetCheckCommand() }, + { "eventhandler_command_object_id", host->GetEventCommand() }, + { "check_timeperiod_object_id", host->GetCheckPeriod() }, + { "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 @@ -193,14 +185,16 @@ void HostDbObject::OnConfigUpdateHeavy() query2.Table = DbType::GetByName("HostGroup")->GetTable() + "_members"; query2.Type = DbQueryInsert; query2.Category = DbCatConfig; - query2.Fields = new Dictionary(); - query2.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query2.Fields->Set("hostgroup_id", DbValue::FromObjectInsertID(group)); - query2.Fields->Set("host_object_id", host); - query2.WhereCriteria = new Dictionary(); - query2.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query2.WhereCriteria->Set("hostgroup_id", DbValue::FromObjectInsertID(group)); - query2.WhereCriteria->Set("host_object_id", host); + query2.Fields = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "hostgroup_id", DbValue::FromObjectInsertID(group) }, + { "host_object_id", host } + }); + query2.WhereCriteria = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "hostgroup_id", DbValue::FromObjectInsertID(group) }, + { "host_object_id", host } + }); queries.emplace_back(std::move(query2)); } } @@ -213,8 +207,9 @@ void HostDbObject::OnConfigUpdateHeavy() query2.Table = GetType()->GetTable() + "_parenthosts"; query2.Type = DbQueryDelete; query2.Category = DbCatConfig; - query2.WhereCriteria = new Dictionary(); - query2.WhereCriteria->Set(GetType()->GetTable() + "_id", DbValue::FromObjectInsertID(GetObject())); + query2.WhereCriteria = new Dictionary({ + { GetType()->GetTable() + "_id", DbValue::FromObjectInsertID(GetObject()) } + }); queries.emplace_back(std::move(query2)); /* parents */ @@ -228,16 +223,15 @@ void HostDbObject::OnConfigUpdateHeavy() << "host parents: " << parent->GetName(); /* 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; query1.Table = GetType()->GetTable() + "_parenthosts"; query1.Type = DbQueryInsert; 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)); } @@ -253,8 +247,9 @@ void HostDbObject::OnConfigUpdateHeavy() query3.Table = GetType()->GetTable() + "dependencies"; query3.Type = DbQueryDelete; query3.Category = DbCatConfig; - query3.WhereCriteria = new Dictionary(); - query3.WhereCriteria->Set("dependent_host_object_id", host); + query3.WhereCriteria = new Dictionary({ + { "dependent_host_object_id", host } + }); queries.emplace_back(std::move(query3)); for (const Dependency::Ptr& dep : host->GetDependencies()) { @@ -271,20 +266,19 @@ void HostDbObject::OnConfigUpdateHeavy() Log(LogDebug, "HostDbObject") << "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; query2.Table = GetType()->GetTable() + "dependencies"; query2.Type = DbQueryInsert; 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)); } @@ -299,24 +293,24 @@ void HostDbObject::OnConfigUpdateHeavy() query4.Table = GetType()->GetTable() + "_contacts"; query4.Type = DbQueryDelete; query4.Category = DbCatConfig; - query4.WhereCriteria = new Dictionary(); - query4.WhereCriteria->Set("host_id", DbValue::FromObjectInsertID(host)); + query4.WhereCriteria = new Dictionary({ + { "host_id", DbValue::FromObjectInsertID(host) } + }); queries.emplace_back(std::move(query4)); for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(host)) { Log(LogDebug, "HostDbObject") << "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; query_contact.Table = GetType()->GetTable() + "_contacts"; query_contact.Type = DbQueryInsert; 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)); } @@ -331,24 +325,24 @@ void HostDbObject::OnConfigUpdateHeavy() query5.Table = GetType()->GetTable() + "_contactgroups"; query5.Type = DbQueryDelete; query5.Category = DbCatConfig; - query5.WhereCriteria = new Dictionary(); - query5.WhereCriteria->Set("host_id", DbValue::FromObjectInsertID(host)); + query5.WhereCriteria = new Dictionary({ + { "host_id", DbValue::FromObjectInsertID(host) } + }); queries.emplace_back(std::move(query5)); for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(host)) { Log(LogDebug, "HostDbObject") << "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; query_contact.Table = GetType()->GetTable() + "_contactgroups"; query_contact.Type = DbQueryInsert; 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)); } @@ -382,7 +376,7 @@ String HostDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields) co if (groups) hashData += DbObject::HashValue(groups); - Array::Ptr parents = new Array(); + ArrayData parents; /* parents */ for (const Checkable::Ptr& checkable : host->GetParents()) { @@ -391,14 +385,14 @@ String HostDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields) co if (!parent) 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 */ for (const Dependency::Ptr& dep : host->GetDependencies()) { @@ -407,37 +401,36 @@ String HostDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields) co if (!parent) continue; - Array::Ptr depInfo = new Array(); - depInfo->Add(parent->GetName()); - depInfo->Add(dep->GetStateFilter()); - depInfo->Add(dep->GetPeriodRaw()); - - dependencies->Add(depInfo); + dependencies.push_back(new Array({ + parent->GetName(), + dep->GetStateFilter(), + dep->GetPeriodRaw() + })); } - 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)) { - 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)) { - 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); } diff --git a/lib/db_ido/hostgroupdbobject.cpp b/lib/db_ido/hostgroupdbobject.cpp index 73996a628..13ee82783 100644 --- a/lib/db_ido/hostgroupdbobject.cpp +++ b/lib/db_ido/hostgroupdbobject.cpp @@ -34,15 +34,14 @@ HostGroupDbObject::HostGroupDbObject(const DbType::Ptr& type, const String& name Dictionary::Ptr HostGroupDbObject::GetConfigFields() const { - Dictionary::Ptr fields = new Dictionary(); HostGroup::Ptr group = static_pointer_cast(GetObject()); - fields->Set("alias", group->GetDisplayName()); - fields->Set("notes", group->GetNotes()); - fields->Set("notes_url", group->GetNotesUrl()); - fields->Set("action_url", group->GetActionUrl()); - - return fields; + return new Dictionary({ + { "alias", group->GetDisplayName() }, + { "notes", group->GetNotes() }, + { "notes_url", group->GetNotesUrl() }, + { "action_url", group->GetActionUrl() } + }); } Dictionary::Ptr HostGroupDbObject::GetStatusFields() const diff --git a/lib/db_ido/idochecktask.cpp b/lib/db_ido/idochecktask.cpp index 7c667474d..544c2cefb 100644 --- a/lib/db_ido/idochecktask.cpp +++ b/lib/db_ido/idochecktask.cpp @@ -181,14 +181,13 @@ void IdoCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const CheckResult cr->SetOutput(msgbuf.str()); - Array::Ptr perfdata = new Array(); - perfdata->Add(new PerfdataValue("queries", qps, false, "", queriesWarning, queriesCritical)); - perfdata->Add(new PerfdataValue("queries_1min", conn->GetQueryCount(60))); - perfdata->Add(new PerfdataValue("queries_5mins", conn->GetQueryCount(5 * 60))); - perfdata->Add(new PerfdataValue("queries_15mins", conn->GetQueryCount(15 * 60))); - perfdata->Add(new PerfdataValue("pending_queries", pendingQueries, false, "", pendingQueriesWarning, pendingQueriesCritical)); - - cr->SetPerformanceData(perfdata); + cr->SetPerformanceData(new Array({ + { new PerfdataValue("queries", qps, false, "", queriesWarning, queriesCritical) }, + { new PerfdataValue("queries_1min", conn->GetQueryCount(60)) }, + { new PerfdataValue("queries_5mins", conn->GetQueryCount(5 * 60)) }, + { new PerfdataValue("queries_15mins", conn->GetQueryCount(15 * 60)) }, + { new PerfdataValue("pending_queries", pendingQueries, false, "", pendingQueriesWarning, pendingQueriesCritical) } + })); checkable->ProcessCheckResult(cr); } diff --git a/lib/db_ido/servicedbobject.cpp b/lib/db_ido/servicedbobject.cpp index 93a80d199..70ea4267e 100644 --- a/lib/db_ido/servicedbobject.cpp +++ b/lib/db_ido/servicedbobject.cpp @@ -50,50 +50,45 @@ ServiceDbObject::ServiceDbObject(const DbType::Ptr& type, const String& name1, c Dictionary::Ptr ServiceDbObject::GetConfigFields() const { - Dictionary::Ptr fields = new Dictionary(); Service::Ptr service = static_pointer_cast(GetObject()); 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 notificationTypeFilter = CompatUtility::GetCheckableNotificationTypeFilter(service); - fields->Set("notify_on_warning", notificationStateFilter & ServiceWarning); - fields->Set("notify_on_unknown", notificationStateFilter & ServiceUnknown); - fields->Set("notify_on_critical", notificationStateFilter & ServiceCritical); - fields->Set("notify_on_recovery", notificationTypeFilter & NotificationRecovery); - fields->Set("notify_on_flapping", (notificationTypeFilter & NotificationFlappingStart) || - (notificationTypeFilter & NotificationFlappingEnd)); - fields->Set("notify_on_downtime", (notificationTypeFilter & NotificationDowntimeStart) || - (notificationTypeFilter & NotificationDowntimeEnd) || (notificationTypeFilter & NotificationDowntimeRemoved)); - - return fields; + return new Dictionary({ + { "host_object_id", host }, + { "display_name", service->GetDisplayName() }, + { "check_command_object_id", service->GetCheckCommand() }, + { "eventhandler_command_object_id", service->GetEventCommand() }, + { "check_timeperiod_object_id", service->GetCheckPeriod() }, + { "check_interval", service->GetCheckInterval() / 60.0 }, + { "retry_interval", service->GetRetryInterval() / 60.0 }, + { "max_check_attempts", service->GetMaxCheckAttempts() }, + { "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 @@ -174,8 +169,9 @@ void ServiceDbObject::OnConfigUpdateHeavy() query1.Table = DbType::GetByName("ServiceGroup")->GetTable() + "_members"; query1.Type = DbQueryDelete; query1.Category = DbCatConfig; - query1.WhereCriteria = new Dictionary(); - query1.WhereCriteria->Set("service_object_id", service); + query1.WhereCriteria = new Dictionary({ + { "service_object_id", service } + }); queries.emplace_back(std::move(query1)); if (groups) { @@ -187,14 +183,16 @@ void ServiceDbObject::OnConfigUpdateHeavy() query2.Table = DbType::GetByName("ServiceGroup")->GetTable() + "_members"; query2.Type = DbQueryInsert; query2.Category = DbCatConfig; - query2.Fields = new Dictionary(); - query2.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query2.Fields->Set("servicegroup_id", DbValue::FromObjectInsertID(group)); - query2.Fields->Set("service_object_id", service); - query2.WhereCriteria = new Dictionary(); - query2.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query2.WhereCriteria->Set("servicegroup_id", DbValue::FromObjectInsertID(group)); - query2.WhereCriteria->Set("service_object_id", service); + query2.Fields = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "servicegroup_id", DbValue::FromObjectInsertID(group) }, + { "service_object_id", service } + }); + query2.WhereCriteria = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "servicegroup_id", DbValue::FromObjectInsertID(group) }, + { "service_object_id", service } + }); queries.emplace_back(std::move(query2)); } } @@ -211,8 +209,9 @@ void ServiceDbObject::OnConfigUpdateHeavy() query2.Table = GetType()->GetTable() + "dependencies"; query2.Type = DbQueryDelete; query2.Category = DbCatConfig; - query2.WhereCriteria = new Dictionary(); - query2.WhereCriteria->Set("dependent_service_object_id", service); + query2.WhereCriteria = new Dictionary({ + { "dependent_service_object_id", service } + }); queries.emplace_back(std::move(query2)); for (const Dependency::Ptr& dep : service->GetDependencies()) { @@ -230,22 +229,21 @@ void ServiceDbObject::OnConfigUpdateHeavy() int stateFilter = dep->GetStateFilter(); /* 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; query1.Table = GetType()->GetTable() + "dependencies"; query1.Type = DbQueryInsert; 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)); } @@ -261,24 +259,25 @@ void ServiceDbObject::OnConfigUpdateHeavy() query3.Table = GetType()->GetTable() + "_contacts"; query3.Type = DbQueryDelete; query3.Category = DbCatConfig; - query3.WhereCriteria = new Dictionary(); - query3.WhereCriteria->Set("service_id", DbValue::FromObjectInsertID(service)); + query3.WhereCriteria = new Dictionary({ + { "service_id", DbValue::FromObjectInsertID(service) } + }); queries.emplace_back(std::move(query3)); for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(service)) { Log(LogDebug, "ServiceDbObject") << "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; query_contact.Table = GetType()->GetTable() + "_contacts"; query_contact.Type = DbQueryInsert; 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)); } @@ -293,24 +292,24 @@ void ServiceDbObject::OnConfigUpdateHeavy() query4.Table = GetType()->GetTable() + "_contactgroups"; query4.Type = DbQueryDelete; query4.Category = DbCatConfig; - query4.WhereCriteria = new Dictionary(); - query4.WhereCriteria->Set("service_id", DbValue::FromObjectInsertID(service)); + query4.WhereCriteria = new Dictionary({ + { "service_id", DbValue::FromObjectInsertID(service) } + }); queries.emplace_back(std::move(query4)); for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(service)) { Log(LogDebug, "ServiceDbObject") << "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; query_contact.Table = GetType()->GetTable() + "_contactgroups"; query_contact.Type = DbQueryInsert; 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)); } @@ -344,7 +343,7 @@ String ServiceDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields) if (groups) hashData += DbObject::HashValue(groups); - Array::Ptr dependencies = new Array(); + ArrayData dependencies; /* dependencies */ for (const Dependency::Ptr& dep : service->GetDependencies()) { @@ -353,37 +352,36 @@ String ServiceDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields) if (!parent) continue; - Array::Ptr depInfo = new Array(); - depInfo->Add(parent->GetName()); - depInfo->Add(dep->GetStateFilter()); - depInfo->Add(dep->GetPeriodRaw()); - - dependencies->Add(depInfo); + dependencies.push_back(new Array({ + parent->GetName(), + dep->GetStateFilter(), + dep->GetPeriodRaw() + })); } - 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)) { - 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)) { - 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); } diff --git a/lib/db_ido/servicegroupdbobject.cpp b/lib/db_ido/servicegroupdbobject.cpp index 153914b0d..085e76f7f 100644 --- a/lib/db_ido/servicegroupdbobject.cpp +++ b/lib/db_ido/servicegroupdbobject.cpp @@ -33,15 +33,14 @@ ServiceGroupDbObject::ServiceGroupDbObject(const DbType::Ptr& type, const String Dictionary::Ptr ServiceGroupDbObject::GetConfigFields() const { - Dictionary::Ptr fields = new Dictionary(); ServiceGroup::Ptr group = static_pointer_cast(GetObject()); - fields->Set("alias", group->GetDisplayName()); - fields->Set("notes", group->GetNotes()); - fields->Set("notes_url", group->GetNotesUrl()); - fields->Set("action_url", group->GetActionUrl()); - - return fields; + return new Dictionary({ + { "alias", group->GetDisplayName() }, + { "notes", group->GetNotes() }, + { "notes_url", group->GetNotesUrl() }, + { "action_url", group->GetActionUrl() } + }); } Dictionary::Ptr ServiceGroupDbObject::GetStatusFields() const diff --git a/lib/db_ido/timeperioddbobject.cpp b/lib/db_ido/timeperioddbobject.cpp index 3bb392be2..a53ae5c2a 100644 --- a/lib/db_ido/timeperioddbobject.cpp +++ b/lib/db_ido/timeperioddbobject.cpp @@ -36,12 +36,11 @@ TimePeriodDbObject::TimePeriodDbObject(const DbType::Ptr& type, const String& na Dictionary::Ptr TimePeriodDbObject::GetConfigFields() const { - Dictionary::Ptr fields = new Dictionary(); TimePeriod::Ptr tp = static_pointer_cast(GetObject()); - fields->Set("alias", tp->GetDisplayName()); - - return fields; + return new Dictionary({ + { "alias", tp->GetDisplayName() } + }); } Dictionary::Ptr TimePeriodDbObject::GetStatusFields() const @@ -57,8 +56,9 @@ void TimePeriodDbObject::OnConfigUpdateHeavy() query_del1.Table = GetType()->GetTable() + "_timeranges"; query_del1.Type = DbQueryDelete; query_del1.Category = DbCatConfig; - query_del1.WhereCriteria = new Dictionary(); - query_del1.WhereCriteria->Set("timeperiod_id", DbValue::FromObjectInsertID(tp)); + query_del1.WhereCriteria = new Dictionary({ + { "timeperiod_id", DbValue::FromObjectInsertID(tp) } + }); OnQuery(query_del1); Dictionary::Ptr ranges = tp->GetRanges(); @@ -89,12 +89,13 @@ void TimePeriodDbObject::OnConfigUpdateHeavy() query.Table = GetType()->GetTable() + "_timeranges"; query.Type = DbQueryInsert; query.Category = DbCatConfig; - query.Fields = new Dictionary(); - query.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query.Fields->Set("timeperiod_id", DbValue::FromObjectInsertID(tp)); - query.Fields->Set("day", wday); - query.Fields->Set("start_sec", begin % 86400); - query.Fields->Set("end_sec", end % 86400); + query.Fields = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "timeperiod_id", DbValue::FromObjectInsertID(tp) }, + { "day", wday }, + { "start_sec", begin % 86400 }, + { "end_sec", end % 86400 } + }); OnQuery(query); } } diff --git a/lib/db_ido/userdbobject.cpp b/lib/db_ido/userdbobject.cpp index d369b38c6..f33883e3a 100644 --- a/lib/db_ido/userdbobject.cpp +++ b/lib/db_ido/userdbobject.cpp @@ -37,46 +37,43 @@ UserDbObject::UserDbObject(const DbType::Ptr& type, const String& name1, const S Dictionary::Ptr UserDbObject::GetConfigFields() const { - Dictionary::Ptr fields = new Dictionary(); User::Ptr user = static_pointer_cast(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 stateFilter = user->GetStateFilter(); - fields->Set("notify_service_recovery", (typeFilter & NotificationRecovery) != 0); - fields->Set("notify_service_warning", (stateFilter & StateFilterWarning) != 0); - fields->Set("notify_service_unknown", (stateFilter & StateFilterUnknown) != 0); - fields->Set("notify_service_critical", (stateFilter & StateFilterCritical) != 0); - fields->Set("notify_service_flapping", (typeFilter & (NotificationFlappingStart | NotificationFlappingEnd)) != 0); - fields->Set("notify_service_downtime", (typeFilter & (NotificationDowntimeStart | NotificationDowntimeEnd | NotificationDowntimeRemoved)) != 0); - fields->Set("notify_host_recovery", (typeFilter & NotificationRecovery) != 0); - fields->Set("notify_host_down", (stateFilter & StateFilterDown) != 0); - fields->Set("notify_host_flapping", (typeFilter & (NotificationFlappingStart | NotificationFlappingEnd)) != 0); - fields->Set("notify_host_downtime", (typeFilter & (NotificationDowntimeStart | NotificationDowntimeEnd | NotificationDowntimeRemoved)) != 0); - - return fields; + return new Dictionary({ + { "alias", user->GetDisplayName() }, + { "email_address", user->GetEmail() }, + { "pager_address", user->GetPager() }, + { "host_timeperiod_object_id", user->GetPeriod() }, + { "service_timeperiod_object_id", user->GetPeriod() }, + { "host_notifications_enabled", user->GetEnableNotifications() }, + { "service_notifications_enabled", user->GetEnableNotifications() }, + { "can_submit_commands", 1 }, + { "notify_service_recovery", (typeFilter & NotificationRecovery) != 0 }, + { "notify_service_warning", (stateFilter & StateFilterWarning) != 0 }, + { "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 fields = new Dictionary(); User::Ptr user = static_pointer_cast(GetObject()); - fields->Set("host_notifications_enabled", user->GetEnableNotifications()); - fields->Set("service_notifications_enabled", user->GetEnableNotifications()); - fields->Set("last_host_notification", DbValue::FromTimestamp(user->GetLastNotification())); - fields->Set("last_service_notification", DbValue::FromTimestamp(user->GetLastNotification())); - - return fields; + return new Dictionary({ + { "host_notifications_enabled", user->GetEnableNotifications() }, + { "service_notifications_enabled", user->GetEnableNotifications() }, + { "last_host_notification", DbValue::FromTimestamp(user->GetLastNotification()) }, + { "last_service_notification", DbValue::FromTimestamp(user->GetLastNotification()) } + }); } void UserDbObject::OnConfigUpdateHeavy() @@ -92,8 +89,9 @@ void UserDbObject::OnConfigUpdateHeavy() query1.Table = DbType::GetByName("UserGroup")->GetTable() + "_members"; query1.Type = DbQueryDelete; query1.Category = DbCatConfig; - query1.WhereCriteria = new Dictionary(); - query1.WhereCriteria->Set("contact_object_id", user); + query1.WhereCriteria = new Dictionary({ + { "contact_object_id", user } + }); queries.emplace_back(std::move(query1)); if (groups) { @@ -105,14 +103,16 @@ void UserDbObject::OnConfigUpdateHeavy() query2.Table = DbType::GetByName("UserGroup")->GetTable() + "_members"; query2.Type = DbQueryInsert | DbQueryUpdate; query2.Category = DbCatConfig; - query2.Fields = new Dictionary(); - query2.Fields->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query2.Fields->Set("contactgroup_id", DbValue::FromObjectInsertID(group)); - query2.Fields->Set("contact_object_id", user); - query2.WhereCriteria = new Dictionary(); - query2.WhereCriteria->Set("instance_id", 0); /* DbConnection class fills in real ID */ - query2.WhereCriteria->Set("contactgroup_id", DbValue::FromObjectInsertID(group)); - query2.WhereCriteria->Set("contact_object_id", user); + query2.Fields = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "contactgroup_id", DbValue::FromObjectInsertID(group) }, + { "contact_object_id", user } + }); + query2.WhereCriteria = new Dictionary({ + { "instance_id", 0 }, /* DbConnection class fills in real ID */ + { "contactgroup_id", DbValue::FromObjectInsertID(group) }, + { "contact_object_id", user } + }); queries.emplace_back(std::move(query2)); } } @@ -125,16 +125,15 @@ void UserDbObject::OnConfigUpdateHeavy() query2.Table = "contact_addresses"; query2.Type = DbQueryDelete; query2.Category = DbCatConfig; - query2.WhereCriteria = new Dictionary(); - query2.WhereCriteria->Set("contact_id", DbValue::FromObjectInsertID(user)); + query2.WhereCriteria = new Dictionary({ + { "contact_id", DbValue::FromObjectInsertID(user) } + }); queries.emplace_back(std::move(query2)); Dictionary::Ptr vars = user->GetVars(); if (vars) { /* This is sparta. */ for (int i = 1; i <= 6; i++) { - Dictionary::Ptr fields = new Dictionary(); - String key = "address" + Convert::ToString(i); if (!vars->Contains(key)) @@ -142,16 +141,17 @@ void UserDbObject::OnConfigUpdateHeavy() 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; query.Type = DbQueryInsert; query.Table = "contact_addresses"; 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)); } } diff --git a/lib/db_ido/usergroupdbobject.cpp b/lib/db_ido/usergroupdbobject.cpp index f38b8a55b..2a8458f94 100644 --- a/lib/db_ido/usergroupdbobject.cpp +++ b/lib/db_ido/usergroupdbobject.cpp @@ -34,12 +34,11 @@ UserGroupDbObject::UserGroupDbObject(const DbType::Ptr& type, const String& name Dictionary::Ptr UserGroupDbObject::GetConfigFields() const { - Dictionary::Ptr fields = new Dictionary(); UserGroup::Ptr group = static_pointer_cast(GetObject()); - fields->Set("alias", group->GetDisplayName()); - - return fields; + return new Dictionary({ + { "alias", group->GetDisplayName() } + }); } Dictionary::Ptr UserGroupDbObject::GetStatusFields() const diff --git a/lib/db_ido/zonedbobject.cpp b/lib/db_ido/zonedbobject.cpp index 252130b98..1c462d7e9 100644 --- a/lib/db_ido/zonedbobject.cpp +++ b/lib/db_ido/zonedbobject.cpp @@ -33,13 +33,13 @@ ZoneDbObject::ZoneDbObject(const DbType::Ptr& type, const String& name1, const S Dictionary::Ptr ZoneDbObject::GetConfigFields() const { - Dictionary::Ptr fields = new Dictionary(); Zone::Ptr zone = static_pointer_cast(GetObject()); - fields->Set("is_global", zone->IsGlobal() ? 1 : 0); - fields->Set("parent_zone_object_id", zone->GetParent()); + return new Dictionary({ + { "is_global", zone->IsGlobal() ? 1 : 0 }, + { "parent_zone_object_id", zone->GetParent() } - return fields; + }); } Dictionary::Ptr ZoneDbObject::GetStatusFields() const @@ -49,8 +49,7 @@ Dictionary::Ptr ZoneDbObject::GetStatusFields() const Log(LogDebug, "ZoneDbObject") << "update status for zone '" << zone->GetName() << "'"; - Dictionary::Ptr fields = new Dictionary(); - fields->Set("parent_zone_object_id", zone->GetParent()); - - return fields; + return new Dictionary({ + { "parent_zone_object_id", zone->GetParent() } + }); } diff --git a/lib/db_ido_mysql/idomysqlconnection.cpp b/lib/db_ido_mysql/idomysqlconnection.cpp index 999d90161..70e019685 100644 --- a/lib/db_ido_mysql/idomysqlconnection.cpp +++ b/lib/db_ido_mysql/idomysqlconnection.cpp @@ -55,20 +55,19 @@ void IdoMysqlConnection::OnConfigLoaded() 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()) { size_t queryQueueItems = idomysqlconnection->m_QueryQueue.GetLength(); double queryQueueItemRate = idomysqlconnection->m_QueryQueue.GetTaskCount(60) / 60.0; - Dictionary::Ptr stats = new Dictionary(); - stats->Set("version", idomysqlconnection->GetSchemaVersion()); - stats->Set("instance_name", idomysqlconnection->GetInstanceName()); - stats->Set("connected", idomysqlconnection->GetConnected()); - stats->Set("query_queue_items", queryQueueItems); - stats->Set("query_queue_item_rate", queryQueueItemRate); - - nodes->Set(idomysqlconnection->GetName(), stats); + nodes.emplace_back(idomysqlconnection->GetName(), new Dictionary({ + { "version", idomysqlconnection->GetSchemaVersion() }, + { "instance_name", idomysqlconnection->GetInstanceName() }, + { "connected", idomysqlconnection->GetConnected() }, + { "query_queue_items", queryQueueItems }, + { "query_queue_item_rate", queryQueueItemRate } + })); 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))); @@ -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)); } - status->Set("idomysqlconnection", nodes); + status->Set("idomysqlconnection", new Dictionary(std::move(nodes))); } void IdoMysqlConnection::Resume() diff --git a/lib/db_ido_pgsql/idopgsqlconnection.cpp b/lib/db_ido_pgsql/idopgsqlconnection.cpp index dbc8c1732..d9483e785 100644 --- a/lib/db_ido_pgsql/idopgsqlconnection.cpp +++ b/lib/db_ido_pgsql/idopgsqlconnection.cpp @@ -62,20 +62,19 @@ void IdoPgsqlConnection::OnConfigLoaded() 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()) { size_t queryQueueItems = idopgsqlconnection->m_QueryQueue.GetLength(); double queryQueueItemRate = idopgsqlconnection->m_QueryQueue.GetTaskCount(60) / 60.0; - Dictionary::Ptr stats = new Dictionary(); - stats->Set("version", idopgsqlconnection->GetSchemaVersion()); - stats->Set("instance_name", idopgsqlconnection->GetInstanceName()); - stats->Set("connected", idopgsqlconnection->GetConnected()); - stats->Set("query_queue_items", queryQueueItems); - stats->Set("query_queue_item_rate", queryQueueItemRate); - - nodes->Set(idopgsqlconnection->GetName(), stats); + nodes.emplace_back(idopgsqlconnection->GetName(), new Dictionary({ + { "version", idopgsqlconnection->GetSchemaVersion() }, + { "instance_name", idopgsqlconnection->GetInstanceName() }, + { "connected", idopgsqlconnection->GetConnected() }, + { "query_queue_items", queryQueueItems }, + { "query_queue_item_rate", queryQueueItemRate } + })); 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))); @@ -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)); } - status->Set("idopgsqlconnection", nodes); + status->Set("idopgsqlconnection", new Dictionary(std::move(nodes))); } void IdoPgsqlConnection::Resume() @@ -534,7 +533,7 @@ Dictionary::Ptr IdoPgsqlConnection::FetchRow(const IdoPgsqlResult& result, int r int columns = m_Pgsql->nfields(result.get()); - Dictionary::Ptr dict = new Dictionary(); + DictionaryData dict; for (int column = 0; column < columns; column++) { Value value; @@ -542,10 +541,10 @@ Dictionary::Ptr IdoPgsqlConnection::FetchRow(const IdoPgsqlResult& result, int r if (!m_Pgsql->getisnull(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) diff --git a/lib/icinga/apiactions.cpp b/lib/icinga/apiactions.cpp index 355bfc878..f916624f0 100644 --- a/lib/icinga/apiactions.cpp +++ b/lib/icinga/apiactions.cpp @@ -52,9 +52,10 @@ REGISTER_APIACTION(generate_ticket, "", &ApiActions::GenerateTicket); Dictionary::Ptr ApiActions::CreateResult(int code, const String& status, const Dictionary::Ptr& additional) { - Dictionary::Ptr result = new Dictionary(); - result->Set("code", code); - result->Set("status", status); + Dictionary::Ptr result = new Dictionary({ + { "code", code }, + { "status", status } + }); if (additional) additional->CopyTo(result); @@ -275,9 +276,10 @@ Dictionary::Ptr ApiActions::AddComment(const ConfigObject::Ptr& object, Comment::Ptr comment = Comment::GetByName(commentName); - Dictionary::Ptr additional = new Dictionary(); - additional->Set("name", commentName); - additional->Set("legacy_id", comment->GetLegacyId()); + Dictionary::Ptr additional = new Dictionary({ + { "name", commentName }, + { "legacy_id", comment->GetLegacyId() } + }); return ApiActions::CreateResult(200, "Successfully added comment '" + commentName + "' for object '" + checkable->GetName() @@ -350,9 +352,10 @@ Dictionary::Ptr ApiActions::ScheduleDowntime(const ConfigObject::Ptr& object, Downtime::Ptr downtime = Downtime::GetByName(downtimeName); - Dictionary::Ptr additional = new Dictionary(); - additional->Set("name", downtimeName); - additional->Set("legacy_id", downtime->GetLegacyId()); + Dictionary::Ptr additional = new Dictionary({ + { "name", downtimeName }, + { "legacy_id", downtime->GetLegacyId() } + }); /* Schedule downtime for all child objects. */ int childOptions = 0; @@ -366,11 +369,11 @@ Dictionary::Ptr ApiActions::ScheduleDowntime(const ConfigObject::Ptr& object, if (childOptions == 1) triggerName = downtimeName; - Array::Ptr childDowntimes = new Array(); - Log(LogCritical, "ApiActions") << "Processing child options " << childOptions << " for downtime " << downtimeName; + ArrayData childDowntimes; + for (const Checkable::Ptr& child : checkable->GetAllChildren()) { Log(LogCritical, "ApiActions") << "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); - Dictionary::Ptr additionalChild = new Dictionary(); - additionalChild->Set("name", childDowntimeName); - additionalChild->Set("legacy_id", childDowntime->GetLegacyId()); - childDowntimes->Add(additionalChild); + childDowntimes.push_back(new Dictionary({ + { "name", childDowntimeName }, + { "legacy_id", childDowntime->GetLegacyId() } + })); } - additional->Set("child_downtimes", childDowntimes); + additional->Set("child_downtimes", new Array(std::move(childDowntimes))); } 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); - Dictionary::Ptr additional = new Dictionary(); - additional->Set("ticket", ticket); + Dictionary::Ptr additional = new Dictionary({ + { "ticket", ticket } + }); return ApiActions::CreateResult(200, "Generated PKI ticket '" + ticket + "' for common name '" + cn + "'.", additional); diff --git a/lib/icinga/apievents.cpp b/lib/icinga/apievents.cpp index 2090bda0c..7041890df 100644 --- a/lib/icinga/apievents.cpp +++ b/lib/icinga/apievents.cpp @@ -129,13 +129,13 @@ void ApiEvents::NotificationSentToAllUsersHandler(const Notification::Ptr& notif if (service) result->Set("service", service->GetShortName()); - Array::Ptr userNames = new Array(); + ArrayData userNames; 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("author", author); result->Set("text", text); @@ -257,11 +257,11 @@ void ApiEvents::CommentAddedHandler(const Comment::Ptr& comment) Log(LogDebug, "ApiEvents", "Processing event type 'CommentAdded'."); - Dictionary::Ptr result = new Dictionary(); - result->Set("type", "CommentAdded"); - result->Set("timestamp", Utility::GetTime()); - - result->Set("comment", Serialize(comment, FAConfig | FAState)); + Dictionary::Ptr result = new Dictionary({ + { "type", "CommentAdded" }, + { "timestamp", Utility::GetTime() }, + { "comment", Serialize(comment, FAConfig | FAState) } + }); for (const EventQueue::Ptr& queue : queues) { queue->ProcessEvent(result); @@ -277,11 +277,11 @@ void ApiEvents::CommentRemovedHandler(const Comment::Ptr& comment) Log(LogDebug, "ApiEvents", "Processing event type 'CommentRemoved'."); - Dictionary::Ptr result = new Dictionary(); - result->Set("type", "CommentRemoved"); - result->Set("timestamp", Utility::GetTime()); - - result->Set("comment", Serialize(comment, FAConfig | FAState)); + Dictionary::Ptr result = new Dictionary({ + { "type", "CommentRemoved" }, + { "timestamp", Utility::GetTime() }, + { "comment", Serialize(comment, FAConfig | FAState) } + }); for (const EventQueue::Ptr& queue : queues) { queue->ProcessEvent(result); @@ -297,11 +297,11 @@ void ApiEvents::DowntimeAddedHandler(const Downtime::Ptr& downtime) Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeAdded'."); - Dictionary::Ptr result = new Dictionary(); - result->Set("type", "DowntimeAdded"); - result->Set("timestamp", Utility::GetTime()); - - result->Set("downtime", Serialize(downtime, FAConfig | FAState)); + Dictionary::Ptr result = new Dictionary({ + { "type", "DowntimeAdded" }, + { "timestamp", Utility::GetTime() }, + { "downtime", Serialize(downtime, FAConfig | FAState) } + }); for (const EventQueue::Ptr& queue : queues) { queue->ProcessEvent(result); @@ -317,11 +317,11 @@ void ApiEvents::DowntimeRemovedHandler(const Downtime::Ptr& downtime) Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeRemoved'."); - Dictionary::Ptr result = new Dictionary(); - result->Set("type", "DowntimeRemoved"); - result->Set("timestamp", Utility::GetTime()); - - result->Set("downtime", Serialize(downtime, FAConfig | FAState)); + Dictionary::Ptr result = new Dictionary({ + { "type", "DowntimeRemoved" }, + { "timestamp", Utility::GetTime() }, + { "downtime", Serialize(downtime, FAConfig | FAState) } + }); for (const EventQueue::Ptr& queue : queues) { queue->ProcessEvent(result); @@ -337,11 +337,11 @@ void ApiEvents::DowntimeStartedHandler(const Downtime::Ptr& downtime) Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeStarted'."); - Dictionary::Ptr result = new Dictionary(); - result->Set("type", "DowntimeStarted"); - result->Set("timestamp", Utility::GetTime()); - - result->Set("downtime", Serialize(downtime, FAConfig | FAState)); + Dictionary::Ptr result = new Dictionary({ + { "type", "DowntimeStarted" }, + { "timestamp", Utility::GetTime() }, + { "downtime", Serialize(downtime, FAConfig | FAState) } + }); for (const EventQueue::Ptr& queue : queues) { queue->ProcessEvent(result); @@ -357,11 +357,11 @@ void ApiEvents::DowntimeTriggeredHandler(const Downtime::Ptr& downtime) Log(LogDebug, "ApiEvents", "Processing event type 'DowntimeTriggered'."); - Dictionary::Ptr result = new Dictionary(); - result->Set("type", "DowntimeTriggered"); - result->Set("timestamp", Utility::GetTime()); - - result->Set("downtime", Serialize(downtime, FAConfig | FAState)); + Dictionary::Ptr result = new Dictionary({ + { "type", "DowntimeTriggered" }, + { "timestamp", Utility::GetTime() }, + { "downtime", Serialize(downtime, FAConfig | FAState) } + }); for (const EventQueue::Ptr& queue : queues) { queue->ProcessEvent(result); diff --git a/lib/icinga/checkable-check.cpp b/lib/icinga/checkable-check.cpp index e7ca7728b..5d658d3b0 100644 --- a/lib/icinga/checkable-check.cpp +++ b/lib/icinga/checkable-check.cpp @@ -301,11 +301,12 @@ void Checkable::ProcessCheckResult(const CheckResult::Ptr& cr, const MessageOrig if (remove_acknowledgement_comments) RemoveCommentsByType(CommentAcknowledgement); - Dictionary::Ptr vars_after = new Dictionary(); - vars_after->Set("state", new_state); - vars_after->Set("state_type", GetStateType()); - vars_after->Set("attempt", GetCheckAttempt()); - vars_after->Set("reachable", reachable); + Dictionary::Ptr vars_after = new Dictionary({ + { "state", new_state }, + { "state_type", GetStateType() }, + { "attempt", GetCheckAttempt() }, + { "reachable", reachable } + }); if (old_cr) cr->SetVarsBefore(old_cr->GetVarsAfter()); diff --git a/lib/icinga/checkable-script.cpp b/lib/icinga/checkable-script.cpp index 31c7f9eda..5d969e3f4 100644 --- a/lib/icinga/checkable-script.cpp +++ b/lib/icinga/checkable-script.cpp @@ -35,12 +35,9 @@ static void CheckableProcessCheckResult(const CheckResult::Ptr& cr) Object::Ptr Checkable::GetPrototype() { - static Dictionary::Ptr prototype; - - if (!prototype) { - prototype = new Dictionary(); - prototype->Set("process_check_result", new Function("Checkable#process_check_result", CheckableProcessCheckResult, { "cr" }, false)); - } + static Dictionary::Ptr prototype = new Dictionary({ + { "process_check_result", new Function("Checkable#process_check_result", CheckableProcessCheckResult, { "cr" }, false) } + }); return prototype; } diff --git a/lib/icinga/clusterevents.cpp b/lib/icinga/clusterevents.cpp index 2015558dc..013bae284 100644 --- a/lib/icinga/clusterevents.cpp +++ b/lib/icinga/clusterevents.cpp @@ -137,7 +137,7 @@ Value ClusterEvents::CheckResultAPIHandler(const MessageOrigin::Ptr& origin, con if (!cr) return Empty; - Array::Ptr rperf = new Array(); + ArrayData rperf; if (vperf) { ObjectLock olock(vperf); @@ -147,13 +147,13 @@ Value ClusterEvents::CheckResultAPIHandler(const MessageOrigin::Ptr& origin, con if (vp.IsObjectType()) { PerfdataValue::Ptr val = new PerfdataValue(); Deserialize(val, vp, true); - rperf->Add(val); + rperf.push_back(val); } 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")); @@ -892,11 +892,11 @@ void ClusterEvents::NotificationSentToAllUsersHandler(const Notification::Ptr& n params->Set("service", service->GetShortName()); params->Set("notification", notification->GetName()); - Array::Ptr ausers = new Array(); + ArrayData ausers; 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("cr", Serialize(cr)); @@ -1003,12 +1003,12 @@ Value ClusterEvents::NotificationSentToAllUsersAPIHandler(const MessageOrigin::P notification->SetLastProblemNotification(params->Get("last_problem_notification")); notification->SetNoMoreNotifications(params->Get("no_more_notifications")); - Array::Ptr notifiedProblemUsers = new Array(); + ArrayData notifiedProblemUsers; 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); diff --git a/lib/icinga/dependency-apply.cpp b/lib/icinga/dependency-apply.cpp index d300b8cfe..cc464aa7d 100644 --- a/lib/icinga/dependency-apply.cpp +++ b/lib/icinga/dependency-apply.cpp @@ -108,9 +108,7 @@ bool Dependency::EvaluateApplyRule(const Checkable::Ptr& checkable, const ApplyR return false; } } else { - Array::Ptr instances = new Array(); - instances->Add(""); - vinstances = instances; + vinstances = new Array({ "" }); } bool match = false; diff --git a/lib/icinga/icingaapplication.cpp b/lib/icinga/icingaapplication.cpp index 3a32586a4..90e623a92 100644 --- a/lib/icinga/icingaapplication.cpp +++ b/lib/icinga/icingaapplication.cpp @@ -65,25 +65,24 @@ REGISTER_STATSFUNCTION(IcingaApplication, &IcingaApplication::StatsFunc); 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()) { - Dictionary::Ptr stats = new Dictionary(); - stats->Set("node_name", icingaapplication->GetNodeName()); - stats->Set("enable_notifications", icingaapplication->GetEnableNotifications()); - stats->Set("enable_event_handlers", icingaapplication->GetEnableEventHandlers()); - stats->Set("enable_flapping", icingaapplication->GetEnableFlapping()); - stats->Set("enable_host_checks", icingaapplication->GetEnableHostChecks()); - stats->Set("enable_service_checks", icingaapplication->GetEnableServiceChecks()); - stats->Set("enable_perfdata", icingaapplication->GetEnablePerfdata()); - stats->Set("pid", Utility::GetPid()); - stats->Set("program_start", Application::GetStartTime()); - stats->Set("version", Application::GetAppVersion()); - - nodes->Set(icingaapplication->GetName(), stats); + nodes.emplace_back(icingaapplication->GetName(), new Dictionary({ + { "node_name", icingaapplication->GetNodeName() }, + { "enable_notifications", icingaapplication->GetEnableNotifications() }, + { "enable_event_handlers", icingaapplication->GetEnableEventHandlers() }, + { "enable_flapping", icingaapplication->GetEnableFlapping() }, + { "enable_host_checks", icingaapplication->GetEnableHostChecks() }, + { "enable_service_checks", icingaapplication->GetEnableServiceChecks() }, + { "enable_perfdata", icingaapplication->GetEnablePerfdata() }, + { "pid", Utility::GetPid() }, + { "program_start", Application::GetStartTime() }, + { "version", Application::GetAppVersion() } + })); } - 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 = "); - Array::Ptr args1 = new Array(); - args1->Add(object->GetReflectionType()->GetName()); - args1->Add(object->GetName()); + Array::Ptr args1 = new Array({ + object->GetReflectionType()->GetName(), + object->GetName() + }); ConfigWriter::EmitFunctionCall(fp, "get_object", args1); ConfigWriter::EmitRaw(fp, "\nif (obj) {\n"); @@ -139,9 +139,10 @@ static void PersistModAttrHelper(std::fstream& fp, ConfigObject::Ptr& previousOb ConfigWriter::EmitRaw(fp, "\tobj."); - Array::Ptr args2 = new Array(); - args2->Add(attr); - args2->Add(value); + Array::Ptr args2 = new Array({ + attr, + value + }); ConfigWriter::EmitFunctionCall(fp, "modify_attribute", args2); ConfigWriter::EmitRaw(fp, "\n"); diff --git a/lib/icinga/legacytimeperiod.cpp b/lib/icinga/legacytimeperiod.cpp index 14cdd8525..2204f4835 100644 --- a/lib/icinga/legacytimeperiod.cpp +++ b/lib/icinga/legacytimeperiod.cpp @@ -374,10 +374,10 @@ Dictionary::Ptr LegacyTimePeriod::ProcessTimeRange(const String& timestamp, tm * ProcessTimeRangeRaw(timestamp, reference, &begin, &end); - Dictionary::Ptr segment = new Dictionary(); - segment->Set("begin", (long)mktime(&begin)); - segment->Set("end", (long)mktime(&end)); - return segment; + return new Dictionary({ + { "begin", (long)mktime(&begin) }, + { "end", (long)mktime(&end) } + }); } void LegacyTimePeriod::ProcessTimeRanges(const String& timeranges, tm *reference, const Array::Ptr& result) diff --git a/lib/icinga/macroprocessor.cpp b/lib/icinga/macroprocessor.cpp index 9a0e7840f..7fc150d94 100644 --- a/lib/icinga/macroprocessor.cpp +++ b/lib/icinga/macroprocessor.cpp @@ -48,7 +48,7 @@ Value MacroProcessor::ResolveMacros(const Value& str, const ResolverList& resolv result = InternalResolveMacros(str, resolvers, cr, missingMacro, escapeFn, resolvedMacros, useResolvedMacros, recursionLevel + 1); } else if (str.IsObjectType()) { - Array::Ptr resultArr = new Array(); + ArrayData resultArr;; Array::Ptr arr = str; ObjectLock olock(arr); @@ -59,12 +59,12 @@ Value MacroProcessor::ResolveMacros(const Value& str, const ResolverList& resolv EscapeCallback(), resolvedMacros, useResolvedMacros, recursionLevel + 1); if (value.IsObjectType()) - resultArr->Add(Utility::Join(value, ';')); + resultArr.push_back(Utility::Join(value, ';')); else - resultArr->Add(value); + resultArr.push_back(value); } - result = resultArr; + result = new Array(std::move(resultArr)); } else if (str.IsObjectType()) { Dictionary::Ptr resultDict = new Dictionary(); Dictionary::Ptr dict = str; @@ -275,19 +275,19 @@ Value MacroProcessor::InternalResolveMacros(const String& str, const ResolverLis if (recursive_macro) { if (resolved_macro.IsObjectType()) { Array::Ptr arr = resolved_macro; - Array::Ptr resolved_arr = new Array(); + ArrayData resolved_arr; ObjectLock olock(arr); for (const Value& value : arr) { if (value.IsScalar()) { - resolved_arr->Add(InternalResolveMacros(value, + resolved_arr.push_back(InternalResolveMacros(value, resolvers, cr, missingMacro, EscapeCallback(), nullptr, false, recursionLevel + 1)); } 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()) { resolved_macro = InternalResolveMacros(resolved_macro, 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, EscapeMacroShellArg, resolvedMacros, useResolvedMacros, recursionLevel + 1); else { - Array::Ptr arr = new Array(); - arr->Add(command); - resolvedCommand = arr; + resolvedCommand = new Array({ command }); } if (arguments) { @@ -562,4 +560,3 @@ Value MacroProcessor::ResolveArguments(const Value& command, const Dictionary::P return resolvedCommand; } - diff --git a/lib/icinga/notification-apply.cpp b/lib/icinga/notification-apply.cpp index 5e05ece3b..7f8f39dab 100644 --- a/lib/icinga/notification-apply.cpp +++ b/lib/icinga/notification-apply.cpp @@ -107,9 +107,7 @@ bool Notification::EvaluateApplyRule(const Checkable::Ptr& checkable, const Appl return false; } } else { - Array::Ptr instances = new Array(); - instances->Add(""); - vinstances = instances; + vinstances = new Array({ "" }); } bool match = false; diff --git a/lib/icinga/pluginutility.cpp b/lib/icinga/pluginutility.cpp index ceffcfc13..02eb27896 100644 --- a/lib/icinga/pluginutility.cpp +++ b/lib/icinga/pluginutility.cpp @@ -145,7 +145,7 @@ std::pair PluginUtility::ParseCheckOutput(const String& output) Array::Ptr PluginUtility::SplitPerfdata(const String& perfdata) { - Array::Ptr result = new Array(); + ArrayData result; size_t begin = 0; String multi_prefix; @@ -182,7 +182,7 @@ Array::Ptr PluginUtility::SplitPerfdata(const String& perfdata) else pdv = label + "=" + value; - result->Add(pdv); + result.emplace_back(std::move(pdv)); if (multi_index != String::NPos) multi_prefix = label.SubStr(0, multi_index); @@ -190,7 +190,7 @@ Array::Ptr PluginUtility::SplitPerfdata(const String& perfdata) begin = spq + 1; } - return result; + return new Array(std::move(result)); } String PluginUtility::FormatPerfdata(const Array::Ptr& perfdata) diff --git a/lib/icinga/scheduleddowntime-apply.cpp b/lib/icinga/scheduleddowntime-apply.cpp index fb44018d0..3909f6fc0 100644 --- a/lib/icinga/scheduleddowntime-apply.cpp +++ b/lib/icinga/scheduleddowntime-apply.cpp @@ -106,9 +106,7 @@ bool ScheduledDowntime::EvaluateApplyRule(const Checkable::Ptr& checkable, const return false; } } else { - Array::Ptr instances = new Array(); - instances->Add(""); - vinstances = instances; + vinstances = new Array({ "" }); } bool match = false; diff --git a/lib/icinga/service-apply.cpp b/lib/icinga/service-apply.cpp index 79d9a78fb..4e9f78a66 100644 --- a/lib/icinga/service-apply.cpp +++ b/lib/icinga/service-apply.cpp @@ -95,9 +95,7 @@ bool Service::EvaluateApplyRule(const Host::Ptr& host, const ApplyRule& rule) return false; } } else { - Array::Ptr instances = new Array(); - instances->Add(""); - vinstances = instances; + vinstances = new Array({ "" }); } bool match = false; diff --git a/lib/icinga/service.cpp b/lib/icinga/service.cpp index 3964b3686..e6ca785f2 100644 --- a/lib/icinga/service.cpp +++ b/lib/icinga/service.cpp @@ -50,11 +50,10 @@ Dictionary::Ptr ServiceNameComposer::ParseName(const String& name) const if (tokens.size() < 2) BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid Service name.")); - Dictionary::Ptr result = new Dictionary(); - result->Set("host_name", tokens[0]); - result->Set("name", tokens[1]); - - return result; + return new Dictionary({ + { "host_name", tokens[0] }, + { "name", tokens[1] } + }); } void Service::OnAllConfigLoaded() diff --git a/lib/icinga/timeperiod.cpp b/lib/icinga/timeperiod.cpp index 13ee6bcfb..4953c3ebb 100644 --- a/lib/icinga/timeperiod.cpp +++ b/lib/icinga/timeperiod.cpp @@ -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. */ - Dictionary::Ptr segment = new Dictionary(); - segment->Set("begin", begin); - segment->Set("end", end); + Dictionary::Ptr segment = new Dictionary({ + { "begin", begin }, + { "end", end } + }); if (!segments) { segments = new Array(); @@ -152,17 +153,15 @@ void TimePeriod::RemoveSegment(double begin, double end) /* Cut between */ if (segment->Get("begin") < begin && segment->Get("end") > end) { - Dictionary::Ptr firstsegment = new Dictionary(); - firstsegment->Set("begin", segment->Get("begin")); - firstsegment->Set("end", begin); - - Dictionary::Ptr secondsegment = new Dictionary(); - secondsegment->Set("begin", end); - secondsegment->Set("end", segment->Get("end")); - - newSegments->Add(firstsegment); - newSegments->Add(secondsegment); - continue; + newSegments->Add(new Dictionary({ + { "begin", segment->Get("begin") }, + { "end", begin } + })); + + newSegments->Add(new Dictionary({ + { "begin", end }, + { "end", segment->Get("end") } + })); } /* Adjust the begin/end timestamps so as to not overlap with the specified range. */ diff --git a/lib/livestatus/commandstable.cpp b/lib/livestatus/commandstable.cpp index ae5145fc1..a26ae91a2 100644 --- a/lib/livestatus/commandstable.cpp +++ b/lib/livestatus/commandstable.cpp @@ -101,19 +101,16 @@ Value CommandsTable::CustomVariableNamesAccessor(const Value& row) Dictionary::Ptr vars = command->GetVars(); - Array::Ptr cv = new Array(); + ArrayData keys; - if (!vars) - return cv; - - { + if (vars) { ObjectLock xlock(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) @@ -125,19 +122,16 @@ Value CommandsTable::CustomVariableValuesAccessor(const Value& row) Dictionary::Ptr vars = command->GetVars(); - Array::Ptr cv = new Array(); - - if (!vars) - return cv; + ArrayData keys; - { + if (vars) { ObjectLock xlock(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) @@ -149,20 +143,17 @@ Value CommandsTable::CustomVariablesAccessor(const Value& row) Dictionary::Ptr vars = command->GetVars(); - Array::Ptr cv = new Array(); - - if (!vars) - return cv; + ArrayData result; - { + if (vars) { ObjectLock xlock(vars); for (const auto& kv : vars) { - Array::Ptr key_val = new Array(); - key_val->Add(kv.first); - key_val->Add(kv.second); - cv->Add(key_val); + result.push_back(new Array({ + kv.first, + kv.second + })); } } - return cv; + return new Array(std::move(result)); } diff --git a/lib/livestatus/contactgroupstable.cpp b/lib/livestatus/contactgroupstable.cpp index 93587674a..2be78ffad 100644 --- a/lib/livestatus/contactgroupstable.cpp +++ b/lib/livestatus/contactgroupstable.cpp @@ -81,11 +81,11 @@ Value ContactGroupsTable::MembersAccessor(const Value& row) if (!user_group) return Empty; - Array::Ptr members = new Array(); + ArrayData result; 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)); } diff --git a/lib/livestatus/contactstable.cpp b/lib/livestatus/contactstable.cpp index aeca4b04d..62030aae6 100644 --- a/lib/livestatus/contactstable.cpp +++ b/lib/livestatus/contactstable.cpp @@ -205,17 +205,16 @@ Value ContactsTable::CustomVariableNamesAccessor(const Value& row) Dictionary::Ptr vars = user->GetVars(); - Array::Ptr cv = new Array(); + ArrayData result; - if (!vars) - return cv; - - ObjectLock olock(vars); - for (const Dictionary::Pair& kv : vars) { - cv->Add(kv.first); + if (vars) { + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + result.push_back(kv.first); + } } - return cv; + return new Array(std::move(result)); } Value ContactsTable::CustomVariableValuesAccessor(const Value& row) @@ -227,20 +226,19 @@ Value ContactsTable::CustomVariableValuesAccessor(const Value& row) Dictionary::Ptr vars = user->GetVars(); - Array::Ptr cv = new Array(); + ArrayData result; - if (!vars) - return cv; - - ObjectLock olock(vars); - for (const Dictionary::Pair& kv : vars) { - if (kv.second.IsObjectType() || kv.second.IsObjectType()) - cv->Add(JsonEncode(kv.second)); - else - cv->Add(kv.second); + if (vars) { + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + if (kv.second.IsObjectType() || kv.second.IsObjectType()) + result.push_back(JsonEncode(kv.second)); + else + result.push_back(kv.second); + } } - return cv; + return new Array(std::move(result)); } Value ContactsTable::CustomVariablesAccessor(const Value& row) @@ -252,25 +250,26 @@ Value ContactsTable::CustomVariablesAccessor(const Value& row) Dictionary::Ptr vars = user->GetVars(); - Array::Ptr cv = new Array(); + ArrayData result; - if (!vars) - return cv; + if (vars) { + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + Value val; - ObjectLock olock(vars); - for (const Dictionary::Pair& kv : vars) { - Array::Ptr key_val = new Array(); - key_val->Add(kv.first); - - if (kv.second.IsObjectType() || kv.second.IsObjectType()) - key_val->Add(JsonEncode(kv.second)); - else - key_val->Add(kv.second); + if (kv.second.IsObjectType() || kv.second.IsObjectType()) + val = JsonEncode(kv.second); + else + 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) diff --git a/lib/livestatus/hostgroupstable.cpp b/lib/livestatus/hostgroupstable.cpp index 117a84a7d..a4ab713a3 100644 --- a/lib/livestatus/hostgroupstable.cpp +++ b/lib/livestatus/hostgroupstable.cpp @@ -135,13 +135,13 @@ Value HostGroupsTable::MembersAccessor(const Value& row) if (!hg) return Empty; - Array::Ptr members = new Array(); + ArrayData members; 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) @@ -151,16 +151,16 @@ Value HostGroupsTable::MembersWithStateAccessor(const Value& row) if (!hg) return Empty; - Array::Ptr members = new Array(); + ArrayData members; for (const Host::Ptr& host : hg->GetMembers()) { - Array::Ptr member_state = new Array(); - member_state->Add(host->GetName()); - member_state->Add(host->GetState()); - members->Add(member_state); + members.push_back(new Array({ + host->GetName(), + host->GetState() + })); } - return members; + return new Array(std::move(members)); } Value HostGroupsTable::WorstHostStateAccessor(const Value& row) diff --git a/lib/livestatus/hoststable.cpp b/lib/livestatus/hoststable.cpp index 795f31b8e..d46b88535 100644 --- a/lib/livestatus/hoststable.cpp +++ b/lib/livestatus/hoststable.cpp @@ -912,13 +912,13 @@ Value HostsTable::ContactsAccessor(const Value& row) if (!host) return Empty; - Array::Ptr contact_names = new Array(); + ArrayData result; 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) @@ -928,16 +928,16 @@ Value HostsTable::DowntimesAccessor(const Value& row) if (!host) return Empty; - Array::Ptr results = new Array(); + ArrayData result; for (const Downtime::Ptr& downtime : host->GetDowntimes()) { if (downtime->IsExpired()) continue; - results->Add(downtime->GetLegacyId()); + result.push_back(downtime->GetLegacyId()); } - return results; + return new Array(std::move(result)); } Value HostsTable::DowntimesWithInfoAccessor(const Value& row) @@ -947,20 +947,20 @@ Value HostsTable::DowntimesWithInfoAccessor(const Value& row) if (!host) return Empty; - Array::Ptr results = new Array(); + ArrayData result; for (const Downtime::Ptr& downtime : host->GetDowntimes()) { if (downtime->IsExpired()) continue; - Array::Ptr downtime_info = new Array(); - downtime_info->Add(downtime->GetLegacyId()); - downtime_info->Add(downtime->GetAuthor()); - downtime_info->Add(downtime->GetComment()); - results->Add(downtime_info); + result.push_back(new Array({ + downtime->GetLegacyId(), + downtime->GetAuthor(), + downtime->GetComment() + })); } - return results; + return new Array(std::move(result)); } Value HostsTable::CommentsAccessor(const Value& row) @@ -970,15 +970,16 @@ Value HostsTable::CommentsAccessor(const Value& row) if (!host) return Empty; - Array::Ptr results = new Array(); + ArrayData result; + for (const Comment::Ptr& comment : host->GetComments()) { if (comment->IsExpired()) continue; - results->Add(comment->GetLegacyId()); + result.push_back(comment->GetLegacyId()); } - return results; + return new Array(std::move(result)); } Value HostsTable::CommentsWithInfoAccessor(const Value& row) @@ -988,20 +989,20 @@ Value HostsTable::CommentsWithInfoAccessor(const Value& row) if (!host) return Empty; - Array::Ptr results = new Array(); + ArrayData result; for (const Comment::Ptr& comment : host->GetComments()) { if (comment->IsExpired()) continue; - Array::Ptr comment_info = new Array(); - comment_info->Add(comment->GetLegacyId()); - comment_info->Add(comment->GetAuthor()); - comment_info->Add(comment->GetText()); - results->Add(comment_info); + result.push_back(new Array({ + comment->GetLegacyId(), + comment->GetAuthor(), + comment->GetText() + })); } - return results; + return new Array(std::move(result)); } Value HostsTable::CommentsWithExtraInfoAccessor(const Value& row) @@ -1011,22 +1012,22 @@ Value HostsTable::CommentsWithExtraInfoAccessor(const Value& row) if (!host) return Empty; - Array::Ptr results = new Array(); + ArrayData result; for (const Comment::Ptr& comment : host->GetComments()) { if (comment->IsExpired()) continue; - Array::Ptr comment_info = new Array(); - comment_info->Add(comment->GetLegacyId()); - comment_info->Add(comment->GetAuthor()); - comment_info->Add(comment->GetText()); - comment_info->Add(comment->GetEntryType()); - comment_info->Add(static_cast(comment->GetEntryTime())); - results->Add(comment_info); + result.push_back(new Array({ + comment->GetLegacyId(), + comment->GetAuthor(), + comment->GetText(), + comment->GetEntryType(), + static_cast(comment->GetEntryTime()) + })); } - return results; + return new Array(std::move(result)); } Value HostsTable::CustomVariableNamesAccessor(const Value& row) @@ -1038,17 +1039,16 @@ Value HostsTable::CustomVariableNamesAccessor(const Value& row) Dictionary::Ptr vars = host->GetVars(); - Array::Ptr cv = new Array(); - - if (!vars) - return cv; + ArrayData result; - ObjectLock olock(vars); - for (const Dictionary::Pair& kv : vars) { - cv->Add(kv.first); + if (vars) { + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + result.push_back(kv.first); + } } - return cv; + return new Array(std::move(result)); } Value HostsTable::CustomVariableValuesAccessor(const Value& row) @@ -1060,20 +1060,19 @@ Value HostsTable::CustomVariableValuesAccessor(const Value& row) Dictionary::Ptr vars = host->GetVars(); - Array::Ptr cv = new Array(); + ArrayData result; - if (!vars) - return cv; - - ObjectLock olock(vars); - for (const Dictionary::Pair& kv : vars) { - if (kv.second.IsObjectType() || kv.second.IsObjectType()) - cv->Add(JsonEncode(kv.second)); - else - cv->Add(kv.second); + if (vars) { + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + if (kv.second.IsObjectType() || kv.second.IsObjectType()) + result.push_back(JsonEncode(kv.second)); + else + result.push_back(kv.second); + } } - return cv; + return new Array(std::move(result)); } Value HostsTable::CustomVariablesAccessor(const Value& row) @@ -1085,25 +1084,26 @@ Value HostsTable::CustomVariablesAccessor(const Value& row) Dictionary::Ptr vars = host->GetVars(); - Array::Ptr cv = new Array(); - - if (!vars) - return cv; + ArrayData result; - ObjectLock olock(vars); - for (const Dictionary::Pair& kv : vars) { - Array::Ptr key_val = new Array(); - key_val->Add(kv.first); + if (vars) { + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + Value val; - if (kv.second.IsObjectType() || kv.second.IsObjectType()) - key_val->Add(JsonEncode(kv.second)); - else - key_val->Add(kv.second); + if (kv.second.IsObjectType() || kv.second.IsObjectType()) + val = JsonEncode(kv.second); + else + 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) @@ -1136,7 +1136,7 @@ Value HostsTable::ParentsAccessor(const Value& row) if (!host) return Empty; - Array::Ptr parents = new Array(); + ArrayData result; for (const Checkable::Ptr& parent : host->GetParents()) { Host::Ptr parent_host = dynamic_pointer_cast(parent); @@ -1144,10 +1144,10 @@ Value HostsTable::ParentsAccessor(const Value& row) if (!parent_host) 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) @@ -1157,7 +1157,7 @@ Value HostsTable::ChildsAccessor(const Value& row) if (!host) return Empty; - Array::Ptr childs = new Array(); + ArrayData result; for (const Checkable::Ptr& child : host->GetChildren()) { Host::Ptr child_host = dynamic_pointer_cast(child); @@ -1165,10 +1165,10 @@ Value HostsTable::ChildsAccessor(const Value& row) if (!child_host) 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) @@ -1421,13 +1421,13 @@ Value HostsTable::ContactGroupsAccessor(const Value& row) if (!host) return Empty; - Array::Ptr contactgroup_names = new Array(); + ArrayData result; 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) @@ -1439,14 +1439,14 @@ Value HostsTable::ServicesAccessor(const Value& row) std::vector rservices = host->GetServices(); - Array::Ptr services = new Array(); - services->Reserve(rservices.size()); + ArrayData result; + result.reserve(rservices.size()); 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) @@ -1458,19 +1458,18 @@ Value HostsTable::ServicesWithStateAccessor(const Value& row) std::vector rservices = host->GetServices(); - Array::Ptr services = new Array(); - services->Reserve(rservices.size()); + ArrayData result; + result.reserve(rservices.size()); 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); - services->Add(svc_add); + result.push_back(new Array({ + service->GetShortName(), + service->GetState(), + service->HasBeenChecked() ? 1 : 0 + })); } - return services; + return new Array(std::move(result)); } Value HostsTable::ServicesWithInfoAccessor(const Value& row) @@ -1482,27 +1481,25 @@ Value HostsTable::ServicesWithInfoAccessor(const Value& row) std::vector rservices = host->GetServices(); - Array::Ptr services = new Array(); - services->Reserve(rservices.size()); + ArrayData result; + result.reserve(rservices.size()); 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; CheckResult::Ptr cr = service->GetLastCheckResult(); if (cr) output = CompatUtility::GetCheckResultOutput(cr); - svc_add->Add(output); - services->Add(svc_add); + result.push_back(new Array({ + service->GetShortName(), + service->GetState(), + service->HasBeenChecked() ? 1 : 0, + output + })); } - return services; + return new Array(std::move(result)); } Value HostsTable::CheckSourceAccessor(const Value& row) diff --git a/lib/livestatus/livestatuslistener.cpp b/lib/livestatus/livestatuslistener.cpp index 164b44fc1..1f7944a39 100644 --- a/lib/livestatus/livestatuslistener.cpp +++ b/lib/livestatus/livestatuslistener.cpp @@ -45,18 +45,17 @@ REGISTER_STATSFUNCTION(LivestatusListener, &LivestatusListener::StatsFunc); 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()) { - Dictionary::Ptr stats = new Dictionary(); - stats->Set("connections", l_Connections); - - nodes->Set(livestatuslistener->GetName(), stats); + nodes.emplace_back(livestatuslistener->GetName(), new Dictionary({ + { "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))); } /** diff --git a/lib/livestatus/livestatusquery.cpp b/lib/livestatus/livestatusquery.cpp index a8e7577aa..df3eb2ff1 100644 --- a/lib/livestatus/livestatusquery.cpp +++ b/lib/livestatus/livestatusquery.cpp @@ -482,8 +482,6 @@ void LivestatusQuery::ExecuteGetHelper(const Stream::Ptr& stream) BeginResultSet(result); if (m_Aggregators.empty()) { - Array::Ptr header = new Array(); - typedef std::pair ColumnPair; std::vector column_objs; @@ -492,24 +490,26 @@ void LivestatusQuery::ExecuteGetHelper(const Stream::Ptr& stream) for (const String& columnName : columns) column_objs.emplace_back(columnName, table->GetColumn(columnName)); + ArrayData header; + for (const LivestatusRowValue& object : objects) { - Array::Ptr row = new Array(); + ArrayData row; - row->Reserve(column_objs.size()); + row.reserve(column_objs.size()); for (const ColumnPair& cv : column_objs) { 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) { - AppendResultRow(result, header, first_row); + AppendResultRow(result, new Array(std::move(header)), first_row); m_ColumnHeaders = false; } - AppendResultRow(result, row, first_row); + AppendResultRow(result, new Array(std::move(row)), first_row); } } else { std::map, std::vector > allStats; @@ -542,45 +542,47 @@ void LivestatusQuery::ExecuteGetHelper(const Stream::Ptr& stream) /* add column headers both for raw and aggregated data */ if (m_ColumnHeaders) { - Array::Ptr header = new Array(); + ArrayData header; for (const String& columnName : m_Columns) { - header->Add(columnName); + header.push_back(columnName); } 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) { - 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) { - row->Add(keyPart); + row.push_back(keyPart); } auto& stats = kv.second; 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*/ 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++) { - row->Add(0); + row.push_back(0); } - AppendResultRow(result, row, first_row); + AppendResultRow(result, new Array(std::move(row)), first_row); } } diff --git a/lib/livestatus/servicegroupstable.cpp b/lib/livestatus/servicegroupstable.cpp index 09c24db77..1d98bfd50 100644 --- a/lib/livestatus/servicegroupstable.cpp +++ b/lib/livestatus/servicegroupstable.cpp @@ -126,16 +126,16 @@ Value ServiceGroupsTable::MembersAccessor(const Value& row) if (!sg) return Empty; - Array::Ptr members = new Array(); + ArrayData result; for (const Service::Ptr& service : sg->GetMembers()) { - Array::Ptr host_svc = new Array(); - host_svc->Add(service->GetHost()->GetName()); - host_svc->Add(service->GetShortName()); - members->Add(host_svc); + result.push_back(new Array({ + service->GetHost()->GetName(), + service->GetShortName() + })); } - return members; + return new Array(std::move(result)); } Value ServiceGroupsTable::MembersWithStateAccessor(const Value& row) @@ -145,18 +145,18 @@ Value ServiceGroupsTable::MembersWithStateAccessor(const Value& row) if (!sg) return Empty; - Array::Ptr members = new Array(); + ArrayData result; for (const Service::Ptr& service : sg->GetMembers()) { - Array::Ptr host_svc = new Array(); - host_svc->Add(service->GetHost()->GetName()); - host_svc->Add(service->GetShortName()); - host_svc->Add(service->GetHost()->GetState()); - host_svc->Add(service->GetState()); - members->Add(host_svc); + result.push_back(new Array({ + service->GetHost()->GetName(), + service->GetShortName(), + service->GetHost()->GetState(), + service->GetState() + })); } - return members; + return new Array(std::move(result)); } Value ServiceGroupsTable::WorstServiceStateAccessor(const Value& row) diff --git a/lib/livestatus/servicestable.cpp b/lib/livestatus/servicestable.cpp index 3abffb423..dce09bf57 100644 --- a/lib/livestatus/servicestable.cpp +++ b/lib/livestatus/servicestable.cpp @@ -933,13 +933,13 @@ Value ServicesTable::ContactsAccessor(const Value& row) if (!service) return Empty; - Array::Ptr contact_names = new Array(); + ArrayData result; 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) @@ -949,16 +949,16 @@ Value ServicesTable::DowntimesAccessor(const Value& row) if (!service) return Empty; - Array::Ptr results = new Array(); + ArrayData result; for (const Downtime::Ptr& downtime : service->GetDowntimes()) { if (downtime->IsExpired()) continue; - results->Add(downtime->GetLegacyId()); + result.push_back(downtime->GetLegacyId()); } - return results; + return new Array(std::move(result)); } Value ServicesTable::DowntimesWithInfoAccessor(const Value& row) @@ -968,20 +968,20 @@ Value ServicesTable::DowntimesWithInfoAccessor(const Value& row) if (!service) return Empty; - Array::Ptr results = new Array(); + ArrayData result; for (const Downtime::Ptr& downtime : service->GetDowntimes()) { if (downtime->IsExpired()) continue; - Array::Ptr downtime_info = new Array(); - downtime_info->Add(downtime->GetLegacyId()); - downtime_info->Add(downtime->GetAuthor()); - downtime_info->Add(downtime->GetComment()); - results->Add(downtime_info); + result.push_back(new Array({ + downtime->GetLegacyId(), + downtime->GetAuthor(), + downtime->GetComment() + })); } - return results; + return new Array(std::move(result)); } Value ServicesTable::CommentsAccessor(const Value& row) @@ -991,16 +991,16 @@ Value ServicesTable::CommentsAccessor(const Value& row) if (!service) return Empty; - Array::Ptr results = new Array(); + ArrayData result; for (const Comment::Ptr& comment : service->GetComments()) { if (comment->IsExpired()) continue; - results->Add(comment->GetLegacyId()); + result.push_back(comment->GetLegacyId()); } - return results; + return new Array(std::move(result)); } Value ServicesTable::CommentsWithInfoAccessor(const Value& row) @@ -1010,20 +1010,20 @@ Value ServicesTable::CommentsWithInfoAccessor(const Value& row) if (!service) return Empty; - Array::Ptr results = new Array(); + ArrayData result; for (const Comment::Ptr& comment : service->GetComments()) { if (comment->IsExpired()) continue; - Array::Ptr comment_info = new Array(); - comment_info->Add(comment->GetLegacyId()); - comment_info->Add(comment->GetAuthor()); - comment_info->Add(comment->GetText()); - results->Add(comment_info); + result.push_back(new Array({ + comment->GetLegacyId(), + comment->GetAuthor(), + comment->GetText() + })); } - return results; + return new Array(std::move(result)); } Value ServicesTable::CommentsWithExtraInfoAccessor(const Value& row) @@ -1033,22 +1033,22 @@ Value ServicesTable::CommentsWithExtraInfoAccessor(const Value& row) if (!service) return Empty; - Array::Ptr results = new Array(); + ArrayData result; for (const Comment::Ptr& comment : service->GetComments()) { if (comment->IsExpired()) continue; - Array::Ptr comment_info = new Array(); - comment_info->Add(comment->GetLegacyId()); - comment_info->Add(comment->GetAuthor()); - comment_info->Add(comment->GetText()); - comment_info->Add(comment->GetEntryType()); - comment_info->Add(static_cast(comment->GetEntryTime())); - results->Add(comment_info); + result.push_back(new Array({ + comment->GetLegacyId(), + comment->GetAuthor(), + comment->GetText(), + comment->GetEntryType(), + static_cast(comment->GetEntryTime()) + })); } - return results; + return new Array(std::move(result)); } Value ServicesTable::CustomVariableNamesAccessor(const Value& row) @@ -1060,17 +1060,16 @@ Value ServicesTable::CustomVariableNamesAccessor(const Value& row) Dictionary::Ptr vars = service->GetVars(); - Array::Ptr cv = new Array(); + ArrayData result; - if (!vars) - return cv; - - ObjectLock olock(vars); - for (const Dictionary::Pair& kv : vars) { - cv->Add(kv.first); + if (vars) { + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + result.push_back(kv.first); + } } - return cv; + return new Array(std::move(result)); } Value ServicesTable::CustomVariableValuesAccessor(const Value& row) @@ -1082,20 +1081,19 @@ Value ServicesTable::CustomVariableValuesAccessor(const Value& row) Dictionary::Ptr vars = service->GetVars(); - Array::Ptr cv = new Array(); + ArrayData result; - if (!vars) - return cv; - - ObjectLock olock(vars); - for (const Dictionary::Pair& kv : vars) { - if (kv.second.IsObjectType() || kv.second.IsObjectType()) - cv->Add(JsonEncode(kv.second)); - else - cv->Add(kv.second); + if (vars) { + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + if (kv.second.IsObjectType() || kv.second.IsObjectType()) + result.push_back(JsonEncode(kv.second)); + else + result.push_back(kv.second); + } } - return cv; + return new Array(std::move(result)); } Value ServicesTable::CustomVariablesAccessor(const Value& row) @@ -1107,25 +1105,26 @@ Value ServicesTable::CustomVariablesAccessor(const Value& row) Dictionary::Ptr vars = service->GetVars(); - Array::Ptr cv = new Array(); - - if (!vars) - return cv; + ArrayData result; - ObjectLock olock(vars); - for (const Dictionary::Pair& kv : vars) { - Array::Ptr key_val = new Array(); - key_val->Add(kv.first); + if (vars) { + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + Value val; - if (kv.second.IsObjectType() || kv.second.IsObjectType()) - key_val->Add(JsonEncode(kv.second)); - else - key_val->Add(kv.second); + if (kv.second.IsObjectType() || kv.second.IsObjectType()) + val = JsonEncode(kv.second); + else + 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) @@ -1173,13 +1172,13 @@ Value ServicesTable::ContactGroupsAccessor(const Value& row) if (!service) return Empty; - Array::Ptr contactgroup_names = new Array(); + ArrayData result; 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) diff --git a/lib/livestatus/statustable.cpp b/lib/livestatus/statustable.cpp index 135e15e99..ec0b62103 100644 --- a/lib/livestatus/statustable.cpp +++ b/lib/livestatus/statustable.cpp @@ -233,58 +233,49 @@ Value StatusTable::CustomVariableNamesAccessor(const Value&) { Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars(); - Array::Ptr cv = new Array(); + ArrayData result; - if (!vars) - return cv; - - { + if (vars) { ObjectLock olock(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&) { Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars(); - Array::Ptr cv = new Array(); - - if (!vars) - return cv; + ArrayData result; - { + if (vars) { ObjectLock olock(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&) { Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars(); - Array::Ptr cv = new Array(); - - if (!vars) - return cv; + ArrayData result; - { + if (vars) { ObjectLock olock(vars); for (const auto& kv : vars) { - Array::Ptr key_val = new Array(); - key_val->Add(kv.first); - key_val->Add(kv.second); - cv->Add(key_val); + result.push_back(new Array({ + kv.first, + kv.second + })); } } - return cv; + return new Array(std::move(result)); } diff --git a/lib/livestatus/zonestable.cpp b/lib/livestatus/zonestable.cpp index f94c825ea..b755862be 100644 --- a/lib/livestatus/zonestable.cpp +++ b/lib/livestatus/zonestable.cpp @@ -89,16 +89,13 @@ Value ZonesTable::EndpointsAccessor(const Value& row) std::set endpoints = zone->GetEndpoints(); - Array::Ptr endpoint_names = new Array(); + ArrayData result; for (const Endpoint::Ptr& endpoint : endpoints) { - endpoint_names->Add(endpoint->GetName()); + result.push_back(endpoint->GetName()); } - if (!endpoint_names) - return Empty; - - return endpoint_names; + return new Array(std::move(result)); } Value ZonesTable::GlobalAccessor(const Value& row) diff --git a/lib/methods/clusterzonechecktask.cpp b/lib/methods/clusterzonechecktask.cpp index 635f7fc8c..4bb114690 100644 --- a/lib/methods/clusterzonechecktask.cpp +++ b/lib/methods/clusterzonechecktask.cpp @@ -138,15 +138,15 @@ void ClusterZoneCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const Che + " greater than warning threshold: " + Utility::FormatDuration(lagWarning)); } - Array::Ptr perfdata = new Array(); - perfdata->Add(new PerfdataValue("slave_lag", zoneLag, false, "s", lagWarning, lagCritical)); - perfdata->Add(new PerfdataValue("last_messages_sent", lastMessageSent)); - perfdata->Add(new PerfdataValue("last_messages_received", lastMessageReceived)); - perfdata->Add(new PerfdataValue("sum_messages_sent_per_second", messagesSentPerSecond)); - perfdata->Add(new PerfdataValue("sum_messages_received_per_second", messagesReceivedPerSecond)); - perfdata->Add(new PerfdataValue("sum_bytes_sent_per_second", bytesSentPerSecond)); - perfdata->Add(new PerfdataValue("sum_bytes_received_per_second", bytesReceivedPerSecond)); - cr->SetPerformanceData(perfdata); + cr->SetPerformanceData(new Array({ + new PerfdataValue("slave_lag", zoneLag, false, "s", lagWarning, lagCritical), + new PerfdataValue("last_messages_sent", lastMessageSent), + new PerfdataValue("last_messages_received", lastMessageReceived), + new PerfdataValue("sum_messages_sent_per_second", messagesSentPerSecond), + new PerfdataValue("sum_messages_received_per_second", messagesReceivedPerSecond), + new PerfdataValue("sum_bytes_sent_per_second", bytesSentPerSecond), + new PerfdataValue("sum_bytes_received_per_second", bytesReceivedPerSecond) + })); checkable->ProcessCheckResult(cr); } diff --git a/lib/methods/nullchecktask.cpp b/lib/methods/nullchecktask.cpp index 68d267549..64d64b034 100644 --- a/lib/methods/nullchecktask.cpp +++ b/lib/methods/nullchecktask.cpp @@ -41,11 +41,10 @@ void NullCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult: String output = "Hello from "; output += IcingaApplication::GetInstance()->GetNodeName(); - Array::Ptr perfdata = new Array(); - perfdata->Add(new PerfdataValue("time", Convert::ToDouble(Utility::GetTime()))); - cr->SetOutput(output); - cr->SetPerformanceData(perfdata); + cr->SetPerformanceData(new Array({ + new PerfdataValue("time", Convert::ToDouble(Utility::GetTime())) + })); cr->SetState(ServiceOK); service->ProcessCheckResult(cr); diff --git a/lib/methods/pluginnotificationtask.cpp b/lib/methods/pluginnotificationtask.cpp index 4fa3ea71f..4e98aa4fb 100644 --- a/lib/methods/pluginnotificationtask.cpp +++ b/lib/methods/pluginnotificationtask.cpp @@ -45,10 +45,11 @@ void PluginNotificationTask::ScriptFunc(const Notification::Ptr& notification, Checkable::Ptr checkable = notification->GetCheckable(); - Dictionary::Ptr notificationExtra = new Dictionary(); - notificationExtra->Set("type", Notification::NotificationTypeToString(type)); - notificationExtra->Set("author", author); - notificationExtra->Set("comment", comment); + Dictionary::Ptr notificationExtra = new Dictionary({ + { "type", Notification::NotificationTypeToString(type) }, + { "author", author }, + { "comment", comment } + }); Host::Ptr host; Service::Ptr service; diff --git a/lib/methods/randomchecktask.cpp b/lib/methods/randomchecktask.cpp index b279b1adf..787a5deac 100644 --- a/lib/methods/randomchecktask.cpp +++ b/lib/methods/randomchecktask.cpp @@ -41,11 +41,10 @@ void RandomCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResul String output = "Hello from "; output += IcingaApplication::GetInstance()->GetNodeName(); - Array::Ptr perfdata = new Array(); - perfdata->Add(new PerfdataValue("time", Convert::ToDouble(Utility::GetTime()))); - cr->SetOutput(output); - cr->SetPerformanceData(perfdata); + cr->SetPerformanceData(new Array({ + new PerfdataValue("time", Convert::ToDouble(Utility::GetTime())) + })); cr->SetState(static_cast(Utility::Random() % 4)); service->ProcessCheckResult(cr); diff --git a/lib/methods/timeperiodtask.cpp b/lib/methods/timeperiodtask.cpp index 9d461e835..cc4e9b51c 100644 --- a/lib/methods/timeperiodtask.cpp +++ b/lib/methods/timeperiodtask.cpp @@ -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 segments = new Array(); + ArrayData segments; for (long t = begin / 60 - 1; t * 60 < end; t++) { if ((t % 2) == 0) { - Dictionary::Ptr segment = new Dictionary(); - segment->Set("begin", t * 60); - segment->Set("end", (t + 1) * 60); - - segments->Add(segment); + segments.push_back(new Dictionary({ + { "begin", t * 60 }, + { "end", (t + 1) * 60 } + })); } } - return segments; + return new Array(std::move(segments)); } diff --git a/lib/notification/notificationcomponent.cpp b/lib/notification/notificationcomponent.cpp index a3bd06797..3f9a83956 100644 --- a/lib/notification/notificationcomponent.cpp +++ b/lib/notification/notificationcomponent.cpp @@ -36,13 +36,13 @@ REGISTER_STATSFUNCTION(NotificationComponent, &NotificationComponent::StatsFunc) 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()) { - 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))); } /** diff --git a/lib/perfdata/elasticsearchwriter.cpp b/lib/perfdata/elasticsearchwriter.cpp index cfea33819..708e90670 100644 --- a/lib/perfdata/elasticsearchwriter.cpp +++ b/lib/perfdata/elasticsearchwriter.cpp @@ -53,23 +53,22 @@ void ElasticsearchWriter::OnConfigLoaded() 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()) { size_t workQueueItems = elasticsearchwriter->m_WorkQueue.GetLength(); double workQueueItemRate = elasticsearchwriter->m_WorkQueue.GetTaskCount(60) / 60.0; - Dictionary::Ptr stats = new Dictionary(); - stats->Set("work_queue_items", workQueueItems); - stats->Set("work_queue_item_rate", workQueueItemRate); - - nodes->Set(elasticsearchwriter->GetName(), stats); + nodes.emplace_back(elasticsearchwriter->GetName(), new Dictionary({ + { "work_queue_items", workQueueItems }, + { "work_queue_item_rate", workQueueItemRate } + })); perfdata->Add(new PerfdataValue("elasticsearchwriter_" + elasticsearchwriter->GetName() + "_work_queue_items", workQueueItems)); 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) @@ -312,13 +311,13 @@ void ElasticsearchWriter::NotificationSentToAllUsersHandlerInternal(const Notifi fields->Set("host", host->GetName()); - Array::Ptr userNames = new Array(); + ArrayData userNames; 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("author", author); fields->Set("text", text); diff --git a/lib/perfdata/gelfwriter.cpp b/lib/perfdata/gelfwriter.cpp index 0394befa1..060da2c80 100644 --- a/lib/perfdata/gelfwriter.cpp +++ b/lib/perfdata/gelfwriter.cpp @@ -55,25 +55,24 @@ void GelfWriter::OnConfigLoaded() 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()) { size_t workQueueItems = gelfwriter->m_WorkQueue.GetLength(); double workQueueItemRate = gelfwriter->m_WorkQueue.GetTaskCount(60) / 60.0; - Dictionary::Ptr stats = new Dictionary(); - stats->Set("work_queue_items", workQueueItems); - stats->Set("work_queue_item_rate", workQueueItemRate); - stats->Set("connected", gelfwriter->GetConnected()); - stats->Set("source", gelfwriter->GetSource()); - - nodes->Set(gelfwriter->GetName(), stats); + nodes.emplace_back(gelfwriter->GetName(), new Dictionary({ + { "work_queue_items", workQueueItems }, + { "work_queue_item_rate", workQueueItemRate }, + { "connected", gelfwriter->GetConnected() }, + { "source", gelfwriter->GetSource() } + })); perfdata->Add(new PerfdataValue("gelfwriter_" + gelfwriter->GetName() + "_work_queue_items", workQueueItems)); 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) diff --git a/lib/perfdata/graphitewriter.cpp b/lib/perfdata/graphitewriter.cpp index b21c139d6..320c146fe 100644 --- a/lib/perfdata/graphitewriter.cpp +++ b/lib/perfdata/graphitewriter.cpp @@ -55,24 +55,23 @@ void GraphiteWriter::OnConfigLoaded() 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()) { size_t workQueueItems = graphitewriter->m_WorkQueue.GetLength(); double workQueueItemRate = graphitewriter->m_WorkQueue.GetTaskCount(60) / 60.0; - Dictionary::Ptr stats = new Dictionary(); - stats->Set("work_queue_items", workQueueItems); - stats->Set("work_queue_item_rate", workQueueItemRate); - stats->Set("connected", graphitewriter->GetConnected()); - - nodes->Set(graphitewriter->GetName(), stats); + nodes.emplace_back(graphitewriter->GetName(), new Dictionary({ + { "work_queue_items", workQueueItems }, + { "work_queue_item_rate", workQueueItemRate }, + { "connected", graphitewriter->GetConnected() } + })); perfdata->Add(new PerfdataValue("graphitewriter_" + graphitewriter->GetName() + "_work_queue_items", workQueueItems)); 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) @@ -330,14 +329,14 @@ Value GraphiteWriter::EscapeMacroMetric(const Value& value) { if (value.IsObjectType()) { Array::Ptr arr = value; - Array::Ptr result = new Array(); + ArrayData result; ObjectLock olock(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 return EscapeMetric(value); } diff --git a/lib/perfdata/influxdbwriter.cpp b/lib/perfdata/influxdbwriter.cpp index a61406450..08f126a80 100644 --- a/lib/perfdata/influxdbwriter.cpp +++ b/lib/perfdata/influxdbwriter.cpp @@ -81,26 +81,25 @@ void InfluxdbWriter::OnConfigLoaded() 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()) { size_t workQueueItems = influxdbwriter->m_WorkQueue.GetLength(); double workQueueItemRate = influxdbwriter->m_WorkQueue.GetTaskCount(60) / 60.0; size_t dataBufferItems = influxdbwriter->m_DataBuffer.size(); - Dictionary::Ptr stats = new Dictionary(); - stats->Set("work_queue_items", workQueueItems); - stats->Set("work_queue_item_rate", workQueueItemRate); - stats->Set("data_buffer_items", dataBufferItems); - - nodes->Set(influxdbwriter->GetName(), stats); + nodes.emplace_back(influxdbwriter->GetName(), new Dictionary({ + { "work_queue_items", workQueueItems }, + { "work_queue_item_rate", workQueueItemRate }, + { "data_buffer_items", dataBufferItems } + })); 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() + "_data_queue_items", dataBufferItems)); } - status->Set("influxdbwriter", nodes); + status->Set("influxdbwriter", new Dictionary(std::move(nodes))); } void InfluxdbWriter::Start(bool runtimeCreated) diff --git a/lib/perfdata/influxdbwriter.ti b/lib/perfdata/influxdbwriter.ti index c787bc716..f08edf997 100644 --- a/lib/perfdata/influxdbwriter.ti +++ b/lib/perfdata/influxdbwriter.ti @@ -55,27 +55,23 @@ class InfluxdbWriter : ConfigObject }; [config, required] Dictionary::Ptr host_template { default {{{ - Dictionary::Ptr tags = new Dictionary(); - tags->Set("hostname", "$host.name$"); - - Dictionary::Ptr tmpl = new Dictionary(); - tmpl->Set("measurement", "$host.check_command$"); - tmpl->Set("tags", tags); - - return tmpl; + return new Dictionary({ + { "measurement", "$host.check_command$" }, + { "tags", new Dictionary({ + { "hostname", "$host.name$" } + }) } + }); }}} }; [config, required] Dictionary::Ptr service_template { default {{{ - Dictionary::Ptr tags = new Dictionary(); - tags->Set("hostname", "$host.name$"); - tags->Set("service", "$service.name$"); - - Dictionary::Ptr tmpl = new Dictionary(); - tmpl->Set("measurement", "$service.check_command$"); - tmpl->Set("tags", tags); - - return tmpl; + return new Dictionary({ + { "measurement", "$service.check_command$" }, + { "tags", new Dictionary({ + { "hostname", "$host.name" }, + { "service", "$service.name$" } + }) } + }); }}} }; [config] bool enable_send_thresholds { diff --git a/lib/perfdata/opentsdbwriter.cpp b/lib/perfdata/opentsdbwriter.cpp index 9bbbbfa54..056da7822 100644 --- a/lib/perfdata/opentsdbwriter.cpp +++ b/lib/perfdata/opentsdbwriter.cpp @@ -48,13 +48,13 @@ REGISTER_STATSFUNCTION(OpenTsdbWriter, &OpenTsdbWriter::StatsFunc); void OpenTsdbWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) { - Dictionary::Ptr nodes = new Dictionary(); + DictionaryData nodes; for (const OpenTsdbWriter::Ptr& opentsdbwriter : ConfigType::GetObjectsByType()) { - 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) diff --git a/lib/perfdata/perfdatawriter.cpp b/lib/perfdata/perfdatawriter.cpp index 9d987c7d8..79d0108d7 100644 --- a/lib/perfdata/perfdatawriter.cpp +++ b/lib/perfdata/perfdatawriter.cpp @@ -40,13 +40,13 @@ REGISTER_STATSFUNCTION(PerfdataWriter, &PerfdataWriter::StatsFunc); void PerfdataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) { - Dictionary::Ptr nodes = new Dictionary(); + DictionaryData nodes; for (const PerfdataWriter::Ptr& perfdatawriter : ConfigType::GetObjectsByType()) { - 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) diff --git a/lib/remote/actionshandler.cpp b/lib/remote/actionshandler.cpp index 7663d02be..4ef93f17d 100644 --- a/lib/remote/actionshandler.cpp +++ b/lib/remote/actionshandler.cpp @@ -72,30 +72,33 @@ bool ActionsHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& reques objs.emplace_back(nullptr); } - Array::Ptr results = new Array(); + ArrayData results; Log(LogNotice, "ApiActionHandler") << "Running action " << actionName; for (const ConfigObject::Ptr& obj : objs) { try { - results->Add(action->Invoke(obj, params)); + results.emplace_back(action->Invoke(obj, params)); } catch (const std::exception& ex) { - Dictionary::Ptr fail = new Dictionary(); - fail->Set("code", 500); - fail->Set("status", "Action execution failed: '" + DiagnosticInformation(ex, false) + "'."); + Dictionary::Ptr fail = new Dictionary({ + { "code", 500 }, + { "status", "Action execution failed: '" + DiagnosticInformation(ex, false) + "'." } + }); + if (HttpUtility::GetLastParameter(params, "verboseErrors")) fail->Set("diagnostic information", DiagnosticInformation(ex)); - results->Add(fail); + + results.emplace_back(std::move(fail)); } } - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(results)) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); return true; } - diff --git a/lib/remote/apilistener-configsync.cpp b/lib/remote/apilistener-configsync.cpp index 8107c971a..ebdf60c51 100644 --- a/lib/remote/apilistener-configsync.cpp +++ b/lib/remote/apilistener-configsync.cpp @@ -289,11 +289,14 @@ void ApiListener::UpdateConfigObject(const ConfigObject::Ptr& object, const Mess if (object->GetPackage() != "_api" && object->GetVersion() == 0) return; - Dictionary::Ptr message = new Dictionary(); - message->Set("jsonrpc", "2.0"); - message->Set("method", "config::UpdateObject"); - 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("type", object->GetReflectionType()->GetName()); 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 modified_attributes = new Dictionary(); - Array::Ptr newOriginalAttributes = new Array(); + ArrayData newOriginalAttributes; if (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); - newOriginalAttributes->Add(kv.first); + newOriginalAttributes.push_back(kv.first); } } params->Set("modified_attributes", modified_attributes); /* only send the original attribute keys */ - params->Set("original_attributes", newOriginalAttributes); - - message->Set("params", params); + params->Set("original_attributes", new Array(std::move(newOriginalAttributes))); #ifdef I2_DEBUG 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 message = new Dictionary({ + { "jsonrpc", "2.0" }, + { "method", "config::DeleteObject" }, + { "params", params } + }); + params->Set("name", object->GetName()); params->Set("type", object->GetReflectionType()->GetName()); params->Set("version", object->GetVersion()); - message->Set("params", params); #ifdef I2_DEBUG Log(LogDebug, "ApiListener") diff --git a/lib/remote/apilistener-filesync.cpp b/lib/remote/apilistener-filesync.cpp index 1ce23b102..30a79a35f 100644 --- a/lib/remote/apilistener-filesync.cpp +++ b/lib/remote/apilistener-filesync.cpp @@ -260,14 +260,14 @@ void ApiListener::SendConfigUpdate(const JsonRpcConnection::Ptr& aclient) configUpdateV2->Set(zone->GetName(), config.UpdateV2); } - Dictionary::Ptr params = new Dictionary(); - params->Set("update", configUpdateV1); - params->Set("update_v2", configUpdateV2); - - Dictionary::Ptr message = new Dictionary(); - message->Set("jsonrpc", "2.0"); - message->Set("method", "config::Update"); - message->Set("params", params); + Dictionary::Ptr message = new Dictionary({ + { "jsonrpc", "2.0" }, + { "method", "config::Update" }, + { "params", new Dictionary({ + { "update", configUpdateV1 }, + { "update_v2", configUpdateV2 } + }) } + }); aclient->SendMessage(message); } diff --git a/lib/remote/apilistener.cpp b/lib/remote/apilistener.cpp index 65ad4d64c..527036e0a 100644 --- a/lib/remote/apilistener.cpp +++ b/lib/remote/apilistener.cpp @@ -503,10 +503,12 @@ void ApiListener::NewClientHandlerInternal(const Socket::Ptr& client, const Stri ClientType ctype; if (role == RoleClient) { - Dictionary::Ptr message = new Dictionary(); - message->Set("jsonrpc", "2.0"); - message->Set("method", "icinga::Hello"); - message->Set("params", new Dictionary()); + Dictionary::Ptr message = new Dictionary({ + { "jsonrpc", "2.0" }, + { "method", "icinga::Hello" }, + { "params", new Dictionary() } + }); + JsonRpc::SendMessage(tlsStream, message); ctype = ClientJsonRpc; } else { @@ -666,13 +668,13 @@ void ApiListener::ApiTimerHandler() if (ts == 0) continue; - Dictionary::Ptr lparams = new Dictionary(); - lparams->Set("log_position", ts); - - Dictionary::Ptr lmessage = new Dictionary(); - lmessage->Set("jsonrpc", "2.0"); - lmessage->Set("method", "log::SetLogPosition"); - lmessage->Set("params", lparams); + Dictionary::Ptr lmessage = new Dictionary({ + { "jsonrpc", "2.0" }, + { "method", "log::SetLogPosition" }, + { "params", new Dictionary({ + { "log_position", ts } + }) } + }); double maxTs = 0; @@ -1161,13 +1163,13 @@ void ApiListener::ReplayLog(const JsonRpcConnection::Ptr& client) if (ts > logpos_ts + 10) { logpos_ts = ts; - Dictionary::Ptr lparams = new Dictionary(); - lparams->Set("log_position", logpos_ts); - - Dictionary::Ptr lmessage = new Dictionary(); - lmessage->Set("jsonrpc", "2.0"); - lmessage->Set("method", "log::SetLogPosition"); - lmessage->Set("params", lparams); + Dictionary::Ptr lmessage = new Dictionary({ + { "jsonrpc", "2.0" }, + { "method", "log::SetLogPosition" }, + { "params", new Dictionary({ + { "log_position", logpos_ts } + }) } + }); size_t bytesSent = JsonRpc::SendMessage(client->GetStream(), lmessage); endpoint->AddMessageSent(bytesSent); @@ -1218,11 +1220,9 @@ void ApiListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& per std::pair ApiListener::GetStatus() { - Dictionary::Ptr status = new Dictionary(); Dictionary::Ptr perfdata = new Dictionary(); /* cluster stats */ - status->Set("identity", GetIdentity()); double allEndpoints = 0; Array::Ptr allNotConnectedEndpoints = new Array(); @@ -1244,10 +1244,10 @@ std::pair ApiListener::GetStatus() int countZoneEndpoints = 0; double zoneLag = 0; - Array::Ptr zoneEndpoints = new Array(); + ArrayData zoneEndpoints; for (const Endpoint::Ptr& endpoint : zone->GetEndpoints()) { - zoneEndpoints->Add(endpoint->GetName()); + zoneEndpoints.emplace_back(endpoint->GetName()); if (endpoint->GetName() == GetIdentity()) continue; @@ -1272,29 +1272,21 @@ std::pair ApiListener::GetStatus() if (zone->GetEndpoints().size() == 1 && countZoneEndpoints == 0) zoneConnected = true; - Dictionary::Ptr zoneStats = new Dictionary(); - zoneStats->Set("connected", zoneConnected); - zoneStats->Set("client_log_lag", zoneLag); - zoneStats->Set("endpoints", zoneEndpoints); - String parentZoneName; Zone::Ptr parentZone = zone->GetParent(); if (parentZone) 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); } - 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 */ size_t jsonRpcClients = GetAnonymousClients().size(); size_t httpClients = GetHttpClients().size(); @@ -1306,22 +1298,31 @@ std::pair ApiListener::GetStatus() double syncQueueItemRate = m_SyncQueue.GetTaskCount(60) / 60.0; double relayQueueItemRate = m_RelayQueue.GetTaskCount(60) / 60.0; - Dictionary::Ptr jsonRpc = new Dictionary(); - jsonRpc->Set("clients", jsonRpcClients); - jsonRpc->Set("work_queue_items", workQueueItems); - jsonRpc->Set("work_queue_count", workQueueCount); - jsonRpc->Set("sync_queue_items", syncQueueItems); - jsonRpc->Set("relay_queue_items", relayQueueItems); - - jsonRpc->Set("work_queue_item_rate", workQueueItemRate); - jsonRpc->Set("sync_queue_item_rate", syncQueueItemRate); - jsonRpc->Set("relay_queue_item_rate", relayQueueItemRate); - - Dictionary::Ptr http = new Dictionary(); - http->Set("clients", httpClients); - - status->Set("json_rpc", jsonRpc); - status->Set("http", http); + Dictionary::Ptr status = new Dictionary({ + { "identity", GetIdentity() }, + { "num_endpoints", allEndpoints }, + { "num_conn_endpoints", allConnectedEndpoints->GetLength() }, + { "num_not_conn_endpoints", allNotConnectedEndpoints->GetLength() }, + { "conn_endpoints", allConnectedEndpoints }, + { "not_conn_endpoints", allNotConnectedEndpoints }, + + { "zones", connectedZones }, + + { "json_rpc", new Dictionary({ + { "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 } + }) }, + + { "http", new Dictionary({ + { "clients", httpClients } + }) } + }); /* performance data */ perfdata->Set("num_endpoints", allEndpoints); diff --git a/lib/remote/configpackageshandler.cpp b/lib/remote/configpackageshandler.cpp index 68cb5dd9d..2d8be3c22 100644 --- a/lib/remote/configpackageshandler.cpp +++ b/lib/remote/configpackageshandler.cpp @@ -51,21 +51,22 @@ void ConfigPackagesHandler::HandleGet(const ApiUser::Ptr& user, HttpRequest& req std::vector packages = ConfigPackageUtility::GetPackages(); - Array::Ptr results = new Array(); + ArrayData results; { boost::mutex::scoped_lock lock(ConfigPackageUtility::GetStaticMutex()); for (const String& package : packages) { - Dictionary::Ptr packageInfo = new Dictionary(); - packageInfo->Set("name", package); - packageInfo->Set("stages", Array::FromVector(ConfigPackageUtility::GetStages(package))); - packageInfo->Set("active-stage", ConfigPackageUtility::GetActiveStage(package)); - results->Add(packageInfo); + results.emplace_back(new Dictionary({ + { "name", package }, + { "stages", Array::FromVector(ConfigPackageUtility::GetStages(package)) }, + { "active-stage", ConfigPackageUtility::GetActiveStage(package) } + })); } } - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(results)) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); @@ -85,8 +86,6 @@ void ConfigPackagesHandler::HandlePost(const ApiUser::Ptr& user, HttpRequest& re return; } - Dictionary::Ptr result1 = new Dictionary(); - try { boost::mutex::scoped_lock lock(ConfigPackageUtility::GetStaticMutex()); ConfigPackageUtility::CreatePackage(packageName); @@ -96,14 +95,14 @@ void ConfigPackagesHandler::HandlePost(const ApiUser::Ptr& user, HttpRequest& re return; } - result1->Set("code", 200); - result1->Set("status", "Created package."); - - Array::Ptr results = new Array(); - results->Add(result1); + Dictionary::Ptr result1 = new Dictionary({ + { "code", 200 }, + { "status", "Created package." } + }); - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array({ result1 }) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); @@ -125,7 +124,7 @@ void ConfigPackagesHandler::HandleDelete(const ApiUser::Ptr& user, HttpRequest& int code = 200; String status = "Deleted package."; - Dictionary::Ptr result1 = new Dictionary(); + DictionaryData result1; try { ConfigPackageUtility::DeletePackage(packageName); @@ -133,21 +132,17 @@ void ConfigPackagesHandler::HandleDelete(const ApiUser::Ptr& user, HttpRequest& code = 500; status = "Failed to delete package."; 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); - result1->Set("code", code); - result1->Set("status", status); - - Array::Ptr results = new Array(); - results->Add(result1); - - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array({ new Dictionary(std::move(result1)) }) } + }); response.SetStatus(code, (code == 200) ? "OK" : "Internal Server Error"); HttpUtility::SendJsonBody(response, params, result); } - diff --git a/lib/remote/configpackageutility.cpp b/lib/remote/configpackageutility.cpp index 889404491..9470d4b24 100644 --- a/lib/remote/configpackageutility.cpp +++ b/lib/remote/configpackageutility.cpp @@ -208,12 +208,13 @@ void ConfigPackageUtility::AsyncTryActivateStage(const String& packageName, cons VERIFY(Application::GetArgC() >= 1); // prepare arguments - Array::Ptr args = new Array(); - args->Add(Application::GetExePath(Application::GetArgV()[0])); - args->Add("daemon"); - args->Add("--validate"); - args->Add("--define"); - args->Add("ActiveStageOverride=" + packageName + ":" + stageName); + Array::Ptr args = new Array({ + Application::GetExePath(Application::GetArgV()[0]), + "daemon", + "--validate", + "--define", + "ActiveStageOverride=" + packageName + ":" + stageName + }); Process::Ptr process = new Process(Process::PrepareCommand(args)); process->SetTimeout(300); diff --git a/lib/remote/configstageshandler.cpp b/lib/remote/configstageshandler.cpp index 56110a71a..ecfc973c2 100644 --- a/lib/remote/configstageshandler.cpp +++ b/lib/remote/configstageshandler.cpp @@ -65,22 +65,22 @@ void ConfigStagesHandler::HandleGet(const ApiUser::Ptr& user, HttpRequest& reque if (!ConfigPackageUtility::ValidateName(stageName)) return HttpUtility::SendJsonError(response, params, 400, "Invalid stage name."); - Array::Ptr results = new Array(); + ArrayData results; std::vector > paths = ConfigPackageUtility::GetFiles(packageName, stageName); String prefixPath = ConfigPackageUtility::GetPackageDir() + "/" + packageName + "/" + stageName + "/"; - typedef std::pair kv_pair; - for (const kv_pair& kv : paths) { - Dictionary::Ptr stageInfo = new Dictionary(); - stageInfo->Set("type", (kv.second ? "directory" : "file")); - stageInfo->Set("name", kv.first.SubStr(prefixPath.GetLength())); - results->Add(stageInfo); + for (const auto& kv : paths) { + results.push_back(new Dictionary({ + { "type", kv.second ? "directory" : "file" }, + { "name", kv.first.SubStr(prefixPath.GetLength()) } + })); } - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(results)) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); @@ -121,21 +121,20 @@ void ConfigStagesHandler::HandlePost(const ApiUser::Ptr& user, HttpRequest& requ HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : ""); } - Dictionary::Ptr result1 = new Dictionary(); String responseStatus = "Created stage. "; responseStatus += (reload ? " Icinga2 will reload." : " Icinga2 reload skipped."); - result1->Set("package", packageName); - result1->Set("stage", stageName); - result1->Set("code", 200); - result1->Set("status", responseStatus); + Dictionary::Ptr result1 = new Dictionary({ + { "package", packageName }, + { "stage", stageName }, + { "code", 200 }, + { "status", responseStatus } + }); - Array::Ptr results = new Array(); - results->Add(result1); - - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array({ result1 }) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); @@ -168,16 +167,14 @@ void ConfigStagesHandler::HandleDelete(const ApiUser::Ptr& user, HttpRequest& re HttpUtility::GetLastParameter(params, "verboseErrors") ? DiagnosticInformation(ex) : ""); } - Dictionary::Ptr result1 = new Dictionary(); - - result1->Set("code", 200); - result1->Set("status", "Stage deleted."); - - Array::Ptr results = new Array(); - results->Add(result1); + Dictionary::Ptr result1 = new Dictionary({ + { "code", 200 }, + { "status", "Stage deleted." } + }); - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array({ result1 }) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); diff --git a/lib/remote/consolehandler.cpp b/lib/remote/consolehandler.cpp index 575db34bd..d2cec89e7 100644 --- a/lib/remote/consolehandler.cpp +++ b/lib/remote/consolehandler.cpp @@ -121,8 +121,7 @@ bool ConsoleHandler::ExecuteScriptHelper(HttpRequest& request, HttpResponse& res lsf.Lines[fileName] = command; - Array::Ptr results = new Array(); - Dictionary::Ptr resultInfo = new Dictionary(); + Dictionary::Ptr resultInfo; std::unique_ptr expr; Value exprResult; @@ -136,9 +135,11 @@ bool ConsoleHandler::ExecuteScriptHelper(HttpRequest& request, HttpResponse& res exprResult = expr->Evaluate(frame); - resultInfo->Set("code", 200); - resultInfo->Set("status", "Executed successfully."); - resultInfo->Set("result", Serialize(exprResult, 0)); + resultInfo = new Dictionary({ + { "code", 200 }, + { "status", "Executed successfully." }, + { "result", Serialize(exprResult, 0) } + }); } catch (const ScriptError& ex) { 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" << ex.what() << "\n"; - resultInfo->Set("code", 500); - resultInfo->Set("status", String(msgbuf.str())); - resultInfo->Set("incomplete_expression", ex.IsIncompleteExpression()); - - Dictionary::Ptr debugInfo = new Dictionary(); - debugInfo->Set("path", di.Path); - debugInfo->Set("first_line", di.FirstLine); - debugInfo->Set("first_column", di.FirstColumn); - debugInfo->Set("last_line", di.LastLine); - debugInfo->Set("last_column", di.LastColumn); - resultInfo->Set("debug_info", debugInfo); + resultInfo = new Dictionary({ + { "code", 500 }, + { "status", String(msgbuf.str()) }, + { "incomplete_expression", ex.IsIncompleteExpression() }, + { "debug_info", new Dictionary({ + { "path", di.Path }, + { "first_line", di.FirstLine }, + { "first_column", di.FirstColumn }, + { "last_line", di.LastLine }, + { "last_column", di.LastColumn } + }) } + }); } - results->Add(resultInfo); - - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array({ resultInfo }) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); @@ -187,22 +188,21 @@ bool ConsoleHandler::AutocompleteScriptHelper(HttpRequest& request, HttpResponse if (!lsf.Locals) lsf.Locals = new Dictionary(); - Array::Ptr results = new Array(); - Dictionary::Ptr resultInfo = new Dictionary(); ScriptFrame frame(true); frame.Locals = lsf.Locals; frame.Self = lsf.Locals; frame.Sandboxed = sandboxed; - resultInfo->Set("code", 200); - resultInfo->Set("status", "Auto-completed successfully."); - resultInfo->Set("suggestions", Array::FromVector(GetAutocompletionSuggestions(command, frame))); - - results->Add(resultInfo); + Dictionary::Ptr result1 = new Dictionary({ + { "code", 200 }, + { "status", "Auto-completed successfully." }, + { "suggestions", Array::FromVector(GetAutocompletionSuggestions(command, frame)) } + }); - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array({ result1 }) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); diff --git a/lib/remote/createobjecthandler.cpp b/lib/remote/createobjecthandler.cpp index 6455a8af6..0cf505e28 100644 --- a/lib/remote/createobjecthandler.cpp +++ b/lib/remote/createobjecthandler.cpp @@ -64,8 +64,9 @@ bool CreateObjectHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& r localZoneName = localZone->GetName(); if (!attrs) { - attrs = new Dictionary(); - attrs->Set("zone", localZoneName); + attrs = new Dictionary({ + { "zone", localZoneName } + }); } else if (!attrs->Contains("zone")) { attrs->Set("zone", localZoneName); } @@ -80,11 +81,9 @@ bool CreateObjectHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& r if (params->Contains("ignore_on_error")) ignoreOnError = HttpUtility::GetLastParameter(params, "ignore_on_error"); - Array::Ptr results = new Array(); - results->Add(result1); - - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array({ result1 }) } + }); String config; @@ -129,4 +128,3 @@ bool CreateObjectHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& r return true; } - diff --git a/lib/remote/deleteobjecthandler.cpp b/lib/remote/deleteobjecthandler.cpp index daa5685e3..b631b6598 100644 --- a/lib/remote/deleteobjecthandler.cpp +++ b/lib/remote/deleteobjecthandler.cpp @@ -72,31 +72,36 @@ bool DeleteObjectHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& r bool cascade = HttpUtility::GetLastParameter(params, "cascade"); - Array::Ptr results = new Array(); + ArrayData results; bool success = true; for (const ConfigObject::Ptr& obj : objs) { - Dictionary::Ptr result1 = new Dictionary(); - result1->Set("type", type->GetName()); - result1->Set("name", obj->GetName()); - results->Add(result1); - + int code; + String status; Array::Ptr errors = new Array(); if (!ConfigObjectUtility::DeleteObject(obj, cascade, errors)) { - result1->Set("code", 500); - result1->Set("status", "Object could not be deleted."); - result1->Set("errors", errors); + code = 500; + status = "Object could not be deleted."; success = false; } else { - result1->Set("code", 200); - result1->Set("status", "Object was deleted."); + code = 200; + status = "Object was deleted."; } + + results.push_back(new Dictionary({ + { "type", type->GetName() }, + { "name", obj->GetName() }, + { "code", code }, + { "status", status }, + { "errors", errors } + })); } - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(results)) } + }); if (!success) response.SetStatus(500, "One or more objects could not be deleted"); diff --git a/lib/remote/httpserverconnection.cpp b/lib/remote/httpserverconnection.cpp index ce3bcd22c..1b19635a4 100644 --- a/lib/remote/httpserverconnection.cpp +++ b/lib/remote/httpserverconnection.cpp @@ -226,10 +226,10 @@ void HttpServerConnection::ProcessMessageAsync(HttpRequest& request) response.AddHeader("WWW-Authenticate", "Basic realm=\"Icinga 2\""); if (request.Headers->Get("accept") == "application/json") { - Dictionary::Ptr result = new Dictionary(); - - result->Set("error", 401); - result->Set("status", "Unauthorized. Please check your user credentials."); + Dictionary::Ptr result = new Dictionary({ + { "error", 401 }, + { "status", "Unauthorized. Please check your user credentials." } + }); HttpUtility::SendJsonBody(response, nullptr, result); } else { @@ -248,10 +248,10 @@ void HttpServerConnection::ProcessMessageAsync(HttpRequest& request) String errorInfo = DiagnosticInformation(ex); if (request.Headers->Get("accept") == "application/json") { - Dictionary::Ptr result = new Dictionary(); - - result->Set("error", 503); - result->Set("status", errorInfo); + Dictionary::Ptr result = new Dictionary({ + { "error", 503 }, + { "status", errorInfo } + }); HttpUtility::SendJsonBody(response, nullptr, result); } else { diff --git a/lib/remote/infohandler.cpp b/lib/remote/infohandler.cpp index c36546453..5336c84cf 100644 --- a/lib/remote/infohandler.cpp +++ b/lib/remote/infohandler.cpp @@ -67,18 +67,16 @@ bool InfoHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& request, } if (request.Headers->Get("accept") == "application/json") { - Dictionary::Ptr result1 = new Dictionary(); - - result1->Set("user", user->GetName()); - result1->Set("permissions", Array::FromVector(permInfo)); - result1->Set("version", Application::GetAppVersion()); - result1->Set("info", "More information about API requests is available in the documentation at https://docs.icinga.com/icinga2/latest."); - - Array::Ptr results = new Array(); - results->Add(result1); - - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result1 = new Dictionary({ + { "user", user->GetName() }, + { "permissions", Array::FromVector(permInfo) }, + { "version", Application::GetAppVersion() }, + { "info", "More information about API requests is available in the documentation at https://docs.icinga.com/icinga2/latest." } + }); + + Dictionary::Ptr result = new Dictionary({ + { "results", new Array({ result1 }) } + }); HttpUtility::SendJsonBody(response, params, result); } else { diff --git a/lib/remote/jsonrpcconnection-heartbeat.cpp b/lib/remote/jsonrpcconnection-heartbeat.cpp index 349103a19..12b0d0c53 100644 --- a/lib/remote/jsonrpcconnection-heartbeat.cpp +++ b/lib/remote/jsonrpcconnection-heartbeat.cpp @@ -42,14 +42,13 @@ void JsonRpcConnection::HeartbeatTimerHandler() continue; } - Dictionary::Ptr request = new Dictionary(); - request->Set("jsonrpc", "2.0"); - request->Set("method", "event::Heartbeat"); - - Dictionary::Ptr params = new Dictionary(); - params->Set("timeout", 120); - - request->Set("params", params); + Dictionary::Ptr request = new Dictionary({ + { "jsonrpc", "2.0" }, + { "method", "event::Heartbeat" }, + { "params", new Dictionary({ + { "timeout", 120 } + }) } + }); client->SendMessage(request); } diff --git a/lib/remote/jsonrpcconnection-pki.cpp b/lib/remote/jsonrpcconnection-pki.cpp index 43543466c..31fa9078a 100644 --- a/lib/remote/jsonrpcconnection-pki.cpp +++ b/lib/remote/jsonrpcconnection-pki.cpp @@ -127,10 +127,11 @@ Value RequestCertificateHandler(const MessageOrigin::Ptr& origin, const Dictiona result->Set("cert", certResponse); result->Set("status_code", 0); - Dictionary::Ptr message = new Dictionary(); - message->Set("jsonrpc", "2.0"); - message->Set("method", "pki::UpdateCertificate"); - message->Set("params", result); + Dictionary::Ptr message = new Dictionary({ + { "jsonrpc", "2.0" }, + { "method", "pki::UpdateCertificate" }, + { "params", result } + }); JsonRpc::SendMessage(client->GetStream(), message); return result; @@ -197,10 +198,11 @@ Value RequestCertificateHandler(const MessageOrigin::Ptr& origin, const Dictiona result->Set("status_code", 0); - message = new Dictionary(); - message->Set("jsonrpc", "2.0"); - message->Set("method", "pki::UpdateCertificate"); - message->Set("params", result); + message = new Dictionary({ + { "jsonrpc", "2.0" }, + { "method", "pki::UpdateCertificate" }, + { "params", result } + }); JsonRpc::SendMessage(client->GetStream(), message); return result; @@ -209,9 +211,10 @@ delayed_request: /* Send a delayed certificate signing request. */ Utility::MkDirP(requestDir, 0700); - Dictionary::Ptr request = new Dictionary(); - request->Set("cert_request", CertificateToString(cert)); - request->Set("ticket", params->Get("ticket")); + Dictionary::Ptr request = new Dictionary({ + { "cert_request", CertificateToString(cert) }, + { "ticket", params->Get("ticket") } + }); Utility::SaveJsonFile(requestPath, 0600, request); diff --git a/lib/remote/modifyobjecthandler.cpp b/lib/remote/modifyobjecthandler.cpp index 65e59fcf0..5e664eca3 100644 --- a/lib/remote/modifyobjecthandler.cpp +++ b/lib/remote/modifyobjecthandler.cpp @@ -78,7 +78,7 @@ bool ModifyObjectHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& r Dictionary::Ptr attrs = attrsVal; - Array::Ptr results = new Array(); + ArrayData results; for (const ConfigObject::Ptr& obj : objs) { Dictionary::Ptr result1 = new Dictionary(); @@ -104,11 +104,12 @@ bool ModifyObjectHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& r result1->Set("status", "Attribute '" + key + "' could not be set: " + DiagnosticInformation(ex)); } - results->Add(result1); + results.push_back(std::move(result1)); } - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(results)) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); diff --git a/lib/remote/objectqueryhandler.cpp b/lib/remote/objectqueryhandler.cpp index 90520a9e6..8bb434a80 100644 --- a/lib/remote/objectqueryhandler.cpp +++ b/lib/remote/objectqueryhandler.cpp @@ -81,10 +81,10 @@ Dictionary::Ptr ObjectQueryHandler::SerializeObjectAttrs(const Object::Ptr& obje } } - Dictionary::Ptr resultAttrs = new Dictionary(); + DictionaryData resultAttrs; + resultAttrs.reserve(fids.size()); - for (int fid : fids) - { + for (int fid : fids) { Field field = type->GetFieldInfo(fid); Value val = object->GetField(fid); @@ -98,10 +98,10 @@ Dictionary::Ptr ObjectQueryHandler::SerializeObjectAttrs(const Object::Ptr& obje continue; Value sval = Serialize(val, FAConfig | FAState); - resultAttrs->Set(field.Name, sval); + resultAttrs.emplace_back(field.Name, sval); } - return resultAttrs; + return new Dictionary(std::move(resultAttrs)); } bool ObjectQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& request, HttpResponse& response, const Dictionary::Ptr& params) @@ -170,8 +170,8 @@ bool ObjectQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& re return true; } - Array::Ptr results = new Array(); - results->Reserve(objs.size()); + ArrayData results; + results.reserve(objs.size()); std::set joinAttrs; std::set userJoinAttrs; @@ -196,21 +196,19 @@ bool ObjectQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& re } for (const ConfigObject::Ptr& obj : objs) { - Dictionary::Ptr result1 = new Dictionary(); - results->Add(result1); + DictionaryData result1{ + { "name", obj->GetName() }, + { "type", obj->GetReflectionType()->GetName() } + }; - result1->Set("name", obj->GetName()); - result1->Set("type", obj->GetReflectionType()->GetName()); - - Dictionary::Ptr metaAttrs = new Dictionary(); - result1->Set("meta", metaAttrs); + DictionaryData metaAttrs; if (umetas) { ObjectLock olock(umetas); for (const String& meta : umetas) { if (meta == "used_by") { Array::Ptr used_by = new Array(); - metaAttrs->Set("used_by", used_by); + metaAttrs.emplace_back("used_by", used_by); for (const Object::Ptr& pobj : DependencyGraph::GetParents((obj))) { @@ -219,20 +217,13 @@ bool ObjectQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& re if (!configObj) continue; - Dictionary::Ptr refInfo = new Dictionary(); - refInfo->Set("type", configObj->GetReflectionType()->GetName()); - refInfo->Set("name", configObj->GetName()); - used_by->Add(refInfo); + used_by->Add(new Dictionary({ + { "type", configObj->GetReflectionType()->GetName() }, + { "name", configObj->GetName() } + })); } } else if (meta == "location") { - DebugInfo di = obj->GetDebugInfo(); - Dictionary::Ptr dinfo = new Dictionary(); - dinfo->Set("path", di.Path); - dinfo->Set("first_line", di.FirstLine); - dinfo->Set("first_column", di.FirstColumn); - dinfo->Set("last_line", di.LastLine); - dinfo->Set("last_column", di.LastColumn); - metaAttrs->Set("location", dinfo); + metaAttrs.emplace_back("location", obj->GetSourceLocation()); } else { HttpUtility::SendJsonError(response, params, 400, "Invalid field specified for meta: " + meta); return true; @@ -240,15 +231,16 @@ bool ObjectQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& re } } + result1.emplace_back("meta", new Dictionary(std::move(metaAttrs))); + try { - result1->Set("attrs", SerializeObjectAttrs(obj, String(), uattrs, false, false)); + result1.emplace_back("attrs", SerializeObjectAttrs(obj, String(), uattrs, false, false)); } catch (const ScriptError& ex) { HttpUtility::SendJsonError(response, params, 400, ex.what()); return true; } - Dictionary::Ptr joins = new Dictionary(); - result1->Set("joins", joins); + DictionaryData joins; for (const String& joinAttr : joinAttrs) { Object::Ptr joinedObj; @@ -274,16 +266,21 @@ bool ObjectQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& re String prefix = field.NavigationName; try { - joins->Set(prefix, SerializeObjectAttrs(joinedObj, prefix, ujoins, true, allJoins)); + joins.emplace_back(prefix, SerializeObjectAttrs(joinedObj, prefix, ujoins, true, allJoins)); } catch (const ScriptError& ex) { HttpUtility::SendJsonError(response, params, 400, ex.what()); return true; } } + + result1.emplace_back("joins", new Dictionary(std::move(joins))); + + results.push_back(new Dictionary(std::move(result1))); } - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(results)) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); diff --git a/lib/remote/pkiutility.cpp b/lib/remote/pkiutility.cpp index 2d3232d2e..6b896dab1 100644 --- a/lib/remote/pkiutility.cpp +++ b/lib/remote/pkiutility.cpp @@ -197,18 +197,18 @@ int PkiUtility::RequestCertificate(const String& host, const String& port, const return 1; } - Dictionary::Ptr request = new Dictionary(); + Dictionary::Ptr params = new Dictionary({ + { "ticket", String(ticket) } + }); String msgid = Utility::NewUniqueID(); - request->Set("jsonrpc", "2.0"); - request->Set("id", msgid); - request->Set("method", "pki::RequestCertificate"); - - Dictionary::Ptr params = new Dictionary(); - params->Set("ticket", String(ticket)); - - request->Set("params", params); + Dictionary::Ptr request = new Dictionary({ + { "jsonrpc", "2.0" }, + { "id", msgid }, + { "method", "pki::RequestCertificate" }, + { "params", params } + }); JsonRpc::SendMessage(stream, request); diff --git a/lib/remote/statushandler.cpp b/lib/remote/statushandler.cpp index a489a3e25..e2c85c2b1 100644 --- a/lib/remote/statushandler.cpp +++ b/lib/remote/statushandler.cpp @@ -57,17 +57,15 @@ public: if (!func) BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid status function name.")); - Dictionary::Ptr result = new Dictionary(); - Dictionary::Ptr status = new Dictionary(); Array::Ptr perfdata = new Array(); func->Invoke({ status, perfdata }); - result->Set("name", name); - result->Set("status", status); - result->Set("perfdata", Serialize(perfdata, FAState)); - - return result; + return new Dictionary({ + { "name", name }, + { "status", status }, + { "perfdata", Serialize(perfdata, FAState) } + }); } bool IsValidType(const String& type) const override @@ -110,10 +108,9 @@ bool StatusHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& request return true; } - Array::Ptr results = Array::FromVector(objs); - - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(objs)) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); diff --git a/lib/remote/templatequeryhandler.cpp b/lib/remote/templatequeryhandler.cpp index c8d101c1e..d0bd35964 100644 --- a/lib/remote/templatequeryhandler.cpp +++ b/lib/remote/templatequeryhandler.cpp @@ -38,20 +38,19 @@ public: static Dictionary::Ptr GetTargetForTemplate(const ConfigItem::Ptr& item) { - Dictionary::Ptr target = new Dictionary(); - target->Set("name", item->GetName()); - target->Set("type", item->GetType()->GetName()); - DebugInfo di = item->GetDebugInfo(); - Dictionary::Ptr dinfo = new Dictionary(); - dinfo->Set("path", di.Path); - dinfo->Set("first_line", di.FirstLine); - dinfo->Set("first_column", di.FirstColumn); - dinfo->Set("last_line", di.LastLine); - dinfo->Set("last_column", di.LastColumn); - target->Set("location", dinfo); - - return target; + + return new Dictionary({ + { "name", item->GetName() }, + { "type", item->GetType()->GetName() }, + { "location", new Dictionary({ + { "path", di.Path }, + { "first_line", di.FirstLine }, + { "first_column", di.FirstColumn }, + { "last_line", di.LastLine }, + { "last_column", di.LastColumn } + }) } + }); } void FindTargets(const String& type, @@ -132,18 +131,12 @@ bool TemplateQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& return true; } - Array::Ptr results = new Array(); - - for (const Dictionary::Ptr& obj : objs) { - results->Add(obj); - } - - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(objs)) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); return true; } - diff --git a/lib/remote/typequeryhandler.cpp b/lib/remote/typequeryhandler.cpp index 70427c2f2..0f26d998f 100644 --- a/lib/remote/typequeryhandler.cpp +++ b/lib/remote/typequeryhandler.cpp @@ -96,11 +96,11 @@ bool TypeQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& requ return true; } - Array::Ptr results = new Array(); + ArrayData results; for (const Type::Ptr& obj : objs) { Dictionary::Ptr result1 = new Dictionary(); - results->Add(result1); + results.push_back(result1); Dictionary::Ptr resultAttrs = new Dictionary(); result1->Set("name", obj->GetName()); @@ -140,25 +140,24 @@ bool TypeQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& requ fieldInfo->Set("navigation_name", field.NavigationName); fieldInfo->Set("array_rank", field.ArrayRank); - Dictionary::Ptr attributeInfo = new Dictionary(); - fieldInfo->Set("attributes", attributeInfo); - - attributeInfo->Set("config", static_cast(field.Attributes & FAConfig)); - attributeInfo->Set("state", static_cast(field.Attributes & FAState)); - attributeInfo->Set("required", static_cast(field.Attributes & FARequired)); - attributeInfo->Set("navigation", static_cast(field.Attributes & FANavigation)); - attributeInfo->Set("no_user_modify", static_cast(field.Attributes & FANoUserModify)); - attributeInfo->Set("no_user_view", static_cast(field.Attributes & FANoUserView)); - attributeInfo->Set("deprecated", static_cast(field.Attributes & FADeprecated)); + fieldInfo->Set("attributes", new Dictionary({ + { "config", static_cast(field.Attributes & FAConfig) }, + { "state", static_cast(field.Attributes & FAState) }, + { "required", static_cast(field.Attributes & FARequired) }, + { "navigation", static_cast(field.Attributes & FANavigation) }, + { "no_user_modify", static_cast(field.Attributes & FANoUserModify) }, + { "no_user_view", static_cast(field.Attributes & FANoUserView) }, + { "deprecated", static_cast(field.Attributes & FADeprecated) } + })); } } - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(results)) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result); return true; } - diff --git a/lib/remote/variablequeryhandler.cpp b/lib/remote/variablequeryhandler.cpp index 6a601a4c2..512d3925a 100644 --- a/lib/remote/variablequeryhandler.cpp +++ b/lib/remote/variablequeryhandler.cpp @@ -38,11 +38,11 @@ public: static Dictionary::Ptr GetTargetForVar(const String& name, const Value& value) { - Dictionary::Ptr target = new Dictionary(); - target->Set("name", name); - target->Set("type", value.GetReflectionType()->GetName()); - target->Set("value", value); - return target; + return new Dictionary({ + { "name", name }, + { "type", value.GetReflectionType()->GetName() }, + { "value", value } + }); } void FindTargets(const String& type, @@ -102,20 +102,19 @@ bool VariableQueryHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& return true; } - Array::Ptr results = new Array(); + ArrayData results; for (const Dictionary::Ptr& var : objs) { - Dictionary::Ptr result1 = new Dictionary(); - results->Add(result1); - - Dictionary::Ptr resultAttrs = new Dictionary(); - result1->Set("name", var->Get("name")); - result1->Set("type", var->Get("type")); - result1->Set("value", Serialize(var->Get("value"), 0)); + results.emplace_back(new Dictionary({ + { "name", var->Get("name") }, + { "type", var->Get("type") }, + { "value", Serialize(var->Get("value"), 0) } + })); } - Dictionary::Ptr result = new Dictionary(); - result->Set("results", results); + Dictionary::Ptr result = new Dictionary({ + { "results", new Array(std::move(results)) } + }); response.SetStatus(200, "OK"); HttpUtility::SendJsonBody(response, params, result);