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);
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)
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)
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;
}
REGISTER_PRIMITIVE_TYPE(Array, Object, Array::GetPrototype());
+Array::Array(const ArrayData& other)
+ : m_Data(other)
+{ }
+
+Array::Array(ArrayData&& other)
+ : m_Data(std::move(other))
+{ }
+
Array::Array(std::initializer_list<Value> init)
: m_Data(init)
{ }
*/
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
{
return x->End();
}
-
namespace icinga
{
+typedef std::vector<Value> ArrayData;
+
/**
* An array of Value items.
*
typedef std::vector<Value>::size_type SizeType;
Array() = default;
+ Array(const ArrayData& other);
+ Array(ArrayData&& other);
Array(std::initializer_list<Value> init);
Value Get(SizeType index) const;
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;
}
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;
}
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);
{
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()
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;
}
{
ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
Dictionary::Ptr self = static_cast<Dictionary::Ptr>(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<Dictionary::Ptr>(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;
}
REGISTER_PRIMITIVE_TYPE(Dictionary, Object, Dictionary::GetPrototype());
+Dictionary::Dictionary(const DictionaryData& other)
+{
+ for (const auto& kv : other)
+ m_Data.emplace(kv);
+}
+
+Dictionary::Dictionary(DictionaryData&& other)
+{
+ for (auto& kv : other)
+ m_Data.emplace(std::move(kv));
+}
+
+Dictionary::Dictionary(std::initializer_list<Dictionary::Pair> init)
+ : m_Data(init)
+{ }
+
/**
* Retrieves a value from a dictionary.
*
*/
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));
}
/**
namespace icinga
{
+typedef std::vector<std::pair<String, Value> > DictionaryData;
+
/**
* A container that holds key-value pairs.
*
typedef std::map<String, Value>::value_type Pair;
+ Dictionary() = default;
+ Dictionary(const DictionaryData& other);
+ Dictionary(DictionaryData&& other);
+ Dictionary(std::initializer_list<Pair> init);
+
Value Get(const String& key) const;
bool Get(const String& key, Value *result) const;
void Set(const String& key, Value value);
void FileLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const FileLogger::Ptr& filelogger : ConfigType::GetObjectsByType<FileLogger>()) {
- 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)));
}
/**
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;
}
}
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);
});
}
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);
});
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;
}
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;
}
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;
}
kill(pid, signum);
int error = errno;
- Dictionary::Ptr response = new Dictionary();
- response->Set("errno", error);
+ Dictionary::Ptr response = new Dictionary({
+ { "errno", error }
+ });
return response;
}
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;
}
static pid_t ProcessSpawn(const std::vector<String>& 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();
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();
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();
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);
}
}
- 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<Value>& 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)
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)
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)
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)
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);
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)
std::vector<String> 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<Value>& args)
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;
}
void SyslogLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const SyslogLogger::Ptr& sysloglogger : ConfigType::GetObjectsByType<SyslogLogger>()) {
- 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()
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;
}
if (lhs.IsEmpty())
return new Array();
- Array::Ptr result = new Array();
+ ArrayData result;
Array::Ptr left = lhs;
Array::Ptr right = 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() + "'"));
}
void CheckerComponent::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const CheckerComponent::Ptr& checker : ConfigType::GetObjectsByType<CheckerComponent>()) {
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()
try {
ScriptFrame frame(true);
- frame.Locals = new Dictionary();
- frame.Locals->Set("arg", value);
+ frame.Locals = new Dictionary({
+ { "arg", value }
+ });
expr = ConfigCompiler::CompileText("<dbg>", text);
Value result = Serialize(expr->Evaluate(frame), 0);
dbg_inspect_value(result);
try {
ScriptFrame frame(true);
- frame.Locals = new Dictionary();
- frame.Locals->Set("arg", object);
+ frame.Locals = new Dictionary({
+ { "arg", object }
+ });
expr = ConfigCompiler::CompileText("<dbg>", text);
Value result = Serialize(expr->Evaluate(frame), 0);
dbg_inspect_value(result);
{
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<String> tokens;
boost::algorithm::split(tokens, endpoint, boost::is_any_of(","));
}
/* 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";
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 */
void CheckResultReader::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const CheckResultReader::Ptr& checkresultreader : ConfigType::GetObjectsByType<CheckResultReader>()) {
- 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)));
}
/**
void CompatLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const CompatLogger::Ptr& compat_logger : ConfigType::GetObjectsByType<CompatLogger>()) {
- 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)));
}
/**
void ExternalCommandListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const ExternalCommandListener::Ptr& externalcommandlistener : ConfigType::GetObjectsByType<ExternalCommandListener>()) {
- 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)));
}
/**
void StatusDataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const StatusDataWriter::Ptr& statusdatawriter : ConfigType::GetObjectsByType<StatusDataWriter>()) {
- 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)));
}
/**
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;
std::vector<std::unique_ptr<Expression> > 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<LiteralExpression>(new LiteralExpression(templateArray)), m_DebugInfo));
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
private:
static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, const std::map<String, std::unique_ptr<Expression> >& closedVars)
{
- Dictionary::Ptr locals;
+ if (closedVars.empty())
+ return nullptr;
- if (!closedVars.empty()) {
- 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));
}
};
Dictionary::Ptr CommandDbObject::GetConfigFields() const
{
- Dictionary::Ptr fields = new Dictionary();
Command::Ptr command = static_pointer_cast<Command>(GetObject());
- fields->Set("command_line", CompatUtility::GetCommandLine(command));
-
- return fields;
+ return new Dictionary({
+ { "command_line", CompatUtility::GetCommandLine(command) }
+ });
}
Dictionary::Ptr CommandDbObject::GetStatusFields() const
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;
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);
}
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));
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<Service>()->GetObjectCount());
[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);
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);
}
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);
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);
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);
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);
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;
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 */
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));
}
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;
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 */
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) */
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;
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);
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);
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));
}
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);
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);
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();
} 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));
}
}
} 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));
}
Dictionary::Ptr EndpointDbObject::GetConfigFields() const
{
- Dictionary::Ptr fields = new Dictionary();
Endpoint::Ptr endpoint = static_pointer_cast<Endpoint>(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<Endpoint>(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)
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);
}
/* 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
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));
}
}
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 */
<< "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));
}
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()) {
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));
}
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));
}
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));
}
if (groups)
hashData += DbObject::HashValue(groups);
- Array::Ptr parents = new Array();
+ ArrayData parents;
/* parents */
for (const Checkable::Ptr& checkable : host->GetParents()) {
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()) {
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);
}
Dictionary::Ptr HostGroupDbObject::GetConfigFields() const
{
- Dictionary::Ptr fields = new Dictionary();
HostGroup::Ptr group = static_pointer_cast<HostGroup>(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
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);
}
Dictionary::Ptr ServiceDbObject::GetConfigFields() const
{
- Dictionary::Ptr fields = new Dictionary();
Service::Ptr service = static_pointer_cast<Service>(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
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) {
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));
}
}
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()) {
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));
}
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));
}
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));
}
if (groups)
hashData += DbObject::HashValue(groups);
- Array::Ptr dependencies = new Array();
+ ArrayData dependencies;
/* dependencies */
for (const Dependency::Ptr& dep : service->GetDependencies()) {
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);
}
Dictionary::Ptr ServiceGroupDbObject::GetConfigFields() const
{
- Dictionary::Ptr fields = new Dictionary();
ServiceGroup::Ptr group = static_pointer_cast<ServiceGroup>(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
Dictionary::Ptr TimePeriodDbObject::GetConfigFields() const
{
- Dictionary::Ptr fields = new Dictionary();
TimePeriod::Ptr tp = static_pointer_cast<TimePeriod>(GetObject());
- fields->Set("alias", tp->GetDisplayName());
-
- return fields;
+ return new Dictionary({
+ { "alias", tp->GetDisplayName() }
+ });
}
Dictionary::Ptr TimePeriodDbObject::GetStatusFields() const
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();
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);
}
}
Dictionary::Ptr UserDbObject::GetConfigFields() const
{
- Dictionary::Ptr fields = new Dictionary();
User::Ptr user = static_pointer_cast<User>(GetObject());
- fields->Set("alias", user->GetDisplayName());
- fields->Set("email_address", user->GetEmail());
- fields->Set("pager_address", user->GetPager());
- fields->Set("host_timeperiod_object_id", user->GetPeriod());
- fields->Set("service_timeperiod_object_id", user->GetPeriod());
- fields->Set("host_notifications_enabled", user->GetEnableNotifications());
- fields->Set("service_notifications_enabled", user->GetEnableNotifications());
- fields->Set("can_submit_commands", 1);
-
int typeFilter = user->GetTypeFilter();
int 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<User>(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()
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) {
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));
}
}
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))
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));
}
}
Dictionary::Ptr UserGroupDbObject::GetConfigFields() const
{
- Dictionary::Ptr fields = new Dictionary();
UserGroup::Ptr group = static_pointer_cast<UserGroup>(GetObject());
- fields->Set("alias", group->GetDisplayName());
-
- return fields;
+ return new Dictionary({
+ { "alias", group->GetDisplayName() }
+ });
}
Dictionary::Ptr UserGroupDbObject::GetStatusFields() const
Dictionary::Ptr ZoneDbObject::GetConfigFields() const
{
- Dictionary::Ptr fields = new Dictionary();
Zone::Ptr zone = static_pointer_cast<Zone>(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
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() }
+ });
}
void IdoMysqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const IdoMysqlConnection::Ptr& idomysqlconnection : ConfigType::GetObjectsByType<IdoMysqlConnection>()) {
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)));
perfdata->Add(new PerfdataValue("idomysqlconnection_" + idomysqlconnection->GetName() + "_query_queue_item_rate", queryQueueItemRate));
}
- status->Set("idomysqlconnection", nodes);
+ status->Set("idomysqlconnection", new Dictionary(std::move(nodes)));
}
void IdoMysqlConnection::Resume()
void IdoPgsqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const IdoPgsqlConnection::Ptr& idopgsqlconnection : ConfigType::GetObjectsByType<IdoPgsqlConnection>()) {
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)));
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()
int columns = m_Pgsql->nfields(result.get());
- Dictionary::Ptr dict = new Dictionary();
+ DictionaryData dict;
for (int column = 0; column < columns; column++) {
Value value;
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)
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);
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()
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;
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();
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 '" +
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);
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);
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);
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);
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);
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);
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);
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);
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());
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;
}
if (!cr)
return Empty;
- Array::Ptr rperf = new Array();
+ ArrayData rperf;
if (vperf) {
ObjectLock olock(vperf);
if (vp.IsObjectType<Dictionary>()) {
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"));
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));
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);
return false;
}
} else {
- Array::Ptr instances = new Array();
- instances->Add("");
- vinstances = instances;
+ vinstances = new Array({ "" });
}
bool match = false;
void IcingaApplication::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const IcingaApplication::Ptr& icingaapplication : ConfigType::GetObjectsByType<IcingaApplication>()) {
- 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)));
}
/**
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");
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");
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)
result = InternalResolveMacros(str, resolvers, cr, missingMacro, escapeFn,
resolvedMacros, useResolvedMacros, recursionLevel + 1);
} else if (str.IsObjectType<Array>()) {
- Array::Ptr resultArr = new Array();
+ ArrayData resultArr;;
Array::Ptr arr = str;
ObjectLock olock(arr);
EscapeCallback(), resolvedMacros, useResolvedMacros, recursionLevel + 1);
if (value.IsObjectType<Array>())
- 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>()) {
Dictionary::Ptr resultDict = new Dictionary();
Dictionary::Ptr dict = str;
if (recursive_macro) {
if (resolved_macro.IsObjectType<Array>()) {
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,
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) {
return resolvedCommand;
}
-
return false;
}
} else {
- Array::Ptr instances = new Array();
- instances->Add("");
- vinstances = instances;
+ vinstances = new Array({ "" });
}
bool match = false;
Array::Ptr PluginUtility::SplitPerfdata(const String& perfdata)
{
- Array::Ptr result = new Array();
+ ArrayData result;
size_t begin = 0;
String multi_prefix;
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);
begin = spq + 1;
}
- return result;
+ return new Array(std::move(result));
}
String PluginUtility::FormatPerfdata(const Array::Ptr& perfdata)
return false;
}
} else {
- Array::Ptr instances = new Array();
- instances->Add("");
- vinstances = instances;
+ vinstances = new Array({ "" });
}
bool match = false;
return false;
}
} else {
- Array::Ptr instances = new Array();
- instances->Add("");
- vinstances = instances;
+ vinstances = new Array({ "" });
}
bool match = false;
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()
}
/* 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();
/* 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. */
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)
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)
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));
}
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));
}
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)
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<Array>() || kv.second.IsObjectType<Dictionary>())
- 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<Array>() || kv.second.IsObjectType<Dictionary>())
+ 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)
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<Array>() || kv.second.IsObjectType<Dictionary>())
- key_val->Add(JsonEncode(kv.second));
- else
- key_val->Add(kv.second);
+ if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>())
+ 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)
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)
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)
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)
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)
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)
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)
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)
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<int>(comment->GetEntryTime()));
- results->Add(comment_info);
+ result.push_back(new Array({
+ comment->GetLegacyId(),
+ comment->GetAuthor(),
+ comment->GetText(),
+ comment->GetEntryType(),
+ static_cast<int>(comment->GetEntryTime())
+ }));
}
- return results;
+ return new Array(std::move(result));
}
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)
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<Array>() || kv.second.IsObjectType<Dictionary>())
- 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<Array>() || kv.second.IsObjectType<Dictionary>())
+ 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)
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<Array>() || kv.second.IsObjectType<Dictionary>())
- key_val->Add(JsonEncode(kv.second));
- else
- key_val->Add(kv.second);
+ if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>())
+ 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)
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<Host>(parent);
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)
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<Host>(child);
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)
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)
std::vector<Service::Ptr> 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)
std::vector<Service::Ptr> 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)
std::vector<Service::Ptr> 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)
void LivestatusListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const LivestatusListener::Ptr& livestatuslistener : ConfigType::GetObjectsByType<LivestatusListener>()) {
- 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)));
}
/**
BeginResultSet(result);
if (m_Aggregators.empty()) {
- Array::Ptr header = new Array();
-
typedef std::pair<String, Column> ColumnPair;
std::vector<ColumnPair> column_objs;
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<Value>, std::vector<AggregatorState *> > allStats;
/* 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);
}
}
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)
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)
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)
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)
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)
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)
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)
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<int>(comment->GetEntryTime()));
- results->Add(comment_info);
+ result.push_back(new Array({
+ comment->GetLegacyId(),
+ comment->GetAuthor(),
+ comment->GetText(),
+ comment->GetEntryType(),
+ static_cast<int>(comment->GetEntryTime())
+ }));
}
- return results;
+ return new Array(std::move(result));
}
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)
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<Array>() || kv.second.IsObjectType<Dictionary>())
- 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<Array>() || kv.second.IsObjectType<Dictionary>())
+ 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)
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<Array>() || kv.second.IsObjectType<Dictionary>())
- key_val->Add(JsonEncode(kv.second));
- else
- key_val->Add(kv.second);
+ if (kv.second.IsObjectType<Array>() || kv.second.IsObjectType<Dictionary>())
+ 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)
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)
{
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));
}
std::set<Endpoint::Ptr> 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)
+ " 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);
}
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);
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;
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<ServiceState>(Utility::Random() % 4));
service->ProcessCheckResult(cr);
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));
}
void NotificationComponent::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const NotificationComponent::Ptr& notification_component : ConfigType::GetObjectsByType<NotificationComponent>()) {
- 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)));
}
/**
void ElasticsearchWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const ElasticsearchWriter::Ptr& elasticsearchwriter : ConfigType::GetObjectsByType<ElasticsearchWriter>()) {
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)
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);
void GelfWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const GelfWriter::Ptr& gelfwriter : ConfigType::GetObjectsByType<GelfWriter>()) {
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)
void GraphiteWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const GraphiteWriter::Ptr& graphitewriter : ConfigType::GetObjectsByType<GraphiteWriter>()) {
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)
{
if (value.IsObjectType<Array>()) {
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);
}
void InfluxdbWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const InfluxdbWriter::Ptr& influxdbwriter : ConfigType::GetObjectsByType<InfluxdbWriter>()) {
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)
};
[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 {
void OpenTsdbWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const OpenTsdbWriter::Ptr& opentsdbwriter : ConfigType::GetObjectsByType<OpenTsdbWriter>()) {
- nodes->Set(opentsdbwriter->GetName(), 1); //add more stats
+ nodes.emplace_back(opentsdbwriter->GetName(), 1); //add more stats
}
- status->Set("opentsdbwriter", nodes);
+ status->Set("opentsdbwriter", new Dictionary(std::move(nodes)));
}
void OpenTsdbWriter::Start(bool runtimeCreated)
void PerfdataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
- Dictionary::Ptr nodes = new Dictionary();
+ DictionaryData nodes;
for (const PerfdataWriter::Ptr& perfdatawriter : ConfigType::GetObjectsByType<PerfdataWriter>()) {
- nodes->Set(perfdatawriter->GetName(), 1); //add more stats
+ nodes.emplace_back(perfdatawriter->GetName(), 1); //add more stats
}
- status->Set("perfdatawriter", nodes);
+ status->Set("perfdatawriter", new Dictionary(std::move(nodes)));
}
void PerfdataWriter::Start(bool runtimeCreated)
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;
}
-
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());
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);
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")
}
}
- 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")
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);
}
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 {
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;
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);
std::pair<Dictionary::Ptr, Dictionary::Ptr> 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();
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;
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();
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);
std::vector<String> 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);
return;
}
- Dictionary::Ptr result1 = new Dictionary();
-
try {
boost::mutex::scoped_lock lock(ConfigPackageUtility::GetStaticMutex());
ConfigPackageUtility::CreatePackage(packageName);
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);
int code = 200;
String status = "Deleted package.";
- Dictionary::Ptr result1 = new Dictionary();
+ DictionaryData result1;
try {
ConfigPackageUtility::DeletePackage(packageName);
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);
}
-
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);
if (!ConfigPackageUtility::ValidateName(stageName))
return HttpUtility::SendJsonError(response, params, 400, "Invalid stage name.");
- Array::Ptr results = new Array();
+ ArrayData results;
std::vector<std::pair<String, bool> > paths = ConfigPackageUtility::GetFiles(packageName, stageName);
String prefixPath = ConfigPackageUtility::GetPackageDir() + "/" + packageName + "/" + stageName + "/";
- typedef std::pair<String, bool> 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);
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);
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);
lsf.Lines[fileName] = command;
- Array::Ptr results = new Array();
- Dictionary::Ptr resultInfo = new Dictionary();
+ Dictionary::Ptr resultInfo;
std::unique_ptr<Expression> expr;
Value exprResult;
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();
<< 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);
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);
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);
}
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;
return true;
}
-
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");
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 {
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 {
}
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 {
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);
}
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;
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;
/* 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);
Dictionary::Ptr attrs = attrsVal;
- Array::Ptr results = new Array();
+ ArrayData results;
for (const ConfigObject::Ptr& obj : objs) {
Dictionary::Ptr result1 = new Dictionary();
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);
}
}
- 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);
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)
return true;
}
- Array::Ptr results = new Array();
- results->Reserve(objs.size());
+ ArrayData results;
+ results.reserve(objs.size());
std::set<String> joinAttrs;
std::set<String> userJoinAttrs;
}
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)))
{
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;
}
}
+ 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;
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);
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);
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
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);
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,
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;
}
-
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());
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<bool>(field.Attributes & FAConfig));
- attributeInfo->Set("state", static_cast<bool>(field.Attributes & FAState));
- attributeInfo->Set("required", static_cast<bool>(field.Attributes & FARequired));
- attributeInfo->Set("navigation", static_cast<bool>(field.Attributes & FANavigation));
- attributeInfo->Set("no_user_modify", static_cast<bool>(field.Attributes & FANoUserModify));
- attributeInfo->Set("no_user_view", static_cast<bool>(field.Attributes & FANoUserView));
- attributeInfo->Set("deprecated", static_cast<bool>(field.Attributes & FADeprecated));
+ fieldInfo->Set("attributes", new Dictionary({
+ { "config", static_cast<bool>(field.Attributes & FAConfig) },
+ { "state", static_cast<bool>(field.Attributes & FAState) },
+ { "required", static_cast<bool>(field.Attributes & FARequired) },
+ { "navigation", static_cast<bool>(field.Attributes & FANavigation) },
+ { "no_user_modify", static_cast<bool>(field.Attributes & FANoUserModify) },
+ { "no_user_view", static_cast<bool>(field.Attributes & FANoUserView) },
+ { "deprecated", static_cast<bool>(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;
}
-
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,
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);