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", "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()
181 ("no-stack-rlimit", "used internally, do not specify manually")
182 ("arg", po::value<std::vector<std::string> >(), "positional argument");
184 po::positional_options_description positionalDesc;
185 positionalDesc.add("arg", -1);
188 CLICommand::Ptr command;
189 po::variables_map vm;
192 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, positionalDesc,
193 vm, cmdname, command, autocomplete);
194 } catch (const std::exception& ex) {
195 Log(LogCritical, "icinga-app")
196 << "Error while parsing command-line options: " << ex.what();
200 String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
202 if (Utility::PathExists(initconfig)) {
203 ConfigCompilerContext::GetInstance()->Reset();
204 ConfigCompiler::CompileFile(initconfig);
208 if (vm.count("color")) {
209 Console::SetType(std::cout, Console_VT100);
210 Console::SetType(std::cerr, Console_VT100);
214 if (vm.count("define")) {
215 BOOST_FOREACH(const String& define, vm["define"].as<std::vector<std::string> >()) {
217 size_t pos = define.FindFirstOf('=');
218 if (pos != String::NPos) {
219 key = define.SubStr(0, pos);
220 value = define.SubStr(pos + 1);
225 ScriptVariable::Set(key, value);
229 Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
230 Application::DeclareObjectsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.debug");
231 Application::DeclarePidPath(Application::GetRunDir() + "/icinga2/icinga2.pid");
233 ConfigCompiler::AddIncludeSearchDir(Application::GetIncludeConfDir());
235 if (!autocomplete && vm.count("include")) {
236 BOOST_FOREACH(const String& includePath, vm["include"].as<std::vector<std::string> >()) {
237 ConfigCompiler::AddIncludeSearchDir(includePath);
241 Logger::SetConsoleLogSeverity(logLevel);
244 if (vm.count("log-level")) {
245 String severity = vm["log-level"].as<std::string>();
247 LogSeverity logLevel = LogInformation;
249 logLevel = Logger::StringToSeverity(severity);
250 } catch (std::exception&) {
251 /* use the default */
252 Log(LogWarning, "icinga", "Invalid log level set. Using default 'information'.");
255 Logger::SetConsoleLogSeverity(logLevel);
258 if (vm.count("library")) {
259 BOOST_FOREACH(const String& libraryName, vm["library"].as<std::vector<std::string> >()) {
260 (void)Utility::LoadExtensionLibrary(libraryName);
264 if (!command || vm.count("help") || vm.count("version")) {
265 String appName = Utility::BaseName(Application::GetArgV()[0]);
267 if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
268 appName = appName.SubStr(3, appName.GetLength() - 3);
270 std::cout << appName << " " << "- The Icinga 2 network monitoring daemon.";
272 if (!command || vm.count("help")) {
273 std::cout << std::endl << std::endl
274 << "Usage:" << std::endl
275 << " " << argv[0] << " ";
277 if (cmdname.IsEmpty())
278 std::cout << "<command>";
280 std::cout << cmdname;
282 std::cout << " [<arguments>]";
285 std::cout << std::endl << std::endl
286 << command->GetDescription();
290 if (vm.count("version")) {
291 std::cout << " (Version: " << Application::GetVersion() << ")";
292 std::cout << std::endl
293 << "Copyright (c) 2012-2014 Icinga Development Team (http://www.icinga.org)" << std::endl
294 << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
295 << "This is free software: you are free to change and redistribute it." << std::endl
296 << "There is NO WARRANTY, to the extent permitted by law.";
299 std::cout << std::endl;
301 if (vm.count("version")) {
302 std::cout << std::endl;
304 Application::DisplayInfoMessage(true);
310 if (!command || vm.count("help")) {
312 std::cout << std::endl;
313 CLICommand::ShowCommands(argc, argv, NULL);
316 std::cout << std::endl
317 << visibleDesc << std::endl
318 << "Report bugs at <https://dev.icinga.org/>" << std::endl
319 << "Icinga home page: <http://www.icinga.org/>" << std::endl;
327 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
328 &GlobalArgumentCompletion, true, autoindex);
330 } else if (command) {
332 String group = Application::GetRunAsGroup();
335 struct group *gr = getgrnam(group.CStr());
339 Log(LogCritical, "cli")
340 << "Invalid group specified: " << group;
343 Log(LogCritical, "cli")
344 << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
349 if (getgid() != gr->gr_gid) {
350 if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) {
351 Log(LogCritical, "cli")
352 << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
356 if (setgid(gr->gr_gid) < 0) {
357 Log(LogCritical, "cli")
358 << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
363 String user = Application::GetRunAsUser();
366 struct passwd *pw = getpwnam(user.CStr());
370 Log(LogCritical, "cli")
371 << "Invalid user specified: " << user;
374 Log(LogCritical, "cli")
375 << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
380 // also activate the additional groups the configured user is member of
381 if (getuid() != pw->pw_uid) {
382 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
383 Log(LogCritical, "cli")
384 << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
388 if (setuid(pw->pw_uid) < 0) {
389 Log(LogCritical, "cli")
390 << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
396 std::vector<std::string> args;
398 args = vm["arg"].as<std::vector<std::string> >();
400 rc = command->Run(vm, args);
404 Application::Exit(rc);
411 static int SetupService(bool install, int argc, char **argv)
413 SC_HANDLE schSCManager = OpenSCManager(
416 SC_MANAGER_ALL_ACCESS);
418 if (NULL == schSCManager) {
419 printf("OpenSCManager failed (%d)\n", GetLastError());
423 TCHAR szPath[MAX_PATH];
425 if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
426 printf("Cannot install service (%d)\n", GetLastError());
431 szArgs = Utility::EscapeShellArg(szPath) + " --scm";
433 for (int i = 0; i < argc; i++)
434 szArgs += " " + Utility::EscapeShellArg(argv[i]);
436 SC_HANDLE schService = OpenService(schSCManager, "icinga2", DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
438 if (schService != NULL) {
439 SERVICE_STATUS status;
440 ControlService(schService, SERVICE_CONTROL_STOP, &status);
442 double start = Utility::GetTime();
443 while (status.dwCurrentState != SERVICE_STOPPED) {
444 double end = Utility::GetTime();
446 if (end - start > 30) {
447 printf("Could not stop the service.\n");
453 if (!QueryServiceStatus(schService, &status)) {
454 printf("QueryServiceStatus failed (%d)\n", GetLastError());
459 if (!DeleteService(schService)) {
460 printf("DeleteService failed (%d)\n", GetLastError());
461 CloseServiceHandle(schService);
462 CloseServiceHandle(schSCManager);
467 printf("Service uninstalled successfully\n");
469 CloseServiceHandle(schService);
473 schService = CreateService(
478 SERVICE_WIN32_OWN_PROCESS,
479 SERVICE_DEMAND_START,
480 SERVICE_ERROR_NORMAL,
485 "NT AUTHORITY\\NetworkService",
488 if (schService == NULL) {
489 printf("CreateService failed (%d)\n", GetLastError());
490 CloseServiceHandle(schSCManager);
493 printf("Service installed successfully\n");
495 ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
496 SERVICE_ERROR_NORMAL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
498 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
499 ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription);
501 if (!StartService(schService, 0, NULL)) {
502 printf("StartService failed (%d)\n", GetLastError());
503 CloseServiceHandle(schService);
504 CloseServiceHandle(schSCManager);
508 CloseServiceHandle(schService);
511 CloseServiceHandle(schSCManager);
516 VOID ReportSvcStatus(DWORD dwCurrentState,
517 DWORD dwWin32ExitCode,
520 static DWORD dwCheckPoint = 1;
522 l_SvcStatus.dwCurrentState = dwCurrentState;
523 l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
524 l_SvcStatus.dwWaitHint = dwWaitHint;
526 if (dwCurrentState == SERVICE_START_PENDING)
527 l_SvcStatus.dwControlsAccepted = 0;
529 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
531 if ((dwCurrentState == SERVICE_RUNNING) ||
532 (dwCurrentState == SERVICE_STOPPED))
533 l_SvcStatus.dwCheckPoint = 0;
535 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
537 SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
540 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
542 if (dwCtrl == SERVICE_CONTROL_STOP) {
543 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
544 Application::RequestShutdown();
548 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
550 l_SvcStatusHandle = RegisterServiceCtrlHandler(
552 ServiceControlHandler);
554 l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
555 l_SvcStatus.dwServiceSpecificExitCode = 0;
557 ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
561 ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, rc);
566 * Entry point for the Icinga application.
568 * @params argc Number of command line arguments.
569 * @params argv Command line arguments.
570 * @returns The application's exit status.
572 int main(int argc, char **argv)
574 /* must be called before using any other libbase functions */
575 Application::InitializeBase();
577 /* Set command-line arguments. */
578 Application::SetArgC(argc);
579 Application::SetArgV(argv);
582 if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
583 return SetupService(true, argc - 2, &argv[2]);
586 if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
587 return SetupService(false, argc - 2, &argv[2]);
590 if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
591 SERVICE_TABLE_ENTRY dispatchTable[] = {
592 { "icinga2", ServiceMain },
596 StartServiceCtrlDispatcher(dispatchTable);
597 Application::Exit(1);
603 Application::Exit(rc);