1 /******************************************************************************
3 * Copyright (C) 2012-2017 Icinga Development Team (https://www.icinga.com/) *
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"
34 #include "base/process.hpp"
36 #include <boost/program_options.hpp>
37 #include <boost/tuple/tuple.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 ScriptGlobal::Set("AttachDebugger", false);
159 ScriptGlobal::Set("PlatformKernel", Utility::GetPlatformKernel());
160 ScriptGlobal::Set("PlatformKernelVersion", Utility::GetPlatformKernelVersion());
161 ScriptGlobal::Set("PlatformName", Utility::GetPlatformName());
162 ScriptGlobal::Set("PlatformVersion", Utility::GetPlatformVersion());
163 ScriptGlobal::Set("PlatformArchitecture", Utility::GetPlatformArchitecture());
165 ScriptGlobal::Set("BuildHostName", ICINGA_BUILD_HOST_NAME);
166 ScriptGlobal::Set("BuildCompilerName", ICINGA_BUILD_COMPILER_NAME);
167 ScriptGlobal::Set("BuildCompilerVersion", ICINGA_BUILD_COMPILER_VERSION);
169 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
170 Logger::SetConsoleLogSeverity(LogWarning);
172 Loader::LoadExtensionLibrary("cli");
174 po::options_description visibleDesc("Global options");
176 visibleDesc.add_options()
177 ("help,h", "show this help message")
178 ("version,V", "show version information")
180 ("color", "use VT100 color codes even when stdout is not a terminal")
182 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
183 ("app,a", po::value<std::string>(), "application library name (default: icinga)")
184 ("library,l", po::value<std::vector<std::string> >(), "load a library")
185 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
186 ("log-level,x", po::value<std::string>(), "specify the log level for the console log.\n"
187 "The valid value is either debug, notice, information (default), warning, or critical")
188 ("script-debugger,X", "whether to enable the script debugger");
190 po::options_description hiddenDesc("Hidden options");
192 hiddenDesc.add_options()
193 ("no-stack-rlimit", "used internally, do not specify manually")
194 ("arg", po::value<std::vector<std::string> >(), "positional argument");
196 po::positional_options_description positionalDesc;
197 positionalDesc.add("arg", -1);
200 CLICommand::Ptr command;
201 po::variables_map vm;
204 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
205 vm, cmdname, command, autocomplete);
206 } catch (const std::exception& ex) {
207 Log(LogCritical, "icinga-app")
208 << "Error while parsing command-line options: " << ex.what();
212 String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
214 if (Utility::PathExists(initconfig)) {
215 Expression *expression;
217 expression = ConfigCompiler::CompileFile(initconfig);
220 expression->Evaluate(frame);
221 } catch (const std::exception& ex) {
224 Log(LogCritical, "config", DiagnosticInformation(ex));
232 if (vm.count("color")) {
233 Console::SetType(std::cout, Console_VT100);
234 Console::SetType(std::cerr, Console_VT100);
238 if (vm.count("define")) {
239 for (const String& define : vm["define"].as<std::vector<std::string> >()) {
241 size_t pos = define.FindFirstOf('=');
242 if (pos != String::NPos) {
243 key = define.SubStr(0, pos);
244 value = define.SubStr(pos + 1);
249 ScriptGlobal::Set(key, value);
253 if (vm.count("script-debugger"))
254 Application::SetScriptDebuggerEnabled(true);
256 Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
257 Application::DeclareModAttrPath(Application::GetLocalStateDir() + "/lib/icinga2/modified-attributes.conf");
258 Application::DeclareObjectsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.debug");
259 Application::DeclareVarsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.vars");
260 Application::DeclarePidPath(Application::GetRunDir() + "/icinga2/icinga2.pid");
262 ConfigCompiler::AddIncludeSearchDir(Application::GetIncludeConfDir());
264 if (!autocomplete && vm.count("include")) {
265 for (const String& includePath : vm["include"].as<std::vector<std::string> >()) {
266 ConfigCompiler::AddIncludeSearchDir(includePath);
271 Logger::SetConsoleLogSeverity(logLevel);
273 if (vm.count("log-level")) {
274 String severity = vm["log-level"].as<std::string>();
276 LogSeverity logLevel = LogInformation;
278 logLevel = Logger::StringToSeverity(severity);
279 } catch (std::exception&) {
280 /* Inform user and exit */
281 Log(LogCritical, "icinga-app", "Invalid log level set. Default is 'information'.");
285 Logger::SetConsoleLogSeverity(logLevel);
288 if (vm.count("library")) {
289 for (const String& libraryName : vm["library"].as<std::vector<std::string> >()) {
291 (void) Loader::LoadExtensionLibrary(libraryName);
292 } catch (const std::exception& ex) {
293 Log(LogCritical, "icinga-app")
294 << "Could not load library \"" << libraryName << "\": " << DiagnosticInformation(ex);
300 if (!command || vm.count("help") || vm.count("version")) {
304 appName = Utility::BaseName(Application::GetArgV()[0]);
305 } catch (const std::bad_alloc&) {
306 Log(LogCritical, "icinga-app", "Allocation failed.");
310 if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
311 appName = appName.SubStr(3, appName.GetLength() - 3);
313 std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
314 << ConsoleColorTag(vm.count("version") ? Console_ForegroundRed : Console_Normal)
315 << Application::GetAppVersion()
318 #endif /* I2_DEBUG */
319 << ConsoleColorTag(Console_Normal)
320 << ")" << std::endl << std::endl;
322 if ((!command || vm.count("help")) && !vm.count("version")) {
323 std::cout << "Usage:" << std::endl
324 << " " << Utility::BaseName(argv[0]) << " ";
326 if (cmdname.IsEmpty())
327 std::cout << "<command>";
329 std::cout << cmdname;
331 std::cout << " [<arguments>]" << std::endl;
334 std::cout << std::endl
335 << command->GetDescription() << std::endl;
339 if (vm.count("version")) {
340 std::cout << "Copyright (c) 2012-2017 Icinga Development Team (https://www.icinga.com/)" << std::endl
341 << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
342 << "This is free software: you are free to change and redistribute it." << std::endl
343 << "There is NO WARRANTY, to the extent permitted by law.";
346 std::cout << std::endl;
348 if (vm.count("version")) {
349 std::cout << std::endl;
351 Application::DisplayInfoMessage(std::cout, true);
357 if (!command || vm.count("help")) {
359 CLICommand::ShowCommands(argc, argv, NULL);
361 std::cout << visibleDesc << std::endl
362 << "Report bugs at <https://github.com/Icinga/icinga2>" << std::endl
363 << "Icinga home page: <https://www.icinga.com/>" << std::endl;
371 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
372 &GlobalArgumentCompletion, true, autoindex);
374 } else if (command) {
375 Logger::DisableTimestamp(true);
377 if (command->GetImpersonationLevel() == ImpersonateRoot) {
379 Log(LogCritical, "cli", "This command must be run as root.");
382 } else if (command && command->GetImpersonationLevel() == ImpersonateIcinga) {
383 String group = Application::GetRunAsGroup();
384 String user = Application::GetRunAsUser();
387 struct group *gr = getgrnam(group.CStr());
391 Log(LogCritical, "cli")
392 << "Invalid group specified: " << group;
395 Log(LogCritical, "cli")
396 << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
401 if (getgid() != gr->gr_gid) {
402 if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) {
403 Log(LogCritical, "cli")
404 << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
405 Log(LogCritical, "cli")
406 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
410 if (setgid(gr->gr_gid) < 0) {
411 Log(LogCritical, "cli")
412 << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
418 struct passwd *pw = getpwnam(user.CStr());
422 Log(LogCritical, "cli")
423 << "Invalid user specified: " << user;
426 Log(LogCritical, "cli")
427 << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
432 // also activate the additional groups the configured user is member of
433 if (getuid() != pw->pw_uid) {
434 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
435 Log(LogCritical, "cli")
436 << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
437 Log(LogCritical, "cli")
438 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
442 if (setuid(pw->pw_uid) < 0) {
443 Log(LogCritical, "cli")
444 << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
445 Log(LogCritical, "cli")
446 << "Please re-run this command as a privileged user or using the \"" << user << "\" account.";
452 Process::InitializeSpawnHelper();
455 std::vector<std::string> args;
457 args = vm["arg"].as<std::vector<std::string> >();
459 if (static_cast<int>(args.size()) < command->GetMinArguments()) {
460 Log(LogCritical, "cli")
461 << "Too few arguments. Command needs at least " << command->GetMinArguments()
462 << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
466 if (command->GetMaxArguments() >= 0 && static_cast<int>(args.size()) > command->GetMaxArguments()) {
467 Log(LogCritical, "cli")
468 << "Too many arguments. At most " << command->GetMaxArguments()
469 << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
473 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
474 Logger::SetConsoleLogSeverity(LogWarning);
477 Loader::LoadExtensionLibrary(vm["app"].as<std::string>());
479 Loader::LoadExtensionLibrary("icinga");
481 Logger::SetConsoleLogSeverity(logLevel);
483 rc = command->Run(vm, args);
490 static int SetupService(bool install, int argc, char **argv)
492 SC_HANDLE schSCManager = OpenSCManager(
495 SC_MANAGER_ALL_ACCESS);
497 if (NULL == schSCManager) {
498 printf("OpenSCManager failed (%d)\n", GetLastError());
502 TCHAR szPath[MAX_PATH];
504 if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
505 printf("Cannot install service (%d)\n", GetLastError());
510 szArgs = Utility::EscapeShellArg(szPath) + " --scm";
512 std::string scmUser = "NT AUTHORITY\\NetworkService";
513 std::ifstream initf(Utility::GetIcingaDataPath() + "\\etc\\icinga2\\user");
515 std::getline(initf, scmUser);
519 for (int i = 0; i < argc; i++) {
520 if (!strcmp(argv[i], "--scm-user") && i + 1 < argc) {
521 scmUser = argv[i + 1];
524 szArgs += " " + Utility::EscapeShellArg(argv[i]);
527 SC_HANDLE schService = OpenService(schSCManager, "icinga2", SERVICE_ALL_ACCESS);
529 if (schService != NULL) {
530 SERVICE_STATUS status;
531 ControlService(schService, SERVICE_CONTROL_STOP, &status);
533 double start = Utility::GetTime();
534 while (status.dwCurrentState != SERVICE_STOPPED) {
535 double end = Utility::GetTime();
537 if (end - start > 30) {
538 printf("Could not stop the service.\n");
544 if (!QueryServiceStatus(schService, &status)) {
545 printf("QueryServiceStatus failed (%d)\n", GetLastError());
549 } else if (install) {
550 schService = CreateService(
555 SERVICE_WIN32_OWN_PROCESS,
556 SERVICE_DEMAND_START,
557 SERVICE_ERROR_NORMAL,
565 if (schService == NULL) {
566 printf("CreateService failed (%d)\n", GetLastError());
567 CloseServiceHandle(schSCManager);
571 printf("Service isn't installed.\n");
572 CloseServiceHandle(schSCManager);
577 if (!DeleteService(schService)) {
578 printf("DeleteService failed (%d)\n", GetLastError());
579 CloseServiceHandle(schService);
580 CloseServiceHandle(schSCManager);
584 printf("Service uninstalled successfully\n");
586 if (!ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
587 SERVICE_ERROR_NORMAL, szArgs.CStr(), NULL, NULL, NULL, scmUser.c_str(), NULL, NULL)) {
588 printf("ChangeServiceConfig failed (%d)\n", GetLastError());
589 CloseServiceHandle(schService);
590 CloseServiceHandle(schSCManager);
594 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
595 if(!ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription)) {
596 printf("ChangeServiceConfig2 failed (%d)\n", GetLastError());
597 CloseServiceHandle(schService);
598 CloseServiceHandle(schSCManager);
602 if (!StartService(schService, 0, NULL)) {
603 printf("StartService failed (%d)\n", GetLastError());
604 CloseServiceHandle(schService);
605 CloseServiceHandle(schSCManager);
609 printf("Service successfully installed for user '%s'\n", scmUser);
611 std::ofstream fuser(Utility::GetIcingaDataPath() + "\\etc\\icinga2\\user", std::ios::out | std::ios::trunc);
615 printf("Could not write user to %s\\etc\\icinga2\\user", Utility::GetIcingaDataPath());
619 CloseServiceHandle(schService);
620 CloseServiceHandle(schSCManager);
625 VOID ReportSvcStatus(DWORD dwCurrentState,
626 DWORD dwWin32ExitCode,
629 static DWORD dwCheckPoint = 1;
631 l_SvcStatus.dwCurrentState = dwCurrentState;
632 l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
633 l_SvcStatus.dwWaitHint = dwWaitHint;
635 if (dwCurrentState == SERVICE_START_PENDING)
636 l_SvcStatus.dwControlsAccepted = 0;
638 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
640 if ((dwCurrentState == SERVICE_RUNNING) ||
641 (dwCurrentState == SERVICE_STOPPED))
642 l_SvcStatus.dwCheckPoint = 0;
644 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
646 SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
649 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
651 if (dwCtrl == SERVICE_CONTROL_STOP) {
652 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
653 TerminateJobObject(l_Job, 0);
657 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
659 l_SvcStatusHandle = RegisterServiceCtrlHandler(
661 ServiceControlHandler);
663 l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
664 l_SvcStatus.dwServiceSpecificExitCode = 0;
666 ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
667 l_Job = CreateJobObject(NULL, NULL);
672 int uargc = Application::GetArgC();
673 char **uargv = Application::GetArgV();
675 args += Utility::EscapeShellArg(Application::GetExePath(uargv[0]));
677 for (int i = 2; i < uargc && uargv[i]; i++) {
681 args += Utility::EscapeShellArg(uargv[i]);
684 STARTUPINFO si = { sizeof(si) };
685 PROCESS_INFORMATION pi;
687 char *uargs = strdup(args.CStr());
689 BOOL res = CreateProcess(NULL, uargs, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
696 CloseHandle(pi.hThread);
698 AssignProcessToJobObject(l_Job, pi.hProcess);
700 if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0)
705 if (!GetExitCodeProcess(pi.hProcess, &exitStatus))
712 TerminateJobObject(l_Job, 0);
716 ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
718 Application::Exit(0);
723 * Entry point for the Icinga application.
725 * @params argc Number of command line arguments.
726 * @params argv Command line arguments.
727 * @returns The application's exit status.
729 int main(int argc, char **argv)
732 if (!getenv("ICINGA2_KEEP_FDS")) {
734 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0) {
735 rlim_t maxfds = rl.rlim_max;
737 if (maxfds == RLIM_INFINITY)
740 for (rlim_t i = 3; i < maxfds; i++) {
745 std::cerr << "Closed FD " << i << " which we inherited from our parent process." << std::endl;
746 #endif /* I2_DEBUG */
752 /* must be called before using any other libbase functions */
753 Application::InitializeBase();
755 /* Set command-line arguments. */
756 Application::SetArgC(argc);
757 Application::SetArgV(argv);
760 if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
761 return SetupService(true, argc - 2, &argv[2]);
764 if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
765 return SetupService(false, argc - 2, &argv[2]);
768 if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
769 SERVICE_TABLE_ENTRY dispatchTable[] = {
770 { "icinga2", ServiceMain },
774 StartServiceCtrlDispatcher(dispatchTable);
775 Application::Exit(EXIT_FAILURE);
781 Application::Exit(rc);