Пример #1
0
static Array::Ptr DictionaryKeys(void)
{
	ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
	Dictionary::Ptr self = static_cast<Dictionary::Ptr>(vframe->Self);
	Array::Ptr keys = new Array();
	ObjectLock olock(self);
	for (const Dictionary::Pair& kv : self) {
		keys->Add(kv.first);
	}
	return keys;
}
Пример #2
0
bool ConfigObjectUtility::DeleteObject(const ConfigObject::Ptr& object, bool cascade, const Array::Ptr& errors)
{
	if (object->GetPackage() != "_api") {
		if (errors)
			errors->Add("Object cannot be deleted because it was not created using the API.");

		return false;
	}

	return DeleteObjectHelper(object, cascade, errors);
}
Пример #3
0
void CheckerComponent::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
	Dictionary::Ptr nodes = new Dictionary();

	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);

		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);
}
Пример #4
0
/**
 * Converts a JSON object to an array.
 *
 * @param json The JSON object.
 * @returns An array that is equivalent to the JSON object.
 */
Array::Ptr Array::FromJson(cJSON *json)
{
	Array::Ptr array = make_shared<Array>();

	ASSERT(json->type == cJSON_Array);

	for (cJSON *i = json->child; i != NULL; i = i->next) {
		array->Add(Value::FromJson(i));
	}

	return array;
}
Пример #5
0
void IdoPgsqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
	Dictionary::Ptr nodes = new Dictionary();

	BOOST_FOREACH(const IdoPgsqlConnection::Ptr& idopgsqlconnection, ConfigType::GetObjectsByType<IdoPgsqlConnection>()) {
		size_t items = idopgsqlconnection->m_QueryQueue.GetLength();

		Dictionary::Ptr stats = new Dictionary();
		stats->Set("version", idopgsqlconnection->GetSchemaVersion());
		stats->Set("connected", idopgsqlconnection->GetConnected());
		stats->Set("instance_name", idopgsqlconnection->GetInstanceName());
		stats->Set("query_queue_items", items);

		nodes->Set(idopgsqlconnection->GetName(), stats);

		perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_rate", idopgsqlconnection->GetQueryCount(60) / 60.0));
		perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_1min", idopgsqlconnection->GetQueryCount(60)));
		perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_5mins", idopgsqlconnection->GetQueryCount(5 * 60)));
		perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_15mins", idopgsqlconnection->GetQueryCount(15 * 60)));
		perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_items", items));
	}
