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 "config/configcompilercontext.h"
21 #include "config/configcompiler.h"
22 #include "config/configitembuilder.h"
23 #include "base/application.h"
24 #include "base/logger.h"
25 #include "base/timer.h"
26 #include "base/utility.h"
27 #include "base/exception.h"
28 #include "base/convert.h"
29 #include "base/scriptvariable.h"
30 #include "base/context.h"
32 #include <boost/program_options.hpp>
33 #include <boost/tuple/tuple.hpp>
34 #include <boost/foreach.hpp>
37 # include <sys/types.h>
42 using namespace icinga;
43 namespace po = boost::program_options;
45 static po::variables_map g_AppParams;
48 SERVICE_STATUS l_SvcStatus;
49 SERVICE_STATUS_HANDLE l_SvcStatusHandle;
52 static String LoadAppType(const String& typeSpec)
56 Log(LogInformation, "icinga-app", "Loading application type: " + typeSpec);
58 index = typeSpec.FindFirstOf('/');
60 if (index == String::NPos)
63 String library = typeSpec.SubStr(0, index);
65 (void) Utility::LoadExtensionLibrary(library);
67 return typeSpec.SubStr(index + 1);
70 static bool LoadConfigFiles(const String& appType, ValidationType validate)
72 ConfigCompilerContext::GetInstance()->Reset();
74 if (g_AppParams.count("config") > 0) {
75 BOOST_FOREACH(const String& configPath, g_AppParams["config"].as<std::vector<std::string> >()) {
76 ConfigCompiler::CompileFile(configPath);
80 String name, fragment;
81 BOOST_FOREACH(boost::tie(name, fragment), ConfigFragmentRegistry::GetInstance()->GetItems()) {
82 ConfigCompiler::CompileText(name, fragment);
85 ConfigItemBuilder::Ptr builder = make_shared<ConfigItemBuilder>();
86 builder->SetType(appType);
87 builder->SetName("application");
88 ConfigItem::Ptr item = builder->Compile();
91 bool result = ConfigItem::ActivateItems(validate);
93 int warnings = 0, errors = 0;
95 BOOST_FOREACH(const ConfigCompilerMessage& message, ConfigCompilerContext::GetInstance()->GetMessages()) {
96 std::ostringstream locbuf;
97 ShowCodeFragment(locbuf, message.Location, true);
98 String location = locbuf.str();
102 if (!location.IsEmpty())
103 logmsg = "Location:\n" + location;
105 logmsg += String("\nConfig ") + (message.Error ? "error" : "warning") + ": " + message.Text;
108 Log(LogCritical, "config", logmsg);
111 Log(LogWarning, "config", logmsg);
116 if (warnings > 0 || errors > 0) {
117 LogSeverity severity;
120 severity = LogWarning;
122 severity = LogCritical;
124 Log(severity, "config", Convert::ToString(errors) + " errors, " + Convert::ToString(warnings) + " warnings.");
134 static void SigHupHandler(int)
136 Application::RequestRestart();
140 static bool Daemonize(const String& stderrFile)
151 int fdnull = open("/dev/null", O_RDWR);
163 const char *errPath = "/dev/null";
165 if (!stderrFile.IsEmpty())
166 errPath = stderrFile.CStr();
168 int fderr = open(errPath, O_WRONLY | O_APPEND);
170 if (fderr < 0 && errno == ENOENT)
171 fderr = open(errPath, O_CREAT | O_WRONLY | O_APPEND, 0600);
181 pid_t sid = setsid();
192 int argc = Application::GetArgC();
193 char **argv = Application::GetArgV();
195 Application::SetStartTime(Utility::GetTime());
197 Application::SetResourceLimits();
199 /* Set thread title. */
200 Utility::SetThreadName("Main Thread", false);
202 /* Install exception handlers to make debugging easier. */
203 Application::InstallExceptionHandlers();
205 Application::DeclarePrefixDir(ICINGA_PREFIX);
206 Application::DeclareSysconfDir(ICINGA_SYSCONFDIR);
207 Application::DeclareLocalStateDir(ICINGA_LOCALSTATEDIR);
208 Application::DeclarePkgDataDir(ICINGA_PKGDATADIR);
210 Application::DeclareApplicationType("icinga/IcingaApplication");
212 po::options_description desc("Supported options");
214 ("help", "show this help message")
215 ("version,V", "show version information")
216 ("library,l", po::value<std::vector<std::string> >(), "load a library")
217 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
218 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
219 ("config,c", po::value<std::vector<std::string> >(), "parse a configuration file")
220 ("no-config,z", "start without a configuration file")
221 ("validate,C", "exit after validating the configuration")
222 ("no-validate,Z", "skip validating the configuration")
223 ("debug,x", "enable debugging")
224 ("errorlog,e", po::value<std::string>(), "log fatal errors to the specified log file (only works in combination with --daemonize)")
226 ("daemonize,d", "detach from the controlling terminal")
227 ("user,u", po::value<std::string>(), "user to run Icinga as")
228 ("group,g", po::value<std::string>(), "group to run Icinga as")
230 ("scm", "run as a Windows service (must be the first argument if specified)")
231 ("scm-install", "installs Icinga 2 as a Windows service (must be the first argument if specified")
232 ("scm-uninstall", "uninstalls the Icinga 2 Windows service (must be the first argument if specified")
237 po::store(po::parse_command_line(argc, argv, desc), g_AppParams);
238 } catch (const std::exception& ex) {
239 std::ostringstream msgbuf;
240 msgbuf << "Error while parsing command-line options: " << ex.what();
241 Log(LogCritical, "icinga-app", msgbuf.str());
245 po::notify(g_AppParams);
247 if (g_AppParams.count("define")) {
248 BOOST_FOREACH(const String& define, g_AppParams["define"].as<std::vector<std::string> >()) {
250 size_t pos = define.FindFirstOf('=');
251 if (pos != String::NPos) {
252 key = define.SubStr(0, pos);
253 value = define.SubStr(pos + 1);
258 ScriptVariable::Set(key, value);
262 Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
263 Application::DeclarePidPath(Application::GetLocalStateDir() + "/run/icinga2/icinga2.pid");
266 if (g_AppParams.count("group")) {
267 String group = g_AppParams["group"].as<std::string>();
270 struct group *gr = getgrnam(group.CStr());
274 BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid group specified: " + group));
276 BOOST_THROW_EXCEPTION(posix_error()
277 << boost::errinfo_api_function("getgrnam")
278 << boost::errinfo_errno(errno));
282 if (setgid(gr->gr_gid) < 0) {
283 BOOST_THROW_EXCEPTION(posix_error()
284 << boost::errinfo_api_function("setgid")
285 << boost::errinfo_errno(errno));
289 if (g_AppParams.count("user")) {
290 String user = g_AppParams["user"].as<std::string>();
293 struct passwd *pw = getpwnam(user.CStr());
297 BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid user specified: " + user));
299 BOOST_THROW_EXCEPTION(posix_error()
300 << boost::errinfo_api_function("getpwnam")
301 << boost::errinfo_errno(errno));
305 if (setuid(pw->pw_uid) < 0) {
306 BOOST_THROW_EXCEPTION(posix_error()
307 << boost::errinfo_api_function("setuid")
308 << boost::errinfo_errno(errno));
313 if (g_AppParams.count("debug"))
314 Application::SetDebugging(true);
316 if (g_AppParams.count("help") || g_AppParams.count("version")) {
317 String appName = Utility::BaseName(argv[0]);
319 if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
320 appName = appName.SubStr(3, appName.GetLength() - 3);
322 std::cout << appName << " " << "- The Icinga 2 network monitoring daemon.";
324 if (g_AppParams.count("version")) {
325 std::cout << " (Version: " << Application::GetVersion() << ")";
326 std::cout << std::endl
327 << "Copyright (c) 2012-2014 Icinga Development Team (http://www.icinga.org)" << std::endl
328 << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
329 << "This is free software: you are free to change and redistribute it." << std::endl
330 << "There is NO WARRANTY, to the extent permitted by law.";
333 std::cout << std::endl;
335 if (g_AppParams.count("version"))
339 if (g_AppParams.count("help")) {
340 std::cout << std::endl
342 << "Report bugs at <https://dev.icinga.org/>" << std::endl
343 << "Icinga home page: <http://www.icinga.org/>" << std::endl;
347 ScriptVariable::Set("UseVfork", true, false, true);
349 Application::MakeVariablesConstant();
351 Log(LogInformation, "icinga-app", "Icinga application loader (version: " + Application::GetVersion() + ")");
353 String appType = LoadAppType(Application::GetApplicationType());
355 if (g_AppParams.count("library")) {
356 BOOST_FOREACH(const String& libraryName, g_AppParams["library"].as<std::vector<std::string> >()) {
357 (void)Utility::LoadExtensionLibrary(libraryName);
361 ConfigCompiler::AddIncludeSearchDir(Application::GetPkgDataDir());
363 if (g_AppParams.count("include")) {
364 BOOST_FOREACH(const String& includePath, g_AppParams["include"].as<std::vector<std::string> >()) {
365 ConfigCompiler::AddIncludeSearchDir(includePath);
369 if (g_AppParams.count("no-config") == 0 && g_AppParams.count("config") == 0) {
370 Log(LogCritical, "icinga-app", "You need to specify at least one config file (using the --config option).");
375 if (g_AppParams.count("daemonize")) {
378 if (g_AppParams.count("errorlog"))
379 errorLog = g_AppParams["errorlog"].as<std::string>();
382 Logger::DisableConsoleLog();
385 ValidationType validate = ValidateStart;
387 if (g_AppParams.count("validate"))
388 validate = ValidateOnly;
390 if (g_AppParams.count("no-validate"))
391 validate = ValidateNone;
393 if (!LoadConfigFiles(appType, validate))
396 if (validate == ValidateOnly) {
397 Log(LogInformation, "icinga-app", "Finished validating the configuration file(s).");
403 memset(&sa, 0, sizeof(sa));
404 sa.sa_handler = &SigHupHandler;
405 sigaction(SIGHUP, &sa, NULL);
408 int rc = Application::GetInstance()->Run();
411 _exit(rc); // Yay, our static destructors are pretty much beyond repair at this point.
418 static int SetupService(bool install, int argc, char **argv)
420 SC_HANDLE schSCManager;
421 SC_HANDLE schService;
422 TCHAR szPath[MAX_PATH * 5];
424 if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
425 printf("Cannot install service (%d)\n", GetLastError());
429 schSCManager = OpenSCManager(
432 SC_MANAGER_ALL_ACCESS);
434 if (NULL == schSCManager) {
435 printf("OpenSCManager failed (%d)\n", GetLastError());
439 strcat(szPath, " --scm");
441 for (int i = 0; i < argc; i++) {
442 strcat(szPath, " \"");
443 strcat(szPath, argv[i]);
444 strcat(szPath, "\"");
447 schService = OpenService(schSCManager, "icinga2", DELETE);
449 if (schService != NULL) {
450 if (!DeleteService(schService)) {
451 printf("DeleteService failed (%d)\n", GetLastError());
452 CloseServiceHandle(schService);
453 CloseServiceHandle(schSCManager);
458 printf("Service uninstalled successfully\n");
460 CloseServiceHandle(schService);
464 schService = CreateService(
469 SERVICE_WIN32_OWN_PROCESS,
470 SERVICE_DEMAND_START,
471 SERVICE_ERROR_NORMAL,
476 "NT AUTHORITY\\NetworkService",
479 if (schService == NULL) {
480 printf("CreateService failed (%d)\n", GetLastError());
481 CloseServiceHandle(schSCManager);
484 printf("Service installed successfully\n");
486 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
487 ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription);
489 CloseServiceHandle(schService);
492 CloseServiceHandle(schSCManager);
497 VOID ReportSvcStatus(DWORD dwCurrentState,
498 DWORD dwWin32ExitCode,
501 static DWORD dwCheckPoint = 1;
503 l_SvcStatus.dwCurrentState = dwCurrentState;
504 l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
505 l_SvcStatus.dwWaitHint = dwWaitHint;
507 if (dwCurrentState == SERVICE_START_PENDING)
508 l_SvcStatus.dwControlsAccepted = 0;
510 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
512 if ((dwCurrentState == SERVICE_RUNNING) ||
513 (dwCurrentState == SERVICE_STOPPED))
514 l_SvcStatus.dwCheckPoint = 0;
516 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
518 SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
521 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
523 if (dwCtrl == SERVICE_CONTROL_STOP) {
524 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
525 Application::RequestShutdown();
529 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
531 l_SvcStatusHandle = RegisterServiceCtrlHandler(
533 ServiceControlHandler);
535 l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
536 l_SvcStatus.dwServiceSpecificExitCode = 0;
538 ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
542 ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, rc);
547 * Entry point for the Icinga application.
549 * @params argc Number of command line arguments.
550 * @params argv Command line arguments.
551 * @returns The application's exit status.
553 int main(int argc, char **argv)
555 /* Set command-line arguments. */
556 Application::SetArgC(argc);
557 Application::SetArgV(argv);
560 if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
561 return SetupService(true, argc - 2, &argv[2]);
564 if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
565 return SetupService(false, argc - 2, &argv[2]);
568 if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
569 SERVICE_TABLE_ENTRY dispatchTable[] = {
570 { "icinga2", ServiceMain },
574 StartServiceCtrlDispatcher(dispatchTable);