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/stdiostream.hpp"
28 #include "base/debug.hpp"
29 #include "base/objectlock.hpp"
30 #include "base/console.hpp"
31 #include <boost/foreach.hpp>
32 #include <boost/algorithm/string/join.hpp>
33 #include <boost/algorithm/string/replace.hpp>
34 #include <boost/algorithm/string/split.hpp>
35 #include <boost/algorithm/string/classification.hpp>
36 #include <boost/algorithm/string/case_conv.hpp>
37 #include <boost/regex.hpp>
41 using namespace icinga;
43 Dictionary::Ptr RepositoryUtility::GetArgumentAttributes(const std::vector<std::string>& arguments)
45 Dictionary::Ptr attrs = make_shared<Dictionary>();
47 BOOST_FOREACH(const String& kv, arguments) {
48 std::vector<String> tokens;
49 boost::algorithm::split(tokens, kv, boost::is_any_of("="));
51 if (tokens.size() != 2) {
52 Log(LogWarning, "cli")
53 << "Cannot parse passed attributes: " << boost::algorithm::join(tokens, "=");
60 value = Convert::ToDouble(tokens[1]);
65 attrs->Set(tokens[0], value);
71 String RepositoryUtility::GetRepositoryConfigPath(void)
73 return Application::GetSysconfDir() + "/icinga2/repository.d";
76 String RepositoryUtility::GetRepositoryObjectConfigPath(const String& type, const Dictionary::Ptr& object)
78 String path = GetRepositoryConfigPath() + "/";
82 else if (type == "Service")
83 path += "hosts/" + object->Get("host_name");
84 else if (type == "Zone")
86 else if (type == "Endpoints")
92 bool RepositoryUtility::FilterRepositoryObjects(const String& type, const String& path)
95 boost::regex expr("hosts/[^/]*.conf", boost::regex::icase);
97 return boost::regex_search(path.GetData(), what, expr);
99 else if (type == "Service")
100 return Utility::Match("*hosts/*/*.conf", path);
101 else if (type == "Zone")
102 return Utility::Match("*zones/*.conf", path);
103 else if (type == "Endpoints")
104 return Utility::Match("*endpoints/*.conf", path);
109 String RepositoryUtility::GetRepositoryObjectConfigFilePath(const String& type, const Dictionary::Ptr& object)
111 String path = GetRepositoryObjectConfigPath(type, object);
113 path += "/" + object->Get("name") + ".conf";
118 String RepositoryUtility::GetRepositoryChangeLogPath(void)
120 return Application::GetLocalStateDir() + "/lib/icinga2/repository/changes";
124 void RepositoryUtility::PrintObjects(std::ostream& fp, const String& type)
126 std::vector<String> objects = GetObjects(); //full path
128 BOOST_FOREACH(const String& object, objects) {
129 if (!FilterRepositoryObjects(type, object)) {
131 << "Ignoring object '" << object << "'. Type '" << type << "' does not match.";
135 fp << "Object Path: " << object << "\n";
137 Dictionary::Ptr obj = GetObjectFromRepository(object); //TODO: config parser not implemented yet!
140 fp << JsonEncode(obj);
144 void RepositoryUtility::PrintChangeLog(std::ostream& fp)
146 Array::Ptr changelog = make_shared<Array>();
148 GetChangeLog(boost::bind(RepositoryUtility::CollectChange, _1, boost::ref(changelog)));
150 ObjectLock olock(changelog);
152 std::cout << "Changes to be committed:\n\n";
154 BOOST_FOREACH(const Value& entry, changelog) {
155 FormatChangelogEntry(std::cout, entry);
159 /* modify objects and write changelog */
160 bool RepositoryUtility::AddObject(const String& name, const String& type, const Dictionary::Ptr& attr)
162 /* add a new changelog entry by timestamp */
163 String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(static_cast<long>(Utility::GetTime())) + ".change";
165 Dictionary::Ptr change = make_shared<Dictionary>();
167 change->Set("timestamp", Utility::GetTime());
168 change->Set("name", name);
169 change->Set("type", type);
170 change->Set("command", "add");
171 change->Set("attr", attr);
173 return WriteObjectToRepositoryChangeLog(path, change);
176 bool RepositoryUtility::RemoveObject(const String& name, const String& type, const Dictionary::Ptr& attr)
178 /* add a new changelog entry by timestamp */
179 String path = GetRepositoryChangeLogPath() + "/" + Convert::ToString(static_cast<long>(Utility::GetTime())) + ".change";
181 Dictionary::Ptr change = make_shared<Dictionary>();
183 change->Set("timestamp", Utility::GetTime());
184 change->Set("name", name);
185 change->Set("type", type);
186 change->Set("command", "remove");
187 change->Set("attr", attr); //required for service->host_name
189 return WriteObjectToRepositoryChangeLog(path, change);
192 bool RepositoryUtility::SetObjectAttribute(const String& name, const String& type, const String& attr, const Value& val)
194 //TODO: Implement modification commands
198 /* commit changelog */
199 bool RepositoryUtility::CommitChangeLog(void)
201 GetChangeLog(boost::bind(RepositoryUtility::CommitChange, _1, _2));
206 /* write/read from changelog repository */
207 bool RepositoryUtility::WriteObjectToRepositoryChangeLog(const String& path, const Dictionary::Ptr& item)
209 Log(LogInformation, "cli", "Dumping changelog items to file '" + path + "'");
211 Utility::MkDirP(Utility::DirName(path), 0750);
213 String tempPath = path + ".tmp";
215 std::ofstream fp(tempPath.CStr(), std::ofstream::out | std::ostream::trunc);
216 fp << JsonEncode(item);
220 _unlink(path.CStr());
223 if (rename(tempPath.CStr(), path.CStr()) < 0) {
224 BOOST_THROW_EXCEPTION(posix_error()
225 << boost::errinfo_api_function("rename")
226 << boost::errinfo_errno(errno)
227 << boost::errinfo_file_name(tempPath));
233 Dictionary::Ptr RepositoryUtility::GetObjectFromRepositoryChangeLog(const String& filename)
236 fp.open(filename.CStr(), std::ifstream::in);
239 return Dictionary::Ptr();
241 String content((std::istreambuf_iterator<char>(fp)), std::istreambuf_iterator<char>());
245 return JsonDecode(content);
248 /* internal implementation when changes are committed */
249 bool RepositoryUtility::AddObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attr)
251 String path = GetRepositoryObjectConfigPath(type, attr) + "/" + name + ".conf";
253 return WriteObjectToRepository(path, name, type, attr);
256 bool RepositoryUtility::RemoveObjectInternal(const String& name, const String& type, const Dictionary::Ptr& attr)
258 String path = GetRepositoryObjectConfigPath(type, attr) + "/" + name + ".conf";
260 return RemoveObjectFileInternal(path);
263 bool RepositoryUtility::RemoveObjectFileInternal(const String& path)
265 if (!Utility::PathExists(path) ) {
266 Log(LogCritical, "cli", "Cannot remove '" + path + "'. Does not exist.");
270 if (unlink(path.CStr()) < 0) {
271 Log(LogCritical, "cli", "Cannot remove file '" + path +
272 "'. Failed with error code " + Convert::ToString(errno) + ", \"" + Utility::FormatErrorNumber(errno) + "\".");
279 bool RepositoryUtility::SetObjectAttributeInternal(const String& name, const String& type, const String& key, const Value& val, const Dictionary::Ptr& attr)
282 String path = GetRepositoryObjectConfigPath(type, attr) + "/" + name + ".conf";
284 Dictionary::Ptr obj = GetObjectFromRepository(path); //TODO
287 Log(LogCritical, "cli")
288 << "Can't get object " << name << " from repository.\n";
294 std::cout << "Writing object '" << name << "' to path '" << path << "'.\n";
296 //TODO: Create a patch file
297 if(!WriteObjectToRepository(path, name, type, obj)) {
298 Log(LogCritical, "cli")
299 << "Can't write object " << name << " to repository.\n";
306 bool RepositoryUtility::WriteObjectToRepository(const String& path, const String& name, const String& type, const Dictionary::Ptr& item)
308 Log(LogInformation, "cli", "Dumping config items to file '" + path + "'");
310 Utility::MkDirP(Utility::DirName(path), 0755);
312 String tempPath = path + ".tmp";
314 std::ofstream fp(tempPath.CStr(), std::ofstream::out | std::ostream::trunc);
315 SerializeObject(fp, name, type, item);
320 _unlink(path.CStr());
323 if (rename(tempPath.CStr(), path.CStr()) < 0) {
324 BOOST_THROW_EXCEPTION(posix_error()
325 << boost::errinfo_api_function("rename")
326 << boost::errinfo_errno(errno)
327 << boost::errinfo_file_name(tempPath));
333 Dictionary::Ptr RepositoryUtility::GetObjectFromRepository(const String& filename)
335 //TODO: Parse existing configuration objects
336 return Dictionary::Ptr();
343 std::vector<String> RepositoryUtility::GetObjects(void)
345 std::vector<String> objects;
346 String path = GetRepositoryConfigPath();
348 Utility::GlobRecursive(path, "*.conf",
349 boost::bind(&RepositoryUtility::CollectObjects, _1, boost::ref(objects)), GlobFile);
354 void RepositoryUtility::CollectObjects(const String& object_file, std::vector<String>& objects)
357 << "Adding object: '" << object_file << "'.";
359 objects.push_back(object_file);
363 bool RepositoryUtility::GetChangeLog(const boost::function<void (const Dictionary::Ptr&, const String&)>& callback)
365 std::vector<String> changelog;
366 String path = GetRepositoryChangeLogPath() + "/";
368 Utility::Glob(path + "/*.change",
369 boost::bind(&RepositoryUtility::CollectChangeLog, _1, boost::ref(changelog)), GlobFile);
371 /* sort by timestamp ascending */
372 std::sort(changelog.begin(), changelog.end());
374 BOOST_FOREACH(const String& entry, changelog) {
375 String file = path + entry + ".change";
376 Dictionary::Ptr change = GetObjectFromRepositoryChangeLog(file);
379 << "Collecting entry " << entry << "\n";
382 callback(change, file);
388 void RepositoryUtility::CollectChangeLog(const String& change_file, std::vector<String>& changelog)
390 String file = Utility::BaseName(change_file);
391 boost::algorithm::replace_all(file, ".change", "");
393 Log(LogDebug, "cli", "Adding change file: " + file);
394 changelog.push_back(file);
397 void RepositoryUtility::CollectChange(const Dictionary::Ptr& change, Array::Ptr& changes)
399 changes->Add(change);
405 void RepositoryUtility::CommitChange(const Dictionary::Ptr& change, const String& path)
408 << "Got change " << change->Get("name");
410 String name = change->Get("name");
411 String type = change->Get("type");
412 String command = change->Get("command");
413 Dictionary::Ptr attr;
415 if (change->Contains("attr")) {
416 attr = change->Get("attr");
419 bool success = false;
421 if (command == "add") {
422 success = AddObjectInternal(name, type, attr);
424 else if (command == "remove") {
425 success = RemoveObjectInternal(name, type, attr);
429 Log(LogNotice, "cli")
430 << "Removing changelog file '" << path << "'.";
431 RemoveObjectFileInternal(path);
436 * Print Changelog helpers
438 void RepositoryUtility::FormatChangelogEntry(std::ostream& fp, const Dictionary::Ptr& change)
443 if (change->Get("command") == "add")
445 if (change->Get("command") == "remove")
448 String type = change->Get("type");
449 boost::algorithm::to_lower(type);
450 Dictionary::Ptr attrs = change->Get("attr");
452 fp << " " << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << type << ConsoleColorTag(Console_Normal) << " '";
453 fp << ConsoleColorTag(Console_ForegroundBlue | Console_Bold) << change->Get("name") << ConsoleColorTag(Console_Normal) << "'";
455 if (!attrs || attrs->GetLength() == 0) {
460 fp << " with attributes: \n";
462 BOOST_FOREACH(const Dictionary::Pair& kv, attrs) {
464 if (kv.first == "name")
467 fp << std::setw(4) << " " << ConsoleColorTag(Console_ForegroundGreen) << kv.first << ConsoleColorTag(Console_Normal) << " = ";
468 FormatValue(fp, kv.second);
474 * print helpers for configuration
475 * TODO: Move into a separate class
477 void RepositoryUtility::SerializeObject(std::ostream& fp, const String& name, const String& type, const Dictionary::Ptr& object)
479 fp << "object " << type << " \"" << name << "\" {\n";
486 if (object->Contains("import")) {
487 Array::Ptr imports = object->Get("import");
489 ObjectLock olock(imports);
490 BOOST_FOREACH(const String& import, imports) {
491 fp << "\t" << "import \"" << import << "\"\n";
495 BOOST_FOREACH(const Dictionary::Pair& kv, object) {
496 if (kv.first == "import" || kv.first == "name") {
499 fp << "\t" << kv.first << " = ";
500 FormatValue(fp, kv.second);
507 void RepositoryUtility::FormatValue(std::ostream& fp, const Value& val)
509 if (val.IsObjectType<Array>()) {
510 FormatArray(fp, val);
514 if (val.IsString()) {
515 fp << "\"" << Convert::ToString(val) << "\"";
519 fp << Convert::ToString(val);
522 void RepositoryUtility::FormatArray(std::ostream& fp, const Array::Ptr& arr)
529 ObjectLock olock(arr);
530 BOOST_FOREACH(const Value& value, arr) {
536 FormatValue(fp, value);