]> granicus.if.org Git - icinga2/blob - lib/livestatus/livestatuslistener.cpp
Merge pull request #6509 from gunnarbeutner/feature/real-constants
[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-ti.cpp"
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         DictionaryData nodes;
49
50         for (const LivestatusListener::Ptr& livestatuslistener : ConfigType::GetObjectsByType<LivestatusListener>()) {
51                 nodes.emplace_back(livestatuslistener->GetName(), new Dictionary({
52                         { "connections", l_Connections }
53                 }));
54
55                 perfdata->Add(new PerfdataValue("livestatuslistener_" + livestatuslistener->GetName() + "_connections", l_Connections));
56         }
57
58         status->Set("livestatuslistener", new Dictionary(std::move(nodes)));
59 }
60
61 /**
62  * Starts the component.
63  */
64 void LivestatusListener::Start(bool runtimeCreated)
65 {
66         ObjectImpl<LivestatusListener>::Start(runtimeCreated);
67
68         Log(LogInformation, "LivestatusListener")
69                 << "'" << GetName() << "' started.";
70
71         if (GetSocketType() == "tcp") {
72                 TcpSocket::Ptr socket = new TcpSocket();
73
74                 try {
75                         socket->Bind(GetBindHost(), GetBindPort(), AF_UNSPEC);
76                 } catch (std::exception&) {
77                         Log(LogCritical, "LivestatusListener")
78                                 << "Cannot bind TCP socket on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
79                         return;
80                 }
81
82                 m_Listener = socket;
83
84                 m_Thread = std::thread(std::bind(&LivestatusListener::ServerThreadProc, this));
85
86                 Log(LogInformation, "LivestatusListener")
87                         << "Created TCP socket listening on host '" << GetBindHost() << "' port '" << GetBindPort() << "'.";
88         }
89         else if (GetSocketType() == "unix") {
90 #ifndef _WIN32
91                 UnixSocket::Ptr socket = new UnixSocket();
92
93                 try {
94                         socket->Bind(GetSocketPath());
95                 } catch (std::exception&) {
96                         Log(LogCritical, "LivestatusListener")
97                                 << "Cannot bind UNIX socket to '" << GetSocketPath() << "'.";
98                         return;
99                 }
100
101                 /* group must be able to write */
102                 mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
103
104                 if (chmod(GetSocketPath().CStr(), mode) < 0) {
105                         Log(LogCritical, "LivestatusListener")
106                                 << "chmod() on unix socket '" << GetSocketPath() << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
107                         return;
108                 }
109
110                 m_Listener = socket;
111
112                 m_Thread = std::thread(std::bind(&LivestatusListener::ServerThreadProc, this));
113
114                 Log(LogInformation, "LivestatusListener")
115                         << "Created UNIX socket in '" << GetSocketPath() << "'.";
116 #else
117                 /* no UNIX sockets on windows */
118                 Log(LogCritical, "LivestatusListener", "Unix sockets are not supported on Windows.");
119                 return;
120 #endif
121         }
122 }
123
124 void LivestatusListener::Stop(bool runtimeRemoved)
125 {
126         ObjectImpl<LivestatusListener>::Stop(runtimeRemoved);
127
128         Log(LogInformation, "LivestatusListener")
129                 << "'" << GetName() << "' stopped.";
130
131         m_Listener->Close();
132
133         if (m_Thread.joinable())
134                 m_Thread.join();
135 }
136
137 int LivestatusListener::GetClientsConnected()
138 {
139         boost::mutex::scoped_lock lock(l_ComponentMutex);
140
141         return l_ClientsConnected;
142 }
143
144 int LivestatusListener::GetConnections()
145 {
146         boost::mutex::scoped_lock lock(l_ComponentMutex);
147
148         return l_Connections;
149 }
150
151 void LivestatusListener::ServerThreadProc()
152 {
153         m_Listener->Listen();
154
155         try {
156                 for (;;) {
157                         timeval tv = { 0, 500000 };
158
159                         if (m_Listener->Poll(true, false, &tv)) {
160                                 Socket::Ptr client = m_Listener->Accept();
161                                 Log(LogNotice, "LivestatusListener", "Client connected");
162                                 Utility::QueueAsyncCallback(std::bind(&LivestatusListener::ClientHandler, this, client), LowLatencyScheduler);
163                         }
164
165                         if (!IsActive())
166                                 break;
167                 }
168         } catch (std::exception&) {
169                 Log(LogCritical, "LivestatusListener", "Cannot accept new connection.");
170         }
171
172         m_Listener->Close();
173 }
174
175 void LivestatusListener::ClientHandler(const Socket::Ptr& client)
176 {
177         {
178                 boost::mutex::scoped_lock lock(l_ComponentMutex);
179                 l_ClientsConnected++;
180                 l_Connections++;
181         }
182
183         Stream::Ptr stream = new NetworkStream(client);
184
185         StreamReadContext context;
186
187         for (;;) {
188                 String line;
189
190                 std::vector<String> lines;
191
192                 for (;;) {
193                         StreamReadStatus srs = stream->ReadLine(&line, context);
194
195                         if (srs == StatusEof)
196                                 break;
197
198                         if (srs != StatusNewItem)
199                                 continue;
200
201                         if (line.GetLength() > 0)
202                                 lines.push_back(line);
203                         else
204                                 break;
205                 }
206
207                 if (lines.empty())
208                         break;
209
210                 LivestatusQuery::Ptr query = new LivestatusQuery(lines, GetCompatLogPath());
211                 if (!query->Execute(stream))
212                         break;
213         }
214
215         {
216                 boost::mutex::scoped_lock lock(l_ComponentMutex);
217                 l_ClientsConnected--;
218         }
219 }
220
221
222 void LivestatusListener::ValidateSocketType(const Lazy<String>& lvalue, const ValidationUtils& utils)
223 {
224         ObjectImpl<LivestatusListener>::ValidateSocketType(lvalue, utils);
225
226         if (lvalue() != "unix" && lvalue() != "tcp")
227                 BOOST_THROW_EXCEPTION(ValidationError(this, { "socket_type" }, "Socket type '" + lvalue() + "' is invalid."));
228 }