]> granicus.if.org Git - icinga2/blob - lib/config/vmops.hpp
Fix copyright header indentation
[icinga2] / lib / config / vmops.hpp
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 #ifndef VMOPS_H
21 #define VMOPS_H
22
23 #include "config/i2-config.hpp"
24 #include "config/expression.hpp"
25 #include "config/configitembuilder.hpp"
26 #include "config/applyrule.hpp"
27 #include "config/objectrule.hpp"
28 #include "base/debuginfo.hpp"
29 #include "base/array.hpp"
30 #include "base/dictionary.hpp"
31 #include "base/function.hpp"
32 #include "base/scriptglobal.hpp"
33 #include "base/exception.hpp"
34 #include "base/convert.hpp"
35 #include "base/objectlock.hpp"
36 #include <boost/foreach.hpp>
37 #include <boost/smart_ptr/make_shared.hpp>
38 #include <map>
39 #include <vector>
40
41 namespace icinga
42 {
43
44 class VMOps
45 {
46 public:
47         static inline Value Variable(ScriptFrame& frame, const String& name, const DebugInfo& debugInfo = DebugInfo())
48         {
49                 if (frame.Locals && frame.Locals->Contains(name))
50                         return frame.Locals->Get(name);
51                 else if (frame.Self.IsObject() && frame.Locals != static_cast<Object::Ptr>(frame.Self) && HasField(frame.Self, name))
52                         return GetField(frame.Self, name, debugInfo);
53                 else
54                         return ScriptGlobal::Get(name);
55         }
56
57         static inline Value FunctionCall(ScriptFrame& frame, const Value& self, const Function::Ptr& func, const std::vector<Value>& arguments)
58         {
59                 boost::shared_ptr<ScriptFrame> vframe;
60
61                 if (!self.IsEmpty())
62                         vframe = boost::make_shared<ScriptFrame>(self); /* passes self to the callee using a TLS variable */
63                 else
64                         vframe = boost::make_shared<ScriptFrame>();
65
66                 return func->Invoke(arguments);
67         }
68
69         static inline Value NewFunction(ScriptFrame& frame, const std::vector<String>& args,
70             std::map<String, Expression *> *closedVars, const boost::shared_ptr<Expression>& expression)
71         {
72                 return new Function(boost::bind(&FunctionWrapper, _1, args,
73                     EvaluateClosedVars(frame, closedVars), expression));
74         }
75
76         static inline Value NewApply(ScriptFrame& frame, const String& type, const String& target, const String& name, const boost::shared_ptr<Expression>& filter,
77                 const String& fkvar, const String& fvvar, const boost::shared_ptr<Expression>& fterm, std::map<String, Expression *> *closedVars,
78                 const boost::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
79         {
80                 ApplyRule::AddRule(type, target, name, expression, filter, fkvar,
81                     fvvar, fterm, debugInfo, EvaluateClosedVars(frame, closedVars));
82
83                 return Empty;
84         }
85
86         static inline Value NewObject(ScriptFrame& frame, bool abstract, const String& type, const String& name, const boost::shared_ptr<Expression>& filter,
87                 const String& zone, std::map<String, Expression *> *closedVars, const boost::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
88         {
89                 ConfigItemBuilder::Ptr item = new ConfigItemBuilder(debugInfo);
90
91                 String checkName = name;
92
93                 if (!abstract) {
94                         Type::Ptr ptype = Type::GetByName(type);
95
96                         NameComposer *nc = dynamic_cast<NameComposer *>(ptype.get());
97
98                         if (nc)
99                                 checkName = nc->MakeName(name, Dictionary::Ptr());
100                 }
101
102                 if (!checkName.IsEmpty()) {
103                         ConfigItem::Ptr oldItem = ConfigItem::GetObject(type, checkName);
104
105                         if (oldItem) {
106                                 std::ostringstream msgbuf;
107                                 msgbuf << "Object '" << name << "' of type '" << type << "' re-defined: " << debugInfo << "; previous definition: " << oldItem->GetDebugInfo();
108                                 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debugInfo));
109                         }
110                 }
111
112                 item->SetType(type);
113
114                 if (name.FindFirstOf("!") != String::NPos) {
115                         std::ostringstream msgbuf;
116                         msgbuf << "Name for object '" << name << "' of type '" << type << "' is invalid: Object names may not contain '!'";
117                         BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debugInfo));
118                 }
119
120                 item->SetName(name);
121
122                 item->AddExpression(new OwnedExpression(expression));
123                 item->SetAbstract(abstract);
124                 item->SetScope(EvaluateClosedVars(frame, closedVars));
125                 item->SetZone(zone);
126                 item->SetFilter(filter);
127                 item->Compile()->Register();
128
129                 return Empty;
130         }
131
132         static inline Value For(ScriptFrame& frame, const String& fkvar, const String& fvvar, const Value& value, Expression *expression, const DebugInfo& debugInfo = DebugInfo())
133         {
134                 if (value.IsObjectType<Array>()) {
135                         if (!fvvar.IsEmpty())
136                                 BOOST_THROW_EXCEPTION(ScriptError("Cannot use dictionary iterator for array.", debugInfo));
137
138                         Array::Ptr arr = value;
139
140                         for (Array::SizeType i = 0; i < arr->GetLength(); i++) {
141                                 frame.Locals->Set(fkvar, arr->Get(i));
142                                 ExpressionResult res = expression->Evaluate(frame);
143                                 CHECK_RESULT_LOOP(res);
144                         }
145                 } else if (value.IsObjectType<Dictionary>()) {
146                         if (fvvar.IsEmpty())
147                                 BOOST_THROW_EXCEPTION(ScriptError("Cannot use array iterator for dictionary.", debugInfo));
148
149                         Dictionary::Ptr dict = value;
150                         std::vector<String> keys;
151
152                         {
153                                 ObjectLock olock(dict);
154                                 BOOST_FOREACH(const Dictionary::Pair& kv, dict) {
155                                         keys.push_back(kv.first);
156                                 }
157                         }
158
159                         BOOST_FOREACH(const String& key, keys) {
160                                 frame.Locals->Set(fkvar, key);
161                                 frame.Locals->Set(fvvar, dict->Get(key));
162                                 ExpressionResult res = expression->Evaluate(frame);
163                                 CHECK_RESULT_LOOP(res);
164                         }
165                 } else
166                         BOOST_THROW_EXCEPTION(ScriptError("Invalid type in for expression: " + value.GetTypeName(), debugInfo));
167
168                 return Empty;
169         }
170
171         static inline bool HasField(const Object::Ptr& context, const String& field)
172         {
173                 Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(context);
174
175                 if (dict)
176                         return dict->Contains(field);
177                 else {
178                         Type::Ptr type = context->GetReflectionType();
179
180                         if (!type)
181                                 return false;
182
183                         return type->GetFieldId(field) != -1;
184                 }
185         }
186
187         static inline Value GetPrototypeField(const Value& context, const String& field, bool not_found_error = true, const DebugInfo& debugInfo = DebugInfo())
188         {
189                 Type::Ptr ctype = context.GetReflectionType();
190                 Type::Ptr type = ctype;
191
192                 do {
193                         Object::Ptr object = type->GetPrototype();
194
195                         if (object && HasField(object, field))
196                                 return GetField(object, field, debugInfo);
197
198                         type = type->GetBaseType();
199                 } while (type);
200
201                 if (not_found_error)
202                         BOOST_THROW_EXCEPTION(ScriptError("Invalid field access (for value of type '" + ctype->GetName() + "'): '" + field + "'", debugInfo));
203                 else
204                         return Empty;
205         }
206
207         static inline Value GetField(const Value& context, const String& field, const DebugInfo& debugInfo = DebugInfo())
208         {
209                 if (context.IsEmpty())
210                         return Empty;
211
212                 if (!context.IsObject())
213                         return GetPrototypeField(context, field, true, debugInfo);
214
215                 Object::Ptr object = context;
216
217                 Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(object);
218
219                 if (dict) {
220                         if (dict->Contains(field))
221                                 return dict->Get(field);
222                         else
223                                 return GetPrototypeField(context, field, false, debugInfo);
224                 }
225
226                 Array::Ptr arr = dynamic_pointer_cast<Array>(object);
227
228                 if (arr) {
229                         int index;
230
231                         try {
232                                 index = Convert::ToLong(field);
233                         } catch (...) {
234                                 return GetPrototypeField(context, field, true, debugInfo);
235                         }
236
237                         if (index < 0 || index >= arr->GetLength())
238                                 BOOST_THROW_EXCEPTION(ScriptError("Array index '" + Convert::ToString(index) + "' is out of bounds.", debugInfo));
239
240                         return arr->Get(index);
241                 }
242
243                 Type::Ptr type = object->GetReflectionType();
244
245                 if (!type)
246                         return Empty;
247
248                 int fid = type->GetFieldId(field);
249
250                 if (fid == -1)
251                         return GetPrototypeField(context, field, true, debugInfo);
252
253                 return object->GetField(fid);
254         }
255
256         static inline void SetField(const Object::Ptr& context, const String& field, const Value& value, const DebugInfo& debugInfo = DebugInfo())
257         {
258                 Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(context);
259
260                 if (dict) {
261                         dict->Set(field, value);
262                         return;
263                 }
264
265                 Array::Ptr arr = dynamic_pointer_cast<Array>(context);
266
267                 if (arr) {
268                         int index = Convert::ToLong(field);
269                         if (index >= arr->GetLength())
270                                 arr->Resize(index + 1);
271                         arr->Set(index, value);
272                         return;
273                 }
274
275                 Type::Ptr type = context->GetReflectionType();
276
277                 if (!type)
278                         BOOST_THROW_EXCEPTION(ScriptError("Cannot set field on object.", debugInfo));
279
280                 int fid = type->GetFieldId(field);
281
282                 if (fid == -1)
283                         BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' does not exist.", debugInfo));
284
285                 try {
286                         context->SetField(fid, value);
287                 } catch (const boost::bad_lexical_cast&) {
288                         BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' cannot be set to value of type '" + value.GetTypeName() + "'", debugInfo));
289                 } catch (const std::bad_cast&) {
290                         BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' cannot be set to value of type '" + value.GetTypeName() + "'", debugInfo));
291                 }
292         }
293
294 private:
295         static inline Value FunctionWrapper(const std::vector<Value>& arguments,
296             const std::vector<String>& funcargs, const Dictionary::Ptr& closedVars, const boost::shared_ptr<Expression>& expr)
297         {
298                 if (arguments.size() < funcargs.size())
299                         BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments for function"));
300
301                 ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
302                 ScriptFrame frame(vframe->Self);
303
304                 if (closedVars)
305                         closedVars->CopyTo(frame.Locals);
306
307                 for (std::vector<Value>::size_type i = 0; i < std::min(arguments.size(), funcargs.size()); i++)
308                         frame.Locals->Set(funcargs[i], arguments[i]);
309
310                 return expr->Evaluate(frame);
311         }
312
313         static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, std::map<String, Expression *> *closedVars)
314         {
315                 Dictionary::Ptr locals;
316
317                 if (closedVars) {
318                         locals = new Dictionary();
319
320                         typedef std::pair<String, Expression *> ClosedVar;
321                         BOOST_FOREACH(const ClosedVar& cvar, *closedVars) {
322                                 locals->Set(cvar.first, cvar.second->Evaluate(frame));
323                         }
324                 }
325
326                 return locals;
327         }
328 };
329
330 }
331
332 #endif /* VMOPS_H */