fixes in legacy console backported from 1.0.x
[public/netxms.git] / src / server / netxmsd / netxmsd.cpp
CommitLineData
5039dede
AK
1/*
2** NetXMS - Network Management System
3** Server startup module
73869331 4** Copyright (C) 2003-2010 NetXMS Team
5039dede
AK
5**
6** This program is free software; you can redistribute it and/or modify
7** it under the terms of the GNU General Public License as published by
8** the Free Software Foundation; either version 2 of the License, or
9** (at your option) any later version.
10**
11** This program is distributed in the hope that it will be useful,
12** but WITHOUT ANY WARRANTY; without even the implied warranty of
13** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14** GNU General Public License for more details.
15**
16** You should have received a copy of the GNU General Public License
17** along with this program; if not, write to the Free Software
18** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19**
20** File: netxmsd.cpp
21**
22**/
23
24#include "netxmsd.h"
25
26#if HAVE_GETOPT_H
27#include <getopt.h>
28#endif
29
30#ifdef _WIN32
31#include <dbghelp.h>
32#endif
33
34
35//
36// Global data
37//
38
39BOOL g_bCheckDB = FALSE;
40
41
42//
43// Help text
44//
45
e0f99bf0
VK
46static TCHAR help_text[] = _T("NetXMS Server Version ") NETXMS_VERSION_STRING _T("\n")
47 _T("Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 NetXMS Team\n\n")
48 _T("Usage: netxmsd [<options>]\n\n")
49 _T("Valid options are:\n")
50 _T(" -e : Run database check on startup\n")
51 _T(" -c <file> : Set non-default configuration file\n")
52 _T(" : Default is ") DEFAULT_CONFIG_FILE _T("\n")
53 _T(" -d : Run as daemon/service\n")
54 _T(" -D <level> : Set debug level (valid levels are 0..9)\n")
55 _T(" -h : Display help and exit\n")
5039dede 56#ifdef _WIN32
e0f99bf0
VK
57 _T(" -I : Install Windows service\n")
58 _T(" -L <user> : Login name for service account.\n")
59 _T(" -P <passwd> : Password for service account.\n")
5039dede 60#else
e0f99bf0 61 _T(" -p <file> : Specify pid file.\n")
5039dede
AK
62#endif
63#ifdef _WIN32
e0f99bf0
VK
64 _T(" -R : Remove Windows service\n")
65 _T(" -s : Start Windows service\n")
66 _T(" -S : Stop Windows service\n")
5039dede 67#endif
e0f99bf0
VK
68 _T(" -v : Display version and exit\n")
69 _T("\n");
5039dede
AK
70
71
72//
5039dede
AK
73// Execute command and wait
74//
75
e0f99bf0 76static BOOL ExecAndWait(char *pszCommand)
5039dede
AK
77{
78 BOOL bSuccess = TRUE;
79
80#ifdef _WIN32
e0f99bf0 81 STARTUPINFOA si;
5039dede
AK
82 PROCESS_INFORMATION pi;
83
84 // Fill in process startup info structure
85 memset(&si, 0, sizeof(STARTUPINFO));
86 si.cb = sizeof(STARTUPINFO);
87 si.dwFlags = 0;
88
89 // Create new process
e0f99bf0
VK
90 if (!CreateProcessA(NULL, pszCommand, NULL, NULL, FALSE,
91 IsStandalone() ? 0 : CREATE_NO_WINDOW | DETACHED_PROCESS,
92 NULL, NULL, &si, &pi))
5039dede
AK
93 {
94 bSuccess = FALSE;
95 }
96 else
97 {
98 WaitForSingleObject(pi.hProcess, INFINITE);
99
100 // Close all handles
101 CloseHandle(pi.hThread);
102 CloseHandle(pi.hProcess);
103 }
104#else
105 bSuccess = (system(pszCommand) != -1);
106#endif
107
108 return bSuccess;
109}
110
111
112//
113// Create minidump of given process
114//
115
116#ifdef _WIN32
117
118static void CreateMiniDump(DWORD pid)
119{
120 HANDLE hFile, hProcess;
121 TCHAR error[256];
122
e0f99bf0 123 _tprintf(_T("INFO: Starting minidump for process %d\n"), pid);
5039dede
AK
124 hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
125 if (hProcess != NULL)
126 {
127 hFile = CreateFile(_T("C:\\netxmsd.mdmp"), GENERIC_WRITE, 0, NULL,
128 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
129 if (hFile != INVALID_HANDLE_VALUE)
130 {
131 MiniDumpWriteDump(hProcess, pid, hFile, MiniDumpNormal, NULL, NULL, NULL);
132 CloseHandle(hFile);
e0f99bf0 133 _tprintf(_T("INFO: Minidump created successfully\n"));
5039dede
AK
134 }
135 else
136 {
e0f99bf0 137 _tprintf(_T("ERROR: cannot create file for minidump (%s)\n"), GetSystemErrorText(GetLastError(), error, 256));
5039dede
AK
138 }
139 }
140 else
141 {
e0f99bf0 142 _tprintf(_T("ERROR: cannot open process %d (%s)\n"), pid, GetSystemErrorText(GetLastError(), error, 256));
5039dede
AK
143 }
144}
145
146#endif
147
148
149//
150// Parse command line
151// Returns TRUE on success and FALSE on failure
152//
153
154#ifdef _WIN32
155#define VALID_OPTIONS "c:CdD:ehIL:P:RsSv"
156#else
157#define VALID_OPTIONS "c:CdD:ehp:v"
158#endif
159
160static BOOL ParseCommandLine(int argc, char *argv[])
161{
162 int ch;
e0f99bf0 163 char *eptr;
5039dede 164#ifdef _WIN32
e0f99bf0
VK
165 TCHAR login[256] = _T(""), password[256] = _T("");
166 char exePath[MAX_PATH], dllPath[MAX_PATH], *ptr;
5039dede
AK
167 BOOL useLogin = FALSE;
168#endif
169#if defined(_WIN32) || HAVE_DECL_GETOPT_LONG
170 static struct option longOptions[] =
171 {
172 { "check-db", 0, NULL, 'e' },
173 { "config", 1, NULL, 'c' },
174 { "daemon", 0, NULL, 'd' },
175 { "debug", 1, NULL, 'D' },
176 { "help", 0, NULL, 'h' },
177#ifdef _WIN32
178 { "check-service", 0, NULL, '!' },
179 { "dump", 1, NULL, '~' },
180 { "install", 0, NULL, 'I' },
181 { "login", 1, NULL, 'L' },
182 { "password", 1, NULL, 'P' },
183 { "remove", 0, NULL, 'R' },
184 { "start", 0, NULL, 's' },
185 { "stop", 0, NULL, 'S' },
186#else
e0f99bf0 187 { _T("pid-file"), 1, NULL, 'p' },
5039dede
AK
188#endif
189 { NULL, 0, 0, 0 }
190 };
191#endif
192
193#if defined(_WIN32) || HAVE_DECL_GETOPT_LONG
194 while((ch = getopt_long(argc, argv, VALID_OPTIONS, longOptions, NULL)) != -1)
195#else
196 while((ch = getopt(argc, argv, VALID_OPTIONS)) != -1)
197#endif
198 {
199 switch(ch)
200 {
201 case 'h':
e0f99bf0 202 _tprintf(help_text);
5039dede
AK
203 return FALSE;
204 case 'v':
e0f99bf0 205 _tprintf(_T("NetXMS Server Version ") NETXMS_VERSION_STRING _T(" Build of %hs\n"), __DATE__);
5039dede
AK
206 return FALSE;
207 case 'c':
e0f99bf0
VK
208#ifdef UNICODE
209 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, g_szConfigFile, MAX_PATH);
210 g_szConfigFile[MAX_PATH - 1] = 0;
211#else
5039dede 212 nx_strncpy(g_szConfigFile, optarg, MAX_PATH);
e0f99bf0 213#endif
5039dede
AK
214 break;
215 case 'C': // Check config
216 g_dwFlags &= ~AF_DAEMON;
e0f99bf0 217 _tprintf(_T("Checking configuration file (%s):\n\n"), g_szConfigFile);
5039dede
AK
218 LoadConfig();
219 return FALSE;
220 case 'd':
221 g_dwFlags |= AF_DAEMON;
222 break;
223 case 'D': // Debug level
224 g_nDebugLevel = strtol(optarg, &eptr, 0);
225 if ((*eptr != 0) || (g_nDebugLevel < 0) || (g_nDebugLevel > 9))
226 {
e0f99bf0 227 _tprintf(_T("Invalid debug level \"%hs\" - should be in range 0..9\n"), optarg);
5039dede
AK
228 g_nDebugLevel = 0;
229 }
230 break;
231 case 'e':
232 g_bCheckDB = TRUE;
233 break;
234#ifdef _WIN32
235 case 'L':
e0f99bf0
VK
236#ifdef UNICODE
237 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, login, 256);
238 login[255] = 0;
239#else
5039dede 240 nx_strncpy(login, optarg, 256);
e0f99bf0 241#endif
5039dede
AK
242 useLogin = TRUE;
243 break;
244 case 'P':
e0f99bf0
VK
245#ifdef UNICODE
246 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, password, 256);
247 password[255] = 0;
248#else
5039dede 249 nx_strncpy(password, optarg, 256);
e0f99bf0 250#endif
5039dede
AK
251 break;
252 case 'I': // Install service
253 ptr = strrchr(argv[0], '\\');
254 if (ptr != NULL)
255 ptr++;
256 else
257 ptr = argv[0];
258
259 _fullpath(exePath, ptr, 255);
260
261 if (stricmp(&exePath[strlen(exePath)-4], ".exe"))
262 strcat(exePath, ".exe");
263 strcpy(dllPath, exePath);
264 ptr = strrchr(dllPath, '\\');
265 if (ptr != NULL) // Shouldn't be NULL
266 {
267 ptr++;
268 strcpy(ptr, "libnxsrv.dll");
269 }
e0f99bf0
VK
270#ifdef UNICODE
271 WCHAR wexePath[MAX_PATH], wdllPath[MAX_PATH];
272 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, exePath, -1, wexePath, MAX_PATH);
273 wexePath[MAX_PATH - 1] = 0;
274 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, dllPath, -1, wdllPath, MAX_PATH);
275 wdllPath[MAX_PATH - 1] = 0;
276 InstallService(wexePath, wdllPath, useLogin ? login : NULL, useLogin ? password : NULL);
277#else
5039dede 278 InstallService(exePath, dllPath, useLogin ? login : NULL, useLogin ? password : NULL);
e0f99bf0 279#endif
5039dede
AK
280 return FALSE;
281 case 'R': // Remove service
282 RemoveService();
283 return FALSE;
284 case 's': // Start service
285 StartCoreService();
286 return FALSE;
287 case 'S': // Stop service
288 StopCoreService();
289 return FALSE;
290 case '!': // Check service configuration (for migration from pre-0.2.20)
291 CheckServiceConfig();
292 return FALSE;
293 case '~':
e0f99bf0 294 CreateMiniDump(strtoul(optarg, NULL, 0));
5039dede
AK
295 return FALSE;
296#endif
297 default:
298 break;
299 }
300 }
301 return TRUE;
302}
303
304
305//
306// Startup code
307//
308
309int main(int argc, char *argv[])
310{
311#ifdef _WIN32
312 HKEY hKey;
313 DWORD dwSize;
314#else
315 int i;
316 FILE *fp;
317 char *pszEnv;
318#endif
319
320 InitThreadLibrary();
321
322#ifdef NETXMS_MEMORY_DEBUG
323 InitMemoryDebugger();
324#endif
325
326 // Check for alternate config file location
327#ifdef _WIN32
328 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NetXMS\\Server"), 0,
329 KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
330 {
331 dwSize = MAX_PATH * sizeof(TCHAR);
332 RegQueryValueEx(hKey, _T("ConfigFile"), NULL, NULL, (BYTE *)g_szConfigFile, &dwSize);
333 RegCloseKey(hKey);
334 }
335#else
82d4fb3d 336 pszEnv = _tgetenv(_T("NETXMSD_CONFIG"));
5039dede
AK
337 if (pszEnv != NULL)
338 nx_strncpy(g_szConfigFile, pszEnv, MAX_PATH);
339#endif
340
341 if (!ParseCommandLine(argc, argv))
342 return 1;
343
344 if (!LoadConfig())
345 {
346 if (IsStandalone())
e0f99bf0 347 _tprintf(_T("Error loading configuration file\n"));
5039dede
AK
348 return 1;
349 }
350
351 // Set exception handler
352#ifdef _WIN32
353 if (g_dwFlags & AF_CATCH_EXCEPTIONS)
4262c0dc 354 SetExceptionHandler(SEHServiceExceptionHandler, SEHServiceExceptionDataWriter,
e0f99bf0 355 g_szDumpDir, _T("netxmsd"), MSG_EXCEPTION, g_dwFlags & AF_WRITE_FULL_DUMP, IsStandalone());
5039dede
AK
356 __try {
357#endif
358
359 // Check database before start if requested
360 if (g_bCheckDB)
361 {
362 char szCmd[MAX_PATH + 128], *pszSep;
363
364 strncpy(szCmd, argv[0], MAX_PATH);
365 pszSep = strrchr(szCmd, FS_PATH_SEPARATOR[0]);
366 if (pszSep != NULL)
367 pszSep++;
368 else
369 pszSep = szCmd;
e0f99bf0
VK
370#ifdef UNICODE
371 snprintf(pszSep, 128, "nxdbmgr -c \"%S\" -f check", g_szConfigFile);
372#else
373 snprintf(pszSep, 128, "nxdbmgr -c \"%s\" -f check", g_szConfigFile);
374#endif
5039dede
AK
375 if (!ExecAndWait(szCmd))
376 if (IsStandalone())
e0f99bf0 377 _tprintf(_T("ERROR: Failed to execute command \"%hs\"\n"), szCmd);
5039dede
AK
378 }
379
380#ifdef _WIN32
381 if (!IsStandalone())
382 {
383 InitService();
384 }
385 else
386 {
387 if (!Initialize())
388 {
e0f99bf0 389 _tprintf(_T("NetXMS Core initialization failed\n"));
5039dede
AK
390
391 // Remove database lock
392 if (g_dwFlags & AF_DB_LOCKED)
393 {
394 UnlockDB();
395 ShutdownDB();
396 }
397 return 3;
398 }
399 Main(NULL);
400 }
401#else /* not _WIN32 */
402 if (!IsStandalone())
403 {
404 if (daemon(0, 0) == -1)
405 {
406 perror("Call to daemon() failed");
407 return 2;
408 }
409 }
410
411 // Write PID file
e0f99bf0 412 fp = _tfopen(g_szPIDFile, _T("w"));
5039dede
AK
413 if (fp != NULL)
414 {
e0f99bf0 415 _ftprintf(fp, _T("%d"), getpid());
5039dede
AK
416 fclose(fp);
417 }
418
419 // Initialize server
420 if (!Initialize())
421 {
422 // Remove database lock
423 if (g_dwFlags & AF_DB_LOCKED)
424 {
425 UnlockDB();
426 ShutdownDB();
427 }
428 return 3;
429 }
430
431 // Everything is OK, start common main loop
432 StartMainLoop(SignalHandler, Main);
433#endif /* _WIN32 */
434
435#ifdef _WIN32
436 LIBNETXMS_EXCEPTION_HANDLER
437#endif
438 return 0;
439}