1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "base/scriptglobal.hpp"
4 #include "base/singleton.hpp"
5 #include "base/logger.hpp"
6 #include "base/stdiostream.hpp"
7 #include "base/netstring.hpp"
8 #include "base/json.hpp"
9 #include "base/convert.hpp"
10 #include "base/objectlock.hpp"
11 #include "base/exception.hpp"
12 #include "base/namespace.hpp"
13 #include "base/utility.hpp"
16 using namespace icinga;
18 Namespace::Ptr ScriptGlobal::m_Globals = new Namespace();
20 Value ScriptGlobal::Get(const String& name, const Value *defaultValue)
24 if (!m_Globals->Get(name, &result)) {
28 BOOST_THROW_EXCEPTION(std::invalid_argument("Tried to access undefined script variable '" + name + "'"));
34 void ScriptGlobal::Set(const String& name, const Value& value, bool overrideFrozen)
36 std::vector<String> tokens = name.Split(".");
39 BOOST_THROW_EXCEPTION(std::invalid_argument("Name must not be empty"));
42 ObjectLock olock(m_Globals);
44 Namespace::Ptr parent = m_Globals;
46 for (std::vector<String>::size_type i = 0; i < tokens.size(); i++) {
47 const String& token = tokens[i];
49 if (i + 1 != tokens.size()) {
52 if (!parent->Get(token, &vparent)) {
53 Namespace::Ptr dict = new Namespace();
54 parent->Set(token, dict);
62 parent->SetFieldByName(tokens[tokens.size() - 1], value, overrideFrozen, DebugInfo());
66 void ScriptGlobal::SetConst(const String& name, const Value& value)
68 GetGlobals()->SetAttribute(name, std::make_shared<ConstEmbeddedNamespaceValue>(value));
71 bool ScriptGlobal::Exists(const String& name)
73 return m_Globals->Contains(name);
76 Namespace::Ptr ScriptGlobal::GetGlobals()
81 void ScriptGlobal::WriteToFile(const String& filename)
83 Log(LogInformation, "ScriptGlobal")
84 << "Dumping variables to file '" << filename << "'";
87 String tempFilename = Utility::CreateTempFile(filename + ".XXXXXX", 0600, fp);
90 BOOST_THROW_EXCEPTION(std::runtime_error("Could not open '" + tempFilename + "' file"));
92 StdioStream::Ptr sfp = new StdioStream(&fp, false);
94 ObjectLock olock(m_Globals);
95 for (const Namespace::Pair& kv : m_Globals) {
96 Value value = kv.second->Get();
99 value = Convert::ToString(value);
101 Dictionary::Ptr persistentVariable = new Dictionary({
102 { "name", kv.first },
106 String json = JsonEncode(persistentVariable);
108 NetString::WriteStringToStream(sfp, json);
115 Utility::RenameFile(tempFilename, filename);