compress generated minidumps
[public/netxms.git] / src / server / netxmsd / netxmsd.cpp
CommitLineData
5039dede
AK
1/*
2** NetXMS - Network Management System
3** Server startup module
3adc64ec 4** Copyright (C) 2003-2017 Raden Solutions
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
d27e7413 34#if defined(_WITH_ENCRYPTION) && defined(_WIN32)
958a9397
VK
35#include <openssl/applink.c>
36#endif
37
f375019e
VK
38/**
39 * Global data
40 */
5039dede
AK
41BOOL g_bCheckDB = FALSE;
42
f375019e 43/**
2df047f4
VK
44 * Debug level
45 */
46static int s_debugLevel = NXCONFIG_UNINITIALIZED_VALUE;
b41dff2a 47static TCHAR *s_debugTags = NULL;
2df047f4
VK
48
49/**
f375019e
VK
50 * Help text
51 */
f62b7eab 52static TCHAR help_text[] = _T("NetXMS Server Version ") NETXMS_VERSION_STRING _T(" Build ") NETXMS_VERSION_BUILD_STRING _T(" (") NETXMS_BUILD_TAG _T(")") IS_UNICODE_BUILD_STRING _T("\n")
43a6f3ca 53 _T("Copyright (c) 2003-2015 Raden Solutions\n\n")
e0f99bf0
VK
54 _T("Usage: netxmsd [<options>]\n\n")
55 _T("Valid options are:\n")
56 _T(" -e : Run database check on startup\n")
57 _T(" -c <file> : Set non-default configuration file\n")
e0f99bf0
VK
58 _T(" -d : Run as daemon/service\n")
59 _T(" -D <level> : Set debug level (valid levels are 0..9)\n")
60 _T(" -h : Display help and exit\n")
5039dede 61#ifdef _WIN32
e0f99bf0
VK
62 _T(" -I : Install Windows service\n")
63 _T(" -L <user> : Login name for service account.\n")
64 _T(" -P <passwd> : Password for service account.\n")
5039dede 65#else
e0f99bf0 66 _T(" -p <file> : Specify pid file.\n")
5039dede 67#endif
7bdb43c3 68 _T(" -q : Disable interactive console\n")
5039dede 69#ifdef _WIN32
e0f99bf0
VK
70 _T(" -R : Remove Windows service\n")
71 _T(" -s : Start Windows service\n")
72 _T(" -S : Stop Windows service\n")
5039dede 73#endif
e0f99bf0
VK
74 _T(" -v : Display version and exit\n")
75 _T("\n");
5039dede 76
f375019e
VK
77/**
78 * Execute command and wait
79 */
e0f99bf0 80static BOOL ExecAndWait(char *pszCommand)
5039dede
AK
81{
82 BOOL bSuccess = TRUE;
83
84#ifdef _WIN32
e0f99bf0 85 STARTUPINFOA si;
5039dede
AK
86 PROCESS_INFORMATION pi;
87
88 // Fill in process startup info structure
977e7d9d
VK
89 memset(&si, 0, sizeof(STARTUPINFOA));
90 si.cb = sizeof(STARTUPINFOA);
5039dede
AK
91 si.dwFlags = 0;
92
93 // Create new process
e0f99bf0
VK
94 if (!CreateProcessA(NULL, pszCommand, NULL, NULL, FALSE,
95 IsStandalone() ? 0 : CREATE_NO_WINDOW | DETACHED_PROCESS,
96 NULL, NULL, &si, &pi))
5039dede
AK
97 {
98 bSuccess = FALSE;
99 }
100 else
101 {
102 WaitForSingleObject(pi.hProcess, INFINITE);
103
104 // Close all handles
105 CloseHandle(pi.hThread);
106 CloseHandle(pi.hProcess);
107 }
108#else
109 bSuccess = (system(pszCommand) != -1);
110#endif
111
112 return bSuccess;
113}
114
41767c3d
VP
115/**
116 * Create minidump of given process
117 */
5039dede
AK
118
119#ifdef _WIN32
120
121static void CreateMiniDump(DWORD pid)
122{
123 HANDLE hFile, hProcess;
124 TCHAR error[256];
125
e0f99bf0 126 _tprintf(_T("INFO: Starting minidump for process %d\n"), pid);
5039dede
AK
127 hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
128 if (hProcess != NULL)
129 {
3af85b5e
VK
130 TCHAR fname[MAX_PATH];
131 _sntprintf(fname, MAX_PATH, _T("%s\\netxmsd-%u-%u.mdmp"), g_szDumpDir, pid, time(NULL));
132 hFile = CreateFile(fname, GENERIC_WRITE, 0, NULL,
5039dede
AK
133 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
134 if (hFile != INVALID_HANDLE_VALUE)
135 {
db63f792 136 static const char *comments = "Version=" NETXMS_VERSION_STRING_A "; BuildTag=" NETXMS_BUILD_TAG_A;
3af85b5e 137 MINIDUMP_USER_STREAM us;
db63f792 138 us.Type = CommentStreamA;
3af85b5e 139 us.Buffer = (void*)comments;
db63f792 140 us.BufferSize = static_cast<ULONG>(strlen(comments) + 1);
3af85b5e
VK
141
142 MINIDUMP_USER_STREAM_INFORMATION usi;
143 usi.UserStreamCount = 1;
144 usi.UserStreamArray = &us;
145
8f413137
VK
146 if (MiniDumpWriteDump(hProcess, pid, hFile,
147 static_cast<MINIDUMP_TYPE>(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithProcessThreadData),
148 NULL, &usi, NULL))
149 {
150 CloseHandle(hFile);
151 if (DeflateFile(fname))
152 DeleteFile(fname);
153 _tprintf(_T("INFO: Minidump created successfully\n"));
154 }
155 else
156 {
157 CloseHandle(hFile);
158 DeleteFile(fname);
159 _tprintf(_T("INFO: Minidump creation failed\n"));
160 }
5039dede
AK
161 }
162 else
163 {
e0f99bf0 164 _tprintf(_T("ERROR: cannot create file for minidump (%s)\n"), GetSystemErrorText(GetLastError(), error, 256));
5039dede
AK
165 }
166 }
167 else
168 {
e0f99bf0 169 _tprintf(_T("ERROR: cannot open process %d (%s)\n"), pid, GetSystemErrorText(GetLastError(), error, 256));
5039dede
AK
170 }
171}
172
173#endif
174
5039dede 175#ifdef _WIN32
7bdb43c3 176#define VALID_OPTIONS "c:CdD:ehIL:P:qRsSv"
5039dede 177#else
7bdb43c3 178#define VALID_OPTIONS "c:CdD:ehp:qv"
5039dede
AK
179#endif
180
d78be64d
VK
181/**
182 * Parse command line
183 * Returns TRUE on success and FALSE on failure
184 */
5039dede
AK
185static BOOL ParseCommandLine(int argc, char *argv[])
186{
187 int ch;
e0f99bf0 188 char *eptr;
5039dede 189#ifdef _WIN32
e0f99bf0
VK
190 TCHAR login[256] = _T(""), password[256] = _T("");
191 char exePath[MAX_PATH], dllPath[MAX_PATH], *ptr;
5039dede
AK
192 BOOL useLogin = FALSE;
193#endif
194#if defined(_WIN32) || HAVE_DECL_GETOPT_LONG
195 static struct option longOptions[] =
196 {
0b8da006
AK
197 { (char *)"check-db", 0, NULL, 'e' },
198 { (char *)"config", 1, NULL, 'c' },
199 { (char *)"daemon", 0, NULL, 'd' },
200 { (char *)"debug", 1, NULL, 'D' },
201 { (char *)"help", 0, NULL, 'h' },
8782d780 202 { (char *)"quiet", 1, NULL, 'q' },
5039dede 203#ifdef _WIN32
0b8da006
AK
204 { (char *)"check-service", 0, NULL, '!' },
205 { (char *)"dump", 1, NULL, '~' },
3af85b5e 206 { (char *)"dump-dir", 1, NULL, '@' },
0b8da006
AK
207 { (char *)"install", 0, NULL, 'I' },
208 { (char *)"login", 1, NULL, 'L' },
209 { (char *)"password", 1, NULL, 'P' },
210 { (char *)"remove", 0, NULL, 'R' },
211 { (char *)"start", 0, NULL, 's' },
212 { (char *)"stop", 0, NULL, 'S' },
5039dede 213#else
0b8da006 214 { (char *)"pid-file", 1, NULL, 'p' },
5039dede
AK
215#endif
216 { NULL, 0, 0, 0 }
217 };
218#endif
219
220#if defined(_WIN32) || HAVE_DECL_GETOPT_LONG
221 while((ch = getopt_long(argc, argv, VALID_OPTIONS, longOptions, NULL)) != -1)
222#else
223 while((ch = getopt(argc, argv, VALID_OPTIONS)) != -1)
224#endif
225 {
226 switch(ch)
227 {
228 case 'h':
e0f99bf0 229 _tprintf(help_text);
5039dede
AK
230 return FALSE;
231 case 'v':
e5390fb5 232 {
f62b7eab 233 _tprintf(_T("NetXMS Server Version ") NETXMS_VERSION_STRING _T(" Build ") NETXMS_VERSION_BUILD_STRING _T(" (") NETXMS_BUILD_TAG _T(")") IS_UNICODE_BUILD_STRING _T("\n"));
e5390fb5
VK
234 String ciphers = NXCPGetSupportedCiphersAsText();
235 _tprintf(_T("NXCP: %d.%d.%d.%d (%s)\n"),
236 NXCP_VERSION, CLIENT_PROTOCOL_VERSION_BASE, CLIENT_PROTOCOL_VERSION_MOBILE, CLIENT_PROTOCOL_VERSION_FULL,
237 ciphers.isEmpty() ? _T("NO ENCRYPTION") : ciphers.getBuffer());
ef6a61aa 238 _tprintf(_T("Built with: %hs\n"), CPP_COMPILER_VERSION);
e5390fb5 239 }
5039dede
AK
240 return FALSE;
241 case 'c':
e0f99bf0
VK
242#ifdef UNICODE
243 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, g_szConfigFile, MAX_PATH);
244 g_szConfigFile[MAX_PATH - 1] = 0;
245#else
5039dede 246 nx_strncpy(g_szConfigFile, optarg, MAX_PATH);
e0f99bf0 247#endif
5039dede
AK
248 break;
249 case 'C': // Check config
c8076b19 250 g_flags &= ~AF_DAEMON;
e0f99bf0 251 _tprintf(_T("Checking configuration file (%s):\n\n"), g_szConfigFile);
2df047f4 252 LoadConfig(&s_debugLevel);
5039dede
AK
253 return FALSE;
254 case 'd':
c8076b19 255 g_flags |= AF_DAEMON;
5039dede
AK
256 break;
257 case 'D': // Debug level
2df047f4
VK
258 s_debugLevel = strtoul(optarg, &eptr, 0);
259 if ((*eptr != 0) || (s_debugLevel > 9))
5039dede 260 {
e0f99bf0 261 _tprintf(_T("Invalid debug level \"%hs\" - should be in range 0..9\n"), optarg);
2df047f4 262 s_debugLevel = 0;
5039dede
AK
263 }
264 break;
3a82d5ae 265 case 'q': // disable interactive console
c8076b19 266 g_flags |= AF_DEBUG_CONSOLE_DISABLED;
3a82d5ae 267 break;
5039dede
AK
268 case 'e':
269 g_bCheckDB = TRUE;
270 break;
271#ifdef _WIN32
272 case 'L':
e0f99bf0
VK
273#ifdef UNICODE
274 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, login, 256);
275 login[255] = 0;
276#else
5039dede 277 nx_strncpy(login, optarg, 256);
e0f99bf0 278#endif
5039dede
AK
279 useLogin = TRUE;
280 break;
0df29c69
VK
281#ifndef _WIN32
282 case 'p': // PID file
283#ifdef UNICODE
284 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, g_szPIDFile, MAX_PATH);
285 g_szPIDFile[MAX_PATH - 1] = 0;
286#else
287 nx_strncpy(g_szPIDFile, optarg, MAX_PATH);
288#endif
289 break;
290#endif
5039dede 291 case 'P':
e0f99bf0
VK
292#ifdef UNICODE
293 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, password, 256);
294 password[255] = 0;
295#else
5039dede 296 nx_strncpy(password, optarg, 256);
e0f99bf0 297#endif
5039dede
AK
298 break;
299 case 'I': // Install service
300 ptr = strrchr(argv[0], '\\');
301 if (ptr != NULL)
302 ptr++;
303 else
304 ptr = argv[0];
305
306 _fullpath(exePath, ptr, 255);
307
308 if (stricmp(&exePath[strlen(exePath)-4], ".exe"))
309 strcat(exePath, ".exe");
310 strcpy(dllPath, exePath);
311 ptr = strrchr(dllPath, '\\');
312 if (ptr != NULL) // Shouldn't be NULL
313 {
314 ptr++;
315 strcpy(ptr, "libnxsrv.dll");
316 }
e0f99bf0
VK
317#ifdef UNICODE
318 WCHAR wexePath[MAX_PATH], wdllPath[MAX_PATH];
319 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, exePath, -1, wexePath, MAX_PATH);
320 wexePath[MAX_PATH - 1] = 0;
321 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, dllPath, -1, wdllPath, MAX_PATH);
322 wdllPath[MAX_PATH - 1] = 0;
323 InstallService(wexePath, wdllPath, useLogin ? login : NULL, useLogin ? password : NULL);
324#else
5039dede 325 InstallService(exePath, dllPath, useLogin ? login : NULL, useLogin ? password : NULL);
e0f99bf0 326#endif
5039dede
AK
327 return FALSE;
328 case 'R': // Remove service
329 RemoveService();
330 return FALSE;
331 case 's': // Start service
332 StartCoreService();
333 return FALSE;
334 case 'S': // Stop service
335 StopCoreService();
336 return FALSE;
337 case '!': // Check service configuration (for migration from pre-0.2.20)
338 CheckServiceConfig();
339 return FALSE;
3af85b5e
VK
340 case '@':
341#ifdef UNICODE
342 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, optarg, -1, g_szDumpDir, MAX_PATH);
343#else
344 strlcpy(g_szDumpDir, optarg, MAX_PATH);
345#endif
346 if (g_szDumpDir[_tcslen(g_szDumpDir) - 1] == _T('\\'))
347 {
348 g_szDumpDir[_tcslen(g_szDumpDir) - 1] = 0;
349 }
350 break;
5039dede 351 case '~':
e0f99bf0 352 CreateMiniDump(strtoul(optarg, NULL, 0));
5039dede
AK
353 return FALSE;
354#endif
355 default:
356 break;
357 }
358 }
359 return TRUE;
360}
361
d78be64d
VK
362/**
363 * Startup code
364 */
06b383fe 365int main(int argc, char* argv[])
5039dede 366{
d37e7f10 367 InitNetXMSProcess(false);
5039dede 368
5039dede
AK
369 // Check for alternate config file location
370#ifdef _WIN32
fe8ea784 371 HKEY hKey;
42acd918 372 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("Software\\NetXMS\\Server"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)
5039dede 373 {
fe8ea784 374 DWORD dwSize = MAX_PATH * sizeof(TCHAR);
5039dede
AK
375 RegQueryValueEx(hKey, _T("ConfigFile"), NULL, NULL, (BYTE *)g_szConfigFile, &dwSize);
376 RegCloseKey(hKey);
377 }
378#else
38ffd4b0
VK
379 const TCHAR *configEnv = _tgetenv(_T("NETXMSD_CONFIG"));
380 if ((configEnv != NULL) && (*configEnv != 0))
381 {
a2ef43f7 382 nx_strncpy(g_szConfigFile, configEnv, MAX_PATH);
38ffd4b0 383 }
5039dede
AK
384#endif
385
1e2b0526
VP
386 if (!ParseCommandLine(argc, argv))
387 return 1;
5039dede 388
2df047f4 389 if (!LoadConfig(&s_debugLevel))
5039dede
AK
390 {
391 if (IsStandalone())
e0f99bf0 392 _tprintf(_T("Error loading configuration file\n"));
5039dede
AK
393 return 1;
394 }
395
2df047f4
VK
396 if (s_debugLevel == NXCONFIG_UNINITIALIZED_VALUE)
397 s_debugLevel = 0;
398 nxlog_set_debug_level(s_debugLevel);
b41dff2a 399 free(s_debugTags);
e2e66145 400
5039dede
AK
401 // Set exception handler
402#ifdef _WIN32
c8076b19 403 if (g_flags & AF_CATCH_EXCEPTIONS)
4262c0dc 404 SetExceptionHandler(SEHServiceExceptionHandler, SEHServiceExceptionDataWriter,
c8076b19 405 g_szDumpDir, _T("netxmsd"), MSG_EXCEPTION, (g_flags & AF_WRITE_FULL_DUMP) ? true : false, IsStandalone());
5039dede
AK
406 __try {
407#endif
408
409 // Check database before start if requested
410 if (g_bCheckDB)
411 {
412 char szCmd[MAX_PATH + 128], *pszSep;
413
414 strncpy(szCmd, argv[0], MAX_PATH);
415 pszSep = strrchr(szCmd, FS_PATH_SEPARATOR[0]);
416 if (pszSep != NULL)
417 pszSep++;
418 else
419 pszSep = szCmd;
e0f99bf0
VK
420#ifdef UNICODE
421 snprintf(pszSep, 128, "nxdbmgr -c \"%S\" -f check", g_szConfigFile);
422#else
423 snprintf(pszSep, 128, "nxdbmgr -c \"%s\" -f check", g_szConfigFile);
424#endif
5039dede
AK
425 if (!ExecAndWait(szCmd))
426 if (IsStandalone())
e0f99bf0 427 _tprintf(_T("ERROR: Failed to execute command \"%hs\"\n"), szCmd);
5039dede
AK
428 }
429
430#ifdef _WIN32
431 if (!IsStandalone())
432 {
433 InitService();
434 }
435 else
436 {
437 if (!Initialize())
438 {
e0f99bf0 439 _tprintf(_T("NetXMS Core initialization failed\n"));
5039dede
AK
440
441 // Remove database lock
c8076b19 442 if (g_flags & AF_DB_LOCKED)
5039dede
AK
443 {
444 UnlockDB();
445 ShutdownDB();
446 }
c370cbf9 447 nxlog_close();
5039dede
AK
448 return 3;
449 }
450 Main(NULL);
451 }
452#else /* not _WIN32 */
453 if (!IsStandalone())
454 {
455 if (daemon(0, 0) == -1)
456 {
457 perror("Call to daemon() failed");
458 return 2;
459 }
460 }
461
462 // Write PID file
fe8ea784 463 FILE *fp = _tfopen(g_szPIDFile, _T("w"));
5039dede
AK
464 if (fp != NULL)
465 {
e0f99bf0 466 _ftprintf(fp, _T("%d"), getpid());
5039dede
AK
467 fclose(fp);
468 }
469
470 // Initialize server
471 if (!Initialize())
472 {
473 // Remove database lock
c8076b19 474 if (g_flags & AF_DB_LOCKED)
5039dede
AK
475 {
476 UnlockDB();
477 ShutdownDB();
478 }
c370cbf9 479 nxlog_close();
5039dede
AK
480 return 3;
481 }
482
483 // Everything is OK, start common main loop
484 StartMainLoop(SignalHandler, Main);
485#endif /* _WIN32 */
486
487#ifdef _WIN32
488 LIBNETXMS_EXCEPTION_HANDLER
489#endif
490 return 0;
491}