]> granicus.if.org Git - icinga2/blobdiff - lib/cli/repositoryutility.cpp
Cli: Ignore 'import' attribute on repository add validation
[icinga2] / lib / cli / repositoryutility.cpp
index af881d6043160cebf74cc819fda4b448fb7c903d..88936266fc54e94d4cbd150f403d28bbe7c73f13 100644 (file)
 
 #include "cli/repositoryutility.hpp"
 #include "cli/clicommand.hpp"
+#include "config/configtype.hpp"
+#include "config/configcompilercontext.hpp"
+#include "config/configcompiler.hpp"
 #include "base/logger.hpp"
 #include "base/application.hpp"
 #include "base/convert.hpp"
 #include "base/json.hpp"
 #include "base/netstring.hpp"
+#include "base/tlsutility.hpp"
 #include "base/stdiostream.hpp"
 #include "base/debug.hpp"
 #include "base/objectlock.hpp"
@@ -42,20 +46,30 @@ using namespace icinga;
 
 Dictionary::Ptr RepositoryUtility::GetArgumentAttributes(const std::vector<std::string>& arguments)
 {
-       Dictionary::Ptr attr = make_shared<Dictionary>();
+       Dictionary::Ptr attrs = make_shared<Dictionary>();
 
        BOOST_FOREACH(const String& kv, arguments) {
                std::vector<String> tokens;
                boost::algorithm::split(tokens, kv, boost::is_any_of("="));
 
-               if (tokens.size() == 2) {
-                       attr->Set(tokens[0], tokens[1]);
-               } else
+               if (tokens.size() != 2) {
                        Log(LogWarning, "cli")
                            << "Cannot parse passed attributes: " << boost::algorithm::join(tokens, "=");
+                       continue;
+               }
+
+               Value value;
+
+               try {
+                       value = Convert::ToDouble(tokens[1]);
+               } catch (...) {
+                       value = tokens[1];
+               }
+
+               attrs->Set(tokens[0], value);
        }
 
-       return attr;
+       return attrs;
 }
 
 String RepositoryUtility::GetRepositoryConfigPath(void)
@@ -73,7 +87,7 @@ String RepositoryUtility::GetRepositoryObjectConfigPath(const String& type, cons
                path += "hosts/" + object->Get("host_name");
        else if (type == "Zone")
                path += "zones";
-       else if (type == "Endpoints")
+       else if (type == "Endpoint")
                path += "endpoints";
 
        return path;
@@ -122,12 +136,32 @@ void RepositoryUtility::PrintObjects(std::ostream& fp, const String& type)
                        continue;
                }
 
-               fp << "Object Path: " << object << "\n";
+               String file = Utility::BaseName(object);
+               boost::algorithm::replace_all(file, ".conf", "");
+
+               fp << ConsoleColorTag(Console_ForegroundMagenta | Console_Bold) << type << ConsoleColorTag(Console_Normal)
+                  << " '" << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << file << ConsoleColorTag(Console_Normal) << "'";
+
+               String prefix = Utility::DirName(object);
+
+               if (type == "Service") {
+                       std::vector<String> tokens;
+                       boost::algorithm::split(tokens, prefix, boost::is_any_of("/"));
+
+                       String host_name = tokens[tokens.size()-1];
+                       fp << " (on " << ConsoleColorTag(Console_ForegroundMagenta | Console_Bold) << "Host" << ConsoleColorTag(Console_Normal)
+                          << " '" << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << host_name << ConsoleColorTag(Console_Normal) << "')";
+
+               }
+
+               fp << "\n";
 
+               /*
                Dictionary::Ptr obj = GetObjectFromRepository(object); //TODO: config parser not implemented yet!
 
                if (obj)
                        fp << JsonEncode(obj);
+               */
        }
 }
 
@@ -146,11 +180,20 @@ void RepositoryUtility::PrintChangeLog(std::ostream& fp)
        }
 }
 
+class RepositoryTypeRuleUtilities : public TypeRuleUtilities
+{
+public:
+       virtual bool ValidateName(const String& type, const String& name, String *hint) const
+       {
+               return true;
+       }
+};
+
 /* modify objects and write changelog */
