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 ******************************************************************************/
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>
47 static inline Value Variable(ScriptFrame& frame, const String& name, const DebugInfo& debugInfo = DebugInfo())
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);
54 return ScriptGlobal::Get(name);
57 static inline Value FunctionCall(ScriptFrame& frame, const Value& self, const Function::Ptr& func, const std::vector<Value>& arguments)
59 boost::shared_ptr<ScriptFrame> vframe;
62 vframe = boost::make_shared<ScriptFrame>(self); /* passes self to the callee using a TLS variable */
64 vframe = boost::make_shared<ScriptFrame>();
66 return func->Invoke(arguments);
69 static inline Value NewFunction(ScriptFrame& frame, const std::vector<String>& args,
70 std::map<String, Expression *> *closedVars, const boost::shared_ptr<Expression>& expression)
72 return new Function(boost::bind(&FunctionWrapper, _1, args,
73 EvaluateClosedVars(frame, closedVars), expression));
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())
80 ApplyRule::AddRule(type, target, name, expression, filter, fkvar,
81 fvvar, fterm, debugInfo, EvaluateClosedVars(frame, closedVars));
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())
89 ConfigItemBuilder::Ptr item = new ConfigItemBuilder(debugInfo);
91 String checkName = name;
94 Type::Ptr ptype = Type::GetByName(type);
96 NameComposer *nc = dynamic_cast<NameComposer *>(ptype.get());
99 checkName = nc->MakeName(name, Dictionary::Ptr());
102 if (!checkName.IsEmpty()) {
103 ConfigItem::Ptr oldItem = ConfigItem::GetObject(type, checkName);
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));
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));
122 item->AddExpression(new OwnedExpression(expression));
123 item->SetAbstract(abstract);
124 item->SetScope(EvaluateClosedVars(frame, closedVars));
126 item->SetFilter(filter);
127 item->Compile()->Register();
132 static inline Value For(ScriptFrame& frame, const String& fkvar, const String& fvvar, const Value& value, Expression *expression, const DebugInfo& debugInfo = DebugInfo())
134 if (value.IsObjectType<Array>()) {
135 if (!fvvar.IsEmpty())
136 BOOST_THROW_EXCEPTION(ScriptError("Cannot use dictionary iterator for array.", debugInfo));
138 Array::Ptr arr = value;
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);
145 } else if (value.IsObjectType<Dictionary>()) {
147 BOOST_THROW_EXCEPTION(ScriptError("Cannot use array iterator for dictionary.", debugInfo));
149 Dictionary::Ptr dict = value;
150 std::vector<String> keys;
153 ObjectLock olock(dict);
154 BOOST_FOREACH(const Dictionary::Pair& kv, dict) {
155 keys.push_back(kv.first);
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);
166 BOOST_THROW_EXCEPTION(ScriptError("Invalid type in for expression: " + value.GetTypeName(), debugInfo));
171 static inline bool HasField(const Object::Ptr& context, const String& field)
173 Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(context);
176 return dict->Contains(field);
178 Type::Ptr type = context->GetReflectionType();
183 return type->GetFieldId(field) != -1;
187 static inline Value GetPrototypeField(const Value& context, const String& field, bool not_found_error = true, const DebugInfo& debugInfo = DebugInfo())
189 Type::Ptr ctype = context.GetReflectionType();
190 Type::Ptr type = ctype;
193 Object::Ptr object = type->GetPrototype();
195 if (object && HasField(object, field))
196 return GetField(object, field, debugInfo);
198 type = type->GetBaseType();
202 BOOST_THROW_EXCEPTION(ScriptError("Invalid field access (for value of type '" + ctype->GetName() + "'): '" + field + "'", debugInfo));
207 static inline Value GetField(const Value& context, const String& field, const DebugInfo& debugInfo = DebugInfo())
209 if (context.IsEmpty())
212 if (!context.IsObject())
213 return GetPrototypeField(context, field, true, debugInfo);
215 Object::Ptr object = context;
217 Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(object);
220 if (dict->Contains(field))
221 return dict->Get(field);
223 return GetPrototypeField(context, field, false, debugInfo);
226 Array::Ptr arr = dynamic_pointer_cast<Array>(object);
232 index = Convert::ToLong(field);
234 return GetPrototypeField(context, field, true, debugInfo);
237 if (index < 0 || index >= arr->GetLength())
238 BOOST_THROW_EXCEPTION(ScriptError("Array index '" + Convert::ToString(index) + "' is out of bounds.", debugInfo));
240 return arr->Get(index);
243 Type::Ptr type = object->GetReflectionType();
248 int fid = type->GetFieldId(field);
251 return GetPrototypeField(context, field, true, debugInfo);
253 return object->GetField(fid);
256 static inline void SetField(const Object::Ptr& context, const String& field, const Value& value, const DebugInfo& debugInfo = DebugInfo())
258 Dictionary::Ptr dict = dynamic_pointer_cast<Dictionary>(context);
261 dict->Set(field, value);
265 Array::Ptr arr = dynamic_pointer_cast<Array>(context);
268 int index = Convert::ToLong(field);
269 if (index >= arr->GetLength())
270 arr->Resize(index + 1);
271 arr->Set(index, value);
275 Type::Ptr type = context->GetReflectionType();
278 BOOST_THROW_EXCEPTION(ScriptError("Cannot set field on object.", debugInfo));
280 int fid = type->GetFieldId(field);
283 BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' does not exist.", debugInfo));
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));
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)
298 if (arguments.size() < funcargs.size())
299 BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments for function"));
301 ScriptFrame *vframe = ScriptFrame::GetCurrentFrame();
302 ScriptFrame frame(vframe->Self);
305 closedVars->CopyTo(frame.Locals);
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]);
310 return expr->Evaluate(frame);
313 static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, std::map<String, Expression *> *closedVars)
315 Dictionary::Ptr locals;
318 locals = new Dictionary();
320 typedef std::pair<String, Expression *> ClosedVar;
321 BOOST_FOREACH(const ClosedVar& cvar, *closedVars) {
322 locals->Set(cvar.first, cvar.second->Evaluate(frame));