]> granicus.if.org Git - icinga2/blob - icinga-app/icinga.cpp
Docs: Update agent/client setup
[icinga2] / icinga-app / icinga.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.org)    *
4  *                                                                            *
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.                     *
9  *                                                                            *
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.                               *
14  *                                                                            *
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  ******************************************************************************/
19
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"
33 #include "config.h"
34 #include <boost/program_options.hpp>
35 #include <boost/tuple/tuple.hpp>
36 #include <boost/foreach.hpp>
37
38 #ifndef _WIN32
39 #       include <sys/types.h>
40 #       include <pwd.h>
41 #       include <grp.h>
42 #endif /* _WIN32 */
43
44 using namespace icinga;
45 namespace po = boost::program_options;
46
47 #ifdef _WIN32
48 SERVICE_STATUS l_SvcStatus;
49 SERVICE_STATUS_HANDLE l_SvcStatusHandle;
50 #endif /* _WIN32 */
51
52 static std::vector<String> GetLogLevelCompletionSuggestions(const String& arg)
53 {
54         std::vector<String> result;
55         
56         String debugLevel = "debug";
57         if (debugLevel.Find(arg) == 0)
58                 result.push_back(debugLevel);
59
60         String noticeLevel = "notice";
61         if (noticeLevel.Find(arg) == 0)
62                 result.push_back(noticeLevel);
63
64         String informationLevel = "information";
65         if (informationLevel.Find(arg) == 0)
66                 result.push_back(informationLevel);
67
68         String warningLevel = "warning";
69         if (warningLevel.Find(arg) == 0)
70                 result.push_back(warningLevel);
71
72         String criticalLevel = "critical";
73         if (criticalLevel.Find(arg) == 0)
74                 result.push_back(criticalLevel);
75
76         return result;
77 }
78
79 static std::vector<String> GlobalArgumentCompletion(const String& argument, const String& word)
80 {
81         if (argument == "include")
82                 return GetBashCompletionSuggestions("directory", word);
83         else if (argument == "log-level")
84                 return GetLogLevelCompletionSuggestions(word);
85         else
86                 return std::vector<String>();
87 }
88
89 int Main(void)
90 {
91         int argc = Application::GetArgC();
92         char **argv = Application::GetArgV();
93
94         bool autocomplete = false;
95         int autoindex = 0;
96
97         if (argc >= 4 && strcmp(argv[1], "--autocomplete") == 0) {
98                 autocomplete = true;
99                 autoindex = Convert::ToLong(argv[2]);
100                 argc -= 3;
101                 argv += 3;
102         }
103
104         Application::SetStartTime(Utility::GetTime());
105
106         if (!autocomplete)
107                 Application::SetResourceLimits();
108
109         /* Set thread title. */
110         Utility::SetThreadName("Main Thread", false);
111
112         /* Install exception handlers to make debugging easier. */
113         Application::InstallExceptionHandlers();
114
115 #ifdef _WIN32
116         bool builtinPaths = true;
117
118         HKEY hKey;
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;
123                 DWORD lType;
124                 if (RegQueryValueEx(hKey, NULL, NULL, &lType, pvData, &cbData) == ERROR_SUCCESS && lType == REG_SZ) {
125                         pvData[cbData] = '\0';
126
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");
134
135                         builtinPaths = false;
136                 }
137
138                 RegCloseKey(hKey);
139         }
140
141         if (builtinPaths) {
142                 Log(LogWarning, "icinga-app", "Registry key could not be read. Falling back to built-in paths.");
143
144 #endif /* _WIN32 */
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);
151 #ifdef _WIN32
152         }
153 #endif /* _WIN32 */
154
155         Application::DeclareZonesDir(Application::GetSysconfDir() + "/icinga2/zones.d");
156         Application::DeclareApplicationType("icinga/IcingaApplication");
157         Application::DeclareRunAsUser(ICINGA_USER);
158         Application::DeclareRunAsGroup(ICINGA_GROUP);
159
160         LogSeverity logLevel = Logger::GetConsoleLogSeverity();
161         Logger::SetConsoleLogSeverity(LogWarning);
162
163         Utility::LoadExtensionLibrary("cli");
164
165         po::options_description visibleDesc("Global options");
166
167         visibleDesc.add_options()
168                 ("help,h", "show this help message")
169                 ("version,V", "show version information")
170 #ifndef _WIN32
171                 ("color", "use VT100 color codes even when stdout is not a terminal")
172 #endif /* _WIN32 */
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");
177
178         po::options_description hiddenDesc("Hidden options");
179
180         hiddenDesc.add_options()
181 #ifndef _WIN32
182                 ("no-stack-rlimit", "used internally, do not specify manually")
183 #else /* _WIN32 */
184                 ("no-stack-rlimit", "used internally, do not specify manually")
185 #endif /* _WIN32 */
186                 ("arg", po::value<std::vector<std::string> >(), "positional argument");
187
188         po::positional_options_description positionalDesc;
189         positionalDesc.add("arg", -1);
190
191         String cmdname;
192         CLICommand::Ptr command;
193         po::variables_map vm;
194
195         try {
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();
201                 return EXIT_FAILURE;
202         }
203
204         String initconfig = Application::GetSysconfDir() + "/icinga2/init.conf";
205
206         if (Utility::PathExists(initconfig)) {
207                 ConfigCompilerContext::GetInstance()->Reset();
208                 ConfigCompiler::CompileFile(initconfig);
209         }
210
211 #ifndef _WIN32
212         if (vm.count("color")) {
213                 Console::SetType(std::cout, Console_VT100);
214                 Console::SetType(std::cerr, Console_VT100);
215         }
216 #endif /* _WIN32 */
217
218         if (vm.count("define")) {
219                 BOOST_FOREACH(const String& define, vm["define"].as<std::vector<std::string> >()) {
220                         String key, value;
221                         size_t pos = define.FindFirstOf('=');
222                         if (pos != String::NPos) {
223                                 key = define.SubStr(0, pos);
224                                 value = define.SubStr(pos + 1);
225                         } else {
226                                 key = define;
227                                 value = "1";
228                         }
229                         ScriptVariable::Set(key, value);
230                 }
231         }
232
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");
237
238         ConfigCompiler::AddIncludeSearchDir(Application::GetIncludeConfDir());
239
240         if (!autocomplete && vm.count("include")) {
241                 BOOST_FOREACH(const String& includePath, vm["include"].as<std::vector<std::string> >()) {
242                         ConfigCompiler::AddIncludeSearchDir(includePath);
243                 }
244         }
245
246         if (!autocomplete) {
247                 Logger::SetConsoleLogSeverity(logLevel);
248
249                 if (vm.count("log-level")) {
250                         String severity = vm["log-level"].as<std::string>();
251
252                         LogSeverity logLevel = LogInformation;
253                         try {
254                                 logLevel = Logger::StringToSeverity(severity);
255                         } catch (std::exception&) {
256                                 /* use the default */
257                                 Log(LogWarning, "icinga", "Invalid log level set. Using default 'information'.");
258                         }
259
260                         Logger::SetConsoleLogSeverity(logLevel);
261                 }
262
263                 if (vm.count("library")) {
264                         BOOST_FOREACH(const String& libraryName, vm["library"].as<std::vector<std::string> >()) {
265                                 (void)Utility::LoadExtensionLibrary(libraryName);
266                         }
267                 }
268
269                 if (!command || vm.count("help") || vm.count("version")) {
270                         String appName = Utility::BaseName(Application::GetArgV()[0]);
271
272                         if (appName.GetLength() > 3 && appName.SubStr(0, 3) == "lt-")
273                                 appName = appName.SubStr(3, appName.GetLength() - 3);
274
275                         std::cout << appName << " " << "- The Icinga 2 network monitoring daemon (version: "
276                             << Application::GetVersion()
277 #ifdef _DEBUG
278                             << "; debug"
279 #endif /* _DEBUG */
280                             << ")" << std::endl << std::endl;
281
282                         if (!command || vm.count("help")) {
283                                 std::cout << "Usage:" << std::endl
284                                     << "  " << argv[0] << " ";
285
286                                 if (cmdname.IsEmpty())
287                                         std::cout << "<command>";
288                                 else
289                                         std::cout << cmdname;
290
291                                 std::cout << " [<arguments>]" << std::endl;
292
293                                 if (command) {
294                                         std::cout << std::endl
295                                                   << command->GetDescription() << std::endl;
296                                 }
297                         }
298
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.";
304                         }
305
306                         std::cout << std::endl;
307
308                         if (vm.count("version")) {
309                                 std::cout << std::endl;
310
311                                 Application::DisplayInfoMessage(true);
312
313                                 return EXIT_SUCCESS;
314                         }
315                 }
316
317                 if (!command || vm.count("help")) {
318                         if (!command)
319                                 CLICommand::ShowCommands(argc, argv, NULL);
320
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;
324                         return EXIT_SUCCESS;
325                 }
326         }
327
328         int rc = 1;
329
330         if (autocomplete) {
331                 CLICommand::ShowCommands(argc, argv, &visibleDesc, &hiddenDesc,
332                     &GlobalArgumentCompletion, true, autoindex);
333                 rc = 0;
334         } else if (command) {
335                 Logger::DisableTimestamp(true);
336 #ifndef _WIN32
337                 if (command->GetImpersonationLevel() == ImpersonateRoot) {
338                         if (getuid() != 0) {
339                                 Log(LogCritical, "cli", "This command must be run as root.");
340                                 return 0;
341                         }
342                 } else if (command && command->GetImpersonationLevel() == ImpersonateIcinga) {
343                         String group = Application::GetRunAsGroup();
344         
345                         errno = 0;
346                         struct group *gr = getgrnam(group.CStr());
347         
348                         if (!gr) {
349                                 if (errno == 0) {
350                                         Log(LogCritical, "cli")
351                                             << "Invalid group specified: " << group;
352                                         return EXIT_FAILURE;
353                                 } else {
354                                         Log(LogCritical, "cli")
355                                             << "getgrnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
356                                         return EXIT_FAILURE;
357                                 }
358                         }
359         
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) << "\"";
364                                         return EXIT_FAILURE;
365                                 }
366         
367                                 if (setgid(gr->gr_gid) < 0) {
368                                         Log(LogCritical, "cli")
369                                             << "setgid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
370                                         return EXIT_FAILURE;
371                                 }
372                         }
373         
374                         String user = Application::GetRunAsUser();
375         
376                         errno = 0;
377                         struct passwd *pw = getpwnam(user.CStr());
378         
379                         if (!pw) {
380                                 if (errno == 0) {
381                                         Log(LogCritical, "cli")
382                                             << "Invalid user specified: " << user;
383                                         return EXIT_FAILURE;
384                                 } else {
385                                         Log(LogCritical, "cli")
386                                             << "getpwnam() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
387                                         return EXIT_FAILURE;
388                                 }
389                         }
390         
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) << "\"";
396                                         return EXIT_FAILURE;
397                                 }
398         
399                                 if (setuid(pw->pw_uid) < 0) {
400                                         Log(LogCritical, "cli")
401                                             << "setuid() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
402                                         return EXIT_FAILURE;
403                                 }
404                         }
405                 }
406 #endif /* _WIN32 */
407
408                 std::vector<std::string> args;
409                 if (vm.count("arg"))
410                         args = vm["arg"].as<std::vector<std::string> >();
411
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" : "") << ".";
416                         return EXIT_FAILURE;
417                 }
418
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.";
423                         return EXIT_FAILURE;
424                 }
425
426                 rc = command->Run(vm, args);
427         }
428
429         return rc;
430 }
431
432 #ifdef _WIN32
433 static int SetupService(bool install, int argc, char **argv)
434 {
435         SC_HANDLE schSCManager = OpenSCManager(
436                 NULL,
437                 NULL,
438                 SC_MANAGER_ALL_ACCESS);
439
440         if (NULL == schSCManager) {
441                 printf("OpenSCManager failed (%d)\n", GetLastError());
442                 return 1;
443         }
444
445         TCHAR szPath[MAX_PATH];
446
447         if (!GetModuleFileName(NULL, szPath, MAX_PATH)) {
448                 printf("Cannot install service (%d)\n", GetLastError());
449                 return 1;
450         }
451
452         String szArgs;
453         szArgs = Utility::EscapeShellArg(szPath) + " --scm";
454
455         for (int i = 0; i < argc; i++)
456                 szArgs += " " + Utility::EscapeShellArg(argv[i]);
457
458         SC_HANDLE schService = OpenService(schSCManager, "icinga2", DELETE | SERVICE_STOP | SERVICE_QUERY_STATUS);
459
460         if (schService != NULL) {
461                 SERVICE_STATUS status;
462                 ControlService(schService, SERVICE_CONTROL_STOP, &status);
463
464                 double start = Utility::GetTime();
465                 while (status.dwCurrentState != SERVICE_STOPPED) {
466                         double end = Utility::GetTime();
467
468                         if (end - start > 30) {
469                                 printf("Could not stop the service.\n");
470                                 break;
471                         }
472
473                         Utility::Sleep(5);
474
475                         if (!QueryServiceStatus(schService, &status)) {
476                                 printf("QueryServiceStatus failed (%d)\n", GetLastError());
477                                 return 1;
478                         }
479                 }
480
481                 if (!DeleteService(schService)) {
482                         printf("DeleteService failed (%d)\n", GetLastError());
483                         CloseServiceHandle(schService);
484                         CloseServiceHandle(schSCManager);
485                         return 1;
486                 }
487
488                 if (!install)
489                         printf("Service uninstalled successfully\n");
490
491                 CloseServiceHandle(schService);
492         }
493
494         if (install) {
495                 schService = CreateService(
496                         schSCManager,
497                         "icinga2",
498                         "Icinga 2",
499                         SERVICE_ALL_ACCESS,
500                         SERVICE_WIN32_OWN_PROCESS,
501                         SERVICE_DEMAND_START,
502                         SERVICE_ERROR_NORMAL,
503                         szArgs.CStr(),
504                         NULL,
505                         NULL,
506                         NULL,
507                         "NT AUTHORITY\\NetworkService",
508                         NULL);
509
510                 if (schService == NULL) {
511                         printf("CreateService failed (%d)\n", GetLastError());
512                         CloseServiceHandle(schSCManager);
513                         return 1;
514                 } else
515                         printf("Service installed successfully\n");
516
517                 ChangeServiceConfig(schService, SERVICE_NO_CHANGE, SERVICE_AUTO_START,
518                     SERVICE_ERROR_NORMAL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
519
520                 SERVICE_DESCRIPTION sdDescription = { "The Icinga 2 monitoring application" };
521                 ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription);
522
523                 if (!StartService(schService, 0, NULL)) {
524                         printf("StartService failed (%d)\n", GetLastError());
525                         CloseServiceHandle(schService);
526                         CloseServiceHandle(schSCManager);
527                         return 1;
528                 }
529
530                 CloseServiceHandle(schService);
531         }
532
533         CloseServiceHandle(schSCManager);
534
535         return 0;
536 }
537
538 VOID ReportSvcStatus(DWORD dwCurrentState,
539         DWORD dwWin32ExitCode,
540         DWORD dwWaitHint)
541 {
542         static DWORD dwCheckPoint = 1;
543
544         l_SvcStatus.dwCurrentState = dwCurrentState;
545         l_SvcStatus.dwWin32ExitCode = dwWin32ExitCode;
546         l_SvcStatus.dwWaitHint = dwWaitHint;
547
548         if (dwCurrentState == SERVICE_START_PENDING)
549                 l_SvcStatus.dwControlsAccepted = 0;
550         else
551                 l_SvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
552
553         if ((dwCurrentState == SERVICE_RUNNING) ||
554             (dwCurrentState == SERVICE_STOPPED))
555                 l_SvcStatus.dwCheckPoint = 0;
556         else
557                 l_SvcStatus.dwCheckPoint = dwCheckPoint++;
558
559         SetServiceStatus(l_SvcStatusHandle, &l_SvcStatus);
560 }
561
562 VOID WINAPI ServiceControlHandler(DWORD dwCtrl)
563 {
564         if (dwCtrl == SERVICE_CONTROL_STOP) {
565                 ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
566                 Application::RequestShutdown();
567         }
568 }
569
570 VOID WINAPI ServiceMain(DWORD argc, LPSTR *argv)
571 {
572         l_SvcStatusHandle = RegisterServiceCtrlHandler(
573                 "icinga2",
574                 ServiceControlHandler);
575
576         l_SvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
577         l_SvcStatus.dwServiceSpecificExitCode = 0;
578
579         ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
580
581         int rc = Main();
582
583         ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, rc);
584
585         Application::Exit(rc);
586 }
587 #endif /* _WIN32 */
588
589 /**
590 * Entry point for the Icinga application.
591 *
592 * @params argc Number of command line arguments.
593 * @params argv Command line arguments.
594 * @returns The application's exit status.
595 */
596 int main(int argc, char **argv)
597 {
598         /* must be called before using any other libbase functions */
599         Application::InitializeBase();
600
601         /* Set command-line arguments. */
602         Application::SetArgC(argc);
603         Application::SetArgV(argv);
604
605 #ifdef _WIN32
606         if (argc > 1 && strcmp(argv[1], "--scm-install") == 0) {
607                 return SetupService(true, argc - 2, &argv[2]);
608         }
609
610         if (argc > 1 && strcmp(argv[1], "--scm-uninstall") == 0) {
611                 return SetupService(false, argc - 2, &argv[2]);
612         }
613
614         if (argc > 1 && strcmp(argv[1], "--scm") == 0) {
615                 SERVICE_TABLE_ENTRY dispatchTable[] = {
616                         { "icinga2", ServiceMain },
617                         { NULL, NULL }
618                 };
619
620                 StartServiceCtrlDispatcher(dispatchTable);
621                 Application::Exit(1);
622         }
623 #endif /* _WIN32 */
624
625         int rc = Main();
626
627         Application::Exit(rc);
628 }