1 /******************************************************************************
3 * Copyright (C) 2012-2016 Icinga Development Team (https://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 ******************************************************************************/
20 #include "base/scriptglobal.hpp"
21 #include "base/singleton.hpp"
22 #include "base/logger.hpp"
23 #include "base/stdiostream.hpp"
24 #include "base/netstring.hpp"
25 #include "base/json.hpp"
26 #include "base/convert.hpp"
27 #include "base/objectlock.hpp"
28 #include "base/exception.hpp"
29 #include <boost/foreach.hpp>
32 using namespace icinga;
34 Dictionary::Ptr ScriptGlobal::m_Globals = new Dictionary();
36 Value ScriptGlobal::Get(const String& name, const Value *defaultValue)
38 if (!m_Globals->Contains(name)) {
42 BOOST_THROW_EXCEPTION(std::invalid_argument("Tried to access undefined script variable '" + name + "'"));
45 return m_Globals->Get(name);
48 void ScriptGlobal::Set(const String& name, const Value& value)
50 m_Globals->Set(name, value);
53 bool ScriptGlobal::Exists(const String& name)
55 return m_Globals->Contains(name);
58 Dictionary::Ptr ScriptGlobal::GetGlobals(void)
63 void ScriptGlobal::WriteToFile(const String& filename)
65 Log(LogInformation, "ScriptGlobal")
66 << "Dumping variables to file '" << filename << "'";
68 String tempFilename = filename + ".tmp";
71 fp.open(tempFilename.CStr(), std::ios_base::out);
74 BOOST_THROW_EXCEPTION(std::runtime_error("Could not open '" + tempFilename + "' file"));
76 StdioStream::Ptr sfp = new StdioStream(&fp, false);
78 ObjectLock olock(m_Globals);
79 BOOST_FOREACH(const Dictionary::Pair& kv, m_Globals) {
80 Dictionary::Ptr persistentVariable = new Dictionary();
82 persistentVariable->Set("name", kv.first);
84 Value value = kv.second;
87 value = Convert::ToString(value);
89 persistentVariable->Set("value", value);
91 String json = JsonEncode(persistentVariable);
93 NetString::WriteStringToStream(sfp, json);
101 _unlink(filename.CStr());
104 if (rename(tempFilename.CStr(), filename.CStr()) < 0) {
105 BOOST_THROW_EXCEPTION(posix_error()
106 << boost::errinfo_api_function("rename")
107 << boost::errinfo_errno(errno)
108 << boost::errinfo_file_name(tempFilename));