summaryrefslogtreecommitdiffstats
path: root/lib/cli/daemonutility.cpp
blob: 9e910f313d1460694432df1aaecc6d923c81b796 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "cli/daemonutility.hpp"
#include "base/configobject.hpp"
#include "base/exception.hpp"
#include "base/utility.hpp"
#include "base/logger.hpp"
#include "base/application.hpp"
#include "base/scriptglobal.hpp"
#include "config/configcompiler.hpp"
#include "config/configcompilercontext.hpp"
#include "config/configitembuilder.hpp"
#include "icinga/dependency.hpp"
#include <set>

using namespace icinga;

static bool ExecuteExpression(Expression *expression)
{
	if (!expression)
		return false;

	try {
		ScriptFrame frame(true);
		expression->Evaluate(frame);
	} catch (const std::exception& ex) {
		Log(LogCritical, "config", DiagnosticInformation(ex));
		return false;
	}

	return true;
}

static bool IncludeZoneDirRecursive(const String& path, const String& package, bool& success)
{
	String zoneName = Utility::BaseName(path);

	/* We don't have an activated zone object yet. We may forcefully guess from configitems
	 * to not include this specific synced zones directory.
	 */
	if(!ConfigItem::GetByTypeAndName(Type::GetByName("Zone"), zoneName)) {
		return false;
	}

	/* register this zone path for cluster config sync */
	ConfigCompiler::RegisterZoneDir("_etc", path, zoneName);

	std::vector<std::unique_ptr<Expression> > expressions;
	Utility::GlobRecursive(path, "*.conf", [&expressions, zoneName, package](const String& file) {
		ConfigCompiler::CollectIncludes(expressions, file, zoneName, package);
	}, GlobFile);

	DictExpression expr(std::move(expressions));
	if (!ExecuteExpression(&expr))
		success = false;

	return true;
}

static bool IncludeNonLocalZone(const String& zonePath, const String& package, bool& success)
{
	/* Note: This include function must not call RegisterZoneDir().
	 * We do not need to copy it for cluster config sync. */

	String zoneName = Utility::BaseName(zonePath);

	/* We don't have an activated zone object yet. We may forcefully guess from configitems
	 * to not include this specific synced zones directory.
	 */
	if(!ConfigItem::GetByTypeAndName(Type::GetByName("Zone"), zoneName)) {
		return false;
	}

	/* Check whether this node already has an authoritative config version
	 * from zones.d in etc or api package directory, or a local marker file)
	 */
	if (ConfigCompiler::HasZoneConfigAuthority(zoneName) || Utility::PathExists(zonePath + "/.authoritative")) {
		Log(LogNotice, "config")
			<< "Ignoring non local config include for zone '" << zoneName << "': We already have an authoritative copy included.";
		return true;
	}

	std::vector<std::unique_ptr<Expression> > expressions;
	Utility::GlobRecursive(zonePath, "*.conf", [&expressions, zoneName, package](const String& file) {
		ConfigCompiler::CollectIncludes(expressions, file, zoneName, package);
	}, GlobFile);

	DictExpression expr(std::move(expressions));
	if (!ExecuteExpression(&expr))
		success = false;

	return true;
}

static void IncludePackage(const String& packagePath, bool& success)
{
	/* Note: Package includes will register their zones
	 * for config sync inside their generated config. */
	String packageName = Utility::BaseName(packagePath);

	if (Utility::PathExists(packagePath + "/include.conf")) {
		std::unique_ptr<Expression> expr = ConfigCompiler::CompileFile(packagePath + "/include.conf",
			String(), packageName);

		if (!ExecuteExpression(&*expr))
			success = false;
	}
}