-bool RepositoryUtility::AddObject(const String& name, const String& type, const Dictionary::Ptr& attr)
+bool RepositoryUtility::AddObject(const String& name, const String& type, const Dictionary::Ptr& attrs)
 {
        /* add a new changelog entry by timestamp */
-       String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(static_cast<long>(Utility::GetTime())) + ".change";
+       String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(Utility::GetTime()) + "-" + type + "-" + SHA256(name) + ".change";
 
        Dictionary::Ptr change = make_shared<Dictionary>();
 
@@ -158,15 +201,55 @@ bool RepositoryUtility::AddObject(const String& name, const String& type, const
        change->Set("name", name);
        change->Set("type", type);
        change->Set("command", "add");
-       change->Set("attr", attr);
+       change->Set("attrs", attrs);
+
+       ConfigCompilerContext::GetInstance()->Reset();
+
+       String fname, fragment;
+       BOOST_FOREACH(boost::tie(fname, fragment), ConfigFragmentRegistry::GetInstance()->GetItems()) {
+               ConfigCompiler::CompileText(fname, fragment);
+       }
+
+       ConfigType::Ptr ctype = ConfigType::GetByName(type);
+
+       if (!ctype)
+               Log(LogCritical, "cli")
+                   << "No validation type available for '" << type << "'.";
+       else {
+               Dictionary::Ptr vattrs = attrs->ShallowClone();
+               vattrs->Set("__name", vattrs->Get("name"));
+               vattrs->Remove("name");
+               vattrs->Remove("import");
+               vattrs->Set("type", type);
+
+               RepositoryTypeRuleUtilities utils;
+               ctype->ValidateItem(name, vattrs, DebugInfo(), &utils);
+
+               int warnings = 0, errors = 0;
+
+               BOOST_FOREACH(const ConfigCompilerMessage& message, ConfigCompilerContext::GetInstance()->GetMessages()) {
+                       String logmsg = String("Config ") + (message.Error ? "error" : "warning") + ": " + message.Text;
+
+                       if (message.Error) {
+                               Log(LogCritical, "config", logmsg);
+                               errors++;
+                       } else {
+                               Log(LogWarning, "config", logmsg);
+                               warnings++;
+                       }
+               }
+
+               if (errors > 0)
+                       return false;
+       }
 
        return WriteObjectToRepositoryChangeLog(path, change);
 }
 
-bool RepositoryUtility::RemoveObject(const String& name, const String& type, const Dictionary::Ptr& attr)
+bool RepositoryUtility::RemoveObject(const String& name, const String& type, const Dictionary::Ptr& attrs)
 {
        /* add a new changelog entry by timestamp */
-       String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(static_cast<long>(Utility::GetTime())) + ".change";
+       String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(Utility::GetTime()) + "-" + type + "-" + SHA256(name) + ".change";
 
        Dictionary::Ptr change = make_shared<Dictionary>();
 
@@ -174,7 +257,7 @@ bool RepositoryUtility::RemoveObject(const String& name, const String& type, con
        change->Set("name", name);
        change->Set("type", type);
        change->Set("command", "remove");
-       change->Set("attr", attr); //required for service->host_name
+       change->Set("attrs", attrs); //required for service->host_name
 
        return WriteObjectToRepositoryChangeLog(path, change);
 }
@@ -185,6 +268,21 @@ bool RepositoryUtility::SetObjectAttribute(const String& name, const String& typ
        return true;
 }
 
+bool RepositoryUtility::ClearChangeLog(void)
+{
+       GetChangeLog(boost::bind(RepositoryUtility::ClearChange, _1, _2));
+
+       return true;
+}
+
+bool RepositoryUtility::ChangeLogHasPendingChanges(void)
+{
+       Array::Ptr changelog = make_shared<Array>();
+       GetChangeLog(boost::bind(RepositoryUtility::CollectChange, _1, boost::ref(changelog)));
+
+       return changelog->GetLength() > 0;
+}
+
 /* commit changelog */
 bool RepositoryUtility::CommitChangeLog(void)
 {
@@ -236,18 +334,38 @@ Dictionary::Ptr RepositoryUtility::GetObjectFromRepositoryChangeLog(const String
 }
 
 /* internal implementation when changes are committed */
-bool RepositoryUtility::AddObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attr)
+bool RepositoryUtility::AddObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attrs)
 {
-       String path = GetRepositoryObjectConfigPath(type, attr) + "/" + name + ".conf";
+       String path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name + ".conf";
 
-       return WriteObjectToRepository(path, name, type, attr);
+       return WriteObjectToRepository(path, name, type, attrs);
 }
 
-bool RepositoryUtility::RemoveObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attr)
+bool RepositoryUtility::RemoveObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attrs)
 {
-       String path = GetRepositoryObjectConfigPath(type, attr) + "/" + name + ".conf";
+       String path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name + ".conf";
+       bool success = RemoveObjectFileInternal(path);
+
+       /* special treatment for hosts -> remove the services too */
+       if (type == "Host") {
+               path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name;
+
+               std::vector<String> files;
+               Utility::GlobRecursive(path, "*.conf",
+                   boost::bind(&RepositoryUtility::CollectObjects, _1, boost::ref(files)), GlobFile);
+
+               BOOST_FOREACH(const String& file, files) {
+                       RemoveObjectFileInternal(file);
+               }
+#ifndef _WIN32
+               rmdir(path.CStr());
+#else
+               _rmdir(path.CStr());
+#endif /* _WIN32 */
+
+       }
 
-       return RemoveObjectFileInternal(path);
+       return success;
 }
 
 bool RepositoryUtility::RemoveObjectFileInternal(const String& path)
