]> granicus.if.org Git - icinga2/blob - lib/icinga/macroprocessor.cpp
Implement support for functions in set_if
[icinga2] / lib / icinga / macroprocessor.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org)    *
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/macroprocessor.hpp"
21 #include "icinga/macroresolver.hpp"
22 #include "icinga/customvarobject.hpp"
23 #include "base/array.hpp"
24 #include "base/objectlock.hpp"
25 #include "base/logger.hpp"
26 #include "base/context.hpp"
27 #include "base/dynamicobject.hpp"
28 #include "base/scriptframe.hpp"
29 #include <boost/foreach.hpp>
30 #include <boost/algorithm/string/split.hpp>
31 #include <boost/algorithm/string/join.hpp>
32 #include <boost/algorithm/string/classification.hpp>
33
34 using namespace icinga;
35
36 Value MacroProcessor::ResolveMacros(const Value& str, const ResolverList& resolvers,
37     const CheckResult::Ptr& cr, String *missingMacro,
38     const MacroProcessor::EscapeCallback& escapeFn, const Dictionary::Ptr& resolvedMacros,
39     bool useResolvedMacros)
40 {
41         Value result;
42
43         if (str.IsEmpty())
44                 return Empty;
45
46         if (str.IsScalar()) {
47                 result = InternalResolveMacros(str, resolvers, cr, missingMacro, escapeFn,
48                     resolvedMacros, useResolvedMacros);
49         } else if (str.IsObjectType<Array>()) {
50                 Array::Ptr resultArr = new Array();
51                 Array::Ptr arr = str;
52
53                 ObjectLock olock(arr);
54
55                 BOOST_FOREACH(const Value& arg, arr) {
56                         /* Note: don't escape macros here. */
57                         resultArr->Add(InternalResolveMacros(arg, resolvers, cr, missingMacro,
58                             EscapeCallback(), resolvedMacros, useResolvedMacros));
59                 }
60
61                 result = resultArr;
62         } else if (str.IsObjectType<Function>()) {
63                 result = EvaluateFunction(str, resolvers, cr, missingMacro, escapeFn, resolvedMacros, useResolvedMacros, 0);
64         } else {
65                 BOOST_THROW_EXCEPTION(std::invalid_argument("Macro is not a string or array."));
66         }
67
68         return result;
69 }
70
71 bool MacroProcessor::ResolveMacro(const String& macro, const ResolverList& resolvers,
72     const CheckResult::Ptr& cr, Value *result, bool *recursive_macro)
73 {
74         CONTEXT("Resolving macro '" + macro + "'");
75
76         *recursive_macro = false;
77
78         std::vector<String> tokens;
79         boost::algorithm::split(tokens, macro, boost::is_any_of("."));
80
81         String objName;
82         if (tokens.size() > 1) {
83                 objName = tokens[0];
84                 tokens.erase(tokens.begin());
85         }
86
87         BOOST_FOREACH(const ResolverSpec& resolver, resolvers) {
88                 if (!objName.IsEmpty() && objName != resolver.first)
89                         continue;
90
91                 if (objName.IsEmpty()) {
92                         CustomVarObject::Ptr dobj = dynamic_pointer_cast<CustomVarObject>(resolver.second);
93
94                         if (dobj) {
95                                 Dictionary::Ptr vars = dobj->GetVars();
96
97                                 if (vars && vars->Contains(macro)) {
98                                         *result = vars->Get(macro);
99                                         *recursive_macro = true;
100                                         return true;
101                                 }
102                         }
103                 }
104
105                 MacroResolver *mresolver = dynamic_cast<MacroResolver *>(resolver.second.get());
106
107                 if (mresolver && mresolver->ResolveMacro(boost::algorithm::join(tokens, "."), cr, result))
108                         return true;
109
110                 Value ref = resolver.second;
111                 bool valid = true;
112
113                 BOOST_FOREACH(const String& token, tokens) {
114                         if (ref.IsObjectType<Dictionary>()) {
115                                 Dictionary::Ptr dict = ref;
116                                 if (dict->Contains(token)) {
117                                         ref = dict->Get(token);
118                                         continue;
119                                 } else {
120                                         valid = false;
121                                         break;
122                                 }
123                         } else if (ref.IsObject()) {
124                                 Object::Ptr object = ref;
125
126                                 Type::Ptr type = object->GetReflectionType();
127
128                                 if (!type) {
129                                         valid = false;
130                                         break;
131                                 }
132
133                                 int field = type->GetFieldId(token);
134
135                                 if (field == -1) {
136                                         valid = false;
137                                         break;
138                                 }
139
140                                 ref = object->GetField(field);
141                         }
142                 }
143
144                 if (valid) {
145                         if (tokens[0] == "vars" ||
146                             tokens[0] == "action_url" ||
147                             tokens[0] == "notes_url" ||
148                             tokens[0] == "notes")
149                                 *recursive_macro = true;
150
151                         *result = ref;
152                         return true;
153                 }
154         }
155
156         return false;
157 }
158
159 Value MacroProcessor::InternalResolveMacrosShim(const std::vector<Value>& args, const ResolverList& resolvers,
160     const CheckResult::Ptr& cr, String *missingMacro,
161     const MacroProcessor::EscapeCallback& escapeFn, const Dictionary::Ptr& resolvedMacros,
162     bool useResolvedMacros, int recursionLevel)
163 {
164         if (args.size() < 1)
165                 BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments for function"));
166
167         return MacroProcessor::InternalResolveMacros(args[0], resolvers, cr, missingMacro, escapeFn,
168             resolvedMacros, useResolvedMacros, recursionLevel);
169 }
170
171 Value MacroProcessor::EvaluateFunction(const Function::Ptr& func, const ResolverList& resolvers,
172     const CheckResult::Ptr& cr, String *missingMacro,
173     const MacroProcessor::EscapeCallback& escapeFn, const Dictionary::Ptr& resolvedMacros,
174     bool useResolvedMacros, int recursionLevel)
175 {
176         Dictionary::Ptr resolvers_this = new Dictionary();
177
178         BOOST_FOREACH(const ResolverSpec& resolver, resolvers) {
179                 resolvers_this->Set(resolver.first, resolver.second);
180         }
181
182         resolvers_this->Set("macro", new Function(boost::bind(&MacroProcessor::InternalResolveMacrosShim,
183             _1, boost::cref(resolvers), cr, missingMacro, boost::cref(escapeFn), resolvedMacros, useResolvedMacros,
184             recursionLevel)));
185
186         ScriptFrame frame(resolvers_this);
187         std::vector<Value> args;
188         return func->Invoke(args);
189 }
190
191 Value MacroProcessor::InternalResolveMacros(const String& str, const ResolverList& resolvers,
192     const CheckResult::Ptr& cr, String *missingMacro,
193     const MacroProcessor::EscapeCallback& escapeFn, const Dictionary::Ptr& resolvedMacros,
194     bool useResolvedMacros, int recursionLevel)
195 {
196         CONTEXT("Resolving macros for string '" + str + "'");
197
198         if (recursionLevel > 15)
199                 BOOST_THROW_EXCEPTION(std::runtime_error("Infinite recursion detected while resolving macros"));
200
201         size_t offset, pos_first, pos_second;
202         offset = 0;
203
204         Dictionary::Ptr resolvers_this;
205
206         String result = str;
207         while ((pos_first = result.FindFirstOf("$", offset)) != String::NPos) {
208                 pos_second = result.FindFirstOf("$", pos_first + 1);
209
210                 if (pos_second == String::NPos)
211                         BOOST_THROW_EXCEPTION(std::runtime_error("Closing $ not found in macro format string."));
212
213                 String name = result.SubStr(pos_first + 1, pos_second - pos_first - 1);
214
215                 Value resolved_macro;
216                 bool recursive_macro;
217                 bool found;
218
219                 if (useResolvedMacros) {
220                         recursive_macro = false;
221                         found = resolvedMacros->Contains(name);
222
223                         if (found)
224                                 resolved_macro = resolvedMacros->Get(name);
225                 } else
226                         found = ResolveMacro(name, resolvers, cr, &resolved_macro, &recursive_macro);
227
228                 /* $$ is an escape sequence for $. */
229                 if (name.IsEmpty()) {
230                         resolved_macro = "$";
231                         found = true;
232                 }
233
234                 if (resolved_macro.IsObjectType<Function>()) {
235                         resolved_macro = EvaluateFunction(resolved_macro, resolvers, cr, missingMacro, escapeFn,
236                             resolvedMacros, useResolvedMacros, recursionLevel);
237                 }
238
239                 if (!found) {
240                         if (!missingMacro)
241                                 Log(LogWarning, "MacroProcessor")
242                                     << "Macro '" << name << "' is not defined.";
243                         else
244                                 *missingMacro = name;
245                 }
246
247                 /* recursively resolve macros in the macro if it was a user macro */
248                 if (recursive_macro) {
249                         if (resolved_macro.IsObjectType<Array>()) {
250                                 Array::Ptr arr = resolved_macro;
251                                 Array::Ptr resolved_arr = new Array();
252
253                                 ObjectLock olock(arr);
254                                 BOOST_FOREACH(const Value& value, arr) {
255                                         if (value.IsScalar()) {
256                                                 resolved_arr->Add(InternalResolveMacros(value,
257                                                         resolvers, cr, missingMacro, EscapeCallback(), Dictionary::Ptr(),
258                                                         false, recursionLevel + 1));
259                                         } else
260                                                 resolved_arr->Add(value);
261                                 }
262
263                                 resolved_macro = resolved_arr;
264                         } else
265                                 resolved_macro = InternalResolveMacros(resolved_macro,
266                                         resolvers, cr, missingMacro, EscapeCallback(), Dictionary::Ptr(),
267                                         false, recursionLevel + 1);
268                 }
269
270                 if (!useResolvedMacros && found && resolvedMacros)
271                         resolvedMacros->Set(name, resolved_macro);
272
273                 if (escapeFn)
274                         resolved_macro = escapeFn(resolved_macro);
275
276                 /* we're done if the value is an array */
277                 if (resolved_macro.IsObjectType<Array>()) {
278                         /* don't allow mixing strings and arrays in macro strings */
279                         if (pos_first != 0 || pos_second != str.GetLength() - 1)
280                                 BOOST_THROW_EXCEPTION(std::invalid_argument("Mixing both strings and non-strings in macros is not allowed."));
281
282                         return resolved_macro;
283                 }
284
285                 String resolved_macro_str = resolved_macro;
286
287                 result.Replace(pos_first, pos_second - pos_first + 1, resolved_macro_str);
288                 offset = pos_first + resolved_macro_str.GetLength();
289         }
290
291         return result;
292 }