]> granicus.if.org Git - icinga2/blob - lib/icinga/macroprocessor.cpp
Implement support for using functions in custom attributes
[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 {
63                 BOOST_THROW_EXCEPTION(std::invalid_argument("Command is not a string or array."));
64         }
65
66         return result;
67 }
68
69 bool MacroProcessor::ResolveMacro(const String& macro, const ResolverList& resolvers,
70     const CheckResult::Ptr& cr, Value *result, bool *recursive_macro)
71 {
72         CONTEXT("Resolving macro '" + macro + "'");
73
74         *recursive_macro = false;
75
76         std::vector<String> tokens;
77         boost::algorithm::split(tokens, macro, boost::is_any_of("."));
78
79         String objName;
80         if (tokens.size() > 1) {
81                 objName = tokens[0];
82                 tokens.erase(tokens.begin());
83         }
84
85         BOOST_FOREACH(const ResolverSpec& resolver, resolvers) {
86                 if (!objName.IsEmpty() && objName != resolver.first)
87                         continue;
88
89                 if (objName.IsEmpty()) {
90                         CustomVarObject::Ptr dobj = dynamic_pointer_cast<CustomVarObject>(resolver.second);
91
92                         if (dobj) {
93                                 Dictionary::Ptr vars = dobj->GetVars();
94
95                                 if (vars && vars->Contains(macro)) {
96                                         *result = vars->Get(macro);
97                                         *recursive_macro = true;
98                                         return true;
99                                 }
100                         }
101                 }
102
103                 MacroResolver *mresolver = dynamic_cast<MacroResolver *>(resolver.second.get());
104
105                 if (mresolver && mresolver->ResolveMacro(boost::algorithm::join(tokens, "."), cr, result))
106                         return true;
107
108                 Value ref = resolver.second;
109                 bool valid = true;
110
111                 BOOST_FOREACH(const String& token, tokens) {
112                         if (ref.IsObjectType<Dictionary>()) {
113                                 Dictionary::Ptr dict = ref;
114                                 if (dict->Contains(token)) {
115                                         ref = dict->Get(token);
116                                         continue;
117                                 } else {
118                                         valid = false;
119                                         break;
120                                 }
121                         } else if (ref.IsObject()) {
122                                 Object::Ptr object = ref;
123
124                                 Type::Ptr type = object->GetReflectionType();
125
126                                 if (!type) {
127                                         valid = false;
128                                         break;
129                                 }
130
131                                 int field = type->GetFieldId(token);
132
133                                 if (field == -1) {
134                                         valid = false;
135                                         break;
136                                 }
137
138                                 ref = object->GetField(field);
139                         }
140                 }
141
142                 if (valid) {
143                         if (tokens[0] == "vars" ||
144                             tokens[0] == "action_url" ||
145                             tokens[0] == "notes_url" ||
146                             tokens[0] == "notes")
147                                 *recursive_macro = true;
148
149                         *result = ref;
150                         return true;
151                 }
152         }
153
154         return false;
155 }
156
157 Value MacroProcessor::InternalResolveMacros(const String& str, const ResolverList& resolvers,
158     const CheckResult::Ptr& cr, String *missingMacro,
159     const MacroProcessor::EscapeCallback& escapeFn, const Dictionary::Ptr& resolvedMacros,
160     bool useResolvedMacros, int recursionLevel)
161 {
162         CONTEXT("Resolving macros for string '" + str + "'");
163
164         if (recursionLevel > 15)
165                 BOOST_THROW_EXCEPTION(std::runtime_error("Infinite recursion detected while resolving macros"));
166
167         size_t offset, pos_first, pos_second;
168         offset = 0;
169
170         Dictionary::Ptr resolvers_this;
171
172         String result = str;
173         while ((pos_first = result.FindFirstOf("$", offset)) != String::NPos) {
174                 pos_second = result.FindFirstOf("$", pos_first + 1);
175
176                 if (pos_second == String::NPos)
177                         BOOST_THROW_EXCEPTION(std::runtime_error("Closing $ not found in macro format string."));
178
179                 String name = result.SubStr(pos_first + 1, pos_second - pos_first - 1);
180
181                 Value resolved_macro;
182                 bool recursive_macro;
183                 bool found;
184
185                 if (useResolvedMacros) {
186                         recursive_macro = false;
187                         found = resolvedMacros->Contains(name);
188
189                         if (found)
190                                 resolved_macro = resolvedMacros->Get(name);
191                 } else
192                         found = ResolveMacro(name, resolvers, cr, &resolved_macro, &recursive_macro);
193
194                 /* $$ is an escape sequence for $. */
195                 if (name.IsEmpty()) {
196                         resolved_macro = "$";
197                         found = true;
198                 }
199
200                 if (resolved_macro.IsObjectType<Function>()) {
201                         Function::Ptr func = resolved_macro;
202
203                         if (!resolvers_this) {
204                                 resolvers_this = new Dictionary();
205
206                                 BOOST_FOREACH(const ResolverSpec& resolver, resolvers) {
207                                         resolvers_this->Set(resolver.first, resolver.second);
208                                 }
209                         }
210
211                         ScriptFrame frame(resolvers_this);
212                         std::vector<Value> args;
213                         resolved_macro = func->Invoke(args);
214                 }
215
216                 if (!found) {
217                         if (!missingMacro)
218                                 Log(LogWarning, "MacroProcessor")
219                                     << "Macro '" << name << "' is not defined.";
220                         else
221                                 *missingMacro = name;
222                 }
223
224                 /* recursively resolve macros in the macro if it was a user macro */
225                 if (recursive_macro) {
226                         if (resolved_macro.IsObjectType<Array>()) {
227                                 Array::Ptr arr = resolved_macro;
228                                 Array::Ptr result = new Array();
229
230                                 ObjectLock olock(arr);
231                                 BOOST_FOREACH(Value& value, arr) {
232                                         result->Add(InternalResolveMacros(value,
233                                                 resolvers, cr, missingMacro, EscapeCallback(), Dictionary::Ptr(),
234                                                 false, recursionLevel + 1));
235                                 }
236
237                                 resolved_macro = result;
238                         } else
239                                 resolved_macro = InternalResolveMacros(resolved_macro,
240                                         resolvers, cr, missingMacro, EscapeCallback(), Dictionary::Ptr(),
241                                         false, recursionLevel + 1);
242                 }
243
244                 if (!useResolvedMacros && found && resolvedMacros)
245                         resolvedMacros->Set(name, resolved_macro);
246
247                 if (escapeFn)
248                         resolved_macro = escapeFn(resolved_macro);
249
250                 /* we're done if the value is an array */
251                 if (resolved_macro.IsObjectType<Array>()) {
252                         /* don't allow mixing strings and arrays in macro strings */
253                         if (pos_first != 0 || pos_second != str.GetLength() - 1)
254                                 BOOST_THROW_EXCEPTION(std::invalid_argument("Mixing both strings and non-strings in macros is not allowed."));
255
256                         return resolved_macro;
257                 }
258
259                 String resolved_macro_str = resolved_macro;
260
261                 result.Replace(pos_first, pos_second - pos_first + 1, resolved_macro_str);
262                 offset = pos_first + resolved_macro_str.GetLength();
263         }
264
265         return result;
266 }