intermediate commit - will not compile!!!
[public/netxms.git] / src / server / core / main.cpp
CommitLineData
5039dede
AK
1/*
2** NetXMS - Network Management System
48c0079d 3** Copyright (C) 2003-2011 NetXMS Team
5039dede
AK
4**
5** This program is free software; you can redistribute it and/or modify
6** it under the terms of the GNU General Public License as published by
7** the Free Software Foundation; either version 2 of the License, or
8** (at your option) any later version.
9**
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.
14**
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
17** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18**
19** File: main.cpp
20**
21**/
22
23#include "nxcore.h"
24#include <netxmsdb.h>
25
0322eed7
VK
26#if !defined(_WIN32) && HAVE_READLINE_READLINE_H && HAVE_READLINE
27#include <readline/readline.h>
28#include <readline/history.h>
29#define USE_READLINE 1
5039dede
AK
30#endif
31
32#ifdef _WIN32
a23d8e0d
VK
33#include <errno.h>
34#include <psapi.h>
d717b69c
VK
35#define open _open
36#define write _write
37#define close _close
5039dede 38#else
a23d8e0d
VK
39#include <signal.h>
40#include <sys/wait.h>
5039dede
AK
41#endif
42
43
44//
45// Messages generated by mc.pl (for UNIX version only)
46//
47
48#ifndef _WIN32
49extern unsigned int g_dwNumMessages;
50extern const TCHAR *g_szMessages[];
51#endif
52
53
54//
55// Shutdown reasons
56//
57
58#define SHUTDOWN_DEFAULT 0
59#define SHUTDOWN_FROM_CONSOLE 1
60#define SHUTDOWN_BY_SIGNAL 2
61
62
63//
64// Externals
65//
66
67extern Queue g_statusPollQueue;
68extern Queue g_configPollQueue;
040c45fa 69extern Queue g_topologyPollQueue;
5039dede
AK
70extern Queue g_routePollQueue;
71extern Queue g_discoveryPollQueue;
72extern Queue g_nodePollerQueue;
73extern Queue g_conditionPollerQueue;
74extern Queue *g_pItemQueue;
75
36e44abe
VK
76void InitClientListeners();
77void InitCertificates();
ab185583
VK
78void InitUsers();
79void CleanupUsers();
5039dede
AK
80
81
82//
83// Thread functions
84//
85
86THREAD_RESULT THREAD_CALL HouseKeeper(void *pArg);
87THREAD_RESULT THREAD_CALL Syncer(void *pArg);
88THREAD_RESULT THREAD_CALL NodePoller(void *pArg);
89THREAD_RESULT THREAD_CALL PollManager(void *pArg);
90THREAD_RESULT THREAD_CALL EventProcessor(void *pArg);
91THREAD_RESULT THREAD_CALL WatchdogThread(void *pArg);
92THREAD_RESULT THREAD_CALL ClientListener(void *pArg);
36e44abe 93THREAD_RESULT THREAD_CALL ClientListenerIPv6(void *arg);
5039dede
AK
94THREAD_RESULT THREAD_CALL ISCListener(void *pArg);
95THREAD_RESULT THREAD_CALL LocalAdminListener(void *pArg);
96THREAD_RESULT THREAD_CALL SNMPTrapReceiver(void *pArg);
97THREAD_RESULT THREAD_CALL SyslogDaemon(void *pArg);
98THREAD_RESULT THREAD_CALL BeaconPoller(void *pArg);
3929b1ca 99THREAD_RESULT THREAD_CALL JobManagerThread(void *arg);
5039dede
AK
100
101
102//
103// Global variables
104//
105
106TCHAR NXCORE_EXPORTABLE g_szConfigFile[MAX_PATH] = DEFAULT_CONFIG_FILE;
107TCHAR NXCORE_EXPORTABLE g_szLogFile[MAX_PATH] = DEFAULT_LOG_FILE;
108TCHAR NXCORE_EXPORTABLE g_szDumpDir[MAX_PATH] = DEFAULT_DUMP_DIR;
109TCHAR g_szCodePage[256] = ICONV_DEFAULT_CODEPAGE;
110TCHAR NXCORE_EXPORTABLE g_szListenAddress[MAX_PATH] = _T("0.0.0.0");
111#ifndef _WIN32
35f836fe 112char NXCORE_EXPORTABLE g_szPIDFile[MAX_PATH] = _T("/var/run/netxmsd.pid");
5039dede
AK
113#endif
114DB_HANDLE g_hCoreDB = 0;
115DWORD g_dwDiscoveryPollingInterval;
116DWORD g_dwStatusPollingInterval;
117DWORD g_dwConfigurationPollingInterval;
118DWORD g_dwRoutingTableUpdateInterval;
040c45fa 119DWORD g_dwTopologyPollingInterval;
5039dede
AK
120DWORD g_dwConditionPollingInterval;
121DWORD g_dwPingSize;
122DWORD g_dwAuditFlags;
d96bd4c7 123TCHAR g_szDataDir[MAX_PATH] = _T("");
9796ce45 124TCHAR g_szLibDir[MAX_PATH] = DEFAULT_LIBDIR;
28f5b9a4 125int g_nDBSyntax = DB_SYNTAX_UNKNOWN;
73869331 126DWORD NXCORE_EXPORTABLE g_processAffinityMask = DEFAULT_AFFINITY_MASK;
5039dede
AK
127QWORD g_qwServerId;
128RSA *g_pServerKey = NULL;
129time_t g_tServerStartTime = 0;
130DWORD g_dwLockTimeout = 60000; // Default timeout for acquiring mutex
5039dede
AK
131DWORD g_dwAgentCommandTimeout = 2000; // Default timeout for requests to agent
132DWORD g_dwThresholdRepeatInterval = 0; // Disabled by default
133int g_nRequiredPolls = 1;
b8c1ec69 134DB_DRIVER g_dbDriver = NULL;
5039dede
AK
135
136
137//
138// Static data
139//
140
141static CONDITION m_condShutdown = INVALID_CONDITION_HANDLE;
142static THREAD m_thPollManager = INVALID_THREAD_HANDLE;
143static THREAD m_thHouseKeeper = INVALID_THREAD_HANDLE;
144static THREAD m_thSyncer = INVALID_THREAD_HANDLE;
145static THREAD m_thSyslogDaemon = INVALID_THREAD_HANDLE;
146static int m_nShutdownReason = SHUTDOWN_DEFAULT;
147
148#ifndef _WIN32
149static pthread_t m_signalHandlerThread;
150#endif
151
152
153//
154// Sleep for specified number of seconds or until system shutdown arrives
155// Function will return TRUE if shutdown event occurs
156//
157
158BOOL NXCORE_EXPORTABLE SleepAndCheckForShutdown(int iSeconds)
159{
160 return ConditionWait(m_condShutdown, iSeconds * 1000);
161}
162
163
164//
165// Disconnect from database (exportable function for startup module)
166//
167
73869331 168void NXCORE_EXPORTABLE ShutdownDB()
5039dede
AK
169{
170 if (g_hCoreDB != NULL)
171 DBDisconnect(g_hCoreDB);
b8c1ec69 172 DBUnloadDriver(g_dbDriver);
5039dede
AK
173}
174
175
176//
177// Check data directory for existence
178//
179
35f836fe 180static BOOL CheckDataDir()
5039dede 181{
35f836fe 182 TCHAR szBuffer[MAX_PATH];
5039dede 183
35f836fe 184 if (_tchdir(g_szDataDir) == -1)
5039dede
AK
185 {
186 nxlog_write(MSG_INVALID_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", g_szDataDir);
187 return FALSE;
188 }
189
190#ifdef _WIN32
35f836fe 191#define MKDIR(name) _tmkdir(name)
5039dede 192#else
35f836fe 193#define MKDIR(name) _tmkdir(name, 0700)
5039dede
AK
194#endif
195
196 // Create directory for mib files if it doesn't exist
35f836fe
VK
197 _tcscpy(szBuffer, g_szDataDir);
198 _tcscat(szBuffer, DDIR_MIBS);
5039dede
AK
199 if (MKDIR(szBuffer) == -1)
200 if (errno != EEXIST)
201 {
202 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
203 return FALSE;
204 }
205
5039dede 206 // Create directory for package files if it doesn't exist
35f836fe
VK
207 _tcscpy(szBuffer, g_szDataDir);
208 _tcscat(szBuffer, DDIR_PACKAGES);
5039dede
AK
209 if (MKDIR(szBuffer) == -1)
210 if (errno != EEXIST)
211 {
212 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
213 return FALSE;
214 }
215
4d0c32f3 216 // Create directory for map background images if it doesn't exist
35f836fe
VK
217 _tcscpy(szBuffer, g_szDataDir);
218 _tcscat(szBuffer, DDIR_BACKGROUNDS);
4d0c32f3
VK
219 if (MKDIR(szBuffer) == -1)
220 if (errno != EEXIST)
221 {
222 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
223 return FALSE;
224 }
225
e6b9439a
AK
226 // Create directory for image library is if does't exists
227 _tcscpy(szBuffer, g_szDataDir);
228 _tcscat(szBuffer, DDIR_IMAGES);
229 if (MKDIR(szBuffer) == -1)
230 {
231 if (errno != EEXIST)
232 {
233 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
234 return FALSE;
235 }
236 }
237
619e5c9b
VK
238 // Create directory for file store if does't exists
239 _tcscpy(szBuffer, g_szDataDir);
240 _tcscat(szBuffer, DDIR_FILES);
241 if (MKDIR(szBuffer) == -1)
242 {
243 if (errno != EEXIST)
244 {
245 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
246 return FALSE;
247 }
248 }
249
5039dede
AK
250#undef MKDIR
251
252 return TRUE;
253}
254
255
256//
257// Load global configuration parameters
258//
259
260static void LoadGlobalConfig()
261{
35f836fe
VK
262 g_dwDiscoveryPollingInterval = ConfigReadInt(_T("DiscoveryPollingInterval"), 900);
263 g_dwStatusPollingInterval = ConfigReadInt(_T("StatusPollingInterval"), 60);
264 g_dwConfigurationPollingInterval = ConfigReadInt(_T("ConfigurationPollingInterval"), 3600);
265 g_dwRoutingTableUpdateInterval = ConfigReadInt(_T("RoutingTableUpdateInterval"), 300);
040c45fa 266 g_dwTopologyPollingInterval = ConfigReadInt(_T("TopologyPollingInterval"), 1800);
35f836fe
VK
267 g_dwConditionPollingInterval = ConfigReadInt(_T("ConditionPollingInterval"), 60);
268 if (ConfigReadInt(_T("DeleteEmptySubnets"), 1))
5039dede 269 g_dwFlags |= AF_DELETE_EMPTY_SUBNETS;
35f836fe 270 if (ConfigReadInt(_T("EnableSNMPTraps"), 1))
5039dede 271 g_dwFlags |= AF_ENABLE_SNMP_TRAPD;
35f836fe 272 if (ConfigReadInt(_T("EnableZoning"), 0))
5039dede 273 g_dwFlags |= AF_ENABLE_ZONING;
35f836fe 274 if (ConfigReadInt(_T("EnableMultipleDBConnections"), 1))
2a8e6a7b
VK
275 {
276 // SQLite has troubles with multiple connections to the same database
277 // from different threads, and it does not speed up database access
278 // anyway, so we will not enable multiple connections for SQLite
279 if (g_nDBSyntax != DB_SYNTAX_SQLITE)
280 {
281 g_dwFlags |= AF_ENABLE_MULTIPLE_DB_CONN;
282 }
283 else
284 {
285 DbgPrintf(1, _T("Configuration parameter EnableMultipleDBConnections ignored because database engine is SQLite"));
286 }
287 }
35f836fe 288 if (ConfigReadInt(_T("RunNetworkDiscovery"), 0))
5039dede 289 g_dwFlags |= AF_ENABLE_NETWORK_DISCOVERY;
35f836fe 290 if (ConfigReadInt(_T("ActiveNetworkDiscovery"), 0))
5039dede 291 g_dwFlags |= AF_ACTIVE_NETWORK_DISCOVERY;
35f836fe 292 if (ConfigReadInt(_T("ResolveNodeNames"), 1))
5039dede 293 g_dwFlags |= AF_RESOLVE_NODE_NAMES;
35f836fe 294 if (ConfigReadInt(_T("SyncNodeNamesWithDNS"), 0))
5039dede 295 g_dwFlags |= AF_SYNC_NODE_NAMES_WITH_DNS;
35f836fe 296 if (ConfigReadInt(_T("InternalCA"), 0))
5039dede 297 g_dwFlags |= AF_INTERNAL_CA;
35f836fe 298 if (ConfigReadInt(_T("CheckTrustedNodes"), 1))
5039dede 299 g_dwFlags |= AF_CHECK_TRUSTED_NODES;
d96bd4c7
VK
300
301 if (g_szDataDir[0] == 0)
302 {
35f836fe 303 ConfigReadStr(_T("DataDirectory"), g_szDataDir, MAX_PATH, DEFAULT_DATA_DIR);
d96bd4c7
VK
304 DbgPrintf(1, _T("Data directory set to %s from server configuration variable"), g_szDataDir);
305 }
306 else
307 {
308 DbgPrintf(1, _T("Using data directory %s"), g_szDataDir);
309 }
310
35f836fe
VK
311 g_dwPingSize = ConfigReadInt(_T("IcmpPingSize"), 46);
312 g_dwLockTimeout = ConfigReadInt(_T("LockTimeout"), 60000);
313 g_dwSNMPTimeout = ConfigReadInt(_T("SNMPRequestTimeout"), 2000);
314 g_dwAgentCommandTimeout = ConfigReadInt(_T("AgentCommandTimeout"), 2000);
315 g_dwThresholdRepeatInterval = ConfigReadInt(_T("ThresholdRepeatInterval"), 0);
316 g_nRequiredPolls = ConfigReadInt(_T("PollCountForStatusChange"), 1);
5039dede
AK
317}
318
319
320//
321// Initialize cryptografic functions
322//
323
73869331 324static BOOL InitCryptografy()
5039dede
AK
325{
326#ifdef _WITH_ENCRYPTION
35f836fe 327 TCHAR szKeyFile[MAX_PATH];
5039dede
AK
328 BOOL bResult = FALSE;
329 int fd, iPolicy;
330 DWORD dwLen;
331 BYTE *pBufPos, *pKeyBuffer, hash[SHA1_DIGEST_SIZE];
332
35f836fe 333 if (!InitCryptoLib(ConfigReadULong(_T("AllowedCiphers"), 15)))
5039dede
AK
334 return FALSE;
335
35f836fe
VK
336 _tcscpy(szKeyFile, g_szDataDir);
337 _tcscat(szKeyFile, DFILE_KEYS);
338 fd = _topen(szKeyFile, O_RDONLY | O_BINARY);
5039dede
AK
339 g_pServerKey = LoadRSAKeys(szKeyFile);
340 if (g_pServerKey == NULL)
341 {
35f836fe 342 DbgPrintf(1, _T("Generating RSA key pair..."));
5039dede
AK
343 g_pServerKey = RSA_generate_key(NETXMS_RSA_KEYLEN, 17, NULL, 0);
344 if (g_pServerKey != NULL)
345 {
35f836fe 346 fd = _topen(szKeyFile, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, 0600);
5039dede
AK
347 if (fd != -1)
348 {
349 dwLen = i2d_RSAPublicKey(g_pServerKey, NULL);
350 dwLen += i2d_RSAPrivateKey(g_pServerKey, NULL);
351 pKeyBuffer = (BYTE *)malloc(dwLen);
352
353 pBufPos = pKeyBuffer;
354 i2d_RSAPublicKey(g_pServerKey, &pBufPos);
355 i2d_RSAPrivateKey(g_pServerKey, &pBufPos);
356 write(fd, &dwLen, sizeof(DWORD));
357 write(fd, pKeyBuffer, dwLen);
358
359 CalculateSHA1Hash(pKeyBuffer, dwLen, hash);
360 write(fd, hash, SHA1_DIGEST_SIZE);
361
362 close(fd);
363 free(pKeyBuffer);
364 bResult = TRUE;
365 }
366 }
367 }
368 else
369 {
370 bResult = TRUE;
371 }
372
35f836fe 373 iPolicy = ConfigReadInt(_T("DefaultEncryptionPolicy"), 1);
5039dede
AK
374 if ((iPolicy < 0) || (iPolicy > 3))
375 iPolicy = 1;
376 SetAgentDEP(iPolicy);
377
378 return bResult;
379#else
380 return TRUE;
381#endif
382}
383
384
385//
386// Check if process with given PID exists and is a NetXMS server process
387//
388
389static BOOL IsNetxmsdProcess(DWORD dwPID)
390{
391#ifdef _WIN32
392 HANDLE hProcess;
393 TCHAR szExtModule[MAX_PATH], szIntModule[MAX_PATH];
394 BOOL bRet = FALSE;
395
396 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwPID);
397 if (hProcess != NULL)
398 {
399 if ((GetModuleBaseName(hProcess, NULL, szExtModule, MAX_PATH) > 0) &&
400 (GetModuleBaseName(GetCurrentProcess(), NULL, szIntModule, MAX_PATH) > 0))
401 {
402 bRet = !_tcsicmp(szExtModule, szIntModule);
403 }
404 else
405 {
406 // Cannot read process name, for safety assume that it's a server process
407 bRet = TRUE;
408 }
409 CloseHandle(hProcess);
410 }
411 return bRet;
412#else
413 return (kill((pid_t)dwPID, 0) != -1);
414#endif
415}
416
417
418//
419// Database event handler
420//
421
35f836fe 422static void DBEventHandler(DWORD dwEvent, const WCHAR *pszArg1, const WCHAR *pszArg2, void *userArg)
5039dede
AK
423{
424 if (!(g_dwFlags & AF_SERVER_INITIALIZED))
425 return; // Don't try to do anything if server is not ready yet
426
427 switch(dwEvent)
428 {
429 case DBEVENT_CONNECTION_LOST:
430 PostEvent(EVENT_DB_CONNECTION_LOST, g_dwMgmtNode, NULL);
431 g_dwFlags |= AF_DB_CONNECTION_LOST;
432 NotifyClientSessions(NX_NOTIFY_DBCONN_STATUS, FALSE);
433 break;
434 case DBEVENT_CONNECTION_RESTORED:
435 PostEvent(EVENT_DB_CONNECTION_RESTORED, g_dwMgmtNode, NULL);
436 g_dwFlags &= ~AF_DB_CONNECTION_LOST;
437 NotifyClientSessions(NX_NOTIFY_DBCONN_STATUS, TRUE);
438 break;
4d0c32f3
VK
439 case DBEVENT_QUERY_FAILED:
440 PostEvent(EVENT_DB_QUERY_FAILED, g_dwMgmtNode, "ss", pszArg1, pszArg2);
441 break;
5039dede
AK
442 default:
443 break;
444 }
445}
446
447
448//
f669df41
VK
449// Send console message to session with open console
450//
451
452static void SendConsoleMessage(ClientSession *session, void *arg)
453{
454 if (session->isConsoleOpen())
455 {
456 CSCPMessage msg;
457
458 msg.SetCode(CMD_ADM_MESSAGE);
459 msg.SetVariable(VID_MESSAGE, (TCHAR *)arg);
d3a7cf4c 460 session->postMessage(&msg);
f669df41
VK
461 }
462}
463
464
465//
466// Console writer
467//
468
469static void LogConsoleWriter(const TCHAR *format, ...)
470{
471 TCHAR buffer[8192];
472 va_list args;
473
474 va_start(args, format);
475 _vsntprintf(buffer, 8192, format, args);
476 buffer[8191] = 0;
477 va_end(args);
478
479 WriteToTerminal(buffer);
480
481 EnumerateClientSessions(SendConsoleMessage, buffer);
482}
483
484
485//
5039dede
AK
486// Server initialization
487//
488
bc980b27 489BOOL NXCORE_EXPORTABLE Initialize()
5039dede
AK
490{
491 int i, iDBVersion;
492 DWORD dwAddr;
35f836fe 493 TCHAR szInfo[256];
5039dede
AK
494
495 g_tServerStartTime = time(NULL);
496 srand((unsigned int)g_tServerStartTime);
497 nxlog_open((g_dwFlags & AF_USE_SYSLOG) ? NETXMSD_SYSLOG_NAME : g_szLogFile,
498 ((g_dwFlags & AF_USE_SYSLOG) ? NXLOG_USE_SYSLOG : 0) |
499 ((g_dwFlags & AF_DAEMON) ? 0 : NXLOG_PRINT_TO_STDOUT),
500 _T("LIBNXSRV.DLL"),
501#ifdef _WIN32
502 0, NULL);
503#else
504 g_dwNumMessages, g_szMessages);
505#endif
f669df41 506 nxlog_set_console_writer(LogConsoleWriter);
5039dede
AK
507
508 // Set code page
509#ifndef _WIN32
510 if (SetDefaultCodepage(g_szCodePage))
511 {
35f836fe 512 DbgPrintf(1, _T("Code page set to %s"), g_szCodePage);
5039dede
AK
513 }
514 else
515 {
516 nxlog_write(MSG_CODEPAGE_ERROR, EVENTLOG_WARNING_TYPE, "s", g_szCodePage);
517 }
518#endif
519
73869331
VK
520 // Set process affinity mask
521 if (g_processAffinityMask != DEFAULT_AFFINITY_MASK)
522 {
523#ifdef _WIN32
524 if (SetProcessAffinityMask(GetCurrentProcess(), g_processAffinityMask))
525 DbgPrintf(1, _T("Process affinity mask set to 0x%08X"), g_processAffinityMask);
526#else
527 nxlog_write(MSG_SET_PROCESS_AFFINITY_NOT_SUPPORTED, EVENTLOG_WARNING_TYPE, NULL);
528#endif
529 }
530
5039dede
AK
531#ifdef _WIN32
532 WSADATA wsaData;
1ddf3f0c
VK
533 int wrc = WSAStartup(MAKEWORD(2, 2), &wsaData);
534 if (wrc != 0)
535 {
536 nxlog_write(MSG_WSASTARTUP_FAILED, EVENTLOG_ERROR_TYPE, "e", wrc);
537 return FALSE;
538 }
5039dede
AK
539#endif
540
541 InitLocalNetInfo();
542
543 // Create queue for delayed SQL queries
73869331 544 g_pLazyRequestQueue = new Queue(256, 64);
5039dede
AK
545
546 // Initialize database driver and connect to database
9d88cdc9 547 DBSetDebugPrintCallback(DbgPrintf2);
b8c1ec69
VK
548 if (!DBInit(MSG_OTHER, (g_dwFlags & AF_LOG_SQL_ERRORS) ? MSG_SQL_ERROR : 0))
549 return FALSE;
550 g_dbDriver = DBLoadDriver(g_szDbDriver, g_szDbDrvParams, (g_nDebugLevel >= 9), DBEventHandler, NULL);
551 if (g_dbDriver == NULL)
5039dede
AK
552 return FALSE;
553
554 // Connect to database
465b3f2d 555 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
5039dede
AK
556 for(i = 0; ; i++)
557 {
465b3f2d 558 g_hCoreDB = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, errorText);
5039dede
AK
559 if ((g_hCoreDB != NULL) || (i == 5))
560 break;
561 ThreadSleep(5);
562 }
563 if (g_hCoreDB == NULL)
564 {
465b3f2d 565 nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
5039dede
AK
566 return FALSE;
567 }
35f836fe 568 DbgPrintf(1, _T("Successfully connected to database %s@%s"), g_szDbName, g_szDbServer);
5039dede
AK
569
570 // Check database version
28f5b9a4 571 iDBVersion = DBGetSchemaVersion(g_hCoreDB);
5039dede
AK
572 if (iDBVersion != DB_FORMAT_VERSION)
573 {
574 nxlog_write(MSG_WRONG_DB_VERSION, EVENTLOG_ERROR_TYPE, "dd", iDBVersion, DB_FORMAT_VERSION);
575 return FALSE;
576 }
577
35f836fe
VK
578 int baseSize = ConfigReadInt(_T("ConnectionPoolBaseSize"), 5);
579 int maxSize = ConfigReadInt(_T("ConnectionPoolMaxSize"), 20);
580 int cooldownTime = ConfigReadInt(_T("ConnectionPoolCooldownTime"), 300);
465b3f2d 581 DBConnectionPoolStartup(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, baseSize, maxSize, cooldownTime, g_hCoreDB);
f727d089 582
5039dede 583 // Read database syntax
28f5b9a4 584 g_nDBSyntax = DBGetSyntax(g_hCoreDB);
5039dede
AK
585
586 // Read server ID
35f836fe 587 ConfigReadStr(_T("ServerID"), szInfo, 256, _T(""));
5039dede
AK
588 StrStrip(szInfo);
589 if (szInfo[0] != 0)
590 {
591 StrToBin(szInfo, (BYTE *)&g_qwServerId, sizeof(QWORD));
592 }
593 else
594 {
595 // Generate new ID
596 g_qwServerId = (((QWORD)time(NULL)) << 32) | rand();
597 BinToStr((BYTE *)&g_qwServerId, sizeof(QWORD), szInfo);
35f836fe 598 ConfigWriteStr(_T("ServerID"), szInfo, TRUE);
5039dede
AK
599 }
600
601 // Initialize locks
602retry_db_lock:
603 if (!InitLocks(&dwAddr, szInfo))
604 {
605 if (dwAddr == UNLOCKED) // Some SQL problems
606 {
607 nxlog_write(MSG_INIT_LOCKS_FAILED, EVENTLOG_ERROR_TYPE, NULL);
608 }
609 else // Database already locked by another server instance
610 {
611 // Check for lock from crashed/terminated local process
612 if (dwAddr == GetLocalIpAddr())
613 {
614 DWORD dwPID;
615
35f836fe 616 dwPID = ConfigReadULong(_T("DBLockPID"), 0);
5039dede
AK
617 if (!IsNetxmsdProcess(dwPID) || (dwPID == GetCurrentProcessId()))
618 {
619 UnlockDB();
620 nxlog_write(MSG_DB_LOCK_REMOVED, EVENTLOG_INFORMATION_TYPE, NULL);
621 goto retry_db_lock;
622 }
623 }
624 nxlog_write(MSG_DB_LOCKED, EVENTLOG_ERROR_TYPE, "as", dwAddr, szInfo);
625 }
626 return FALSE;
627 }
628 g_dwFlags |= AF_DB_LOCKED;
629
630 // Load global configuration parameters
631 LoadGlobalConfig();
35f836fe 632 DbgPrintf(1, _T("Global configuration loaded"));
5039dede
AK
633
634 // Check data directory
635 if (!CheckDataDir())
636 return FALSE;
637
638 // Initialize cryptografy
639 if (!InitCryptografy())
640 {
641 nxlog_write(MSG_INIT_CRYPTO_FAILED, EVENTLOG_ERROR_TYPE, NULL);
642 return FALSE;
643 }
644
645 // Initialize certificate store and CA
646 InitCertificates();
647
5039dede
AK
648 // Create synchronization stuff
649 m_condShutdown = ConditionCreate(TRUE);
650
651 // Setup unique identifiers table
652 if (!InitIdTable())
653 return FALSE;
35f836fe 654 DbgPrintf(2, _T("ID table created"));
5039dede
AK
655
656 // Load and compile scripts
657 LoadScripts();
658
659 // Initialize mailer and SMS sender
660 InitMailer();
661 InitSMSSender();
662
663 // Load users from database
ab185583 664 InitUsers();
5039dede
AK
665 if (!LoadUsers())
666 {
667 nxlog_write(MSG_ERROR_LOADING_USERS, EVENTLOG_ERROR_TYPE, NULL);
668 return FALSE;
669 }
35f836fe 670 DbgPrintf(2, _T("User accounts loaded"));
5039dede
AK
671
672 // Initialize audit
673 InitAuditLog();
674
675 // Initialize objects infrastructure and load objects from database
9796ce45 676 LoadNetworkDeviceDrivers();
5039dede
AK
677 ObjectsInit();
678 if (!LoadObjects())
679 return FALSE;
680 LoadMaps();
35f836fe 681 DbgPrintf(1, _T("Objects loaded and initialized"));
5039dede
AK
682
683 // Initialize situations
684 if (!SituationsInit())
685 return FALSE;
35f836fe 686 DbgPrintf(1, _T("Situations loaded and initialized"));
5039dede
AK
687
688 // Initialize and load event actions
689 if (!InitActions())
690 {
691 nxlog_write(MSG_ACTION_INIT_ERROR, EVENTLOG_ERROR_TYPE, NULL);
692 return FALSE;
693 }
694
695 // Initialize event handling subsystem
696 if (!InitEventSubsystem())
697 return FALSE;
698
699 // Initialize alarms
700 if (!g_alarmMgr.Init())
701 return FALSE;
702
703 // Initialize data collection subsystem
704 if (!InitDataCollector())
705 return FALSE;
706
e05b1945
VK
707 InitLogAccess();
708
5039dede
AK
709 // Initialize watchdog
710 WatchdogInit();
711
712 // Check if management node object presented in database
713 CheckForMgmtNode();
714 if (g_dwMgmtNode == 0)
715 {
716 nxlog_write(MSG_CANNOT_FIND_SELF, EVENTLOG_ERROR_TYPE, NULL);
717 return FALSE;
718 }
719
720 // Start threads
721 ThreadCreate(WatchdogThread, 0, NULL);
722 ThreadCreate(NodePoller, 0, NULL);
3929b1ca 723 ThreadCreate(JobManagerThread, 0, NULL);
5039dede
AK
724 m_thSyncer = ThreadCreateEx(Syncer, 0, NULL);
725 m_thHouseKeeper = ThreadCreateEx(HouseKeeper, 0, NULL);
726 m_thPollManager = ThreadCreateEx(PollManager, 0, NULL);
727
728 // Start event processor
729 ThreadCreate(EventProcessor, 0, NULL);
730
731 // Start SNMP trapper
732 InitTraps();
35f836fe 733 if (ConfigReadInt(_T("EnableSNMPTraps"), 1))
5039dede
AK
734 ThreadCreate(SNMPTrapReceiver, 0, NULL);
735
736 // Start built-in syslog daemon
35f836fe 737 if (ConfigReadInt(_T("EnableSyslogDaemon"), 0))
5039dede
AK
738 m_thSyslogDaemon = ThreadCreateEx(SyslogDaemon, 0, NULL);
739
35f836fe 740 // Start database _T("lazy") write thread
5039dede
AK
741 StartDBWriter();
742
743 // Start local administartive interface listener if required
35f836fe 744 if (ConfigReadInt(_T("EnableAdminInterface"), 1))
5039dede
AK
745 ThreadCreate(LocalAdminListener, 0, NULL);
746
747 // Load modules
748 LoadNetXMSModules();
749
750 // Start beacon host poller
751 ThreadCreate(BeaconPoller, 0, NULL);
752
753 // Start inter-server communication listener
35f836fe 754 if (ConfigReadInt(_T("EnableISCListener"), 0))
5039dede
AK
755 ThreadCreate(ISCListener, 0, NULL);
756
757 // Allow clients to connect
36e44abe 758 InitClientListeners();
5039dede 759 ThreadCreate(ClientListener, 0, NULL);
36e44abe
VK
760#ifdef WITH_IPV6
761 ThreadCreate(ClientListenerIPv6, 0, NULL);
762#endif
5039dede
AK
763
764 g_dwFlags |= AF_SERVER_INITIALIZED;
35f836fe 765 DbgPrintf(1, _T("Server initialization completed"));
5039dede
AK
766 return TRUE;
767}
768
769
770//
771// Server shutdown
772//
773
035a4d73 774void NXCORE_EXPORTABLE Shutdown()
5039dede
AK
775{
776 DWORD i, dwNumThreads;
777
778 // Notify clients
779 NotifyClientSessions(NX_NOTIFY_SHUTDOWN, 0);
780
781 nxlog_write(MSG_SERVER_STOPPED, EVENTLOG_INFORMATION_TYPE, NULL);
782 g_dwFlags |= AF_SHUTDOWN; // Set shutdown flag
783 ConditionSet(m_condShutdown);
784
785#ifndef _WIN32
786 if (IsStandalone() && (m_nShutdownReason != SHUTDOWN_BY_SIGNAL))
787 {
788 pthread_kill(m_signalHandlerThread, SIGUSR1); // Terminate signal handler
789 }
790#endif
791
792 // Stop event processor(s)
793 g_pEventQueue->Clear();
35f836fe 794 dwNumThreads = ConfigReadInt(_T("NumberOfEventProcessors"), 1);
5039dede
AK
795 for(i = 0; i < dwNumThreads; i++)
796 g_pEventQueue->Put(INVALID_POINTER_VALUE);
797
798 ShutdownMailer();
799 ShutdownSMSSender();
800
801 ThreadSleep(1); // Give other threads a chance to terminate in a safe way
35f836fe 802 DbgPrintf(2, _T("All threads was notified, continue with shutdown"));
5039dede
AK
803
804 // Wait for critical threads
805 ThreadJoin(m_thHouseKeeper);
806 ThreadJoin(m_thPollManager);
807 ThreadJoin(m_thSyncer);
808 ThreadJoin(m_thSyslogDaemon);
809
810 SaveObjects(g_hCoreDB);
35f836fe 811 DbgPrintf(2, _T("All objects saved to database"));
5039dede 812 SaveUsers(g_hCoreDB);
35f836fe 813 DbgPrintf(2, _T("All users saved to database"));
5039dede 814 StopDBWriter();
35f836fe 815 DbgPrintf(1, _T("Database writer stopped"));
5039dede 816
ab185583
VK
817 CleanupUsers();
818
5039dede
AK
819 // Remove database lock
820 UnlockDB();
821
822 // Disconnect from database and unload driver
823 if (g_hCoreDB != NULL)
824 DBDisconnect(g_hCoreDB);
c20b2798
AK
825
826 DBConnectionPoolShutdown();
827
b8c1ec69 828 DBUnloadDriver(g_dbDriver);
35f836fe 829 DbgPrintf(1, _T("Database driver unloaded"));
5039dede
AK
830
831 CleanupActions();
832 ShutdownEventSubsystem();
35f836fe 833 DbgPrintf(1, _T("Event processing stopped"));
5039dede
AK
834
835 // Delete all objects
836 //for(i = 0; i < g_dwIdIndexSize; i++)
837 // delete g_pIndexById[i].pObject;
838
839 delete g_pScriptLibrary;
840
841 nxlog_close();
842
843 // Remove PID file
844#ifndef _WIN32
845 remove(g_szPIDFile);
846#endif
847
848 // Terminate process
849#ifdef _WIN32
850 if (!(g_dwFlags & AF_DAEMON))
851 ExitProcess(0);
852#else
853 exit(0);
854#endif
855}
856
857
858//
859// Fast server shutdown - normally called only by Windows service on system shutdown
860//
861
f669df41 862void NXCORE_EXPORTABLE FastShutdown()
5039dede
AK
863{
864 g_dwFlags |= AF_SHUTDOWN; // Set shutdown flag
865 ConditionSet(m_condShutdown);
866
867 SaveObjects(g_hCoreDB);
35f836fe 868 DbgPrintf(2, _T("All objects saved to database"));
5039dede 869 SaveUsers(g_hCoreDB);
35f836fe 870 DbgPrintf(2, _T("All users saved to database"));
5039dede
AK
871
872 // Remove database lock first, because we have a chance to loose DB connection
873 UnlockDB();
874
875 // Stop database writers
876 StopDBWriter();
35f836fe 877 DbgPrintf(1, _T("Database writer stopped"));
5039dede
AK
878
879 nxlog_close();
880}
881
882
883//
884// Compare given string to command template with abbreviation possibility
885//
886
35f836fe 887static BOOL IsCommand(const TCHAR *pszTemplate, TCHAR *pszString, int iMinChars)
5039dede
AK
888{
889 int i;
890
891 // Convert given string to uppercase
35f836fe 892 _tcsupr(pszString);
5039dede
AK
893
894 for(i = 0; pszString[i] != 0; i++)
895 if (pszString[i] != pszTemplate[i])
896 return FALSE;
897 if (i < iMinChars)
898 return FALSE;
899 return TRUE;
900}
901
902
903//
904// Dump index
905//
906
6aba3998 907static void DumpIndex(CONSOLE_CTX pCtx, ObjectIndex *index, BOOL bIndexByIp)
5039dede
AK
908{
909 DWORD i;
35f836fe 910 TCHAR szIpAddr[16];
5039dede 911
5039dede
AK
912 for(i = 0; i < dwSize; i++)
913 {
914 if (bIndexByIp)
915 {
35f836fe 916 ConsolePrintf(pCtx, _T("%08X [%-15s] %p %s\n"), pIndex[i].dwKey,
5039dede
AK
917 IpToStr(pIndex[i].dwKey, szIpAddr),
918 pIndex[i].pObject, ((NetObj *)pIndex[i].pObject)->Name());
919 }
920 else
921 {
35f836fe 922 ConsolePrintf(pCtx, _T("%08X %p %s\n"), pIndex[i].dwKey, pIndex[i].pObject,
5039dede
AK
923 ((NetObj *)pIndex[i].pObject)->Name());
924 }
925 }
926
927 RWLockUnlock(hLock);
928}
929
930
931//
932// Process command entered from command line in standalone mode
35f836fe 933// Return TRUE if command was _T("down")
5039dede
AK
934//
935
35f836fe 936int ProcessConsoleCommand(const TCHAR *pszCmdLine, CONSOLE_CTX pCtx)
5039dede 937{
35f836fe 938 const TCHAR *pArg;
48c0079d 939 TCHAR szBuffer[256], *eptr;
5039dede
AK
940 int nExitCode = CMD_EXIT_CONTINUE;
941
942 // Get command
943 pArg = ExtractWord(pszCmdLine, szBuffer);
944
35f836fe 945 if (IsCommand(_T("DEBUG"), szBuffer, 2))
5039dede
AK
946 {
947 // Get argument
948 pArg = ExtractWord(pArg, szBuffer);
48c0079d
VK
949 int level = (int)_tcstol(szBuffer, &eptr, 0);
950 if ((*eptr == 0) && (level >= 0) && (level <= 9))
5039dede 951 {
48c0079d
VK
952 g_nDebugLevel = level;
953 ConsolePrintf(pCtx, (level == 0) ? _T("Debug mode turned off\n") : _T("Debug level set to %d\n"), level);
5039dede 954 }
35f836fe 955 else if (IsCommand(_T("OFF"), szBuffer, 2))
5039dede
AK
956 {
957 g_nDebugLevel = 0;
35f836fe 958 ConsolePrintf(pCtx, _T("Debug mode turned off\n"));
5039dede
AK
959 }
960 else
961 {
962 if (szBuffer[0] == 0)
35f836fe 963 ConsolePrintf(pCtx, _T("ERROR: Missing argument\n\n"));
5039dede 964 else
48c0079d 965 ConsolePrintf(pCtx, _T("ERROR: Invalid debug level\n\n"));
5039dede
AK
966 }
967 }
35f836fe 968 else if (IsCommand(_T("DOWN"), szBuffer, 4))
5039dede 969 {
35f836fe 970 ConsolePrintf(pCtx, _T("Proceeding with server shutdown...\n"));
5039dede
AK
971 nExitCode = CMD_EXIT_SHUTDOWN;
972 }
35f836fe 973 else if (IsCommand(_T("DUMP"), szBuffer, 4))
5039dede
AK
974 {
975 DumpProcess(pCtx);
976 }
35f836fe 977 else if (IsCommand(_T("RAISE"), szBuffer, 5))
5039dede
AK
978 {
979 // Get argument
980 pArg = ExtractWord(pArg, szBuffer);
981
35f836fe 982 if (IsCommand(_T("ACCESS"), szBuffer, 6))
5039dede 983 {
35f836fe 984 ConsolePrintf(pCtx, _T("Raising exception...\n"));
5039dede
AK
985 char *p = NULL;
986 *p = 0;
987 }
35f836fe 988 else if (IsCommand(_T("BREAKPOINT"), szBuffer, 5))
5039dede
AK
989 {
990#ifdef _WIN32
35f836fe 991 ConsolePrintf(pCtx, _T("Raising exception...\n"));
5039dede
AK
992 RaiseException(EXCEPTION_BREAKPOINT, 0, 0, NULL);
993#else
35f836fe 994 ConsolePrintf(pCtx, _T("ERROR: Not supported on current platform\n"));
5039dede
AK
995#endif
996 }
997 else
998 {
35f836fe 999 ConsolePrintf(pCtx, _T("Invalid exception name; possible names are:\nACCESS BREAKPOINT\n"));
5039dede
AK
1000 }
1001 }
35f836fe 1002 else if (IsCommand(_T("EXIT"), szBuffer, 4))
5039dede 1003 {
f669df41 1004 if ((pCtx->hSocket != -1) || (pCtx->session != NULL))
5039dede 1005 {
35f836fe 1006 ConsolePrintf(pCtx, _T("Closing session...\n"));
5039dede
AK
1007 nExitCode = CMD_EXIT_CLOSE_SESSION;
1008 }
1009 else
1010 {
35f836fe 1011 ConsolePrintf(pCtx, _T("Cannot exit from local server console\n"));
5039dede
AK
1012 }
1013 }
35f836fe 1014 else if (IsCommand(_T("SHOW"), szBuffer, 2))
5039dede
AK
1015 {
1016 // Get argument
1017 pArg = ExtractWord(pArg, szBuffer);
1018
35f836fe 1019 if (IsCommand(_T("FLAGS"), szBuffer, 1))
5039dede 1020 {
35f836fe 1021 ConsolePrintf(pCtx, _T("Flags: 0x%08X\n"), g_dwFlags);
5039dede
AK
1022 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DAEMON));
1023 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_USE_SYSLOG));
1024 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_NETWORK_DISCOVERY));
1025 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ACTIVE_NETWORK_DISCOVERY));
1026 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_LOG_SQL_ERRORS));
1027 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DELETE_EMPTY_SUBNETS));
1028 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_SNMP_TRAPD));
1029 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_ZONING));
5039dede 1030 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SYNC_NODE_NAMES_WITH_DNS));
cbc777ee
VK
1031 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_CHECK_TRUSTED_NODES));
1032 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_WRITE_FULL_DUMP));
1033 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_RESOLVE_NODE_NAMES));
5039dede 1034 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_CATCH_EXCEPTIONS));
5039dede
AK
1035 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_INTERNAL_CA));
1036 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_LOCKED));
cbc777ee 1037 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_MULTIPLE_DB_CONN));
5039dede 1038 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_CONNECTION_LOST));
cbc777ee 1039 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_NO_NETWORK_CONNECTIVITY));
5039dede
AK
1040 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_EVENT_STORM_DETECTED));
1041 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SERVER_INITIALIZED));
1042 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SHUTDOWN));
35f836fe 1043 ConsolePrintf(pCtx, _T("\n"));
5039dede 1044 }
35f836fe 1045 else if (IsCommand(_T("INDEX"), szBuffer, 1))
5039dede
AK
1046 {
1047 // Get argument
1048 pArg = ExtractWord(pArg, szBuffer);
1049
35f836fe 1050 if (IsCommand(_T("CONDITION"), szBuffer, 1))
5039dede 1051 {
6aba3998 1052 DumpIndex(pCtx, &g_idxConditionById, FALSE);
5039dede 1053 }
35f836fe 1054 else if (IsCommand(_T("ID"), szBuffer, 2))
5039dede 1055 {
6aba3998 1056 DumpIndex(pCtx, &g_idxObjectById, FALSE);
5039dede 1057 }
35f836fe 1058 else if (IsCommand(_T("INTERFACE"), szBuffer, 2))
5039dede 1059 {
6aba3998
VK
1060 DumpIndex(pCtx, &g_idxInterfaceByAddr, TRUE);
1061 }
1062 else if (IsCommand(_T("NODE"), szBuffer, 2))
1063 {
1064 DumpIndex(pCtx, &g_idxNodeById, FALSE);
5039dede 1065 }
35f836fe 1066 else if (IsCommand(_T("SUBNET"), szBuffer, 1))
5039dede 1067 {
6aba3998 1068 DumpIndex(pCtx, &g_idxSubnetByAddr, TRUE);
5039dede
AK
1069 }
1070 else
1071 {
1072 if (szBuffer[0] == 0)
35f836fe 1073 ConsolePrintf(pCtx, _T("ERROR: Missing index name\n")
889d7ff7 1074 _T("Valid names are: CONDITION, ID, INTERFACE, SUBNET\n\n"));
5039dede 1075 else
35f836fe 1076 ConsolePrintf(pCtx, _T("ERROR: Invalid index name\n\n"));
5039dede
AK
1077 }
1078 }
35f836fe 1079 else if (IsCommand(_T("MEMORY"), szBuffer, 2))
5039dede
AK
1080 {
1081#ifdef NETXMS_MEMORY_DEBUG
1082 PrintMemoryBlocks();
1083#else
35f836fe 1084 ConsolePrintf(pCtx, _T("ERROR: Server was compiled without memory debugger\n\n"));
5039dede
AK
1085#endif
1086 }
35f836fe 1087 else if (IsCommand(_T("OBJECTS"), szBuffer, 1))
5039dede
AK
1088 {
1089 DumpObjects(pCtx);
1090 }
35f836fe 1091 else if (IsCommand(_T("POLLERS"), szBuffer, 1))
5039dede
AK
1092 {
1093 ShowPollerState(pCtx);
1094 }
35f836fe 1095 else if (IsCommand(_T("QUEUES"), szBuffer, 1))
5039dede 1096 {
35f836fe
VK
1097 ShowQueueStats(pCtx, &g_conditionPollerQueue, _T("Condition poller"));
1098 ShowQueueStats(pCtx, &g_configPollQueue, _T("Configuration poller"));
040c45fa 1099 ShowQueueStats(pCtx, &g_topologyPollQueue, _T("Topology poller"));
35f836fe
VK
1100 ShowQueueStats(pCtx, g_pItemQueue, _T("Data collector"));
1101 ShowQueueStats(pCtx, g_pLazyRequestQueue, _T("Database writer"));
1102 ShowQueueStats(pCtx, g_pEventQueue, _T("Event processor"));
1103 ShowQueueStats(pCtx, &g_discoveryPollQueue, _T("Network discovery poller"));
1104 ShowQueueStats(pCtx, &g_nodePollerQueue, _T("Node poller"));
1105 ShowQueueStats(pCtx, &g_routePollQueue, _T("Routing table poller"));
1106 ShowQueueStats(pCtx, &g_statusPollQueue, _T("Status poller"));
1107 ConsolePrintf(pCtx, _T("\n"));
5039dede 1108 }
35f836fe 1109 else if (IsCommand(_T("ROUTING-TABLE"), szBuffer, 1))
5039dede
AK
1110 {
1111 DWORD dwNode;
1112 NetObj *pObject;
1113
1114 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1115 dwNode = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1116 if (dwNode != 0)
1117 {
1118 pObject = FindObjectById(dwNode);
1119 if (pObject != NULL)
1120 {
1121 if (pObject->Type() == OBJECT_NODE)
1122 {
1123 ROUTING_TABLE *pRT;
35f836fe 1124 TCHAR szIpAddr[16];
5039dede
AK
1125 int i;
1126
35f836fe 1127 ConsolePrintf(pCtx, _T("Routing table for node %s:\n\n"), pObject->Name());
58b3e451 1128 pRT = ((Node *)pObject)->getCachedRoutingTable();
5039dede
AK
1129 if (pRT != NULL)
1130 {
1131 for(i = 0; i < pRT->iNumEntries; i++)
1132 {
35f836fe
VK
1133 _sntprintf(szBuffer, 256, _T("%s/%d"), IpToStr(pRT->pRoutes[i].dwDestAddr, szIpAddr),
1134 BitsInMask(pRT->pRoutes[i].dwDestMask));
1135 ConsolePrintf(pCtx, _T("%-18s %-15s %-6d %d\n"), szBuffer,
1136 IpToStr(pRT->pRoutes[i].dwNextHop, szIpAddr),
1137 pRT->pRoutes[i].dwIfIndex, pRT->pRoutes[i].dwRouteType);
5039dede 1138 }
35f836fe 1139 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1140 }
1141 else
1142 {
35f836fe 1143 ConsolePrintf(pCtx, _T("Node doesn't have cached routing table\n\n"));
5039dede
AK
1144 }
1145 }
1146 else
1147 {
35f836fe 1148 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
5039dede
AK
1149 }
1150 }
1151 else
1152 {
35f836fe 1153 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode);
5039dede
AK
1154 }
1155 }
1156 else
1157 {
35f836fe 1158 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node ID\n\n"));
5039dede
AK
1159 }
1160 }
35f836fe 1161 else if (IsCommand(_T("SESSIONS"), szBuffer, 2))
5039dede
AK
1162 {
1163 DumpSessions(pCtx);
1164 }
35f836fe 1165 else if (IsCommand(_T("STATS"), szBuffer, 2))
5039dede
AK
1166 {
1167 ShowServerStats(pCtx);
1168 }
35f836fe 1169 else if (IsCommand(_T("USERS"), szBuffer, 1))
5039dede
AK
1170 {
1171 DumpUsers(pCtx);
1172 }
b0ff1179
VK
1173 else if (IsCommand(_T("VLANS"), szBuffer, 1))
1174 {
1175 DWORD dwNode;
1176 NetObj *pObject;
1177
1178 pArg = ExtractWord(pArg, szBuffer);
1179 dwNode = _tcstoul(szBuffer, NULL, 0);
1180 if (dwNode != 0)
1181 {
1182 pObject = FindObjectById(dwNode);
1183 if (pObject != NULL)
1184 {
1185 if (pObject->Type() == OBJECT_NODE)
1186 {
1187 VlanList *vlans = ((Node *)pObject)->getVlans();
1188 if (vlans != NULL)
1189 {
1190 ConsolePrintf(pCtx, _T("\x1b[1mVLAN\x1b[0m | \x1b[1mName\x1b[0m | \x1b[1mPorts\x1b[0m\n")
1191 _T("-----+------------------+-----------------------------------------------------------------\n"));
1192 for(int i = 0; i < vlans->getSize(); i++)
1193 {
1194 VlanInfo *vlan = vlans->get(i);
1195 ConsolePrintf(pCtx, _T("%4d | %-16s |"), vlan->getVlanId(), vlan->getName());
1196 for(int j = 0; j < vlan->getNumPorts(); j++)
1197 ConsolePrintf(pCtx, _T(" %d.%d"), (int)(vlan->getPorts()[j] >> 16), (int)(vlan->getPorts()[j] & 0xFFFF));
1198 ConsolePrintf(pCtx, _T("\n"));
1199 }
1200 ConsolePrintf(pCtx, _T("\n"));
1201 vlans->decRefCount();
1202 }
1203 else
1204 {
1205 ConsolePrintf(pCtx, _T("\x1b[31mNode doesn't have VLAN information\x1b[0m\n\n"));
1206 }
1207 }
1208 else
1209 {
1210 ConsolePrintf(pCtx, _T("\x1b[31mERROR: Object is not a node\x1b[0m\n\n"));
1211 }
1212 }
1213 else
1214 {
1215 ConsolePrintf(pCtx, _T("\x1b[31mERROR: Object with ID %d does not exist\x1b[0m\n\n"), dwNode);
1216 }
1217 }
1218 else
1219 {
1220 ConsolePrintf(pCtx, _T("\x1b[31mERROR: Invalid or missing node ID\x1b[0m\n\n"));
1221 }
1222 }
35f836fe 1223 else if (IsCommand(_T("WATCHDOG"), szBuffer, 1))
5039dede
AK
1224 {
1225 WatchdogPrintStatus(pCtx);
35f836fe 1226 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1227 }
1228 else
1229 {
1230 if (szBuffer[0] == 0)
35f836fe 1231 ConsolePrintf(pCtx, _T("ERROR: Missing subcommand\n\n"));
5039dede 1232 else
35f836fe 1233 ConsolePrintf(pCtx, _T("ERROR: Invalid SHOW subcommand\n\n"));
5039dede
AK
1234 }
1235 }
35f836fe 1236 else if (IsCommand(_T("TRACE"), szBuffer, 1))
5039dede
AK
1237 {
1238 DWORD dwNode1, dwNode2;
1239 NetObj *pObject1, *pObject2;
1240 NETWORK_PATH_TRACE *pTrace;
35f836fe 1241 TCHAR szNextHop[16];
5039dede
AK
1242 int i;
1243
1244 // Get arguments
1245 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1246 dwNode1 = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1247
1248 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1249 dwNode2 = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1250
1251 if ((dwNode1 != 0) && (dwNode2 != 0))
1252 {
1253 pObject1 = FindObjectById(dwNode1);
1254 if (pObject1 == NULL)
1255 {
35f836fe 1256 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode1);
5039dede
AK
1257 }
1258 else
1259 {
1260 pObject2 = FindObjectById(dwNode2);
1261 if (pObject2 == NULL)
1262 {
35f836fe 1263 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode2);
5039dede
AK
1264 }
1265 else
1266 {
1267 if ((pObject1->Type() == OBJECT_NODE) &&
1268 (pObject2->Type() == OBJECT_NODE))
1269 {
1270 pTrace = TraceRoute((Node *)pObject1, (Node *)pObject2);
1271 if (pTrace != NULL)
1272 {
35f836fe 1273 ConsolePrintf(pCtx, _T("Trace from %s to %s (%d hops):\n"),
5039dede
AK
1274 pObject1->Name(), pObject2->Name(), pTrace->iNumHops);
1275 for(i = 0; i < pTrace->iNumHops; i++)
35f836fe 1276 ConsolePrintf(pCtx, _T("[%d] %s %s %s %d\n"),
5039dede
AK
1277 pTrace->pHopList[i].pObject->Id(),
1278 pTrace->pHopList[i].pObject->Name(),
1279 IpToStr(pTrace->pHopList[i].dwNextHop, szNextHop),
35f836fe 1280 pTrace->pHopList[i].bIsVPN ? _T("VPN Connector ID:") : _T("Interface Index: "),
5039dede
AK
1281 pTrace->pHopList[i].dwIfIndex);
1282 DestroyTraceData(pTrace);
35f836fe 1283 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1284 }
1285 else
1286 {
35f836fe 1287 ConsolePrintf(pCtx, _T("ERROR: Call to TraceRoute() failed\n\n"));
5039dede
AK
1288 }
1289 }
1290 else
1291 {
35f836fe 1292 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
5039dede
AK
1293 }
1294 }
1295 }
1296 }
1297 else
1298 {
35f836fe 1299 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node id(s)\n\n"));
5039dede
AK
1300 }
1301 }
35f836fe 1302 else if (IsCommand(_T("HELP"), szBuffer, 2) || IsCommand(_T("?"), szBuffer, 1))
5039dede 1303 {
35f836fe 1304 ConsolePrintf(pCtx, _T("Valid commands are:\n")
48c0079d 1305 _T(" debug [<level>|off] - Set debug level (valid range is 0..9)\n")
35f836fe
VK
1306 _T(" down - Down NetXMS server\n")
1307 _T(" exit - Exit from remote session\n")
1308 _T(" help - Display this help\n")
1309 _T(" raise <exception> - Raise exception\n")
1310 _T(" show flags - Show internal server flags\n")
1311 _T(" show index <index> - Show internal index\n")
35f836fe
VK
1312 _T(" show objects - Dump network objects to screen\n")
1313 _T(" show pollers - Show poller threads state information\n")
1314 _T(" show queues - Show internal queues statistics\n")
1315 _T(" show routing-table <node> - Show cached routing table for node\n")
1316 _T(" show sessions - Show active client sessions\n")
1317 _T(" show stats - Show server statistics\n")
1318 _T(" show users - Show users\n")
b0ff1179 1319 _T(" show vlans <node> - Show cached VLAN information for node\n")
35f836fe
VK
1320 _T(" show watchdog - Display watchdog information\n")
1321 _T(" trace <node1> <node2> - Show network path trace between two nodes\n")
1322 _T("\nAlmost all commands can be abbreviated to 2 or 3 characters\n")
1323 _T("\n"));
5039dede
AK
1324 }
1325 else
1326 {
35f836fe 1327 ConsolePrintf(pCtx, _T("UNKNOWN COMMAND\n\n"));
5039dede
AK
1328 }
1329
1330 return nExitCode;
1331}
1332
1333
1334//
1335// Signal handler for UNIX platforms
1336//
1337
1338#ifndef _WIN32
1339
1340void SignalHandlerStub(int nSignal)
1341{
1342 // should be unused, but JIC...
1343 if (nSignal == SIGCHLD)
1344 {
1345 while (waitpid(-1, NULL, WNOHANG) > 0)
1346 ;
1347 }
1348}
1349
1350THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL SignalHandler(void *pArg)
1351{
1352 sigset_t signals;
1353 int nSignal;
1354 BOOL bCallShutdown = FALSE;
1355
1356 m_signalHandlerThread = pthread_self();
1357
1358 // default for SIGCHLD: ignore
1359 signal(SIGCHLD, &SignalHandlerStub);
1360
1361 sigemptyset(&signals);
1362 sigaddset(&signals, SIGTERM);
1363 sigaddset(&signals, SIGINT);
1364 sigaddset(&signals, SIGPIPE);
1365 sigaddset(&signals, SIGSEGV);
1366 sigaddset(&signals, SIGCHLD);
1367 sigaddset(&signals, SIGHUP);
1368 sigaddset(&signals, SIGUSR1);
1369 sigaddset(&signals, SIGUSR2);
1370
1371 sigprocmask(SIG_BLOCK, &signals, NULL);
1372
1373 while(1)
1374 {
1375 if (sigwait(&signals, &nSignal) == 0)
1376 {
1377 switch(nSignal)
1378 {
1379 case SIGTERM:
1380 case SIGINT:
1381 m_nShutdownReason = SHUTDOWN_BY_SIGNAL;
1382 if (IsStandalone())
1383 bCallShutdown = TRUE;
1384 ConditionSet(m_condShutdown);
1385 goto stop_handler;
1386 case SIGSEGV:
1387 abort();
1388 break;
1389 case SIGCHLD:
1390 while (waitpid(-1, NULL, WNOHANG) > 0)
1391 ;
1392 break;
1393 case SIGUSR1:
1394 if (g_dwFlags & AF_SHUTDOWN)
1395 goto stop_handler;
1396 break;
1397 default:
1398 break;
1399 }
1400 }
1401 else
1402 {
1403 ThreadSleepMs(100);
1404 }
1405 }
1406
1407stop_handler:
1408 sigprocmask(SIG_UNBLOCK, &signals, NULL);
1409 if (bCallShutdown)
1410 Shutdown();
1411 return THREAD_OK;
1412}
1413
1414#endif
1415
1416
1417//
1418// Common main()
1419//
1420
1421THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL Main(void *pArg)
1422{
1423 nxlog_write(MSG_SERVER_STARTED, EVENTLOG_INFORMATION_TYPE, NULL);
1424
1425 if (IsStandalone())
1426 {
1427 char *ptr, szCommand[256];
1428 struct __console_ctx ctx;
35f836fe
VK
1429#ifdef UNICODE
1430 WCHAR wcCommand[256];
1431#endif
5039dede
AK
1432
1433 ctx.hSocket = -1;
d3a7cf4c 1434 ctx.socketMutex = INVALID_MUTEX_HANDLE;
5039dede 1435 ctx.pMsg = NULL;
200d662d 1436 ctx.session = NULL;
f669df41
VK
1437 WriteToTerminal(_T("\nNetXMS Server V") NETXMS_VERSION_STRING _T(" Ready\n")
1438 _T("Enter \"\x1b[1mhelp\x1b[0m\" for command list or \"\x1b[1mdown\x1b[0m\" for server shutdown\n")
1439 _T("System Console\n\n"));
5039dede
AK
1440
1441#if USE_READLINE
1442 // Initialize readline library if we use it
0322eed7 1443 rl_bind_key('\t', RL_INSERT_CAST rl_insert);
5039dede
AK
1444#endif
1445
1446 while(1)
1447 {
1448#if USE_READLINE
f669df41 1449 ptr = readline("\x1b[33mnetxmsd:\x1b[0m ");
5039dede 1450#else
f669df41 1451 WriteToTerminal(_T("\x1b[33mnetxmsd:\x1b[0m "));
5039dede
AK
1452 fflush(stdout);
1453 if (fgets(szCommand, 255, stdin) == NULL)
1454 break; // Error reading stdin
1455 ptr = strchr(szCommand, '\n');
1456 if (ptr != NULL)
1457 *ptr = 0;
1458 ptr = szCommand;
1459#endif
1460
1461 if (ptr != NULL)
1462 {
35f836fe
VK
1463#ifdef UNICODE
1464 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, ptr, -1, wcCommand, 256);
1465 wcCommand[255] = 0;
1466 StrStrip(wcCommand);
1467 if (wcCommand[0] != 0)
1468 {
1469 if (ProcessConsoleCommand(wcCommand, &ctx) == CMD_EXIT_SHUTDOWN)
1470#else
5039dede
AK
1471 StrStrip(ptr);
1472 if (*ptr != 0)
1473 {
1474 if (ProcessConsoleCommand(ptr, &ctx) == CMD_EXIT_SHUTDOWN)
35f836fe 1475#endif
5039dede
AK
1476 break;
1477#if USE_READLINE
1478 add_history(ptr);
1479#endif
1480 }
1481#if USE_READLINE
1482 free(ptr);
1483#endif
1484 }
1485 else
1486 {
1487 printf("\n");
1488 }
1489 }
1490
1491#if USE_READLINE
1492 free(ptr);
1493#endif
1494 m_nShutdownReason = SHUTDOWN_FROM_CONSOLE;
1495 Shutdown();
1496 }
1497 else
1498 {
1499 ConditionWait(m_condShutdown, INFINITE);
1500 // On Win32, Shutdown() will be called by service control handler
1501#ifndef _WIN32
1502 Shutdown();
1503#endif
1504 }
1505 return THREAD_OK;
1506}
1507
1508
1509//
1510// Initiate server shutdown
1511//
1512
035a4d73 1513void InitiateShutdown()
5039dede
AK
1514{
1515#ifdef _WIN32
1516 Shutdown();
1517#else
1518 if (IsStandalone())
1519 {
1520 Shutdown();
1521 }
1522 else
1523 {
1524 pthread_kill(m_signalHandlerThread, SIGTERM);
1525 }
1526#endif
1527}
1528
1529
1530//
1531// DLL Entry point
1532//
1533
1534#ifdef _WIN32
1535
1536BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
1537{
1538 if (dwReason == DLL_PROCESS_ATTACH)
1539 DisableThreadLibraryCalls(hInstance);
1540 return TRUE;
1541}
1542
1543#endif