1 /******************************************************************************
3 * Copyright (C) 2012-2015 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/clicommand.hpp"
21 #include "config/configcompilercontext.hpp"
22 #include "config/configcompiler.hpp"
23 #include "config/configitembuilder.hpp"
24 #include "base/application.hpp"
25 #include "base/logger.hpp"
26 #include "base/timer.hpp"
27 #include "base/utility.hpp"
28 #include "base/loader.hpp"
29 #include "base/exception.hpp"
30 #include "base/convert.hpp"
31 #include "base/scriptglobal.hpp"
32 #include "base/context.hpp"
33 #include "base/console.hpp"
35 #include <boost/program_options.hpp>
36 #include <boost/tuple/tuple.hpp>
37 #include <boost/foreach.hpp>
40 # include <sys/types.h>
45 using namespace icinga;
46 namespace po = boost::program_options;
49 SERVICE_STATUS l_SvcStatus;
50 SERVICE_STATUS_HANDLE l_SvcStatusHandle;
53 static std::vector<String> GetLogLevelCompletionSuggestions(const String& arg)
55 std::vector<String> result;
57 String debugLevel = "debug";
58 if (debugLevel.Find(arg) == 0)
59 result.push_back(debugLevel);
61 String noticeLevel = "notice";
62 if (noticeLevel.Find(arg) == 0)
63 result.push_back(noticeLevel);
65 String informationLevel = "information";
66 if (informationLevel.Find(arg) == 0)
67 result.push_back(informationLevel);
69 String warningLevel = "warning";
70 if (warningLevel.Find(arg) == 0)
71 result.push_back(warningLevel);
73 String criticalLevel = "critical";
74 if (criticalLevel.Find(arg) == 0)
75 result.push_back(criticalLevel);
80 static std::vector<String> GlobalArgumentCompletion(const String& argument, const String& word)
82 if (argument == "include")
83 return GetBashCompletionSuggestions("directory", word);
84 else if (argument == "log-level")
85 return GetLogLevelCompletionSuggestions(word);
87 return std::vector<String>();
92 int argc = Application::GetArgC();
93 char **argv = Application::GetArgV();
95 bool autocomplete = false;
98 if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
102 autoindex = Convert::ToLong(argv[2]);
103 } catch (const std::invalid_argument& ex) {
104 Log(LogCritical, "icinga-app")
105 << "Invalid index for --autocomplete: " << argv[2];
113 Application::SetStartTime(Utility::GetTime());
116 Application::SetResourceLimits();
118 /* Set thread title. */
119 Utility::SetThreadName("Main Thread", false);
121 /* Install exception handlers to make debugging easier. */
122 Application::InstallExceptionHandlers();
125 bool builtinPaths = true;
128 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Icinga Development Team\\ICINGA2", 0,
129 KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
130 BYTE pvData[MAX_PATH];
131 DWORD cbData = sizeof(pvData)-1;
133 if (RegQueryValueEx(hKey, NULL, NULL, &lType, pvData, &cbData) == ERROR_SUCCESS && lType == REG_SZ) {
134 pvData[cbData] = '\0';
136 String prefix = (char *)pvData;
137 Application::DeclarePrefixDir(prefix);
138 Application::DeclareSysconfDir(prefix + "\\etc");
139 Application::DeclareRunDir(prefix + "\\var\\run");
140 Application::DeclareLocalStateDir(prefix + "\\var");
141 Application::DeclarePkgDataDir(prefix + "\\share\\icinga2");
142 Application::DeclareIncludeConfDir(prefix + "\\share\\icinga2\\include");
144 builtinPaths = false;
151 Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");
154 Application::DeclarePrefixDir(ICINGA_PREFIX);
155 Application::DeclareSysconfDir(ICINGA_SYSCONFDIR);
156 Application::DeclareRunDir(ICINGA_RUNDIR);
157 Application::DeclareLocalStateDir(ICINGA_LOCALSTATEDIR);
158 Application::DeclarePkgDataDir(ICINGA_PKGDATADIR);
159 Application::DeclareIncludeConfDir(ICINGA_INCLUDECONFDIR);
164 Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
165 Application::DeclareRunAsUser(ICINGA_USER);
166 Application::DeclareRunAsGroup(ICINGA_GROUP);
167 Application::DeclareConcurrency(boost::thread::hardware_concurrency());
169 if (!ScriptGlobal::Exists("UseVfork"))
171 ScriptGlobal::Set("UseVfork", false);
172 #else /* __APPLE__ */
173 ScriptGlobal::Set("UseVfork", true);
174 #endif /* __APPLE__ */
176 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
177 Logger::SetConsoleLogSeverity(LogWarning);
179 Loader::LoadExtensionLibrary("cli");
181 po::options_description visibleDesc("Global options");
183 visibleDesc.add_options()
184 ("help,h", "show this help message")
185 ("version,V", "show version information")
187 ("color", "use VT100 color codes even when stdout is not a terminal")
189 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
190 ("app,a", po::value<std::string>(), "application library name (default: icinga)")
191 ("library,l", po::value<std::vector<std::string> >(), "load a library")
192 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
193 ("log-level,x", po::value<std::string>(), "specify the log level for the console log");
195 po::options_description hiddenDesc("Hidden options");
197 hiddenDesc.add_options()
199 ("no-stack-rlimit", "used internally, do not specify manually")
201 ("no-stack-rlimit", "used internally, do not specify manually")
203 ("arg", po::value<std::vector<std::string> >(), "positional argument");
205 po::positional_options_description positionalDesc;
206 positionalDesc.add("arg", -1);
209 CLICommand::Ptr command;
210 po::variables_map vm;
213 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
214 vm, cmdname, command, autocomplete);
215 } catch (const std::exception& ex) {
216 Log(LogCritical, "icinga-app")
217 << "Error while parsing command-line options: " << ex.what();
221 String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
223 if (Utility::PathExists(initconfig)) {
224 Expression *expression;
226 expression = ConfigCompiler::CompileFile(initconfig);
229 expression->Evaluate(frame);
230 } catch (const std::exception& ex) {
233 Log(LogCritical, "config", DiagnosticInformation(ex));
241 if (vm.count("color")) {
242 Console::SetType(std::cout, Console_VT100);
243 Console::SetType(std::cerr, Console_VT100);
247 if (vm.count("define")) {
248 BOOST_FOREACH(const String& define, vm["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 ScriptGlobal::Set(key, value);
262 Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
263 Application::DeclareObjectsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.debug");
264 Application::DeclareVarsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.vars");
265 Application::DeclarePidPath(Application::GetRunDir() + "/icinga2/icinga2.pid");
267 ConfigCompiler::AddIncludeSearchDir(Application::GetIncludeConfDir());
269 if (!autocomplete && vm.count("include")) {
270 BOOST_FOREACH(const String& includePath, vm["include"].as<std::vector<std::string> >()) {
271 ConfigCompiler::AddIncludeSearchDir(includePath);
276 Logger::SetConsoleLogSeverity(logLevel);
278 if (vm.count("log-level")) {
279 String severity = vm["log-level"].as<std::string>();
281 LogSeverity logLevel = LogInformation;
283 logLevel = Logger::StringToSeverity(severity);
284 } catch (std::exception&) {
285 /* Inform user and exit */
286 Log(LogCritical, "icinga-app", "Invalid log level set. Default is 'information'.");
290 Logger::SetConsoleLogSeverity(logLevel);
293 if (vm.count("library")) {
294 BOOST_FOREACH(const String& libraryName, vm["library"].as<std::vector<std::string> >()) {
296 (void) Loader::LoadExtensionLibrary(libraryName);
297 } catch (const std::exception& ex) {
298 Log(LogCritical, "icinga-app")
299 << "Could not load library \"" << libraryName << "\": " << DiagnosticInformation(ex);
305 if (!command || vm.count("help") || vm.count("version")) {
309 appName = Utility::BaseName(Application::GetArgV()[0]);
310 } catch (const std::bad_alloc&) {
311 Log(LogCritical, "icinga-app", "Allocation failed.");
315 if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
316 appName = appName.SubStr(3, appName.GetLength() - 3);
318 std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
319 << ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal)
320 << Application::GetVersion()
323 #endif /* I2_DEBUG */
324 << ConsoleColorTag(Console_Normal)
325 << ")" << std::endl << std::endl;
327 if ((!command || vm.count("help")) && !vm.count("version")) {
328 std::cout << "Usage:" << std::endl
329 << " " << argv[0] << " ";
331 if (cmdname.IsEmpty())
332 std::cout << "<command>";
334 std::cout << cmdname;
336 std::cout << " [<arguments>]" << std::endl;
339 std::cout << std::endl
340 << command->GetDescription() << std::endl;
344 if (vm.count("version")) {
345 std::cout << "Copyright (c) 2012-2015 Icinga Development Team (https://www.icinga.org)" << std::endl
346 << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
347 << "This is free software: you are free to change and redistribute it." << std::endl
348 << "There is NO WARRANTY, to the extent permitted by law.";
351 std::cout << std::endl;
353 if (vm.count("version")) {
354 std::cout << std::endl;
356 Application::DisplayInfoMessage(std::cout, true);
362 if (!command || vm.count("help")) {
364 CLICommand::ShowCommands(argc, argv, NULL);
366 std::cout << visibleDesc << std::endl
367 << "Report bugs at <https://dev.icinga.org/>" << std::endl
368 << "Icinga home page: <https://www.icinga.org/>" << std::endl;
376 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
377 &GlobalArgumentCompletion, true, autoindex);
379 } else if (command) {
380 Logger::DisableTimestamp(true);
382 if (command->GetImpersonationLevel() == ImpersonateRoot) {
384 Log(LogCritical, "cli", "This command must be run as root.");
387 } else if (command && command->GetImpersonationLevel() == ImpersonateIcinga) {
388 String group = Application::GetRunAsGroup();
389 String user = Application::GetRunAsUser();
392 struct group *gr = getgrnam(group.CStr());
396 Log(LogCritical, "cli")
397 << "Invalid group specified: " << group;
400 Log(LogCritical, "cli")
401 << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
406 if (getgid() != gr->gr_gid) {
407 if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) {
408 Log(LogCritical, "cli")
409 << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
410 Log(LogCritical, "cli")
411 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
415 if (setgid(gr->gr_gid) < 0) {
416 Log(LogCritical, "cli")
417 << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
423 struct passwd *pw = getpwnam(user.CStr());
427 Log(LogCritical, "cli")
428 << "Invalid user specified: " << user;
431 Log(LogCritical, "cli")
432 << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
437 // also activate the additional groups the configured user is member of
438 if (getuid() != pw->pw_uid) {
439 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
440 Log(LogCritical, "cli")
441 << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
442 Log(LogCritical, "cli")
443 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
447 if (setuid(pw->pw_uid) < 0) {
448 Log(LogCritical, "cli")
449 << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
450 Log(LogCritical, "cli")
451 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
458 std::vector<std::string> args;
460 args = vm["arg"].as<std::vector<std::string> >();
462 if (args.size() < command->GetMinArguments()) {
463 Log(LogCritical, "cli")
464 << "Too few arguments. Command needs at least " << command->GetMinArguments()
465 << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
469 if (command->GetMaxArguments() >= 0 && args.size() > command->GetMaxArguments()) {
470 Log(LogCritical, "cli")
471 << "Too many arguments. At most " << command->GetMaxArguments()
472 << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
476 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
477 Logger::SetConsoleLogSeverity(LogWarning);
480 Loader::LoadExtensionLibrary(vm["app"].as<std::string>());
482 Loader::LoadExtensionLibrary("icinga");
484 Logger::SetConsoleLogSeverity(logLevel);
486 rc = command->Run(vm, args);
493 static int SetupService(bool install, int argc, char **argv)
495 SC_HANDLE schSCManager = OpenSCManager(
498 SC_MANAGER_ALL_ACCESS);
500 if (NULL == schSCManager) {
501 printf("OpenSCManager failed (%d)\n", GetLastError());
505 TCHAR szPath[MAX_PATH];
507 if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
508 printf("Cannot install service (%d)\n", GetLastError());
513 szArgs = Utility::EscapeShellArg(szPath) + " --scm";
515 for (int i = 0; i < argc; i++)
516 szArgs += " " + Utility::EscapeShellArg(argv[i]);
518 SC_HANDLE schService = OpenService(schSCManager, "icinga2", DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
520 if (schService != NULL) {
521 SERVICE_STATUS status;
522 ControlService(schService, SERVICE_CONTROL_STOP, &status);
524 double start = Utility::GetTime();
525 while (status.dwCurrentState != SERVICE_STOPPED) {
526 double end = Utility::GetTime();
528 if (end - start > 30) {
529 printf("Could not stop the service.\n");
535 if (!QueryServiceStatus(schService, &status)) {
536 printf("QueryServiceStatus failed (%d)\n", GetLastError());
541 if (!DeleteService(schService)) {
542 printf("DeleteService failed (%d)\n", GetLastError());
543 CloseServiceHandle(schService);
544 CloseServiceHandle(schSCManager);
549 printf("Service uninstalled successfully\n");
551 CloseServiceHandle(schService);
555 schService = CreateService(
560 SERVICE_WIN32_OWN_PROCESS,
561 SERVICE_DEMAND_START,
562 SERVICE_ERROR_NORMAL,
567 "NT AUTHORITY\\NetworkService",
570 if (schService == NULL) {
571 printf("CreateService failed (%d)\n", GetLastError());
572 CloseServiceHandle(schSCManager);
575 printf("Service installed successfully\n");
577 ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
578 SERVICE_ERROR_NORMAL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
580 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
581 ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription);
583 if (!StartService(schService, 0, NULL)) {
584 printf("StartService failed (%d)\n", GetLastError());
585 CloseServiceHandle(schService);
586 CloseServiceHandle(schSCManager);
590 CloseServiceHandle(schService);
593 CloseServiceHandle(schSCManager);
598 VOID ReportSvcStatus(DWORD dwCurrentState,
599 DWORD dwWin32ExitCode,
602 static DWORD dwCheckPoint = 1;
604 l_SvcStatus.dwCurrentState = dwCurrentState;
605 l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
606 l_SvcStatus.dwWaitHint = dwWaitHint;
608 if (dwCurrentState == SERVICE_START_PENDING)
609 l_SvcStatus.dwControlsAccepted = 0;
611 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
613 if ((dwCurrentState == SERVICE_RUNNING) ||
614 (dwCurrentState == SERVICE_STOPPED))
615 l_SvcStatus.dwCheckPoint = 0;
617 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
619 SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
622 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
624 if (dwCtrl == SERVICE_CONTROL_STOP) {
625 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
626 Application::RequestShutdown();
630 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
632 l_SvcStatusHandle = RegisterServiceCtrlHandler(
634 ServiceControlHandler);
636 l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
637 l_SvcStatus.dwServiceSpecificExitCode = 0;
639 ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
643 ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, rc);
645 Application::Exit(rc);
650 * Entry point for the Icinga application.
652 * @params argc Number of command line arguments.
653 * @params argv Command line arguments.
654 * @returns The application's exit status.
656 int main(int argc, char **argv)
660 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0) {
661 rlim_t maxfds = rl.rlim_max;
663 if (maxfds == RLIM_INFINITY)
666 for (rlim_t i = 3; i < maxfds; i++) {
671 std::cerr << "Closed FD " << i << " which we inherited from our parent process." << std::endl;
672 #endif /* I2_DEBUG */
677 /* must be called before using any other libbase functions */
678 Application::InitializeBase();
680 /* Set command-line arguments. */
681 Application::SetArgC(argc);
682 Application::SetArgV(argv);
685 if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
686 return SetupService(true, argc - 2, &argv[2]);
689 if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
690 return SetupService(false, argc - 2, &argv[2]);
693 if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
694 SERVICE_TABLE_ENTRY dispatchTable[] = {
695 { "icinga2", ServiceMain },
699 StartServiceCtrlDispatcher(dispatchTable);
700 Application::Exit(EXIT_FAILURE);
706 Application::Exit(rc);