]> granicus.if.org Git - icinga2/blob - lib/livestatus/livestatuslistener.cpp
Move CompatUtility::GetCheckableInCheckPeriod() into Livestatus feature
[icinga2] / lib / livestatus / livestatuslistener.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2018 Icinga Development Team (https://www.icinga.com/)  *
4  *                                                                            *
5  * This program is free software; you can redistribute it and/or              *
6  * modify it under the terms of the GNU General Public License                *
7  * as published by the Free Software Foundation; either version 2             *
8  * of the License, or (at your option) any later version.                     *
9  *                                                                            *
10  * This program is distributed in the hope that it will be useful,            *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
13  * GNU General Public License for more details.                               *
14  *                                                                            *
15  * You should have received a copy of the GNU General Public License          *
16  * along with this program; if not, write to the Free Software Foundation     *
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.             *
18  ******************************************************************************/
19
20 #include "livestatus/livestatuslistener.hpp"
21 #include "livestatus/livestatuslistener.tcpp"
22 #include "base/utility.hpp"
23 #include "base/perfdatavalue.hpp"
24 #include "base/objectlock.hpp"
25 #include "base/configtype.hpp"
26 #include "base/logger.hpp"
27 #include "base/exception.hpp"
28 #include "base/tcpsocket.hpp"
29 #include "base/unixsocket.hpp"
30 #include "base/networkstream.hpp"
31 #include "base/application.hpp"
32 #include "base/function.hpp"
33 #include "base/statsfunction.hpp"
34 #include "base/convert.hpp"
35
36 using namespace icinga;
37
38 REGISTER_TYPE(LivestatusListener);
39
40 static int l_ClientsConnected = 0;
41 static int l_Connections = 0;
42 static boost::mutex l_ComponentMutex;
43
44 REGISTER_STATSFUNCTION(LivestatusListener, &LivestatusListener::StatsFunc);
45
46 void LivestatusListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
47 {
48         Dictionary::Ptr nodes = new Dictionary();
49
50         for (const LivestatusListener::Ptr& livestatuslistener : ConfigType::GetObjectsByType<LivestatusListener>()) {
51                 Dictionary::Ptr stats = new Dictionary();
52                 stats->Set("connections", l_Connections);
53
54                 nodes->Set(livestatuslistener->GetName(), stats);
55
56                 perfdata->Add(new PerfdataValue("livestatuslistener_" + livestatuslistener->GetName() + "_connections", l_Connections));
57         }
58
59         status->Set("livestatuslistener", nodes);
60 }
61
62 /**
63  * Starts the component.
64  */
65 void LivestatusListener::Start(bool runtimeCreated)
66 {
67         ObjectImpl<LivestatusListener>::Start(runtimeCreated);
68
69         Log(LogInformation, "LivestatusListener")
70                 << "'" << GetName() << "' started.";
71
72         if (GetSocketType() == "tcp") {
73                 TcpSocket::Ptr socket = new TcpSocket();
74
75                 try {
76                         socket->Bind(GetBindHost(), GetBindPort(), AF_UNSPEC);
77                 } catch (std::exception&) {
78                         Log(LogCritical, "LivestatusListener")
79                                 << "Cannot bind TCP socket on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
80                         return;
81                 }
82
83                 m_Listener = socket;
84
85                 m_Thread = std::thread(std::bind(&LivestatusListener::ServerThreadProc, this));
86
87                 Log(LogInformation, "LivestatusListener")
88                         << "Created TCP socket listening on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
89         }
90         else if (GetSocketType() == "unix") {
91 #ifndef _WIN32
92                 UnixSocket::Ptr socket = new UnixSocket();
93
94                 try {
95                         socket->Bind(GetSocketPath());
96                 } catch (std::exception&) {
97                         Log(LogCritical, "LivestatusListener")
98                                 << "Cannot bind UNIX socket to '" << GetSocketPath() << "'.";
99                         return;
100                 }
101
102                 /* group must be able to write */
103                 mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
104
105                 if (chmod(GetSocketPath().CStr(), mode) < 0) {
106                         Log(LogCritical, "LivestatusListener")
107                                 << "chmod() on unix socket '" << GetSocketPath() << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
108                         return;
109                 }
110
111                 m_Listener = socket;
112
113                 m_Thread = std::thread(std::bind(&LivestatusListener::ServerThreadProc, this));
114
115                 Log(LogInformation, "LivestatusListener")
116                         << "Created UNIX socket in '" << GetSocketPath() << "'.";
117 #else
118                 /* no UNIX sockets on windows */
119                 Log(LogCritical, "LivestatusListener", "Unix sockets are not supported on Windows.");
120                 return;
121 #endif
122         }
123 }
124
125 void LivestatusListener::Stop(bool runtimeRemoved)
126 {
127         ObjectImpl<LivestatusListener>::Stop(runtimeRemoved);
128
129         Log(LogInformation, "LivestatusListener")
130                 << "'" << GetName() << "' stopped.";
131
132         m_Listener->Close();
133
134         if (m_Thread.joinable())
135                 m_Thread.join();
136 }
137
138 int LivestatusListener::GetClientsConnected()
139 {
140         boost::mutex::scoped_lock lock(l_ComponentMutex);
141
142         return l_ClientsConnected;
143 }
144
145 int LivestatusListener::GetConnections()
146 {
147         boost::mutex::scoped_lock lock(l_ComponentMutex);
148
149         return l_Connections;
150 }
151
152 void LivestatusListener::ServerThreadProc()
153 {
154         m_Listener->Listen();
155
156         try {
157                 for (;;) {
158                         timeval tv = { 0, 500000 };
159
160                         if (m_Listener->Poll(true, false, &tv)) {
161                                 Socket::Ptr client = m_Listener->Accept();
162                                 Log(LogNotice, "LivestatusListener", "Client connected");
163                                 Utility::QueueAsyncCallback(std::bind(&LivestatusListener::ClientHandler, this, client), LowLatencyScheduler);
164                         }
165
166                         if (!IsActive())
167                                 break;
168                 }
169         } catch (std::exception&) {
170                 Log(LogCritical, "LivestatusListener", "Cannot accept new connection.");
171         }
172
173         m_Listener->Close();
174 }
175
176 void LivestatusListener::ClientHandler(const Socket::Ptr& client)
177 {
178         {
179                 boost::mutex::scoped_lock lock(l_ComponentMutex);
180                 l_ClientsConnected++;
181                 l_Connections++;
182         }
183
184         Stream::Ptr stream = new NetworkStream(client);
185
186         StreamReadContext context;
187
188         for (;;) {
189                 String line;
190
191                 std::vector<String> lines;
192
193                 for (;;) {
194                         StreamReadStatus srs = stream->ReadLine(&line, context);
195
196                         if (srs == StatusEof)
197                                 break;
198
199                         if (srs != StatusNewItem)
200                                 continue;
201
202                         if (line.GetLength() > 0)
203                                 lines.push_back(line);
204                         else
205                                 break;
206                 }
207
208                 if (lines.empty())
209                         break;
210
211                 LivestatusQuery::Ptr query = new LivestatusQuery(lines, GetCompatLogPath());
212                 if (!query->Execute(stream))
213                         break;
214         }
215
216         {
217                 boost::mutex::scoped_lock lock(l_ComponentMutex);
218                 l_ClientsConnected--;
219         }
220 }
221
222
223 void LivestatusListener::ValidateSocketType(const Lazy<String>& lvalue, const ValidationUtils& utils)
224 {
225         ObjectImpl<LivestatusListener>::ValidateSocketType(lvalue, utils);
226
227         if (lvalue() != "unix" && lvalue() != "tcp")
228                 BOOST_THROW_EXCEPTION(ValidationError(this, { "socket_type" }, "Socket type '" + lvalue() + "' is invalid."));
229 }