Пример #6
0
void IdoPgsqlConnection::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
	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;

		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() + "_queries_5mins", idopgsqlconnection->GetQueryCount(5 * 60)));
		perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_queries_15mins", idopgsqlconnection->GetQueryCount(15 * 60)));
		perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_items", queryQueueItems));
		perfdata->Add(new PerfdataValue("idopgsqlconnection_" + idopgsqlconnection->GetName() + "_query_queue_item_rate", queryQueueItemRate));
	}

	status->Set("idopgsqlconnection", new Dictionary(std::move(nodes)));
}
Пример #7
0
void ScriptFrame::AddImport(const Object::Ptr& import)
{
	Array::Ptr imports;

	if (!m_Imports)
		imports = new Array();
	else
		imports = m_Imports->ShallowClone();

	imports->Add(import);

	m_Imports = imports;
}
Пример #8
0
void InfluxdbWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
	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();

		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", new Dictionary(std::move(nodes)));
}
Пример #9
0
Array::Ptr ScriptUtils::Keys(const Dictionary::Ptr& dict)
{
	Array::Ptr result = new Array();

	if (dict) {
		ObjectLock olock(dict);
		for (const Dictionary::Pair& kv : dict) {
			result->Add(kv.first);
		}
	}

	return result;
}
Пример #10
0
bool Service::EvaluateApplyRule(const Host::Ptr& host, const ApplyRule& rule)
{
	DebugInfo di = rule.GetDebugInfo();

	std::ostringstream msgbuf;
	msgbuf << "Evaluating 'apply' rule (" << di << ")";
	CONTEXT(msgbuf.str());

	ScriptFrame frame;
	if (rule.GetScope())
		rule.GetScope()->CopyTo(frame.Locals);
	frame.Locals->Set("host", host);

	Value vinstances;

	if (rule.GetFTerm()) {
		try {
			vinstances = rule.GetFTerm()->Evaluate(frame);
		} catch (const std::exception&) {
			/* Silently ignore errors here and assume there are no instances. */
			return false;
		}
	} else {
		Array::Ptr instances = new Array();
		instances->Add("");
		vinstances = instances;
	}

	bool match = false;

	if (vinstances.IsObjectType<Array>()) {
		if (!rule.GetFVVar().IsEmpty())
			BOOST_THROW_EXCEPTION(ScriptError("Dictionary iterator requires value to be a dictionary.", di));

		Array::Ptr arr = vinstances;
		Array::Ptr arrclone = arr->ShallowClone();

		ObjectLock olock(arrclone);
		BOOST_FOREACH(const Value& instance, arrclone) {
			String name = rule.GetName();

			if (!rule.GetFKVar().IsEmpty()) {
				frame.Locals->Set(rule.GetFKVar(), instance);
				name += instance;
			}

			if (EvaluateApplyRuleInstance(host, name, frame, rule))
				match = true;
		}
	} else if (vinstances.IsObjectType<Dictionary>()) {
Пример #11
0
ExpressionResult ArrayExpression::DoEvaluate(ScriptFrame& frame, DebugHint *dhint) const
{
	Array::Ptr result = new Array();
	result->Reserve(m_Expressions.size());

	for (Expression *aexpr : m_Expressions) {
		ExpressionResult element = aexpr->Evaluate(frame);
		CHECK_RESULT(element);

		result->Add(element.GetValue());
	}

	return result;
}
Пример #12
0
bool ScheduledDowntime::EvaluateApplyRule(const Checkable::Ptr& checkable, const ApplyRule& rule)
{
	DebugInfo di = rule.GetDebugInfo();

	std::ostringstream msgbuf;
	msgbuf << "Evaluating 'apply' rule (" << di << ")";
	CONTEXT(msgbuf.str());

	Host::Ptr host;
	Service::Ptr service;
	tie(host, service) = GetHostService(checkable);

	VMFrame frame;
	if (rule.GetScope())
		rule.GetScope()->CopyTo(frame.Locals);
	frame.Locals->Set("host", host);
	if (service)
		frame.Locals->Set("service", service);

	if (!rule.EvaluateFilter(frame))
		return false;

	Value vinstances;

	if (rule.GetFTerm()) {
		vinstances = rule.GetFTerm()->Evaluate(frame);
	} else {
		Array::Ptr instances = new Array();
		instances->Add("");
		vinstances = instances;
	}

	if (vinstances.IsObjectType<Array>()) {
		if (!rule.GetFVVar().IsEmpty())
			BOOST_THROW_EXCEPTION(ConfigError("Array iterator requires value to be an array.") << errinfo_debuginfo(di));

		Array::Ptr arr = vinstances;

		ObjectLock olock(arr);
		BOOST_FOREACH(const String& instance, arr) {
			String name = rule.GetName();

			if (!rule.GetFKVar().IsEmpty()) {
				frame.Locals->Set(rule.GetFKVar(), instance);
				name += instance;
			}

			EvaluateApplyRuleInstance(checkable, name, frame, rule);
		}
	} else if (vinstances.IsObjectType<Dictionary>()) {
Пример #13
0
void User::AddGroup(const String& name)
{
	boost::mutex::scoped_lock lock(m_UserMutex);

	Array::Ptr groups = GetGroups();

	if (groups && groups->Contains(name))
		return;

	if (!groups)
		groups = new Array();

	groups->Add(name);
}
Пример #14
0
pid_t Application::StartReloadProcess(void)
{
	Log(LogInformation, "Application", "Got reload command: Starting new instance.");

	// prepare arguments
	Array::Ptr args = new Array();
	args->Add(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]);
		else
			i++;     // the next parameter after --reload-internal is the pid, remove that too
	}
	args->Add("--reload-internal");
	args->Add(Convert::ToString(Utility::GetPid()));

	Process::Ptr process = new Process(Process::PrepareCommand(args));
	process->SetTimeout(300);
	process->Run(&ReloadProcessCallback);

	return process->GetPID();
}
Пример #15
0
Value StatusTable::CustomVariableNamesAccessor(const Value&)
{
	Dictionary::Ptr vars = IcingaApplication::GetInstance()->GetVars();

	if (!vars)
		return Empty;

	Array::Ptr cv = new Array();

	String key;
	Value value;
	BOOST_FOREACH(tie(key, value), vars) {
		cv->Add(key);
	}
Пример #16
0
void LegacyTimePeriod::ProcessTimeRanges(const String& timeranges, tm *reference, const Array::Ptr& result)
{
	std::vector<String> ranges;

	boost::algorithm::split(ranges, timeranges, boost::is_any_of(","));

	for (const String& range : ranges) {
		Dictionary::Ptr segment = ProcessTimeRange(range, reference);

		if (segment->Get("begin") >= segment->Get("end"))
			continue;

		result->Add(segment);
	}
}
Пример #17
0
Value ContactGroupsTable::MembersAccessor(const Value& row)
{
	UserGroup::Ptr user_group = static_cast<UserGroup::Ptr>(row);

	if (!user_group)
		return Empty;

	Array::Ptr members = new Array();

	BOOST_FOREACH(const User::Ptr& user, user_group->GetMembers()) {
		members->Add(user->GetName());
	}

	return members;
}
Пример #18
0
Value ClusterEvents::CheckResultAPIHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params)
{
	Endpoint::Ptr endpoint = origin->FromClient->GetEndpoint();

	if (!endpoint) {
		Log(LogNotice, "ClusterEvents")
		    << "Discarding 'check result' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
		return Empty;
	}

	if (!params)
		return Empty;

	CheckResult::Ptr cr = new CheckResult();

	Dictionary::Ptr vcr = params->Get("cr");
	Array::Ptr vperf = vcr->Get("performance_data");
	vcr->Remove("performance_data");

	Deserialize(cr, params->Get("cr"), true);

	Array::Ptr rperf = new Array();

	if (vperf) {
		ObjectLock olock(vperf);
		BOOST_FOREACH(const Value& vp, vperf) {
			Value p;

			if (vp.IsObjectType<Dictionary>()) {
				PerfdataValue::Ptr val = new PerfdataValue();
				Deserialize(val, vp, true);
				rperf->Add(val);
			} else
				rperf->Add(vp);
		}
	}
Пример #19
0
bool CreateObjectHandler::HandleRequest(const ApiUser::Ptr& user, HttpRequest& request, HttpResponse& response)
{
	if (request.RequestMethod != "PUT")
		return false;

	if (request.RequestUrl->GetPath().size() < 3)
		return false;

	Type::Ptr type = FilterUtility::TypeFromPluralName(request.RequestUrl->GetPath()[1]);

	if (!type)
		return false;

	String name = request.RequestUrl->GetPath()[2];
	Dictionary::Ptr params = HttpUtility::FetchRequestParameters(request);
	Array::Ptr templates = params->Get("templates");
	Dictionary::Ptr attrs = params->Get("attrs");

	Dictionary::Ptr result1 = new Dictionary();
	int code;
	String status;
	Array::Ptr errors = new Array();
	
	String config = ConfigObjectUtility::CreateObjectConfig(type, name, templates, attrs);
	
	if (!ConfigObjectUtility::CreateObject(type, name, config, errors)) {
		result1->Set("errors", errors);
		code = 500;
		status = "Object could not be created.";
	} else {
		code = 200;
		status = "Object was created.";
	}

	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);

	response.SetStatus(code, status);
	HttpUtility::SendJsonBody(response, result);

	return true;
}
Пример #20
0
Array::Ptr TimePeriodTask::EvenMinutesTimePeriodUpdate(const TimePeriod::Ptr&, double begin, double end)
{
	Array::Ptr segments = new Array();

	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);
		}
	}

	return segments;
}
Пример #21
0
void TimePeriod::AddSegment(double begin, double end)
{
	ASSERT(OwnsLock());

	Log(LogDebug, "TimePeriod")
	    << "Adding segment '" << Utility::FormatDateTime("%c", begin) << "' <-> '"
	    << Utility::FormatDateTime("%c", end) << "' to TimePeriod '" << GetName() << "'";

	if (GetValidBegin().IsEmpty() || begin < GetValidBegin())
		SetValidBegin(begin);

	if (GetValidEnd().IsEmpty() || end > GetValidEnd())
		SetValidEnd(end);

	Array::Ptr segments = GetSegments();

	if (segments) {
		/* Try to merge the new segment into an existing segment. */
		ObjectLock dlock(segments);
		BOOST_FOREACH(const Dictionary::Ptr& segment, segments) {
			if (segment->Get("begin") <= begin && segment->Get("end") >= end)
				return; /* New segment is fully contained in this segment. */

			if (segment->Get("begin") <= begin && segment->Get("end") >= begin) {
				segment->Set("end", end); /* Extend an existing segment. */
				return;
			}

			if (segment->Get("begin") >= begin && segment->Get("begin") <= end) {
				segment->Set("begin", begin); /* Extend an existing segment. */
				return;
			}
		}
	}

	/* 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);

	if (!segments) {
		segments = new Array();
		SetSegments(segments);
	}

	segments->Add(segment);
}
Пример #22
0
String ServiceDbObject::CalculateConfigHash(const Dictionary::Ptr& configFields) const
{
	String hashData = DbObject::CalculateConfigHash(configFields);

	Service::Ptr service = static_pointer_cast<Service>(GetObject());

	Array::Ptr groups = service->GetGroups();

	if (groups)
		hashData += DbObject::HashValue(groups);

	Array::Ptr dependencies = new Array();

	/* dependencies */
	for (const Dependency::Ptr& dep : service->GetDependencies()) {
		Checkable::Ptr parent = dep->GetParent();

		if (!parent)
			continue;

		Array::Ptr depInfo = new Array();
		depInfo->Add(parent->GetName());
		depInfo->Add(dep->GetStateFilter());
		depInfo->Add(dep->GetPeriodRaw());

		dependencies->Add(depInfo);
	}

	dependencies->Sort();

	hashData += DbObject::HashValue(dependencies);

	Array::Ptr users = new Array();

	for (const User::Ptr& user : CompatUtility::GetCheckableNotificationUsers(service)) {
		users->Add(user->GetName());
	}

	users->Sort();

	hashData += DbObject::HashValue(users);

	Array::Ptr userGroups = new Array();

	for (const UserGroup::Ptr& usergroup : CompatUtility::GetCheckableNotificationUserGroups(service)) {
		userGroups->Add(usergroup->GetName());
	}

	userGroups->Sort();

	hashData += DbObject::HashValue(userGroups);

	return SHA256(hashData);
}
Пример #23
0
void ApiListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
{
	std::pair<Dictionary::Ptr, Dictionary::Ptr> stats;

	ApiListener::Ptr listener = ApiListener::GetInstance();

	if (!listener)
		return;

	stats = listener->GetStatus();

	ObjectLock olock(stats.second);
	for (const Dictionary::Pair& kv : stats.second)
		perfdata->Add("'api_" + kv.first + "'=" + Convert::ToString(kv.second));

	status->Set("api", stats.first);
}
Пример #24
0
Array::Ptr ScriptUtils::GetObjects(const Type::Ptr& type)
{
	if (!type)
		BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid type: Must not be null"));

	ConfigType *ctype = dynamic_cast<ConfigType *>(type.get());

	if (!ctype)
		BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid type: Type must inherit from 'ConfigObject'"));

	Array::Ptr result = new Array();

	for (const ConfigObject::Ptr& object : ctype->GetObjects())
		result->Add(object);

	return result;
}
Пример #25
0
void NullCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
    const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
	if (resolvedMacros && !useResolvedMacros)
		return;

	String output = "Hello from ";
	output += Utility::GetFQDN();

	Array::Ptr perfdata = new Array();
	perfdata->Add(new PerfdataValue("time", Convert::ToDouble(Utility::GetTime())));

	cr->SetOutput(output);
	cr->SetPerformanceData(perfdata);
	cr->SetState(ServiceOK);

	service->ProcessCheckResult(cr);
}
Пример #26
0
void RandomCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr,
    const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros)
{
	if (resolvedMacros && !useResolvedMacros)
		return;

	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->SetState(static_cast<ServiceState>(Utility::Random() % 4));

	service->ProcessCheckResult(cr);
}
Пример #27
0
static Array::Ptr ArrayMap(const Function::Ptr& function)
{
	ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
	Array::Ptr self = static_cast<Array::Ptr>(vframe->Self);

	if (vframe->Sandboxed && !function->IsSideEffectFree())
		BOOST_THROW_EXCEPTION(ScriptError("Map function must be side-effect free."));

	Array::Ptr result = new Array();

	ObjectLock olock(self);
	for (const Value& item : self) {
		std::vector<Value> args;
		args.push_back(item);
		result->Add(function->Invoke(args));
	}

	return result;
}
Пример #28
0
void Checkable::AddGroup(const String& name)
{
	boost::mutex::scoped_lock lock(m_CheckableMutex);

	Array::Ptr groups;
	auto *host = dynamic_cast<Host *>(this);

	if (host)
		groups = host->GetGroups();
	else
		groups = static_cast<Service *>(this)->GetGroups();

	if (groups && groups->Contains(name))
		return;

	if (!groups)
		groups = new Array();

	groups->Add(name);
}
Пример #29
0
Array::Ptr ScriptUtils::Union(const std::vector<Value>& arguments)
{
	std::set<Value> values;

	for (const Value& varr : arguments) {
		Array::Ptr arr = varr;

		if (arr) {
			ObjectLock olock(arr);
			for (const Value& value : arr) {
				values.insert(value);
			}
		}
	}

	Array::Ptr result = new Array();
	for (const Value& value : values) {
		result->Add(value);
	}

	return result;
}
Пример #30
0
bool HostGroup::EvaluateObjectRule(const Host::Ptr& host, const ConfigItem::Ptr& group)
{
	String group_name = group->GetName();

	CONTEXT("Evaluating rule for group '" + group_name + "'");

	ScriptFrame frame;
	if (group->GetScope())
		group->GetScope()->CopyTo(frame.Locals);
	frame.Locals->Set("host", host);

	if (!group->GetFilter()->Evaluate(frame).GetValue().ToBool())
		return false;

	Log(LogDebug, "HostGroup")
	    << "Assigning membership for group '" << group_name << "' to host '" << host->GetName() << "'";

	Array::Ptr groups = host->GetGroups();
	groups->Add(group_name);

	return true;
}