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 "config/configcompilercontext.hpp"
21 #include "config/configcompiler.hpp"
22 #include "config/configitembuilder.hpp"
23 #include "base/application.hpp"
24 #include "base/logger.hpp"
25 #include "base/timer.hpp"
26 #include "base/utility.hpp"
27 #include "base/exception.hpp"
28 #include "base/convert.hpp"
29 #include "base/scriptvariable.hpp"
30 #include "base/context.hpp"
31 #include "base/clicommand.hpp"
33 #include <boost/program_options.hpp>
34 #include <boost/tuple/tuple.hpp>
35 #include <boost/foreach.hpp>
38 # include <sys/types.h>
43 using namespace icinga;
44 namespace po = boost::program_options;
47 SERVICE_STATUS l_SvcStatus;
48 SERVICE_STATUS_HANDLE l_SvcStatusHandle;
53 int argc = Application::GetArgC();
54 char **argv = Application::GetArgV();
56 bool autocomplete = false;
59 if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
61 autoindex = Convert::ToLong(argv[2]);
66 Application::SetStartTime(Utility::GetTime());
69 Application::SetResourceLimits();
71 /* Set thread title. */
72 Utility::SetThreadName("Main Thread", false);
74 /* Install exception handlers to make debugging easier. */
75 Application::InstallExceptionHandlers();
78 bool builtinPaths = true;
81 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Icinga Development Team\\ICINGA2", 0,
82 KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
83 BYTE pvData[MAX_PATH];
84 DWORD cbData = sizeof(pvData)-1;
86 if (RegQueryValueEx(hKey, NULL, NULL, &lType, pvData, &cbData) == ERROR_SUCCESS && lType == REG_SZ) {
87 pvData[cbData] = '\0';
89 String prefix = (char *)pvData;
90 Application::DeclarePrefixDir(prefix);
91 Application::DeclareSysconfDir(prefix + "\\etc");
92 Application::DeclareRunDir(prefix + "\\var\\run");
93 Application::DeclareLocalStateDir(prefix + "\\var");
94 Application::DeclarePkgDataDir(prefix + "\\share\\icinga2");
95 Application::DeclareIncludeConfDir(prefix + "\\share\\icinga2\\include");
104 Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");
107 Application::DeclarePrefixDir(ICINGA_PREFIX);
108 Application::DeclareSysconfDir(ICINGA_SYSCONFDIR);
109 Application::DeclareRunDir(ICINGA_RUNDIR);
110 Application::DeclareLocalStateDir(ICINGA_LOCALSTATEDIR);
111 Application::DeclarePkgDataDir(ICINGA_PKGDATADIR);
112 Application::DeclareIncludeConfDir(ICINGA_INCLUDECONFDIR);
117 Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
118 Application::DeclareApplicationType("icinga/IcingaApplication");
119 Application::DeclareRunAsUser(ICINGA_USER);
120 Application::DeclareRunAsGroup(ICINGA_GROUP);
122 LogSeverity logLevel = Logger::GetConsoleLogSeverity();
123 Logger::SetConsoleLogSeverity(LogWarning);
125 Utility::LoadExtensionLibrary("cli");
127 po::options_description visibleDesc("Global options");
129 visibleDesc.add_options()
130 ("help", "show this help message")
131 ("version,V", "show version information")
132 ("define,D", po::value<std::vector<std::string> >(), "define a constant")
133 ("library,l", po::value<std::vector<std::string> >(), "load a library")
134 ("include,I", po::value<std::vector<std::string> >(), "add include search directory")
135 ("log-level,x", po::value<std::string>(), "specify the log level for the console log")
137 ("user,u", po::value<std::string>(), "user to run Icinga as")
138 ("group,g", po::value<std::string>(), "group to run Icinga as")
142 po::options_description hiddenDesc("Hidden options");
144 hiddenDesc.add_options()
145 ("no-stack-rlimit", "used internally, do not specify manually");
148 CLICommand::Ptr command;
149 po::variables_map vm;
152 CLICommand::ParseCommand(argc, argv, visibleDesc, hiddenDesc, vm, cmdname, command, autocomplete);
153 } catch (const std::exception& ex) {
154 std::ostringstream msgbuf;
155 msgbuf << "Error while parsing command-line options: " << ex.what();
156 Log(LogCritical, "icinga-app", msgbuf.str());
160 String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
162 if (Utility::PathExists(initconfig)) {
163 ConfigCompilerContext::GetInstance()->Reset();
164 ConfigCompiler::CompileFile(initconfig);
167 if (vm.count("define")) {
168 BOOST_FOREACH(const String& define, vm["define"].as<std::vector<std::string> >()) {
170 size_t pos = define.FindFirstOf('=');
171 if (pos != String::NPos) {
172 key = define.SubStr(0, pos);
173 value = define.SubStr(pos + 1);
178 ScriptVariable::Set(key, value);
182 if (vm.count("group"))
183 ScriptVariable::Set("RunAsGroup", String(vm["group"].as<std::string>()));
185 if (vm.count("user"))
186 ScriptVariable::Set("RunAsUser", String(vm["user"].as<std::string>()));
189 String group = Application::GetRunAsGroup();
192 struct group *gr = getgrnam(group.CStr());
196 std::ostringstream msgbuf;
197 msgbuf << "Invalid group specified: " + group;
198 Log(LogCritical, "cli", msgbuf.str());
201 std::ostringstream msgbuf;
202 msgbuf << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
203 Log(LogCritical, "cli", msgbuf.str());
208 if (getgid() != gr->gr_gid) {
209 if (!vm.count("reload-internal") && setgroups(0, NULL) < 0) {
210 std::ostringstream msgbuf;
211 msgbuf << "setgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
212 Log(LogCritical, "cli", msgbuf.str());
216 if (setgid(gr->gr_gid) < 0) {
217 std::ostringstream msgbuf;
218 msgbuf << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
219 Log(LogCritical, "cli", msgbuf.str());
224 String user = Application::GetRunAsUser();
227 struct passwd *pw = getpwnam(user.CStr());
231 std::ostringstream msgbuf;
232 msgbuf << "Invalid user specified: " + user;
233 Log(LogCritical, "cli", msgbuf.str());
236 std::ostringstream msgbuf;
237 msgbuf << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
238 Log(LogCritical, "cli", msgbuf.str());
243 // also activate the additional groups the configured user is member of
244 if (getuid() != pw->pw_uid) {
245 if (!vm.count("reload-internal") && initgroups(user.CStr(), pw->pw_gid) < 0) {
246 std::ostringstream msgbuf;
247 msgbuf << "initgroups() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
248 Log(LogCritical, "cli", msgbuf.str());
252 if (setuid(pw->pw_uid) < 0) {
253 std::ostringstream msgbuf;
254 msgbuf << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
255 Log(LogCritical, "cli", msgbuf.str());
261 Application::DeclareStatePath(Application::GetLocalStateDir() + "/lib/icinga2/icinga2.state");
262 Application::DeclareObjectsPath(Application::GetLocalStateDir() + "/cache/icinga2/icinga2.debug");
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);
273 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 /* use the default */
284 Log(LogWarning, "icinga", "Invalid log level set. Using default 'information'.");
287 Logger::SetConsoleLogSeverity(logLevel);
290 if (vm.count("library")) {
291 BOOST_FOREACH(const String& libraryName, vm["library"].as<std::vector<std::string> >()) {
292 (void)Utility::LoadExtensionLibrary(libraryName);
296 if (!command || vm.count("help") || vm.count("version")) {
297 String appName = Utility::BaseName(Application::GetArgV()[0]);
299 if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
300 appName = appName.SubStr(3, appName.GetLength() - 3);
302 std::cout << appName << " " << "- The Icinga 2 network monitoring daemon.";
304 if (!command || vm.count("help")) {
305 std::cout << std::endl << std::endl
306 << "Usage:" << std::endl
307 << " " << argv[0] << " ";
309 if (cmdname.IsEmpty())
310 std::cout << "<command>";
312 std::cout << cmdname;
314 std::cout << " [<arguments>]";
317 std::cout << std::endl << std::endl
318 << command->GetDescription();
322 if (vm.count("version")) {
323 std::cout << " (Version: " << Application::GetVersion() << ")";
324 std::cout << std::endl
325 << "Copyright (c) 2012-2014 Icinga Development Team (http://www.icinga.org)" << std::endl
326 << "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl2.html>" << std::endl
327 << "This is free software: you are free to change and redistribute it." << std::endl
328 << "There is NO WARRANTY, to the extent permitted by law.";
331 std::cout << std::endl;
333 if (vm.count("version")) {
334 std::cout << std::endl;
336 Application::DisplayInfoMessage(true);
342 if (!command || vm.count("help")) {
344 std::cout << std::endl;
345 CLICommand::ShowCommands(argc, argv, NULL);
348 std::cout << std::endl
349 << visibleDesc << std::endl
350 << "Report bugs at <https://dev.icinga.org/>" << std::endl
351 << "Icinga home page: <http://www.icinga.org/>" << std::endl;
359 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc, true, autoindex);
362 rc = command->Run(vm);
365 Application::Exit(rc);
372 static int SetupService(bool install, int argc, char **argv)
374 SC_HANDLE schSCManager = OpenSCManager(
377 SC_MANAGER_ALL_ACCESS);
379 if (NULL == schSCManager) {
380 printf("OpenSCManager failed (%d)\n", GetLastError());
384 TCHAR szPath[MAX_PATH];
386 if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
387 printf("Cannot install service (%d)\n", GetLastError());
392 szArgs = Utility::EscapeShellArg(szPath) + " --scm";
394 for (int i = 0; i < argc; i++)
395 szArgs += " " + Utility::EscapeShellArg(argv[i]);
397 SC_HANDLE schService = OpenService(schSCManager, "icinga2", DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
399 if (schService != NULL) {
400 SERVICE_STATUS status;
401 ControlService(schService, SERVICE_CONTROL_STOP, &status);
403 double start = Utility::GetTime();
404 while (status.dwCurrentState != SERVICE_STOPPED) {
405 double end = Utility::GetTime();
407 if (end - start > 30) {
408 printf("Could not stop the service.\n");
414 if (!QueryServiceStatus(schService, &status)) {
415 printf("QueryServiceStatus failed (%d)\n", GetLastError());
420 if (!DeleteService(schService)) {
421 printf("DeleteService failed (%d)\n", GetLastError());
422 CloseServiceHandle(schService);
423 CloseServiceHandle(schSCManager);
428 printf("Service uninstalled successfully\n");
430 CloseServiceHandle(schService);
434 schService = CreateService(
439 SERVICE_WIN32_OWN_PROCESS,
440 SERVICE_DEMAND_START,
441 SERVICE_ERROR_NORMAL,
446 "NT AUTHORITY\\NetworkService",
449 if (schService == NULL) {
450 printf("CreateService failed (%d)\n", GetLastError());
451 CloseServiceHandle(schSCManager);
454 printf("Service installed successfully\n");
456 ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
457 SERVICE_ERROR_NORMAL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
459 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
460 ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription);
462 if (!StartService(schService, 0, NULL)) {
463 printf("StartService failed (%d)\n", GetLastError());
464 CloseServiceHandle(schService);
465 CloseServiceHandle(schSCManager);
469 CloseServiceHandle(schService);
472 CloseServiceHandle(schSCManager);
477 VOID ReportSvcStatus(DWORD dwCurrentState,
478 DWORD dwWin32ExitCode,
481 static DWORD dwCheckPoint = 1;
483 l_SvcStatus.dwCurrentState = dwCurrentState;
484 l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
485 l_SvcStatus.dwWaitHint = dwWaitHint;
487 if (dwCurrentState == SERVICE_START_PENDING)
488 l_SvcStatus.dwControlsAccepted = 0;
490 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
492 if ((dwCurrentState == SERVICE_RUNNING) ||
493 (dwCurrentState == SERVICE_STOPPED))
494 l_SvcStatus.dwCheckPoint = 0;
496 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
498 SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
501 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
503 if (dwCtrl == SERVICE_CONTROL_STOP) {
504 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
505 Application::RequestShutdown();
509 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
511 l_SvcStatusHandle = RegisterServiceCtrlHandler(
513 ServiceControlHandler);
515 l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
516 l_SvcStatus.dwServiceSpecificExitCode = 0;
518 ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
522 ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, rc);
527 * Entry point for the Icinga application.
529 * @params argc Number of command line arguments.
530 * @params argv Command line arguments.
531 * @returns The application's exit status.
533 int main(int argc, char **argv)
535 /* must be called before using any other libbase functions */
536 Application::InitializeBase();
538 /* Set command-line arguments. */
539 Application::SetArgC(argc);
540 Application::SetArgV(argv);
543 if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
544 return SetupService(true, argc - 2, &argv[2]);
547 if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
548 return SetupService(false, argc - 2, &argv[2]);
551 if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
552 SERVICE_TABLE_ENTRY dispatchTable[] = {
553 { "icinga2", ServiceMain },
557 StartServiceCtrlDispatcher(dispatchTable);
558 Application::Exit(1);
564 Application::Exit(rc);