added API call getVlans
[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);
460 session->sendMessage(&msg);
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
35f836fe 907static void DumpIndex(CONSOLE_CTX pCtx, RWLOCK hLock, INDEX *pIndex, DWORD dwSize, BOOL bIndexByIp)
5039dede
AK
908{
909 DWORD i;
35f836fe 910 TCHAR szIpAddr[16];
5039dede
AK
911
912 if (!RWLockReadLock(hLock, 5000))
913 {
35f836fe 914 ConsolePrintf(pCtx, _T("ERROR: unable to obtain index lock in 5 seconds\n"));
5039dede
AK
915 return;
916 }
917
918 for(i = 0; i < dwSize; i++)
919 {
920 if (bIndexByIp)
921 {
35f836fe 922 ConsolePrintf(pCtx, _T("%08X [%-15s] %p %s\n"), pIndex[i].dwKey,
5039dede
AK
923 IpToStr(pIndex[i].dwKey, szIpAddr),
924 pIndex[i].pObject, ((NetObj *)pIndex[i].pObject)->Name());
925 }
926 else
927 {
35f836fe 928 ConsolePrintf(pCtx, _T("%08X %p %s\n"), pIndex[i].dwKey, pIndex[i].pObject,
5039dede
AK
929 ((NetObj *)pIndex[i].pObject)->Name());
930 }
931 }
932
933 RWLockUnlock(hLock);
934}
935
936
937//
938// Process command entered from command line in standalone mode
35f836fe 939// Return TRUE if command was _T("down")
5039dede
AK
940//
941
35f836fe 942int ProcessConsoleCommand(const TCHAR *pszCmdLine, CONSOLE_CTX pCtx)
5039dede 943{
35f836fe 944 const TCHAR *pArg;
48c0079d 945 TCHAR szBuffer[256], *eptr;
5039dede
AK
946 int nExitCode = CMD_EXIT_CONTINUE;
947
948 // Get command
949 pArg = ExtractWord(pszCmdLine, szBuffer);
950
35f836fe 951 if (IsCommand(_T("DEBUG"), szBuffer, 2))
5039dede
AK
952 {
953 // Get argument
954 pArg = ExtractWord(pArg, szBuffer);
48c0079d
VK
955 int level = (int)_tcstol(szBuffer, &eptr, 0);
956 if ((*eptr == 0) && (level >= 0) && (level <= 9))
5039dede 957 {
48c0079d
VK
958 g_nDebugLevel = level;
959 ConsolePrintf(pCtx, (level == 0) ? _T("Debug mode turned off\n") : _T("Debug level set to %d\n"), level);
5039dede 960 }
35f836fe 961 else if (IsCommand(_T("OFF"), szBuffer, 2))
5039dede
AK
962 {
963 g_nDebugLevel = 0;
35f836fe 964 ConsolePrintf(pCtx, _T("Debug mode turned off\n"));
5039dede
AK
965 }
966 else
967 {
968 if (szBuffer[0] == 0)
35f836fe 969 ConsolePrintf(pCtx, _T("ERROR: Missing argument\n\n"));
5039dede 970 else
48c0079d 971 ConsolePrintf(pCtx, _T("ERROR: Invalid debug level\n\n"));
5039dede
AK
972 }
973 }
35f836fe 974 else if (IsCommand(_T("DOWN"), szBuffer, 4))
5039dede 975 {
35f836fe 976 ConsolePrintf(pCtx, _T("Proceeding with server shutdown...\n"));
5039dede
AK
977 nExitCode = CMD_EXIT_SHUTDOWN;
978 }
35f836fe 979 else if (IsCommand(_T("DUMP"), szBuffer, 4))
5039dede
AK
980 {
981 DumpProcess(pCtx);
982 }
35f836fe 983 else if (IsCommand(_T("RAISE"), szBuffer, 5))
5039dede
AK
984 {
985 // Get argument
986 pArg = ExtractWord(pArg, szBuffer);
987
35f836fe 988 if (IsCommand(_T("ACCESS"), szBuffer, 6))
5039dede 989 {
35f836fe 990 ConsolePrintf(pCtx, _T("Raising exception...\n"));
5039dede
AK
991 char *p = NULL;
992 *p = 0;
993 }
35f836fe 994 else if (IsCommand(_T("BREAKPOINT"), szBuffer, 5))
5039dede
AK
995 {
996#ifdef _WIN32
35f836fe 997 ConsolePrintf(pCtx, _T("Raising exception...\n"));
5039dede
AK
998 RaiseException(EXCEPTION_BREAKPOINT, 0, 0, NULL);
999#else
35f836fe 1000 ConsolePrintf(pCtx, _T("ERROR: Not supported on current platform\n"));
5039dede
AK
1001#endif
1002 }
1003 else
1004 {
35f836fe 1005 ConsolePrintf(pCtx, _T("Invalid exception name; possible names are:\nACCESS BREAKPOINT\n"));
5039dede
AK
1006 }
1007 }
35f836fe 1008 else if (IsCommand(_T("EXIT"), szBuffer, 4))
5039dede 1009 {
f669df41 1010 if ((pCtx->hSocket != -1) || (pCtx->session != NULL))
5039dede 1011 {
35f836fe 1012 ConsolePrintf(pCtx, _T("Closing session...\n"));
5039dede
AK
1013 nExitCode = CMD_EXIT_CLOSE_SESSION;
1014 }
1015 else
1016 {
35f836fe 1017 ConsolePrintf(pCtx, _T("Cannot exit from local server console\n"));
5039dede
AK
1018 }
1019 }
35f836fe 1020 else if (IsCommand(_T("SHOW"), szBuffer, 2))
5039dede
AK
1021 {
1022 // Get argument
1023 pArg = ExtractWord(pArg, szBuffer);
1024
35f836fe 1025 if (IsCommand(_T("FLAGS"), szBuffer, 1))
5039dede 1026 {
35f836fe 1027 ConsolePrintf(pCtx, _T("Flags: 0x%08X\n"), g_dwFlags);
5039dede
AK
1028 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DAEMON));
1029 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_USE_SYSLOG));
1030 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_NETWORK_DISCOVERY));
1031 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ACTIVE_NETWORK_DISCOVERY));
1032 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_LOG_SQL_ERRORS));
1033 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DELETE_EMPTY_SUBNETS));
1034 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_SNMP_TRAPD));
1035 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_ZONING));
5039dede 1036 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SYNC_NODE_NAMES_WITH_DNS));
cbc777ee
VK
1037 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_CHECK_TRUSTED_NODES));
1038 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_WRITE_FULL_DUMP));
1039 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_RESOLVE_NODE_NAMES));
5039dede 1040 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_CATCH_EXCEPTIONS));
5039dede
AK
1041 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_INTERNAL_CA));
1042 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_LOCKED));
cbc777ee 1043 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_MULTIPLE_DB_CONN));
5039dede 1044 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_CONNECTION_LOST));
cbc777ee 1045 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_NO_NETWORK_CONNECTIVITY));
5039dede
AK
1046 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_EVENT_STORM_DETECTED));
1047 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SERVER_INITIALIZED));
1048 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SHUTDOWN));
35f836fe 1049 ConsolePrintf(pCtx, _T("\n"));
5039dede 1050 }
35f836fe 1051 else if (IsCommand(_T("INDEX"), szBuffer, 1))
5039dede
AK
1052 {
1053 // Get argument
1054 pArg = ExtractWord(pArg, szBuffer);
1055
35f836fe 1056 if (IsCommand(_T("CONDITION"), szBuffer, 1))
5039dede
AK
1057 {
1058 DumpIndex(pCtx, g_rwlockConditionIndex, g_pConditionIndex, g_dwConditionIndexSize, FALSE);
1059 }
35f836fe 1060 else if (IsCommand(_T("ID"), szBuffer, 2))
5039dede
AK
1061 {
1062 DumpIndex(pCtx, g_rwlockIdIndex, g_pIndexById, g_dwIdIndexSize, FALSE);
1063 }
35f836fe 1064 else if (IsCommand(_T("INTERFACE"), szBuffer, 2))
5039dede
AK
1065 {
1066 DumpIndex(pCtx, g_rwlockInterfaceIndex, g_pInterfaceIndexByAddr,
1067 g_dwInterfaceAddrIndexSize, TRUE);
1068 }
35f836fe 1069 else if (IsCommand(_T("SUBNET"), szBuffer, 1))
5039dede
AK
1070 {
1071 DumpIndex(pCtx, g_rwlockSubnetIndex, g_pSubnetIndexByAddr,
1072 g_dwSubnetAddrIndexSize, TRUE);
1073 }
1074 else
1075 {
1076 if (szBuffer[0] == 0)
35f836fe 1077 ConsolePrintf(pCtx, _T("ERROR: Missing index name\n")
889d7ff7 1078 _T("Valid names are: CONDITION, ID, INTERFACE, SUBNET\n\n"));
5039dede 1079 else
35f836fe 1080 ConsolePrintf(pCtx, _T("ERROR: Invalid index name\n\n"));
5039dede
AK
1081 }
1082 }
35f836fe 1083 else if (IsCommand(_T("MEMORY"), szBuffer, 2))
5039dede
AK
1084 {
1085#ifdef NETXMS_MEMORY_DEBUG
1086 PrintMemoryBlocks();
1087#else
35f836fe 1088 ConsolePrintf(pCtx, _T("ERROR: Server was compiled without memory debugger\n\n"));
5039dede
AK
1089#endif
1090 }
35f836fe 1091 else if (IsCommand(_T("MUTEX"), szBuffer, 2))
5039dede 1092 {
35f836fe
VK
1093 ConsolePrintf(pCtx, _T("Mutex status:\n"));
1094 DbgTestRWLock(g_rwlockIdIndex, _T("g_hMutexIdIndex"), pCtx);
35f836fe
VK
1095 DbgTestRWLock(g_rwlockSubnetIndex, _T("g_hMutexSubnetIndex"), pCtx);
1096 DbgTestRWLock(g_rwlockInterfaceIndex, _T("g_hMutexInterfaceIndex"), pCtx);
1097 ConsolePrintf(pCtx, _T("\n"));
5039dede 1098 }
35f836fe 1099 else if (IsCommand(_T("OBJECTS"), szBuffer, 1))
5039dede
AK
1100 {
1101 DumpObjects(pCtx);
1102 }
35f836fe 1103 else if (IsCommand(_T("POLLERS"), szBuffer, 1))
5039dede
AK
1104 {
1105 ShowPollerState(pCtx);
1106 }
35f836fe 1107 else if (IsCommand(_T("QUEUES"), szBuffer, 1))
5039dede 1108 {
35f836fe
VK
1109 ShowQueueStats(pCtx, &g_conditionPollerQueue, _T("Condition poller"));
1110 ShowQueueStats(pCtx, &g_configPollQueue, _T("Configuration poller"));
040c45fa 1111 ShowQueueStats(pCtx, &g_topologyPollQueue, _T("Topology poller"));
35f836fe
VK
1112 ShowQueueStats(pCtx, g_pItemQueue, _T("Data collector"));
1113 ShowQueueStats(pCtx, g_pLazyRequestQueue, _T("Database writer"));
1114 ShowQueueStats(pCtx, g_pEventQueue, _T("Event processor"));
1115 ShowQueueStats(pCtx, &g_discoveryPollQueue, _T("Network discovery poller"));
1116 ShowQueueStats(pCtx, &g_nodePollerQueue, _T("Node poller"));
1117 ShowQueueStats(pCtx, &g_routePollQueue, _T("Routing table poller"));
1118 ShowQueueStats(pCtx, &g_statusPollQueue, _T("Status poller"));
1119 ConsolePrintf(pCtx, _T("\n"));
5039dede 1120 }
35f836fe 1121 else if (IsCommand(_T("ROUTING-TABLE"), szBuffer, 1))
5039dede
AK
1122 {
1123 DWORD dwNode;
1124 NetObj *pObject;
1125
1126 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1127 dwNode = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1128 if (dwNode != 0)
1129 {
1130 pObject = FindObjectById(dwNode);
1131 if (pObject != NULL)
1132 {
1133 if (pObject->Type() == OBJECT_NODE)
1134 {
1135 ROUTING_TABLE *pRT;
35f836fe 1136 TCHAR szIpAddr[16];
5039dede
AK
1137 int i;
1138
35f836fe 1139 ConsolePrintf(pCtx, _T("Routing table for node %s:\n\n"), pObject->Name());
58b3e451 1140 pRT = ((Node *)pObject)->getCachedRoutingTable();
5039dede
AK
1141 if (pRT != NULL)
1142 {
1143 for(i = 0; i < pRT->iNumEntries; i++)
1144 {
35f836fe
VK
1145 _sntprintf(szBuffer, 256, _T("%s/%d"), IpToStr(pRT->pRoutes[i].dwDestAddr, szIpAddr),
1146 BitsInMask(pRT->pRoutes[i].dwDestMask));
1147 ConsolePrintf(pCtx, _T("%-18s %-15s %-6d %d\n"), szBuffer,
1148 IpToStr(pRT->pRoutes[i].dwNextHop, szIpAddr),
1149 pRT->pRoutes[i].dwIfIndex, pRT->pRoutes[i].dwRouteType);
5039dede 1150 }
35f836fe 1151 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1152 }
1153 else
1154 {
35f836fe 1155 ConsolePrintf(pCtx, _T("Node doesn't have cached routing table\n\n"));
5039dede
AK
1156 }
1157 }
1158 else
1159 {
35f836fe 1160 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
5039dede
AK
1161 }
1162 }
1163 else
1164 {
35f836fe 1165 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode);
5039dede
AK
1166 }
1167 }
1168 else
1169 {
35f836fe 1170 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node ID\n\n"));
5039dede
AK
1171 }
1172 }
35f836fe 1173 else if (IsCommand(_T("SESSIONS"), szBuffer, 2))
5039dede
AK
1174 {
1175 DumpSessions(pCtx);
1176 }
35f836fe 1177 else if (IsCommand(_T("STATS"), szBuffer, 2))
5039dede
AK
1178 {
1179 ShowServerStats(pCtx);
1180 }
35f836fe 1181 else if (IsCommand(_T("USERS"), szBuffer, 1))
5039dede
AK
1182 {
1183 DumpUsers(pCtx);
1184 }
35f836fe 1185 else if (IsCommand(_T("WATCHDOG"), szBuffer, 1))
5039dede
AK
1186 {
1187 WatchdogPrintStatus(pCtx);
35f836fe 1188 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1189 }
1190 else
1191 {
1192 if (szBuffer[0] == 0)
35f836fe 1193 ConsolePrintf(pCtx, _T("ERROR: Missing subcommand\n\n"));
5039dede 1194 else
35f836fe 1195 ConsolePrintf(pCtx, _T("ERROR: Invalid SHOW subcommand\n\n"));
5039dede
AK
1196 }
1197 }
35f836fe 1198 else if (IsCommand(_T("TRACE"), szBuffer, 1))
5039dede
AK
1199 {
1200 DWORD dwNode1, dwNode2;
1201 NetObj *pObject1, *pObject2;
1202 NETWORK_PATH_TRACE *pTrace;
35f836fe 1203 TCHAR szNextHop[16];
5039dede
AK
1204 int i;
1205
1206 // Get arguments
1207 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1208 dwNode1 = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1209
1210 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1211 dwNode2 = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1212
1213 if ((dwNode1 != 0) && (dwNode2 != 0))
1214 {
1215 pObject1 = FindObjectById(dwNode1);
1216 if (pObject1 == NULL)
1217 {
35f836fe 1218 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode1);
5039dede
AK
1219 }
1220 else
1221 {
1222 pObject2 = FindObjectById(dwNode2);
1223 if (pObject2 == NULL)
1224 {
35f836fe 1225 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode2);
5039dede
AK
1226 }
1227 else
1228 {
1229 if ((pObject1->Type() == OBJECT_NODE) &&
1230 (pObject2->Type() == OBJECT_NODE))
1231 {
1232 pTrace = TraceRoute((Node *)pObject1, (Node *)pObject2);
1233 if (pTrace != NULL)
1234 {
35f836fe 1235 ConsolePrintf(pCtx, _T("Trace from %s to %s (%d hops):\n"),
5039dede
AK
1236 pObject1->Name(), pObject2->Name(), pTrace->iNumHops);
1237 for(i = 0; i < pTrace->iNumHops; i++)
35f836fe 1238 ConsolePrintf(pCtx, _T("[%d] %s %s %s %d\n"),
5039dede
AK
1239 pTrace->pHopList[i].pObject->Id(),
1240 pTrace->pHopList[i].pObject->Name(),
1241 IpToStr(pTrace->pHopList[i].dwNextHop, szNextHop),
35f836fe 1242 pTrace->pHopList[i].bIsVPN ? _T("VPN Connector ID:") : _T("Interface Index: "),
5039dede
AK
1243 pTrace->pHopList[i].dwIfIndex);
1244 DestroyTraceData(pTrace);
35f836fe 1245 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1246 }
1247 else
1248 {
35f836fe 1249 ConsolePrintf(pCtx, _T("ERROR: Call to TraceRoute() failed\n\n"));
5039dede
AK
1250 }
1251 }
1252 else
1253 {
35f836fe 1254 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
5039dede
AK
1255 }
1256 }
1257 }
1258 }
1259 else
1260 {
35f836fe 1261 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node id(s)\n\n"));
5039dede
AK
1262 }
1263 }
35f836fe 1264 else if (IsCommand(_T("HELP"), szBuffer, 2) || IsCommand(_T("?"), szBuffer, 1))
5039dede 1265 {
35f836fe 1266 ConsolePrintf(pCtx, _T("Valid commands are:\n")
48c0079d 1267 _T(" debug [<level>|off] - Set debug level (valid range is 0..9)\n")
35f836fe
VK
1268 _T(" down - Down NetXMS server\n")
1269 _T(" exit - Exit from remote session\n")
1270 _T(" help - Display this help\n")
1271 _T(" raise <exception> - Raise exception\n")
1272 _T(" show flags - Show internal server flags\n")
1273 _T(" show index <index> - Show internal index\n")
1274 _T(" show mutex - Display mutex status\n")
1275 _T(" show objects - Dump network objects to screen\n")
1276 _T(" show pollers - Show poller threads state information\n")
1277 _T(" show queues - Show internal queues statistics\n")
1278 _T(" show routing-table <node> - Show cached routing table for node\n")
1279 _T(" show sessions - Show active client sessions\n")
1280 _T(" show stats - Show server statistics\n")
1281 _T(" show users - Show users\n")
1282 _T(" show watchdog - Display watchdog information\n")
1283 _T(" trace <node1> <node2> - Show network path trace between two nodes\n")
1284 _T("\nAlmost all commands can be abbreviated to 2 or 3 characters\n")
1285 _T("\n"));
5039dede
AK
1286 }
1287 else
1288 {
35f836fe 1289 ConsolePrintf(pCtx, _T("UNKNOWN COMMAND\n\n"));
5039dede
AK
1290 }
1291
1292 return nExitCode;
1293}
1294
1295
1296//
1297// Signal handler for UNIX platforms
1298//
1299
1300#ifndef _WIN32
1301
1302void SignalHandlerStub(int nSignal)
1303{
1304 // should be unused, but JIC...
1305 if (nSignal == SIGCHLD)
1306 {
1307 while (waitpid(-1, NULL, WNOHANG) > 0)
1308 ;
1309 }
1310}
1311
1312THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL SignalHandler(void *pArg)
1313{
1314 sigset_t signals;
1315 int nSignal;
1316 BOOL bCallShutdown = FALSE;
1317
1318 m_signalHandlerThread = pthread_self();
1319
1320 // default for SIGCHLD: ignore
1321 signal(SIGCHLD, &SignalHandlerStub);
1322
1323 sigemptyset(&signals);
1324 sigaddset(&signals, SIGTERM);
1325 sigaddset(&signals, SIGINT);
1326 sigaddset(&signals, SIGPIPE);
1327 sigaddset(&signals, SIGSEGV);
1328 sigaddset(&signals, SIGCHLD);
1329 sigaddset(&signals, SIGHUP);
1330 sigaddset(&signals, SIGUSR1);
1331 sigaddset(&signals, SIGUSR2);
1332
1333 sigprocmask(SIG_BLOCK, &signals, NULL);
1334
1335 while(1)
1336 {
1337 if (sigwait(&signals, &nSignal) == 0)
1338 {
1339 switch(nSignal)
1340 {
1341 case SIGTERM:
1342 case SIGINT:
1343 m_nShutdownReason = SHUTDOWN_BY_SIGNAL;
1344 if (IsStandalone())
1345 bCallShutdown = TRUE;
1346 ConditionSet(m_condShutdown);
1347 goto stop_handler;
1348 case SIGSEGV:
1349 abort();
1350 break;
1351 case SIGCHLD:
1352 while (waitpid(-1, NULL, WNOHANG) > 0)
1353 ;
1354 break;
1355 case SIGUSR1:
1356 if (g_dwFlags & AF_SHUTDOWN)
1357 goto stop_handler;
1358 break;
1359 default:
1360 break;
1361 }
1362 }
1363 else
1364 {
1365 ThreadSleepMs(100);
1366 }
1367 }
1368
1369stop_handler:
1370 sigprocmask(SIG_UNBLOCK, &signals, NULL);
1371 if (bCallShutdown)
1372 Shutdown();
1373 return THREAD_OK;
1374}
1375
1376#endif
1377
1378
1379//
1380// Common main()
1381//
1382
1383THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL Main(void *pArg)
1384{
1385 nxlog_write(MSG_SERVER_STARTED, EVENTLOG_INFORMATION_TYPE, NULL);
1386
1387 if (IsStandalone())
1388 {
1389 char *ptr, szCommand[256];
1390 struct __console_ctx ctx;
35f836fe
VK
1391#ifdef UNICODE
1392 WCHAR wcCommand[256];
1393#endif
5039dede
AK
1394
1395 ctx.hSocket = -1;
1396 ctx.pMsg = NULL;
200d662d 1397 ctx.session = NULL;
f669df41
VK
1398 WriteToTerminal(_T("\nNetXMS Server V") NETXMS_VERSION_STRING _T(" Ready\n")
1399 _T("Enter \"\x1b[1mhelp\x1b[0m\" for command list or \"\x1b[1mdown\x1b[0m\" for server shutdown\n")
1400 _T("System Console\n\n"));
5039dede
AK
1401
1402#if USE_READLINE
1403 // Initialize readline library if we use it
0322eed7 1404 rl_bind_key('\t', RL_INSERT_CAST rl_insert);
5039dede
AK
1405#endif
1406
1407 while(1)
1408 {
1409#if USE_READLINE
f669df41 1410 ptr = readline("\x1b[33mnetxmsd:\x1b[0m ");
5039dede 1411#else
f669df41 1412 WriteToTerminal(_T("\x1b[33mnetxmsd:\x1b[0m "));
5039dede
AK
1413 fflush(stdout);
1414 if (fgets(szCommand, 255, stdin) == NULL)
1415 break; // Error reading stdin
1416 ptr = strchr(szCommand, '\n');
1417 if (ptr != NULL)
1418 *ptr = 0;
1419 ptr = szCommand;
1420#endif
1421
1422 if (ptr != NULL)
1423 {
35f836fe
VK
1424#ifdef UNICODE
1425 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, ptr, -1, wcCommand, 256);
1426 wcCommand[255] = 0;
1427 StrStrip(wcCommand);
1428 if (wcCommand[0] != 0)
1429 {
1430 if (ProcessConsoleCommand(wcCommand, &ctx) == CMD_EXIT_SHUTDOWN)
1431#else
5039dede
AK
1432 StrStrip(ptr);
1433 if (*ptr != 0)
1434 {
1435 if (ProcessConsoleCommand(ptr, &ctx) == CMD_EXIT_SHUTDOWN)
35f836fe 1436#endif
5039dede
AK
1437 break;
1438#if USE_READLINE
1439 add_history(ptr);
1440#endif
1441 }
1442#if USE_READLINE
1443 free(ptr);
1444#endif
1445 }
1446 else
1447 {
1448 printf("\n");
1449 }
1450 }
1451
1452#if USE_READLINE
1453 free(ptr);
1454#endif
1455 m_nShutdownReason = SHUTDOWN_FROM_CONSOLE;
1456 Shutdown();
1457 }
1458 else
1459 {
1460 ConditionWait(m_condShutdown, INFINITE);
1461 // On Win32, Shutdown() will be called by service control handler
1462#ifndef _WIN32
1463 Shutdown();
1464#endif
1465 }
1466 return THREAD_OK;
1467}
1468
1469
1470//
1471// Initiate server shutdown
1472//
1473
035a4d73 1474void InitiateShutdown()
5039dede
AK
1475{
1476#ifdef _WIN32
1477 Shutdown();
1478#else
1479 if (IsStandalone())
1480 {
1481 Shutdown();
1482 }
1483 else
1484 {
1485 pthread_kill(m_signalHandlerThread, SIGTERM);
1486 }
1487#endif
1488}
1489
1490
1491//
1492// DLL Entry point
1493//
1494
1495#ifdef _WIN32
1496
1497BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
1498{
1499 if (dwReason == DLL_PROCESS_ATTACH)
1500 DisableThreadLibraryCalls(hInstance);
1501 return TRUE;
1502}
1503
1504#endif