1 /******************************************************************************
3 * Copyright (C) 2012-2016 Icinga Development Team (https://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 static SERVICE_STATUS l_SvcStatus;
50 static SERVICE_STATUS_HANDLE l_SvcStatusHandle;
54 static std::vector<String> GetLogLevelCompletionSuggestions(const String& arg)
56 std::vector<String> result;
58 String debugLevel = "debug";
59 if (debugLevel.Find(arg) == 0)
60 result.push_back(debugLevel);
62 String noticeLevel = "notice";
63 if (noticeLevel.Find(arg) == 0)
64 result.push_back(noticeLevel);
66 String informationLevel = "information";
67 if (informationLevel.Find(arg) == 0)
68 result.push_back(informationLevel);
70 String warningLevel = "warning";
71 if (warningLevel.Find(arg) == 0)
72 result.push_back(warningLevel);
74 String criticalLevel = "critical";
75 if (criticalLevel.Find(arg) == 0)
76 result.push_back(criticalLevel);
81 static std::vector<String> GlobalArgumentCompletion(const String& argument, const String& word)
83 if (argument == "include")
84 return GetBashCompletionSuggestions("directory", word);
85 else if (argument == "log-level")
86 return GetLogLevelCompletionSuggestions(word);
88 return std::vector<String>();
93 int argc = Application::GetArgC();
94 char **argv = Application::GetArgV();
96 bool autocomplete = false;
99 if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
103 autoindex = Convert::ToLong(argv[2]);
104 } catch (const std::invalid_argument& ex) {
105 Log(LogCritical, "icinga-app")
106 << "Invalid index for --autocomplete: " << argv[2];
114 Application::SetStartTime(Utility::GetTime());
117 Application::SetResourceLimits();
119 /* Set thread title. */
120 Utility::SetThreadName("Main Thread", false);
122 /* Install exception handlers to make debugging easier. */
123 Application::InstallExceptionHandlers();
126 bool builtinPaths = true;
128 String binaryPrefix = Utility::GetIcingaInstallPath();
129 String dataPrefix = Utility::GetIcingaDataPath();
131 if (!binaryPrefix.IsEmpty() && !dataPrefix.IsEmpty()) {
132 Application::DeclarePrefixDir(binaryPrefix);
133 Application::DeclareSysconfDir(dataPrefix + "\\etc");
134 Application::DeclareRunDir(dataPrefix + "\\var\\run");
135 Application::DeclareLocalStateDir(dataPrefix + "\\var");
136 Application::DeclarePkgDataDir(binaryPrefix + "\\share\\icinga2");
137 Application::DeclareIncludeConfDir(binaryPrefix + "\\share\\icinga2\\include");
139 Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");
142 Application::DeclarePrefixDir(ICINGA_PREFIX);
143 Application::DeclareSysconfDir(ICINGA_SYSCONFDIR);
144 Application::DeclareRunDir(ICINGA_RUNDIR);
145 Application::DeclareLocalStateDir(ICINGA_LOCALSTATEDIR);
146 Application::DeclarePkgDataDir(ICINGA_PKGDATADIR);
147 Application::DeclareIncludeConfDir(ICINGA_INCLUDECONFDIR);
152 Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
153 Application::DeclareRunAsUser(ICINGA_USER);
154 Application::DeclareRunAsGroup(ICINGA_GROUP);
155 Application::DeclareConcurrency(boost::thread::hardware_concurrency());
157 if (!ScriptGlobal::Exists("UseVfork"))
159 ScriptGlobal::Set("UseVfork", false);
160 #else /* __APPLE__ */
161 ScriptGlobal::Set("UseVfork", true);
162 #endif /* __APPLE__ */
164 ScriptGlobal::Set("AttachDebugger", false);
166 ScriptGlobal::Set("PlatformKernel", Utility::GetPlatformKernel());
167 ScriptGlobal::Set("PlatformKernelVersion", Utility::GetPlatformKernelVersion());
168 ScriptGlobal::Set("PlatformName", Utility::GetPlatformName());
169 ScriptGlobal::Set("PlatformVersion", Utility::GetPlatformVersion());
170 ScriptGlobal::Set("PlatformArchitecture", Utility::GetPlatformArchitecture());
172 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
173 Logger::SetConsoleLogSeverity(LogWarning);
175 Loader::LoadExtensionLibrary("cli");
177 po::options_description visibleDesc("Global options");
179 visibleDesc.add_options()
180 ("help,h", "show this help message")
181 ("version,V", "show version information")
183 ("color", "use VT100 color codes even when stdout is not a terminal")
185 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
186 ("app,a", po::value<std::string>(), "application library name (default: icinga)")
187 ("library,l", po::value<std::vector<std::string> >(), "load a library")
188 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
189 ("log-level,x", po::value<std::string>(), "specify the log level for the console log.\n"
190 "The valid value is either debug, notice, information (default), warning, or critical")
191 ("script-debugger,X", "whether to enable the script debugger");
193 po::options_description hiddenDesc("Hidden options");
195 hiddenDesc.add_options()
196 ("no-stack-rlimit", "used internally, do not specify manually")
197 ("arg", po::value<std::vector<std::string> >(), "positional argument");
199 po::positional_options_description positionalDesc;
200 positionalDesc.add("arg", -1);
203 CLICommand::Ptr command;
204 po::variables_map vm;
207 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
208 vm, cmdname, command, autocomplete);
209 } catch (const std::exception& ex) {
210 Log(LogCritical, "icinga-app")
211 << "Error while parsing command-line options: " << ex.what();
215 String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
217 if (Utility::PathExists(initconfig)) {
218 Expression *expression;
220 expression = ConfigCompiler::CompileFile(initconfig);
223 expression->Evaluate(frame);
224 } catch (const std::exception& ex) {
227 Log(LogCritical, "config", DiagnosticInformation(ex));
235 if (vm.count("color")) {
236 Console::SetType(std::cout, Console_VT100);
237 Console::SetType(std::cerr, Console_VT100);
241 if (vm.count("define")) {
242 BOOST_FOREACH(const String& define, vm["define"].as<std::vector<std::string> >()) {
244 size_t pos = define.FindFirstOf('=');
245 if (pos != String::NPos) {
246 key = define.SubStr(0, pos);
247 value = define.SubStr(pos + 1);
252 ScriptGlobal::Set(key, value);
256 if (vm.count("script-debugger"))
257 Application::SetScriptDebuggerEnabled(true);
259 Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
260 Application::DeclareModAttrPath(Application::GetLocalStateDir() + "/lib/icinga2/modified-attributes.conf");
261 Application::DeclareObjectsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.debug");
262 Application::DeclareVarsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.vars");
263 Application::DeclarePidPath(Application::GetRunDir() + "/icinga2/icinga2.pid");
265 ConfigCompiler::AddIncludeSearchDir(Application::GetIncludeConfDir());
267 if (!autocomplete && vm.count("include")) {
268 BOOST_FOREACH(const String& includePath, vm["include"].as<std::vector<std::string> >()) {
269 ConfigCompiler::AddIncludeSearchDir(includePath);
274 Logger::SetConsoleLogSeverity(logLevel);
276 if (vm.count("log-level")) {
277 String severity = vm["log-level"].as<std::string>();
279 LogSeverity logLevel = LogInformation;
281 logLevel = Logger::StringToSeverity(severity);
282 } catch (std::exception&) {
283 /* Inform user and exit */
284 Log(LogCritical, "icinga-app", "Invalid log level set. Default is 'information'.");
288 Logger::SetConsoleLogSeverity(logLevel);
291 if (vm.count("library")) {
292 BOOST_FOREACH(const String& libraryName, vm["library"].as<std::vector<std::string> >()) {
294 (void) Loader::LoadExtensionLibrary(libraryName);
295 } catch (const std::exception& ex) {
296 Log(LogCritical, "icinga-app")
297 << "Could not load library \"" << libraryName << "\": " << DiagnosticInformation(ex);
303 if (!command || vm.count("help") || vm.count("version")) {
307 appName = Utility::BaseName(Application::GetArgV()[0]);
308 } catch (const std::bad_alloc&) {
309 Log(LogCritical, "icinga-app", "Allocation failed.");
313 if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
314 appName = appName.SubStr(3, appName.GetLength() - 3);
316 std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
317 << ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal)
318 << Application::GetAppVersion()
321 #endif /* I2_DEBUG */
322 << ConsoleColorTag(Console_Normal)
323 << ")" << std::endl << std::endl;
325 if ((!command || vm.count("help")) && !vm.count("version")) {
326 std::cout << "Usage:" << std::endl
327 << " " << argv[0] << " ";
329 if (cmdname.IsEmpty())
330 std::cout << "<command>";
332 std::cout << cmdname;
334 std::cout << " [<arguments>]" << std::endl;
337 std::cout << std::endl
338 << command->GetDescription() << std::endl;
342 if (vm.count("version")) {
343 std::cout << "Copyright (c) 2012-2016 Icinga Development Team (https://www.icinga.org/)" << std::endl
344 << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
345 << "This is free software: you are free to change and redistribute it." << std::endl
346 << "There is NO WARRANTY, to the extent permitted by law.";
349 std::cout << std::endl;
351 if (vm.count("version")) {
352 std::cout << std::endl;
354 Application::DisplayInfoMessage(std::cout, true);
360 if (!command || vm.count("help")) {
362 CLICommand::ShowCommands(argc, argv, NULL);
364 std::cout << visibleDesc << std::endl
365 << "Report bugs at <https://dev.icinga.org/>" << std::endl
366 << "Icinga home page: <https://www.icinga.org/>" << std::endl;
374 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
375 &GlobalArgumentCompletion, true, autoindex);
377 } else if (command) {
378 Logger::DisableTimestamp(true);
380 if (command->GetImpersonationLevel() == ImpersonateRoot) {
382 Log(LogCritical, "cli", "This command must be run as root.");
385 } else if (command && command->GetImpersonationLevel() == ImpersonateIcinga) {
386 String group = Application::GetRunAsGroup();
387 String user = Application::GetRunAsUser();
390 struct group *gr = getgrnam(group.CStr());
394 Log(LogCritical, "cli")
395 << "Invalid group specified: " << group;
398 Log(LogCritical, "cli")
399 << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
404 if (getgid() != gr->gr_gid) {
405 if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) {
406 Log(LogCritical, "cli")
407 << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
408 Log(LogCritical, "cli")
409 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
413 if (setgid(gr->gr_gid) < 0) {
414 Log(LogCritical, "cli")
415 << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
421 struct passwd *pw = getpwnam(user.CStr());
425 Log(LogCritical, "cli")
426 << "Invalid user specified: " << user;
429 Log(LogCritical, "cli")
430 << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
435 // also activate the additional groups the configured user is member of
436 if (getuid() != pw->pw_uid) {
437 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
438 Log(LogCritical, "cli")
439 << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
440 Log(LogCritical, "cli")
441 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
445 if (setuid(pw->pw_uid) < 0) {
446 Log(LogCritical, "cli")
447 << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
448 Log(LogCritical, "cli")
449 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
456 std::vector<std::string> args;
458 args = vm["arg"].as<std::vector<std::string> >();
460 if (args.size() < command->GetMinArguments()) {
461 Log(LogCritical, "cli")
462 << "Too few arguments. Command needs at least " << command->GetMinArguments()
463 << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
467 if (command->GetMaxArguments() >= 0 && args.size() > command->GetMaxArguments()) {
468 Log(LogCritical, "cli")
469 << "Too many arguments. At most " << command->GetMaxArguments()
470 << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
474 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
475 Logger::SetConsoleLogSeverity(LogWarning);
478 Loader::LoadExtensionLibrary(vm["app"].as<std::string>());
480 Loader::LoadExtensionLibrary("icinga");
482 Logger::SetConsoleLogSeverity(logLevel);
484 rc = command->Run(vm, args);
491 static int SetupService(bool install, int argc, char **argv)
493 SC_HANDLE schSCManager = OpenSCManager(
496 SC_MANAGER_ALL_ACCESS);
498 if (NULL == schSCManager) {
499 printf("OpenSCManager failed (%d)\n", GetLastError());
503 TCHAR szPath[MAX_PATH];
505 if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
506 printf("Cannot install service (%d)\n", GetLastError());
511 szArgs = Utility::EscapeShellArg(szPath) + " --scm";
513 for (int i = 0; i < argc; i++)
514 szArgs += " " + Utility::EscapeShellArg(argv[i]);
516 SC_HANDLE schService = OpenService(schSCManager, "icinga2", SERVICE_ALL_ACCESS);
518 if (schService != NULL) {
519 SERVICE_STATUS status;
520 ControlService(schService, SERVICE_CONTROL_STOP, &status);
522 double start = Utility::GetTime();
523 while (status.dwCurrentState != SERVICE_STOPPED) {
524 double end = Utility::GetTime();
526 if (end - start > 30) {
527 printf("Could not stop the service.\n");
533 if (!QueryServiceStatus(schService, &status)) {
534 printf("QueryServiceStatus failed (%d)\n", GetLastError());
538 } else if (install) {
539 schService = CreateService(
544 SERVICE_WIN32_OWN_PROCESS,
545 SERVICE_DEMAND_START,
546 SERVICE_ERROR_NORMAL,
551 "NT AUTHORITY\\NetworkService",
554 if (schService == NULL) {
555 printf("CreateService failed (%d)\n", GetLastError());
556 CloseServiceHandle(schSCManager);
560 printf("Service isn't installed.\n");
561 CloseServiceHandle(schSCManager);
566 if (!DeleteService(schService)) {
567 printf("DeleteService failed (%d)\n", GetLastError());
568 CloseServiceHandle(schService);
569 CloseServiceHandle(schSCManager);
573 printf("Service uninstalled successfully\n");
575 ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
576 SERVICE_ERROR_NORMAL, szArgs.CStr(), NULL, NULL, NULL, NULL, NULL, NULL);
578 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
579 ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription);
581 if (!StartService(schService, 0, NULL)) {
582 printf("StartService failed (%d)\n", GetLastError());
583 CloseServiceHandle(schService);
584 CloseServiceHandle(schSCManager);
588 printf("Service installed successfully\n");
591 CloseServiceHandle(schService);
592 CloseServiceHandle(schSCManager);
597 VOID ReportSvcStatus(DWORD dwCurrentState,
598 DWORD dwWin32ExitCode,
601 static DWORD dwCheckPoint = 1;
603 l_SvcStatus.dwCurrentState = dwCurrentState;
604 l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
605 l_SvcStatus.dwWaitHint = dwWaitHint;
607 if (dwCurrentState == SERVICE_START_PENDING)
608 l_SvcStatus.dwControlsAccepted = 0;
610 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
612 if ((dwCurrentState == SERVICE_RUNNING) ||
613 (dwCurrentState == SERVICE_STOPPED))
614 l_SvcStatus.dwCheckPoint = 0;
616 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
618 SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
621 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
623 if (dwCtrl == SERVICE_CONTROL_STOP) {
624 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
625 TerminateJobObject(l_Job, 0);
629 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
631 l_SvcStatusHandle = RegisterServiceCtrlHandler(
633 ServiceControlHandler);
635 l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
636 l_SvcStatus.dwServiceSpecificExitCode = 0;
638 ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
640 l_Job = CreateJobObject(NULL, NULL);
645 int uargc = Application::GetArgC();
646 char **uargv = Application::GetArgV();
648 args += Utility::EscapeShellArg(Application::GetExePath(uargv[0]));
650 for (int i = 2; i < uargc && uargv[i]; i++) {
654 args += Utility::EscapeShellArg(uargv[i]);
657 STARTUPINFO si = { sizeof(si) };
658 PROCESS_INFORMATION pi;
660 char *uargs = strdup(args.CStr());
662 BOOL res = CreateProcess(NULL, uargs, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
669 CloseHandle(pi.hThread);
671 AssignProcessToJobObject(l_Job, pi.hProcess);
673 if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0)
678 if (!GetExitCodeProcess(pi.hProcess, &exitStatus))
685 TerminateJobObject(l_Job, 0);
689 ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
691 Application::Exit(0);
696 * Entry point for the Icinga application.
698 * @params argc Number of command line arguments.
699 * @params argv Command line arguments.
700 * @returns The application's exit status.
702 int main(int argc, char **argv)
706 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0) {
707 rlim_t maxfds = rl.rlim_max;
709 if (maxfds == RLIM_INFINITY)
712 for (rlim_t i = 3; i < maxfds; i++) {
717 std::cerr << "Closed FD " << i << " which we inherited from our parent process." << std::endl;
718 #endif /* I2_DEBUG */
723 /* must be called before using any other libbase functions */
724 Application::InitializeBase();
726 /* Set command-line arguments. */
727 Application::SetArgC(argc);
728 Application::SetArgV(argv);
731 if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
732 return SetupService(true, argc - 2, &argv[2]);
735 if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
736 return SetupService(false, argc - 2, &argv[2]);
739 if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
740 SERVICE_TABLE_ENTRY dispatchTable[] = {
741 { "icinga2", ServiceMain },
745 StartServiceCtrlDispatcher(dispatchTable);
746 Application::Exit(EXIT_FAILURE);
752 Application::Exit(rc);