]> granicus.if.org Git - icinga2/blob - lib/base/object.cpp
b1fff79d2d77d99a812e57322d9f5521333999f2
[icinga2] / lib / base / object.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2018 Icinga Development Team (https://www.icinga.com/)  *
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 "base/object.hpp"
21 #include "base/value.hpp"
22 #include "base/dictionary.hpp"
23 #include "base/primitivetype.hpp"
24 #include "base/utility.hpp"
25 #include "base/timer.hpp"
26 #include "base/logger.hpp"
27 #include "base/exception.hpp"
28 #include <boost/lexical_cast.hpp>
29 #include <boost/thread/recursive_mutex.hpp>
30
31 using namespace icinga;
32
33 DEFINE_TYPE_INSTANCE(Object);
34
35 #ifdef I2_LEAK_DEBUG
36 static boost::mutex l_ObjectCountLock;
37 static std::map<String, int> l_ObjectCounts;
38 static Timer::Ptr l_ObjectCountTimer;
39 #endif /* I2_LEAK_DEBUG */
40
41 /**
42  * Destructor for the Object class.
43  */
44 Object::~Object()
45 {
46         delete reinterpret_cast<boost::recursive_mutex *>(m_Mutex);
47 }
48
49 /**
50  * Returns a string representation for the object.
51  */
52 String Object::ToString() const
53 {
54         return "Object of type '" + GetReflectionType()->GetName() + "'";
55 }
56
57 #ifdef I2_DEBUG
58 /**
59  * Checks if the calling thread owns the lock on this object.
60  *
61  * @returns True if the calling thread owns the lock, false otherwise.
62  */
63 bool Object::OwnsLock() const
64 {
65 #ifdef _WIN32
66         DWORD tid = InterlockedExchangeAdd(&m_LockOwner, 0);
67
68         return (tid == GetCurrentThreadId());
69 #else /* _WIN32 */
70         pthread_t tid = __sync_fetch_and_add(&m_LockOwner, 0);
71
72         return (tid == pthread_self());
73 #endif /* _WIN32 */
74 }
75 #endif /* I2_DEBUG */
76
77 void Object::SetField(int id, const Value&, bool, const Value&)
78 {
79         if (id == 0)
80                 BOOST_THROW_EXCEPTION(std::runtime_error("Type field cannot be set."));
81         else
82                 BOOST_THROW_EXCEPTION(std::runtime_error("Invalid field ID."));
83 }
84
85 Value Object::GetField(int id) const
86 {
87         if (id == 0)
88                 return GetReflectionType()->GetName();
89         else
90                 BOOST_THROW_EXCEPTION(std::runtime_error("Invalid field ID."));
91 }
92
93 bool Object::HasOwnField(const String& field) const
94 {
95         Type::Ptr type = GetReflectionType();
96
97         if (!type)
98                 return false;
99
100         return type->GetFieldId(field) != -1;
101 }
102
103 bool Object::GetOwnField(const String& field, Value *result) const
104 {
105         Type::Ptr type = GetReflectionType();
106
107         if (!type)
108                 return false;
109
110         int tid = type->GetFieldId(field);
111
112         if (tid == -1)
113                 return false;
114
115         *result = GetField(tid);
116         return true;
117 }
118
119 Value Object::GetFieldByName(const String& field, bool sandboxed, const DebugInfo& debugInfo) const
120 {
121         Type::Ptr type = GetReflectionType();
122
123         if (!type)
124                 return Empty;
125
126         int fid = type->GetFieldId(field);
127
128         if (fid == -1)
129                 return GetPrototypeField(const_cast<Object *>(this), field, true, debugInfo);
130
131         if (sandboxed) {
132                 Field fieldInfo = type->GetFieldInfo(fid);
133
134                 if (fieldInfo.Attributes & FANoUserView)
135                         BOOST_THROW_EXCEPTION(ScriptError("Accessing the field '" + field + "' for type '" + type->GetName() + "' is not allowed in sandbox mode.", debugInfo));
136         }
137
138         return GetField(fid);
139 }
140
141 void Object::SetFieldByName(const String& field, const Value& value, const DebugInfo& debugInfo)
142 {
143         Type::Ptr type = GetReflectionType();
144
145         if (!type)
146                 BOOST_THROW_EXCEPTION(ScriptError("Cannot set field on object.", debugInfo));
147
148         int fid = type->GetFieldId(field);
149
150         if (fid == -1)
151                 BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' does not exist.", debugInfo));
152
153         try {
154                 SetField(fid, value);
155         } catch (const boost::bad_lexical_cast&) {
156                 Field fieldInfo = type->GetFieldInfo(fid);
157                 Type::Ptr ftype = Type::GetByName(fieldInfo.TypeName);
158                 BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' cannot be set to value of type '" + value.GetTypeName() + "', expected '" + ftype->GetName() + "'", debugInfo));
159         } catch (const std::bad_cast&) {
160                 Field fieldInfo = type->GetFieldInfo(fid);
161                 Type::Ptr ftype = Type::GetByName(fieldInfo.TypeName);
162                 BOOST_THROW_EXCEPTION(ScriptError("Attribute '" + field + "' cannot be set to value of type '" + value.GetTypeName() + "', expected '" + ftype->GetName() + "'", debugInfo));
163         }
164 }
165
166 void Object::Validate(int types, const ValidationUtils& utils)
167 {
168         /* Nothing to do here. */
169 }
170
171 void Object::ValidateField(int id, const Lazy<Value>& lvalue, const ValidationUtils& utils)
172 {
173         /* Nothing to do here. */
174 }
175
176 void Object::NotifyField(int id, const Value& cookie)
177 {
178         BOOST_THROW_EXCEPTION(std::runtime_error("Invalid field ID."));
179 }
180
181 Object::Ptr Object::NavigateField(int id) const
182 {
183         BOOST_THROW_EXCEPTION(std::runtime_error("Invalid field ID."));
184 }
185
186 Object::Ptr Object::Clone() const
187 {
188         BOOST_THROW_EXCEPTION(std::runtime_error("Object cannot be cloned."));
189 }
190
191 Type::Ptr Object::GetReflectionType() const
192 {
193         return Object::TypeInstance;
194 }
195
196 Value icinga::GetPrototypeField(const Value& context, const String& field, bool not_found_error, const DebugInfo& debugInfo)
197 {
198         Type::Ptr ctype = context.GetReflectionType();
199         Type::Ptr type = ctype;
200
201         do {
202                 Object::Ptr object = type->GetPrototype();
203
204                 if (object && object->HasOwnField(field))
205                         return object->GetFieldByName(field, false, debugInfo);
206
207                 type = type->GetBaseType();
208         } while (type);
209
210         if (not_found_error)
211                 BOOST_THROW_EXCEPTION(ScriptError("Invalid field access (for value of type '" + ctype->GetName() + "'): '" + field + "'", debugInfo));
212         else
213                 return Empty;
214 }
215
216 #ifdef I2_LEAK_DEBUG
217 void icinga::TypeAddObject(Object *object)
218 {
219         boost::mutex::scoped_lock lock(l_ObjectCountLock);
220         String typeName = Utility::GetTypeName(typeid(*object));
221         l_ObjectCounts[typeName]++;
222 }
223
224 void icinga::TypeRemoveObject(Object *object)
225 {
226         boost::mutex::scoped_lock lock(l_ObjectCountLock);
227         String typeName = Utility::GetTypeName(typeid(*object));
228         l_ObjectCounts[typeName]--;
229 }
230
231 static void TypeInfoTimerHandler()
232 {
233         boost::mutex::scoped_lock lock(l_ObjectCountLock);
234
235         typedef std::map<String, int>::value_type kv_pair;
236         for (kv_pair& kv : l_ObjectCounts) {
237                 if (kv.second == 0)
238                         continue;
239
240                 Log(LogInformation, "TypeInfo")
241                         << kv.second << " " << kv.first << " objects";
242
243                 kv.second = 0;
244         }
245 }
246
247 INITIALIZE_ONCE([]() {
248         l_ObjectCountTimer = new Timer();
249         l_ObjectCountTimer->SetInterval(10);
250         l_ObjectCountTimer->OnTimerExpired.connect(std::bind(TypeInfoTimerHandler));
251         l_ObjectCountTimer->Start();
252 });
253 #endif /* I2_LEAK_DEBUG */
254
255 void icinga::intrusive_ptr_add_ref(Object *object)
256 {
257 #ifdef I2_LEAK_DEBUG
258         if (object->m_References == 0)
259                 TypeAddObject(object);
260 #endif /* I2_LEAK_DEBUG */
261
262 #ifdef _WIN32
263         InterlockedIncrement(&object->m_References);
264 #else /* _WIN32 */
265         __sync_add_and_fetch(&object->m_References, 1);
266 #endif /* _WIN32 */
267 }
268
269 void icinga::intrusive_ptr_release(Object *object)
270 {
271         uintptr_t refs;
272
273 #ifdef _WIN32
274         refs = InterlockedDecrement(&object->m_References);
275 #else /* _WIN32 */
276         refs = __sync_sub_and_fetch(&object->m_References, 1);
277 #endif /* _WIN32 */
278
279         if (unlikely(refs == 0)) {
280 #ifdef I2_LEAK_DEBUG
281                 TypeRemoveObject(object);
282 #endif /* I2_LEAK_DEBUG */
283
284                 delete object;
285         }
286 }
287
288 void icinga::DefaultObjectFactoryCheckArgs(const std::vector<Value>& args)
289 {
290         if (!args.empty())
291                 BOOST_THROW_EXCEPTION(std::invalid_argument("Constructor does not take any arguments."));
292 }
293
294 void icinga::RequireNotNullInternal(const intrusive_ptr<Object>& object, const char *description)
295 {
296         if (!object)
297                 BOOST_THROW_EXCEPTION(std::invalid_argument("Pointer must not be null: " + String(description)));
298 }