]> granicus.if.org Git - icinga2/blob - lib/base/application.cpp
e5e9caed661ce035aea78887c7051b1ac32dc150
[icinga2] / lib / base / application.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2015 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 "base/application.hpp"
21 #include "base/application.tcpp"
22 #include "base/stacktrace.hpp"
23 #include "base/timer.hpp"
24 #include "base/logger.hpp"
25 #include "base/exception.hpp"
26 #include "base/objectlock.hpp"
27 #include "base/utility.hpp"
28 #include "base/loader.hpp"
29 #include "base/debug.hpp"
30 #include "base/type.hpp"
31 #include "base/convert.hpp"
32 #include "base/scriptglobal.hpp"
33 #include "base/process.hpp"
34 #include <boost/algorithm/string/classification.hpp>
35 #include <boost/foreach.hpp>
36 #include <boost/algorithm/string/split.hpp>
37 #include <boost/algorithm/string/trim.hpp>
38 #include <boost/exception/errinfo_api_function.hpp>
39 #include <boost/exception/errinfo_errno.hpp>
40 #include <boost/exception/errinfo_file_name.hpp>
41 #include <sstream>
42 #include <iostream>
43 #include <fstream>
44 #ifdef __linux__
45 #include <sys/prctl.h>
46 #endif /* __linux__ */
47
48 using namespace icinga;
49
50 REGISTER_TYPE(Application);
51
52 boost::signals2::signal<void (void)> Application::OnReopenLogs;
53 Application::Ptr Application::m_Instance = NULL;
54 bool Application::m_ShuttingDown = false;
55 bool Application::m_RequestRestart = false;
56 bool Application::m_RequestReopenLogs = false;
57 pid_t Application::m_ReloadProcess = 0;
58 static bool l_Restarting = false;
59 static bool l_InExceptionHandler = false;
60 int Application::m_ArgC;
61 char **Application::m_ArgV;
62 double Application::m_StartTime;
63 bool Application::m_ScriptDebuggerEnabled = false;
64
65 /**
66  * Constructor for the Application class.
67  */
68 void Application::OnConfigLoaded(void)
69 {
70         m_PidFile = NULL;
71
72         ASSERT(m_Instance == NULL);
73         m_Instance = this;
74 }
75
76 /**
77  * Destructor for the application class.
78  */
79 void Application::Stop(bool runtimeRemoved)
80 {
81         m_ShuttingDown = true;
82
83 #ifdef _WIN32
84         WSACleanup();
85 #endif /* _WIN32 */
86
87         // Getting a shutdown-signal when a restart is in progress usually
88         // means that the restart succeeded and the new process wants to take
89         // over. Write the PID of the new process to the pidfile before this
90         // process exits to keep systemd happy.
91         if (l_Restarting) {
92                 try {
93                         UpdatePidFile(GetPidPath(), m_ReloadProcess);
94                 } catch (const std::exception&) {
95                         /* abort restart */
96                         Log(LogCritical, "Application", "Cannot update PID file. Aborting restart operation.");
97                         return;
98                 }
99                 ClosePidFile(false);
100         } else
101                 ClosePidFile(true);
102
103         ObjectImpl<Application>::Stop(runtimeRemoved);
104 }
105
106 Application::~Application(void)
107 {
108         m_Instance = NULL;
109 }
110
111 void Application::Exit(int rc)
112 {
113         std::cout.flush();
114         std::cerr.flush();
115
116         BOOST_FOREACH(const Logger::Ptr& logger, Logger::GetLoggers()) {
117                 logger->Flush();
118         }
119
120         UninitializeBase();
121 #ifdef I2_DEBUG
122         exit(rc);
123 #else /* I2_DEBUG */
124         _exit(rc); // Yay, our static destructors are pretty much beyond repair at this point.
125 #endif /* I2_DEBUG */
126 }
127
128 void Application::InitializeBase(void)
129 {
130 #ifdef _WIN32
131         /* disable GUI-based error messages for LoadLibrary() */
132         SetErrorMode(SEM_FAILCRITICALERRORS);
133
134         WSADATA wsaData;
135         if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
136                 BOOST_THROW_EXCEPTION(win32_error()
137                         << boost::errinfo_api_function("WSAStartup")
138                         << errinfo_win32_error(WSAGetLastError()));
139         }
140 #endif /* _WIN32 */
141
142         Loader::ExecuteDeferredInitializers();
143
144         /* make sure the thread pool gets initialized */
145         GetTP().Start();
146
147         Timer::Initialize();
148 }
149
150 void Application::UninitializeBase(void)
151 {
152         Timer::Uninitialize();
153
154         GetTP().Stop();
155 }
156
157 /**
158  * Retrieves a pointer to the application singleton object.
159  *
160  * @returns The application object.
161  */
162 Application::Ptr Application::GetInstance(void)
163 {
164         return m_Instance;
165 }
166
167 void Application::SetResourceLimits(void)
168 {
169 #ifdef __linux__
170         rlimit rl;
171
172 #       ifdef RLIMIT_NOFILE
173         rl.rlim_cur = 16 * 1024;
174         rl.rlim_max = rl.rlim_cur;
175
176         if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
177                 Log(LogNotice, "Application", "Could not adjust resource limit for open file handles (RLIMIT_NOFILE)");
178 #       else /* RLIMIT_NOFILE */
179         Log(LogNotice, "Application", "System does not support adjusting the resource limit for open file handles (RLIMIT_NOFILE)");
180 #       endif /* RLIMIT_NOFILE */
181
182 #       ifdef RLIMIT_NPROC
183         rl.rlim_cur = 16 * 1024;
184         rl.rlim_max = rl.rlim_cur;
185
186         if (setrlimit(RLIMIT_NPROC, &rl) < 0)
187                 Log(LogNotice, "Application", "Could not adjust resource limit for number of processes (RLIMIT_NPROC)");
188 #       else /* RLIMIT_NPROC */
189         Log(LogNotice, "Application", "System does not support adjusting the resource limit for number of processes (RLIMIT_NPROC)");
190 #       endif /* RLIMIT_NPROC */
191
192 #       ifdef RLIMIT_STACK
193         int argc = Application::GetArgC();
194         char **argv = Application::GetArgV();
195         bool set_stack_rlimit = true;
196
197         for (int i = 0; i < argc; i++) {
198                 if (strcmp(argv[i], "--no-stack-rlimit") == 0) {
199                         set_stack_rlimit = false;
200                         break;
201                 }
202         }
203
204         if (getrlimit(RLIMIT_STACK, &rl) < 0) {
205                 Log(LogWarning, "Application", "Could not determine resource limit for stack size (RLIMIT_STACK)");
206                 rl.rlim_max = RLIM_INFINITY;
207         }
208
209         if (set_stack_rlimit)
210                 rl.rlim_cur = 256 * 1024;
211         else
212                 rl.rlim_cur = rl.rlim_max;
213
214         if (setrlimit(RLIMIT_STACK, &rl) < 0)
215                 Log(LogNotice, "Application", "Could not adjust resource limit for stack size (RLIMIT_STACK)");
216         else if (set_stack_rlimit) {
217                 char **new_argv = static_cast<char **>(malloc(sizeof(char *) * (argc + 2)));
218
219                 if (!new_argv) {
220                         perror("malloc");
221                         Exit(EXIT_FAILURE);
222                 }
223
224                 new_argv[0] = argv[0];
225                 new_argv[1] = strdup("--no-stack-rlimit");
226
227                 if (!new_argv[1]) {
228                         perror("strdup");
229                         exit(1);
230                 }
231
232                 for (int i = 1; i < argc; i++)
233                         new_argv[i + 1] = argv[i];
234
235                 new_argv[argc + 1] = NULL;
236
237                 (void) execvp(new_argv[0], new_argv);
238                 perror("execvp");
239                 _exit(EXIT_FAILURE);
240         }
241 #       else /* RLIMIT_STACK */
242         Log(LogNotice, "Application", "System does not support adjusting the resource limit for stack size (RLIMIT_STACK)");
243 #       endif /* RLIMIT_STACK */
244 #endif /* __linux__ */
245 }
246
247 int Application::GetArgC(void)
248 {
249         return m_ArgC;
250 }
251
252 void Application::SetArgC(int argc)
253 {
254         m_ArgC = argc;
255 }
256
257 char **Application::GetArgV(void)
258 {
259         return m_ArgV;
260 }
261
262 void Application::SetArgV(char **argv)
263 {
264         m_ArgV = argv;
265 }
266
267 /**
268  * Processes events for registered sockets and timers and calls whatever
269  * handlers have been set up for these events.
270  */
271 void Application::RunEventLoop(void)
272 {
273         Timer::Initialize();
274
275         double lastLoop = Utility::GetTime();
276
277 mainloop:
278         while (!m_ShuttingDown && !m_RequestRestart) {
279                 /* Watches for changes to the system time. Adjusts timers if necessary. */
280                 Utility::Sleep(2.5);
281
282                 if (m_RequestReopenLogs) {
283                         Log(LogNotice, "Application", "Reopening log files");
284                         m_RequestReopenLogs = false;
285                         OnReopenLogs();
286                 }
287
288                 double now = Utility::GetTime();
289                 double timeDiff = lastLoop - now;
290
291                 if (std::fabs(timeDiff) > 15) {
292                         /* We made a significant jump in time. */
293                         Log(LogInformation, "Application")
294                             << "We jumped "
295                             << (timeDiff < 0 ? "forward" : "backward")
296                             << " in time: " << std::fabs(timeDiff) << " seconds";
297
298                         Timer::AdjustTimers(-timeDiff);
299                 }
300
301                 lastLoop = now;
302         }
303
304         if (m_RequestRestart) {
305                 m_RequestRestart = false;         // we are now handling the request, once is enough
306
307                 // are we already restarting? ignore request if we already are
308                 if (l_Restarting)
309                         goto mainloop;
310
311                 l_Restarting = true;
312                 m_ReloadProcess = StartReloadProcess();
313
314                 goto mainloop;
315         }
316
317         Log(LogInformation, "Application", "Shutting down...");
318
319         ConfigObject::StopObjects();
320         Application::GetInstance()->OnShutdown();
321
322         UninitializeBase();
323 }
324
325 void Application::OnShutdown(void)
326 {
327         /* Nothing to do here. */
328 }
329
330 static void ReloadProcessCallbackInternal(const ProcessResult& pr)
331 {
332         if (pr.ExitStatus != 0)
333                 Log(LogCritical, "Application", "Found error in config: reloading aborted");
334 #ifdef _WIN32
335         else
336                 Application::Exit(7); /* keep this exit code in sync with icinga-app */
337 #endif /* _WIN32 */
338 }
339
340 static void ReloadProcessCallback(const ProcessResult& pr)
341 {
342         l_Restarting = false;
343
344         boost::thread t(boost::bind(&ReloadProcessCallbackInternal, pr));
345         t.detach();
346 }
347
348 pid_t Application::StartReloadProcess(void)
349 {
350         Log(LogInformation, "Application", "Got reload command: Starting new instance.");
351
352         // prepare arguments
353         Array::Ptr args = new Array();
354         args->Add(GetExePath(m_ArgV[0]));
355
356         for (int i=1; i < Application::GetArgC(); i++) {
357                 if (std::string(Application::GetArgV()[i]) != "--reload-internal")
358                         args->Add(Application::GetArgV()[i]);
359                 else
360                         i++;     // the next parameter after --reload-internal is the pid, remove that too
361         }
362
363 #ifndef _WIN32
364         args->Add("--reload-internal");
365         args->Add(Convert::ToString(Utility::GetPid()));
366 #else /* _WIN32 */
367         args->Add("--validate");
368 #endif /* _WIN32 */
369
370         Process::Ptr process = new Process(Process::PrepareCommand(args));
371         process->SetTimeout(300);
372         process->Run(&ReloadProcessCallback);
373
374         return process->GetPID();
375 }
376
377 /**
378  * Signals the application to shut down during the next
379  * execution of the event loop.
380  */
381 void Application::RequestShutdown(void)
382 {
383         Log(LogInformation, "Application", "Received request to shut down.");
384
385         m_ShuttingDown = true;
386 }
387
388 /**
389  * Signals the application to restart during the next
390  * execution of the event loop.
391  */
392 void Application::RequestRestart(void)
393 {
394         m_RequestRestart = true;
395 }
396
397 /**
398  * Signals the application to reopen log files during the
399  * next execution of the event loop.
400  */
401 void Application::RequestReopenLogs(void)
402 {
403         m_RequestReopenLogs = true;
404 }
405
406 /**
407  * Retrieves the full path of the executable.
408  *
409  * @param argv0 The first command-line argument.
410  * @returns The path.
411  */
412 String Application::GetExePath(const String& argv0)
413 {
414         String executablePath;
415
416 #ifndef _WIN32
417         char buffer[MAXPATHLEN];
418         if (getcwd(buffer, sizeof(buffer)) == NULL) {
419                 BOOST_THROW_EXCEPTION(posix_error()
420                     << boost::errinfo_api_function("getcwd")
421                     << boost::errinfo_errno(errno));
422         }
423
424         String workingDirectory = buffer;
425
426         if (argv0[0] != '/')
427                 executablePath = workingDirectory + "/" + argv0;
428         else
429                 executablePath = argv0;
430
431         bool foundSlash = false;
432         for (size_t i = 0; i < argv0.GetLength(); i++) {
433                 if (argv0[i] == '/') {
434                         foundSlash = true;
435                         break;
436                 }
437         }
438
439         if (!foundSlash) {
440                 const char *pathEnv = getenv("PATH");
441                 if (pathEnv != NULL) {
442                         std::vector<String> paths;
443                         boost::algorithm::split(paths, pathEnv, boost::is_any_of(":"));
444
445                         bool foundPath = false;
446                         BOOST_FOREACH(String& path, paths) {
447                                 String pathTest = path + "/" + argv0;
448
449                                 if (access(pathTest.CStr(), X_OK) == 0) {
450                                         executablePath = pathTest;
451                                         foundPath = true;
452                                         break;
453                                 }
454                         }
455
456                         if (!foundPath) {
457                                 executablePath.Clear();
458                                 BOOST_THROW_EXCEPTION(std::runtime_error("Could not determine executable path."));
459                         }
460                 }
461         }
462
463         if (realpath(executablePath.CStr(), buffer) == NULL) {
464                 BOOST_THROW_EXCEPTION(posix_error()
465                     << boost::errinfo_api_function("realpath")
466                     << boost::errinfo_errno(errno)
467                     << boost::errinfo_file_name(executablePath));
468         }
469
470         return buffer;
471 #else /* _WIN32 */
472         char FullExePath[MAXPATHLEN];
473
474         if (!GetModuleFileName(NULL, FullExePath, sizeof(FullExePath)))
475                 BOOST_THROW_EXCEPTION(win32_error()
476                     << boost::errinfo_api_function("GetModuleFileName")
477                     << errinfo_win32_error(GetLastError()));
478
479         return FullExePath;
480 #endif /* _WIN32 */
481 }
482
483 /**
484  * Display version and path information.
485  */
486 void Application::DisplayInfoMessage(std::ostream& os, bool skipVersion)
487 {
488         os << "Application information:" << "\n";
489
490         if (!skipVersion)
491                 os << "  Application version: " << GetAppVersion() << "\n";
492
493         os << "  Installation root: " << GetPrefixDir() << "\n"
494            << "  Sysconf directory: " << GetSysconfDir() << "\n"
495            << "  Run directory: " << GetRunDir() << "\n"
496            << "  Local state directory: " << GetLocalStateDir() << "\n"
497            << "  Package data directory: " << GetPkgDataDir() << "\n"
498            << "  State path: " << GetStatePath() << "\n"
499            << "  Modified attributes path: " << GetModAttrPath() << "\n"
500            << "  Objects path: " << GetObjectsPath() << "\n"
501            << "  Vars path: " << GetVarsPath() << "\n"
502            << "  PID path: " << GetPidPath() << "\n";
503
504         os << "\n"
505            << "System information:" << "\n"
506            << "  Platform: " << Utility::GetPlatformName() << "\n"
507            << "  Platform version: " << Utility::GetPlatformVersion() << "\n"
508            << "  Kernel: " << Utility::GetPlatformKernel() << "\n"
509            << "  Kernel version: " << Utility::GetPlatformKernelVersion() << "\n"
510            << "  Architecture: " << Utility::GetPlatformArchitecture() << "\n";
511 }
512
513 /**
514  * Displays a message that tells users what to do when they encounter a bug.
515  */
516 void Application::DisplayBugMessage(std::ostream& os)
517 {
518         os << "***" << "\n"
519            << "* This would indicate a runtime problem or configuration error. If you believe this is a bug in Icinga 2" << "\n"
520            << "* please submit a bug report at https://dev.icinga.org/ and include this stack trace as well as any other" << "\n"
521            << "* information that might be useful in order to reproduce this problem." << "\n"
522            << "***" << "\n";
523 }
524
525 String Application::GetCrashReportFilename(void)
526 {
527         return GetLocalStateDir() + "/log/icinga2/crash/report." + Convert::ToString(Utility::GetTime());
528 }
529
530
531 void Application::AttachDebugger(const String& filename, bool interactive)
532 {
533 #ifndef _WIN32
534 #ifdef __linux__
535         prctl(PR_SET_DUMPABLE, 1);
536 #endif /* __linux __ */
537
538         String my_pid = Convert::ToString(Utility::GetPid());
539
540         pid_t pid = fork();
541
542         if (pid < 0) {
543                 BOOST_THROW_EXCEPTION(posix_error()
544                     << boost::errinfo_api_function("fork")
545                     << boost::errinfo_errno(errno));
546         }
547
548         if (pid == 0) {
549                 if (!interactive) {
550                         int fd = open(filename.CStr(), O_CREAT | O_RDWR | O_APPEND, 0600);
551
552                         if (fd < 0) {
553                                 BOOST_THROW_EXCEPTION(posix_error()
554                                     << boost::errinfo_api_function("open")
555                                     << boost::errinfo_errno(errno)
556                                     << boost::errinfo_file_name(filename));
557                         }
558
559                         if (fd != 1) {
560                                 /* redirect stdout to the file */
561                                 dup2(fd, 1);
562                                 close(fd);
563                         }
564
565                         /* redirect stderr to stdout */
566                         if (fd != 2)
567                                 close(2);
568
569                         dup2(1, 2);
570                 }
571
572                 char **argv;
573                 char *my_pid_str = strdup(my_pid.CStr());
574
575                 if (interactive) {
576                         const char *uargv[] = {
577                                 "gdb",
578                                 "-p",
579                                 my_pid_str,
580                                 NULL
581                         };
582                         argv = const_cast<char **>(uargv);
583                 } else {
584                         const char *uargv[] = {
585                                 "gdb",
586                                 "--batch",
587                                 "-p",
588                                 my_pid_str,
589                                 "-ex",
590                                 "thread apply all bt full",
591                                 "-ex",
592                                 "detach",
593                                 "-ex",
594                                 "quit",
595                                 NULL
596                         };
597                         argv = const_cast<char **>(uargv);
598                 }
599
600                 (void)execvp(argv[0], argv);
601                 perror("Failed to launch GDB");
602                 free(my_pid_str);
603                 _exit(0);
604         }
605
606         int status;
607         if (waitpid(pid, &status, 0) < 0) {
608                 BOOST_THROW_EXCEPTION(posix_error()
609                     << boost::errinfo_api_function("waitpid")
610                     << boost::errinfo_errno(errno));
611         }
612
613 #ifdef __linux__
614         prctl(PR_SET_DUMPABLE, 0);
615 #endif /* __linux __ */
616 #else /* _WIN32 */
617         DebugBreak();
618 #endif /* _WIN32 */
619 }
620
621 #ifndef _WIN32
622 /**
623  * Signal handler for SIGINT and SIGTERM. Prepares the application for cleanly
624  * shutting down during the next execution of the event loop.
625  *
626  * @param - The signal number.
627  */
628 void Application::SigIntTermHandler(int signum)
629 {
630         struct sigaction sa;
631         memset(&sa, 0, sizeof(sa));
632         sa.sa_handler = SIG_DFL;
633         sigaction(signum, &sa, NULL);
634
635         Application::Ptr instance = Application::GetInstance();
636
637         if (!instance)
638                 return;
639
640         instance->RequestShutdown();
641 }
642 #endif /* _WIN32 */
643
644 /**
645  * Signal handler for SIGUSR1. This signal causes Icinga to re-open
646  * its log files and is mainly for use by logrotate.
647  *
648  * @param - The signal number.
649  */
650 void Application::SigUsr1Handler(int)
651 {
652         RequestReopenLogs();
653 }
654
655 /**
656  * Signal handler for SIGABRT. Helps with debugging ASSERT()s.
657  *
658  * @param - The signal number.
659  */
660 void Application::SigAbrtHandler(int)
661 {
662 #ifndef _WIN32
663         struct sigaction sa;
664         memset(&sa, 0, sizeof(sa));
665         sa.sa_handler = SIG_DFL;
666         sigaction(SIGABRT, &sa, NULL);
667 #endif /* _WIN32 */
668
669         std::cerr << "Caught SIGABRT." << std::endl
670                   << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << std::endl
671                   << std::endl;
672
673         String fname = GetCrashReportFilename();
674         Utility::MkDir(Utility::DirName(fname), 0750);
675
676         bool interactive_debugger = Convert::ToBool(ScriptGlobal::Get("AttachDebugger"));
677
678         if (!interactive_debugger) {
679                 std::ofstream ofs;
680                 ofs.open(fname.CStr());
681
682                 Log(LogCritical, "Application")
683                     << "Icinga 2 has terminated unexpectedly. Additional information can be found in '" << fname << "'" << "\n";
684
685                 DisplayInfoMessage(ofs);
686
687                 StackTrace trace;
688                 ofs << "Stacktrace:" << "\n";
689                 trace.Print(ofs, 1);
690
691                 DisplayBugMessage(ofs);
692
693                 ofs << "\n";
694                 ofs.close();
695         } else {
696                 Log(LogCritical, "Application", "Icinga 2 has terminated unexpeectedly. Attaching debugger...");
697         }
698
699         AttachDebugger(fname, interactive_debugger);
700 }
701
702 #ifdef _WIN32
703 /**
704  * Console control handler. Prepares the application for cleanly
705  * shutting down during the next execution of the event loop.
706  */
707 BOOL WINAPI Application::CtrlHandler(DWORD type)
708 {
709         Application::Ptr instance = Application::GetInstance();
710
711         if (!instance)
712                 return TRUE;
713
714         instance->RequestShutdown();
715
716         SetConsoleCtrlHandler(NULL, FALSE);
717         return TRUE;
718 }
719 #endif /* _WIN32 */
720
721 /**
722  * Handler for unhandled exceptions.
723  */
724 void Application::ExceptionHandler(void)
725 {
726         if (l_InExceptionHandler)
727                 for (;;)
728                         Utility::Sleep(5);
729
730         l_InExceptionHandler = true;
731
732 #ifndef _WIN32
733         struct sigaction sa;
734         memset(&sa, 0, sizeof(sa));
735         sa.sa_handler = SIG_DFL;
736         sigaction(SIGABRT, &sa, NULL);
737 #endif /* _WIN32 */
738
739         String fname = GetCrashReportFilename();
740         Utility::MkDir(Utility::DirName(fname), 0750);
741
742         bool interactive_debugger = Convert::ToBool(ScriptGlobal::Get("AttachDebugger"));
743
744         if (interactive_debugger) {
745                 std::ofstream ofs;
746                 ofs.open(fname.CStr());
747
748                 ofs << "Caught unhandled exception." << "\n"
749                     << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n"
750                     << "\n";
751
752                 DisplayInfoMessage(ofs);
753
754                 try {
755                         RethrowUncaughtException();
756                 } catch (const std::exception& ex) {
757                         Log(LogCritical, "Application")
758                             << DiagnosticInformation(ex, false) << "\n"
759                             << "\n"
760                             << "Additional information is available in '" << fname << "'" << "\n";
761
762                         ofs << "\n"
763                             << DiagnosticInformation(ex)
764                             << "\n";
765                 }
766
767                 DisplayBugMessage(ofs);
768
769                 ofs.close();
770         }
771
772         AttachDebugger(fname, interactive_debugger);
773
774         abort();
775 }
776
777 #ifdef _WIN32
778 LONG CALLBACK Application::SEHUnhandledExceptionFilter(PEXCEPTION_POINTERS exi)
779 {
780         if (l_InExceptionHandler)
781                 return EXCEPTION_CONTINUE_SEARCH;
782
783         l_InExceptionHandler = true;
784
785         String fname = GetCrashReportFilename();
786         Utility::MkDir(Utility::DirName(fname), 0750);
787
788         std::ofstream ofs;
789         ofs.open(fname.CStr());
790
791         Log(LogCritical, "Application")
792             << "Icinga 2 has terminated unexpectedly. Additional information can be found in '" << fname << "'";
793
794         DisplayInfoMessage(ofs);
795
796         ofs << "Caught unhandled SEH exception." << "\n"
797             << "Current time: " << Utility::FormatDateTime("%Y-%m-%d %H:%M:%S %z", Utility::GetTime()) << "\n"
798             << "\n";
799
800         StackTrace trace(exi);
801         ofs << "Stacktrace:" << "\n";
802         trace.Print(ofs, 1);
803
804         DisplayBugMessage(ofs);
805
806         return EXCEPTION_CONTINUE_SEARCH;
807 }
808 #endif /* _WIN32 */
809
810 /**
811  * Installs the exception handlers.
812  */
813 void Application::InstallExceptionHandlers(void)
814 {
815         std::set_terminate(&Application::ExceptionHandler);
816
817 #ifndef _WIN32
818         struct sigaction sa;
819         memset(&sa, 0, sizeof(sa));
820         sa.sa_handler = &Application::SigAbrtHandler;
821         sigaction(SIGABRT, &sa, NULL);
822 #else /* _WIN32 */
823         SetUnhandledExceptionFilter(&Application::SEHUnhandledExceptionFilter);
824 #endif /* _WIN32 */
825 }
826
827 /**
828  * Runs the application.
829  *
830  * @returns The application's exit code.
831  */
832 int Application::Run(void)
833 {
834 #ifndef _WIN32
835         struct sigaction sa;
836         memset(&sa, 0, sizeof(sa));
837         sa.sa_handler = &Application::SigIntTermHandler;
838         sigaction(SIGINT, &sa, NULL);
839         sigaction(SIGTERM, &sa, NULL);
840
841         sa.sa_handler = SIG_IGN;
842         sigaction(SIGPIPE, &sa, NULL);
843
844         sa.sa_handler = &Application::SigUsr1Handler;
845         sigaction(SIGUSR1, &sa, NULL);
846 #else /* _WIN32 */
847         SetConsoleCtrlHandler(&Application::CtrlHandler, TRUE);
848 #endif /* _WIN32 */
849
850         try {
851                 UpdatePidFile(GetPidPath());
852         } catch (const std::exception&) {
853                 Log(LogCritical, "Application")
854                     << "Cannot update PID file '" << GetPidPath() << "'. Aborting.";
855                 return EXIT_FAILURE;
856         }
857
858         return Main();
859 }
860
861 /**
862  * Grabs the PID file lock and updates the PID. Terminates the application
863  * if the PID file is already locked by another instance of the application.
864  *
865  * @param filename The name of the PID file.
866  * @param pid The PID to write; default is the current PID
867  */
868 void Application::UpdatePidFile(const String& filename, pid_t pid)
869 {
870         ObjectLock olock(this);
871
872         if (m_PidFile != NULL)
873                 fclose(m_PidFile);
874
875         /* There's just no sane way of getting a file descriptor for a
876          * C++ ofstream which is why we're using FILEs here. */
877         m_PidFile = fopen(filename.CStr(), "r+");
878
879         if (m_PidFile == NULL)
880                 m_PidFile = fopen(filename.CStr(), "w");
881
882         if (m_PidFile == NULL) {
883                 Log(LogCritical, "Application")
884                     << "Could not open PID file '" << filename << "'.";
885                 BOOST_THROW_EXCEPTION(std::runtime_error("Could not open PID file '" + filename + "'"));
886         }
887
888 #ifndef _WIN32
889         int fd = fileno(m_PidFile);
890
891         Utility::SetCloExec(fd);
892
893         struct flock lock;
894
895         lock.l_start = 0;
896         lock.l_len = 0;
897         lock.l_type = F_WRLCK;
898         lock.l_whence = SEEK_SET;
899
900         if (fcntl(fd, F_SETLK, &lock) < 0) {
901                 Log(LogCritical, "Application", "Could not lock PID file. Make sure that only one instance of the application is running.");
902
903                 Application::Exit(EXIT_FAILURE);
904         }
905
906         if (ftruncate(fd, 0) < 0) {
907                 Log(LogCritical, "Application")
908                     << "ftruncate() failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\"";
909
910                 BOOST_THROW_EXCEPTION(posix_error()
911                     << boost::errinfo_api_function("ftruncate")
912                     << boost::errinfo_errno(errno));
913         }
914 #endif /* _WIN32 */
915
916         fprintf(m_PidFile, "%lu\n", (unsigned long)pid);
917         fflush(m_PidFile);
918 }
919
920 /**
921  * Closes the PID file. Does nothing if the PID file is not currently open.
922  */
923 void Application::ClosePidFile(bool unlink)
924 {
925         ObjectLock olock(this);
926
927         if (m_PidFile != NULL)
928         {
929                 if (unlink) {
930                         String pidpath = GetPidPath();
931                         ::unlink(pidpath.CStr());
932                 }
933
934                 fclose(m_PidFile);
935         }
936
937         m_PidFile = NULL;
938 }
939
940 /**
941  * Checks if another process currently owns the pidfile and read it
942  *
943  * @param filename The name of the PID file.
944  * @returns 0: no process owning the pidfile, pid of the process otherwise
945  */
946 pid_t Application::ReadPidFile(const String& filename)
947 {
948         FILE *pidfile = fopen(filename.CStr(), "r");
949
950         if (pidfile == NULL)
951                 return 0;
952
953 #ifndef _WIN32
954         int fd = fileno(pidfile);
955
956         struct flock lock;
957
958         lock.l_start = 0;
959         lock.l_len = 0;
960         lock.l_type = F_WRLCK;
961         lock.l_whence = SEEK_SET;
962
963         if (fcntl(fd, F_GETLK, &lock) < 0) {
964                 int error = errno;
965                 fclose(pidfile);
966                 BOOST_THROW_EXCEPTION(posix_error()
967                     << boost::errinfo_api_function("fcntl")
968                     << boost::errinfo_errno(error));
969         }
970
971         if (lock.l_type == F_UNLCK) {
972                 // nobody has locked the file: no icinga running
973                 fclose(pidfile);
974                 return -1;
975         }
976 #endif /* _WIN32 */
977
978         pid_t runningpid;
979         int res = fscanf(pidfile, "%d", &runningpid);
980         fclose(pidfile);
981
982         // bogus result?
983         if (res != 1)
984                 return 0;
985
986 #ifdef _WIN32
987         HANDLE hProcess = OpenProcess(0, FALSE, runningpid);
988
989         if (!hProcess)
990                 return 0;
991
992         CloseHandle(hProcess);
993 #endif /* _WIN32 */
994
995         return runningpid;
996 }
997
998
999 /**
1000  * Retrieves the path of the installation prefix.
1001  *
1002  * @returns The path.
1003  */
1004 String Application::GetPrefixDir(void)
1005 {
1006         return ScriptGlobal::Get("PrefixDir");
1007 }
1008
1009 /**
1010  * Sets the path for the installation prefix.
1011  *
1012  * @param path The new path.
1013  */
1014 void Application::DeclarePrefixDir(const String& path)
1015 {
1016         if (!ScriptGlobal::Exists("PrefixDir"))
1017                 ScriptGlobal::Set("PrefixDir", path);
1018 }
1019
1020 /**
1021  * Retrives the path of the sysconf dir.
1022  *
1023  * @returns The path.
1024  */
1025 String Application::GetSysconfDir(void)
1026 {
1027         return ScriptGlobal::Get("SysconfDir");
1028 }
1029
1030 /**
1031  * Sets the path of the sysconf dir.
1032  *
1033  * @param path The new path.
1034  */
1035 void Application::DeclareSysconfDir(const String& path)
1036 {
1037         if (!ScriptGlobal::Exists("SysconfDir"))
1038                 ScriptGlobal::Set("SysconfDir", path);
1039 }
1040
1041 /**
1042  * Retrieves the path for the run dir.
1043  *
1044  * @returns The path.
1045  */
1046 String Application::GetRunDir(void)
1047 {
1048         return ScriptGlobal::Get("RunDir");
1049 }
1050
1051 /**
1052  * Sets the path of the run dir.
1053  *
1054  * @param path The new path.
1055  */
1056 void Application::DeclareRunDir(const String& path)
1057 {
1058         if (!ScriptGlobal::Exists("RunDir"))
1059                 ScriptGlobal::Set("RunDir", path);
1060 }
1061
1062 /**
1063  * Retrieves the path for the local state dir.
1064  *
1065  * @returns The path.
1066  */
1067 String Application::GetLocalStateDir(void)
1068 {
1069         return ScriptGlobal::Get("LocalStateDir");
1070 }
1071
1072 /**
1073  * Sets the path for the local state dir.
1074  *
1075  * @param path The new path.
1076  */
1077 void Application::DeclareLocalStateDir(const String& path)
1078 {
1079         if (!ScriptGlobal::Exists("LocalStateDir"))
1080                 ScriptGlobal::Set("LocalStateDir", path);
1081 }
1082
1083 /**
1084  * Retrieves the path for the local state dir.
1085  *
1086  * @returns The path.
1087  */
1088 String Application::GetZonesDir(void)
1089 {
1090         return ScriptGlobal::Get("ZonesDir", &Empty);
1091 }
1092
1093 /**
1094  * Sets the path of the zones dir.
1095  *
1096  * @param path The new path.
1097  */
1098 void Application::DeclareZonesDir(const String& path)
1099 {
1100         if (!ScriptGlobal::Exists("ZonesDir"))
1101                 ScriptGlobal::Set("ZonesDir", path);
1102 }
1103
1104 /**
1105  * Retrieves the path for the package data dir.
1106  *
1107  * @returns The path.
1108  */
1109 String Application::GetPkgDataDir(void)
1110 {
1111         String defaultValue = "";
1112         return ScriptGlobal::Get("PkgDataDir", &Empty);
1113 }
1114
1115 /**
1116  * Sets the path for the package data dir.
1117  *
1118  * @param path The new path.
1119  */
1120 void Application::DeclarePkgDataDir(const String& path)
1121 {
1122         if (!ScriptGlobal::Exists("PkgDataDir"))
1123                 ScriptGlobal::Set("PkgDataDir", path);
1124 }
1125
1126 /**
1127  * Retrieves the path for the include conf dir.
1128  *
1129  * @returns The path.
1130  */
1131 String Application::GetIncludeConfDir(void)
1132 {
1133         return ScriptGlobal::Get("IncludeConfDir", &Empty);
1134 }
1135
1136 /**
1137  * Sets the path for the package data dir.
1138  *
1139  * @param path The new path.
1140  */
1141 void Application::DeclareIncludeConfDir(const String& path)
1142 {
1143         if (!ScriptGlobal::Exists("IncludeConfDir"))
1144                 ScriptGlobal::Set("IncludeConfDir", path);
1145 }
1146
1147 /**
1148  * Retrieves the path for the state file.
1149  *
1150  * @returns The path.
1151  */
1152 String Application::GetStatePath(void)
1153 {
1154         return ScriptGlobal::Get("StatePath", &Empty);
1155 }
1156
1157 /**
1158  * Sets the path for the state file.
1159  *
1160  * @param path The new path.
1161  */
1162 void Application::DeclareStatePath(const String& path)
1163 {
1164         if (!ScriptGlobal::Exists("StatePath"))
1165                 ScriptGlobal::Set("StatePath", path);
1166 }
1167
1168 /**
1169  * Retrieves the path for the modified attributes file.
1170  *
1171  * @returns The path.
1172  */
1173 String Application::GetModAttrPath(void)
1174 {
1175         return ScriptGlobal::Get("ModAttrPath", &Empty);
1176 }
1177
1178 /**
1179  * Sets the path for the modified attributes file.
1180  *
1181  * @param path The new path.
1182  */
1183 void Application::DeclareModAttrPath(const String& path)
1184 {
1185         if (!ScriptGlobal::Exists("ModAttrPath"))
1186                 ScriptGlobal::Set("ModAttrPath", path);
1187 }
1188
1189 /**
1190  * Retrieves the path for the objects file.
1191  *
1192  * @returns The path.
1193  */
1194 String Application::GetObjectsPath(void)
1195 {
1196         return ScriptGlobal::Get("ObjectsPath", &Empty);
1197 }
1198
1199 /**
1200  * Sets the path for the objects file.
1201  *
1202  * @param path The new path.
1203  */
1204 void Application::DeclareObjectsPath(const String& path)
1205 {
1206         if (!ScriptGlobal::Exists("ObjectsPath"))
1207                 ScriptGlobal::Set("ObjectsPath", path);
1208 }
1209
1210 /**
1211 * Retrieves the path for the vars file.
1212 *
1213 * @returns The path.
1214 */
1215 String Application::GetVarsPath(void)
1216 {
1217         return ScriptGlobal::Get("VarsPath", &Empty);
1218 }
1219
1220 /**
1221 * Sets the path for the vars file.
1222 *
1223 * @param path The new path.
1224 */
1225 void Application::DeclareVarsPath(const String& path)
1226 {
1227         if (!ScriptGlobal::Exists("VarsPath"))
1228                 ScriptGlobal::Set("VarsPath", path);
1229 }
1230
1231 /**
1232  * Retrieves the path for the PID file.
1233  *
1234  * @returns The path.
1235  */
1236 String Application::GetPidPath(void)
1237 {
1238         return ScriptGlobal::Get("PidPath", &Empty);
1239 }
1240
1241 /**
1242  * Sets the path for the PID file.
1243  *
1244  * @param path The new path.
1245  */
1246 void Application::DeclarePidPath(const String& path)
1247 {
1248         if (!ScriptGlobal::Exists("PidPath"))
1249                 ScriptGlobal::Set("PidPath", path);
1250 }
1251
1252 /**
1253  * Retrieves the name of the user.
1254  *
1255  * @returns The name.
1256  */
1257 String Application::GetRunAsUser(void)
1258 {
1259         return ScriptGlobal::Get("RunAsUser");
1260 }
1261
1262 /**
1263  * Sets the name of the user.
1264  *
1265  * @param path The new user name.
1266  */
1267 void Application::DeclareRunAsUser(const String& user)
1268 {
1269         if (!ScriptGlobal::Exists("RunAsUser"))
1270                 ScriptGlobal::Set("RunAsUser", user);
1271 }
1272
1273 /**
1274  * Retrieves the name of the group.
1275  *
1276  * @returns The name.
1277  */
1278 String Application::GetRunAsGroup(void)
1279 {
1280         return ScriptGlobal::Get("RunAsGroup");
1281 }
1282
1283 /**
1284  * Sets the concurrency level.
1285  *
1286  * @param path The new concurrency level.
1287  */
1288 void Application::DeclareConcurrency(int ncpus)
1289 {
1290         if (!ScriptGlobal::Exists("Concurrency"))
1291                 ScriptGlobal::Set("Concurrency", ncpus);
1292 }
1293
1294 /**
1295  * Retrieves the concurrency level.
1296  *
1297  * @returns The concurrency level.
1298  */
1299 int Application::GetConcurrency(void)
1300 {
1301         Value defaultConcurrency = boost::thread::hardware_concurrency();
1302         return ScriptGlobal::Get("Concurrency", &defaultConcurrency);
1303 }
1304
1305 /**
1306  * Sets the name of the group.
1307  *
1308  * @param path The new group name.
1309  */
1310 void Application::DeclareRunAsGroup(const String& group)
1311 {
1312         if (!ScriptGlobal::Exists("RunAsGroup"))
1313                 ScriptGlobal::Set("RunAsGroup", group);
1314 }
1315
1316 /**
1317  * Returns the global thread pool.
1318  *
1319  * @returns The global thread pool.
1320  */
1321 ThreadPool& Application::GetTP(void)
1322 {
1323         static ThreadPool tp;
1324         return tp;
1325 }
1326
1327 double Application::GetStartTime(void)
1328 {
1329         return m_StartTime;
1330 }
1331
1332 void Application::SetStartTime(double ts)
1333 {
1334         m_StartTime = ts;
1335 }
1336
1337 bool Application::GetScriptDebuggerEnabled(void)
1338 {
1339         return m_ScriptDebuggerEnabled;
1340 }
1341
1342 void Application::SetScriptDebuggerEnabled(bool enabled)
1343 {
1344         m_ScriptDebuggerEnabled = enabled;
1345 }
1346
1347 void Application::ValidateName(const String& value, const ValidationUtils& utils)
1348 {
1349         ObjectImpl<Application>::ValidateName(value, utils);
1350
1351         if (value != "app")
1352                 BOOST_THROW_EXCEPTION(ValidationError(this, boost::assign::list_of("name"), "Application object must be named 'app'."));
1353 }