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 Object::ClearHeldObjects();
101 Timer::CallExpiredTimers();
107 Socket::CollectionType::iterator prev, i;
108 for (i = Socket::Sockets.begin();
109 i != Socket::Sockets.end(); ) {
110 Socket::Ptr socket = i->lock();
116 Socket::Sockets.erase(prev);
120 int fd = socket->GetFD();
122 if (socket->WantsToWrite())
123 FD_SET(fd, &writefds);
125 if (socket->WantsToRead())
126 FD_SET(fd, &readfds);
128 FD_SET(fd, &exceptfds);
134 time_t now = time(NULL);
135 time_t next = Timer::GetNextCall();
136 time_t sleep = (next < now) ? 0 : (next - now);
142 tv.tv_sec = (sleep < 0) ? 0 : (long)sleep;
148 Sleep(tv.tv_sec * 1000 + tv.tv_usec);
151 ready = select(nfds + 1, &readfds, &writefds,
160 ea.Source = shared_from_this();
162 for (i = Socket::Sockets.begin();
163 i != Socket::Sockets.end(); ) {
164 Socket::Ptr socket = i->lock();
170 Socket::Sockets.erase(prev);
176 fd = socket->GetFD();
177 if (fd != INVALID_SOCKET && FD_ISSET(fd, &writefds))
178 socket->OnWritable(ea);
180 fd = socket->GetFD();
181 if (fd != INVALID_SOCKET && FD_ISSET(fd, &readfds))
182 socket->OnReadable(ea);
184 fd = socket->GetFD();
185 if (fd != INVALID_SOCKET && FD_ISSET(fd, &exceptfds))
186 socket->OnException(ea);
192 * Signals the application to shut down during the next
193 * execution of the event loop.
195 void Application::Shutdown(void)
197 m_ShuttingDown = true;
201 * Loads a component from a shared library.
203 * @param path The path of the component library.
204 * @param componentConfig The configuration for the component.
205 * @returns The component.
207 Component::Ptr Application::LoadComponent(const string& path,
208 const ConfigObject::Ptr& componentConfig)
210 Component::Ptr component;
211 Component *(*pCreateComponent)();
213 Log("Loading component '" + path + "'");
216 HMODULE hModule = LoadLibrary(path.c_str());
218 lt_dlhandle hModule = lt_dlopen(path.c_str());
222 throw runtime_error("Could not load module");
225 pCreateComponent = (CreateComponentFunction)GetProcAddress(hModule,
229 /* suppress compiler warning for void * cast */
232 pCreateComponent = (CreateComponentFunction)lt_dlsym(hModule,
236 if (pCreateComponent == NULL)
237 throw runtime_error("Loadable module does not contain "
238 "CreateComponent function");
240 component = Component::Ptr(pCreateComponent());
241 component->SetConfig(componentConfig);
242 RegisterComponent(component);
247 * Registers a component object and starts it.
249 * @param component The component.
251 void Application::RegisterComponent(Component::Ptr component)
253 m_Components[component->GetName()] = component;
259 * Unregisters a component object and stops it.
261 * @param component The component.
263 void Application::UnregisterComponent(Component::Ptr component)
265 string name = component->GetName();
267 Log("Unloading component '" + name + "'");
268 map<string, Component::Ptr>::iterator i = m_Components.find(name);
269 if (i != m_Components.end())
270 m_Components.erase(i);
276 * Finds a loaded component by name.
278 * @param name The name of the component.
279 * @returns The component or a null pointer if the component could not be found.
281 Component::Ptr Application::GetComponent(const string& name) const
283 map<string, Component::Ptr>::const_iterator i = m_Components.find(name);
285 if (i == m_Components.end())
286 return Component::Ptr();
292 * Writes a message to the application's log.
294 * @param message The message.
296 void Application::Log(string message)
302 tm tmnow = *localtime(&now);
304 strftime(timestamp, sizeof(timestamp), "%a %B %d %Y %H:%M:%S", &tmnow);
306 cout << "[" << timestamp << "]: " << message << endl;
310 * Retrieves the directory the application's binary is contained in.
312 * @returns The directory.
314 string Application::GetExeDirectory(void) const
316 static string ExePath;
318 if (ExePath.length() != 0)
322 char Cwd[MAXPATHLEN];
323 char *PathEnv, *Directory, PathTest[MAXPATHLEN], FullExePath[MAXPATHLEN];
326 const char *argv0 = m_Arguments[0].c_str();
328 if (getcwd(Cwd, sizeof(Cwd)) == NULL)
329 throw PosixException("getcwd failed", errno);
332 snprintf(FullExePath, sizeof(FullExePath), "%s/%s", Cwd, argv0);
334 strncpy(FullExePath, argv0, sizeof(FullExePath));
336 if (strchr(argv0, '/') == NULL) {
337 PathEnv = getenv("PATH");
339 if (PathEnv != NULL) {
340 PathEnv = strdup(PathEnv);
347 for (Directory = strtok(PathEnv, ":"); Directory != NULL; Directory = strtok(NULL, ":")) {
348 if (snprintf(PathTest, sizeof(PathTest), "%s/%s", Directory, argv0) < 0)
349 throw PosixException("snprintf failed", errno);
351 if (access(PathTest, X_OK) == 0) {
352 strncpy(FullExePath, PathTest, sizeof(FullExePath));
363 throw runtime_error("Could not determine executable path.");
368 if (realpath(FullExePath, Buf) == NULL)
369 throw PosixException("realpath failed", errno);
372 char *LastSlash = strrchr(Buf, '/');
374 if (LastSlash != NULL)
377 ExePath = string(Buf);
379 char FullExePath[MAXPATHLEN];
381 GetModuleFileName(NULL, FullExePath, sizeof(FullExePath));
383 PathRemoveFileSpec(FullExePath);
385 ExePath = string(FullExePath);
392 * Adds a directory to the component search path.
394 * @param componentDirectory The directory.
396 void Application::AddComponentSearchDir(const string& componentDirectory)
399 SetDllDirectory(componentDirectory.c_str());
401 lt_dladdsearchdir(componentDirectory.c_str());
406 * Retrieves the debugging mode of the application.
408 * @returns true if the application is being debugged, false otherwise
410 bool Application::IsDebugging(void)
417 * Signal handler for SIGINT. Prepares the application for cleanly
418 * shutting down during the next execution of the event loop.
420 * @param signum The signal number.
422 void Application::SigIntHandler(int signum)
424 assert(signum == SIGINT);
426 Application::GetInstance()->Shutdown();
429 memset(&sa, 0, sizeof(sa));
430 sa.sa_handler = SIG_DFL;
431 sigaction(SIGINT, &sa, NULL);
435 * Console control handler. Prepares the application for cleanly
436 * shutting down during the next execution of the event loop.
438 BOOL WINAPI Application::CtrlHandler(DWORD type)
440 Application::GetInstance()->Shutdown();
441 SetConsoleCtrlHandler(NULL, FALSE);
447 * Runs the application.
449 * @param argc The number of arguments.
450 * @param argv The arguments that should be passed to the application.
451 * @returns The application's exit code.
453 int Application::Run(int argc, char **argv)
457 assert(!Application::m_Instance);
458 Application::m_Instance = static_pointer_cast<Application>(shared_from_this());
462 memset(&sa, 0, sizeof(sa));
463 sa.sa_handler = &Application::SigIntHandler;
464 sigaction(SIGINT, &sa, NULL);
466 sa.sa_handler = SIG_IGN;
467 sigaction(SIGPIPE, &sa, NULL);
469 SetConsoleCtrlHandler(&Application::CtrlHandler, TRUE);
473 for (int i = 0; i < argc; i++)
474 m_Arguments.push_back(string(argv[i]));
477 result = Main(m_Arguments);
479 Application::m_Instance.reset();
482 result = Main(m_Arguments);
483 } catch (const std::exception& ex) {
484 Application::m_Instance.reset();
486 Application::Log("---");
487 Application::Log("Exception: " + Utility::GetTypeName(ex));
488 Application::Log("Message: " + string(ex.what()));