bool DaemonUtility::ValidateConfigFiles(const std::vector<std::string>& configs, const String& objectsFile)
{
	bool success;

	Namespace::Ptr systemNS = ScriptGlobal::Get("System");
	VERIFY(systemNS);

	Namespace::Ptr internalNS = ScriptGlobal::Get("Internal");
	VERIFY(internalNS);

	if (!objectsFile.IsEmpty())
		ConfigCompilerContext::GetInstance()->OpenObjectsFile(objectsFile);

	if (!configs.empty()) {
		for (const String& configPath : configs) {
			try {
				std::unique_ptr<Expression> expression = ConfigCompiler::CompileFile(configPath, String(), "_etc");
				success = ExecuteExpression(&*expression);
				if (!success)
					return false;
			} catch (const std::exception& ex) {
				Log(LogCritical, "cli", "Could not compile config files: " + DiagnosticInformation(ex, false));
				Application::Exit(1);
			}
		}
	}

	/* Load cluster config files from /etc/icinga2/zones.d.
	 * This should probably be in libremote but
	 * unfortunately moving it there is somewhat non-trivial. */
	success = true;

	/* Only load zone directory if we're not in staging validation. */
	if (!internalNS->Contains("ZonesStageVarDir")) {
		String zonesEtcDir = Configuration::ZonesDir;
		if (!zonesEtcDir.IsEmpty() && Utility::PathExists(zonesEtcDir)) {
			std::set<String> zoneEtcDirs;
			Utility::Glob(zonesEtcDir + "/*", [&zoneEtcDirs](const String& zoneEtcDir) { zoneEtcDirs.emplace(zoneEtcDir); }, GlobDirectory);

			bool hasSuccess = true;

			while (!zoneEtcDirs.empty() && hasSuccess) {
				hasSuccess = false;

				for (auto& zoneEtcDir : zoneEtcDirs) {
					if (IncludeZoneDirRecursive(zoneEtcDir, "_etc", success)) {
						zoneEtcDirs.erase(zoneEtcDir);
						hasSuccess = true;
						break;
					}
				}
			}

			for (auto& zoneEtcDir : zoneEtcDirs) {
				Log(LogWarning, "config")
					<< "Ignoring directory '" << zoneEtcDir << "' for unknown zone '" << Utility::BaseName(zoneEtcDir) << "'.";
			}
		}

		if (!success)
			return false;
	}

	/* Load package config files - they may contain additional zones which
	 * are authoritative on this node and are checked in HasZoneConfigAuthority(). */
	String packagesVarDir = Configuration::DataDir + "/api/packages";
	if (Utility::PathExists(packagesVarDir))
		Utility::Glob(packagesVarDir + "/*", [&success](const String& packagePath) { IncludePackage(packagePath, success); }, GlobDirectory);

	if (!success)
		return false;

	/* Load cluster synchronized configuration files. This can be overridden for staged sync validations. */
	String zonesVarDir = Configuration::DataDir + "/api/zones";

	/* Cluster config sync stage validation needs this. */
	if (internalNS->Contains("ZonesStageVarDir")) {
		zonesVarDir = internalNS->Get("ZonesStageVarDir");

		Log(LogNotice, "DaemonUtility")
			<< "Overriding zones var directory with '" << zonesVarDir << "' for cluster config sync staging.";
	}


	if (Utility::PathExists(zonesVarDir)) {
		std::set<String> zoneVarDirs;
		Utility::Glob(zonesVarDir + "/*", [&zoneVarDirs](const String& zoneVarDir) { zoneVarDirs.emplace(zoneVarDir); }, GlobDirectory);

		bool hasSuccess = true;

		while (!zoneVarDirs.empty() && hasSuccess) {
			hasSuccess = false;

			for (auto& zoneVarDir : zoneVarDirs) {
				if (IncludeNonLocalZone(zoneVarDir, "_cluster", success)) {
					zoneVarDirs.erase(zoneVarDir);
					hasSuccess = true;
					break;
				}
			}
		}

		for (auto& zoneEtcDir : zoneVarDirs) {
			Log(LogWarning, "config")
				<< "Ignoring directory '" << zoneEtcDir << "' for unknown zone '" << Utility::BaseName(zoneEtcDir) << "'.";
		}
	}

	if (!success)
		return false;

	/* This is initialized inside the IcingaApplication class. */
	Value vAppType;
	VERIFY(systemNS->Get("ApplicationType", &vAppType));

	Type::Ptr appType = Type::GetByName(vAppType);

	if (ConfigItem::GetItems(appType).empty()) {
		ConfigItemBuilder builder;
		builder.SetType(appType);
		builder.SetName("app");
		builder.AddExpression(new ImportDefaultTemplatesExpression());
		ConfigItem::Ptr item = builder.Compile();
		item->Register();
	}

	return true;
}

bool DaemonUtility::LoadConfigFiles(const std::vector<std::string>& configs,
	std::vector<ConfigItem::Ptr>& newItems,
	const String& objectsFile, const String& varsfile)
{
	ActivationScope ascope;

	if (!DaemonUtility::ValidateConfigFiles(configs, objectsFile)) {
		ConfigCompilerContext::GetInstance()->CancelObjectsFile();
		return false;
	}

	// After evaluating the top-level statements of the config files (happening in ValidateConfigFiles() above),
	// prevent further modification of the global scope. This allows for a faster execution of the following steps
	// as Freeze() disables locking as it's not necessary on a read-only data structure anymore.
	ScriptGlobal::GetGlobals()->Freeze();

	WorkQueue upq(25000, Configuration::Concurrency);
	upq.SetName("DaemonUtility::LoadConfigFiles");
	bool result = ConfigItem::CommitItems(ascope.GetContext(), upq, newItems);

	if (result) {
		try {
			Dependency::AssertNoCycles();
		} catch (...) {
			Log(LogCritical, "config")
				<< DiagnosticInformation(boost::current_exception(), false);

			result = false;
		}
	}

	if (!result) {
		ConfigCompilerContext::GetInstance()->CancelObjectsFile();
		return false;
	}

	try {
		ScriptGlobal::WriteToFile(varsfile);
	} catch (const std::exception& ex) {
		Log(LogCritical, "cli", "Could not write vars file: " + DiagnosticInformation(ex, false));
		Application::Exit(1);
	}

	ConfigCompilerContext::GetInstance()->FinishObjectsFile();

	return true;
}