1 /******************************************************************************
3 * Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.org) *
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. *
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. *
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 ******************************************************************************/
20 #include "remote/apilistener.hpp"
21 #include "remote/apiclient.hpp"
22 #include "remote/endpoint.hpp"
23 #include "base/convert.hpp"
24 #include "base/netstring.hpp"
25 #include "base/dynamictype.hpp"
26 #include "base/logger_fwd.hpp"
27 #include "base/objectlock.hpp"
28 #include "base/stdiostream.hpp"
29 #include "base/application.hpp"
30 #include "base/context.hpp"
31 #include "base/statsfunction.hpp"
34 using namespace icinga;
36 REGISTER_TYPE(ApiListener);
38 boost::signals2::signal<void(bool)> ApiListener::OnMasterChanged;
40 REGISTER_STATSFUNCTION(ApiListenerStats, &ApiListener::StatsFunc);
42 void ApiListener::OnConfigLoaded(void)
44 /* set up SSL context */
45 shared_ptr<X509> cert = GetX509Certificate(GetCertPath());
46 SetIdentity(GetCertificateCN(cert));
47 Log(LogInformation, "remote", "My API identity: " + GetIdentity());
49 m_SSLContext = MakeSSLContext(GetCertPath(), GetKeyPath(), GetCaPath());
51 if (!GetCrlPath().IsEmpty())
52 AddCRLToSSLContext(m_SSLContext, GetCrlPath());
54 if (!Endpoint::GetByName(GetIdentity()))
55 BOOST_THROW_EXCEPTION(std::runtime_error("Endpoint object for '" + GetIdentity() + "' is missing."));
61 * Starts the component.
63 void ApiListener::Start(void)
65 if (std::distance(DynamicType::GetObjects<ApiListener>().first, DynamicType::GetObjects<ApiListener>().second) > 1)
66 BOOST_THROW_EXCEPTION(std::runtime_error("Only one ApiListener object is allowed."));
68 DynamicObject::Start();
71 boost::mutex::scoped_lock(m_LogLock);
76 /* create the primary JSON-RPC listener */
77 AddListener(GetBindPort());
79 m_Timer = make_shared<Timer>();
80 m_Timer->OnTimerExpired.connect(boost::bind(&ApiListener::ApiTimerHandler, this));
81 m_Timer->SetInterval(5);
83 m_Timer->Reschedule(0);
85 OnMasterChanged(true);
88 ApiListener::Ptr ApiListener::GetInstance(void)
90 BOOST_FOREACH(const ApiListener::Ptr& listener, DynamicType::GetObjects<ApiListener>())
93 return ApiListener::Ptr();
96 shared_ptr<SSL_CTX> ApiListener::GetSSLContext(void) const
101 Endpoint::Ptr ApiListener::GetMaster(void) const
103 Zone::Ptr zone = Zone::GetLocalZone();
104 std::vector<String> names;
106 BOOST_FOREACH(const Endpoint::Ptr& endpoint, zone->GetEndpoints())
107 if (endpoint->IsConnected() || endpoint->GetName() == GetIdentity())
108 names.push_back(endpoint->GetName());
110 std::sort(names.begin(), names.end());
112 return Endpoint::GetByName(*names.begin());
115 bool ApiListener::IsMaster(void) const
117 return GetMaster()->GetName() == GetIdentity();
121 * Creates a new JSON-RPC listener on the specified port.
123 * @param service The port to listen on.
125 void ApiListener::AddListener(const String& service)
127 ObjectLock olock(this);
129 shared_ptr<SSL_CTX> sslContext = m_SSLContext;
132 BOOST_THROW_EXCEPTION(std::logic_error("SSL context is required for AddListener()"));
134 std::ostringstream s;
135 s << "Adding new listener: port " << service;
136 Log(LogInformation, "remote", s.str());
138 TcpSocket::Ptr server = make_shared<TcpSocket>();
139 server->Bind(service, AF_INET6);
141 boost::thread thread(boost::bind(&ApiListener::ListenerThreadProc, this, server));
144 m_Servers.insert(server);
147 void ApiListener::ListenerThreadProc(const Socket::Ptr& server)
149 Utility::SetThreadName("API Listener");
154 Socket::Ptr client = server->Accept();
156 Utility::QueueAsyncCallback(boost::bind(&ApiListener::NewClientHandler, this, client, RoleServer));
161 * Creates a new JSON-RPC client and connects to the specified host and port.
163 * @param node The remote host.
164 * @param service The remote port.
166 void ApiListener::AddConnection(const String& node, const String& service)
169 ObjectLock olock(this);
171 shared_ptr<SSL_CTX> sslContext = m_SSLContext;
174 BOOST_THROW_EXCEPTION(std::logic_error("SSL context is required for AddConnection()"));
177 TcpSocket::Ptr client = make_shared<TcpSocket>();
180 client->Connect(node, service);
181 Utility::QueueAsyncCallback(boost::bind(&ApiListener::NewClientHandler, this, client, RoleClient));
182 } catch (const std::exception& ex) {
183 std::ostringstream info, debug;
184 info << "Cannot connect to host '" << node << "' on port '" << service << "'";
185 debug << info.str() << std::endl << DiagnosticInformation(ex);
186 Log(LogCritical, "remote", info.str());
187 Log(LogDebug, "remote", debug.str());
192 * Processes a new client connection.
194 * @param client The new client.
196 void ApiListener::NewClientHandler(const Socket::Ptr& client, ConnectionRole role)
198 CONTEXT("Handling new API client connection");
200 TlsStream::Ptr tlsStream;
203 ObjectLock olock(this);
204 tlsStream = make_shared<TlsStream>(client, role, m_SSLContext);
207 tlsStream->Handshake();
209 shared_ptr<X509> cert = tlsStream->GetPeerCertificate();
210 String identity = GetCertificateCN(cert);
212 Log(LogInformation, "remote", "New client connection for identity '" + identity + "'");
214 Endpoint::Ptr endpoint = Endpoint::GetByName(identity);
216 bool need_sync = false;
219 need_sync = !endpoint->IsConnected();
221 ApiClient::Ptr aclient = make_shared<ApiClient>(identity, tlsStream, role);
227 ObjectLock olock(endpoint);
229 endpoint->SetSyncing(true);
235 SendConfigUpdate(aclient);
237 endpoint->AddClient(aclient);
239 AddAnonymousClient(aclient);
242 void ApiListener::ApiTimerHandler(void)
244 double now = Utility::GetTime();
246 std::vector<int> files;
247 Utility::Glob(GetApiDir() + "log/*", boost::bind(&ApiListener::LogGlobHandler, boost::ref(files), _1), GlobFile);
248 std::sort(files.begin(), files.end());
250 BOOST_FOREACH(int ts, files) {
253 BOOST_FOREACH(const Endpoint::Ptr& endpoint, DynamicType::GetObjects<Endpoint>()) {
254 if (endpoint->GetName() == GetIdentity())
257 if (endpoint->GetLogDuration() >= 0 && ts < now - endpoint->GetLogDuration())
260 if (ts > endpoint->GetLocalLogPosition()) {
267 String path = GetApiDir() + "log/" + Convert::ToString(ts);
268 Log(LogNotice, "remote", "Removing old log file: " + path);
269 (void)unlink(path.CStr());
274 Zone::Ptr my_zone = Zone::GetLocalZone();
276 BOOST_FOREACH(const Zone::Ptr& zone, DynamicType::GetObjects<Zone>()) {
277 /* only connect to endpoints in a) the same zone b) our parent zone c) immediate child zones */
278 if (my_zone != zone && my_zone != zone->GetParent() && zone != my_zone->GetParent())
281 bool connected = false;
283 BOOST_FOREACH(const Endpoint::Ptr& endpoint, zone->GetEndpoints()) {
284 if (endpoint->IsConnected()) {
290 /* don't connect to an endpoint if we already have a connection to the zone */
294 BOOST_FOREACH(const Endpoint::Ptr& endpoint, zone->GetEndpoints()) {
295 /* don't connect to ourselves */
296 if (endpoint->GetName() == GetIdentity())
299 /* don't try to connect to endpoints which don't have a host and port */
300 if (endpoint->GetHost().IsEmpty() || endpoint->GetPort().IsEmpty())
303 AddConnection(endpoint->GetHost(), endpoint->GetPort());
308 BOOST_FOREACH(const Endpoint::Ptr& endpoint, DynamicType::GetObjects<Endpoint>()) {
309 if (!endpoint->IsConnected())
312 double ts = endpoint->GetRemoteLogPosition();
317 Dictionary::Ptr lparams = make_shared<Dictionary>();
318 lparams->Set("log_position", ts);
320 Dictionary::Ptr lmessage = make_shared<Dictionary>();
321 lmessage->Set("jsonrpc", "2.0");
322 lmessage->Set("method", "log::SetLogPosition");
323 lmessage->Set("params", lparams);
325 BOOST_FOREACH(const ApiClient::Ptr& client, endpoint->GetClients())
326 client->SendMessage(lmessage);
328 Log(LogNotice, "remote", "Setting log position for identity '" + endpoint->GetName() + "': " +
329 Utility::FormatDateTime("%Y/%m/%d %H:%M:%S", ts));
332 Log(LogNotice, "remote", "Current zone master: " + GetMaster()->GetName());
334 std::vector<String> names;
335 BOOST_FOREACH(const Endpoint::Ptr& endpoint, DynamicType::GetObjects<Endpoint>())
336 if (endpoint->IsConnected())
337 names.push_back(endpoint->GetName() + " (" + Convert::ToString(endpoint->GetClients().size()) + ")");
339 Log(LogNotice, "remote", "Connected endpoints: " + Utility::NaturalJoin(names));
342 void ApiListener::RelayMessage(const MessageOrigin& origin, const DynamicObject::Ptr& secobj, const Dictionary::Ptr& message, bool log)
344 m_RelayQueue.Enqueue(boost::bind(&ApiListener::SyncRelayMessage, this, origin, secobj, message, log));
347 void ApiListener::PersistMessage(const Dictionary::Ptr& message)
349 double ts = message->Get("ts");
353 Dictionary::Ptr pmessage = make_shared<Dictionary>();
354 pmessage->Set("timestamp", ts);
356 pmessage->Set("message", JsonSerialize(message));
358 boost::mutex::scoped_lock lock(m_LogLock);
360 NetString::WriteStringToStream(m_LogFile, JsonSerialize(pmessage));
362 SetLogMessageTimestamp(ts);
364 if (m_LogMessageCount > 50000) {
372 void ApiListener::SyncRelayMessage(const MessageOrigin& origin, const DynamicObject::Ptr& secobj, const Dictionary::Ptr& message, bool log)
374 double ts = Utility::GetTime();
375 message->Set("ts", ts);
377 Log(LogNotice, "remote", "Relaying '" + message->Get("method") + "' message");
380 m_LogQueue.Enqueue(boost::bind(&ApiListener::PersistMessage, this, message));
383 message->Set("originZone", origin.FromZone->GetName());
385 bool is_master = IsMaster();
386 Endpoint::Ptr master = GetMaster();
387 Zone::Ptr my_zone = Zone::GetLocalZone();
389 std::vector<Endpoint::Ptr> skippedEndpoints;
390 std::set<Zone::Ptr> finishedZones;
392 BOOST_FOREACH(const Endpoint::Ptr& endpoint, DynamicType::GetObjects<Endpoint>()) {
393 /* don't relay messages to ourselves or disconnected endpoints */
394 if (endpoint->GetName() == GetIdentity() || !endpoint->IsConnected())
397 Zone::Ptr target_zone = endpoint->GetZone();
399 /* don't relay the message to the zone through more than one endpoint */
400 if (finishedZones.find(target_zone) != finishedZones.end()) {
401 skippedEndpoints.push_back(endpoint);
405 /* don't relay messages back to the endpoint which we got the message from */
406 if (origin.FromClient && endpoint == origin.FromClient->GetEndpoint()) {
407 skippedEndpoints.push_back(endpoint);
411 /* don't relay messages back to the zone which we got the message from */
412 if (origin.FromZone && target_zone == origin.FromZone) {
413 skippedEndpoints.push_back(endpoint);
417 /* only relay message to the master if we're not currently the master */
418 if (!is_master && master != endpoint) {
419 skippedEndpoints.push_back(endpoint);
423 /* only relay the message to a) the same zone, b) the parent zone and c) direct child zones */
424 if (target_zone != my_zone && target_zone != my_zone->GetParent() &&
425 secobj->GetZone() != target_zone->GetName()) {
426 skippedEndpoints.push_back(endpoint);
430 /* only relay messages to zones which have access to the object */
431 if (!target_zone->CanAccessObject(secobj))
434 finishedZones.insert(target_zone);
437 ObjectLock olock(endpoint);
439 if (!endpoint->GetSyncing()) {
440 Log(LogNotice, "remote", "Sending message to '" + endpoint->GetName() + "'");
442 BOOST_FOREACH(const ApiClient::Ptr& client, endpoint->GetClients())
443 client->SendMessage(message);
448 BOOST_FOREACH(const Endpoint::Ptr& endpoint, skippedEndpoints)
449 endpoint->SetLocalLogPosition(ts);
452 String ApiListener::GetApiDir(void)
454 return Application::GetLocalStateDir() + "/lib/icinga2/api/";
457 /* must hold m_LogLock */
458 void ApiListener::OpenLogFile(void)
460 String path = GetApiDir() + "log/current";
462 std::fstream *fp = new std::fstream(path.CStr(), std::fstream::out | std::ofstream::app);
465 Log(LogWarning, "cluster", "Could not open spool file: " + path);
469 m_LogFile = make_shared<StdioStream>(fp, true);
470 m_LogMessageCount = 0;
471 SetLogMessageTimestamp(Utility::GetTime());
474 /* must hold m_LogLock */
475 void ApiListener::CloseLogFile(void)
484 /* must hold m_LogLock */
485 void ApiListener::RotateLogFile(void)
487 double ts = GetLogMessageTimestamp();
490 ts = Utility::GetTime();
492 String oldpath = GetApiDir() + "log/current";
493 String newpath = GetApiDir() + "log/" + Convert::ToString(static_cast<int>(ts)+1);
494 (void) rename(oldpath.CStr(), newpath.CStr());
497 void ApiListener::LogGlobHandler(std::vector<int>& files, const String& file)
499 String name = Utility::BaseName(file);
504 ts = Convert::ToLong(name);
506 catch (const std::exception&) {
513 void ApiListener::ReplayLog(const ApiClient::Ptr& client)
515 Endpoint::Ptr endpoint = client->GetEndpoint();
517 CONTEXT("Replaying log for Endpoint '" + endpoint->GetName() + "'");
520 double peer_ts = endpoint->GetLocalLogPosition();
521 bool last_sync = false;
524 boost::mutex::scoped_lock lock(m_LogLock);
529 if (count == -1 || count > 50000) {
538 std::vector<int> files;
539 Utility::Glob(GetApiDir() + "log/*", boost::bind(&ApiListener::LogGlobHandler, boost::ref(files), _1), GlobFile);
540 std::sort(files.begin(), files.end());
542 BOOST_FOREACH(int ts, files) {
543 String path = GetApiDir() + "log/" + Convert::ToString(ts);
548 Log(LogNotice, "remote", "Replaying log: " + path);
550 std::fstream *fp = new std::fstream(path.CStr(), std::fstream::in);
551 StdioStream::Ptr logStream = make_shared<StdioStream>(fp, true);
555 Dictionary::Ptr pmessage;
558 if (!NetString::ReadStringFromStream(logStream, &message))
561 pmessage = JsonDeserialize(message);
562 } catch (const std::exception&) {
563 Log(LogWarning, "remote", "Unexpected end-of-file for cluster log: " + path);
565 /* Log files may be incomplete or corrupted. This is perfectly OK. */
569 if (pmessage->Get("timestamp") <= peer_ts)
572 NetString::WriteStringToStream(client->GetStream(), pmessage->Get("message"));
575 peer_ts = pmessage->Get("timestamp");
581 Log(LogNotice, "remote", "Replayed " + Convert::ToString(count) + " messages.");
585 ObjectLock olock2(endpoint);
586 endpoint->SetSyncing(false);
596 Value ApiListener::StatsFunc(Dictionary::Ptr& status, Dictionary::Ptr& perfdata)
598 Dictionary::Ptr nodes = make_shared<Dictionary>();
599 std::pair<Dictionary::Ptr, Dictionary::Ptr> stats;
601 ApiListener::Ptr listener = ApiListener::GetInstance();
606 stats = listener->GetStatus();
608 BOOST_FOREACH(Dictionary::Pair const& kv, stats.second)
609 perfdata->Set("api_" + kv.first, kv.second);
611 status->Set("api", stats.first);
616 std::pair<Dictionary::Ptr, Dictionary::Ptr> ApiListener::GetStatus(void)
618 Dictionary::Ptr status = make_shared<Dictionary>();
619 Dictionary::Ptr perfdata = make_shared<Dictionary>();
622 status->Set("identity", GetIdentity());
624 double count_endpoints = 0;
625 Array::Ptr not_connected_endpoints = make_shared<Array>();
626 Array::Ptr connected_endpoints = make_shared<Array>();
628 BOOST_FOREACH(const Endpoint::Ptr& endpoint, DynamicType::GetObjects<Endpoint>()) {
629 if (endpoint->GetName() == GetIdentity())
634 if (!endpoint->IsConnected())
635 not_connected_endpoints->Add(endpoint->GetName());
637 connected_endpoints->Add(endpoint->GetName());
640 status->Set("num_endpoints", count_endpoints);
641 status->Set("num_conn_endpoints", connected_endpoints->GetLength());
642 status->Set("num_not_conn_endpoints", not_connected_endpoints->GetLength());
643 status->Set("conn_endpoints", connected_endpoints);
644 status->Set("not_conn_endpoints", not_connected_endpoints);
646 perfdata->Set("num_endpoints", count_endpoints);
647 perfdata->Set("num_conn_endpoints", Convert::ToDouble(connected_endpoints->GetLength()));
648 perfdata->Set("num_not_conn_endpoints", Convert::ToDouble(not_connected_endpoints->GetLength()));
650 return std::make_pair(status, perfdata);
653 void ApiListener::AddAnonymousClient(const ApiClient::Ptr& aclient)
655 ObjectLock olock(this);
656 m_AnonymousClients.insert(aclient);
659 void ApiListener::RemoveAnonymousClient(const ApiClient::Ptr& aclient)
661 ObjectLock olock(this);
662 m_AnonymousClients.erase(aclient);
665 std::set<ApiClient::Ptr> ApiListener::GetAnonymousClients(void) const
667 ObjectLock olock(this);
668 return m_AnonymousClients;