summaryrefslogtreecommitdiffstats
path: root/lib/livestatus/livestatuslistener.cpp
blob: e44650bfe585c0b40d70f25667e8d450a9977cf2 (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
202
203
204
205
206
207
208
209
210
211
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "livestatus/livestatuslistener.hpp"
#include "livestatus/livestatuslistener-ti.cpp"
#include "base/utility.hpp"
#include "base/perfdatavalue.hpp"
#include "base/objectlock.hpp"
#include "base/configtype.hpp"
#include "base/logger.hpp"
#include "base/exception.hpp"
#include "base/tcpsocket.hpp"
#include "base/unixsocket.hpp"
#include "base/networkstream.hpp"
#include "base/application.hpp"
#include "base/function.hpp"
#include "base/statsfunction.hpp"
#include "base/convert.hpp"

using namespace icinga;

REGISTER_TYPE(LivestatusListener);

static int l_ClientsConnected = 0;
static int l_Connections = 0;
static std::mutex l_ComponentMutex;

REGISTER_STATSFUNCTION(LivestatusListener, &LivestatusListener::StatsFunc);

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

	for (const LivestatusListener::Ptr& livestatuslistener : ConfigType::GetObjectsByType<LivestatusListener>()) {
		nodes.emplace_back(livestatuslistener->GetName(), new Dictionary({
			{ "connections", l_Connections }
		}));

		perfdata->Add(new PerfdataValue("livestatuslistener_" + livestatuslistener->GetName() + "_connections", l_Connections));
	}

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

/**
 * Starts the component.
 */
void LivestatusListener::Start(bool runtimeCreated)
{
	ObjectImpl<LivestatusListener>::Start(runtimeCreated);

	Log(LogInformation, "LivestatusListener")
		<< "'" << GetName() << "' started.";

	if (GetSocketType() == "tcp") {
		TcpSocket::Ptr socket = new TcpSocket();

		try {
			socket->Bind(GetBindHost(), GetBindPort(), AF_UNSPEC);
		} catch (std::exception&) {
			Log(LogCritical, "LivestatusListener")
				<< "Cannot bind TCP socket on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
			return;
		}

		m_Listener = socket;

		m_Thread = std::thread([this]() { ServerThreadProc(); });

		Log(LogInformation, "LivestatusListener")
			<< "Created TCP socket listening on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
	}
	else if (GetSocketType() == "unix") {
#ifndef _WIN32
		UnixSocket::Ptr socket = new UnixSocket();

		try {
			socket->Bind(GetSocketPath());
		} catch (std::exception&) {
			Log(LogCritical, "LivestatusListener")
				<< "Cannot bind UNIX socket to '" << GetSocketPath() << "'.";
			return;
		}

		/* group must be able to write */
		mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;

		if (chmod(GetSocketPath().CStr(), mode) < 0) {
			Log(LogCritical, "LivestatusListener")
				<< "chmod() on unix socket '" << GetSocketPath() << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
			return;
		}

		m_Listener = socket;

		m_Thread = std::thread([this]() { ServerThreadProc(); });

		Log(LogInformation, "LivestatusListener")
			<< "Created UNIX socket in '" << GetSocketPath() << "'.";
#else
		/* no UNIX sockets on windows */
		Log(LogCritical, "LivestatusListener", "Unix sockets are not supported on Windows.");
		return;
#endif
	}
}

void LivestatusListener::Stop(bool runtimeRemoved)
{
	ObjectImpl<LivestatusListener>::Stop(runtimeRemoved);

	Log(LogInformation, "LivestatusListener")
		<< "'" << GetName() << "' stopped.";

	m_Listener->Close();

	if (m_Thread.joinable())
		m_Thread.join();
}

int LivestatusListener::GetClientsConnected()
{
	std::unique_lock<std::mutex> lock(l_ComponentMutex);

	return l_ClientsConnected;
}

int LivestatusListener::GetConnections()
{
	std::unique_lock<std::mutex> lock(l_ComponentMutex);

	return l_Connections;
}

void LivestatusListener::ServerThreadProc()
{
	m_Listener->Listen();

	try {
		for (;;) {
			timeval tv = { 0, 500000 };

			if (m_Listener->Poll(true, false, &tv)) {
				Socket::Ptr client = m_Listener->Accept();
				Log(LogNotice, "LivestatusListener", "Client connected");
				Utility::QueueAsyncCallback([this, client]() { ClientHandler(client); }, LowLatencyScheduler);
			}

			if (!IsActive())
				break;
		}
	} catch (std::exception&) {
		Log(LogCritical, "LivestatusListener", "Cannot accept new connection.");
	}

	m_Listener->Close();
}

void LivestatusListener::ClientHandler(const Socket::Ptr& client)
{
	{
		std::unique_lock<std::mutex> lock(l_ComponentMutex);
		l_ClientsConnected++;
		l_Connections++;
	}

	Stream::Ptr stream = new NetworkStream(client);

	StreamReadContext context;

	for (;;) {
		String line;

		std::vector<String> lines;

		for (;;) {
			StreamReadStatus srs = stream->ReadLine(&line, context);

			if (srs == StatusEof)
				break;

			if (srs != StatusNewItem)
				continue;

			if (line.GetLength() > 0)
				lines.push_back(line);
			else
				break;
		}

		if (lines.empty())
			break;

		LivestatusQuery::Ptr query = new LivestatusQuery(lines, GetCompatLogPath());
		if (!query->Execute(stream))
			break;
	}

	{
		std::unique_lock<std::mutex> lock(l_ComponentMutex);
		l_ClientsConnected--;
	}
}


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

	if (lvalue() != "unix" && lvalue() != "tcp")
		BOOST_THROW_EXCEPTION(ValidationError(this, { "socket_type" }, "Socket type '" + lvalue() + "' is invalid."));
}