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 "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/exception.hpp"
29 #include "base/convert.hpp"
30 #include "base/scriptvariable.hpp"
31 #include "base/context.hpp"
32 #include "base/console.hpp"
34 #include <boost/program_options.hpp>
35 #include <boost/tuple/tuple.hpp>
36 #include <boost/foreach.hpp>
39 # include <sys/types.h>
44 using namespace icinga;
45 namespace po = boost::program_options;
48 SERVICE_STATUS l_SvcStatus;
49 SERVICE_STATUS_HANDLE l_SvcStatusHandle;
52 static std::vector<String> GetLogLevelCompletionSuggestions(const String& arg)
54 std::vector<String> result;
56 String debugLevel = "debug";
57 if (debugLevel.Find(arg) == 0)
58 result.push_back(debugLevel);
60 String noticeLevel = "notice";
61 if (noticeLevel.Find(arg) == 0)
62 result.push_back(noticeLevel);
64 String informationLevel = "information";
65 if (informationLevel.Find(arg) == 0)
66 result.push_back(informationLevel);
68 String warningLevel = "warning";
69 if (warningLevel.Find(arg) == 0)
70 result.push_back(warningLevel);
72 String criticalLevel = "critical";
73 if (criticalLevel.Find(arg) == 0)
74 result.push_back(criticalLevel);
79 static std::vector<String> GlobalArgumentCompletion(const String& argument, const String& word)
81 if (argument == "include")
82 return GetBashCompletionSuggestions("directory", word);
83 else if (argument == "log-level")
84 return GetLogLevelCompletionSuggestions(word);
86 return std::vector<String>();
91 int argc = Application::GetArgC();
92 char **argv = Application::GetArgV();
94 bool autocomplete = false;
97 if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
99 autoindex = Convert::ToLong(argv[2]);
104 Application::SetStartTime(Utility::GetTime());
107 Application::SetResourceLimits();
109 /* Set thread title. */
110 Utility::SetThreadName("Main Thread", false);
112 /* Install exception handlers to make debugging easier. */
113 Application::InstallExceptionHandlers();
116 bool builtinPaths = true;
119 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Icinga Development Team\\ICINGA2", 0,
120 KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
121 BYTE pvData[MAX_PATH];
122 DWORD cbData = sizeof(pvData)-1;
124 if (RegQueryValueEx(hKey, NULL, NULL, &lType, pvData, &cbData) == ERROR_SUCCESS && lType == REG_SZ) {
125 pvData[cbData] = '\0';
127 String prefix = (char *)pvData;
128 Application::DeclarePrefixDir(prefix);
129 Application::DeclareSysconfDir(prefix + "\\etc");
130 Application::DeclareRunDir(prefix + "\\var\\run");
131 Application::DeclareLocalStateDir(prefix + "\\var");
132 Application::DeclarePkgDataDir(prefix + "\\share\\icinga2");
133 Application::DeclareIncludeConfDir(prefix + "\\share\\icinga2\\include");
135 builtinPaths = false;
142 Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");
145 Application::DeclarePrefixDir(ICINGA_PREFIX);
146 Application::DeclareSysconfDir(ICINGA_SYSCONFDIR);
147 Application::DeclareRunDir(ICINGA_RUNDIR);
148 Application::DeclareLocalStateDir(ICINGA_LOCALSTATEDIR);
149 Application::DeclarePkgDataDir(ICINGA_PKGDATADIR);
150 Application::DeclareIncludeConfDir(ICINGA_INCLUDECONFDIR);
155 Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
156 Application::DeclareApplicationType("icinga/IcingaApplication");
157 Application::DeclareRunAsUser(ICINGA_USER);
158 Application::DeclareRunAsGroup(ICINGA_GROUP);
160 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
161 Logger::SetConsoleLogSeverity(LogWarning);
163 Utility::LoadExtensionLibrary("cli");
165 po::options_description visibleDesc("Global options");
167 visibleDesc.add_options()
168 ("help,h", "show this help message")
169 ("version,V", "show version information")
171 ("color", "use VT100 color codes even when stdout is not a terminal")
173 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
174 ("library,l", po::value<std::vector<std::string> >(), "load a library")
175 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
176 ("log-level,x", po::value<std::string>(), "specify the log level for the console log");
178 po::options_description hiddenDesc("Hidden options");
180 hiddenDesc.add_options()
182 ("no-stack-rlimit", "used internally, do not specify manually")
184 ("no-stack-rlimit", "used internally, do not specify manually")
186 ("arg", po::value<std::vector<std::string> >(), "positional argument");
188 po::positional_options_description positionalDesc;
189 positionalDesc.add("arg", -1);
192 CLICommand::Ptr command;
193 po::variables_map vm;
196 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
197 vm, cmdname, command, autocomplete);
198 } catch (const std::exception& ex) {
199 Log(LogCritical, "icinga-app")
200 << "Error while parsing command-line options: " << ex.what();
204 String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
206 if (Utility::PathExists(initconfig)) {
207 ConfigCompilerContext::GetInstance()->Reset();
208 ConfigCompiler::CompileFile(initconfig);
212 if (vm.count("color")) {
213 Console::SetType(std::cout, Console_VT100);
214 Console::SetType(std::cerr, Console_VT100);
218 if (vm.count("define")) {
219 BOOST_FOREACH(const String& define, vm["define"].as<std::vector<std::string> >()) {
221 size_t pos = define.FindFirstOf('=');
222 if (pos != String::NPos) {
223 key = define.SubStr(0, pos);
224 value = define.SubStr(pos + 1);
229 ScriptVariable::Set(key, value);
233 Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
234 Application::DeclareObjectsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.debug");
235 Application::DeclareVarsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.vars");
236 Application::DeclarePidPath(Application::GetRunDir() + "/icinga2/icinga2.pid");
238 ConfigCompiler::AddIncludeSearchDir(Application::GetIncludeConfDir());
240 if (!autocomplete && vm.count("include")) {
241 BOOST_FOREACH(const String& includePath, vm["include"].as<std::vector<std::string> >()) {
242 ConfigCompiler::AddIncludeSearchDir(includePath);
247 Logger::SetConsoleLogSeverity(logLevel);
249 if (vm.count("log-level")) {
250 String severity = vm["log-level"].as<std::string>();
252 LogSeverity logLevel = LogInformation;
254 logLevel = Logger::StringToSeverity(severity);
255 } catch (std::exception&) {
256 /* use the default */
257 Log(LogWarning, "icinga", "Invalid log level set. Using default 'information'.");
260 Logger::SetConsoleLogSeverity(logLevel);
263 if (vm.count("library")) {
264 BOOST_FOREACH(const String& libraryName, vm["library"].as<std::vector<std::string> >()) {
265 (void)Utility::LoadExtensionLibrary(libraryName);
269 if (!command || vm.count("help") || vm.count("version")) {
270 String appName = Utility::BaseName(Application::GetArgV()[0]);
272 if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
273 appName = appName.SubStr(3, appName.GetLength() - 3);
275 std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
276 << Application::GetVersion()
280 << ")" << std::endl << std::endl;
282 if (!command || vm.count("help")) {
283 std::cout << "Usage:" << std::endl
284 << " " << argv[0] << " ";
286 if (cmdname.IsEmpty())
287 std::cout << "<command>";
289 std::cout << cmdname;
291 std::cout << " [<arguments>]" << std::endl;
294 std::cout << std::endl
295 << command->GetDescription() << std::endl;
299 if (vm.count("version")) {
300 std::cout << "Copyright (c) 2012-2014 Icinga Development Team (http://www.icinga.org)" << std::endl
301 << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
302 << "This is free software: you are free to change and redistribute it." << std::endl
303 << "There is NO WARRANTY, to the extent permitted by law.";
306 std::cout << std::endl;
308 if (vm.count("version")) {
309 std::cout << std::endl;
311 Application::DisplayInfoMessage(true);
317 if (!command || vm.count("help")) {
319 CLICommand::ShowCommands(argc, argv, NULL);
321 std::cout << visibleDesc << std::endl
322 << "Report bugs at <https://dev.icinga.org/>" << std::endl
323 << "Icinga home page: <http://www.icinga.org/>" << std::endl;
331 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
332 &GlobalArgumentCompletion, true, autoindex);
334 } else if (command) {
335 Logger::DisableTimestamp(true);
337 if (command->GetImpersonationLevel() == ImpersonateRoot) {
339 Log(LogCritical, "cli", "This command must be run as root.");
342 } else if (command && command->GetImpersonationLevel() == ImpersonateIcinga) {
343 String group = Application::GetRunAsGroup();
346 struct group *gr = getgrnam(group.CStr());
350 Log(LogCritical, "cli")
351 << "Invalid group specified: " << group;
354 Log(LogCritical, "cli")
355 << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
360 if (getgid() != gr->gr_gid) {
361 if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) {
362 Log(LogCritical, "cli")
363 << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
367 if (setgid(gr->gr_gid) < 0) {
368 Log(LogCritical, "cli")
369 << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
374 String user = Application::GetRunAsUser();
377 struct passwd *pw = getpwnam(user.CStr());
381 Log(LogCritical, "cli")
382 << "Invalid user specified: " << user;
385 Log(LogCritical, "cli")
386 << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
391 // also activate the additional groups the configured user is member of
392 if (getuid() != pw->pw_uid) {
393 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
394 Log(LogCritical, "cli")
395 << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
399 if (setuid(pw->pw_uid) < 0) {
400 Log(LogCritical, "cli")
401 << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
408 std::vector<std::string> args;
410 args = vm["arg"].as<std::vector<std::string> >();
412 if (args.size() < command->GetMinArguments()) {
413 Log(LogCritical, "cli")
414 << "Too few arguments. Command needs at least " << command->GetMinArguments()
415 << " argument" << (command->GetMinArguments() != 1 ? "s" : "") << ".";
419 if (command->GetMaxArguments() >= 0 && args.size() > command->GetMaxArguments()) {
420 Log(LogCritical, "cli")
421 << "Too many arguments. At most " << command->GetMaxArguments()
422 << " argument" << (command->GetMaxArguments() != 1 ? "s" : "") << " may be specified.";
426 rc = command->Run(vm, args);
433 static int SetupService(bool install, int argc, char **argv)
435 SC_HANDLE schSCManager = OpenSCManager(
438 SC_MANAGER_ALL_ACCESS);
440 if (NULL == schSCManager) {
441 printf("OpenSCManager failed (%d)\n", GetLastError());
445 TCHAR szPath[MAX_PATH];
447 if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
448 printf("Cannot install service (%d)\n", GetLastError());
453 szArgs = Utility::EscapeShellArg(szPath) + " --scm";
455 for (int i = 0; i < argc; i++)
456 szArgs += " " + Utility::EscapeShellArg(argv[i]);
458 SC_HANDLE schService = OpenService(schSCManager, "icinga2", DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
460 if (schService != NULL) {
461 SERVICE_STATUS status;
462 ControlService(schService, SERVICE_CONTROL_STOP, &status);
464 double start = Utility::GetTime();
465 while (status.dwCurrentState != SERVICE_STOPPED) {
466 double end = Utility::GetTime();
468 if (end - start > 30) {
469 printf("Could not stop the service.\n");
475 if (!QueryServiceStatus(schService, &status)) {
476 printf("QueryServiceStatus failed (%d)\n", GetLastError());
481 if (!DeleteService(schService)) {
482 printf("DeleteService failed (%d)\n", GetLastError());
483 CloseServiceHandle(schService);
484 CloseServiceHandle(schSCManager);
489 printf("Service uninstalled successfully\n");
491 CloseServiceHandle(schService);
495 schService = CreateService(
500 SERVICE_WIN32_OWN_PROCESS,
501 SERVICE_DEMAND_START,
502 SERVICE_ERROR_NORMAL,
507 "NT AUTHORITY\\NetworkService",
510 if (schService == NULL) {
511 printf("CreateService failed (%d)\n", GetLastError());
512 CloseServiceHandle(schSCManager);
515 printf("Service installed successfully\n");
517 ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
518 SERVICE_ERROR_NORMAL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
520 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
521 ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription);
523 if (!StartService(schService, 0, NULL)) {
524 printf("StartService failed (%d)\n", GetLastError());
525 CloseServiceHandle(schService);
526 CloseServiceHandle(schSCManager);
530 CloseServiceHandle(schService);
533 CloseServiceHandle(schSCManager);
538 VOID ReportSvcStatus(DWORD dwCurrentState,
539 DWORD dwWin32ExitCode,
542 static DWORD dwCheckPoint = 1;
544 l_SvcStatus.dwCurrentState = dwCurrentState;
545 l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
546 l_SvcStatus.dwWaitHint = dwWaitHint;
548 if (dwCurrentState == SERVICE_START_PENDING)
549 l_SvcStatus.dwControlsAccepted = 0;
551 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
553 if ((dwCurrentState == SERVICE_RUNNING) ||
554 (dwCurrentState == SERVICE_STOPPED))
555 l_SvcStatus.dwCheckPoint = 0;
557 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
559 SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
562 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
564 if (dwCtrl == SERVICE_CONTROL_STOP) {
565 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
566 Application::RequestShutdown();
570 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
572 l_SvcStatusHandle = RegisterServiceCtrlHandler(
574 ServiceControlHandler);
576 l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
577 l_SvcStatus.dwServiceSpecificExitCode = 0;
579 ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
583 ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, rc);
585 Application::Exit(rc);
590 * Entry point for the Icinga application.
592 * @params argc Number of command line arguments.
593 * @params argv Command line arguments.
594 * @returns The application's exit status.
596 int main(int argc, char **argv)
598 /* must be called before using any other libbase functions */
599 Application::InitializeBase();
601 /* Set command-line arguments. */
602 Application::SetArgC(argc);
603 Application::SetArgV(argv);
606 if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
607 return SetupService(true, argc - 2, &argv[2]);
610 if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
611 return SetupService(false, argc - 2, &argv[2]);
614 if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
615 SERVICE_TABLE_ENTRY dispatchTable[] = {
616 { "icinga2", ServiceMain },
620 StartServiceCtrlDispatcher(dispatchTable);
621 Application::Exit(1);
627 Application::Exit(rc);