summaryrefslogtreecommitdiffstats
path: root/lib/perfdata/perfdatawriter.cpp
blob: 849f19ed68bf494283b2f5ff6231fa296560ad54 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "perfdata/perfdatawriter.hpp"
#include "perfdata/perfdatawriter-ti.cpp"
#include "icinga/service.hpp"
#include "icinga/macroprocessor.hpp"
#include "icinga/icingaapplication.hpp"
#include "base/configtype.hpp"
#include "base/objectlock.hpp"
#include "base/logger.hpp"
#include "base/convert.hpp"
#include "base/utility.hpp"
#include "base/context.hpp"
#include "base/exception.hpp"
#include "base/application.hpp"
#include "base/statsfunction.hpp"

using namespace icinga;

REGISTER_TYPE(PerfdataWriter);

REGISTER_STATSFUNCTION(PerfdataWriter, &PerfdataWriter::StatsFunc);

void PerfdataWriter::OnConfigLoaded()
{
	ObjectImpl<PerfdataWriter>::OnConfigLoaded();

	if (!GetEnableHa()) {
		Log(LogDebug, "PerfdataWriter")
			<< "HA functionality disabled. Won't pause connection: " << GetName();

		SetHAMode(HARunEverywhere);
	} else {
		SetHAMode(HARunOnce);
	}
}

void PerfdataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
{
	DictionaryData nodes;

	for (const PerfdataWriter::Ptr& perfdatawriter : ConfigType::GetObjectsByType<PerfdataWriter>()) {
		nodes.emplace_back(perfdatawriter->GetName(), 1); //add more stats
	}

	status->Set("perfdatawriter", new Dictionary(std::move(nodes)));
}

void PerfdataWriter::Resume()
{
	ObjectImpl<PerfdataWriter>::Resume();

	Log(LogInformation, "PerfdataWriter")
		<< "'" << GetName() << "' resumed.";

	m_HandleCheckResults = Checkable::OnNewCheckResult.connect([this](const Checkable::Ptr& checkable,
		const CheckResult::Ptr& cr, const MessageOrigin::Ptr&) {
		CheckResultHandler(checkable, cr);
	});

	m_RotationTimer = Timer::Create();
	m_RotationTimer->OnTimerExpired.connect([this](const Timer * const&) { RotationTimerHandler(); });
	m_RotationTimer->SetInterval(GetRotationInterval());
	m_RotationTimer->Start();

	RotateFile(m_ServiceOutputFile, GetServiceTempPath(), GetServicePerfdataPath());
	RotateFile(m_HostOutputFile, GetHostTempPath(), GetHostPerfdataPath());
}

void PerfdataWriter::Pause()
{
	m_HandleCheckResults.disconnect();
	m_RotationTimer->Stop(true);

#ifdef I2_DEBUG
	//m_HostOutputFile << "\n# Pause the feature" << "\n\n";
	//m_ServiceOutputFile << "\n# Pause the feature" << "\n\n";
#endif /* I2_DEBUG */

	/* Force a rotation closing the file stream. */
	RotateAllFiles();

	Log(LogInformation, "PerfdataWriter")
		<< "'" << GetName() << "' paused.";

	ObjectImpl<PerfdataWriter>::Pause();
}

Value PerfdataWriter::EscapeMacroMetric(const Value& value)
{
	if (value.IsObjectType<Array>())
		return Utility::Join(value, ';');
	else
		return value;
}

void PerfdataWriter::CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr)
{
	if (IsPaused())
		return;

	CONTEXT("Writing performance data for object '" << checkable->GetName() << "'");

	if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !checkable->GetEnablePerfdata())
		return;

	Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
	Host::Ptr host;

	if (service)
		host = service->GetHost();
	else
		host = static_pointer_cast<Host>(checkable);

	MacroProcessor::ResolverList resolvers;
	if (service)
		resolvers.emplace_back("service", service);
	resolvers.emplace_back("host", host);

	if (service) {
		String line = MacroProcessor::ResolveMacros(GetServiceFormatTemplate(), resolvers, cr, nullptr, &PerfdataWriter::EscapeMacroMetric);

		{
			std::unique_lock<std::mutex> lock(m_StreamMutex);

			if (!m_ServiceOutputFile.good())
				return;

			m_ServiceOutputFile << line << "\n";
		}
	} else {
		String line = MacroProcessor::ResolveMacros(GetHostFormatTemplate(), resolvers, cr, nullptr, &PerfdataWriter::EscapeMacroMetric);

		{
			std::unique_lock<std::mutex> lock(m_StreamMutex);

			if (!m_HostOutputFile.good())
				return;

			m_HostOutputFile << line << "\n";
		}
	}
}

void PerfdataWriter::RotateFile(std::ofstream& output, const String& temp_path, const String& perfdata_path)
{
	Log(LogDebug, "PerfdataWriter")
		<< "Rotating perfdata files.";

	std::unique_lock<std::mutex> lock(m_StreamMutex);

	if (output.good()) {
		output.close();

		if (Utility::PathExists(temp_path)) {
			String finalFile = perfdata_path + "." + Convert::ToString((long)Utility::GetTime());

			Log(LogDebug, "PerfdataWriter")
				<< "Closed output file and renaming into '" << finalFile << "'.";

			Utility::RenameFile(temp_path, finalFile);
		}
	}

	output.open(temp_path.CStr());

	if (!output.good()) {
		Log(LogWarning, "PerfdataWriter")
			<< "Could not open perfdata file '" << temp_path << "' for writing. Perfdata will be lost.";
	}
}

void PerfdataWriter::RotationTimerHandler()
{
	if (IsPaused())
		return;

	RotateAllFiles();
}

void PerfdataWriter::RotateAllFiles()
{
	RotateFile(m_ServiceOutputFile, GetServiceTempPath(), GetServicePerfdataPath());
	RotateFile(m_HostOutputFile, GetHostTempPath(), GetHostPerfdataPath());
}

void PerfdataWriter::ValidateHostFormatTemplate(const Lazy<String>& lvalue, const ValidationUtils& utils)
{
	ObjectImpl<PerfdataWriter>::ValidateHostFormatTemplate(lvalue, utils);

	if (!MacroProcessor::ValidateMacroString(lvalue()))
		BOOST_THROW_EXCEPTION(ValidationError(this, { "host_format_template" }, "Closing $ not found in macro format string '" + lvalue() + "'."));
}

void PerfdataWriter::ValidateServiceFormatTemplate(const Lazy<String>& lvalue, const ValidationUtils& utils)
{
	ObjectImpl<PerfdataWriter>::ValidateServiceFormatTemplate(lvalue, utils);

	if (!MacroProcessor::ValidateMacroString(lvalue()))
		BOOST_THROW_EXCEPTION(ValidationError(this, { "service_format_template" }, "Closing $ not found in macro format string '" + lvalue() + "'."));
}