1 /******************************************************************************
3 * Copyright (C) 2012-2015 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 "livestatus/livestatusquery.hpp"
21 #include "livestatus/countaggregator.hpp"
22 #include "livestatus/sumaggregator.hpp"
23 #include "livestatus/minaggregator.hpp"
24 #include "livestatus/maxaggregator.hpp"
25 #include "livestatus/avgaggregator.hpp"
26 #include "livestatus/stdaggregator.hpp"
27 #include "livestatus/invsumaggregator.hpp"
28 #include "livestatus/invavgaggregator.hpp"
29 #include "livestatus/attributefilter.hpp"
30 #include "livestatus/negatefilter.hpp"
31 #include "livestatus/orfilter.hpp"
32 #include "livestatus/andfilter.hpp"
33 #include "icinga/externalcommandprocessor.hpp"
34 #include "config/configcompiler.hpp"
35 #include "base/debug.hpp"
36 #include "base/convert.hpp"
37 #include "base/objectlock.hpp"
38 #include "base/logger.hpp"
39 #include "base/exception.hpp"
40 #include "base/utility.hpp"
41 #include "base/json.hpp"
42 #include "base/serializer.hpp"
43 #include "base/timer.hpp"
44 #include "base/initialize.hpp"
45 #include <boost/algorithm/string/classification.hpp>
46 #include <boost/foreach.hpp>
47 #include <boost/algorithm/string/replace.hpp>
48 #include <boost/algorithm/string/split.hpp>
49 #include <boost/algorithm/string/join.hpp>
51 using namespace icinga;
53 static int l_ExternalCommands = 0;
54 static boost::mutex l_QueryMutex;
55 static std::map<String, LivestatusScriptFrame> l_LivestatusScriptFrames;
56 static Timer::Ptr l_FrameCleanupTimer;
57 static boost::mutex l_LivestatusScriptMutex;
59 static void ScriptFrameCleanupHandler(void)
61 boost::mutex::scoped_lock lock(l_LivestatusScriptMutex);
63 std::vector<String> cleanup_keys;
65 typedef std::pair<String, LivestatusScriptFrame> KVPair;
67 BOOST_FOREACH(const KVPair& kv, l_LivestatusScriptFrames) {
68 if (kv.second.Seen < Utility::GetTime() - 1800)
69 cleanup_keys.push_back(kv.first);
72 BOOST_FOREACH(const String& key, cleanup_keys)
73 l_LivestatusScriptFrames.erase(key);
76 static void InitScriptFrameCleanup(void)
78 l_FrameCleanupTimer = new Timer();
79 l_FrameCleanupTimer->OnTimerExpired.connect(boost::bind(ScriptFrameCleanupHandler));
80 l_FrameCleanupTimer->SetInterval(30);
81 l_FrameCleanupTimer->Start();
84 INITIALIZE_ONCE(InitScriptFrameCleanup);
86 LivestatusQuery::LivestatusQuery(const std::vector<String>& lines, const String& compat_log_path)
87 : m_KeepAlive(false), m_OutputFormat("csv"), m_ColumnHeaders(true),
88 m_LogTimeFrom(0), m_LogTimeUntil(static_cast<long>(Utility::GetTime()))
90 if (lines.size() == 0) {
92 m_ErrorCode = LivestatusErrorQuery;
93 m_ErrorMessage = "Empty Query. Aborting.";
98 BOOST_FOREACH(const String& line, lines) {
101 Log(LogDebug, "LivestatusQuery", msg);
103 m_CompatLogPath = compat_log_path;
105 /* default separators */
106 m_Separators.push_back("\n");
107 m_Separators.push_back(";");
108 m_Separators.push_back(",");
109 m_Separators.push_back("|");
111 String line = lines[0];
113 size_t sp_index = line.FindFirstOf(" ");
115 if (sp_index == String::NPos)
116 BOOST_THROW_EXCEPTION(std::runtime_error("Livestatus header must contain a verb."));
118 String verb = line.SubStr(0, sp_index);
119 String target = line.SubStr(sp_index + 1);
123 if (m_Verb == "COMMAND") {
126 } else if (m_Verb == "SCRIPT") {
129 for (unsigned int i = 1; i < lines.size(); i++) {
132 m_Command += lines[i];
136 } else if (m_Verb == "GET") {
140 m_ErrorCode = LivestatusErrorQuery;
141 m_ErrorMessage = "Unknown livestatus verb: " + m_Verb;
145 std::deque<Filter::Ptr> filters, stats;
146 std::deque<Aggregator::Ptr> aggregators;
148 for (unsigned int i = 1; i < lines.size(); i++) {
151 size_t col_index = line.FindFirstOf(":");
152 String header = line.SubStr(0, col_index);
155 //OutputFormat:json or OutputFormat: json
156 if (line.GetLength() > col_index + 1)
157 params = line.SubStr(col_index + 1);
161 if (header == "ResponseHeader")
162 m_ResponseHeader = params;
163 else if (header == "OutputFormat")
164 m_OutputFormat = params;
165 else if (header == "KeepAlive")
166 m_KeepAlive = (params == "on");
167 else if (header == "Columns") {
168 m_ColumnHeaders = false; // Might be explicitly re-enabled later on
169 boost::algorithm::split(m_Columns, params, boost::is_any_of(" "));
170 } else if (header == "Separators") {
171 std::vector<String> separators;
173 boost::algorithm::split(separators, params, boost::is_any_of(" "));
174 /* ugly ascii long to char conversion, but works */
175 if (separators.size() > 0)
176 m_Separators[0] = String(1, static_cast<char>(Convert::ToLong(separators[0])));
177 if (separators.size() > 1)
178 m_Separators[1] = String(1, static_cast<char>(Convert::ToLong(separators[1])));
179 if (separators.size() > 2)
180 m_Separators[2] = String(1, static_cast<char>(Convert::ToLong(separators[2])));
181 if (separators.size() > 3)
182 m_Separators[3] = String(1, static_cast<char>(Convert::ToLong(separators[3])));
183 } else if (header == "ColumnHeaders")
184 m_ColumnHeaders = (params == "on");
185 else if (header == "Filter") {
186 Filter::Ptr filter = ParseFilter(params, m_LogTimeFrom, m_LogTimeUntil);
190 m_ErrorCode = LivestatusErrorQuery;
191 m_ErrorMessage = "Invalid filter specification: " + line;
195 filters.push_back(filter);
196 } else if (header == "Stats") {
197 m_ColumnHeaders = false; // Might be explicitly re-enabled later on
199 std::vector<String> tokens;
200 boost::algorithm::split(tokens, params, boost::is_any_of(" "));
202 if (tokens.size() < 2) {
204 m_ErrorCode = LivestatusErrorQuery;
205 m_ErrorMessage = "Missing aggregator column name: " + line;
209 String aggregate_arg = tokens[0];
210 String aggregate_attr = tokens[1];
212 Aggregator::Ptr aggregator;
215 if (aggregate_arg == "sum") {
216 aggregator = new SumAggregator(aggregate_attr);
217 } else if (aggregate_arg == "min") {
218 aggregator = new MinAggregator(aggregate_attr);
219 } else if (aggregate_arg == "max") {
220 aggregator = new MaxAggregator(aggregate_attr);
221 } else if (aggregate_arg == "avg") {
222 aggregator = new AvgAggregator(aggregate_attr);
223 } else if (aggregate_arg == "std") {
224 aggregator = new StdAggregator(aggregate_attr);
225 } else if (aggregate_arg == "suminv") {
226 aggregator = new InvSumAggregator(aggregate_attr);
227 } else if (aggregate_arg == "avginv") {
228 aggregator = new InvAvgAggregator(aggregate_attr);
230 filter = ParseFilter(params, m_LogTimeFrom, m_LogTimeUntil);
234 m_ErrorCode = LivestatusErrorQuery;
235 m_ErrorMessage = "Invalid filter specification: " + line;
239 aggregator = new CountAggregator();
242 aggregator->SetFilter(filter);
243 aggregators.push_back(aggregator);
245 stats.push_back(filter);
246 } else if (header == "Or" || header == "And" || header == "StatsOr" || header == "StatsAnd") {
247 std::deque<Filter::Ptr>& deq = (header == "Or" || header == "And") ? filters : stats;
249 unsigned int num = Convert::ToLong(params);
250 CombinerFilter::Ptr filter;
252 if (header == "Or" || header == "StatsOr") {
253 filter = new OrFilter();
254 Log(LogDebug, "LivestatusQuery")
255 << "Add OR filter for " << params << " column(s). " << deq.size() << " filters available.";
257 filter = new AndFilter();
258 Log(LogDebug, "LivestatusQuery")
259 << "Add AND filter for " << params << " column(s). " << deq.size() << " filters available.";
262 if (num > deq.size()) {
265 m_ErrorMessage = "Or/StatsOr is referencing " + Convert::ToString(num) + " filters; stack only contains " + Convert::ToString(static_cast<long>(deq.size())) + " filters";
269 while (num > 0 && num--) {
270 filter->AddSubFilter(deq.back());
271 Log(LogDebug, "LivestatusQuery")
272 << "Add " << num << " filter.";
275 aggregators.pop_back();
278 deq.push_back(filter);
279 if (&deq == &stats) {
280 Aggregator::Ptr aggregator = new CountAggregator();
281 aggregator->SetFilter(filter);
282 aggregators.push_back(aggregator);
284 } else if (header == "Negate" || header == "StatsNegate") {
285 std::deque<Filter::Ptr>& deq = (header == "Negate") ? filters : stats;
290 m_ErrorMessage = "Negate/StatsNegate used, however the filter stack is empty";
294 Filter::Ptr filter = deq.back();
300 m_ErrorMessage = "Negate/StatsNegate used, however last stats doesn't have a filter";
304 deq.push_back(new NegateFilter(filter));
307 Aggregator::Ptr aggregator = aggregators.back();
308 aggregator->SetFilter(filter);
313 /* Combine all top-level filters into a single filter. */
314 AndFilter::Ptr top_filter = new AndFilter();
316 BOOST_FOREACH(const Filter::Ptr& filter, filters) {
317 top_filter->AddSubFilter(filter);
320 m_Filter = top_filter;
321 m_Aggregators.swap(aggregators);
324 int LivestatusQuery::GetExternalCommands(void)
326 boost::mutex::scoped_lock lock(l_QueryMutex);
328 return l_ExternalCommands;
331 Filter::Ptr LivestatusQuery::ParseFilter(const String& params, unsigned long& from, unsigned long& until)
335 * type = SERVICE FLAPPING ALERT
337 std::vector<String> tokens;
339 String temp_buffer = params;
341 /* extract attr and op */
342 for (int i = 0; i < 2; i++) {
343 sp_index = temp_buffer.FindFirstOf(" ");
345 /* check if this is the last argument */
346 if (sp_index == String::NPos) {
347 /* 'attr op' or 'attr op val' is valid */
349 BOOST_THROW_EXCEPTION(std::runtime_error("Livestatus filter '" + params + "' does not contain all required fields."));
354 tokens.push_back(temp_buffer.SubStr(0, sp_index));
355 temp_buffer = temp_buffer.SubStr(sp_index + 1);
358 /* add the rest as value */
359 tokens.push_back(temp_buffer);
361 if (tokens.size() == 2)
362 tokens.push_back("");
364 if (tokens.size() < 3)
365 return Filter::Ptr();
368 String attr = tokens[0];
369 String op = tokens[1];
370 String val = tokens[2];
375 } else if (op == "!~") {
378 } else if (op == "!=~") {
381 } else if (op == "!~~") {
386 Filter::Ptr filter = new AttributeFilter(attr, op, val);
389 filter = new NegateFilter(filter);
391 /* pre-filter log time duration */
392 if (attr == "time") {
393 if (op == "<" || op == "<=") {
394 until = Convert::ToLong(val);
395 } else if (op == ">" || op == ">=") {
396 from = Convert::ToLong(val);
400 Log(LogDebug, "LivestatusQuery")
401 << "Parsed filter with attr: '" << attr << "' op: '" << op << "' val: '" << val << "'.";
406 void LivestatusQuery::PrintResultSet(std::ostream& fp, const Array::Ptr& rs) const
408 if (m_OutputFormat == "csv") {
409 ObjectLock olock(rs);
411 BOOST_FOREACH(const Array::Ptr& row, rs) {
414 ObjectLock rlock(row);
415 BOOST_FOREACH(const Value& value, row) {
419 fp << m_Separators[1];
421 if (value.IsObjectType<Array>())
422 PrintCsvArray(fp, value, 0);
427 fp << m_Separators[0];
429 } else if (m_OutputFormat == "json") {
430 fp << JsonEncode(rs);
431 } else if (m_OutputFormat == "python") {
432 PrintPythonArray(fp, rs);
436 void LivestatusQuery::PrintCsvArray(std::ostream& fp, const Array::Ptr& array, int level) const
440 ObjectLock olock(array);
441 BOOST_FOREACH(const Value& value, array) {
445 fp << ((level == 0) ? m_Separators[2] : m_Separators[3]);
447 if (value.IsObjectType<Array>())
448 PrintCsvArray(fp, value, level + 1);
449 else if (value.IsBoolean())
450 fp << Convert::ToLong(value);
456 void LivestatusQuery::PrintPythonArray(std::ostream& fp, const Array::Ptr& rs) const
462 BOOST_FOREACH(const Value& value, rs) {
468 if (value.IsObjectType<Array>())
469 PrintPythonArray(fp, value);
470 else if (value.IsNumber())
473 fp << QuoteStringPython(value);
479 String LivestatusQuery::QuoteStringPython(const String& str) {
481 boost::algorithm::replace_all(result, "\"", "\\\"");
482 return "r\"" + result + "\"";
485 void LivestatusQuery::ExecuteGetHelper(const Stream::Ptr& stream)
487 Log(LogNotice, "LivestatusQuery")
488 << "Table: " << m_Table;
490 Table::Ptr table = Table::GetByName(m_Table, m_CompatLogPath, m_LogTimeFrom, m_LogTimeUntil);
493 SendResponse(stream, LivestatusErrorNotFound, "Table '" + m_Table + "' does not exist.");
498 std::vector<LivestatusRowValue> objects = table->FilterRows(m_Filter);
499 std::vector<String> columns;
501 if (m_Columns.size() > 0)
504 columns = table->GetColumnNames();
506 Array::Ptr rs = new Array();
508 if (m_Aggregators.empty()) {
509 Array::Ptr header = new Array();
511 BOOST_FOREACH(const LivestatusRowValue& object, objects) {
512 Array::Ptr row = new Array();
514 BOOST_FOREACH(const String& columnName, columns) {
515 Column column = table->GetColumn(columnName);
518 header->Add(columnName);
520 row->Add(column.ExtractValue(object.Row, object.GroupByType, object.GroupByObject));
523 if (m_ColumnHeaders) {
525 m_ColumnHeaders = false;
531 std::vector<double> stats(m_Aggregators.size(), 0);
534 /* add aggregated stats */
535 BOOST_FOREACH(const Aggregator::Ptr aggregator, m_Aggregators) {
536 BOOST_FOREACH(const LivestatusRowValue& object, objects) {
537 aggregator->Apply(table, object.Row);
540 stats[index] = aggregator->GetResult();
544 /* add column headers both for raw and aggregated data */
545 if (m_ColumnHeaders) {
546 Array::Ptr header = new Array();
548 BOOST_FOREACH(const String& columnName, m_Columns) {
549 header->Add(columnName);
552 for (size_t i = 1; i <= m_Aggregators.size(); i++) {
553 header->Add("stats_" + Convert::ToString(i));
559 Array::Ptr row = new Array();
562 * add selected columns next to stats
563 * may not be accurate for grouping!
565 if (objects.size() > 0 && m_Columns.size() > 0) {
566 BOOST_FOREACH(const String& columnName, m_Columns) {
567 Column column = table->GetColumn(columnName);
569 LivestatusRowValue object = objects[0]; //first object wins
571 row->Add(column.ExtractValue(object.Row, object.GroupByType, object.GroupByObject));
575 for (size_t i = 0; i < m_Aggregators.size(); i++)
581 std::ostringstream result;
582 PrintResultSet(result, rs);
584 SendResponse(stream, LivestatusErrorOK, result.str());
587 void LivestatusQuery::ExecuteCommandHelper(const Stream::Ptr& stream)
590 boost::mutex::scoped_lock lock(l_QueryMutex);
592 l_ExternalCommands++;
595 Log(LogNotice, "LivestatusQuery")
596 << "Executing command: " << m_Command;
597 ExternalCommandProcessor::Execute(m_Command);
598 SendResponse(stream, LivestatusErrorOK, "");
601 void LivestatusQuery::ExecuteScriptHelper(const Stream::Ptr& stream)
603 Log(LogInformation, "LivestatusQuery")
604 << "Executing expression: " << m_Command;
606 m_ResponseHeader = "fixed16";
608 LivestatusScriptFrame& lsf = l_LivestatusScriptFrames[m_Session];
609 lsf.Seen = Utility::GetTime();
612 lsf.Locals = new Dictionary();
614 String fileName = "<" + Convert::ToString(lsf.NextLine) + ">";
617 lsf.Lines[fileName] = m_Command;
619 Expression *expr = ConfigCompiler::CompileText(fileName, m_Command);
623 frame.Locals = lsf.Locals;
624 result = expr->Evaluate(frame);
625 } catch (const ScriptError& ex) {
628 DebugInfo di = ex.GetDebugInfo();
630 std::ostringstream msgbuf;
632 msgbuf << di.Path << ": " << lsf.Lines[di.Path] << "\n"
633 << String(di.Path.GetLength() + 2, ' ')
634 << String(di.FirstColumn, ' ') << String(di.LastColumn - di.FirstColumn + 1, '^') << "\n"
635 << ex.what() << "\n";
637 SendResponse(stream, LivestatusErrorQuery, msgbuf.str());
644 SendResponse(stream, LivestatusErrorOK, JsonEncode(Serialize(result, FAState | FAConfig), true));
647 void LivestatusQuery::ExecuteErrorHelper(const Stream::Ptr& stream)
649 Log(LogDebug, "LivestatusQuery")
650 << "ERROR: Code: '" << m_ErrorCode << "' Message: '" << m_ErrorMessage << "'.";
651 SendResponse(stream, m_ErrorCode, m_ErrorMessage);
654 void LivestatusQuery::SendResponse(const Stream::Ptr& stream, int code, const String& data)
656 if (m_ResponseHeader == "fixed16")
657 PrintFixed16(stream, code, data);
659 if (m_ResponseHeader == "fixed16" || code == LivestatusErrorOK) {
661 stream->Write(data.CStr(), data.GetLength());
662 } catch (const std::exception&) {
663 Log(LogCritical, "LivestatusQuery", "Cannot write to TCP socket.");
668 void LivestatusQuery::PrintFixed16(const Stream::Ptr& stream, int code, const String& data)
670 ASSERT(code >= 100 && code <= 999);
672 String sCode = Convert::ToString(code);
673 String sLength = Convert::ToString(static_cast<long>(data.GetLength()));
675 String header = sCode + String(16 - 3 - sLength.GetLength() - 1, ' ') + sLength + m_Separators[0];
678 stream->Write(header.CStr(), header.GetLength());
679 } catch (const std::exception&) {
680 Log(LogCritical, "LivestatusQuery", "Cannot write to TCP socket.");
684 bool LivestatusQuery::Execute(const Stream::Ptr& stream)
687 Log(LogNotice, "LivestatusQuery")
688 << "Executing livestatus query: " << m_Verb;
691 ExecuteGetHelper(stream);
692 else if (m_Verb == "COMMAND")
693 ExecuteCommandHelper(stream);
694 else if (m_Verb == "SCRIPT")
695 ExecuteScriptHelper(stream);
696 else if (m_Verb == "ERROR")
697 ExecuteErrorHelper(stream);
699 BOOST_THROW_EXCEPTION(std::runtime_error("Invalid livestatus query verb."));
700 } catch (const std::exception& ex) {
701 SendResponse(stream, LivestatusErrorQuery, DiagnosticInformation(ex));