1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "config/configcompiler.hpp"
4 #include "config/configitem.hpp"
5 #include "base/logger.hpp"
6 #include "base/utility.hpp"
7 #include "base/loader.hpp"
8 #include "base/context.hpp"
9 #include "base/exception.hpp"
12 using namespace icinga;
14 std::vector<String> ConfigCompiler::m_IncludeSearchDirs;
15 boost::mutex ConfigCompiler::m_ZoneDirsMutex;
16 std::map<String, std::vector<ZoneFragment> > ConfigCompiler::m_ZoneDirs;
19 * Constructor for the ConfigCompiler class.
21 * @param path The path of the configuration file (or another name that
22 * identifies the source of the configuration text).
23 * @param input Input stream for the configuration file.
24 * @param zone The zone.
26 ConfigCompiler::ConfigCompiler(String path, std::istream *input,
27 String zone, String package)
28 : m_Path(std::move(path)), m_Input(input), m_Zone(std::move(zone)),
29 m_Package(std::move(package)), m_Eof(false), m_OpenBraces(0)
35 * Destructor for the ConfigCompiler class.
37 ConfigCompiler::~ConfigCompiler()
43 * Reads data from the input stream. Used internally by the lexer.
45 * @param buffer Where to store data.
46 * @param max_size The maximum number of bytes to read from the stream.
47 * @returns The actual number of bytes read.
49 size_t ConfigCompiler::ReadInput(char *buffer, size_t max_size)
51 m_Input->read(buffer, max_size);
52 return static_cast<size_t>(m_Input->gcount());
56 * Retrieves the scanner object.
58 * @returns The scanner object.
60 void *ConfigCompiler::GetScanner() const
66 * Retrieves the path for the input file.
70 const char *ConfigCompiler::GetPath() const
75 void ConfigCompiler::SetZone(const String& zone)
80 String ConfigCompiler::GetZone() const
85 void ConfigCompiler::SetPackage(const String& package)
90 String ConfigCompiler::GetPackage() const
95 void ConfigCompiler::CollectIncludes(std::vector<std::unique_ptr<Expression> >& expressions,
96 const String& file, const String& zone, const String& package)
99 expressions.emplace_back(CompileFile(file, zone, package));
100 } catch (const std::exception& ex) {
101 Log(LogWarning, "ConfigCompiler")
102 << "Cannot compile file '"
103 << file << "': " << DiagnosticInformation(ex);
108 * Handles an include directive.
110 * @param relativeBath The path this include is relative to.
111 * @param path The path from the include directive.
112 * @param search Whether to search global include dirs.
113 * @param debuginfo Debug information.
115 std::unique_ptr<Expression> ConfigCompiler::HandleInclude(const String& relativeBase, const String& path,
116 bool search, const String& zone, const String& package, const DebugInfo& debuginfo)
120 if (search || (IsAbsolutePath(path)))
123 upath = relativeBase + "/" + path;
125 String includePath = upath;
128 for (const String& dir : m_IncludeSearchDirs) {
129 String spath = dir + "/" + path;
131 if (Utility::PathExists(spath)) {
138 std::vector<std::unique_ptr<Expression> > expressions;
140 if (!Utility::Glob(includePath, std::bind(&ConfigCompiler::CollectIncludes, std::ref(expressions), _1, zone, package), GlobFile) && includePath.FindFirstOf("*?") == String::NPos) {
141 std::ostringstream msgbuf;
142 msgbuf << "Include file '" + path + "' does not exist";
143 BOOST_THROW_EXCEPTION(ScriptError(msgbuf.str(), debuginfo));
146 std::unique_ptr<DictExpression> expr{new DictExpression(std::move(expressions))};
148 return std::move(expr);
152 * Handles recursive includes.
154 * @param relativeBase The path this include is relative to.
155 * @param path The directory path.
156 * @param pattern The file pattern.
157 * @param debuginfo Debug information.
159 std::unique_ptr<Expression> ConfigCompiler::HandleIncludeRecursive(const String& relativeBase, const String& path,
160 const String& pattern, const String& zone, const String& package, const DebugInfo&)
164 if (IsAbsolutePath(path))
167 ppath = relativeBase + "/" + path;
169 std::vector<std::unique_ptr<Expression> > expressions;
170 Utility::GlobRecursive(ppath, pattern, std::bind(&ConfigCompiler::CollectIncludes, std::ref(expressions), _1, zone, package), GlobFile);
172 std::unique_ptr<DictExpression> dict{new DictExpression(std::move(expressions))};
174 return std::move(dict);
177 void ConfigCompiler::HandleIncludeZone(const String& relativeBase, const String& tag, const String& path, const String& pattern, const String& package, std::vector<std::unique_ptr<Expression> >& expressions)
179 String zoneName = Utility::BaseName(path);
183 if (IsAbsolutePath(path))
186 ppath = relativeBase + "/" + path;
188 RegisterZoneDir(tag, ppath, zoneName);
190 Utility::GlobRecursive(ppath, pattern, std::bind(&ConfigCompiler::CollectIncludes, std::ref(expressions), _1, zoneName, package), GlobFile);
194 * Handles zone includes.
196 * @param relativeBase The path this include is relative to.
197 * @param tag The tag name.
198 * @param path The directory path.
199 * @param pattern The file pattern.
200 * @param debuginfo Debug information.
202 std::unique_ptr<Expression> ConfigCompiler::HandleIncludeZones(const String& relativeBase, const String& tag,
203 const String& path, const String& pattern, const String& package, const DebugInfo&)
206 String newRelativeBase = relativeBase;
208 if (IsAbsolutePath(path))
211 ppath = relativeBase + "/" + path;
212 newRelativeBase = ".";
215 std::vector<std::unique_ptr<Expression> > expressions;
216 Utility::Glob(ppath + "/*", std::bind(&ConfigCompiler::HandleIncludeZone, newRelativeBase, tag, _1, pattern, package, std::ref(expressions)), GlobDirectory);
217 return std::unique_ptr<Expression>(new DictExpression(std::move(expressions)));
223 * @param path A name identifying the stream.
224 * @param stream The input stream.
225 * @returns Configuration items.
227 std::unique_ptr<Expression> ConfigCompiler::CompileStream(const String& path,
228 std::istream *stream, const String& zone, const String& package)
230 CONTEXT("Compiling configuration stream with name '" + path + "'");
232 stream->exceptions(std::istream::badbit);
234 ConfigCompiler ctx(path, stream, zone, package);
237 return ctx.Compile();
238 } catch (const ScriptError& ex) {
239 return std::unique_ptr<Expression>(new ThrowExpression(MakeLiteral(ex.what()), ex.IsIncompleteExpression(), ex.GetDebugInfo()));
240 } catch (const std::exception& ex) {
241 return std::unique_ptr<Expression>(new ThrowExpression(MakeLiteral(DiagnosticInformation(ex)), false));
248 * @param path The path.
249 * @returns Configuration items.
251 std::unique_ptr<Expression> ConfigCompiler::CompileFile(const String& path, const String& zone,
252 const String& package)
254 CONTEXT("Compiling configuration file '" + path + "'");
256 std::ifstream stream(path.CStr(), std::ifstream::in);
259 BOOST_THROW_EXCEPTION(posix_error()
260 << boost::errinfo_api_function("std::ifstream::open")
261 << boost::errinfo_errno(errno)
262 << boost::errinfo_file_name(path));
264 Log(LogNotice, "ConfigCompiler")
265 << "Compiling config file: " << path;
267 return CompileStream(path, &stream, zone, package);
271 * Compiles a snippet of text.
273 * @param path A name identifying the text.
274 * @param text The text.
275 * @returns Configuration items.
277 std::unique_ptr<Expression> ConfigCompiler::CompileText(const String& path, const String& text,
278 const String& zone, const String& package)
280 std::stringstream stream(text);
281 return CompileStream(path, &stream, zone, package);
285 * Adds a directory to the list of include search dirs.
287 * @param dir The new dir.
289 void ConfigCompiler::AddIncludeSearchDir(const String& dir)
291 Log(LogInformation, "ConfigCompiler")
292 << "Adding include search dir: " << dir;
294 m_IncludeSearchDirs.push_back(dir);
297 std::vector<ZoneFragment> ConfigCompiler::GetZoneDirs(const String& zone)
299 boost::mutex::scoped_lock lock(m_ZoneDirsMutex);
300 auto it = m_ZoneDirs.find(zone);
301 if (it == m_ZoneDirs.end())
302 return std::vector<ZoneFragment>();
307 void ConfigCompiler::RegisterZoneDir(const String& tag, const String& ppath, const String& zoneName)
313 boost::mutex::scoped_lock lock(m_ZoneDirsMutex);
314 m_ZoneDirs[zoneName].push_back(zf);
317 bool ConfigCompiler::HasZoneConfigAuthority(const String& zoneName)
319 std::vector<ZoneFragment> zoneDirs = m_ZoneDirs[zoneName];
321 bool empty = zoneDirs.empty();
324 std::vector<String> paths;
325 paths.reserve(zoneDirs.size());
327 for (const ZoneFragment& zf : zoneDirs) {
328 paths.push_back(zf.Path);
331 Log(LogNotice, "ConfigCompiler")
332 << "Registered authoritative config directories for zone '" << zoneName << "': " << Utility::NaturalJoin(paths);
339 bool ConfigCompiler::IsAbsolutePath(const String& path)
342 return (path.GetLength() > 0 && path[0] == '/');
344 return !PathIsRelative(path.CStr());
348 void ConfigCompiler::AddImport(const std::shared_ptr<Expression>& import)
350 m_Imports.push_back(import);
353 std::vector<std::shared_ptr<Expression> > ConfigCompiler::GetImports() const