@@ -258,7 +376,7 @@ bool RepositoryUtility::RemoveObjectFileInternal(const String& path)
        }
 
        if (unlink(path.CStr()) < 0) {
-               Log(LogCritical, "cli", "Cannot remove file '" + path +
+               Log(LogCritical, "cli", "Cannot remove path '" + path +
                    "'. Failed with error code " + Convert::ToString(errno) + ", \"" + Utility::FormatErrorNumber(errno) + "\".");
                return false;
        }
@@ -266,10 +384,10 @@ bool RepositoryUtility::RemoveObjectFileInternal(const String& path)
        return true;
 }
 
-bool RepositoryUtility::SetObjectAttributeInternal(const String& name, const String& type, const String& key, const Value& val, const Dictionary::Ptr& attr)
+bool RepositoryUtility::SetObjectAttributeInternal(const String& name, const String& type, const String& key, const Value& val, const Dictionary::Ptr& attrs)
 {
        //Fixme
-       String path = GetRepositoryObjectConfigPath(type, attr) + "/" + name + ".conf";
+       String path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name + ".conf";
 
        Dictionary::Ptr obj = GetObjectFromRepository(path); //TODO
 
@@ -295,7 +413,8 @@ bool RepositoryUtility::SetObjectAttributeInternal(const String& name, const Str
 
 bool RepositoryUtility::WriteObjectToRepository(const String& path, const String& name, const String& type, const Dictionary::Ptr& item)
 {
-       Log(LogInformation, "cli", "Dumping config items to file '" + path + "'");
+       Log(LogInformation, "cli")
+           << "Dumping config object '" << name << "' to file '" << path << "'";
 
        Utility::MkDirP(Utility::DirName(path), 0755);
 
@@ -380,7 +499,9 @@ void RepositoryUtility::CollectChangeLog(const String& change_file, std::vector<
        String file = Utility::BaseName(change_file);
        boost::algorithm::replace_all(file, ".change", "");
 
-       Log(LogDebug, "cli", "Adding change file: " + file);
+       Log(LogDebug, "cli")
+           << "Adding change file: '" << file << "'.";
+
        changelog.push_back(file);
 }
 
@@ -390,7 +511,7 @@ void RepositoryUtility::CollectChange(const Dictionary::Ptr& change, Array::Ptr&
 }
 
 /*
- * Commit Changelog
+ * Commit Changelog entry
  */
 void RepositoryUtility::CommitChange(const Dictionary::Ptr& change, const String& path)
 {
@@ -400,19 +521,19 @@ void RepositoryUtility::CommitChange(const Dictionary::Ptr& change, const String
        String name = change->Get("name");
        String type = change->Get("type");
        String command = change->Get("command");
-       Dictionary::Ptr attr;
+       Dictionary::Ptr attrs;
 
-       if (change->Contains("attr")) {
-               attr = change->Get("attr");
+       if (change->Contains("attrs")) {
+               attrs = change->Get("attrs");
        }
 
        bool success = false;
 
        if (command == "add") {
-               success = AddObjectInternal(name, type, attr);
+               success = AddObjectInternal(name, type, attrs);
        }
        else if (command == "remove") {
-               success = RemoveObjectInternal(name, type, attr);
+               success = RemoveObjectInternal(name, type, attrs);
        }
 
        if (success) {
@@ -422,6 +543,20 @@ void RepositoryUtility::CommitChange(const Dictionary::Ptr& change, const String
        }
 }
 
+/*
+ * Clear Changelog entry
+ */
+void RepositoryUtility::ClearChange(const Dictionary::Ptr& change, const String& path)
+{
+       Log(LogDebug, "cli")
+          << "Clearing change " << change->Get("name");
+
+       Log(LogInformation, "cli")
+          << "Removing changelog file '" << path << "'.";
+
+       RemoveObjectFileInternal(path);
+}
+
 /*
  * Print Changelog helpers
  */
@@ -437,7 +572,7 @@ void RepositoryUtility::FormatChangelogEntry(std::ostream& fp, const Dictionary:
 
        String type = change->Get("type");
        boost::algorithm::to_lower(type);
-       Dictionary::Ptr attrs = change->Get("attr");
+       Dictionary::Ptr attrs = change->Get("attrs");
 
        fp << " " << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << type << ConsoleColorTag(Console_Normal) << " '";
        fp << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << change->Get("name") << ConsoleColorTag(Console_Normal) << "'";