1 /******************************************************************************
3 * Copyright (C) 2012-2014 Icinga Development Team (http://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 "cli/repositoryutility.hpp"
21 #include "cli/clicommand.hpp"
22 #include "base/logger.hpp"
23 #include "base/application.hpp"
24 #include "base/convert.hpp"
25 #include "base/json.hpp"
26 #include "base/netstring.hpp"
27 #include "base/tlsutility.hpp"
28 #include "base/stdiostream.hpp"
29 #include "base/debug.hpp"
30 #include "base/objectlock.hpp"
31 #include "base/console.hpp"
32 #include <boost/foreach.hpp>
33 #include <boost/algorithm/string/join.hpp>
34 #include <boost/algorithm/string/replace.hpp>
35 #include <boost/algorithm/string/split.hpp>
36 #include <boost/algorithm/string/classification.hpp>
37 #include <boost/algorithm/string/case_conv.hpp>
38 #include <boost/regex.hpp>
42 using namespace icinga;
44 Dictionary::Ptr RepositoryUtility::GetArgumentAttributes(const std::vector<std::string>& arguments)
46 Dictionary::Ptr attrs = make_shared<Dictionary>();
48 BOOST_FOREACH(const String& kv, arguments) {
49 std::vector<String> tokens;
50 boost::algorithm::split(tokens, kv, boost::is_any_of("="));
52 if (tokens.size() != 2) {
53 Log(LogWarning, "cli")
54 << "Cannot parse passed attributes: " << boost::algorithm::join(tokens, "=");
61 value = Convert::ToDouble(tokens[1]);
66 attrs->Set(tokens[0], value);
72 String RepositoryUtility::GetRepositoryConfigPath(void)
74 return Application::GetSysconfDir() + "/icinga2/repository.d";
77 String RepositoryUtility::GetRepositoryObjectConfigPath(const String& type, const Dictionary::Ptr& object)
79 String path = GetRepositoryConfigPath() + "/";
83 else if (type == "Service")
84 path += "hosts/" + object->Get("host_name");
85 else if (type == "Zone")
87 else if (type == "Endpoints")
93 bool RepositoryUtility::FilterRepositoryObjects(const String& type, const String& path)
96 boost::regex expr("hosts/[^/]*.conf", boost::regex::icase);
98 return boost::regex_search(path.GetData(), what, expr);
100 else if (type == "Service")
101 return Utility::Match("*hosts/*/*.conf", path);
102 else if (type == "Zone")
103 return Utility::Match("*zones/*.conf", path);
104 else if (type == "Endpoints")
105 return Utility::Match("*endpoints/*.conf", path);
110 String RepositoryUtility::GetRepositoryObjectConfigFilePath(const String& type, const Dictionary::Ptr& object)
112 String path = GetRepositoryObjectConfigPath(type, object);
114 path += "/" + object->Get("name") + ".conf";
119 String RepositoryUtility::GetRepositoryChangeLogPath(void)
121 return Application::GetLocalStateDir() + "/lib/icinga2/repository/changes";
125 void RepositoryUtility::PrintObjects(std::ostream& fp, const String& type)
127 std::vector<String> objects = GetObjects(); //full path
129 BOOST_FOREACH(const String& object, objects) {
130 if (!FilterRepositoryObjects(type, object)) {
132 << "Ignoring object '" << object << "'. Type '" << type << "' does not match.";
136 fp << "Object Path: " << object << "\n";
138 Dictionary::Ptr obj = GetObjectFromRepository(object); //TODO: config parser not implemented yet!
141 fp << JsonEncode(obj);
145 void RepositoryUtility::PrintChangeLog(std::ostream& fp)
147 Array::Ptr changelog = make_shared<Array>();
149 GetChangeLog(boost::bind(RepositoryUtility::CollectChange, _1, boost::ref(changelog)));
151 ObjectLock olock(changelog);
153 std::cout << "Changes to be committed:\n\n";
155 BOOST_FOREACH(const Value& entry, changelog) {
156 FormatChangelogEntry(std::cout, entry);
160 /* modify objects and write changelog */
161 bool RepositoryUtility::AddObject(const String& name, const String& type, const Dictionary::Ptr& attrs)
163 /* add a new changelog entry by timestamp */
164 String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(static_cast<long>(Utility::GetTime())) + "-" + SHA256(name) + ".change";
166 Dictionary::Ptr change = make_shared<Dictionary>();
168 change->Set("timestamp", Utility::GetTime());
169 change->Set("name", name);
170 change->Set("type", type);
171 change->Set("command", "add");
172 change->Set("attrs", attrs);
174 return WriteObjectToRepositoryChangeLog(path, change);
177 bool RepositoryUtility::RemoveObject(const String& name, const String& type, const Dictionary::Ptr& attrs)
179 /* add a new changelog entry by timestamp */
180 String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(static_cast<long>(Utility::GetTime())) + "-" + SHA256(name) + ".change";
182 Dictionary::Ptr change = make_shared<Dictionary>();
184 change->Set("timestamp", Utility::GetTime());
185 change->Set("name", name);
186 change->Set("type", type);
187 change->Set("command", "remove");
188 change->Set("attrs", attrs); //required for service->host_name
190 return WriteObjectToRepositoryChangeLog(path, change);
193 bool RepositoryUtility::SetObjectAttribute(const String& name, const String& type, const String& attr, const Value& val)
195 //TODO: Implement modification commands
199 bool RepositoryUtility::ClearChangeLog(void)
201 GetChangeLog(boost::bind(RepositoryUtility::ClearChange, _1, _2));
206 bool RepositoryUtility::ChangeLogHasPendingChanges(void)
208 Array::Ptr changelog = make_shared<Array>();
209 GetChangeLog(boost::bind(RepositoryUtility::CollectChange, _1, boost::ref(changelog)));
211 return changelog->GetLength() > 0;
214 /* commit changelog */
215 bool RepositoryUtility::CommitChangeLog(void)
217 GetChangeLog(boost::bind(RepositoryUtility::CommitChange, _1, _2));
222 /* write/read from changelog repository */
223 bool RepositoryUtility::WriteObjectToRepositoryChangeLog(const String& path, const Dictionary::Ptr& item)
225 Log(LogInformation, "cli", "Dumping changelog items to file '" + path + "'");
227 Utility::MkDirP(Utility::DirName(path), 0750);
229 String tempPath = path + ".tmp";
231 std::ofstream fp(tempPath.CStr(), std::ofstream::out | std::ostream::trunc);
232 fp << JsonEncode(item);
236 _unlink(path.CStr());
239 if (rename(tempPath.CStr(), path.CStr()) < 0) {
240 BOOST_THROW_EXCEPTION(posix_error()
241 << boost::errinfo_api_function("rename")
242 << boost::errinfo_errno(errno)
243 << boost::errinfo_file_name(tempPath));
249 Dictionary::Ptr RepositoryUtility::GetObjectFromRepositoryChangeLog(const String& filename)
252 fp.open(filename.CStr(), std::ifstream::in);
255 return Dictionary::Ptr();
257 String content((std::istreambuf_iterator<char>(fp)), std::istreambuf_iterator<char>());
261 return JsonDecode(content);
264 /* internal implementation when changes are committed */
265 bool RepositoryUtility::AddObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attrs)
267 String path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name + ".conf";
269 return WriteObjectToRepository(path, name, type, attrs);
272 bool RepositoryUtility::RemoveObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attrs)
274 String path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name + ".conf";
275 bool success = RemoveObjectFileInternal(path);
277 /* special treatment for hosts -> remove the services too */
278 if (type == "Host") {
279 path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name;
281 std::vector<String> files;
282 Utility::GlobRecursive(path, "*.conf",
283 boost::bind(&RepositoryUtility::CollectObjects, _1, boost::ref(files)), GlobFile);
285 BOOST_FOREACH(const String& file, files) {
286 RemoveObjectFileInternal(file);
299 bool RepositoryUtility::RemoveObjectFileInternal(const String& path)
301 if (!Utility::PathExists(path) ) {
302 Log(LogCritical, "cli", "Cannot remove '" + path + "'. Does not exist.");
306 if (unlink(path.CStr()) < 0) {
307 Log(LogCritical, "cli", "Cannot remove path '" + path +
308 "'. Failed with error code " + Convert::ToString(errno) + ", \"" + Utility::FormatErrorNumber(errno) + "\".");
315 bool RepositoryUtility::SetObjectAttributeInternal(const String& name, const String& type, const String& key, const Value& val, const Dictionary::Ptr& attrs)
318 String path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name + ".conf";
320 Dictionary::Ptr obj = GetObjectFromRepository(path); //TODO
323 Log(LogCritical, "cli")
324 << "Can't get object " << name << " from repository.\n";
330 std::cout << "Writing object '" << name << "' to path '" << path << "'.\n";
332 //TODO: Create a patch file
333 if(!WriteObjectToRepository(path, name, type, obj)) {
334 Log(LogCritical, "cli")
335 << "Can't write object " << name << " to repository.\n";
342 bool RepositoryUtility::WriteObjectToRepository(const String& path, const String& name, const String& type, const Dictionary::Ptr& item)
344 Log(LogInformation, "cli")
345 << "Dumping config object '" << name << "' to file '" << path << "'";
347 Utility::MkDirP(Utility::DirName(path), 0755);
349 String tempPath = path + ".tmp";
351 std::ofstream fp(tempPath.CStr(), std::ofstream::out | std::ostream::trunc);
352 SerializeObject(fp, name, type, item);
357 _unlink(path.CStr());
360 if (rename(tempPath.CStr(), path.CStr()) < 0) {
361 BOOST_THROW_EXCEPTION(posix_error()
362 << boost::errinfo_api_function("rename")
363 << boost::errinfo_errno(errno)
364 << boost::errinfo_file_name(tempPath));
370 Dictionary::Ptr RepositoryUtility::GetObjectFromRepository(const String& filename)
372 //TODO: Parse existing configuration objects
373 return Dictionary::Ptr();
380 std::vector<String> RepositoryUtility::GetObjects(void)
382 std::vector<String> objects;
383 String path = GetRepositoryConfigPath();
385 Utility::GlobRecursive(path, "*.conf",
386 boost::bind(&RepositoryUtility::CollectObjects, _1, boost::ref(objects)), GlobFile);
391 void RepositoryUtility::CollectObjects(const String& object_file, std::vector<String>& objects)
394 << "Adding object: '" << object_file << "'.";
396 objects.push_back(object_file);
400 bool RepositoryUtility::GetChangeLog(const boost::function<void (const Dictionary::Ptr&, const String&)>& callback)
402 std::vector<String> changelog;
403 String path = GetRepositoryChangeLogPath() + "/";
405 Utility::Glob(path + "/*.change",
406 boost::bind(&RepositoryUtility::CollectChangeLog, _1, boost::ref(changelog)), GlobFile);
408 /* sort by timestamp ascending */
409 std::sort(changelog.begin(), changelog.end());
411 BOOST_FOREACH(const String& entry, changelog) {
412 String file = path + entry + ".change";
413 Dictionary::Ptr change = GetObjectFromRepositoryChangeLog(file);
416 << "Collecting entry " << entry << "\n";
419 callback(change, file);
425 void RepositoryUtility::CollectChangeLog(const String& change_file, std::vector<String>& changelog)
427 String file = Utility::BaseName(change_file);
428 boost::algorithm::replace_all(file, ".change", "");
431 << "Adding change file: '" << file << "'.";
433 changelog.push_back(file);
436 void RepositoryUtility::CollectChange(const Dictionary::Ptr& change, Array::Ptr& changes)
438 changes->Add(change);
442 * Commit Changelog entry
444 void RepositoryUtility::CommitChange(const Dictionary::Ptr& change, const String& path)
447 << "Got change " << change->Get("name");
449 String name = change->Get("name");
450 String type = change->Get("type");
451 String command = change->Get("command");
452 Dictionary::Ptr attrs;
454 if (change->Contains("attrs")) {
455 attrs = change->Get("attrs");
458 bool success = false;
460 if (command == "add") {
461 success = AddObjectInternal(name, type, attrs);
463 else if (command == "remove") {
464 success = RemoveObjectInternal(name, type, attrs);
468 Log(LogNotice, "cli")
469 << "Removing changelog file '" << path << "'.";
470 RemoveObjectFileInternal(path);
475 * Clear Changelog entry
477 void RepositoryUtility::ClearChange(const Dictionary::Ptr& change, const String& path)
480 << "Clearing change " << change->Get("name");
482 Log(LogInformation, "cli")
483 << "Removing changelog file '" << path << "'.";
485 RemoveObjectFileInternal(path);
489 * Print Changelog helpers
491 void RepositoryUtility::FormatChangelogEntry(std::ostream& fp, const Dictionary::Ptr& change)
496 if (change->Get("command") == "add")
498 if (change->Get("command") == "remove")
501 String type = change->Get("type");
502 boost::algorithm::to_lower(type);
503 Dictionary::Ptr attrs = change->Get("attrs");
505 fp << " " << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << type << ConsoleColorTag(Console_Normal) << " '";
506 fp << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << change->Get("name") << ConsoleColorTag(Console_Normal) << "'";
508 if (!attrs || attrs->GetLength() == 0) {
513 fp << " with attributes: \n";
515 BOOST_FOREACH(const Dictionary::Pair& kv, attrs) {
517 if (kv.first == "name")
520 fp << std::setw(4) << " " << ConsoleColorTag(Console_ForegroundGreen) << kv.first << ConsoleColorTag(Console_Normal) << " = ";
521 FormatValue(fp, kv.second);
527 * print helpers for configuration
528 * TODO: Move into a separate class
530 void RepositoryUtility::SerializeObject(std::ostream& fp, const String& name, const String& type, const Dictionary::Ptr& object)
532 fp << "object " << type << " \"" << name << "\" {\n";
539 if (object->Contains("import")) {
540 Array::Ptr imports = object->Get("import");
542 ObjectLock olock(imports);
543 BOOST_FOREACH(const String& import, imports) {
544 fp << "\t" << "import \"" << import << "\"\n";
548 BOOST_FOREACH(const Dictionary::Pair& kv, object) {
549 if (kv.first == "import" || kv.first == "name") {
552 fp << "\t" << kv.first << " = ";
553 FormatValue(fp, kv.second);
560 void RepositoryUtility::FormatValue(std::ostream& fp, const Value& val)
562 if (val.IsObjectType<Array>()) {
563 FormatArray(fp, val);
567 if (val.IsString()) {
568 fp << "\"" << Convert::ToString(val) << "\"";
572 fp << Convert::ToString(val);
575 void RepositoryUtility::FormatArray(std::ostream& fp, const Array::Ptr& arr)
582 ObjectLock olock(arr);
583 BOOST_FOREACH(const Value& value, arr) {
589 FormatValue(fp, value);