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 String file = Utility::BaseName(object);
137 boost::algorithm::replace_all(file, ".conf", "");
139 fp << ConsoleColorTag(Console_ForegroundMagenta | Console_Bold) << type << ConsoleColorTag(Console_Normal)
140 << " '" << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << file << ConsoleColorTag(Console_Normal) << "'";
142 String prefix = Utility::DirName(object);
144 if (type == "Service") {
145 std::vector<String> tokens;
146 boost::algorithm::split(tokens, prefix, boost::is_any_of("/"));
148 String host_name = tokens[tokens.size()-1];
149 fp << " (on " << ConsoleColorTag(Console_ForegroundMagenta | Console_Bold) << "Host" << ConsoleColorTag(Console_Normal)
150 << " '" << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << host_name << ConsoleColorTag(Console_Normal) << "')";
157 Dictionary::Ptr obj = GetObjectFromRepository(object); //TODO: config parser not implemented yet!
160 fp << JsonEncode(obj);
165 void RepositoryUtility::PrintChangeLog(std::ostream& fp)
167 Array::Ptr changelog = make_shared<Array>();
169 GetChangeLog(boost::bind(RepositoryUtility::CollectChange, _1, boost::ref(changelog)));
171 ObjectLock olock(changelog);
173 std::cout << "Changes to be committed:\n\n";
175 BOOST_FOREACH(const Value& entry, changelog) {
176 FormatChangelogEntry(std::cout, entry);
180 /* modify objects and write changelog */
181 bool RepositoryUtility::AddObject(const String& name, const String& type, const Dictionary::Ptr& attrs)
183 /* add a new changelog entry by timestamp */
184 String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(static_cast<long>(Utility::GetTime())) + "-" + SHA256(name) + ".change";
186 Dictionary::Ptr change = make_shared<Dictionary>();
188 change->Set("timestamp", Utility::GetTime());
189 change->Set("name", name);
190 change->Set("type", type);
191 change->Set("command", "add");
192 change->Set("attrs", attrs);
194 return WriteObjectToRepositoryChangeLog(path, change);
197 bool RepositoryUtility::RemoveObject(const String& name, const String& type, const Dictionary::Ptr& attrs)
199 /* add a new changelog entry by timestamp */
200 String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(static_cast<long>(Utility::GetTime())) + "-" + SHA256(name) + ".change";
202 Dictionary::Ptr change = make_shared<Dictionary>();
204 change->Set("timestamp", Utility::GetTime());
205 change->Set("name", name);
206 change->Set("type", type);
207 change->Set("command", "remove");
208 change->Set("attrs", attrs); //required for service->host_name
210 return WriteObjectToRepositoryChangeLog(path, change);
213 bool RepositoryUtility::SetObjectAttribute(const String& name, const String& type, const String& attr, const Value& val)
215 //TODO: Implement modification commands
219 bool RepositoryUtility::ClearChangeLog(void)
221 GetChangeLog(boost::bind(RepositoryUtility::ClearChange, _1, _2));
226 bool RepositoryUtility::ChangeLogHasPendingChanges(void)
228 Array::Ptr changelog = make_shared<Array>();
229 GetChangeLog(boost::bind(RepositoryUtility::CollectChange, _1, boost::ref(changelog)));
231 return changelog->GetLength() > 0;
234 /* commit changelog */
235 bool RepositoryUtility::CommitChangeLog(void)
237 GetChangeLog(boost::bind(RepositoryUtility::CommitChange, _1, _2));
242 /* write/read from changelog repository */
243 bool RepositoryUtility::WriteObjectToRepositoryChangeLog(const String& path, const Dictionary::Ptr& item)
245 Log(LogInformation, "cli", "Dumping changelog items to file '" + path + "'");
247 Utility::MkDirP(Utility::DirName(path), 0750);
249 String tempPath = path + ".tmp";
251 std::ofstream fp(tempPath.CStr(), std::ofstream::out | std::ostream::trunc);
252 fp << JsonEncode(item);
256 _unlink(path.CStr());
259 if (rename(tempPath.CStr(), path.CStr()) < 0) {
260 BOOST_THROW_EXCEPTION(posix_error()
261 << boost::errinfo_api_function("rename")
262 << boost::errinfo_errno(errno)
263 << boost::errinfo_file_name(tempPath));
269 Dictionary::Ptr RepositoryUtility::GetObjectFromRepositoryChangeLog(const String& filename)
272 fp.open(filename.CStr(), std::ifstream::in);
275 return Dictionary::Ptr();
277 String content((std::istreambuf_iterator<char>(fp)), std::istreambuf_iterator<char>());
281 return JsonDecode(content);
284 /* internal implementation when changes are committed */
285 bool RepositoryUtility::AddObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attrs)
287 String path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name + ".conf";
289 return WriteObjectToRepository(path, name, type, attrs);
292 bool RepositoryUtility::RemoveObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attrs)
294 String path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name + ".conf";
295 bool success = RemoveObjectFileInternal(path);
297 /* special treatment for hosts -> remove the services too */
298 if (type == "Host") {
299 path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name;
301 std::vector<String> files;
302 Utility::GlobRecursive(path, "*.conf",
303 boost::bind(&RepositoryUtility::CollectObjects, _1, boost::ref(files)), GlobFile);
305 BOOST_FOREACH(const String& file, files) {
306 RemoveObjectFileInternal(file);
319 bool RepositoryUtility::RemoveObjectFileInternal(const String& path)
321 if (!Utility::PathExists(path) ) {
322 Log(LogCritical, "cli", "Cannot remove '" + path + "'. Does not exist.");
326 if (unlink(path.CStr()) < 0) {
327 Log(LogCritical, "cli", "Cannot remove path '" + path +
328 "'. Failed with error code " + Convert::ToString(errno) + ", \"" + Utility::FormatErrorNumber(errno) + "\".");
335 bool RepositoryUtility::SetObjectAttributeInternal(const String& name, const String& type, const String& key, const Value& val, const Dictionary::Ptr& attrs)
338 String path = GetRepositoryObjectConfigPath(type, attrs) + "/" + name + ".conf";
340 Dictionary::Ptr obj = GetObjectFromRepository(path); //TODO
343 Log(LogCritical, "cli")
344 << "Can't get object " << name << " from repository.\n";
350 std::cout << "Writing object '" << name << "' to path '" << path << "'.\n";
352 //TODO: Create a patch file
353 if(!WriteObjectToRepository(path, name, type, obj)) {
354 Log(LogCritical, "cli")
355 << "Can't write object " << name << " to repository.\n";
362 bool RepositoryUtility::WriteObjectToRepository(const String& path, const String& name, const String& type, const Dictionary::Ptr& item)
364 Log(LogInformation, "cli")
365 << "Dumping config object '" << name << "' to file '" << path << "'";
367 Utility::MkDirP(Utility::DirName(path), 0755);
369 String tempPath = path + ".tmp";
371 std::ofstream fp(tempPath.CStr(), std::ofstream::out | std::ostream::trunc);
372 SerializeObject(fp, name, type, item);
377 _unlink(path.CStr());
380 if (rename(tempPath.CStr(), path.CStr()) < 0) {
381 BOOST_THROW_EXCEPTION(posix_error()
382 << boost::errinfo_api_function("rename")
383 << boost::errinfo_errno(errno)
384 << boost::errinfo_file_name(tempPath));
390 Dictionary::Ptr RepositoryUtility::GetObjectFromRepository(const String& filename)
392 //TODO: Parse existing configuration objects
393 return Dictionary::Ptr();
400 std::vector<String> RepositoryUtility::GetObjects(void)
402 std::vector<String> objects;
403 String path = GetRepositoryConfigPath();
405 Utility::GlobRecursive(path, "*.conf",
406 boost::bind(&RepositoryUtility::CollectObjects, _1, boost::ref(objects)), GlobFile);
411 void RepositoryUtility::CollectObjects(const String& object_file, std::vector<String>& objects)
414 << "Adding object: '" << object_file << "'.";
416 objects.push_back(object_file);
420 bool RepositoryUtility::GetChangeLog(const boost::function<void (const Dictionary::Ptr&, const String&)>& callback)
422 std::vector<String> changelog;
423 String path = GetRepositoryChangeLogPath() + "/";
425 Utility::Glob(path + "/*.change",
426 boost::bind(&RepositoryUtility::CollectChangeLog, _1, boost::ref(changelog)), GlobFile);
428 /* sort by timestamp ascending */
429 std::sort(changelog.begin(), changelog.end());
431 BOOST_FOREACH(const String& entry, changelog) {
432 String file = path + entry + ".change";
433 Dictionary::Ptr change = GetObjectFromRepositoryChangeLog(file);
436 << "Collecting entry " << entry << "\n";
439 callback(change, file);
445 void RepositoryUtility::CollectChangeLog(const String& change_file, std::vector<String>& changelog)
447 String file = Utility::BaseName(change_file);
448 boost::algorithm::replace_all(file, ".change", "");
451 << "Adding change file: '" << file << "'.";
453 changelog.push_back(file);
456 void RepositoryUtility::CollectChange(const Dictionary::Ptr& change, Array::Ptr& changes)
458 changes->Add(change);
462 * Commit Changelog entry
464 void RepositoryUtility::CommitChange(const Dictionary::Ptr& change, const String& path)
467 << "Got change " << change->Get("name");
469 String name = change->Get("name");
470 String type = change->Get("type");
471 String command = change->Get("command");
472 Dictionary::Ptr attrs;
474 if (change->Contains("attrs")) {
475 attrs = change->Get("attrs");
478 bool success = false;
480 if (command == "add") {
481 success = AddObjectInternal(name, type, attrs);
483 else if (command == "remove") {
484 success = RemoveObjectInternal(name, type, attrs);
488 Log(LogNotice, "cli")
489 << "Removing changelog file '" << path << "'.";
490 RemoveObjectFileInternal(path);
495 * Clear Changelog entry
497 void RepositoryUtility::ClearChange(const Dictionary::Ptr& change, const String& path)
500 << "Clearing change " << change->Get("name");
502 Log(LogInformation, "cli")
503 << "Removing changelog file '" << path << "'.";
505 RemoveObjectFileInternal(path);
509 * Print Changelog helpers
511 void RepositoryUtility::FormatChangelogEntry(std::ostream& fp, const Dictionary::Ptr& change)
516 if (change->Get("command") == "add")
518 if (change->Get("command") == "remove")
521 String type = change->Get("type");
522 boost::algorithm::to_lower(type);
523 Dictionary::Ptr attrs = change->Get("attrs");
525 fp << " " << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << type << ConsoleColorTag(Console_Normal) << " '";
526 fp << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << change->Get("name") << ConsoleColorTag(Console_Normal) << "'";
528 if (!attrs || attrs->GetLength() == 0) {
533 fp << " with attributes: \n";
535 BOOST_FOREACH(const Dictionary::Pair& kv, attrs) {
537 if (kv.first == "name")
540 fp << std::setw(4) << " " << ConsoleColorTag(Console_ForegroundGreen) << kv.first << ConsoleColorTag(Console_Normal) << " = ";
541 FormatValue(fp, kv.second);
547 * print helpers for configuration
548 * TODO: Move into a separate class
550 void RepositoryUtility::SerializeObject(std::ostream& fp, const String& name, const String& type, const Dictionary::Ptr& object)
552 fp << "object " << type << " \"" << name << "\" {\n";
559 if (object->Contains("import")) {
560 Array::Ptr imports = object->Get("import");
562 ObjectLock olock(imports);
563 BOOST_FOREACH(const String& import, imports) {
564 fp << "\t" << "import \"" << import << "\"\n";
568 BOOST_FOREACH(const Dictionary::Pair& kv, object) {
569 if (kv.first == "import" || kv.first == "name") {
572 fp << "\t" << kv.first << " = ";
573 FormatValue(fp, kv.second);
580 void RepositoryUtility::FormatValue(std::ostream& fp, const Value& val)
582 if (val.IsObjectType<Array>()) {
583 FormatArray(fp, val);
587 if (val.IsString()) {
588 fp << "\"" << Convert::ToString(val) << "\"";
592 fp << Convert::ToString(val);
595 void RepositoryUtility::FormatArray(std::ostream& fp, const Array::Ptr& arr)
602 ObjectLock olock(arr);
603 BOOST_FOREACH(const Value& value, arr) {
609 FormatValue(fp, value);