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 "icinga/pluginutility.hpp"
21 #include "icinga/macroprocessor.hpp"
22 #include "icinga/perfdatavalue.hpp"
23 #include "base/logger.hpp"
24 #include "base/utility.hpp"
25 #include "base/convert.hpp"
26 #include "base/process.hpp"
27 #include "base/objectlock.hpp"
28 #include <boost/algorithm/string/classification.hpp>
29 #include <boost/algorithm/string/split.hpp>
30 #include <boost/algorithm/string/trim.hpp>
31 #include <boost/foreach.hpp>
33 using namespace icinga;
35 struct CommandArgument
45 : Order(0), SkipKey(false), RepeatKey(true), SkipValue(false)
48 bool operator<(const CommandArgument& rhs) const
50 return Order < rhs.Order;
54 void PluginUtility::AddArgumentHelper(const Array::Ptr& args, const String& key, const String& value, bool add_key, bool add_value)
63 Value PluginUtility::EscapeMacroShellArg(const Value& value)
67 if (value.IsObjectType<Array>()) {
68 Array::Ptr arr = value;
70 ObjectLock olock(arr);
71 BOOST_FOREACH(const Value& arg, arr) {
72 if (result.GetLength() > 0)
75 result += Utility::EscapeShellArg(arg);
78 result = Utility::EscapeShellArg(value);
83 void PluginUtility::ExecuteCommand(const Command::Ptr& commandObj, const Checkable::Ptr& checkable,
84 const CheckResult::Ptr& cr, const MacroProcessor::ResolverList& macroResolvers,
85 const Dictionary::Ptr& resolvedMacros, bool useResolvedMacros,
86 const boost::function<void(const Value& commandLine, const ProcessResult&)>& callback)
88 Value raw_command = commandObj->GetCommandLine();
89 Dictionary::Ptr raw_arguments = commandObj->GetArguments();
92 if (!raw_arguments || raw_command.IsObjectType<Array>())
93 command = MacroProcessor::ResolveMacros(raw_command, macroResolvers, cr, NULL,
94 PluginUtility::EscapeMacroShellArg, resolvedMacros, useResolvedMacros);
96 Array::Ptr arr = new Array();
97 arr->Add(raw_command);
102 std::vector<CommandArgument> args;
104 ObjectLock olock(raw_arguments);
105 BOOST_FOREACH(const Dictionary::Pair& kv, raw_arguments) {
106 const Value& arginfo = kv.second;
111 bool required = false;
114 if (arginfo.IsObjectType<Dictionary>()) {
115 Dictionary::Ptr argdict = arginfo;
116 if (argdict->Contains("key"))
117 arg.Key = argdict->Get("key");
118 argval = argdict->Get("value");
119 if (argdict->Contains("required"))
120 required = argdict->Get("required");
121 arg.SkipKey = argdict->Get("skip_key");
122 if (argdict->Contains("repeat_key"))
123 arg.RepeatKey = argdict->Get("repeat_key");
124 arg.Order = argdict->Get("order");
126 String set_if = argdict->Get("set_if");
128 if (!set_if.IsEmpty()) {
130 String set_if_resolved = MacroProcessor::ResolveMacros(set_if, macroResolvers,
131 cr, &missingMacro, MacroProcessor::EscapeCallback(), resolvedMacros,
134 if (!missingMacro.IsEmpty())
138 if (!Convert::ToLong(set_if_resolved))
140 } catch (const std::exception& ex) {
141 /* tried to convert a string */
142 Log(LogWarning, "PluginUtility")
143 << "Error evaluating set_if value '" << set_if_resolved << "': " << ex.what();
151 if (argval.IsEmpty())
152 arg.SkipValue = true;
155 arg.AValue = MacroProcessor::ResolveMacros(argval, macroResolvers,
156 cr, &missingMacro, MacroProcessor::EscapeCallback(), resolvedMacros,
159 if (!missingMacro.IsEmpty()) {
161 String message = "Non-optional macro '" + missingMacro + "' used in argument '" +
162 arg.Key + "' is missing while executing command '" + commandObj->GetName() +
163 "' for object '" + checkable->GetName() + "'";
164 Log(LogWarning, "PluginUtility", message);
169 pr.ExecutionStart = Utility::GetTime();
170 pr.ExecutionStart = pr.ExecutionStart;
171 pr.ExitStatus = 3; /* Unknown */
185 std::sort(args.begin(), args.end());
187 Array::Ptr command_arr = command;
188 BOOST_FOREACH(const CommandArgument& arg, args) {
191 if (arg.AValue.IsString())
192 AddArgumentHelper(command_arr, arg.Key, arg.AValue, !arg.SkipKey, !arg.SkipValue);
193 else if (arg.AValue.IsObjectType<Array>())
194 arr = static_cast<Array::Ptr>(arg.AValue);
201 ObjectLock olock(arr);
202 BOOST_FOREACH(const Value& value, arr) {
207 add_key = !arg.SkipKey;
209 add_key = !arg.SkipKey && arg.RepeatKey;
212 AddArgumentHelper(command_arr, arg.Key, value, add_key, !arg.SkipValue);
218 Dictionary::Ptr envMacros = new Dictionary();
220 Dictionary::Ptr env = commandObj->GetEnv();
223 ObjectLock olock(env);
224 BOOST_FOREACH(const Dictionary::Pair& kv, env) {
225 String name = kv.second;
227 Value value = MacroProcessor::ResolveMacros(name, macroResolvers, cr,
228 NULL, MacroProcessor::EscapeCallback(), resolvedMacros,
231 if (value.IsObjectType<Array>())
232 value = Utility::Join(value, ';');
234 envMacros->Set(kv.first, value);
238 if (resolvedMacros && !useResolvedMacros)
241 Process::Ptr process = new Process(Process::PrepareCommand(command), envMacros);
242 process->SetTimeout(commandObj->GetTimeout());
243 process->Run(boost::bind(callback, command, _1));
246 ServiceState PluginUtility::ExitStatusToState(int exitStatus)
248 switch (exitStatus) {
252 return ServiceWarning;
254 return ServiceCritical;
256 return ServiceUnknown;
260 std::pair<String, String> PluginUtility::ParseCheckOutput(const String& output)
265 std::vector<String> lines;
266 boost::algorithm::split(lines, output, boost::is_any_of("\r\n"));
268 BOOST_FOREACH (const String& line, lines) {
269 size_t delim = line.FindFirstOf("|");
274 if (delim != String::NPos) {
275 text += line.SubStr(0, delim);
277 if (!perfdata.IsEmpty())
280 perfdata += line.SubStr(delim + 1, line.GetLength());
286 boost::algorithm::trim(perfdata);
288 return std::make_pair(text, perfdata);
291 Array::Ptr PluginUtility::SplitPerfdata(const String& perfdata)
293 Array::Ptr result = new Array();
299 size_t eqp = perfdata.FindFirstOf('=', begin);
301 if (eqp == String::NPos)
304 String label = perfdata.SubStr(begin, eqp - begin);
306 if (label.GetLength() > 2 && label[0] == '\'' && label[label.GetLength() - 1] == '\'')
307 label = label.SubStr(1, label.GetLength() - 2);
309 size_t multi_index = label.RFind("::");
311 if (multi_index != String::NPos)
314 size_t spq = perfdata.FindFirstOf(' ', eqp);
316 if (spq == String::NPos)
317 spq = perfdata.GetLength();
319 String value = perfdata.SubStr(eqp + 1, spq - eqp - 1);
321 if (!multi_prefix.IsEmpty())
322 label = multi_prefix + "::" + label;
325 if (label.FindFirstOf(" ") != String::NPos)
326 pdv = "'" + label + "'=" + value;
328 pdv = label + "=" + value;
332 if (multi_index != String::NPos)
333 multi_prefix = label.SubStr(0, multi_index);
341 String PluginUtility::FormatPerfdata(const Array::Ptr& perfdata)
346 std::ostringstream result;
348 ObjectLock olock(perfdata);
351 BOOST_FOREACH(const Value& pdv, perfdata) {
357 if (pdv.IsObjectType<PerfdataValue>())
358 result << static_cast<PerfdataValue::Ptr>(pdv)->Format();