]> granicus.if.org Git - icinga2/blob - lib/config/vmops.hpp
Replace BOOST_FOREACH with range-based for loops
[icinga2] / lib / config / vmops.hpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2016 Icinga Development Team (https://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/smart_ptr/make_shared.hpp>
37 #include <map>
38 #include <vector>
39
40 namespace icinga
41 {
42
43 class VMOps
44 {
45 public:
46         static inline bool FindVarImportRef(ScriptFrame& frame, const String& name, Value *result, const DebugInfo& debugInfo = DebugInfo())
47         {
48                 Array::Ptr imports = ScriptFrame::GetImports();
49
50                 ObjectLock olock(imports);
51                 for (const Value& import : imports) {
52                         Object::Ptr obj = import;
53                         if (obj->HasOwnField(name)) {
54                                 *result = import;
55                                 return true;
56                         }
57                 }
58
59                 return false;
60         }
61
62         static inline bool FindVarImport(ScriptFrame& frame, const String& name, Value *result, const DebugInfo& debugInfo = DebugInfo())
63         {
64                 Value parent;
65
66                 if (FindVarImportRef(frame, name, &parent, debugInfo)) {
67                         *result = GetField(parent, name, frame.Sandboxed, debugInfo);
68                         return true;
69                 }
70
71                 return false;
72         }
73
74         static inline Value ConstructorCall(const Type::Ptr& type, const std::vector<Value>& args, const DebugInfo& debugInfo = DebugInfo())
75         {
76                 if (type->GetName() == "String") {
77                         if (args.empty())
78                                 return "";
79                         else if (args.size() == 1)
80                                 return Convert::ToString(args[0]);
81                         else
82                                 BOOST_THROW_EXCEPTION(ScriptError("Too many arguments for constructor."));
83                 } else if (type->GetName() == "Number") {
84                         if (args.empty())
85                                 return 0;
86                         else if (args.size() == 1)
87                                 return Convert::ToDouble(args[0]);
88                         else
89                                 BOOST_THROW_EXCEPTION(ScriptError("Too many arguments for constructor."));
90                 } else if (type->GetName() == "Boolean") {
91                         if (args.empty())
92                                 return 0;
93                         else if (args.size() == 1)
94                                 return Convert::ToBool(args[0]);
95                         else
96                                 BOOST_THROW_EXCEPTION(ScriptError("Too many arguments for constructor."));
97                 } else if (args.size() == 1 && type->IsAssignableFrom(args[0].GetReflectionType()))
98                         return args[0];
99                 else
100                         return type->Instantiate(args);
101         }
102
103         static inline Value FunctionCall(ScriptFrame& frame, const Value& self, const Function::Ptr& func, const std::vector<Value>& arguments)
104         {
105                 ScriptFrame vframe;
106                 
107                 if (!self.IsEmpty() || self.IsString())
108                         return func->Invoke(self, arguments);
109                 else
110                         return func->Invoke(arguments);
111
112         }
113
114         static inline Value NewFunction(ScriptFrame& frame, const String& name, const std::vector<String>& args,
115             std::map<String, Expression *> *closedVars, const boost::shared_ptr<Expression>& expression)
116         {
117                 return new Function(name, boost::bind(&FunctionWrapper, _1, args,
118                     EvaluateClosedVars(frame, closedVars), expression));
119         }
120
121         static inline Value NewApply(ScriptFrame& frame, const String& type, const String& target, const String& name, const boost::shared_ptr<Expression>& filter,
122                 const String& package, const String& fkvar, const String& fvvar, const boost::shared_ptr<Expression>& fterm, std::map<String, Expression *> *closedVars,
123                 bool ignoreOnError, const boost::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
124         {
125                 ApplyRule::AddRule(type, target, name, expression, filter, package, fkvar,
126                     fvvar, fterm, ignoreOnError, debugInfo, EvaluateClosedVars(frame, closedVars));
127
128                 return Empty;
129         }
130
131         static inline Value NewObject(ScriptFrame& frame, bool abstract, const String& type, const String& name, const boost::shared_ptr<Expression>& filter,
132                 const String& zone, const String& package, bool ignoreOnError, std::map<String, Expression *> *closedVars, const boost::shared_ptr<Expression>& expression, const DebugInfo& debugInfo = DebugInfo())
133         {
134                 ConfigItemBuilder::Ptr item = new ConfigItemBuilder(debugInfo);
135
136                 String checkName = name;
137
138                 if (!abstract) {
139                         Type::Ptr ptype = Type::GetByName(type);
140
141                         NameComposer *nc = dynamic_cast<NameComposer *>(ptype.get());
142
143                         if (nc)
144                                 checkName = nc->MakeName(name, Dictionary::Ptr());
145                 }
146
147                 if (!checkName.IsEmpty()) {
148                         ConfigItem::Ptr oldItem = ConfigItem::GetByTypeAndName(type, checkName);
149
150                         if (oldItem) {
151                                 std::ostringstream msgbuf;
152                                 msgbuf << "Object '" << name << "' of type '" << type << "' re-defined: " << debugInfo << "; previous definition: " << oldItem->GetDebugInfo();
153                                 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debugInfo));
154                         }
155                 }
156
157                 item->SetType(type);
158                 item->SetName(name);
159
160                 item->AddExpression(new OwnedExpression(expression));
161                 item->SetAbstract(abstract);
162                 item->SetScope(EvaluateClosedVars(frame, closedVars));
163                 item->SetZone(zone);
164                 item->SetPackage(package);
165                 item->SetFilter(filter);
166                 item->SetIgnoreOnError(ignoreOnError);
167                 item->Compile()->Register();
168
169                 return Empty;
170         }
171
172         static inline ExpressionResult For(ScriptFrame& frame, const String& fkvar, const String& fvvar, const Value& value, Expression *expression, const DebugInfo& debugInfo = DebugInfo())
173         {
174                 if (value.IsObjectType<Array>()) {
175                         if (!fvvar.IsEmpty())
176                                 BOOST_THROW_EXCEPTION(ScriptError("Cannot use dictionary iterator for array.", debugInfo));
177
178                         Array::Ptr arr = value;
179
180                         for (Array::SizeType i = 0; i < arr->GetLength(); i++) {
181                                 frame.Locals->Set(fkvar, arr->Get(i));
182                                 ExpressionResult res = expression->Evaluate(frame);
183                                 CHECK_RESULT_LOOP(res);
184                         }
185                 } else if (value.IsObjectType<Dictionary>()) {
186                         if (fvvar.IsEmpty())
187                                 BOOST_THROW_EXCEPTION(ScriptError("Cannot use array iterator for dictionary.", debugInfo));
188
189                         Dictionary::Ptr dict = value;
190                         std::vector<String> keys;
191
192                         {
193                                 ObjectLock olock(dict);
194                                 for (const Dictionary::Pair& kv : dict) {
195                                         keys.push_back(kv.first);
196                                 }
197                         }
198
199                         for (const String& key : keys) {
200                                 frame.Locals->Set(fkvar, key);
201                                 frame.Locals->Set(fvvar, dict->Get(key));
202                                 ExpressionResult res = expression->Evaluate(frame);
203                                 CHECK_RESULT_LOOP(res);
204                         }
205                 } else
206                         BOOST_THROW_EXCEPTION(ScriptError("Invalid type in for expression: " + value.GetTypeName(), debugInfo));
207
208                 return Empty;
209         }
210
211         static inline Value GetField(const Value& context, const String& field, bool sandboxed = false, const DebugInfo& debugInfo = DebugInfo())
212         {
213                 if (unlikely(context.IsEmpty() && !context.IsString()))
214                         return Empty;
215
216                 if (unlikely(!context.IsObject()))
217                         return GetPrototypeField(context, field, true, debugInfo);
218
219                 Object::Ptr object = context;
220
221                 return object->GetFieldByName(field, sandboxed, debugInfo);
222         }
223
224         static inline void SetField(const Object::Ptr& context, const String& field, const Value& value, const DebugInfo& debugInfo = DebugInfo())
225         {
226                 if (!context)
227                         BOOST_THROW_EXCEPTION(ScriptError("Cannot set field '" + field + "' on a value that is not an object.", debugInfo));
228
229                 return context->SetFieldByName(field, value, debugInfo);
230         }
231
232 private:
233         static inline Value FunctionWrapper(const std::vector<Value>& arguments,
234             const std::vector<String>& funcargs, const Dictionary::Ptr& closedVars, const boost::shared_ptr<Expression>& expr)
235         {
236                 if (arguments.size() < funcargs.size())
237                         BOOST_THROW_EXCEPTION(std::invalid_argument("Too few arguments for function"));
238
239                 ScriptFrame *frame = ScriptFrame::GetCurrentFrame();
240
241                 if (closedVars)
242                         closedVars->CopyTo(frame->Locals);
243
244                 for (std::vector<Value>::size_type i = 0; i < std::min(arguments.size(), funcargs.size()); i++)
245                         frame->Locals->Set(funcargs[i], arguments[i]);
246
247                 return expr->Evaluate(*frame);
248         }
249
250         static inline Dictionary::Ptr EvaluateClosedVars(ScriptFrame& frame, std::map<String, Expression *> *closedVars)
251         {
252                 Dictionary::Ptr locals;
253
254                 if (closedVars) {
255                         locals = new Dictionary();
256
257                         typedef std::pair<String, Expression *> ClosedVar;
258                         for (const ClosedVar& cvar : *closedVars) {
259                                 locals->Set(cvar.first, cvar.second->Evaluate(frame));
260                         }
261                 }
262
263                 return locals;
264         }
265 };
266
267 }
268
269 #endif /* VMOPS_H */