1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "remote/apilistener.hpp"
4 #include "remote/apifunction.hpp"
5 #include "config/configcompiler.hpp"
6 #include "base/configtype.hpp"
7 #include "base/logger.hpp"
8 #include "base/convert.hpp"
9 #include "base/exception.hpp"
13 using namespace icinga;
15 REGISTER_APIFUNCTION(Update, config, &ApiListener::ConfigUpdateHandler);
17 void ApiListener::ConfigGlobHandler(ConfigDirInformation& config, const String& path, const String& file)
19 CONTEXT("Creating config update for file '" + file + "'");
21 Log(LogNotice, "ApiListener")
22 << "Creating config update for file '" << file << "'.";
24 std::ifstream fp(file.CStr(), std::ifstream::binary);
28 String content((std::istreambuf_iterator<char>(fp)), std::istreambuf_iterator<char>());
30 Dictionary::Ptr update;
32 if (Utility::Match("*.conf", file))
33 update = config.UpdateV1;
35 update = config.UpdateV2;
37 update->Set(file.SubStr(path.GetLength()), content);
40 Dictionary::Ptr ApiListener::MergeConfigUpdate(const ConfigDirInformation& config)
42 Dictionary::Ptr result = new Dictionary();
45 config.UpdateV1->CopyTo(result);
48 config.UpdateV2->CopyTo(result);
53 ConfigDirInformation ApiListener::LoadConfigDir(const String& dir)
55 ConfigDirInformation config;
56 config.UpdateV1 = new Dictionary();
57 config.UpdateV2 = new Dictionary();
58 Utility::GlobRecursive(dir, "*", std::bind(&ApiListener::ConfigGlobHandler, std::ref(config), dir, _1), GlobFile);
62 bool ApiListener::UpdateConfigDir(const ConfigDirInformation& oldConfigInfo, const ConfigDirInformation& newConfigInfo, const String& configDir, bool authoritative)
64 bool configChange = false;
66 Dictionary::Ptr oldConfig = MergeConfigUpdate(oldConfigInfo);
67 Dictionary::Ptr newConfig = MergeConfigUpdate(newConfigInfo);
71 if (!oldConfig->Contains("/.timestamp"))
74 oldTimestamp = oldConfig->Get("/.timestamp");
78 if (!newConfig->Contains("/.timestamp"))
79 newTimestamp = Utility::GetTime();
81 newTimestamp = newConfig->Get("/.timestamp");
83 /* skip update if our configuration files are more recent */
84 if (oldTimestamp >= newTimestamp) {
85 Log(LogNotice, "ApiListener")
86 << "Our configuration is more recent than the received configuration update."
87 << " Ignoring configuration file update for path '" << configDir << "'. Current timestamp '"
88 << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", oldTimestamp) << "' ("
89 << std::fixed << std::setprecision(6) << oldTimestamp
90 << ") >= received timestamp '"
91 << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", newTimestamp) << "' ("
92 << newTimestamp << ").";
99 ObjectLock olock(newConfig);
100 for (const Dictionary::Pair& kv : newConfig) {
101 if (oldConfig->Get(kv.first) != kv.second) {
102 if (!Utility::Match("*/.timestamp", kv.first))
105 String path = configDir + "/" + kv.first;
106 Log(LogInformation, "ApiListener")
107 << "Updating configuration file: " << path;
109 /* Sync string content only. */
110 String content = kv.second;
112 /* Generate a directory tree (zones/1/2/3 might not exist yet). */
113 Utility::MkDirP(Utility::DirName(path), 0755);
114 std::ofstream fp(path.CStr(), std::ofstream::out | std::ostream::binary | std::ostream::trunc);
118 numBytes += content.GetLength();
123 Log(LogInformation, "ApiListener")
124 << "Applying configuration file update for path '" << configDir << "' (" << numBytes << " Bytes). Received timestamp '"
125 << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", newTimestamp) << "' ("
126 << std::fixed << std::setprecision(6) << newTimestamp
127 << "), Current timestamp '"
128 << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", oldTimestamp) << "' ("
129 << oldTimestamp << ").";
131 ObjectLock xlock(oldConfig);
132 for (const Dictionary::Pair& kv : oldConfig) {
133 if (!newConfig->Contains(kv.first)) {
136 String path = configDir + "/" + kv.first;
137 (void) unlink(path.CStr());
141 String tsPath = configDir + "/.timestamp";
142 if (!Utility::PathExists(tsPath)) {
143 std::ofstream fp(tsPath.CStr(), std::ofstream::out | std::ostream::trunc);
144 fp << std::fixed << newTimestamp;
149 String authPath = configDir + "/.authoritative";
150 if (!Utility::PathExists(authPath)) {
151 std::ofstream fp(authPath.CStr(), std::ofstream::out | std::ostream::trunc);
159 void ApiListener::SyncZoneDir(const Zone::Ptr& zone) const
161 ConfigDirInformation newConfigInfo;
162 newConfigInfo.UpdateV1 = new Dictionary();
163 newConfigInfo.UpdateV2 = new Dictionary();
165 for (const ZoneFragment& zf : ConfigCompiler::GetZoneDirs(zone->GetName())) {
166 ConfigDirInformation newConfigPart = LoadConfigDir(zf.Path);
169 ObjectLock olock(newConfigPart.UpdateV1);
170 for (const Dictionary::Pair& kv : newConfigPart.UpdateV1) {
171 newConfigInfo.UpdateV1->Set("/" + zf.Tag + kv.first, kv.second);
176 ObjectLock olock(newConfigPart.UpdateV2);
177 for (const Dictionary::Pair& kv : newConfigPart.UpdateV2) {
178 newConfigInfo.UpdateV2->Set("/" + zf.Tag + kv.first, kv.second);
183 int sumUpdates = newConfigInfo.UpdateV1->GetLength() + newConfigInfo.UpdateV2->GetLength();
188 String oldDir = Configuration::DataDir + "/api/zones/" + zone->GetName();
190 Log(LogInformation, "ApiListener")
191 << "Copying " << sumUpdates << " zone configuration files for zone '" << zone->GetName() << "' to '" << oldDir << "'.";
193 Utility::MkDirP(oldDir, 0700);
195 ConfigDirInformation oldConfigInfo = LoadConfigDir(oldDir);
197 UpdateConfigDir(oldConfigInfo, newConfigInfo, oldDir, true);
200 void ApiListener::SyncZoneDirs() const
202 for (const Zone::Ptr& zone : ConfigType::GetObjectsByType<Zone>()) {
205 } catch (const std::exception&) {
211 void ApiListener::SendConfigUpdate(const JsonRpcConnection::Ptr& aclient)
213 Endpoint::Ptr endpoint = aclient->GetEndpoint();
216 Zone::Ptr azone = endpoint->GetZone();
217 Zone::Ptr lzone = Zone::GetLocalZone();
219 /* don't try to send config updates to our master */
220 if (!azone->IsChildOf(lzone))
223 Dictionary::Ptr configUpdateV1 = new Dictionary();
224 Dictionary::Ptr configUpdateV2 = new Dictionary();
226 String zonesDir = Configuration::DataDir + "/api/zones";
228 for (const Zone::Ptr& zone : ConfigType::GetObjectsByType<Zone>()) {
229 String zoneDir = zonesDir + "/" + zone->GetName();
231 if (!zone->IsChildOf(azone) && !zone->IsGlobal())
234 if (!Utility::PathExists(zoneDir))
237 Log(LogInformation, "ApiListener")
238 << "Syncing configuration files for " << (zone->IsGlobal() ? "global " : "")
239 << "zone '" << zone->GetName() << "' to endpoint '" << endpoint->GetName() << "'.";
241 ConfigDirInformation config = LoadConfigDir(zonesDir + "/" + zone->GetName());
242 configUpdateV1->Set(zone->GetName(), config.UpdateV1);
243 configUpdateV2->Set(zone->GetName(), config.UpdateV2);
246 Dictionary::Ptr message = new Dictionary({
247 { "jsonrpc", "2.0" },
248 { "method", "config::Update" },
249 { "params", new Dictionary({
250 { "update", configUpdateV1 },
251 { "update_v2", configUpdateV2 }
255 aclient->SendMessage(message);
258 Value ApiListener::ConfigUpdateHandler(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params)
260 if (!origin->FromClient->GetEndpoint() || (origin->FromZone && !Zone::GetLocalZone()->IsChildOf(origin->FromZone)))
263 ApiListener::Ptr listener = ApiListener::GetInstance();
266 Log(LogCritical, "ApiListener", "No instance available.");
270 if (!listener->GetAcceptConfig()) {
271 Log(LogWarning, "ApiListener")
272 << "Ignoring config update. '" << listener->GetName() << "' does not accept config.";
276 Log(LogInformation, "ApiListener")
277 << "Applying config update from endpoint '" << origin->FromClient->GetEndpoint()->GetName()
278 << "' of zone '" << GetFromZoneName(origin->FromZone) << "'.";
280 Dictionary::Ptr updateV1 = params->Get("update");
281 Dictionary::Ptr updateV2 = params->Get("update_v2");
283 bool configChange = false;
285 ObjectLock olock(updateV1);
286 for (const Dictionary::Pair& kv : updateV1) {
287 Zone::Ptr zone = Zone::GetByName(kv.first);
290 Log(LogWarning, "ApiListener")
291 << "Ignoring config update for unknown zone '" << kv.first << "'.";
295 if (ConfigCompiler::HasZoneConfigAuthority(kv.first)) {
296 Log(LogWarning, "ApiListener")
297 << "Ignoring config update for zone '" << kv.first << "' because we have an authoritative version of the zone's config.";
301 String oldDir = Configuration::DataDir + "/api/zones/" + zone->GetName();
303 Utility::MkDirP(oldDir, 0700);
305 ConfigDirInformation newConfigInfo;
306 newConfigInfo.UpdateV1 = kv.second;
309 newConfigInfo.UpdateV2 = updateV2->Get(kv.first);
311 Dictionary::Ptr newConfig = kv.second;
312 ConfigDirInformation oldConfigInfo = LoadConfigDir(oldDir);
314 if (UpdateConfigDir(oldConfigInfo, newConfigInfo, oldDir, false))
319 Log(LogInformation, "ApiListener", "Restarting after configuration change.");
320 Application::RequestRestart();