]> granicus.if.org Git - icinga2/blob - lib/compat/checkresultreader.cpp
Add activation priorities for config object types
[icinga2] / lib / compat / checkresultreader.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 "icinga/compatutility.hpp"
21 #include "compat/checkresultreader.hpp"
22 #include "compat/checkresultreader-ti.cpp"
23 #include "icinga/service.hpp"
24 #include "icinga/pluginutility.hpp"
25 #include "icinga/icingaapplication.hpp"
26 #include "base/configtype.hpp"
27 #include "base/objectlock.hpp"
28 #include "base/logger.hpp"
29 #include "base/convert.hpp"
30 #include "base/application.hpp"
31 #include "base/utility.hpp"
32 #include "base/exception.hpp"
33 #include "base/context.hpp"
34 #include "base/statsfunction.hpp"
35 #include <fstream>
36
37 using namespace icinga;
38
39 REGISTER_TYPE(CheckResultReader);
40
41 REGISTER_STATSFUNCTION(CheckResultReader, &CheckResultReader::StatsFunc);
42
43 void CheckResultReader::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&)
44 {
45         DictionaryData nodes;
46
47         for (const CheckResultReader::Ptr& checkresultreader : ConfigType::GetObjectsByType<CheckResultReader>()) {
48                 nodes.emplace_back(checkresultreader->GetName(), 1); //add more stats
49         }
50
51         status->Set("checkresultreader", new Dictionary(std::move(nodes)));
52 }
53
54 /**
55  * @threadsafety Always.
56  */
57 void CheckResultReader::Start(bool runtimeCreated)
58 {
59         ObjectImpl<CheckResultReader>::Start(runtimeCreated);
60
61         Log(LogInformation, "CheckResultReader")
62                 << "'" << GetName() << "' started.";
63         Log(LogWarning, "CheckResultReader")
64                 << "The CheckResultReader feature is deprecated and will be removed with Icinga 2.10.0";
65
66 #ifndef _WIN32
67         m_ReadTimer = new Timer();
68         m_ReadTimer->OnTimerExpired.connect(std::bind(&CheckResultReader::ReadTimerHandler, this));
69         m_ReadTimer->SetInterval(5);
70         m_ReadTimer->Start();
71 #endif /* _WIN32 */
72 }
73
74 /**
75  * @threadsafety Always.
76  */
77 void CheckResultReader::Stop(bool runtimeRemoved)
78 {
79         Log(LogInformation, "CheckResultReader")
80                 << "'" << GetName() << "' stopped.";
81
82         ObjectImpl<CheckResultReader>::Stop(runtimeRemoved);
83 }
84
85 /**
86  * @threadsafety Always.
87  */
88 void CheckResultReader::ReadTimerHandler() const
89 {
90         CONTEXT("Processing check result files in '" + GetSpoolDir() + "'");
91
92         Utility::Glob(GetSpoolDir() + "/c??????.ok", std::bind(&CheckResultReader::ProcessCheckResultFile, this, _1), GlobFile);
93 }
94
95 void CheckResultReader::ProcessCheckResultFile(const String& path) const
96 {
97         CONTEXT("Processing check result file '" + path + "'");
98
99         String crfile = String(path.Begin(), path.End() - 3); /* Remove the ".ok" extension. */
100
101         std::ifstream fp;
102         fp.exceptions(std::ifstream::badbit);
103         fp.open(crfile.CStr());
104
105         std::map<String, String> attrs;
106
107         while (fp.good()) {
108                 std::string line;
109                 std::getline(fp, line);
110
111                 if (line.empty() || line[0] == '#')
112                         continue; /* Ignore comments and empty lines. */
113
114                 size_t pos = line.find_first_of('=');
115
116                 if (pos == std::string::npos)
117                         continue; /* Ignore invalid lines. */
118
119                 String key = line.substr(0, pos);
120                 String value = line.substr(pos + 1);
121
122                 attrs[key] = value;
123         }
124
125         /* Remove the checkresult files. */
126         if (unlink(path.CStr()) < 0)
127                 BOOST_THROW_EXCEPTION(posix_error()
128                         << boost::errinfo_api_function("unlink")
129                         << boost::errinfo_errno(errno)
130                         << boost::errinfo_file_name(path));
131
132         if (unlink(crfile.CStr()) < 0)
133                 BOOST_THROW_EXCEPTION(posix_error()
134                         << boost::errinfo_api_function("unlink")
135                         << boost::errinfo_errno(errno)
136                         << boost::errinfo_file_name(crfile));
137
138         Checkable::Ptr checkable;
139
140         Host::Ptr host = Host::GetByName(attrs["host_name"]);
141
142         if (!host) {
143                 Log(LogWarning, "CheckResultReader")
144                         << "Ignoring checkresult file for host '" << attrs["host_name"] << "': Host does not exist.";
145
146                 return;
147         }
148
149         if (attrs.find("service_description") != attrs.end()) {
150                 Service::Ptr service = host->GetServiceByShortName(attrs["service_description"]);
151
152                 if (!service) {
153                         Log(LogWarning, "CheckResultReader")
154                                 << "Ignoring checkresult file for host '" << attrs["host_name"]
155                                 << "', service '" << attrs["service_description"] << "': Service does not exist.";
156
157                         return;
158                 }
159
160                 checkable = service;
161         } else
162                 checkable = host;
163
164         CheckResult::Ptr result = new CheckResult();
165         String output = CompatUtility::UnEscapeString(attrs["output"]);
166         std::pair<String, Value> co = PluginUtility::ParseCheckOutput(output);
167         result->SetOutput(co.first);
168         result->SetPerformanceData(PluginUtility::SplitPerfdata(co.second));
169         result->SetState(PluginUtility::ExitStatusToState(Convert::ToLong(attrs["return_code"])));
170
171         if (attrs.find("start_time") != attrs.end())
172                 result->SetExecutionStart(Convert::ToDouble(attrs["start_time"]));
173         else
174                 result->SetExecutionStart(Utility::GetTime());
175
176         if (attrs.find("finish_time") != attrs.end())
177                 result->SetExecutionEnd(Convert::ToDouble(attrs["finish_time"]));
178         else
179                 result->SetExecutionEnd(result->GetExecutionStart());
180
181         checkable->ProcessCheckResult(result);
182
183         Log(LogDebug, "CheckResultReader")
184                 << "Processed checkresult file for object '" << checkable->GetName() << "'";
185
186         /* Reschedule the next check. The side effect of this is that for as long
187          * as we receive check result files for a host/service we won't execute any
188          * active checks. */
189         checkable->SetNextCheck(Utility::GetTime() + checkable->GetCheckInterval());
190 }