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