1 /******************************************************************************
3 * Copyright (C) 2012 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 ******************************************************************************/
26 using namespace icinga;
28 Application::Ptr I2_EXPORT Application::m_Instance;
29 bool I2_EXPORT Application::m_ShuttingDown = false;
30 bool I2_EXPORT Application::m_Debugging = false;
33 * Constructor for the Application class.
35 Application::Application(void)
39 if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
40 throw Win32Exception("WSAStartup failed", WSAGetLastError());
45 char *debugging = getenv("_DEBUG");
46 m_Debugging = (debugging && strtol(debugging, NULL, 10) != 0);
49 if (IsDebuggerPresent())
55 * Destructor for the application class.
57 Application::~Application(void)
59 m_ShuttingDown = true;
61 /* stop all components */
62 for (map<string, Component::Ptr>::iterator i = m_Components.begin();
63 i != m_Components.end(); i++) {
77 * Retrieves a pointer to the application singleton object.
79 * @returns The application object.
81 Application::Ptr Application::GetInstance(void)
84 return Application::Ptr();
90 * Processes events for registered sockets and timers and calls whatever
91 * handlers have been set up for these events.
93 void Application::RunEventLoop(void)
95 while (!m_ShuttingDown) {
96 fd_set readfds, writefds, exceptfds;
99 Timer::CallExpiredTimers();
105 Socket::CollectionType::iterator prev, i;
106 for (i = Socket::Sockets.begin();
107 i != Socket::Sockets.end(); ) {
108 Socket::Ptr socket = i->lock();
114 Socket::Sockets.erase(prev);
118 int fd = socket->GetFD();
120 if (socket->WantsToWrite())
121 FD_SET(fd, &writefds);
123 if (socket->WantsToRead())
124 FD_SET(fd, &readfds);
126 FD_SET(fd, &exceptfds);
132 time_t now = time(NULL);
133 time_t next = Timer::GetNextCall();
134 time_t sleep = (next < now) ? 0 : (next - now);
140 tv.tv_sec = (sleep < 0) ? 0 : (long)sleep;
146 Sleep(tv.tv_sec * 1000 + tv.tv_usec);
149 ready = select(nfds + 1, &readfds, &writefds,
158 ea.Source = shared_from_this();
160 for (i = Socket::Sockets.begin();
161 i != Socket::Sockets.end(); ) {
162 Socket::Ptr socket = i->lock();
168 Socket::Sockets.erase(prev);
174 fd = socket->GetFD();
175 if (fd != INVALID_SOCKET && FD_ISSET(fd, &writefds))
176 socket->OnWritable(ea);
178 fd = socket->GetFD();
179 if (fd != INVALID_SOCKET && FD_ISSET(fd, &readfds))
180 socket->OnReadable(ea);
182 fd = socket->GetFD();
183 if (fd != INVALID_SOCKET && FD_ISSET(fd, &exceptfds))
184 socket->OnException(ea);
190 * Signals the application to shut down during the next
191 * execution of the event loop.
193 void Application::Shutdown(void)
195 m_ShuttingDown = true;
199 * Loads a component from a shared library.
201 * @param path The path of the component library.
202 * @param componentConfig The configuration for the component.
203 * @returns The component.
205 Component::Ptr Application::LoadComponent(const string& path,
206 const ConfigObject::Ptr& componentConfig)
208 Component::Ptr component;
209 Component *(*pCreateComponent)();
211 Log("Loading component '" + path + "'");
214 HMODULE hModule = LoadLibrary(path.c_str());
216 lt_dlhandle hModule = lt_dlopen(path.c_str());
220 throw runtime_error("Could not load module");
223 pCreateComponent = (CreateComponentFunction)GetProcAddress(hModule,
227 /* suppress compiler warning for void * cast */
230 pCreateComponent = (CreateComponentFunction)lt_dlsym(hModule,
234 if (pCreateComponent == NULL)
235 throw runtime_error("Loadable module does not contain "
236 "CreateComponent function");
238 component = Component::Ptr(pCreateComponent());
239 component->SetConfig(componentConfig);
240 RegisterComponent(component);
245 * Registers a component object and starts it.
247 * @param component The component.
249 void Application::RegisterComponent(Component::Ptr component)
251 m_Components[component->GetName()] = component;
257 * Unregisters a component object and stops it.
259 * @param component The component.
261 void Application::UnregisterComponent(Component::Ptr component)
263 string name = component->GetName();
265 Log("Unloading component '" + name + "'");
266 map<string, Component::Ptr>::iterator i = m_Components.find(name);
267 if (i != m_Components.end())
268 m_Components.erase(i);
274 * Finds a loaded component by name.
276 * @param name The name of the component.
277 * @returns The component or a null pointer if the component could not be found.
279 Component::Ptr Application::GetComponent(const string& name) const
281 map<string, Component::Ptr>::const_iterator i = m_Components.find(name);
283 if (i == m_Components.end())
284 return Component::Ptr();
290 * Writes a message to the application's log.
292 * @param message The message.
294 void Application::Log(string message)
300 tm tmnow = *localtime(&now);
302 strftime(timestamp, sizeof(timestamp), "%a %B %d %Y %H:%M:%S", &tmnow);
304 cout << "[" << timestamp << "]: " << message << endl;
308 * Retrieves the directory the application's binary is contained in.
310 * @returns The directory.
312 string Application::GetExeDirectory(void) const
314 static string ExePath;
316 if (ExePath.length() != 0)
320 char Cwd[MAXPATHLEN];
321 char *PathEnv, *Directory, PathTest[MAXPATHLEN], FullExePath[MAXPATHLEN];
324 const char *argv0 = m_Arguments[0].c_str();
326 if (getcwd(Cwd, sizeof(Cwd)) == NULL)
327 throw PosixException("getcwd failed", errno);
330 snprintf(FullExePath, sizeof(FullExePath), "%s/%s", Cwd, argv0);
332 strncpy(FullExePath, argv0, sizeof(FullExePath));
334 if (strchr(argv0, '/') == NULL) {
335 PathEnv = getenv("PATH");
337 if (PathEnv != NULL) {
338 PathEnv = strdup(PathEnv);
345 for (Directory = strtok(PathEnv, ":"); Directory != NULL; Directory = strtok(NULL, ":")) {
346 if (snprintf(PathTest, sizeof(PathTest), "%s/%s", Directory, argv0) < 0)
347 throw PosixException("snprintf failed", errno);
349 if (access(PathTest, X_OK) == 0) {
350 strncpy(FullExePath, PathTest, sizeof(FullExePath));
361 throw runtime_error("Could not determine executable path.");
366 if (realpath(FullExePath, Buf) == NULL)
367 throw PosixException("realpath failed", errno);
370 char *LastSlash = strrchr(Buf, '/');
372 if (LastSlash != NULL)
375 ExePath = string(Buf);
377 char FullExePath[MAXPATHLEN];
379 GetModuleFileName(NULL, FullExePath, sizeof(FullExePath));
381 PathRemoveFileSpec(FullExePath);
383 ExePath = string(FullExePath);
390 * Adds a directory to the component search path.
392 * @param componentDirectory The directory.
394 void Application::AddComponentSearchDir(const string& componentDirectory)
397 SetDllDirectory(componentDirectory.c_str());
399 lt_dladdsearchdir(componentDirectory.c_str());
404 * Retrieves the debugging mode of the application.
406 * @returns true if the application is being debugged, false otherwise
408 bool Application::IsDebugging(void)
415 * Signal handler for SIGINT. Prepares the application for cleanly
416 * shutting down during the next execution of the event loop.
418 * @param signum The signal number.
420 void Application::SigIntHandler(int signum)
422 assert(signum == SIGINT);
424 Application::GetInstance()->Shutdown();
427 memset(&sa, 0, sizeof(sa));
428 sa.sa_handler = SIG_DFL;
429 sigaction(SIGINT, &sa, NULL);
433 * Console control handler. Prepares the application for cleanly
434 * shutting down during the next execution of the event loop.
436 BOOL WINAPI Application::CtrlHandler(DWORD type)
438 Application::GetInstance()->Shutdown();
439 SetConsoleCtrlHandler(NULL, FALSE);
445 * Runs the application.
447 * @param argc The number of arguments.
448 * @param argv The arguments that should be passed to the application.
449 * @returns The application's exit code.
451 int Application::Run(int argc, char **argv)
455 assert(!Application::m_Instance);
456 Application::m_Instance = static_pointer_cast<Application>(shared_from_this());
460 memset(&sa, 0, sizeof(sa));
461 sa.sa_handler = &Application::SigIntHandler;
462 sigaction(SIGINT, &sa, NULL);
464 sa.sa_handler = SIG_IGN;
465 sigaction(SIGPIPE, &sa, NULL);
467 SetConsoleCtrlHandler(&Application::CtrlHandler, TRUE);
471 for (int i = 0; i < argc; i++)
472 m_Arguments.push_back(string(argv[i]));
475 result = Main(m_Arguments);
477 Application::m_Instance.reset();
480 result = Main(m_Arguments);
481 } catch (const std::exception& ex) {
482 Application::m_Instance.reset();
484 Application::Log("---");
485 Application::Log("Exception: " + Utility::GetTypeName(ex));
486 Application::Log("Message: " + string(ex.what()));