fixed perf tab display for DCIs created via instance discovery from template
[public/netxms.git] / src / server / core / main.cpp
CommitLineData
d9177dd1 1/*
5039dede 2** NetXMS - Network Management System
fdbee7f8 3** Copyright (C) 2003-2013 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>
fdbee7f8 25#include <netxms_mt.h>
6fad8870 26#include <hdlink.h>
5039dede 27
b847803c 28#if !defined(_WIN32) && HAVE_READLINE_READLINE_H && HAVE_READLINE && !defined(UNICODE)
0322eed7
VK
29#include <readline/readline.h>
30#include <readline/history.h>
31#define USE_READLINE 1
5039dede
AK
32#endif
33
34#ifdef _WIN32
a23d8e0d
VK
35#include <errno.h>
36#include <psapi.h>
7bdb43c3 37#include <conio.h>
d717b69c
VK
38#define open _open
39#define write _write
40#define close _close
5039dede 41#else
a23d8e0d
VK
42#include <signal.h>
43#include <sys/wait.h>
5039dede
AK
44#endif
45
3a82d5ae 46/**
ea50bc33
VK
47 * Format string to show value of global flag
48 */
49#define SHOW_FLAG_VALUE(x) _T(" %-38s = %d\n"), _T(#x), (g_flags & x) ? 1 : 0
50
51/**
3a82d5ae
VK
52 * Messages generated by mc.pl (for UNIX version only)
53 */
5039dede
AK
54#ifndef _WIN32
55extern unsigned int g_dwNumMessages;
56extern const TCHAR *g_szMessages[];
57#endif
58
8f99849c
VK
59/**
60 * Shutdown reasons
61 */
030a0779
VK
62#define SHUTDOWN_DEFAULT 0
63#define SHUTDOWN_FROM_CONSOLE 1
64#define SHUTDOWN_BY_SIGNAL 2
5039dede 65
8f99849c
VK
66/**
67 * Externals
68 */
5039dede
AK
69extern Queue g_statusPollQueue;
70extern Queue g_configPollQueue;
040c45fa 71extern Queue g_topologyPollQueue;
5039dede
AK
72extern Queue g_routePollQueue;
73extern Queue g_discoveryPollQueue;
74extern Queue g_nodePollerQueue;
75extern Queue g_conditionPollerQueue;
d140955e
VK
76extern Queue g_dataCollectionQueue;
77extern Queue g_dciCacheLoaderQueue;
f1784ab6
VK
78extern Queue g_syslogProcessingQueue;
79extern Queue g_syslogWriteQueue;
5039dede 80
36e44abe 81void InitClientListeners();
534e1b83 82void InitMobileDeviceListeners();
36e44abe 83void InitCertificates();
ab185583
VK
84void InitUsers();
85void CleanupUsers();
8fd95c92 86void LoadPerfDataStorageDrivers();
058bf6fc
VK
87
88#if XMPP_SUPPORTED
244c65ef 89void StopXMPPConnector();
058bf6fc 90#endif
5039dede 91
534e1b83
VK
92/**
93 * Thread functions
94 */
95THREAD_RESULT THREAD_CALL HouseKeeper(void *);
96THREAD_RESULT THREAD_CALL Syncer(void *);
97THREAD_RESULT THREAD_CALL NodePoller(void *);
98THREAD_RESULT THREAD_CALL PollManager(void *);
99THREAD_RESULT THREAD_CALL EventProcessor(void *);
100THREAD_RESULT THREAD_CALL WatchdogThread(void *);
101THREAD_RESULT THREAD_CALL ClientListener(void *);
102THREAD_RESULT THREAD_CALL ClientListenerIPv6(void *);
103THREAD_RESULT THREAD_CALL MobileDeviceListener(void *);
104THREAD_RESULT THREAD_CALL MobileDeviceListenerIPv6(void *);
105THREAD_RESULT THREAD_CALL ISCListener(void *);
106THREAD_RESULT THREAD_CALL LocalAdminListener(void *);
107THREAD_RESULT THREAD_CALL SNMPTrapReceiver(void *);
108THREAD_RESULT THREAD_CALL SyslogDaemon(void *);
109THREAD_RESULT THREAD_CALL BeaconPoller(void *);
110THREAD_RESULT THREAD_CALL JobManagerThread(void *);
111THREAD_RESULT THREAD_CALL UptimeCalculator(void *);
d75003e1 112THREAD_RESULT THREAD_CALL ReportingServerConnector(void *);
058bf6fc
VK
113
114#if XMPP_SUPPORTED
244c65ef 115THREAD_RESULT THREAD_CALL XMPPConnectionManager(void *);
058bf6fc 116#endif
5039dede 117
534e1b83
VK
118/**
119 * Global variables
120 */
5039dede
AK
121TCHAR NXCORE_EXPORTABLE g_szConfigFile[MAX_PATH] = DEFAULT_CONFIG_FILE;
122TCHAR NXCORE_EXPORTABLE g_szLogFile[MAX_PATH] = DEFAULT_LOG_FILE;
967893bb
VK
123UINT32 g_dwLogRotationMode = NXLOG_ROTATION_BY_SIZE;
124UINT32 g_dwMaxLogSize = 16384 * 1024;
125UINT32 g_dwLogHistorySize = 4;
4f8998ca 126TCHAR g_szDailyLogFileSuffix[64] = _T("");
5039dede 127TCHAR NXCORE_EXPORTABLE g_szDumpDir[MAX_PATH] = DEFAULT_DUMP_DIR;
29dc8792 128char g_szCodePage[256] = ICONV_DEFAULT_CODEPAGE;
5039dede
AK
129TCHAR NXCORE_EXPORTABLE g_szListenAddress[MAX_PATH] = _T("0.0.0.0");
130#ifndef _WIN32
b07c50cc 131TCHAR NXCORE_EXPORTABLE g_szPIDFile[MAX_PATH] = _T("/var/run/netxmsd.pid");
5039dede
AK
132#endif
133DB_HANDLE g_hCoreDB = 0;
967893bb
VK
134UINT32 g_dwDiscoveryPollingInterval;
135UINT32 g_dwStatusPollingInterval;
136UINT32 g_dwConfigurationPollingInterval;
137UINT32 g_dwRoutingTableUpdateInterval;
138UINT32 g_dwTopologyPollingInterval;
139UINT32 g_dwConditionPollingInterval;
c59466d2
VK
140UINT32 g_icmpPingSize;
141UINT32 g_icmpPingTimeout = 1500; // ICMP ping timeout (milliseconds)
142UINT32 g_auditFlags;
143UINT32 g_slmPollingInterval;
d96bd4c7 144TCHAR g_szDataDir[MAX_PATH] = _T("");
9796ce45 145TCHAR g_szLibDir[MAX_PATH] = DEFAULT_LIBDIR;
2a964810 146int g_dbSyntax = DB_SYNTAX_UNKNOWN;
967893bb 147UINT32 NXCORE_EXPORTABLE g_processAffinityMask = DEFAULT_AFFINITY_MASK;
5039dede
AK
148QWORD g_qwServerId;
149RSA *g_pServerKey = NULL;
c59466d2
VK
150time_t g_serverStartTime = 0;
151UINT32 g_lockTimeout = 60000; // Default timeout for acquiring mutex
152UINT32 g_agentCommandTimeout = 4000; // Default timeout for requests to agent
153UINT32 g_thresholdRepeatInterval = 0; // Disabled by default
154int g_requiredPolls = 1;
b8c1ec69 155DB_DRIVER g_dbDriver = NULL;
5039dede 156
f375019e
VK
157/**
158 * Static data
159 */
5039dede
AK
160static CONDITION m_condShutdown = INVALID_CONDITION_HANDLE;
161static THREAD m_thPollManager = INVALID_THREAD_HANDLE;
162static THREAD m_thHouseKeeper = INVALID_THREAD_HANDLE;
163static THREAD m_thSyncer = INVALID_THREAD_HANDLE;
164static THREAD m_thSyslogDaemon = INVALID_THREAD_HANDLE;
058bf6fc 165#if XMPP_SUPPORTED
244c65ef 166static THREAD m_thXMPPConnector = INVALID_THREAD_HANDLE;
058bf6fc 167#endif
5039dede
AK
168static int m_nShutdownReason = SHUTDOWN_DEFAULT;
169
170#ifndef _WIN32
171static pthread_t m_signalHandlerThread;
172#endif
173
496390c2
VK
174/**
175 * Sleep for specified number of seconds or until system shutdown arrives
176 * Function will return TRUE if shutdown event occurs
177 *
178 * @param seconds seconds to sleep
179 * @return true if server is shutting down
180 */
400e55c4 181bool NXCORE_EXPORTABLE SleepAndCheckForShutdown(int seconds)
5039dede 182{
496390c2 183 return ConditionWait(m_condShutdown, seconds * 1000);
5039dede
AK
184}
185
496390c2
VK
186/**
187 * Disconnect from database (exportable function for startup module)
188 */
73869331 189void NXCORE_EXPORTABLE ShutdownDB()
5039dede
AK
190{
191 if (g_hCoreDB != NULL)
192 DBDisconnect(g_hCoreDB);
b8c1ec69 193 DBUnloadDriver(g_dbDriver);
5039dede
AK
194}
195
496390c2
VK
196/**
197 * Check data directory for existence
198 */
35f836fe 199static BOOL CheckDataDir()
5039dede 200{
35f836fe 201 TCHAR szBuffer[MAX_PATH];
5039dede 202
35f836fe 203 if (_tchdir(g_szDataDir) == -1)
5039dede
AK
204 {
205 nxlog_write(MSG_INVALID_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", g_szDataDir);
206 return FALSE;
207 }
208
209#ifdef _WIN32
35f836fe 210#define MKDIR(name) _tmkdir(name)
5039dede 211#else
35f836fe 212#define MKDIR(name) _tmkdir(name, 0700)
5039dede
AK
213#endif
214
215 // Create directory for mib files if it doesn't exist
35f836fe
VK
216 _tcscpy(szBuffer, g_szDataDir);
217 _tcscat(szBuffer, DDIR_MIBS);
5039dede
AK
218 if (MKDIR(szBuffer) == -1)
219 if (errno != EEXIST)
220 {
221 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
222 return FALSE;
223 }
224
5039dede 225 // Create directory for package files if it doesn't exist
35f836fe
VK
226 _tcscpy(szBuffer, g_szDataDir);
227 _tcscat(szBuffer, DDIR_PACKAGES);
5039dede
AK
228 if (MKDIR(szBuffer) == -1)
229 if (errno != EEXIST)
230 {
231 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
232 return FALSE;
233 }
234
4d0c32f3 235 // Create directory for map background images if it doesn't exist
35f836fe
VK
236 _tcscpy(szBuffer, g_szDataDir);
237 _tcscat(szBuffer, DDIR_BACKGROUNDS);
4d0c32f3
VK
238 if (MKDIR(szBuffer) == -1)
239 if (errno != EEXIST)
240 {
241 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
242 return FALSE;
243 }
244
e6b9439a
AK
245 // Create directory for image library is if does't exists
246 _tcscpy(szBuffer, g_szDataDir);
247 _tcscat(szBuffer, DDIR_IMAGES);
248 if (MKDIR(szBuffer) == -1)
249 {
250 if (errno != EEXIST)
251 {
252 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
253 return FALSE;
254 }
255 }
256
6f16f12d
VK
257 // Create directory for shared file store if does't exists
258 _tcscpy(szBuffer, g_szDataDir);
259 _tcscat(szBuffer, DDIR_SHARED_FILES);
260 if (MKDIR(szBuffer) == -1)
261 {
262 if (errno != EEXIST)
263 {
264 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
265 return FALSE;
266 }
267 }
268
619e5c9b
VK
269 // Create directory for file store if does't exists
270 _tcscpy(szBuffer, g_szDataDir);
271 _tcscat(szBuffer, DDIR_FILES);
272 if (MKDIR(szBuffer) == -1)
273 {
274 if (errno != EEXIST)
275 {
276 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
57fef75c
VK
277 return FALSE;
278 }
279 }
280
281 // Create directory for reports if does't exists
282 _tcscpy(szBuffer, g_szDataDir);
283 _tcscat(szBuffer, DDIR_REPORTS);
284 if (MKDIR(szBuffer) == -1)
285 {
286 if (errno != EEXIST)
287 {
288 nxlog_write(MSG_ERROR_CREATING_DATA_DIR, EVENTLOG_ERROR_TYPE, "s", szBuffer);
619e5c9b
VK
289 return FALSE;
290 }
291 }
292
5039dede
AK
293#undef MKDIR
294
295 return TRUE;
296}
297
496390c2
VK
298/**
299 * Load global configuration parameters
300 */
5039dede
AK
301static void LoadGlobalConfig()
302{
35f836fe
VK
303 g_dwDiscoveryPollingInterval = ConfigReadInt(_T("DiscoveryPollingInterval"), 900);
304 g_dwStatusPollingInterval = ConfigReadInt(_T("StatusPollingInterval"), 60);
305 g_dwConfigurationPollingInterval = ConfigReadInt(_T("ConfigurationPollingInterval"), 3600);
306 g_dwRoutingTableUpdateInterval = ConfigReadInt(_T("RoutingTableUpdateInterval"), 300);
040c45fa 307 g_dwTopologyPollingInterval = ConfigReadInt(_T("TopologyPollingInterval"), 1800);
35f836fe 308 g_dwConditionPollingInterval = ConfigReadInt(_T("ConditionPollingInterval"), 60);
c59466d2 309 g_slmPollingInterval = ConfigReadInt(_T("SlmPollingInterval"), 60);
35f836fe 310 if (ConfigReadInt(_T("DeleteEmptySubnets"), 1))
c8076b19 311 g_flags |= AF_DELETE_EMPTY_SUBNETS;
35f836fe 312 if (ConfigReadInt(_T("EnableSNMPTraps"), 1))
c8076b19
VK
313 g_flags |= AF_ENABLE_SNMP_TRAPD;
314 if (ConfigReadInt(_T("ProcessTrapsFromUnmanagedNodes"), 0))
315 g_flags |= AF_TRAPS_FROM_UNMANAGED_NODES;
35f836fe 316 if (ConfigReadInt(_T("EnableZoning"), 0))
c8076b19 317 g_flags |= AF_ENABLE_ZONING;
549f48b3 318 if (ConfigReadInt(_T("EnableObjectTransactions"), 0))
c8076b19 319 g_flags |= AF_ENABLE_OBJECT_TRANSACTIONS;
35f836fe 320 if (ConfigReadInt(_T("EnableMultipleDBConnections"), 1))
2a8e6a7b
VK
321 {
322 // SQLite has troubles with multiple connections to the same database
323 // from different threads, and it does not speed up database access
324 // anyway, so we will not enable multiple connections for SQLite
66c11d49 325 //if (g_dbSyntax != DB_SYNTAX_SQLITE)
2a8e6a7b 326 {
c8076b19 327 g_flags |= AF_ENABLE_MULTIPLE_DB_CONN;
2a8e6a7b 328 }
66c11d49 329 /*
2a8e6a7b
VK
330 else
331 {
332 DbgPrintf(1, _T("Configuration parameter EnableMultipleDBConnections ignored because database engine is SQLite"));
333 }
66c11d49 334 */
2a8e6a7b 335 }
35f836fe 336 if (ConfigReadInt(_T("RunNetworkDiscovery"), 0))
c8076b19 337 g_flags |= AF_ENABLE_NETWORK_DISCOVERY;
35f836fe 338 if (ConfigReadInt(_T("ActiveNetworkDiscovery"), 0))
c8076b19 339 g_flags |= AF_ACTIVE_NETWORK_DISCOVERY;
e02953a4 340 if (ConfigReadInt(_T("UseSNMPTrapsForDiscovery"), 0))
c8076b19 341 g_flags |= AF_SNMP_TRAP_DISCOVERY;
35f836fe 342 if (ConfigReadInt(_T("ResolveNodeNames"), 1))
c8076b19 343 g_flags |= AF_RESOLVE_NODE_NAMES;
35f836fe 344 if (ConfigReadInt(_T("SyncNodeNamesWithDNS"), 0))
c8076b19 345 g_flags |= AF_SYNC_NODE_NAMES_WITH_DNS;
35f836fe 346 if (ConfigReadInt(_T("CheckTrustedNodes"), 1))
c8076b19 347 g_flags |= AF_CHECK_TRUSTED_NODES;
3bbc7435 348 if (ConfigReadInt(_T("EnableNXSLContainerFunctions"), 1))
c8076b19 349 g_flags |= AF_ENABLE_NXSL_CONTAINER_FUNCS;
f31c22b3 350 if (ConfigReadInt(_T("UseFQDNForNodeNames"), 1))
c8076b19 351 g_flags |= AF_USE_FQDN_FOR_NODE_NAMES;
f31c22b3 352 if (ConfigReadInt(_T("ApplyDCIFromTemplateToDisabledDCI"), 0))
c8076b19 353 g_flags |= AF_APPLY_TO_DISABLED_DCI_FROM_TEMPLATE;
4553d424 354 if (ConfigReadInt(_T("ResolveDNSToIPOnStatusPoll"), 0))
385b1f20 355 g_flags |= AF_RESOLVE_IP_FOR_EACH_STATUS_POLL;
fc958888 356
f31c22b3
VK
357 if (g_szDataDir[0] == 0)
358 {
359 const TCHAR *homeDir = _tgetenv(_T("NETXMS_HOME"));
360 if (homeDir != NULL)
361 {
362 TCHAR path[MAX_PATH];
363 _sntprintf(path, MAX_PATH, _T("%s/share/netxms"), homeDir);
364 ConfigReadStr(_T("DataDirectory"), g_szDataDir, MAX_PATH, path);
365 }
366 else
367 {
368 ConfigReadStr(_T("DataDirectory"), g_szDataDir, MAX_PATH, DEFAULT_DATA_DIR);
369 }
370 DbgPrintf(1, _T("Data directory set to %s from server configuration variable"), g_szDataDir);
371 }
372 else
373 {
374 DbgPrintf(1, _T("Using data directory %s"), g_szDataDir);
375 }
d96bd4c7 376
c59466d2
VK
377 g_icmpPingTimeout = ConfigReadInt(_T("IcmpPingTimeout"), 1500);
378 g_icmpPingSize = ConfigReadInt(_T("IcmpPingSize"), 46);
379 g_lockTimeout = ConfigReadInt(_T("LockTimeout"), 60000);
c42b4551 380 g_snmpTimeout = ConfigReadInt(_T("SNMPRequestTimeout"), 2000);
c59466d2
VK
381 g_agentCommandTimeout = ConfigReadInt(_T("AgentCommandTimeout"), 4000);
382 g_thresholdRepeatInterval = ConfigReadInt(_T("ThresholdRepeatInterval"), 0);
383 g_requiredPolls = ConfigReadInt(_T("PollCountForStatusChange"), 1);
5039dede
AK
384}
385
fdbee7f8
VK
386/**
387 * Initialize cryptografic functions
388 */
73869331 389static BOOL InitCryptografy()
5039dede
AK
390{
391#ifdef _WITH_ENCRYPTION
35f836fe 392 TCHAR szKeyFile[MAX_PATH];
5039dede
AK
393 BOOL bResult = FALSE;
394 int fd, iPolicy;
967893bb 395 UINT32 dwLen;
5039dede
AK
396 BYTE *pBufPos, *pKeyBuffer, hash[SHA1_DIGEST_SIZE];
397
6468147c 398 if (!InitCryptoLib(ConfigReadULong(_T("AllowedCiphers"), 0x7F), DbgPrintf2))
5039dede
AK
399 return FALSE;
400
958a9397 401 SSL_library_init();
0fd5c0a1 402 SSL_load_error_strings();
958a9397 403
35f836fe
VK
404 _tcscpy(szKeyFile, g_szDataDir);
405 _tcscat(szKeyFile, DFILE_KEYS);
406 fd = _topen(szKeyFile, O_RDONLY | O_BINARY);
5039dede
AK
407 g_pServerKey = LoadRSAKeys(szKeyFile);
408 if (g_pServerKey == NULL)
409 {
35f836fe 410 DbgPrintf(1, _T("Generating RSA key pair..."));
5039dede
AK
411 g_pServerKey = RSA_generate_key(NETXMS_RSA_KEYLEN, 17, NULL, 0);
412 if (g_pServerKey != NULL)
413 {
35f836fe 414 fd = _topen(szKeyFile, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, 0600);
5039dede
AK
415 if (fd != -1)
416 {
417 dwLen = i2d_RSAPublicKey(g_pServerKey, NULL);
418 dwLen += i2d_RSAPrivateKey(g_pServerKey, NULL);
419 pKeyBuffer = (BYTE *)malloc(dwLen);
420
421 pBufPos = pKeyBuffer;
422 i2d_RSAPublicKey(g_pServerKey, &pBufPos);
423 i2d_RSAPrivateKey(g_pServerKey, &pBufPos);
967893bb 424 write(fd, &dwLen, sizeof(UINT32));
5039dede
AK
425 write(fd, pKeyBuffer, dwLen);
426
427 CalculateSHA1Hash(pKeyBuffer, dwLen, hash);
428 write(fd, hash, SHA1_DIGEST_SIZE);
429
430 close(fd);
431 free(pKeyBuffer);
432 bResult = TRUE;
433 }
c578be51
AK
434 else
435 {
436 DbgPrintf(0, _T("Failed to open %s for writing"), szKeyFile);
437 }
5039dede 438 }
c578be51
AK
439 else
440 {
441 DbgPrintf(0, _T("Failed to generate RSA key"));
442 }
5039dede
AK
443 }
444 else
445 {
446 bResult = TRUE;
447 }
448
35f836fe 449 iPolicy = ConfigReadInt(_T("DefaultEncryptionPolicy"), 1);
5039dede
AK
450 if ((iPolicy < 0) || (iPolicy > 3))
451 iPolicy = 1;
452 SetAgentDEP(iPolicy);
453
454 return bResult;
455#else
456 return TRUE;
457#endif
458}
459
496390c2
VK
460/**
461 * Check if process with given PID exists and is a NetXMS server process
462 */
967893bb 463static BOOL IsNetxmsdProcess(UINT32 dwPID)
5039dede
AK
464{
465#ifdef _WIN32
466 HANDLE hProcess;
467 TCHAR szExtModule[MAX_PATH], szIntModule[MAX_PATH];
468 BOOL bRet = FALSE;
469
470 hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwPID);
471 if (hProcess != NULL)
472 {
473 if ((GetModuleBaseName(hProcess, NULL, szExtModule, MAX_PATH) > 0) &&
474 (GetModuleBaseName(GetCurrentProcess(), NULL, szIntModule, MAX_PATH) > 0))
475 {
476 bRet = !_tcsicmp(szExtModule, szIntModule);
477 }
478 else
479 {
480 // Cannot read process name, for safety assume that it's a server process
481 bRet = TRUE;
482 }
483 CloseHandle(hProcess);
484 }
485 return bRet;
486#else
487 return (kill((pid_t)dwPID, 0) != -1);
488#endif
489}
490
496390c2
VK
491/**
492 * Database event handler
493 */
35f836fe 494static void DBEventHandler(DWORD dwEvent, const WCHAR *pszArg1, const WCHAR *pszArg2, void *userArg)
5039dede 495{
c8076b19 496 if (!(g_flags & AF_SERVER_INITIALIZED))
5039dede
AK
497 return; // Don't try to do anything if server is not ready yet
498
499 switch(dwEvent)
500 {
501 case DBEVENT_CONNECTION_LOST:
502 PostEvent(EVENT_DB_CONNECTION_LOST, g_dwMgmtNode, NULL);
c8076b19 503 g_flags |= AF_DB_CONNECTION_LOST;
5039dede
AK
504 NotifyClientSessions(NX_NOTIFY_DBCONN_STATUS, FALSE);
505 break;
506 case DBEVENT_CONNECTION_RESTORED:
507 PostEvent(EVENT_DB_CONNECTION_RESTORED, g_dwMgmtNode, NULL);
c8076b19 508 g_flags &= ~AF_DB_CONNECTION_LOST;
5039dede
AK
509 NotifyClientSessions(NX_NOTIFY_DBCONN_STATUS, TRUE);
510 break;
4d0c32f3 511 case DBEVENT_QUERY_FAILED:
5049e942 512 PostEvent(EVENT_DB_QUERY_FAILED, g_dwMgmtNode, "uu", pszArg1, pszArg2);
4d0c32f3 513 break;
5039dede
AK
514 default:
515 break;
516 }
517}
518
496390c2
VK
519/**
520 * Send console message to session with open console
521 */
f669df41
VK
522static void SendConsoleMessage(ClientSession *session, void *arg)
523{
524 if (session->isConsoleOpen())
525 {
b368969c 526 NXCPMessage msg;
f669df41 527
b368969c
VK
528 msg.setCode(CMD_ADM_MESSAGE);
529 msg.setField(VID_MESSAGE, (TCHAR *)arg);
d3a7cf4c 530 session->postMessage(&msg);
f669df41
VK
531 }
532}
533
d6217efa
VK
534/**
535 * Console writer
536 */
f669df41
VK
537static void LogConsoleWriter(const TCHAR *format, ...)
538{
539 TCHAR buffer[8192];
540 va_list args;
541
542 va_start(args, format);
543 _vsntprintf(buffer, 8192, format, args);
544 buffer[8191] = 0;
545 va_end(args);
546
547 WriteToTerminal(buffer);
548
549 EnumerateClientSessions(SendConsoleMessage, buffer);
550}
551
fdbee7f8
VK
552/**
553 * Server initialization
554 */
bc980b27 555BOOL NXCORE_EXPORTABLE Initialize()
5039dede
AK
556{
557 int i, iDBVersion;
967893bb 558 UINT32 dwAddr;
35f836fe 559 TCHAR szInfo[256];
5039dede 560
c59466d2
VK
561 g_serverStartTime = time(NULL);
562 srand((unsigned int)g_serverStartTime);
4f8998ca 563
c8076b19 564 if (!(g_flags & AF_USE_SYSLOG))
4f8998ca
VK
565 {
566 if (!nxlog_set_rotation_policy((int)g_dwLogRotationMode, (int)g_dwMaxLogSize, (int)g_dwLogHistorySize, g_szDailyLogFileSuffix))
c8076b19 567 if (!(g_flags & AF_DAEMON))
4f8998ca
VK
568 _tprintf(_T("WARNING: cannot set log rotation policy; using default values\n"));
569 }
c8076b19
VK
570 if (!nxlog_open((g_flags & AF_USE_SYSLOG) ? NETXMSD_SYSLOG_NAME : g_szLogFile,
571 ((g_flags & AF_USE_SYSLOG) ? NXLOG_USE_SYSLOG : 0) | ((g_flags & AF_DAEMON) ? 0 : NXLOG_PRINT_TO_STDOUT),
9d381279 572 _T("LIBNXSRV.DLL"),
5039dede 573#ifdef _WIN32
9d381279 574 0, NULL))
5039dede 575#else
9d381279 576 g_dwNumMessages, g_szMessages))
5039dede 577#endif
9d381279
VK
578 {
579 _ftprintf(stderr, _T("FATAL ERROR: Cannot open log file\n"));
580 return FALSE;
581 }
f669df41 582 nxlog_set_console_writer(LogConsoleWriter);
5039dede
AK
583
584 // Set code page
585#ifndef _WIN32
586 if (SetDefaultCodepage(g_szCodePage))
587 {
f5797a09 588 DbgPrintf(1, _T("Code page set to %hs"), g_szCodePage);
5039dede
AK
589 }
590 else
591 {
f375019e 592 nxlog_write(MSG_CODEPAGE_ERROR, EVENTLOG_WARNING_TYPE, "m", g_szCodePage);
5039dede
AK
593 }
594#endif
595
73869331
VK
596 // Set process affinity mask
597 if (g_processAffinityMask != DEFAULT_AFFINITY_MASK)
598 {
599#ifdef _WIN32
600 if (SetProcessAffinityMask(GetCurrentProcess(), g_processAffinityMask))
601 DbgPrintf(1, _T("Process affinity mask set to 0x%08X"), g_processAffinityMask);
602#else
603 nxlog_write(MSG_SET_PROCESS_AFFINITY_NOT_SUPPORTED, EVENTLOG_WARNING_TYPE, NULL);
604#endif
605 }
606
5039dede
AK
607#ifdef _WIN32
608 WSADATA wsaData;
1ddf3f0c
VK
609 int wrc = WSAStartup(MAKEWORD(2, 2), &wsaData);
610 if (wrc != 0)
611 {
612 nxlog_write(MSG_WSASTARTUP_FAILED, EVENTLOG_ERROR_TYPE, "e", wrc);
613 return FALSE;
614 }
5039dede
AK
615#endif
616
617 InitLocalNetInfo();
618
619 // Create queue for delayed SQL queries
76fcb995
VK
620 g_dbWriterQueue = new Queue(256, 64);
621 g_dciDataWriterQueue = new Queue(1024, 1024);
622 g_dciRawDataWriterQueue = new Queue(1024, 1024);
5039dede
AK
623
624 // Initialize database driver and connect to database
9d88cdc9 625 DBSetDebugPrintCallback(DbgPrintf2);
c8076b19 626 if (!DBInit(MSG_OTHER, (g_flags & AF_LOG_SQL_ERRORS) ? MSG_SQL_ERROR : 0))
b8c1ec69 627 return FALSE;
ed950274 628 g_dbDriver = DBLoadDriver(g_szDbDriver, g_szDbDrvParams, (g_debugLevel >= 9), DBEventHandler, NULL);
b8c1ec69 629 if (g_dbDriver == NULL)
5039dede
AK
630 return FALSE;
631
632 // Connect to database
465b3f2d 633 TCHAR errorText[DBDRV_MAX_ERROR_TEXT];
5039dede
AK
634 for(i = 0; ; i++)
635 {
f3c30cf5 636 g_hCoreDB = DBConnect(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, errorText);
5039dede
AK
637 if ((g_hCoreDB != NULL) || (i == 5))
638 break;
639 ThreadSleep(5);
640 }
641 if (g_hCoreDB == NULL)
642 {
465b3f2d 643 nxlog_write(MSG_DB_CONNFAIL, EVENTLOG_ERROR_TYPE, "s", errorText);
5039dede
AK
644 return FALSE;
645 }
35f836fe 646 DbgPrintf(1, _T("Successfully connected to database %s@%s"), g_szDbName, g_szDbServer);
5039dede
AK
647
648 // Check database version
28f5b9a4 649 iDBVersion = DBGetSchemaVersion(g_hCoreDB);
5039dede
AK
650 if (iDBVersion != DB_FORMAT_VERSION)
651 {
652 nxlog_write(MSG_WRONG_DB_VERSION, EVENTLOG_ERROR_TYPE, "dd", iDBVersion, DB_FORMAT_VERSION);
653 return FALSE;
654 }
655
35f836fe
VK
656 int baseSize = ConfigReadInt(_T("ConnectionPoolBaseSize"), 5);
657 int maxSize = ConfigReadInt(_T("ConnectionPoolMaxSize"), 20);
658 int cooldownTime = ConfigReadInt(_T("ConnectionPoolCooldownTime"), 300);
30d9c43c 659 DBConnectionPoolStartup(g_dbDriver, g_szDbServer, g_szDbName, g_szDbLogin, g_szDbPassword, g_szDbSchema, baseSize, maxSize, cooldownTime, 0, g_hCoreDB);
c8076b19 660 g_flags |= AF_DB_CONNECTION_POOL_READY;
f727d089 661
58f1f627
VK
662 UINT32 lrt = ConfigReadULong(_T("LongRunningQueryThreshold"), 0);
663 if (lrt != 0)
664 DBSetLongRunningThreshold(lrt);
665
5039dede 666 // Read database syntax
2a964810 667 g_dbSyntax = DBGetSyntax(g_hCoreDB);
5039dede
AK
668
669 // Read server ID
35f836fe 670 ConfigReadStr(_T("ServerID"), szInfo, 256, _T(""));
5039dede
AK
671 StrStrip(szInfo);
672 if (szInfo[0] != 0)
673 {
674 StrToBin(szInfo, (BYTE *)&g_qwServerId, sizeof(QWORD));
675 }
676 else
677 {
678 // Generate new ID
679 g_qwServerId = (((QWORD)time(NULL)) << 32) | rand();
680 BinToStr((BYTE *)&g_qwServerId, sizeof(QWORD), szInfo);
35f836fe 681 ConfigWriteStr(_T("ServerID"), szInfo, TRUE);
5039dede
AK
682 }
683
684 // Initialize locks
685retry_db_lock:
686 if (!InitLocks(&dwAddr, szInfo))
687 {
688 if (dwAddr == UNLOCKED) // Some SQL problems
689 {
690 nxlog_write(MSG_INIT_LOCKS_FAILED, EVENTLOG_ERROR_TYPE, NULL);
691 }
692 else // Database already locked by another server instance
693 {
694 // Check for lock from crashed/terminated local process
695 if (dwAddr == GetLocalIpAddr())
696 {
967893bb 697 UINT32 dwPID;
5039dede 698
35f836fe 699 dwPID = ConfigReadULong(_T("DBLockPID"), 0);
5039dede
AK
700 if (!IsNetxmsdProcess(dwPID) || (dwPID == GetCurrentProcessId()))
701 {
702 UnlockDB();
703 nxlog_write(MSG_DB_LOCK_REMOVED, EVENTLOG_INFORMATION_TYPE, NULL);
704 goto retry_db_lock;
705 }
706 }
707 nxlog_write(MSG_DB_LOCKED, EVENTLOG_ERROR_TYPE, "as", dwAddr, szInfo);
708 }
709 return FALSE;
710 }
c8076b19 711 g_flags |= AF_DB_LOCKED;
5039dede
AK
712
713 // Load global configuration parameters
714 LoadGlobalConfig();
958a9397 715 CASReadSettings();
35f836fe 716 DbgPrintf(1, _T("Global configuration loaded"));
5039dede
AK
717
718 // Check data directory
719 if (!CheckDataDir())
720 return FALSE;
721
722 // Initialize cryptografy
723 if (!InitCryptografy())
724 {
725 nxlog_write(MSG_INIT_CRYPTO_FAILED, EVENTLOG_ERROR_TYPE, NULL);
726 return FALSE;
727 }
728
729 // Initialize certificate store and CA
730 InitCertificates();
731
5039dede
AK
732 // Create synchronization stuff
733 m_condShutdown = ConditionCreate(TRUE);
734
735 // Setup unique identifiers table
736 if (!InitIdTable())
737 return FALSE;
35f836fe 738 DbgPrintf(2, _T("ID table created"));
5039dede 739
24dc5346
VK
740 // Update status for unfinished jobs in job history
741 DBQuery(g_hCoreDB, _T("UPDATE job_history SET status=4,failure_message='Aborted due to server shutdown or crash' WHERE status NOT IN (3,4,5)"));
742
5039dede
AK
743 // Load and compile scripts
744 LoadScripts();
745
f7e4c50e
VK
746 // Initialize watchdog
747 WatchdogInit();
748
53d2de79 749 // Load modules
890478d8
VK
750 if (!LoadNetXMSModules())
751 return FALSE; // Mandatory module not loaded
53d2de79 752
5039dede
AK
753 // Initialize mailer and SMS sender
754 InitMailer();
755 InitSMSSender();
756
757 // Load users from database
ab185583 758 InitUsers();
5039dede
AK
759 if (!LoadUsers())
760 {
761 nxlog_write(MSG_ERROR_LOADING_USERS, EVENTLOG_ERROR_TYPE, NULL);
762 return FALSE;
763 }
35f836fe 764 DbgPrintf(2, _T("User accounts loaded"));
5039dede
AK
765
766 // Initialize audit
767 InitAuditLog();
768
da84c57a
VK
769 // Initialize event handling subsystem
770 if (!InitEventSubsystem())
771 return FALSE;
772
773 // Initialize alarms
774 if (!InitAlarmManager())
775 return FALSE;
776
5039dede 777 // Initialize objects infrastructure and load objects from database
9796ce45 778 LoadNetworkDeviceDrivers();
5039dede
AK
779 ObjectsInit();
780 if (!LoadObjects())
781 return FALSE;
35f836fe 782 DbgPrintf(1, _T("Objects loaded and initialized"));
d9177dd1 783
5039dede
AK
784 // Initialize situations
785 if (!SituationsInit())
786 return FALSE;
35f836fe 787 DbgPrintf(1, _T("Situations loaded and initialized"));
5039dede
AK
788
789 // Initialize and load event actions
790 if (!InitActions())
791 {
792 nxlog_write(MSG_ACTION_INIT_ERROR, EVENTLOG_ERROR_TYPE, NULL);
793 return FALSE;
794 }
795
6fad8870
VK
796 // Initialize helpdesk link
797 SetHDLinkEntryPoints(ResolveAlarmByHDRef, TerminateAlarmByHDRef);
798 LoadHelpDeskLink();
799
5039dede 800 // Initialize data collection subsystem
8fd95c92 801 LoadPerfDataStorageDrivers();
5039dede
AK
802 if (!InitDataCollector())
803 return FALSE;
804
e05b1945 805 InitLogAccess();
d77baddd 806 FileUploadJob::init();
fdbee7f8 807 InitMappingTables();
e05b1945 808
5039dede
AK
809 // Check if management node object presented in database
810 CheckForMgmtNode();
811 if (g_dwMgmtNode == 0)
812 {
813 nxlog_write(MSG_CANNOT_FIND_SELF, EVENTLOG_ERROR_TYPE, NULL);
814 return FALSE;
815 }
816
817 // Start threads
818 ThreadCreate(WatchdogThread, 0, NULL);
819 ThreadCreate(NodePoller, 0, NULL);
3929b1ca 820 ThreadCreate(JobManagerThread, 0, NULL);
5039dede
AK
821 m_thSyncer = ThreadCreateEx(Syncer, 0, NULL);
822 m_thHouseKeeper = ThreadCreateEx(HouseKeeper, 0, NULL);
823 m_thPollManager = ThreadCreateEx(PollManager, 0, NULL);
824
825 // Start event processor
826 ThreadCreate(EventProcessor, 0, NULL);
827
828 // Start SNMP trapper
829 InitTraps();
35f836fe 830 if (ConfigReadInt(_T("EnableSNMPTraps"), 1))
5039dede
AK
831 ThreadCreate(SNMPTrapReceiver, 0, NULL);
832
833 // Start built-in syslog daemon
35f836fe 834 if (ConfigReadInt(_T("EnableSyslogDaemon"), 0))
5039dede
AK
835 m_thSyslogDaemon = ThreadCreateEx(SyslogDaemon, 0, NULL);
836
35f836fe 837 // Start database _T("lazy") write thread
5039dede
AK
838 StartDBWriter();
839
840 // Start local administartive interface listener if required
35f836fe 841 if (ConfigReadInt(_T("EnableAdminInterface"), 1))
5039dede
AK
842 ThreadCreate(LocalAdminListener, 0, NULL);
843
5039dede
AK
844 // Start beacon host poller
845 ThreadCreate(BeaconPoller, 0, NULL);
846
847 // Start inter-server communication listener
35f836fe 848 if (ConfigReadInt(_T("EnableISCListener"), 0))
5039dede
AK
849 ThreadCreate(ISCListener, 0, NULL);
850
d75003e1
AK
851 // Start reporting server connector
852 if (ConfigReadInt(_T("EnableReportingServer"), 0))
853 ThreadCreate(ReportingServerConnector, 0, NULL);
854
d9177dd1 855 //Start ldap synchronization
856 if (ConfigReadInt(_T("LdapSyncInterval"), 0))
857 ThreadCreate(SyncLDAPUsers, 0, NULL);
858
5039dede 859 // Allow clients to connect
36e44abe 860 InitClientListeners();
5039dede 861 ThreadCreate(ClientListener, 0, NULL);
36e44abe
VK
862#ifdef WITH_IPV6
863 ThreadCreate(ClientListenerIPv6, 0, NULL);
864#endif
5039dede 865
534e1b83
VK
866 // Allow mobile devices to connect
867 InitMobileDeviceListeners();
868 ThreadCreate(MobileDeviceListener, 0, NULL);
869#ifdef WITH_IPV6
870 ThreadCreate(MobileDeviceListenerIPv6, 0, NULL);
871#endif
872
86457857
AK
873 // Start uptime calculator for SLM
874 ThreadCreate(UptimeCalculator, 0, NULL);
875
712dd47d
VK
876 DbgPrintf(2, _T("LIBDIR: %s"), g_szLibDir);
877
1b42a673 878 // Call startup functions for the modules
a0efa7b5 879 CALL_ALL_MODULES(pfServerStarted, ());
53d2de79 880
058bf6fc 881#if XMPP_SUPPORTED
244c65ef
VK
882 if (ConfigReadInt(_T("EnableXMPPConnector"), 1))
883 {
884 m_thXMPPConnector = ThreadCreateEx(XMPPConnectionManager, 0, NULL);
885 }
058bf6fc 886#endif
244c65ef 887
c8076b19 888 g_flags |= AF_SERVER_INITIALIZED;
35f836fe 889 DbgPrintf(1, _T("Server initialization completed"));
5039dede
AK
890 return TRUE;
891}
892
371d9c60
VK
893/**
894 * Server shutdown
895 */
035a4d73 896void NXCORE_EXPORTABLE Shutdown()
5039dede 897{
5039dede
AK
898 // Notify clients
899 NotifyClientSessions(NX_NOTIFY_SHUTDOWN, 0);
900
901 nxlog_write(MSG_SERVER_STOPPED, EVENTLOG_INFORMATION_TYPE, NULL);
c8076b19 902 g_flags |= AF_SHUTDOWN; // Set shutdown flag
5039dede
AK
903 ConditionSet(m_condShutdown);
904
d140955e
VK
905 // Stop DCI cache loading thread
906 g_dciCacheLoaderQueue.SetShutdownMode();
907
058bf6fc 908#if XMPP_SUPPORTED
244c65ef 909 StopXMPPConnector();
058bf6fc 910#endif
244c65ef 911
5039dede
AK
912#ifndef _WIN32
913 if (IsStandalone() && (m_nShutdownReason != SHUTDOWN_BY_SIGNAL))
914 {
915 pthread_kill(m_signalHandlerThread, SIGUSR1); // Terminate signal handler
916 }
917#endif
918
4f50e45c 919 // Stop event processor
5039dede 920 g_pEventQueue->Clear();
4f50e45c 921 g_pEventQueue->Put(INVALID_POINTER_VALUE);
5039dede
AK
922
923 ShutdownMailer();
924 ShutdownSMSSender();
925
926 ThreadSleep(1); // Give other threads a chance to terminate in a safe way
35f836fe 927 DbgPrintf(2, _T("All threads was notified, continue with shutdown"));
5039dede
AK
928
929 // Wait for critical threads
930 ThreadJoin(m_thHouseKeeper);
931 ThreadJoin(m_thPollManager);
932 ThreadJoin(m_thSyncer);
933 ThreadJoin(m_thSyslogDaemon);
058bf6fc 934#if XMPP_SUPPORTED
244c65ef 935 ThreadJoin(m_thXMPPConnector);
058bf6fc 936#endif
5039dede 937
a0efa7b5
VK
938 // Call shutdown functions for the modules
939 // CALL_ALL_MODULES cannot be used here because it checks for shutdown flag
940 for(UINT32 i = 0; i < g_dwNumModules; i++)
941 {
942 if (g_pModuleList[i].pfShutdown != NULL)
943 g_pModuleList[i].pfShutdown();
944 }
945
5039dede 946 SaveObjects(g_hCoreDB);
35f836fe 947 DbgPrintf(2, _T("All objects saved to database"));
5039dede 948 SaveUsers(g_hCoreDB);
35f836fe 949 DbgPrintf(2, _T("All users saved to database"));
5039dede 950 StopDBWriter();
35f836fe 951 DbgPrintf(1, _T("Database writer stopped"));
5039dede 952
ab185583
VK
953 CleanupUsers();
954
5039dede
AK
955 // Remove database lock
956 UnlockDB();
957
7a7dfb3e
VK
958 DBConnectionPoolShutdown();
959
5039dede
AK
960 // Disconnect from database and unload driver
961 if (g_hCoreDB != NULL)
962 DBDisconnect(g_hCoreDB);
c20b2798 963
b8c1ec69 964 DBUnloadDriver(g_dbDriver);
35f836fe 965 DbgPrintf(1, _T("Database driver unloaded"));
5039dede
AK
966
967 CleanupActions();
968 ShutdownEventSubsystem();
da84c57a 969 ShutdownAlarmManager();
35f836fe 970 DbgPrintf(1, _T("Event processing stopped"));
5039dede 971
5039dede
AK
972 delete g_pScriptLibrary;
973
974 nxlog_close();
975
976 // Remove PID file
977#ifndef _WIN32
dda7c270 978 _tremove(g_szPIDFile);
5039dede
AK
979#endif
980
981 // Terminate process
982#ifdef _WIN32
c8076b19 983 if (!(g_flags & AF_DAEMON))
5039dede
AK
984 ExitProcess(0);
985#else
986 exit(0);
987#endif
988}
989
371d9c60
VK
990/**
991 * Fast server shutdown - normally called only by Windows service on system shutdown
992 */
f669df41 993void NXCORE_EXPORTABLE FastShutdown()
5039dede 994{
c8076b19 995 g_flags |= AF_SHUTDOWN; // Set shutdown flag
5039dede
AK
996 ConditionSet(m_condShutdown);
997
998 SaveObjects(g_hCoreDB);
35f836fe 999 DbgPrintf(2, _T("All objects saved to database"));
5039dede 1000 SaveUsers(g_hCoreDB);
35f836fe 1001 DbgPrintf(2, _T("All users saved to database"));
5039dede
AK
1002
1003 // Remove database lock first, because we have a chance to loose DB connection
1004 UnlockDB();
1005
1006 // Stop database writers
1007 StopDBWriter();
35f836fe 1008 DbgPrintf(1, _T("Database writer stopped"));
5039dede
AK
1009
1010 nxlog_close();
1011}
1012
fdbee7f8
VK
1013/**
1014 * Compare given string to command template with abbreviation possibility
1015 */
ca0e18d2 1016static bool IsCommand(const TCHAR *cmdTemplate, TCHAR *pszString, int iMinChars)
5039dede
AK
1017{
1018 int i;
1019
1020 // Convert given string to uppercase
35f836fe 1021 _tcsupr(pszString);
5039dede
AK
1022
1023 for(i = 0; pszString[i] != 0; i++)
ca0e18d2 1024 if (pszString[i] != cmdTemplate[i])
fdbee7f8 1025 return false;
5039dede 1026 if (i < iMinChars)
fdbee7f8
VK
1027 return false;
1028 return true;
5039dede
AK
1029}
1030
fdbee7f8
VK
1031/**
1032 * Dump index
1033 */
d5e19c61 1034struct __dump_index_data
5039dede 1035{
d5e19c61
VK
1036 CONSOLE_CTX console;
1037 bool indexByIP;
1038};
5039dede 1039
d5e19c61
VK
1040static void DumpIndexCallback(NetObj *object, void *data)
1041{
1042 struct __dump_index_data *d = (struct __dump_index_data *)data;
1043 if (d->indexByIP)
5039dede 1044 {
d5e19c61
VK
1045 TCHAR buffer[16];
1046 ConsolePrintf(d->console, _T("%08X [%-15s] %p %s\n"), object->IpAddr(),
1047 IpToStr(object->IpAddr(), buffer),
c42b4551 1048 object, object->getName());
5039dede 1049 }
d5e19c61
VK
1050 else
1051 {
c42b4551 1052 ConsolePrintf(d->console, _T("%08X %p %s\n"), object->getId(), object, object->getName());
d5e19c61
VK
1053 }
1054}
5039dede 1055
d5e19c61
VK
1056static void DumpIndex(CONSOLE_CTX pCtx, ObjectIndex *index, bool indexByIp)
1057{
1058 struct __dump_index_data data;
1059 data.console = pCtx;
1060 data.indexByIP = indexByIp;
1061 index->forEach(DumpIndexCallback, &data);
5039dede
AK
1062}
1063
e323047c
VK
1064/**
1065 * Process command entered from command line in standalone mode
1066 * Return TRUE if command was _T("down")
1067 */
35f836fe 1068int ProcessConsoleCommand(const TCHAR *pszCmdLine, CONSOLE_CTX pCtx)
5039dede 1069{
35f836fe 1070 const TCHAR *pArg;
48c0079d 1071 TCHAR szBuffer[256], *eptr;
5039dede
AK
1072 int nExitCode = CMD_EXIT_CONTINUE;
1073
1074 // Get command
1075 pArg = ExtractWord(pszCmdLine, szBuffer);
1076
35f836fe 1077 if (IsCommand(_T("DEBUG"), szBuffer, 2))
5039dede
AK
1078 {
1079 // Get argument
1080 pArg = ExtractWord(pArg, szBuffer);
48c0079d
VK
1081 int level = (int)_tcstol(szBuffer, &eptr, 0);
1082 if ((*eptr == 0) && (level >= 0) && (level <= 9))
5039dede 1083 {
967893bb 1084 g_debugLevel = (UINT32)level;
48c0079d 1085 ConsolePrintf(pCtx, (level == 0) ? _T("Debug mode turned off\n") : _T("Debug level set to %d\n"), level);
5039dede 1086 }
35f836fe 1087 else if (IsCommand(_T("OFF"), szBuffer, 2))
5039dede 1088 {
ed950274 1089 g_debugLevel = 0;
35f836fe 1090 ConsolePrintf(pCtx, _T("Debug mode turned off\n"));
5039dede
AK
1091 }
1092 else
1093 {
1094 if (szBuffer[0] == 0)
35f836fe 1095 ConsolePrintf(pCtx, _T("ERROR: Missing argument\n\n"));
5039dede 1096 else
48c0079d 1097 ConsolePrintf(pCtx, _T("ERROR: Invalid debug level\n\n"));
5039dede
AK
1098 }
1099 }
35f836fe 1100 else if (IsCommand(_T("DOWN"), szBuffer, 4))
5039dede 1101 {
35f836fe 1102 ConsolePrintf(pCtx, _T("Proceeding with server shutdown...\n"));
5039dede
AK
1103 nExitCode = CMD_EXIT_SHUTDOWN;
1104 }
35f836fe 1105 else if (IsCommand(_T("DUMP"), szBuffer, 4))
5039dede
AK
1106 {
1107 DumpProcess(pCtx);
1108 }
206e268e
VK
1109 else if (IsCommand(_T("GET"), szBuffer, 3))
1110 {
1111 pArg = ExtractWord(pArg, szBuffer);
1112 if (szBuffer[0] != 0)
1113 {
1114 TCHAR value[256];
1115 ConfigReadStr(szBuffer, value, 256, _T(""));
1116 ConsolePrintf(pCtx, _T("%s = %s\n"), szBuffer, value);
1117 }
1118 else
1119 {
1120 ConsolePrintf(pCtx, _T("Variable name missing\n"));
1121 }
1122 }
35f836fe 1123 else if (IsCommand(_T("RAISE"), szBuffer, 5))
5039dede
AK
1124 {
1125 // Get argument
1126 pArg = ExtractWord(pArg, szBuffer);
1127
35f836fe 1128 if (IsCommand(_T("ACCESS"), szBuffer, 6))
5039dede 1129 {
35f836fe 1130 ConsolePrintf(pCtx, _T("Raising exception...\n"));
5039dede
AK
1131 char *p = NULL;
1132 *p = 0;
1133 }
35f836fe 1134 else if (IsCommand(_T("BREAKPOINT"), szBuffer, 5))
5039dede
AK
1135 {
1136#ifdef _WIN32
35f836fe 1137 ConsolePrintf(pCtx, _T("Raising exception...\n"));
5039dede
AK
1138 RaiseException(EXCEPTION_BREAKPOINT, 0, 0, NULL);
1139#else
35f836fe 1140 ConsolePrintf(pCtx, _T("ERROR: Not supported on current platform\n"));
5039dede
AK
1141#endif
1142 }
1143 else
1144 {
35f836fe 1145 ConsolePrintf(pCtx, _T("Invalid exception name; possible names are:\nACCESS BREAKPOINT\n"));
5039dede
AK
1146 }
1147 }
35f836fe 1148 else if (IsCommand(_T("EXIT"), szBuffer, 4))
5039dede 1149 {
f669df41 1150 if ((pCtx->hSocket != -1) || (pCtx->session != NULL))
5039dede 1151 {
35f836fe 1152 ConsolePrintf(pCtx, _T("Closing session...\n"));
5039dede
AK
1153 nExitCode = CMD_EXIT_CLOSE_SESSION;
1154 }
1155 else
1156 {
35f836fe 1157 ConsolePrintf(pCtx, _T("Cannot exit from local server console\n"));
5039dede
AK
1158 }
1159 }
5d9a9c84
VK
1160 else if (IsCommand(_T("KILL"), szBuffer, 4))
1161 {
1162 pArg = ExtractWord(pArg, szBuffer);
1163 if (szBuffer[0] != 0)
1164 {
1165 int id = _tcstol(szBuffer, &eptr, 10);
1166 if (*eptr == 0)
1167 {
1168 if (KillClientSession(id))
1169 {
1170 ConsolePrintf(pCtx, _T("Session killed\n"));
1171 }
1172 else
1173 {
1174 ConsolePrintf(pCtx, _T("Invalid session ID\n"));
1175 }
1176 }
1177 else
1178 {
1179 ConsolePrintf(pCtx, _T("Invalid session ID\n"));
1180 }
1181 }
1182 else
1183 {
1184 ConsolePrintf(pCtx, _T("Session ID missing\n"));
1185 }
1186 }
206e268e
VK
1187 else if (IsCommand(_T("SET"), szBuffer, 3))
1188 {
1189 pArg = ExtractWord(pArg, szBuffer);
1190 if (szBuffer[0] != 0)
1191 {
1192 TCHAR value[256];
1193 pArg = ExtractWord(pArg, value);
1194 if (ConfigWriteStr(szBuffer, value, TRUE, TRUE, TRUE))
1195 {
1196 ConsolePrintf(pCtx, _T("Configuration variable %s updated\n"), szBuffer);
1197 }
1198 else
1199 {
1200 ConsolePrintf(pCtx, _T("ERROR: cannot update configuration variable %s\n"), szBuffer);
1201 }
1202 }
1203 else
1204 {
1205 ConsolePrintf(pCtx, _T("Variable name missing\n"));
1206 }
1207 }
35f836fe 1208 else if (IsCommand(_T("SHOW"), szBuffer, 2))
5039dede
AK
1209 {
1210 // Get argument
1211 pArg = ExtractWord(pArg, szBuffer);
1212
50d0de67
VK
1213 if (IsCommand(_T("COMPONENTS"), szBuffer, 1))
1214 {
1215 // Get argument
1216 pArg = ExtractWord(pArg, szBuffer);
967893bb 1217 UINT32 dwNode = _tcstoul(szBuffer, NULL, 0);
50d0de67
VK
1218 if (dwNode != 0)
1219 {
1220 NetObj *pObject = FindObjectById(dwNode);
1221 if (pObject != NULL)
1222 {
c42b4551 1223 if (pObject->getObjectClass() == OBJECT_NODE)
50d0de67 1224 {
8836184f
VK
1225 ComponentTree *components = ((Node *)pObject)->getComponents();
1226 if (components != NULL)
50d0de67 1227 {
8836184f
VK
1228 components->print(pCtx);
1229 components->decRefCount();
50d0de67
VK
1230 }
1231 else
1232 {
1233 ConsolePrintf(pCtx, _T("ERROR: Node does not have physical component information\n\n"));
1234 }
1235 }
1236 else
1237 {
1238 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
1239 }
1240 }
1241 else
1242 {
1243 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode);
1244 }
1245 }
1246 else
1247 {
1248 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node ID\n\n"));
1249 }
1250 }
9c133761
VK
1251 else if (IsCommand(_T("DBCP"), szBuffer, 4))
1252 {
1253 ObjectArray<PoolConnectionInfo> *list = DBConnectionPoolGetConnectionList();
1254 for(int i = 0; i < list->size(); i++)
1255 {
1256 PoolConnectionInfo *c = list->get(i);
1257 TCHAR accessTime[64];
1258 struct tm *ltm = localtime(&c->lastAccessTime);
1259 _tcsftime(accessTime, 64, _T("%d.%b.%Y %H:%M:%S"), ltm);
1260 ConsolePrintf(pCtx, _T("%p %s %hs:%d\n"), c->handle, accessTime, c->srcFile, c->srcLine);
1261 }
1262 ConsolePrintf(pCtx, _T("%d database connections in use\n\n"), list->size());
1263 delete list;
1264 }
4321449e
VK
1265 else if (IsCommand(_T("FDB"), szBuffer, 3))
1266 {
1267 // Get argument
1268 pArg = ExtractWord(pArg, szBuffer);
1269 UINT32 dwNode = _tcstoul(szBuffer, NULL, 0);
1270 if (dwNode != 0)
1271 {
1272 NetObj *pObject = FindObjectById(dwNode);
1273 if (pObject != NULL)
1274 {
c42b4551 1275 if (pObject->getObjectClass() == OBJECT_NODE)
4321449e
VK
1276 {
1277 ForwardingDatabase *fdb = ((Node *)pObject)->getSwitchForwardingDatabase();
1278 if (fdb != NULL)
1279 {
1280 fdb->print(pCtx, (Node *)pObject);
1281 fdb->decRefCount();
1282 }
1283 else
1284 {
1285 ConsolePrintf(pCtx, _T("ERROR: Node does not have forwarding database information\n\n"));
1286 }
1287 }
1288 else
1289 {
1290 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
1291 }
1292 }
1293 else
1294 {
1295 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode);
1296 }
1297 }
1298 else
1299 {
1300 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node ID\n\n"));
1301 }
1302 }
50d0de67 1303 else if (IsCommand(_T("FLAGS"), szBuffer, 1))
5039dede 1304 {
c8076b19 1305 ConsolePrintf(pCtx, _T("Flags: 0x") UINT64X_FMT(_T("016")) _T("\n"), g_flags);
5039dede
AK
1306 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DAEMON));
1307 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_USE_SYSLOG));
1308 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_NETWORK_DISCOVERY));
1309 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ACTIVE_NETWORK_DISCOVERY));
1310 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_LOG_SQL_ERRORS));
1311 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DELETE_EMPTY_SUBNETS));
1312 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_SNMP_TRAPD));
1313 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_ZONING));
5039dede 1314 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SYNC_NODE_NAMES_WITH_DNS));
cbc777ee 1315 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_CHECK_TRUSTED_NODES));
549f48b3
VK
1316 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_NXSL_CONTAINER_FUNCS));
1317 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_USE_FQDN_FOR_NODE_NAMES));
1318 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_APPLY_TO_DISABLED_DCI_FROM_TEMPLATE));
1319 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DEBUG_CONSOLE_DISABLED));
1320 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_OBJECT_TRANSACTIONS));
cbc777ee
VK
1321 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_WRITE_FULL_DUMP));
1322 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_RESOLVE_NODE_NAMES));
5039dede 1323 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_CATCH_EXCEPTIONS));
d41268ba 1324 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_HELPDESK_LINK_ACTIVE));
5039dede 1325 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_LOCKED));
cbc777ee 1326 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_ENABLE_MULTIPLE_DB_CONN));
5039dede 1327 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_DB_CONNECTION_LOST));
cbc777ee 1328 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_NO_NETWORK_CONNECTIVITY));
5039dede 1329 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_EVENT_STORM_DETECTED));
e02953a4 1330 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SNMP_TRAP_DISCOVERY));
c8076b19 1331 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_TRAPS_FROM_UNMANAGED_NODES));
ea50bc33
VK
1332 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_RESOLVE_IP_FOR_EACH_STATUS_POLL));
1333 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_PERFDATA_STORAGE_DRIVER_LOADED));
5039dede
AK
1334 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SERVER_INITIALIZED));
1335 ConsolePrintf(pCtx, SHOW_FLAG_VALUE(AF_SHUTDOWN));
35f836fe 1336 ConsolePrintf(pCtx, _T("\n"));
5039dede 1337 }
35f836fe 1338 else if (IsCommand(_T("INDEX"), szBuffer, 1))
5039dede
AK
1339 {
1340 // Get argument
1341 pArg = ExtractWord(pArg, szBuffer);
1342
35f836fe 1343 if (IsCommand(_T("CONDITION"), szBuffer, 1))
5039dede 1344 {
d5e19c61 1345 DumpIndex(pCtx, &g_idxConditionById, false);
5039dede 1346 }
35f836fe 1347 else if (IsCommand(_T("ID"), szBuffer, 2))
5039dede 1348 {
d5e19c61 1349 DumpIndex(pCtx, &g_idxObjectById, false);
5039dede 1350 }
35f836fe 1351 else if (IsCommand(_T("INTERFACE"), szBuffer, 2))
5039dede 1352 {
d5e19c61 1353 DumpIndex(pCtx, &g_idxInterfaceByAddr, true);
6aba3998 1354 }
16d6f798
VK
1355 else if (IsCommand(_T("NODEADDR"), szBuffer, 5))
1356 {
1357 DumpIndex(pCtx, &g_idxNodeByAddr, true);
1358 }
1359 else if (IsCommand(_T("NODEID"), szBuffer, 5))
6aba3998 1360 {
d5e19c61 1361 DumpIndex(pCtx, &g_idxNodeById, false);
5039dede 1362 }
35f836fe 1363 else if (IsCommand(_T("SUBNET"), szBuffer, 1))
5039dede 1364 {
d5e19c61 1365 DumpIndex(pCtx, &g_idxSubnetByAddr, true);
5039dede 1366 }
16d6f798
VK
1367 else if (IsCommand(_T("ZONE"), szBuffer, 1))
1368 {
1369 DumpIndex(pCtx, &g_idxZoneByGUID, true);
1370 }
5039dede
AK
1371 else
1372 {
1373 if (szBuffer[0] == 0)
35f836fe 1374 ConsolePrintf(pCtx, _T("ERROR: Missing index name\n")
16d6f798 1375 _T("Valid names are: CONDITION, ID, INTERFACE, NODEADDR, NODEID, SUBNET, ZONE\n\n"));
5039dede 1376 else
35f836fe 1377 ConsolePrintf(pCtx, _T("ERROR: Invalid index name\n\n"));
5039dede
AK
1378 }
1379 }
35f836fe 1380 else if (IsCommand(_T("MEMORY"), szBuffer, 2))
5039dede
AK
1381 {
1382#ifdef NETXMS_MEMORY_DEBUG
1383 PrintMemoryBlocks();
1384#else
35f836fe 1385 ConsolePrintf(pCtx, _T("ERROR: Server was compiled without memory debugger\n\n"));
5039dede
AK
1386#endif
1387 }
35f836fe 1388 else if (IsCommand(_T("OBJECTS"), szBuffer, 1))
5039dede
AK
1389 {
1390 DumpObjects(pCtx);
1391 }
35f836fe 1392 else if (IsCommand(_T("POLLERS"), szBuffer, 1))
5039dede
AK
1393 {
1394 ShowPollerState(pCtx);
1395 }
35f836fe 1396 else if (IsCommand(_T("QUEUES"), szBuffer, 1))
5039dede 1397 {
35f836fe
VK
1398 ShowQueueStats(pCtx, &g_conditionPollerQueue, _T("Condition poller"));
1399 ShowQueueStats(pCtx, &g_configPollQueue, _T("Configuration poller"));
040c45fa 1400 ShowQueueStats(pCtx, &g_topologyPollQueue, _T("Topology poller"));
d140955e
VK
1401 ShowQueueStats(pCtx, &g_dataCollectionQueue, _T("Data collector"));
1402 ShowQueueStats(pCtx, &g_dciCacheLoaderQueue, _T("DCI cache loader"));
76fcb995
VK
1403 ShowQueueStats(pCtx, g_dbWriterQueue, _T("Database writer"));
1404 ShowQueueStats(pCtx, g_dciDataWriterQueue, _T("Database writer (IData)"));
1405 ShowQueueStats(pCtx, g_dciRawDataWriterQueue, _T("Database writer (raw DCI values)"));
35f836fe
VK
1406 ShowQueueStats(pCtx, g_pEventQueue, _T("Event processor"));
1407 ShowQueueStats(pCtx, &g_discoveryPollQueue, _T("Network discovery poller"));
1408 ShowQueueStats(pCtx, &g_nodePollerQueue, _T("Node poller"));
1409 ShowQueueStats(pCtx, &g_routePollQueue, _T("Routing table poller"));
1410 ShowQueueStats(pCtx, &g_statusPollQueue, _T("Status poller"));
f1784ab6
VK
1411 ShowQueueStats(pCtx, &g_syslogProcessingQueue, _T("Syslog processing"));
1412 ShowQueueStats(pCtx, &g_syslogWriteQueue, _T("Syslog writer"));
35f836fe 1413 ConsolePrintf(pCtx, _T("\n"));
5039dede 1414 }
35f836fe 1415 else if (IsCommand(_T("ROUTING-TABLE"), szBuffer, 1))
5039dede 1416 {
967893bb 1417 UINT32 dwNode;
5039dede
AK
1418 NetObj *pObject;
1419
1420 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1421 dwNode = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1422 if (dwNode != 0)
1423 {
1424 pObject = FindObjectById(dwNode);
1425 if (pObject != NULL)
1426 {
c42b4551 1427 if (pObject->getObjectClass() == OBJECT_NODE)
5039dede
AK
1428 {
1429 ROUTING_TABLE *pRT;
35f836fe 1430 TCHAR szIpAddr[16];
5039dede
AK
1431 int i;
1432
c42b4551 1433 ConsolePrintf(pCtx, _T("Routing table for node %s:\n\n"), pObject->getName());
58b3e451 1434 pRT = ((Node *)pObject)->getCachedRoutingTable();
5039dede
AK
1435 if (pRT != NULL)
1436 {
1437 for(i = 0; i < pRT->iNumEntries; i++)
1438 {
35f836fe
VK
1439 _sntprintf(szBuffer, 256, _T("%s/%d"), IpToStr(pRT->pRoutes[i].dwDestAddr, szIpAddr),
1440 BitsInMask(pRT->pRoutes[i].dwDestMask));
1441 ConsolePrintf(pCtx, _T("%-18s %-15s %-6d %d\n"), szBuffer,
1442 IpToStr(pRT->pRoutes[i].dwNextHop, szIpAddr),
1443 pRT->pRoutes[i].dwIfIndex, pRT->pRoutes[i].dwRouteType);
5039dede 1444 }
35f836fe 1445 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1446 }
1447 else
1448 {
35f836fe 1449 ConsolePrintf(pCtx, _T("Node doesn't have cached routing table\n\n"));
5039dede
AK
1450 }
1451 }
1452 else
1453 {
35f836fe 1454 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
5039dede
AK
1455 }
1456 }
1457 else
1458 {
35f836fe 1459 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode);
5039dede
AK
1460 }
1461 }
1462 else
1463 {
35f836fe 1464 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node ID\n\n"));
5039dede
AK
1465 }
1466 }
35f836fe 1467 else if (IsCommand(_T("SESSIONS"), szBuffer, 2))
5039dede 1468 {
534e1b83
VK
1469 ConsolePrintf(pCtx, _T("\x1b[1mCLIENT SESSIONS\x1b[0m\n============================================================\n"));
1470 DumpClientSessions(pCtx);
1471 ConsolePrintf(pCtx, _T("\n\x1b[1mMOBILE DEVICE SESSIONS\x1b[0m\n============================================================\n"));
1472 DumpMobileDeviceSessions(pCtx);
5039dede 1473 }
35f836fe 1474 else if (IsCommand(_T("STATS"), szBuffer, 2))
5039dede
AK
1475 {
1476 ShowServerStats(pCtx);
1477 }
b833cbf5
VK
1478 else if (IsCommand(_T("TOPOLOGY"), szBuffer, 1))
1479 {
1480 pArg = ExtractWord(pArg, szBuffer);
1481 UINT32 nodeId = _tcstoul(szBuffer, NULL, 0);
1482 if (nodeId != 0)
1483 {
1484 Node *node = (Node *)FindObjectById(nodeId, OBJECT_NODE);
1485 if (node != NULL)
1486 {
1487 LinkLayerNeighbors *nbs = BuildLinkLayerNeighborList(node);
1488 if (nbs != NULL)
1489 {
1490 ConsolePrintf(pCtx, _T("Proto | PtP | ifLocal | ifRemote | Peer\n")
1491 _T("--------+-----+---------+----------+------------------------------------\n"));
1492 for(int i = 0; i < nbs->size(); i++)
1493 {
1494 LL_NEIGHBOR_INFO *ni = nbs->getConnection(i);
1495 TCHAR peer[256];
1496 if (ni->objectId != 0)
1497 {
1498 NetObj *object = FindObjectById(ni->objectId);
1499 if (object != NULL)
c42b4551 1500 _sntprintf(peer, 256, _T("%s [%d]"), object->getName(), ni->objectId);
b833cbf5
VK
1501 else
1502 _sntprintf(peer, 256, _T("[%d]"), ni->objectId);
1503 }
1504 else
1505 {
1506 peer[0] = 0;
1507 }
1508 ConsolePrintf(pCtx, _T("%-7s | %c | %7d | %7d | %s\n"),
1509 GetLinkLayerProtocolName(ni->protocol), ni->isPtToPt ? _T('Y') : _T('N'), ni->ifLocal, ni->ifRemote, peer);
1510 }
1511 nbs->decRefCount();
1512 }
1513 else
1514 {
1515 ConsolePrintf(pCtx, _T("ERROR: call to BuildLinkLayerNeighborList failed\n\n"));
1516 }
1517 }
1518 else
1519 {
1520 ConsolePrintf(pCtx, _T("ERROR: Node with ID %d does not exist\n\n"), nodeId);
1521 }
1522 }
1523 else
1524 {
1525 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node ID\n\n"));
1526 }
1527 }
35f836fe 1528 else if (IsCommand(_T("USERS"), szBuffer, 1))
5039dede
AK
1529 {
1530 DumpUsers(pCtx);
1531 }
b0ff1179
VK
1532 else if (IsCommand(_T("VLANS"), szBuffer, 1))
1533 {
967893bb 1534 UINT32 dwNode;
b0ff1179
VK
1535 NetObj *pObject;
1536
1537 pArg = ExtractWord(pArg, szBuffer);
1538 dwNode = _tcstoul(szBuffer, NULL, 0);
1539 if (dwNode != 0)
1540 {
1541 pObject = FindObjectById(dwNode);
1542 if (pObject != NULL)
1543 {
c42b4551 1544 if (pObject->getObjectClass() == OBJECT_NODE)
b0ff1179
VK
1545 {
1546 VlanList *vlans = ((Node *)pObject)->getVlans();
1547 if (vlans != NULL)
1548 {
1549 ConsolePrintf(pCtx, _T("\x1b[1mVLAN\x1b[0m | \x1b[1mName\x1b[0m | \x1b[1mPorts\x1b[0m\n")
1550 _T("-----+------------------+-----------------------------------------------------------------\n"));
a6312bd6 1551 for(int i = 0; i < vlans->size(); i++)
b0ff1179
VK
1552 {
1553 VlanInfo *vlan = vlans->get(i);
1554 ConsolePrintf(pCtx, _T("%4d | %-16s |"), vlan->getVlanId(), vlan->getName());
1555 for(int j = 0; j < vlan->getNumPorts(); j++)
1556 ConsolePrintf(pCtx, _T(" %d.%d"), (int)(vlan->getPorts()[j] >> 16), (int)(vlan->getPorts()[j] & 0xFFFF));
1557 ConsolePrintf(pCtx, _T("\n"));
1558 }
1559 ConsolePrintf(pCtx, _T("\n"));
1560 vlans->decRefCount();
1561 }
1562 else
1563 {
1564 ConsolePrintf(pCtx, _T("\x1b[31mNode doesn't have VLAN information\x1b[0m\n\n"));
1565 }
1566 }
1567 else
1568 {
1569 ConsolePrintf(pCtx, _T("\x1b[31mERROR: Object is not a node\x1b[0m\n\n"));
1570 }
1571 }
1572 else
1573 {
1574 ConsolePrintf(pCtx, _T("\x1b[31mERROR: Object with ID %d does not exist\x1b[0m\n\n"), dwNode);
1575 }
1576 }
1577 else
1578 {
1579 ConsolePrintf(pCtx, _T("\x1b[31mERROR: Invalid or missing node ID\x1b[0m\n\n"));
1580 }
1581 }
35f836fe 1582 else if (IsCommand(_T("WATCHDOG"), szBuffer, 1))
5039dede
AK
1583 {
1584 WatchdogPrintStatus(pCtx);
35f836fe 1585 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1586 }
1587 else
1588 {
1589 if (szBuffer[0] == 0)
35f836fe 1590 ConsolePrintf(pCtx, _T("ERROR: Missing subcommand\n\n"));
5039dede 1591 else
35f836fe 1592 ConsolePrintf(pCtx, _T("ERROR: Invalid SHOW subcommand\n\n"));
5039dede
AK
1593 }
1594 }
06a8857b
AK
1595 else if (IsCommand(_T("EXEC"), szBuffer, 3))
1596 {
1597 pArg = ExtractWord(pArg, szBuffer);
35104062 1598
e323047c 1599 bool libraryLocked = true;
6b29839d 1600 bool destroyCompiledScript = false;
e323047c
VK
1601 g_pScriptLibrary->lock();
1602
35104062
VK
1603 NXSL_Program *compiledScript = g_pScriptLibrary->findScript(szBuffer);
1604 if (compiledScript == NULL)
06a8857b 1605 {
e323047c
VK
1606 g_pScriptLibrary->unlock();
1607 libraryLocked = false;
6b29839d 1608 destroyCompiledScript = true;
35104062 1609 char *script;
967893bb 1610 UINT32 fileSize;
35104062 1611 if ((script = (char *)LoadFile(szBuffer, &fileSize)) != NULL)
06a8857b 1612 {
35104062
VK
1613 const int errorMsgLen = 512;
1614 TCHAR errorMsg[errorMsgLen];
1615#ifdef UNICODE
1616 WCHAR *wscript = WideStringFromMBString(script);
1617 compiledScript = NXSLCompile(wscript, errorMsg, errorMsgLen);
1618 free(wscript);
1619#else
1620 compiledScript = NXSLCompile(script, errorMsg, errorMsgLen);
1621#endif
1622 free(script);
1623 if (compiledScript == NULL)
06a8857b 1624 {
35104062 1625 ConsolePrintf(pCtx, _T("ERROR: Script compilation error: %s\n\n"), errorMsg);
06a8857b
AK
1626 }
1627 }
1628 else
1629 {
35104062 1630 ConsolePrintf(pCtx, _T("ERROR: Script \"%s\" not found\n\n"), szBuffer);
06a8857b
AK
1631 }
1632 }
35104062
VK
1633
1634 if (compiledScript != NULL)
06a8857b 1635 {
35104062 1636 NXSL_ServerEnv *pEnv = new NXSL_ServerEnv;
2773ef30 1637 pEnv->setConsole(pCtx);
35104062 1638
6b29839d
VK
1639 NXSL_VM *vm = new NXSL_VM(pEnv);
1640 if (vm->load(compiledScript))
d9177dd1 1641 {
6b29839d
VK
1642 if (libraryLocked)
1643 {
1644 g_pScriptLibrary->unlock();
1645 libraryLocked = false;
1646 }
1647
1648 NXSL_Value *argv[32];
1649 int argc = 0;
1650 while(argc < 32)
1651 {
1652 pArg = ExtractWord(pArg, szBuffer);
1653 if (szBuffer[0] == 0)
1654 break;
1655 argv[argc++] = new NXSL_Value(szBuffer);
1656 }
1657
1658 if (vm->run(argc, argv))
1659 {
1660 NXSL_Value *pValue = vm->getResult();
1661 int retCode = pValue->getValueAsInt32();
1662 ConsolePrintf(pCtx, _T("INFO: Script finished with rc=%d\n\n"), retCode);
1663 }
1664 else
1665 {
1666 ConsolePrintf(pCtx, _T("ERROR: Script finished with error: %s\n\n"), vm->getErrorText());
1667 }
1668 }
1669 else
1670 {
1671 ConsolePrintf(pCtx, _T("ERROR: VM creation failed: %s\n\n"), vm->getErrorText());
1672 }
1673 delete vm;
1674 if (destroyCompiledScript)
1675 delete compiledScript;
06a8857b 1676 }
e323047c
VK
1677 if (libraryLocked)
1678 g_pScriptLibrary->unlock();
06a8857b 1679 }
35f836fe 1680 else if (IsCommand(_T("TRACE"), szBuffer, 1))
5039dede 1681 {
967893bb 1682 UINT32 dwNode1, dwNode2;
5039dede 1683 NetObj *pObject1, *pObject2;
6d069676 1684 NetworkPath *pTrace;
35f836fe 1685 TCHAR szNextHop[16];
5039dede
AK
1686 int i;
1687
1688 // Get arguments
1689 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1690 dwNode1 = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1691
1692 pArg = ExtractWord(pArg, szBuffer);
35f836fe 1693 dwNode2 = _tcstoul(szBuffer, NULL, 0);
5039dede
AK
1694
1695 if ((dwNode1 != 0) && (dwNode2 != 0))
1696 {
1697 pObject1 = FindObjectById(dwNode1);
1698 if (pObject1 == NULL)
1699 {
35f836fe 1700 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode1);
5039dede
AK
1701 }
1702 else
1703 {
1704 pObject2 = FindObjectById(dwNode2);
1705 if (pObject2 == NULL)
1706 {
35f836fe 1707 ConsolePrintf(pCtx, _T("ERROR: Object with ID %d does not exist\n\n"), dwNode2);
5039dede
AK
1708 }
1709 else
1710 {
c42b4551 1711 if ((pObject1->getObjectClass() == OBJECT_NODE) && (pObject2->getObjectClass() == OBJECT_NODE))
5039dede
AK
1712 {
1713 pTrace = TraceRoute((Node *)pObject1, (Node *)pObject2);
1714 if (pTrace != NULL)
1715 {
99c11466
VK
1716 TCHAR sourceIp[32];
1717 ConsolePrintf(pCtx, _T("Trace from %s to %s (%d hops, %s, source IP %s):\n"),
c42b4551 1718 pObject1->getName(), pObject2->getName(), pTrace->getHopCount(),
99c11466
VK
1719 pTrace->isComplete() ? _T("complete") : _T("incomplete"),
1720 IpToStr(pTrace->getSourceAddress(), sourceIp));
1721 for(i = 0; i < pTrace->getHopCount(); i++)
6d069676
VK
1722 {
1723 HOP_INFO *hop = pTrace->getHopInfo(i);
35f836fe 1724 ConsolePrintf(pCtx, _T("[%d] %s %s %s %d\n"),
c42b4551
VK
1725 hop->object->getId(),
1726 hop->object->getName(),
6d069676
VK
1727 IpToStr(hop->nextHop, szNextHop),
1728 hop->isVpn ? _T("VPN Connector ID:") : _T("Interface Index: "),
1729 hop->ifIndex);
1730 }
1731 delete pTrace;
35f836fe 1732 ConsolePrintf(pCtx, _T("\n"));
5039dede
AK
1733 }
1734 else
1735 {
35f836fe 1736 ConsolePrintf(pCtx, _T("ERROR: Call to TraceRoute() failed\n\n"));
5039dede
AK
1737 }
1738 }
1739 else
1740 {
35f836fe 1741 ConsolePrintf(pCtx, _T("ERROR: Object is not a node\n\n"));
5039dede
AK
1742 }
1743 }
1744 }
1745 }
1746 else
1747 {
35f836fe 1748 ConsolePrintf(pCtx, _T("ERROR: Invalid or missing node id(s)\n\n"));
5039dede
AK
1749 }
1750 }
d9177dd1 1751 else if (IsCommand(_T("LDAPSYNC"), szBuffer, 4))
1752 {
1753 LDAPConnection conn;
1754 conn.syncUsers();
1755 }
35f836fe 1756 else if (IsCommand(_T("HELP"), szBuffer, 2) || IsCommand(_T("?"), szBuffer, 1))
5039dede 1757 {
35f836fe 1758 ConsolePrintf(pCtx, _T("Valid commands are:\n")
48c0079d 1759 _T(" debug [<level>|off] - Set debug level (valid range is 0..9)\n")
48a3497b
VK
1760 _T(" down - Shutdown NetXMS server\n")
1761 _T(" exec <script> [<params>] - Executes NXSL script from script library\n")
35f836fe 1762 _T(" exit - Exit from remote session\n")
5d9a9c84 1763 _T(" kill <session> - Kill client session\n")
206e268e 1764 _T(" get <variable> - Get value of server configuration variable\n")
35f836fe 1765 _T(" help - Display this help\n")
d9177dd1 1766 _T(" ldapsync - Synchronize ldap users with local user database\n")
35f836fe 1767 _T(" raise <exception> - Raise exception\n")
206e268e 1768 _T(" set <variable> <value> - Set value of server configuration variable\n")
50d0de67 1769 _T(" show components <node> - Show physical components of given node\n")
9c133761 1770 _T(" show dbcp - Show active sessions in database connection pool\n")
48a3497b 1771 _T(" show fdb <node> - Show forwarding database for node\n")
35f836fe
VK
1772 _T(" show flags - Show internal server flags\n")
1773 _T(" show index <index> - Show internal index\n")
35f836fe
VK
1774 _T(" show objects - Dump network objects to screen\n")
1775 _T(" show pollers - Show poller threads state information\n")
1776 _T(" show queues - Show internal queues statistics\n")
1777 _T(" show routing-table <node> - Show cached routing table for node\n")
1778 _T(" show sessions - Show active client sessions\n")
1779 _T(" show stats - Show server statistics\n")
b833cbf5 1780 _T(" show topology <node> - Collect and show link layer topology for node\n")
35f836fe 1781 _T(" show users - Show users\n")
b0ff1179 1782 _T(" show vlans <node> - Show cached VLAN information for node\n")
35f836fe
VK
1783 _T(" show watchdog - Display watchdog information\n")
1784 _T(" trace <node1> <node2> - Show network path trace between two nodes\n")
1785 _T("\nAlmost all commands can be abbreviated to 2 or 3 characters\n")
1786 _T("\n"));
5039dede 1787 }
d9177dd1 1788 else
5039dede 1789 {
35f836fe 1790 ConsolePrintf(pCtx, _T("UNKNOWN COMMAND\n\n"));
5039dede
AK
1791 }
1792
1793 return nExitCode;
1794}
1795
fdbee7f8
VK
1796/**
1797 * Signal handler for UNIX platforms
1798 */
5039dede
AK
1799#ifndef _WIN32
1800
1801void SignalHandlerStub(int nSignal)
1802{
1803 // should be unused, but JIC...
1804 if (nSignal == SIGCHLD)
1805 {
1806 while (waitpid(-1, NULL, WNOHANG) > 0)
1807 ;
1808 }
1809}
1810
1811THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL SignalHandler(void *pArg)
1812{
1813 sigset_t signals;
1814 int nSignal;
1815 BOOL bCallShutdown = FALSE;
1816
1817 m_signalHandlerThread = pthread_self();
1818
1819 // default for SIGCHLD: ignore
1820 signal(SIGCHLD, &SignalHandlerStub);
1821
1822 sigemptyset(&signals);
1823 sigaddset(&signals, SIGTERM);
1824 sigaddset(&signals, SIGINT);
5039dede
AK
1825 sigaddset(&signals, SIGSEGV);
1826 sigaddset(&signals, SIGCHLD);
1827 sigaddset(&signals, SIGHUP);
1828 sigaddset(&signals, SIGUSR1);
1829 sigaddset(&signals, SIGUSR2);
95e2329a
VK
1830#if !defined(__sun) && !defined(_AIX) && !defined(__hpux)
1831 sigaddset(&signals, SIGPIPE);
1832#endif
5039dede
AK
1833
1834 sigprocmask(SIG_BLOCK, &signals, NULL);
1835
1836 while(1)
1837 {
1838 if (sigwait(&signals, &nSignal) == 0)
1839 {
1840 switch(nSignal)
1841 {
1842 case SIGTERM:
1843 case SIGINT:
1844 m_nShutdownReason = SHUTDOWN_BY_SIGNAL;
1845 if (IsStandalone())
1846 bCallShutdown = TRUE;
1847 ConditionSet(m_condShutdown);
1848 goto stop_handler;
1849 case SIGSEGV:
1850 abort();
1851 break;
1852 case SIGCHLD:
1853 while (waitpid(-1, NULL, WNOHANG) > 0)
1854 ;
1855 break;
1856 case SIGUSR1:
c8076b19 1857 if (g_flags & AF_SHUTDOWN)
5039dede
AK
1858 goto stop_handler;
1859 break;
1860 default:
1861 break;
1862 }
1863 }
1864 else
1865 {
1866 ThreadSleepMs(100);
1867 }
1868 }
1869
1870stop_handler:
1871 sigprocmask(SIG_UNBLOCK, &signals, NULL);
1872 if (bCallShutdown)
1873 Shutdown();
1874 return THREAD_OK;
1875}
1876
1877#endif
1878
fdbee7f8
VK
1879/**
1880 * Common main()
1881 */
5039dede
AK
1882THREAD_RESULT NXCORE_EXPORTABLE THREAD_CALL Main(void *pArg)
1883{
1884 nxlog_write(MSG_SERVER_STARTED, EVENTLOG_INFORMATION_TYPE, NULL);
1885
7bdb43c3
VK
1886 if (IsStandalone())
1887 {
c8076b19 1888 if (!(g_flags & AF_DEBUG_CONSOLE_DISABLED))
7bdb43c3
VK
1889 {
1890 char *ptr, szCommand[256];
1891 struct __console_ctx ctx;
35f836fe 1892#ifdef UNICODE
7bdb43c3 1893 WCHAR wcCommand[256];
35f836fe 1894#endif
5039dede 1895
7bdb43c3
VK
1896 ctx.hSocket = -1;
1897 ctx.socketMutex = INVALID_MUTEX_HANDLE;
1898 ctx.pMsg = NULL;
1899 ctx.session = NULL;
1900 ctx.output = NULL;
8e17001f 1901 WriteToTerminal(_T("\nNetXMS Server V") NETXMS_VERSION_STRING _T(" Build ") NETXMS_VERSION_BUILD_STRING IS_UNICODE_BUILD_STRING _T(" Ready\n")
7bdb43c3
VK
1902 _T("Enter \"\x1b[1mhelp\x1b[0m\" for command list or \"\x1b[1mdown\x1b[0m\" for server shutdown\n")
1903 _T("System Console\n\n"));
5039dede
AK
1904
1905#if USE_READLINE
7bdb43c3
VK
1906 // Initialize readline library if we use it
1907 rl_bind_key('\t', RL_INSERT_CAST rl_insert);
5039dede
AK
1908#endif
1909
7bdb43c3
VK
1910 while(1)
1911 {
5039dede 1912#if USE_READLINE
7bdb43c3 1913 ptr = readline("\x1b[33mnetxmsd:\x1b[0m ");
5039dede 1914#else
7bdb43c3
VK
1915 WriteToTerminal(_T("\x1b[33mnetxmsd:\x1b[0m "));
1916 fflush(stdout);
1917 if (fgets(szCommand, 255, stdin) == NULL)
1918 break; // Error reading stdin
1919 ptr = strchr(szCommand, '\n');
1920 if (ptr != NULL)
1921 *ptr = 0;
1922 ptr = szCommand;
5039dede
AK
1923#endif
1924
7bdb43c3
VK
1925 if (ptr != NULL)
1926 {
35f836fe 1927#ifdef UNICODE
7bdb43c3
VK
1928 MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, ptr, -1, wcCommand, 256);
1929 wcCommand[255] = 0;
1930 StrStrip(wcCommand);
1931 if (wcCommand[0] != 0)
1932 {
1933 if (ProcessConsoleCommand(wcCommand, &ctx) == CMD_EXIT_SHUTDOWN)
35f836fe 1934#else
7bdb43c3
VK
1935 StrStrip(ptr);
1936 if (*ptr != 0)
1937 {
1938 if (ProcessConsoleCommand(ptr, &ctx) == CMD_EXIT_SHUTDOWN)
35f836fe 1939#endif
7bdb43c3 1940 break;
5039dede 1941#if USE_READLINE
7bdb43c3 1942 add_history(ptr);
5039dede 1943#endif
7bdb43c3 1944 }
5039dede 1945#if USE_READLINE
7bdb43c3 1946 free(ptr);
5039dede 1947#endif
7bdb43c3
VK
1948 }
1949 else
1950 {
1951 _tprintf(_T("\n"));
1952 }
1953 }
5039dede
AK
1954
1955#if USE_READLINE
7bdb43c3 1956 free(ptr);
5039dede 1957#endif
7bdb43c3
VK
1958 m_nShutdownReason = SHUTDOWN_FROM_CONSOLE;
1959 Shutdown();
1960 }
1961 else
1962 {
1963 // standalone with debug console disabled
1964#ifdef _WIN32
1965 _tprintf(_T("Server running. Press ESC to shutdown.\n"));
1966 while(1)
1967 {
1968 if (_getch() == 27)
1969 break;
1970 }
1971 _tprintf(_T("Server shutting down...\n"));
1972 Shutdown();
1973#else
1974 _tprintf(_T("Server running. Press Ctrl+C to shutdown.\n"));
1975 // Shutdown will be called from signal handler
1976 ConditionWait(m_condShutdown, INFINITE);
1977#endif
1978 }
5039dede
AK
1979 }
1980 else
1981 {
1982 ConditionWait(m_condShutdown, INFINITE);
1983 // On Win32, Shutdown() will be called by service control handler
1984#ifndef _WIN32
1985 Shutdown();
1986#endif
1987 }
1988 return THREAD_OK;
1989}
1990
fdbee7f8
VK
1991/**
1992 * Initiate server shutdown
1993 */
035a4d73 1994void InitiateShutdown()
5039dede
AK
1995{
1996#ifdef _WIN32
1997 Shutdown();
1998#else
1999 if (IsStandalone())
2000 {
2001 Shutdown();
2002 }
2003 else
2004 {
2005 pthread_kill(m_signalHandlerThread, SIGTERM);
2006 }
2007#endif
2008}
2009
fdbee7f8
VK
2010/**
2011 *DLL Entry point
2012 */
5039dede
AK
2013#ifdef _WIN32
2014
2015BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
2016{
2017 if (dwReason == DLL_PROCESS_ATTACH)
2018 DisableThreadLibraryCalls(hInstance);
2019 return TRUE;
2020}
2021
2022#endif