all pollers converted to single thread pool
[public/netxms.git] / src / server / core / node.cpp
1 /*
2 ** NetXMS - Network Management System
3 ** Copyright (C) 2003-2015 Victor Kirhenshtein
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: node.cpp
20 **
21 **/
22
23 #include "nxcore.h"
24
25 /**
26 * Node class default constructor
27 */
28 Node::Node() : DataCollectionTarget()
29 {
30 m_primaryName[0] = 0;
31 m_iStatus = STATUS_UNKNOWN;
32 m_dwFlags = 0;
33 m_dwDynamicFlags = 0;
34 m_zoneId = 0;
35 m_agentPort = AGENT_LISTEN_PORT;
36 m_agentAuthMethod = AUTH_NONE;
37 m_agentCacheMode = AGENT_CACHE_DEFAULT;
38 m_szSharedSecret[0] = 0;
39 m_iStatusPollType = POLL_ICMP_PING;
40 m_snmpVersion = SNMP_VERSION_1;
41 m_snmpPort = SNMP_DEFAULT_PORT;
42 char community[MAX_COMMUNITY_LENGTH];
43 ConfigReadStrA(_T("DefaultCommunityString"), community, MAX_COMMUNITY_LENGTH, "public");
44 m_snmpSecurity = new SNMP_SecurityContext(community);
45 m_szObjectId[0] = 0;
46 m_lastDiscoveryPoll = 0;
47 m_lastStatusPoll = 0;
48 m_lastConfigurationPoll = 0;
49 m_lastInstancePoll = 0;
50 m_lastTopologyPoll = 0;
51 m_lastRTUpdate = 0;
52 m_downSince = 0;
53 m_bootTime = 0;
54 m_agentUpTime = 0;
55 m_hPollerMutex = MutexCreate();
56 m_hAgentAccessMutex = MutexCreate();
57 m_hSmclpAccessMutex = MutexCreate();
58 m_mutexRTAccess = MutexCreate();
59 m_mutexTopoAccess = MutexCreate();
60 m_pAgentConnection = NULL;
61 m_smclpConnection = NULL;
62 m_lastAgentTrapId = 0;
63 m_lastSNMPTrapId = 0;
64 m_lastAgentPushRequestId = 0;
65 m_szAgentVersion[0] = 0;
66 m_szPlatformName[0] = 0;
67 m_sysDescription = NULL;
68 m_sysName = NULL;
69 m_lldpNodeId = NULL;
70 m_lldpLocalPortInfo = NULL;
71 m_paramList = NULL;
72 m_tableList = NULL;
73 m_pollerNode = 0;
74 m_agentProxy = 0;
75 m_snmpProxy = 0;
76 m_icmpProxy = 0;
77 memset(m_qwLastEvents, 0, sizeof(QWORD) * MAX_LAST_EVENTS);
78 m_pRoutingTable = NULL;
79 m_failTimeSNMP = 0;
80 m_failTimeAgent = 0;
81 m_linkLayerNeighbors = NULL;
82 m_vrrpInfo = NULL;
83 m_pTopology = NULL;
84 m_topologyRebuildTimestamp = 0;
85 m_iPendingStatus = -1;
86 m_iPollCount = 0;
87 m_iRequiredPollCount = 0; // Use system default
88 m_nUseIfXTable = IFXTABLE_DEFAULT; // Use system default
89 m_jobQueue = new ServerJobQueue();
90 m_fdb = NULL;
91 m_vlans = NULL;
92 m_wirelessStations = NULL;
93 m_adoptedApCount = 0;
94 m_totalApCount = 0;
95 m_driver = NULL;
96 m_driverData = NULL;
97 m_components = NULL;
98 m_softwarePackages = NULL;
99 m_winPerfObjects = NULL;
100 memset(m_baseBridgeAddress, 0, MAC_ADDR_LENGTH);
101 }
102
103 /**
104 * Constructor for new node object
105 */
106 Node::Node(const InetAddress& addr, UINT32 dwFlags, UINT32 agentProxy, UINT32 snmpProxy, UINT32 dwZone) : DataCollectionTarget()
107 {
108 addr.toString(m_primaryName);
109 m_iStatus = STATUS_UNKNOWN;
110 m_ipAddress = addr;
111 m_dwFlags = dwFlags;
112 m_dwDynamicFlags = 0;
113 m_zoneId = dwZone;
114 m_agentPort = AGENT_LISTEN_PORT;
115 m_agentAuthMethod = AUTH_NONE;
116 m_agentCacheMode = AGENT_CACHE_DEFAULT;
117 m_szSharedSecret[0] = 0;
118 m_iStatusPollType = POLL_ICMP_PING;
119 m_snmpVersion = SNMP_VERSION_1;
120 m_snmpPort = SNMP_DEFAULT_PORT;
121 char community[MAX_COMMUNITY_LENGTH];
122 ConfigReadStrA(_T("DefaultCommunityString"), community, MAX_COMMUNITY_LENGTH, "public");
123 m_snmpSecurity = new SNMP_SecurityContext(community);
124 addr.toString(m_name); // Make default name from IP address
125 m_szObjectId[0] = 0;
126 m_lastDiscoveryPoll = 0;
127 m_lastStatusPoll = 0;
128 m_lastConfigurationPoll = 0;
129 m_lastInstancePoll = 0;
130 m_lastTopologyPoll = 0;
131 m_lastRTUpdate = 0;
132 m_downSince = 0;
133 m_bootTime = 0;
134 m_agentUpTime = 0;
135 m_hPollerMutex = MutexCreate();
136 m_hAgentAccessMutex = MutexCreate();
137 m_hSmclpAccessMutex = MutexCreate();
138 m_mutexRTAccess = MutexCreate();
139 m_mutexTopoAccess = MutexCreate();
140 m_pAgentConnection = NULL;
141 m_smclpConnection = NULL;
142 m_lastAgentTrapId = 0;
143 m_lastSNMPTrapId = 0;
144 m_lastAgentPushRequestId = 0;
145 m_szAgentVersion[0] = 0;
146 m_szPlatformName[0] = 0;
147 m_sysDescription = NULL;
148 m_sysName = NULL;
149 m_lldpNodeId = NULL;
150 m_lldpLocalPortInfo = NULL;
151 m_paramList = NULL;
152 m_tableList = NULL;
153 m_pollerNode = 0;
154 m_agentProxy = agentProxy;
155 m_snmpProxy = snmpProxy;
156 m_icmpProxy = 0;
157 memset(m_qwLastEvents, 0, sizeof(QWORD) * MAX_LAST_EVENTS);
158 m_isHidden = true;
159 m_pRoutingTable = NULL;
160 m_failTimeSNMP = 0;
161 m_failTimeAgent = 0;
162 m_linkLayerNeighbors = NULL;
163 m_vrrpInfo = NULL;
164 m_pTopology = NULL;
165 m_topologyRebuildTimestamp = 0;
166 m_iPendingStatus = -1;
167 m_iPollCount = 0;
168 m_iRequiredPollCount = 0; // Use system default
169 m_nUseIfXTable = IFXTABLE_DEFAULT; // Use system default
170 m_jobQueue = new ServerJobQueue();
171 m_fdb = NULL;
172 m_vlans = NULL;
173 m_wirelessStations = NULL;
174 m_adoptedApCount = 0;
175 m_totalApCount = 0;
176 m_driver = NULL;
177 m_driverData = NULL;
178 m_components = NULL;
179 m_softwarePackages = NULL;
180 m_winPerfObjects = NULL;
181 memset(m_baseBridgeAddress, 0, MAC_ADDR_LENGTH);
182 }
183
184 /**
185 * Node destructor
186 */
187 Node::~Node()
188 {
189 delete m_driverData;
190 MutexDestroy(m_hPollerMutex);
191 MutexDestroy(m_hAgentAccessMutex);
192 MutexDestroy(m_hSmclpAccessMutex);
193 MutexDestroy(m_mutexRTAccess);
194 MutexDestroy(m_mutexTopoAccess);
195 delete m_pAgentConnection;
196 delete m_smclpConnection;
197 delete m_paramList;
198 delete m_tableList;
199 safe_free(m_sysDescription);
200 DestroyRoutingTable(m_pRoutingTable);
201 if (m_linkLayerNeighbors != NULL)
202 m_linkLayerNeighbors->decRefCount();
203 delete m_vrrpInfo;
204 delete m_pTopology;
205 delete m_jobQueue;
206 delete m_snmpSecurity;
207 if (m_fdb != NULL)
208 m_fdb->decRefCount();
209 if (m_vlans != NULL)
210 m_vlans->decRefCount();
211 delete m_wirelessStations;
212 if (m_components != NULL)
213 m_components->decRefCount();
214 delete m_lldpLocalPortInfo;
215 delete m_softwarePackages;
216 delete m_winPerfObjects;
217 safe_free(m_sysName);
218 }
219
220 /**
221 * Create object from database data
222 */
223 BOOL Node::loadFromDatabase(UINT32 dwId)
224 {
225 int i, iNumRows;
226 UINT32 dwSubnetId;
227 NetObj *pObject;
228 BOOL bResult = FALSE;
229
230 m_id = dwId;
231
232 if (!loadCommonProperties())
233 {
234 DbgPrintf(2, _T("Cannot load common properties for node object %d"), dwId);
235 return FALSE;
236 }
237
238 DB_STATEMENT hStmt = DBPrepare(g_hCoreDB,
239 _T("SELECT primary_name,primary_ip,node_flags,")
240 _T("snmp_version,auth_method,secret,")
241 _T("agent_port,status_poll_type,snmp_oid,agent_version,")
242 _T("platform_name,poller_node_id,zone_guid,")
243 _T("proxy_node,snmp_proxy,required_polls,uname,")
244 _T("use_ifxtable,snmp_port,community,usm_auth_password,")
245 _T("usm_priv_password,usm_methods,snmp_sys_name,bridge_base_addr,")
246 _T("runtime_flags,down_since,boot_time,driver_name,icmp_proxy,")
247 _T("agent_cache_mode FROM nodes WHERE id=?"));
248 if (hStmt == NULL)
249 return FALSE;
250
251 DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, dwId);
252 DB_RESULT hResult = DBSelectPrepared(hStmt);
253 if (hResult == NULL)
254 {
255 DBFreeStatement(hStmt);
256 return FALSE; // Query failed
257 }
258
259 if (DBGetNumRows(hResult) == 0)
260 {
261 DBFreeResult(hResult);
262 DBFreeStatement(hStmt);
263 DbgPrintf(2, _T("Missing record in \"nodes\" table for node object %d"), dwId);
264 return FALSE;
265 }
266
267 DBGetField(hResult, 0, 0, m_primaryName, MAX_DNS_NAME);
268 m_ipAddress = DBGetFieldInetAddr(hResult, 0, 1);
269 m_dwFlags = DBGetFieldULong(hResult, 0, 2);
270 m_snmpVersion = DBGetFieldLong(hResult, 0, 3);
271 m_agentAuthMethod = (WORD)DBGetFieldLong(hResult, 0, 4);
272 DBGetField(hResult, 0, 5, m_szSharedSecret, MAX_SECRET_LENGTH);
273 m_agentPort = (WORD)DBGetFieldLong(hResult, 0, 6);
274 m_iStatusPollType = DBGetFieldLong(hResult, 0, 7);
275 DBGetField(hResult, 0, 8, m_szObjectId, MAX_OID_LEN * 4);
276 DBGetField(hResult, 0, 9, m_szAgentVersion, MAX_AGENT_VERSION_LEN);
277 DBGetField(hResult, 0, 10, m_szPlatformName, MAX_PLATFORM_NAME_LEN);
278 m_pollerNode = DBGetFieldULong(hResult, 0, 11);
279 m_zoneId = DBGetFieldULong(hResult, 0, 12);
280 m_agentProxy = DBGetFieldULong(hResult, 0, 13);
281 m_snmpProxy = DBGetFieldULong(hResult, 0, 14);
282 m_iRequiredPollCount = DBGetFieldLong(hResult, 0, 15);
283 m_sysDescription = DBGetField(hResult, 0, 16, NULL, 0);
284 m_nUseIfXTable = (BYTE)DBGetFieldLong(hResult, 0, 17);
285 m_snmpPort = (WORD)DBGetFieldLong(hResult, 0, 18);
286
287 // SNMP authentication parameters
288 char snmpAuthObject[256], snmpAuthPassword[256], snmpPrivPassword[256];
289 DBGetFieldA(hResult, 0, 19, snmpAuthObject, 256);
290 DBGetFieldA(hResult, 0, 20, snmpAuthPassword, 256);
291 DBGetFieldA(hResult, 0, 21, snmpPrivPassword, 256);
292 int snmpMethods = DBGetFieldLong(hResult, 0, 22);
293 delete m_snmpSecurity;
294 m_snmpSecurity = new SNMP_SecurityContext(snmpAuthObject, snmpAuthPassword, snmpPrivPassword, snmpMethods & 0xFF, snmpMethods >> 8);
295 m_snmpSecurity->setSecurityModel((m_snmpVersion == SNMP_VERSION_3) ? SNMP_SECURITY_MODEL_USM : SNMP_SECURITY_MODEL_V2C);
296
297 m_sysName = DBGetField(hResult, 0, 23, NULL, 0);
298
299 TCHAR baseAddr[16];
300 TCHAR *value = DBGetField(hResult, 0, 24, baseAddr, 16);
301 if (value != NULL)
302 StrToBin(value, m_baseBridgeAddress, MAC_ADDR_LENGTH);
303
304 m_dwDynamicFlags = DBGetFieldULong(hResult, 0, 25);
305 m_dwDynamicFlags &= NDF_PERSISTENT; // Clear out all non-persistent runtime flags
306
307 m_downSince = DBGetFieldLong(hResult, 0, 26);
308 m_bootTime = DBGetFieldLong(hResult, 0, 27);
309
310 // Setup driver
311 TCHAR driverName[34];
312 DBGetField(hResult, 0, 28, driverName, 34);
313 StrStrip(driverName);
314 if (driverName[0] != 0)
315 m_driver = FindDriverByName(driverName);
316
317 m_icmpProxy = DBGetFieldULong(hResult, 0, 29);
318 m_agentCacheMode = (INT16)DBGetFieldLong(hResult, 0, 30);
319 if ((m_agentCacheMode != AGENT_CACHE_ON) && (m_agentCacheMode != AGENT_CACHE_OFF))
320 m_agentCacheMode = AGENT_CACHE_DEFAULT;
321
322 DBFreeResult(hResult);
323 DBFreeStatement(hStmt);
324
325 if (!m_isDeleted)
326 {
327 // Link node to subnets
328 hStmt = DBPrepare(g_hCoreDB, _T("SELECT subnet_id FROM nsmap WHERE node_id=?"));
329 if (hStmt == NULL)
330 return FALSE;
331
332 DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_id);
333 hResult = DBSelectPrepared(hStmt);
334 if (hResult == NULL)
335 {
336 DBFreeStatement(hStmt);
337 return FALSE; // Query failed
338 }
339
340 iNumRows = DBGetNumRows(hResult);
341 for(i = 0; i < iNumRows; i++)
342 {
343 dwSubnetId = DBGetFieldULong(hResult, i, 0);
344 pObject = FindObjectById(dwSubnetId);
345 if (pObject == NULL)
346 {
347 nxlog_write(MSG_INVALID_SUBNET_ID, EVENTLOG_ERROR_TYPE, "dd", dwId, dwSubnetId);
348 break;
349 }
350 else if (pObject->getObjectClass() != OBJECT_SUBNET)
351 {
352 nxlog_write(MSG_SUBNET_NOT_SUBNET, EVENTLOG_ERROR_TYPE, "dd", dwId, dwSubnetId);
353 break;
354 }
355 else
356 {
357 pObject->AddChild(this);
358 AddParent(pObject);
359 }
360 }
361
362 DBFreeResult(hResult);
363 DBFreeStatement(hStmt);
364
365 loadItemsFromDB();
366 loadACLFromDB();
367
368 // Walk through all items in the node and load appropriate thresholds
369 bResult = TRUE;
370 for(i = 0; i < m_dcObjects->size(); i++)
371 if (!m_dcObjects->get(i)->loadThresholdsFromDB())
372 {
373 DbgPrintf(3, _T("Cannot load thresholds for DCI %d of node %d (%s)"),
374 m_dcObjects->get(i)->getId(), dwId, m_name);
375 bResult = FALSE;
376 }
377 }
378 else
379 {
380 bResult = TRUE;
381 }
382
383 return bResult;
384 }
385
386 /**
387 * Save object to database
388 */
389 BOOL Node::saveToDatabase(DB_HANDLE hdb)
390 {
391 // Lock object's access
392 lockProperties();
393
394 if (!saveCommonProperties(hdb))
395 {
396 unlockProperties();
397 return FALSE;
398 }
399
400 // Form and execute INSERT or UPDATE query
401 int snmpMethods = m_snmpSecurity->getAuthMethod() | (m_snmpSecurity->getPrivMethod() << 8);
402 DB_STATEMENT hStmt;
403 if (IsDatabaseRecordExist(hdb, _T("nodes"), _T("id"), m_id))
404 {
405 hStmt = DBPrepare(hdb,
406 _T("UPDATE nodes SET primary_ip=?,primary_name=?,snmp_port=?,node_flags=?,snmp_version=?,community=?,")
407 _T("status_poll_type=?,agent_port=?,auth_method=?,secret=?,snmp_oid=?,uname=?,agent_version=?,")
408 _T("platform_name=?,poller_node_id=?,zone_guid=?,proxy_node=?,snmp_proxy=?,icmp_proxy=?,required_polls=?,")
409 _T("use_ifxtable=?,usm_auth_password=?,usm_priv_password=?,usm_methods=?,snmp_sys_name=?,bridge_base_addr=?,")
410 _T("runtime_flags=?,down_since=?,driver_name=?,rack_image=?,rack_position=?,rack_id=?,boot_time=?,")
411 _T("agent_cache_mode=? WHERE id=?"));
412 }
413 else
414 {
415 hStmt = DBPrepare(hdb,
416 _T("INSERT INTO nodes (primary_ip,primary_name,snmp_port,node_flags,snmp_version,community,status_poll_type,")
417 _T("agent_port,auth_method,secret,snmp_oid,uname,agent_version,platform_name,poller_node_id,zone_guid,")
418 _T("proxy_node,snmp_proxy,icmp_proxy,required_polls,use_ifxtable,usm_auth_password,usm_priv_password,usm_methods,")
419 _T("snmp_sys_name,bridge_base_addr,runtime_flags,down_since,driver_name,rack_image,rack_position,rack_id,boot_time,")
420 _T("agent_cache_mode,id) ")
421 _T("VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"));
422 }
423 if (hStmt == NULL)
424 {
425 unlockProperties();
426 return FALSE;
427 }
428
429 TCHAR ipAddr[64], baseAddress[16], cacheMode[16];
430
431 DBBind(hStmt, 1, DB_SQLTYPE_VARCHAR, m_ipAddress.toString(ipAddr), DB_BIND_STATIC);
432 DBBind(hStmt, 2, DB_SQLTYPE_VARCHAR, m_primaryName, DB_BIND_STATIC);
433 DBBind(hStmt, 3, DB_SQLTYPE_INTEGER, (LONG)m_snmpPort);
434 DBBind(hStmt, 4, DB_SQLTYPE_INTEGER, m_dwFlags);
435 DBBind(hStmt, 5, DB_SQLTYPE_INTEGER, (LONG)m_snmpVersion);
436 #ifdef UNICODE
437 DBBind(hStmt, 6, DB_SQLTYPE_VARCHAR, WideStringFromMBString(m_snmpSecurity->getCommunity()), DB_BIND_DYNAMIC);
438 #else
439 DBBind(hStmt, 6, DB_SQLTYPE_VARCHAR, m_snmpSecurity->getCommunity(), DB_BIND_STATIC);
440 #endif
441 DBBind(hStmt, 7, DB_SQLTYPE_INTEGER, (LONG)m_iStatusPollType);
442 DBBind(hStmt, 8, DB_SQLTYPE_INTEGER, (LONG)m_agentPort);
443 DBBind(hStmt, 9, DB_SQLTYPE_INTEGER, (LONG)m_agentAuthMethod);
444 DBBind(hStmt, 10, DB_SQLTYPE_VARCHAR, m_szSharedSecret, DB_BIND_STATIC);
445 DBBind(hStmt, 11, DB_SQLTYPE_VARCHAR, m_szObjectId, DB_BIND_STATIC);
446 DBBind(hStmt, 12, DB_SQLTYPE_VARCHAR, m_sysDescription, DB_BIND_STATIC);
447 DBBind(hStmt, 13, DB_SQLTYPE_VARCHAR, m_szAgentVersion, DB_BIND_STATIC);
448 DBBind(hStmt, 14, DB_SQLTYPE_VARCHAR, m_szPlatformName, DB_BIND_STATIC);
449 DBBind(hStmt, 15, DB_SQLTYPE_INTEGER, m_pollerNode);
450 DBBind(hStmt, 16, DB_SQLTYPE_INTEGER, m_zoneId);
451 DBBind(hStmt, 17, DB_SQLTYPE_INTEGER, m_agentProxy);
452 DBBind(hStmt, 18, DB_SQLTYPE_INTEGER, m_snmpProxy);
453 DBBind(hStmt, 19, DB_SQLTYPE_INTEGER, m_icmpProxy);
454 DBBind(hStmt, 20, DB_SQLTYPE_INTEGER, (LONG)m_iRequiredPollCount);
455 DBBind(hStmt, 21, DB_SQLTYPE_INTEGER, (LONG)m_nUseIfXTable);
456 #ifdef UNICODE
457 DBBind(hStmt, 22, DB_SQLTYPE_VARCHAR, WideStringFromMBString(m_snmpSecurity->getAuthPassword()), DB_BIND_DYNAMIC);
458 DBBind(hStmt, 23, DB_SQLTYPE_VARCHAR, WideStringFromMBString(m_snmpSecurity->getPrivPassword()), DB_BIND_DYNAMIC);
459 #else
460 DBBind(hStmt, 22, DB_SQLTYPE_VARCHAR, m_snmpSecurity->getAuthPassword(), DB_BIND_STATIC);
461 DBBind(hStmt, 23, DB_SQLTYPE_VARCHAR, m_snmpSecurity->getPrivPassword(), DB_BIND_STATIC);
462 #endif
463 DBBind(hStmt, 24, DB_SQLTYPE_INTEGER, (LONG)snmpMethods);
464 DBBind(hStmt, 25, DB_SQLTYPE_VARCHAR, m_sysName, DB_BIND_STATIC);
465 DBBind(hStmt, 26, DB_SQLTYPE_VARCHAR, BinToStr(m_baseBridgeAddress, MAC_ADDR_LENGTH, baseAddress), DB_BIND_STATIC);
466 DBBind(hStmt, 27, DB_SQLTYPE_INTEGER, m_dwDynamicFlags);
467 DBBind(hStmt, 28, DB_SQLTYPE_INTEGER, (LONG)m_downSince);
468 DBBind(hStmt, 29, DB_SQLTYPE_VARCHAR, (m_driver != NULL) ? m_driver->getName() : _T(""), DB_BIND_STATIC);
469 DBBind(hStmt, 30, DB_SQLTYPE_VARCHAR, _T("00000000-0000-0000-0000-000000000000"), DB_BIND_STATIC); // rack image
470 DBBind(hStmt, 31, DB_SQLTYPE_INTEGER, (LONG)0); // rack position
471 DBBind(hStmt, 32, DB_SQLTYPE_INTEGER, (LONG)0); // rack ID
472 DBBind(hStmt, 33, DB_SQLTYPE_INTEGER, (LONG)m_bootTime); // rack ID
473 DBBind(hStmt, 34, DB_SQLTYPE_VARCHAR, _itot(m_agentCacheMode, cacheMode, 10), DB_BIND_STATIC);
474 DBBind(hStmt, 35, DB_SQLTYPE_INTEGER, m_id);
475
476 BOOL bResult = DBExecute(hStmt);
477 DBFreeStatement(hStmt);
478
479 // Save access list
480 saveACLToDB(hdb);
481
482 unlockProperties();
483
484 // Save data collection items
485 if (bResult)
486 {
487 lockDciAccess(false);
488 for(int i = 0; i < m_dcObjects->size(); i++)
489 m_dcObjects->get(i)->saveToDB(hdb);
490 unlockDciAccess();
491 }
492
493 // Clear modifications flag
494 lockProperties();
495 m_isModified = false;
496 unlockProperties();
497
498 return bResult;
499 }
500
501 /**
502 * Delete object from database
503 */
504 bool Node::deleteFromDatabase(DB_HANDLE hdb)
505 {
506 bool success = DataCollectionTarget::deleteFromDatabase(hdb);
507 if (success)
508 success = executeQueryOnObject(hdb, _T("DELETE FROM nodes WHERE id=?"));
509 if (success)
510 success = executeQueryOnObject(hdb, _T("DELETE FROM nsmap WHERE node_id=?"));
511 return success;
512 }
513
514 /**
515 * Get ARP cache from node
516 */
517 ARP_CACHE *Node::getArpCache()
518 {
519 ARP_CACHE *pArpCache = NULL;
520
521 if (m_dwFlags & NF_IS_LOCAL_MGMT)
522 {
523 pArpCache = GetLocalArpCache();
524 }
525 else if (m_dwFlags & NF_IS_NATIVE_AGENT)
526 {
527 agentLock();
528 if (connectToAgent())
529 pArpCache = m_pAgentConnection->getArpCache();
530 agentUnlock();
531 }
532 else if (m_dwFlags & NF_IS_SNMP)
533 {
534 SNMP_Transport *pTransport;
535
536 pTransport = createSnmpTransport();
537 if (pTransport != NULL)
538 {
539 pArpCache = SnmpGetArpCache(m_snmpVersion, pTransport);
540 delete pTransport;
541 }
542 }
543
544 return pArpCache;
545 }
546
547 /**
548 * Get list of interfaces from node
549 */
550 InterfaceList *Node::getInterfaceList()
551 {
552 InterfaceList *pIfList = NULL;
553
554 if ((m_dwFlags & NF_IS_NATIVE_AGENT) && (!(m_dwFlags & NF_DISABLE_NXCP)))
555 {
556 agentLock();
557 if (connectToAgent())
558 {
559 pIfList = m_pAgentConnection->getInterfaceList();
560 }
561 agentUnlock();
562 }
563 if ((pIfList == NULL) && (m_dwFlags & NF_IS_LOCAL_MGMT))
564 {
565 pIfList = GetLocalInterfaceList();
566 }
567 if ((pIfList == NULL) && (m_dwFlags & NF_IS_SNMP) &&
568 (!(m_dwFlags & NF_DISABLE_SNMP)) && (m_driver != NULL))
569 {
570 SNMP_Transport *pTransport = createSnmpTransport();
571 if (pTransport != NULL)
572 {
573 bool useIfXTable;
574 if (m_nUseIfXTable == IFXTABLE_DEFAULT)
575 {
576 useIfXTable = (ConfigReadInt(_T("UseIfXTable"), 1) != 0) ? true : false;
577 }
578 else
579 {
580 useIfXTable = (m_nUseIfXTable == IFXTABLE_ENABLED) ? true : false;
581 }
582
583 int useAliases = ConfigReadInt(_T("UseInterfaceAliases"), 0);
584 pIfList = m_driver->getInterfaces(pTransport, &m_customAttributes, m_driverData, useAliases, useIfXTable);
585
586 if ((pIfList != NULL) && (m_dwFlags & NF_IS_BRIDGE))
587 {
588 BridgeMapPorts(m_snmpVersion, pTransport, pIfList);
589 }
590 delete pTransport;
591 }
592 }
593
594 if (pIfList != NULL)
595 {
596 checkInterfaceNames(pIfList);
597 addVrrpInterfaces(pIfList);
598 }
599
600 return pIfList;
601 }
602
603 /**
604 * Add VRRP interfaces to interface list
605 */
606 void Node::addVrrpInterfaces(InterfaceList *ifList)
607 {
608 int i, j, k;
609 TCHAR buffer[32];
610
611 lockProperties();
612 if (m_vrrpInfo != NULL)
613 {
614 DbgPrintf(6, _T("Node::addVrrpInterfaces(node=%s [%d]): m_vrrpInfo->size()=%d"), m_name, (int)m_id, m_vrrpInfo->size());
615
616 for(i = 0; i < m_vrrpInfo->size(); i++)
617 {
618 VrrpRouter *router = m_vrrpInfo->getRouter(i);
619 DbgPrintf(6, _T("Node::addVrrpInterfaces(node=%s [%d]): vrouter %d state=%d"), m_name, (int)m_id, i, router->getState());
620 if (router->getState() != VRRP_STATE_MASTER)
621 continue; // Do not add interfaces if router is not in master state
622
623 // Get netmask for this VR
624 int maskBits = 0;
625 for(j = 0; j < ifList->size(); j++)
626 {
627 InterfaceInfo *iface = ifList->get(j);
628 if (iface->index == router->getIfIndex())
629 {
630 for(int k = 0; k < iface->ipAddrList.size(); k++)
631 {
632 const InetAddress& addr = iface->ipAddrList.get(k);
633 if (addr.getSubnetAddress().contain(router->getVip(0)))
634 {
635 maskBits = addr.getMaskBits();
636 }
637 }
638 break;
639 }
640 }
641
642 // Walk through all VR virtual IPs
643 for(j = 0; j < router->getVipCount(); j++)
644 {
645 UINT32 vip = router->getVip(j);
646 DbgPrintf(6, _T("Node::addVrrpInterfaces(node=%s [%d]): checking VIP %s@%d"), m_name, (int)m_id, IpToStr(vip, buffer), i);
647 if (vip != 0)
648 {
649 for(k = 0; k < ifList->size(); k++)
650 if (ifList->get(k)->hasAddress(vip))
651 break;
652 if (k == ifList->size())
653 {
654 InterfaceInfo *iface = new InterfaceInfo(0);
655 _sntprintf(iface->name, MAX_DB_STRING, _T("vrrp.%u.%u.%d"), router->getId(), router->getIfIndex(), j);
656 memcpy(iface->macAddr, router->getVirtualMacAddr(), MAC_ADDR_LENGTH);
657 InetAddress addr(vip);
658 addr.setMaskBits(maskBits);
659 iface->ipAddrList.add(addr);
660 ifList->add(iface);
661 DbgPrintf(6, _T("Node::addVrrpInterfaces(node=%s [%d]): added interface %s"), m_name, (int)m_id, iface->name);
662 }
663 }
664 }
665 }
666 }
667 unlockProperties();
668 }
669
670 /**
671 * Find interface by index and/or IP subnet. Interface IP considered matching
672 * if it is from same IP subnet as hostAddr or if hostAddr set to INADDR_ANY.
673 *
674 * @param ifIndex interface index to match or INVALID_INDEX to select first matching interface
675 * @param hostAddr IP address to match or INADDR_ANY to select first matching interface
676 * @return pointer to interface object or NULL if appropriate interface couldn't be found
677 */
678 Interface *Node::findInterfaceByIndex(UINT32 ifIndex)
679 {
680 UINT32 i;
681 Interface *pInterface;
682
683 LockChildList(FALSE);
684 for(i = 0; i < m_dwChildCount; i++)
685 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
686 {
687 pInterface = (Interface *)m_pChildList[i];
688 if (pInterface->getIfIndex() == ifIndex)
689 {
690 UnlockChildList();
691 return pInterface;
692 }
693 }
694 UnlockChildList();
695 return NULL;
696 }
697
698 /**
699 * Find interface by name or description
700 * Returns pointer to interface object or NULL if appropriate interface couldn't be found
701 */
702 Interface *Node::findInterfaceByName(const TCHAR *name)
703 {
704 UINT32 i;
705 Interface *pInterface;
706
707 LockChildList(FALSE);
708 for(i = 0; i < m_dwChildCount; i++)
709 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
710 {
711 pInterface = (Interface *)m_pChildList[i];
712 if (!_tcsicmp(pInterface->getName(), name) || !_tcsicmp(pInterface->getDescription(), name))
713 {
714 UnlockChildList();
715 return pInterface;
716 }
717 }
718 UnlockChildList();
719 return NULL;
720 }
721
722 /**
723 * Find interface by slot/port pair
724 * Returns pointer to interface object or NULL if appropriate interface couldn't be found
725 */
726 Interface *Node::findInterfaceBySlotAndPort(UINT32 slot, UINT32 port)
727 {
728 UINT32 i;
729 Interface *pInterface;
730
731 LockChildList(FALSE);
732 for(i = 0; i < m_dwChildCount; i++)
733 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
734 {
735 pInterface = (Interface *)m_pChildList[i];
736 if (pInterface->isPhysicalPort() && (pInterface->getSlotNumber() == slot) && (pInterface->getPortNumber() == port))
737 {
738 UnlockChildList();
739 return pInterface;
740 }
741 }
742 UnlockChildList();
743 return NULL;
744 }
745
746 /**
747 * Find interface by MAC address
748 * Returns pointer to interface object or NULL if appropriate interface couldn't be found
749 */
750 Interface *Node::findInterfaceByMAC(const BYTE *macAddr)
751 {
752 Interface *iface = NULL;
753 LockChildList(FALSE);
754 for(UINT32 i = 0; i < m_dwChildCount; i++)
755 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
756 {
757 if (!memcmp(((Interface *)m_pChildList[i])->getMacAddr(), macAddr, MAC_ADDR_LENGTH))
758 {
759 iface = (Interface *)m_pChildList[i];
760 break;
761 }
762 }
763 UnlockChildList();
764 return iface;
765 }
766
767 /**
768 * Find interface by IP address
769 * Returns pointer to interface object or NULL if appropriate interface couldn't be found
770 */
771 Interface *Node::findInterfaceByIP(const InetAddress& addr)
772 {
773 UINT32 i;
774 Interface *pInterface;
775
776 if (!addr.isValid())
777 return NULL;
778
779 LockChildList(FALSE);
780 for(i = 0; i < m_dwChildCount; i++)
781 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
782 {
783 pInterface = (Interface *)m_pChildList[i];
784 if (pInterface->getIpAddressList()->hasAddress(addr))
785 {
786 UnlockChildList();
787 return pInterface;
788 }
789 }
790 UnlockChildList();
791 return NULL;
792 }
793
794 /**
795 * Find interface by bridge port number
796 */
797 Interface *Node::findBridgePort(UINT32 bridgePortNumber)
798 {
799 UINT32 i;
800 Interface *pInterface;
801
802 LockChildList(FALSE);
803 for(i = 0; i < m_dwChildCount; i++)
804 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
805 {
806 pInterface = (Interface *)m_pChildList[i];
807 if (pInterface->getBridgePortNumber() == bridgePortNumber)
808 {
809 UnlockChildList();
810 return pInterface;
811 }
812 }
813 UnlockChildList();
814 return NULL;
815 }
816
817 /**
818 * Find connection point for node
819 */
820 NetObj *Node::findConnectionPoint(UINT32 *localIfId, BYTE *localMacAddr, int *type)
821 {
822 NetObj *cp = NULL;
823 LockChildList(FALSE);
824 for(UINT32 i = 0; i < m_dwChildCount; i++)
825 {
826 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
827 {
828 Interface *iface = (Interface *)m_pChildList[i];
829 cp = FindInterfaceConnectionPoint(iface->getMacAddr(), type);
830 if (cp != NULL)
831 {
832 *localIfId = iface->getId();
833 memcpy(localMacAddr, iface->getMacAddr(), MAC_ADDR_LENGTH);
834 break;
835 }
836 }
837 }
838 UnlockChildList();
839 return cp;
840 }
841
842 /**
843 * Find attached access point by MAC address
844 */
845 AccessPoint *Node::findAccessPointByMAC(const BYTE *macAddr)
846 {
847 AccessPoint *ap = NULL;
848 LockChildList(FALSE);
849 for(UINT32 i = 0; i < m_dwChildCount; i++)
850 if (m_pChildList[i]->getObjectClass() == OBJECT_ACCESSPOINT)
851 {
852 if (!memcmp(((AccessPoint *)m_pChildList[i])->getMacAddr(), macAddr, MAC_ADDR_LENGTH))
853 {
854 ap = (AccessPoint *)m_pChildList[i];
855 break;
856 }
857 }
858 UnlockChildList();
859 return ap;
860 }
861
862 /**
863 * Find access point by radio ID (radio interface index)
864 */
865 AccessPoint *Node::findAccessPointByRadioId(int rfIndex)
866 {
867 AccessPoint *ap = NULL;
868 LockChildList(FALSE);
869 for(UINT32 i = 0; i < m_dwChildCount; i++)
870 if (m_pChildList[i]->getObjectClass() == OBJECT_ACCESSPOINT)
871 {
872 if (((AccessPoint *)m_pChildList[i])->isMyRadio(rfIndex))
873 {
874 ap = (AccessPoint *)m_pChildList[i];
875 break;
876 }
877 }
878 UnlockChildList();
879 return ap;
880 }
881
882 /**
883 * Find attached access point by BSSID
884 */
885 AccessPoint *Node::findAccessPointByBSSID(const BYTE *bssid)
886 {
887 AccessPoint *ap = NULL;
888 LockChildList(FALSE);
889 for(UINT32 i = 0; i < m_dwChildCount; i++)
890 if (m_pChildList[i]->getObjectClass() == OBJECT_ACCESSPOINT)
891 {
892 if (!memcmp(((AccessPoint *)m_pChildList[i])->getMacAddr(), bssid, MAC_ADDR_LENGTH) ||
893 ((AccessPoint *)m_pChildList[i])->isMyRadio(bssid))
894 {
895 ap = (AccessPoint *)m_pChildList[i];
896 break;
897 }
898 }
899 UnlockChildList();
900 return ap;
901 }
902
903 /**
904 * Check if given IP address is one of node's interfaces
905 */
906 bool Node::isMyIP(const InetAddress& addr)
907 {
908 UINT32 i;
909
910 LockChildList(FALSE);
911 for(i = 0; i < m_dwChildCount; i++)
912 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
913 {
914 if (((Interface *)m_pChildList[i])->getIpAddressList()->hasAddress(addr))
915 {
916 UnlockChildList();
917 return true;
918 }
919 }
920 UnlockChildList();
921 return false;
922 }
923
924 /**
925 * Create new interface - convenience wrapper
926 */
927 Interface *Node::createNewInterface(const InetAddress& ipAddr, BYTE *macAddr)
928 {
929 InterfaceInfo info(1);
930 info.ipAddrList.add(ipAddr);
931 if (macAddr != NULL)
932 memcpy(info.macAddr, macAddr, MAC_ADDR_LENGTH);
933 return createNewInterface(&info, false);
934 }
935
936 /**
937 * Create new interface
938 */
939 Interface *Node::createNewInterface(InterfaceInfo *info, bool manuallyCreated)
940 {
941 bool bSyntheticMask = false;
942 TCHAR buffer[64];
943
944 DbgPrintf(5, _T("Node::createNewInterface(\"%s\", %d, %d, bp=%d, slot=%d, port=%d) called for node %s [%d]"),
945 info->name, info->index, info->type, info->bridgePort, info->slot, info->port, m_name, m_id);
946 for(int i = 0; i < info->ipAddrList.size(); i++)
947 {
948 const InetAddress& addr = info->ipAddrList.get(i);
949 DbgPrintf(5, _T("Node::createNewInterface(%s): IP address %s/%d"), info->name, addr.toString(buffer), addr.getMaskBits());
950 }
951
952 // Find subnet to place interface object to
953 if (info->type != IFTYPE_SOFTWARE_LOOPBACK)
954 {
955 Cluster *pCluster = getMyCluster();
956 for(int i = 0; i < info->ipAddrList.size(); i++)
957 {
958 InetAddress addr = info->ipAddrList.get(i);
959 bool addToSubnet = addr.isValidUnicast() && ((pCluster == NULL) || !pCluster->isSyncAddr(addr));
960 DbgPrintf(5, _T("Node::createNewInterface: node=%s [%d] ip=%s/%d cluster=%s [%d] add=%s"),
961 m_name, m_id, addr.toString(buffer), addr.getMaskBits(),
962 (pCluster != NULL) ? pCluster->getName() : _T("(null)"),
963 (pCluster != NULL) ? pCluster->getId() : 0, addToSubnet ? _T("yes") : _T("no"));
964 if (addToSubnet)
965 {
966 Subnet *pSubnet = FindSubnetForNode(m_zoneId, addr);
967 if (pSubnet == NULL)
968 {
969 // Check if netmask is 0 (detect), and if yes, create
970 // new subnet with class mask
971 if (addr.getMaskBits() == 0)
972 {
973 bSyntheticMask = true;
974 addr.setMaskBits((addr.getFamily() == AF_INET) ? 24 : 64);
975 info->ipAddrList.replace(addr);
976 }
977
978 // Create new subnet object
979 if (addr.getHostBits() >= 2)
980 {
981 pSubnet = createSubnet(addr, bSyntheticMask);
982 }
983 }
984 else
985 {
986 // Set correct netmask if we was asked for it
987 if (addr.getMaskBits() == 0)
988 {
989 bSyntheticMask = pSubnet->isSyntheticMask();
990 addr.setMaskBits(pSubnet->getIpAddress().getMaskBits());
991 info->ipAddrList.replace(addr);
992 }
993 }
994 if (pSubnet != NULL)
995 {
996 pSubnet->addNode(this);
997 }
998 } // addToSubnet
999 } // loop by address list
1000 }
1001
1002 // Create interface object
1003 Interface *pInterface;
1004 if (info->name[0] != 0)
1005 pInterface = new Interface(info->name, (info->description[0] != 0) ? info->description : info->name,
1006 info->index, info->ipAddrList, info->type, m_zoneId);
1007 else
1008 pInterface = new Interface(info->ipAddrList, m_zoneId, bSyntheticMask);
1009 pInterface->setMacAddr(info->macAddr);
1010 pInterface->setBridgePortNumber(info->bridgePort);
1011 pInterface->setSlotNumber(info->slot);
1012 pInterface->setPortNumber(info->port);
1013 pInterface->setPhysicalPortFlag(info->isPhysicalPort);
1014 pInterface->setManualCreationFlag(manuallyCreated);
1015 pInterface->setSystemFlag(info->isSystem);
1016 pInterface->setMTU(info->mtu);
1017
1018 // Insert to objects' list and generate event
1019 NetObjInsert(pInterface, TRUE);
1020 addInterface(pInterface);
1021 if (!m_isHidden)
1022 pInterface->unhide();
1023 if (!pInterface->isSystem())
1024 {
1025 const InetAddress& addr = pInterface->getFirstIpAddress();
1026 PostEvent(EVENT_INTERFACE_ADDED, m_id, "dsAdd", pInterface->getId(),
1027 pInterface->getName(), &addr, addr.getMaskBits(), pInterface->getIfIndex());
1028 }
1029
1030 return pInterface;
1031 }
1032
1033 /**
1034 * Delete interface from node
1035 */
1036 void Node::deleteInterface(Interface *iface)
1037 {
1038 DbgPrintf(5, _T("Node::deleteInterface(node=%s [%d], interface=%s [%d])"), m_name, m_id, iface->getName(), iface->getId());
1039
1040 // Check if we should unlink node from interface's subnet
1041 if (!iface->isExcludedFromTopology())
1042 {
1043 const ObjectArray<InetAddress> *list = iface->getIpAddressList()->getList();
1044 for(int i = 0; i < list->size(); i++)
1045 {
1046 bool doUnlink = true;
1047 const InetAddress *addr = list->get(i);
1048
1049 LockChildList(FALSE);
1050 for(UINT32 j = 0; j < m_dwChildCount; j++)
1051 if ((m_pChildList[j]->getObjectClass() == OBJECT_INTERFACE) && (m_pChildList[j] != iface) &&
1052 ((Interface *)m_pChildList[j])->getIpAddressList()->findSameSubnetAddress(*addr).isValid())
1053 {
1054 doUnlink = false;
1055 break;
1056 }
1057 UnlockChildList();
1058
1059 if (doUnlink)
1060 {
1061 // Last interface in subnet, should unlink node
1062 Subnet *pSubnet = FindSubnetByIP(m_zoneId, addr->getSubnetAddress());
1063 if (pSubnet != NULL)
1064 {
1065 DeleteParent(pSubnet);
1066 pSubnet->DeleteChild(this);
1067 }
1068 DbgPrintf(5, _T("Node::deleteInterface(node=%s [%d], interface=%s [%d]): unlinked from subnet %s [%d]"),
1069 m_name, m_id, iface->getName(), iface->getId(),
1070 (pSubnet != NULL) ? pSubnet->getName() : _T("(null)"),
1071 (pSubnet != NULL) ? pSubnet->getId() : 0);
1072 }
1073 }
1074 }
1075 iface->deleteObject();
1076 }
1077
1078 /**
1079 * Calculate node status based on child objects status
1080 */
1081 void Node::calculateCompoundStatus(BOOL bForcedRecalc)
1082 {
1083 int iOldStatus = m_iStatus;
1084 static UINT32 dwEventCodes[] = { EVENT_NODE_NORMAL, EVENT_NODE_WARNING,
1085 EVENT_NODE_MINOR, EVENT_NODE_MAJOR, EVENT_NODE_CRITICAL,
1086 EVENT_NODE_UNKNOWN, EVENT_NODE_UNMANAGED };
1087
1088 DataCollectionTarget::calculateCompoundStatus(bForcedRecalc);
1089 if (m_iStatus != iOldStatus)
1090 PostEvent(dwEventCodes[m_iStatus], m_id, "d", iOldStatus);
1091 }
1092
1093 /**
1094 * Status poller entry point
1095 */
1096 void Node::statusPoll(PollerInfo *poller)
1097 {
1098 poller->startExecution();
1099 statusPoll(NULL, 0, poller);
1100
1101 // Check if the node has to be deleted due to long downtime
1102 time_t unreachableDeleteDays = (time_t)ConfigReadInt(_T("DeleteUnreachableNodesPeriod"), 0);
1103 if ((unreachableDeleteDays > 0) && (m_downSince > 0) &&
1104 (time(NULL) - m_downSince > unreachableDeleteDays * 24 * 3600))
1105 {
1106 deleteObject();
1107 }
1108 delete poller;
1109 }
1110
1111 /**
1112 * Perform status poll on node
1113 */
1114 void Node::statusPoll(ClientSession *pSession, UINT32 dwRqId, PollerInfo *poller)
1115 {
1116 if (m_dwDynamicFlags & NDF_DELETE_IN_PROGRESS)
1117 {
1118 if (dwRqId == 0)
1119 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_STATUS_POLL;
1120 return;
1121 }
1122
1123 UINT32 i, dwPollListSize, dwOldFlags = m_dwFlags;
1124 NetObj *pPollerNode = NULL, **ppPollList;
1125 BOOL bAllDown;
1126 SNMP_Transport *pTransport;
1127 Cluster *pCluster;
1128 time_t tNow, tExpire;
1129
1130 Queue *pQueue = new Queue; // Delayed event queue
1131 poller->setStatus(_T("wait for lock"));
1132 pollerLock();
1133 m_pollRequestor = pSession;
1134 sendPollerMsg(dwRqId, _T("Starting status poll for node %s\r\n"), m_name);
1135 DbgPrintf(5, _T("Starting status poll for node %s (ID: %d)"), m_name, m_id);
1136
1137 // Read capability expiration time and current time
1138 tExpire = (time_t)ConfigReadULong(_T("CapabilityExpirationTime"), 604800);
1139 tNow = time(NULL);
1140
1141 restart_agent_check:
1142 if (g_flags & AF_RESOLVE_IP_FOR_EACH_STATUS_POLL)
1143 {
1144 updatePrimaryIpAddr();
1145 }
1146
1147 // Check SNMP agent connectivity
1148 if ((m_dwFlags & NF_IS_SNMP) && (!(m_dwFlags & NF_DISABLE_SNMP)) && m_ipAddress.isValidUnicast())
1149 {
1150 TCHAR szBuffer[256];
1151 UINT32 dwResult;
1152
1153 DbgPrintf(6, _T("StatusPoll(%s): check SNMP"), m_name);
1154 pTransport = createSnmpTransport();
1155 if (pTransport != NULL)
1156 {
1157 poller->setStatus(_T("check SNMP"));
1158 sendPollerMsg(dwRqId, _T("Checking SNMP agent connectivity\r\n"));
1159 const TCHAR *testOid = m_customAttributes.get(_T("snmp.testoid"));
1160 if (testOid == NULL)
1161 {
1162 testOid = _T(".1.3.6.1.2.1.1.2.0");
1163 }
1164 dwResult = SnmpGet(m_snmpVersion, pTransport, testOid, NULL, 0, szBuffer, sizeof(szBuffer), 0);
1165 if ((dwResult == SNMP_ERR_SUCCESS) || (dwResult == SNMP_ERR_NO_OBJECT))
1166 {
1167 if (m_dwDynamicFlags & NDF_SNMP_UNREACHABLE)
1168 {
1169 m_dwDynamicFlags &= ~NDF_SNMP_UNREACHABLE;
1170 PostEventEx(pQueue, EVENT_SNMP_OK, m_id, NULL);
1171 sendPollerMsg(dwRqId, POLLER_INFO _T("Connectivity with SNMP agent restored\r\n"));
1172 }
1173
1174 // Update authoritative engine data for SNMPv3
1175 if ((pTransport->getSnmpVersion() == SNMP_VERSION_3) && (pTransport->getAuthoritativeEngine() != NULL))
1176 {
1177 lockProperties();
1178 m_snmpSecurity->setAuthoritativeEngine(*pTransport->getAuthoritativeEngine());
1179 unlockProperties();
1180 }
1181 }
1182 else
1183 {
1184 sendPollerMsg(dwRqId, POLLER_ERROR _T("SNMP agent unreachable\r\n"));
1185 if (m_dwDynamicFlags & NDF_SNMP_UNREACHABLE)
1186 {
1187 if ((tNow > m_failTimeSNMP + tExpire) &&
1188 (!(m_dwDynamicFlags & NDF_UNREACHABLE)))
1189 {
1190 m_dwFlags &= ~NF_IS_SNMP;
1191 m_dwDynamicFlags &= ~NDF_SNMP_UNREACHABLE;
1192 m_szObjectId[0] = 0;
1193 sendPollerMsg(dwRqId, POLLER_WARNING _T("Attribute isSNMP set to FALSE\r\n"));
1194 }
1195 }
1196 else
1197 {
1198 m_dwDynamicFlags |= NDF_SNMP_UNREACHABLE;
1199 PostEventEx(pQueue, EVENT_SNMP_FAIL, m_id, NULL);
1200 m_failTimeSNMP = tNow;
1201 }
1202 }
1203 delete pTransport;
1204 }
1205 else
1206 {
1207 DbgPrintf(6, _T("StatusPoll(%s): cannot create SNMP transport"), m_name);
1208 }
1209 DbgPrintf(6, _T("StatusPoll(%s): SNMP check finished"), m_name);
1210 }
1211
1212 // Check native agent connectivity
1213 if ((m_dwFlags & NF_IS_NATIVE_AGENT) && (!(m_dwFlags & NF_DISABLE_NXCP)) && m_ipAddress.isValidUnicast())
1214 {
1215 DbgPrintf(6, _T("StatusPoll(%s): checking agent"), m_name);
1216 poller->setStatus(_T("check agent"));
1217 sendPollerMsg(dwRqId, _T("Checking NetXMS agent connectivity\r\n"));
1218
1219 UINT32 error, socketError;
1220 agentLock();
1221 if (connectToAgent(&error, &socketError))
1222 {
1223 DbgPrintf(7, _T("StatusPoll(%s): connected to agent"), m_name);
1224 if (m_dwDynamicFlags & NDF_AGENT_UNREACHABLE)
1225 {
1226 m_dwDynamicFlags &= ~NDF_AGENT_UNREACHABLE;
1227 PostEventEx(pQueue, EVENT_AGENT_OK, m_id, NULL);
1228 sendPollerMsg(dwRqId, POLLER_INFO _T("Connectivity with NetXMS agent restored\r\n"));
1229 }
1230 }
1231 else
1232 {
1233 DbgPrintf(6, _T("StatusPoll(%s): agent unreachable, error=%d, socketError=%d"), m_name, (int)error, (int)socketError);
1234 sendPollerMsg(dwRqId, POLLER_ERROR _T("NetXMS agent unreachable\r\n"));
1235 if (m_dwDynamicFlags & NDF_AGENT_UNREACHABLE)
1236 {
1237 if ((tNow > m_failTimeAgent + tExpire) && !(m_dwDynamicFlags & NDF_UNREACHABLE))
1238 {
1239 m_dwFlags &= ~NF_IS_NATIVE_AGENT;
1240 m_dwDynamicFlags &= ~NDF_AGENT_UNREACHABLE;
1241 m_szPlatformName[0] = 0;
1242 m_szAgentVersion[0] = 0;
1243 sendPollerMsg(dwRqId, POLLER_WARNING _T("Attribute isNetXMSAgent set to FALSE\r\n"));
1244 }
1245 }
1246 else
1247 {
1248 m_dwDynamicFlags |= NDF_AGENT_UNREACHABLE;
1249 PostEventEx(pQueue, EVENT_AGENT_FAIL, m_id, NULL);
1250 m_failTimeAgent = tNow;
1251 //cancel file monitoring locally(on agent it is canceled if agent have fallen)
1252 g_monitoringList.removeDisconectedNode(m_id);
1253 }
1254 }
1255 agentUnlock();
1256 DbgPrintf(7, _T("StatusPoll(%s): agent check finished"), m_name);
1257 }
1258
1259 poller->setStatus(_T("prepare polling list"));
1260
1261 // Find service poller node object
1262 lockProperties();
1263 if (m_pollerNode != 0)
1264 {
1265 UINT32 id = m_pollerNode;
1266 unlockProperties();
1267 pPollerNode = FindObjectById(id);
1268 if (pPollerNode != NULL)
1269 {
1270 if (pPollerNode->getObjectClass() != OBJECT_NODE)
1271 pPollerNode = NULL;
1272 }
1273 }
1274 else
1275 {
1276 unlockProperties();
1277 }
1278
1279 // If nothing found, use management server
1280 if (pPollerNode == NULL)
1281 {
1282 pPollerNode = FindObjectById(g_dwMgmtNode);
1283 if (pPollerNode != NULL)
1284 pPollerNode->incRefCount();
1285 }
1286 else
1287 {
1288 pPollerNode->incRefCount();
1289 }
1290
1291 // Create polling list
1292 ppPollList = (NetObj **)malloc(sizeof(NetObj *) * m_dwChildCount);
1293 LockChildList(FALSE);
1294 for(i = 0, dwPollListSize = 0; i < m_dwChildCount; i++)
1295 if (m_pChildList[i]->Status() != STATUS_UNMANAGED)
1296 {
1297 m_pChildList[i]->incRefCount();
1298 ppPollList[dwPollListSize++] = m_pChildList[i];
1299 }
1300 UnlockChildList();
1301
1302 // Poll interfaces and services
1303 poller->setStatus(_T("child poll"));
1304 DbgPrintf(7, _T("StatusPoll(%s): starting child object poll"), m_name);
1305 pCluster = getMyCluster();
1306 pTransport = createSnmpTransport();
1307 for(i = 0; i < dwPollListSize; i++)
1308 {
1309 switch(ppPollList[i]->getObjectClass())
1310 {
1311 case OBJECT_INTERFACE:
1312 DbgPrintf(7, _T("StatusPoll(%s): polling interface %d [%s]"), m_name, ppPollList[i]->getId(), ppPollList[i]->getName());
1313 ((Interface *)ppPollList[i])->statusPoll(pSession, dwRqId, pQueue, pCluster, pTransport, m_icmpProxy);
1314 break;
1315 case OBJECT_NETWORKSERVICE:
1316 DbgPrintf(7, _T("StatusPoll(%s): polling network service %d [%s]"), m_name, ppPollList[i]->getId(), ppPollList[i]->getName());
1317 ((NetworkService *)ppPollList[i])->statusPoll(pSession, dwRqId, (Node *)pPollerNode, pQueue);
1318 break;
1319 case OBJECT_ACCESSPOINT:
1320 DbgPrintf(7, _T("StatusPoll(%s): polling access point %d [%s]"), m_name, ppPollList[i]->getId(), ppPollList[i]->getName());
1321 ((AccessPoint *)ppPollList[i])->statusPoll(pSession, dwRqId, pQueue, this, pTransport);
1322 break;
1323 default:
1324 DbgPrintf(7, _T("StatusPoll(%s): skipping object %d [%s] class %d"), m_name, ppPollList[i]->getId(), ppPollList[i]->getName(), ppPollList[i]->getObjectClass());
1325 break;
1326 }
1327 ppPollList[i]->decRefCount();
1328 }
1329 delete pTransport;
1330 safe_free(ppPollList);
1331 DbgPrintf(7, _T("StatusPoll(%s): finished child object poll"), m_name);
1332
1333 // Check if entire node is down
1334 // This check is disabled for nodes without IP address
1335 if (m_ipAddress.isValidUnicast())
1336 {
1337 LockChildList(FALSE);
1338 if (m_dwChildCount > 0)
1339 {
1340 for(i = 0, bAllDown = TRUE; i < m_dwChildCount; i++)
1341 if ((m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE) &&
1342 (m_pChildList[i]->Status() != STATUS_CRITICAL) &&
1343 (m_pChildList[i]->Status() != STATUS_UNKNOWN) &&
1344 (m_pChildList[i]->Status() != STATUS_UNMANAGED) &&
1345 (m_pChildList[i]->Status() != STATUS_DISABLED))
1346 {
1347 bAllDown = FALSE;
1348 break;
1349 }
1350 }
1351 else
1352 {
1353 bAllDown = FALSE;
1354 }
1355 UnlockChildList();
1356 if (bAllDown && (m_dwFlags & NF_IS_NATIVE_AGENT) &&
1357 (!(m_dwFlags & NF_DISABLE_NXCP)))
1358 if (!(m_dwDynamicFlags & NDF_AGENT_UNREACHABLE))
1359 bAllDown = FALSE;
1360 if (bAllDown && (m_dwFlags & NF_IS_SNMP) &&
1361 (!(m_dwFlags & NF_DISABLE_SNMP)))
1362 if (!(m_dwDynamicFlags & NDF_SNMP_UNREACHABLE))
1363 bAllDown = FALSE;
1364
1365 DbgPrintf(6, _T("StatusPoll(%s): bAllDown=%s, dynFlags=0x%08X"), m_name, bAllDown ? _T("true") : _T("false"), m_dwDynamicFlags);
1366 if (bAllDown)
1367 {
1368 if (!(m_dwDynamicFlags & NDF_UNREACHABLE))
1369 {
1370 m_dwDynamicFlags |= NDF_UNREACHABLE;
1371 m_downSince = time(NULL);
1372 poller->setStatus(_T("check network path"));
1373 if (checkNetworkPath(dwRqId))
1374 {
1375 m_dwDynamicFlags |= NDF_NETWORK_PATH_PROBLEM;
1376
1377 // Set interfaces and network services to UNKNOWN state
1378 LockChildList(FALSE);
1379 for(i = 0, bAllDown = TRUE; i < m_dwChildCount; i++)
1380 if (((m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE) || (m_pChildList[i]->getObjectClass() == OBJECT_NETWORKSERVICE)) &&
1381 (m_pChildList[i]->Status() == STATUS_CRITICAL))
1382 {
1383 m_pChildList[i]->resetStatus();
1384 }
1385 UnlockChildList();
1386
1387 // Clear delayed event queue
1388 while(1)
1389 {
1390 Event *pEvent = (Event *)pQueue->get();
1391 if (pEvent == NULL)
1392 break;
1393 delete pEvent;
1394 }
1395 delete_and_null(pQueue);
1396
1397 PostEvent(EVENT_NODE_UNREACHABLE, m_id, NULL);
1398 }
1399 else
1400 {
1401 PostEvent(EVENT_NODE_DOWN, m_id, NULL);
1402 }
1403 sendPollerMsg(dwRqId, POLLER_ERROR _T("Node is unreachable\r\n"));
1404 }
1405 else
1406 {
1407 sendPollerMsg(dwRqId, POLLER_WARNING _T("Node is still unreachable\r\n"));
1408 }
1409 }
1410 else
1411 {
1412 m_downSince = 0;
1413 if (m_dwDynamicFlags & NDF_UNREACHABLE)
1414 {
1415 int reason = (m_dwDynamicFlags & NDF_NETWORK_PATH_PROBLEM) ? 1 : 0;
1416 m_dwDynamicFlags &= ~(NDF_UNREACHABLE | NDF_SNMP_UNREACHABLE | NDF_AGENT_UNREACHABLE | NDF_NETWORK_PATH_PROBLEM);
1417 PostEvent(EVENT_NODE_UP, m_id, "d", reason);
1418 sendPollerMsg(dwRqId, POLLER_INFO _T("Node recovered from unreachable state\r\n"));
1419 goto restart_agent_check;
1420 }
1421 else
1422 {
1423 sendPollerMsg(dwRqId, POLLER_INFO _T("Node is connected\r\n"));
1424 }
1425 }
1426 }
1427
1428 // Get uptime and update boot time
1429 if (!(m_dwDynamicFlags & NDF_UNREACHABLE))
1430 {
1431 TCHAR buffer[MAX_RESULT_LENGTH];
1432 if (getItemFromAgent(_T("System.Uptime"), MAX_RESULT_LENGTH, buffer) == DCE_SUCCESS)
1433 {
1434 m_bootTime = time(NULL) - _tcstol(buffer, NULL, 0);
1435 DbgPrintf(5, _T("StatusPoll(%s [%d]): boot time set to %u from agent"), m_name, m_id, (UINT32)m_bootTime);
1436 }
1437 else if (getItemFromSNMP(m_snmpPort, _T(".1.3.6.1.2.1.1.3.0"), MAX_RESULT_LENGTH, buffer, SNMP_RAWTYPE_NONE) == DCE_SUCCESS)
1438 {
1439 m_bootTime = time(NULL) - _tcstol(buffer, NULL, 0) / 100; // sysUpTime is in hundredths of a second
1440 DbgPrintf(5, _T("StatusPoll(%s [%d]): boot time set to %u from SNMP"), m_name, m_id, (UINT32)m_bootTime);
1441 }
1442 else
1443 {
1444 DbgPrintf(5, _T("StatusPoll(%s [%d]): unable to get system uptime"), m_name, m_id);
1445 }
1446 }
1447 else
1448 {
1449 m_bootTime = 0;
1450 }
1451
1452 // Get agent uptime to check if it was restared
1453 if (!(m_dwDynamicFlags & NDF_UNREACHABLE))
1454 {
1455 TCHAR buffer[MAX_RESULT_LENGTH];
1456 if (getItemFromAgent(_T("Agent.Uptime"), MAX_RESULT_LENGTH, buffer) == DCE_SUCCESS)
1457 {
1458 time_t oldAgentuptime = m_agentUpTime;
1459 m_agentUpTime = _tcstol(buffer, NULL, 0);
1460 if((UINT32)oldAgentuptime > (UINT32)m_agentUpTime)
1461 {
1462 //cancel file monitoring locally(on agent it is canceled if agent have fallen)
1463 g_monitoringList.removeDisconectedNode(m_id);
1464 }
1465 }
1466 else
1467 {
1468 DbgPrintf(5, _T("StatusPoll(%s [%d]): unable to get agent uptime"), m_name, m_id);
1469 g_monitoringList.removeDisconectedNode(m_id);
1470 m_agentUpTime = 0;
1471 }
1472 }
1473 else
1474 {
1475 g_monitoringList.removeDisconectedNode(m_id);
1476 m_agentUpTime = 0;
1477 }
1478
1479 // Send delayed events and destroy delayed event queue
1480 if (pQueue != NULL)
1481 {
1482 ResendEvents(pQueue);
1483 delete pQueue;
1484 }
1485
1486 // Call hooks in loaded modules
1487 for(UINT32 i = 0; i < g_dwNumModules; i++)
1488 {
1489 if (g_pModuleList[i].pfStatusPollHook != NULL)
1490 {
1491 DbgPrintf(5, _T("StatusPoll(%s [%d]): calling hook in module %s"), m_name, m_id, g_pModuleList[i].szName);
1492 g_pModuleList[i].pfStatusPollHook(this, pSession, dwRqId, poller);
1493 }
1494 }
1495
1496 // Execute hook script
1497 poller->setStatus(_T("hook"));
1498 executeHookScript(_T("StatusPoll"));
1499
1500 poller->setStatus(_T("cleanup"));
1501 if (pPollerNode != NULL)
1502 pPollerNode->decRefCount();
1503
1504 if (dwOldFlags != m_dwFlags)
1505 {
1506 PostEvent(EVENT_NODE_FLAGS_CHANGED, m_id, "xx", dwOldFlags, m_dwFlags);
1507 lockProperties();
1508 setModified();
1509 unlockProperties();
1510 }
1511
1512 calculateCompoundStatus();
1513 m_lastStatusPoll = time(NULL);
1514 sendPollerMsg(dwRqId, _T("Finished status poll for node %s\r\n"), m_name);
1515 sendPollerMsg(dwRqId, _T("Node status after poll is %s\r\n"), GetStatusAsText(m_iStatus, true));
1516 m_pollRequestor = NULL;
1517 if (dwRqId == 0)
1518 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_STATUS_POLL;
1519 pollerUnlock();
1520 DbgPrintf(5, _T("Finished status poll for node %s (ID: %d)"), m_name, m_id);
1521 }
1522
1523 /**
1524 * Check single element of network path
1525 */
1526 bool Node::checkNetworkPathElement(UINT32 nodeId, const TCHAR *nodeType, bool isProxy, UINT32 dwRqId)
1527 {
1528 Node *node = (Node *)FindObjectById(nodeId, OBJECT_NODE);
1529 if (node == NULL)
1530 return false;
1531
1532 DbgPrintf(6, _T("Node::checkNetworkPathElement(%s [%d]): found %s: %s [%d]"), m_name, m_id, nodeType, node->getName(), node->getId());
1533 if (node->isDown())
1534 {
1535 DbgPrintf(5, _T("Node::checkNetworkPathElement(%s [%d]): %s %s [%d] is down"),
1536 m_name, m_id, nodeType, node->getName(), node->getId());
1537 sendPollerMsg(dwRqId, POLLER_WARNING _T(" %s %s is down\r\n"), nodeType, node->getName());
1538 return true;
1539 }
1540 if (isProxy && node->isNativeAgent() && (node->getRuntimeFlags() & NDF_AGENT_UNREACHABLE))
1541 {
1542 DbgPrintf(5, _T("Node::checkNetworkPathElement(%s [%d]): agent on %s %s [%d] is down"),
1543 m_name, m_id, nodeType, node->getName(), node->getId());
1544 sendPollerMsg(dwRqId, POLLER_WARNING _T(" Agent on %s %s is down\r\n"), nodeType, node->getName());
1545 return true;
1546 }
1547 if (node->m_lastStatusPoll < time(NULL) - 1)
1548 {
1549 DbgPrintf(6, _T("Node::checkNetworkPathElement(%s [%d]): forced status poll on node %s [%d]"),
1550 m_name, m_id, node->getName(), node->getId());
1551 PollerInfo *poller = RegisterPoller(POLLER_TYPE_STATUS, node);
1552 poller->startExecution();
1553 node->statusPoll(NULL, 0, poller);
1554 delete poller;
1555 if (node->isDown())
1556 {
1557 DbgPrintf(5, _T("Node::checkNetworkPathElement(%s [%d]): %s %s [%d] is down"),
1558 m_name, m_id, nodeType, node->getName(), node->getId());
1559 sendPollerMsg(dwRqId, POLLER_WARNING _T(" %s %s is down\r\n"), nodeType, node->getName());
1560 return true;
1561 }
1562 if (isProxy && node->isNativeAgent() && (node->getRuntimeFlags() & NDF_AGENT_UNREACHABLE))
1563 {
1564 DbgPrintf(5, _T("Node::checkNetworkPathElement(%s [%d]): agent on %s %s [%d] is down"),
1565 m_name, m_id, nodeType, node->getName(), node->getId());
1566 sendPollerMsg(dwRqId, POLLER_WARNING _T(" Agent on %s %s is down\r\n"), nodeType, node->getName());
1567 return true;
1568 }
1569 }
1570 return false;
1571 }
1572
1573 /**
1574 * Check network path between node and management server to detect possible intermediate node failure
1575 *
1576 * @return true if network path problems found
1577 */
1578 bool Node::checkNetworkPath(UINT32 dwRqId)
1579 {
1580 time_t now = time(NULL);
1581
1582 // Check proxy node(s)
1583 if (IsZoningEnabled() && (m_zoneId != 0))
1584 {
1585 Zone *zone = (Zone *)g_idxZoneByGUID.get(m_zoneId);
1586 if ((zone != NULL) && ((zone->getAgentProxy() != 0) || (zone->getSnmpProxy() != 0) || (zone->getIcmpProxy() != 0)))
1587 {
1588 bool allProxyDown = true;
1589 if (zone->getIcmpProxy() != 0)
1590 allProxyDown = checkNetworkPathElement(zone->getIcmpProxy(), _T("ICMP proxy"), true, dwRqId);
1591 if (allProxyDown && (zone->getSnmpProxy() != 0) && (zone->getSnmpProxy() != zone->getIcmpProxy()))
1592 allProxyDown = checkNetworkPathElement(zone->getSnmpProxy(), _T("SNMP proxy"), true, dwRqId);
1593 if (allProxyDown && (zone->getAgentProxy() != 0) && (zone->getAgentProxy() != zone->getIcmpProxy()) && (zone->getAgentProxy() != zone->getSnmpProxy()))
1594 allProxyDown = checkNetworkPathElement(zone->getAgentProxy(), _T("agent proxy"), true, dwRqId);
1595 if (allProxyDown)
1596 return true;
1597 }
1598 }
1599
1600 // Check directly connected switch
1601 sendPollerMsg(dwRqId, _T("Checking ethernet connectivity...\r\n"));
1602 Interface *iface = findInterfaceByIP(m_ipAddress);
1603 if ((iface != NULL) && (iface->getPeerNodeId() != 0))
1604 {
1605 DbgPrintf(6, _T("Node::checkNetworkPath(%s [%d]): found interface object for primary IP: %s [%d]"), m_name, m_id, iface->getName(), iface->getId());
1606 if (checkNetworkPathElement(iface->getPeerNodeId(), _T("upstream switch"), false, dwRqId))
1607 return true;
1608 }
1609 else
1610 {
1611 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): cannot find interface object for primary IP"), m_name, m_id);
1612 }
1613
1614 Node *mgmtNode = (Node *)FindObjectById(g_dwMgmtNode);
1615 if (mgmtNode == NULL)
1616 {
1617 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): cannot find management node"), m_name, m_id);
1618 return false;
1619 }
1620
1621 NetworkPath *trace = TraceRoute(mgmtNode, this);
1622 if (trace == NULL)
1623 {
1624 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): trace not available"), m_name, m_id);
1625 return false;
1626 }
1627 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): trace available, %d hops, %s"),
1628 m_name, m_id, trace->getHopCount(), trace->isComplete() ? _T("complete") : _T("incomplete"));
1629
1630 // We will do path check in two passes
1631 // If unreachable intermediate node will be found on first pass,
1632 // then method will just return true. Otherwise, we will do
1633 // second pass, this time forcing status poll on each node in the path.
1634 sendPollerMsg(dwRqId, _T("Checking network path...\r\n"));
1635 bool secondPass = false;
1636 bool pathProblemFound = false;
1637 restart:
1638 for(int i = 0; i < trace->getHopCount(); i++)
1639 {
1640 HOP_INFO *hop = trace->getHopInfo(i);
1641 if ((hop->object == NULL) || (hop->object == this) || (hop->object->getObjectClass() != OBJECT_NODE))
1642 continue;
1643
1644 DbgPrintf(6, _T("Node::checkNetworkPath(%s [%d]): checking upstream node %s [%d]"),
1645 m_name, m_id, hop->object->getName(), hop->object->getId());
1646 if (secondPass && !((Node *)hop->object)->isDown() && (((Node *)hop->object)->m_lastStatusPoll < now - 1))
1647 {
1648 DbgPrintf(6, _T("Node::checkNetworkPath(%s [%d]): forced status poll on node %s [%d]"),
1649 m_name, m_id, hop->object->getName(), hop->object->getId());
1650 PollerInfo *poller = RegisterPoller(POLLER_TYPE_STATUS, (Node *)hop->object);
1651 poller->startExecution();
1652 ((Node *)hop->object)->statusPoll(NULL, 0, poller);
1653 delete poller;
1654 }
1655
1656 if (((Node *)hop->object)->isDown())
1657 {
1658 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): upstream node %s [%d] is down"),
1659 m_name, m_id, hop->object->getName(), hop->object->getId());
1660 sendPollerMsg(dwRqId, POLLER_WARNING _T(" Upstream node %s is down\r\n"), hop->object->getName());
1661 pathProblemFound = true;
1662 break;
1663 }
1664 }
1665 if (!secondPass && !pathProblemFound)
1666 {
1667 DbgPrintf(5, _T("Node::checkNetworkPath(%s [%d]): will do second pass"), m_name, m_id);
1668 secondPass = true;
1669 goto restart;
1670 }
1671 delete trace;
1672 return pathProblemFound;
1673 }
1674
1675 /**
1676 * Check agent policy binding
1677 * Intended to be called only from configuration poller
1678 */
1679 void Node::checkAgentPolicyBinding(AgentConnection *conn)
1680 {
1681 AgentPolicyInfo *ap;
1682 UINT32 rcc = conn->getPolicyInventory(&ap);
1683 if (rcc == ERR_SUCCESS)
1684 {
1685 // Check for unbound but installed policies
1686 for(int i = 0; i < ap->size(); i++)
1687 {
1688 uuid_t guid;
1689 ap->getGuid(i, guid);
1690 NetObj *object = FindObjectByGUID(guid, -1);
1691 if ((object != NULL) && (!object->isChild(m_id)))
1692 {
1693 object->AddChild(this);
1694 AddParent(object);
1695 DbgPrintf(5, _T("ConfPoll(%s): bound to policy object %s [%d]"), m_name, object->getName(), object->getId());
1696 }
1697 }
1698
1699 // Check for bound but not installed policies
1700 LockParentList(FALSE);
1701 NetObj **unbindList = (NetObj **)malloc(sizeof(NetObj *) * m_dwParentCount);
1702 int unbindListSize = 0;
1703 for(UINT32 i = 0; i < m_dwParentCount; i++)
1704 {
1705 if (IsAgentPolicyObject(m_pParentList[i]))
1706 {
1707 uuid_t guid1, guid2;
1708 int j;
1709
1710 m_pParentList[i]->getGuid(guid1);
1711 for(j = 0; j < ap->size(); j++)
1712 {
1713 ap->getGuid(j, guid2);
1714 if (!uuid_compare(guid1, guid2))
1715 break;
1716 }
1717 if (j == ap->size())
1718 unbindList[unbindListSize++] = m_pParentList[i];
1719 }
1720 }
1721 UnlockParentList();
1722
1723 for(int i = 0; i < unbindListSize; i++)
1724 {
1725 unbindList[i]->DeleteChild(this);
1726 DeleteParent(unbindList[i]);
1727 DbgPrintf(5, _T("ConfPoll(%s): unbound from policy object %s [%d]"), m_name, unbindList[i]->getName(), unbindList[i]->getId());
1728 }
1729 safe_free(unbindList);
1730
1731 delete ap;
1732 }
1733 else
1734 {
1735 DbgPrintf(5, _T("ConfPoll(%s): AgentConnection::getPolicyInventory() failed: rcc=%d"), m_name, rcc);
1736 }
1737 }
1738
1739 /**
1740 * Update primary IP address from primary name
1741 */
1742 void Node::updatePrimaryIpAddr()
1743 {
1744 if (m_primaryName[0] == 0)
1745 return;
1746
1747 InetAddress ipAddr = InetAddress::parse(m_primaryName);
1748 if (!ipAddr.isValid() && (m_zoneId != 0))
1749 {
1750 // resolve address through proxy agent
1751 Zone *zone = FindZoneByGUID(m_zoneId);
1752 if (zone != NULL)
1753 {
1754 Node *proxy = (Node *)FindObjectById(zone->getAgentProxy(), OBJECT_NODE);
1755 if (proxy != NULL)
1756 {
1757 TCHAR query[256], buffer[128];
1758 _sntprintf(query, 256, _T("Net.Resolver.AddressByName(%s)"), m_primaryName);
1759 if (proxy->getItemFromAgent(query, 128, buffer) == ERR_SUCCESS)
1760 {
1761 ipAddr = InetAddress::parse(buffer);
1762 }
1763 }
1764 }
1765 }
1766
1767 // Resolve address through local resolver
1768 if (!ipAddr.isValid())
1769 {
1770 ipAddr = InetAddress::resolveHostName(m_primaryName);
1771 }
1772
1773 if (!ipAddr.equals(m_ipAddress) && (ipAddr.isValidUnicast() || !_tcscmp(m_primaryName, _T("0.0.0.0"))))
1774 {
1775 TCHAR buffer1[64], buffer2[64];
1776
1777 DbgPrintf(4, _T("IP address for node %s [%d] changed from %s to %s"),
1778 m_name, (int)m_id, m_ipAddress.toString(buffer1), ipAddr.toString(buffer2));
1779 PostEvent(EVENT_IP_ADDRESS_CHANGED, m_id, "AA", &ipAddr, &m_ipAddress);
1780
1781 if (m_dwFlags & NF_REMOTE_AGENT)
1782 {
1783 lockProperties();
1784 m_ipAddress = ipAddr;
1785 setModified();
1786 unlockProperties();
1787 }
1788 else
1789 {
1790 setPrimaryIPAddress(ipAddr);
1791 }
1792
1793 agentLock();
1794 delete_and_null(m_pAgentConnection);
1795 agentUnlock();
1796 }
1797 }
1798
1799 /**
1800 * Entry point for configuration poller
1801 */
1802 void Node::configurationPoll(PollerInfo *poller)
1803 {
1804 poller->startExecution();
1805 ObjectTransactionStart();
1806 configurationPoll(NULL, 0, poller, 0);
1807 ObjectTransactionEnd();
1808 delete poller;
1809 }
1810
1811 /**
1812 * Perform configuration poll on node
1813 */
1814 void Node::configurationPoll(ClientSession *pSession, UINT32 dwRqId, PollerInfo *poller, int maskBits)
1815 {
1816 if (m_dwDynamicFlags & NDF_DELETE_IN_PROGRESS)
1817 {
1818 if (dwRqId == 0)
1819 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_CONFIG_POLL;
1820 return;
1821 }
1822
1823 UINT32 dwOldFlags = m_dwFlags;
1824 TCHAR szBuffer[4096];
1825 bool hasChanges = false;
1826
1827 poller->setStatus(_T("wait for lock"));
1828 pollerLock();
1829 m_pollRequestor = pSession;
1830 sendPollerMsg(dwRqId, _T("Starting configuration poll for node %s\r\n"), m_name);
1831 DbgPrintf(4, _T("Starting configuration poll for node %s (ID: %d)"), m_name, m_id);
1832
1833 // Check for forced capabilities recheck
1834 if (m_dwDynamicFlags & NDF_RECHECK_CAPABILITIES)
1835 {
1836 sendPollerMsg(dwRqId, POLLER_WARNING _T("Capability reset\r\n"));
1837 m_dwFlags &= ~(NF_IS_NATIVE_AGENT | NF_IS_SNMP | NF_IS_CPSNMP |
1838 NF_IS_BRIDGE | NF_IS_ROUTER | NF_IS_OSPF | NF_IS_PRINTER |
1839 NF_IS_CDP | NF_IS_LLDP | NF_IS_SONMP | NF_IS_VRRP | NF_HAS_VLANS |
1840 NF_IS_8021X | NF_IS_STP | NF_HAS_ENTITY_MIB | NF_HAS_IFXTABLE |
1841 NF_HAS_WINPDH);
1842 m_dwDynamicFlags &= ~NDF_CONFIGURATION_POLL_PASSED;
1843 m_szObjectId[0] = 0;
1844 m_szPlatformName[0] = 0;
1845 m_szAgentVersion[0] = 0;
1846 safe_free_and_null(m_sysDescription);
1847 safe_free_and_null(m_sysName);
1848 safe_free_and_null(m_lldpNodeId);
1849 }
1850
1851 // Check if node is marked as unreachable
1852 if ((m_dwDynamicFlags & NDF_UNREACHABLE) && !(m_dwDynamicFlags & NDF_RECHECK_CAPABILITIES))
1853 {
1854 sendPollerMsg(dwRqId, POLLER_WARNING _T("Node is marked as unreachable, configuration poll aborted\r\n"));
1855 DbgPrintf(4, _T("Node is marked as unreachable, configuration poll aborted"));
1856 m_lastConfigurationPoll = time(NULL);
1857 }
1858 else
1859 {
1860 updatePrimaryIpAddr();
1861
1862 poller->setStatus(_T("capability check"));
1863 sendPollerMsg(dwRqId, _T("Checking node's capabilities...\r\n"));
1864
1865 if (confPollAgent(dwRqId))
1866 hasChanges = true;
1867 if (confPollSnmp(dwRqId))
1868 hasChanges = true;
1869
1870 // Check for CheckPoint SNMP agent on port 260
1871 if (ConfigReadInt(_T("EnableCheckPointSNMP"), 0))
1872 {
1873 DbgPrintf(5, _T("ConfPoll(%s): checking for CheckPoint SNMP on port 260"), m_name);
1874 if (!((m_dwFlags & NF_IS_CPSNMP) && (m_dwDynamicFlags & NDF_CPSNMP_UNREACHABLE)) && m_ipAddress.isValidUnicast())
1875 {
1876 SNMP_Transport *pTransport = new SNMP_UDPTransport;
1877 ((SNMP_UDPTransport *)pTransport)->createUDPTransport(m_ipAddress, CHECKPOINT_SNMP_PORT);
1878 if (SnmpGet(SNMP_VERSION_1, pTransport,
1879 _T(".1.3.6.1.4.1.2620.1.1.10.0"), NULL, 0, szBuffer, sizeof(szBuffer), 0) == SNMP_ERR_SUCCESS)
1880 {
1881 lockProperties();
1882 m_dwFlags |= NF_IS_CPSNMP | NF_IS_ROUTER;
1883 m_dwDynamicFlags &= ~NDF_CPSNMP_UNREACHABLE;
1884 unlockProperties();
1885 sendPollerMsg(dwRqId, POLLER_INFO _T(" CheckPoint SNMP agent on port 260 is active\r\n"));
1886 }
1887 delete pTransport;
1888 }
1889 }
1890
1891 // Generate event if node flags has been changed
1892 if (dwOldFlags != m_dwFlags)
1893 {
1894 PostEvent(EVENT_NODE_FLAGS_CHANGED, m_id, "xx", dwOldFlags, m_dwFlags);
1895 hasChanges = true;
1896 }
1897
1898 // Retrieve interface list
1899 poller->setStatus(_T("interface check"));
1900 sendPollerMsg(dwRqId, _T("Capability check finished\r\n"));
1901
1902 if (updateInterfaceConfiguration(dwRqId, maskBits))
1903 hasChanges = true;
1904
1905 m_lastConfigurationPoll = time(NULL);
1906
1907 // Check node name
1908 sendPollerMsg(dwRqId, _T("Checking node name\r\n"));
1909 UINT32 dwAddr = ntohl(_t_inet_addr(m_name));
1910 if ((g_flags & AF_RESOLVE_NODE_NAMES) &&
1911 (dwAddr != INADDR_NONE) &&
1912 (dwAddr != INADDR_ANY) &&
1913 isMyIP(dwAddr))
1914 {
1915 sendPollerMsg(dwRqId, _T("Node name is an IP address and need to be resolved\r\n"));
1916 poller->setStatus(_T("resolving name"));
1917 if (resolveName(FALSE))
1918 {
1919 sendPollerMsg(dwRqId, POLLER_INFO _T("Node name resolved to %s\r\n"), m_name);
1920 hasChanges = true;
1921 }
1922 else
1923 {
1924 sendPollerMsg(dwRqId, POLLER_WARNING _T("Node name cannot be resolved\r\n"));
1925 }
1926 }
1927 else
1928 {
1929 if (g_flags & AF_SYNC_NODE_NAMES_WITH_DNS)
1930 {
1931 sendPollerMsg(dwRqId, _T("Syncing node name with DNS\r\n"));
1932 poller->setStatus(_T("resolving name"));
1933 if (resolveName(TRUE))
1934 {
1935 sendPollerMsg(dwRqId, POLLER_INFO _T("Node name resolved to %s\r\n"), m_name);
1936 hasChanges = true;
1937 }
1938 }
1939 else
1940 {
1941 sendPollerMsg(dwRqId, _T("Node name is OK\r\n"));
1942 }
1943 }
1944
1945 applyUserTemplates();
1946 updateContainerMembership();
1947
1948 // Get list of installed products
1949 if (m_dwFlags & NF_IS_NATIVE_AGENT)
1950 {
1951 poller->setStatus(_T("software check"));
1952 sendPollerMsg(dwRqId, _T("Reading list of installed software packages\r\n"));
1953
1954 Table *table;
1955 if (getTableFromAgent(_T("System.InstalledProducts"), &table) == DCE_SUCCESS)
1956 {
1957 lockProperties();
1958 delete m_softwarePackages;
1959 m_softwarePackages = new ObjectArray<SoftwarePackage>(table->getNumRows(), 16, true);
1960 for(int i = 0; i < table->getNumRows(); i++)
1961 m_softwarePackages->add(new SoftwarePackage(table, i));
1962 unlockProperties();
1963 delete table;
1964 sendPollerMsg(dwRqId, POLLER_INFO _T("Got information about %d installed software packages\r\n"), m_softwarePackages->size());
1965 }
1966 else
1967 {
1968 delete_and_null(m_softwarePackages);
1969 sendPollerMsg(dwRqId, POLLER_WARNING _T("Unable to get information about installed software packages\r\n"));
1970 }
1971 }
1972
1973 sendPollerMsg(dwRqId, _T("Finished configuration poll for node %s\r\n"), m_name);
1974 sendPollerMsg(dwRqId, _T("Node configuration was%schanged after poll\r\n"), hasChanges ? _T(" ") : _T(" not "));
1975
1976 // Call hooks in loaded modules
1977 for(UINT32 i = 0; i < g_dwNumModules; i++)
1978 {
1979 if (g_pModuleList[i].pfConfPollHook != NULL)
1980 {
1981 DbgPrintf(5, _T("ConfigurationPoll(%s [%d]): calling hook in module %s"), m_name, m_id, g_pModuleList[i].szName);
1982 if (g_pModuleList[i].pfConfPollHook(this, pSession, dwRqId, poller))
1983 hasChanges = true;
1984 }
1985 }
1986
1987 // Execute hook script
1988 poller->setStatus(_T("hook"));
1989 executeHookScript(_T("ConfigurationPoll"));
1990
1991 m_dwDynamicFlags |= NDF_CONFIGURATION_POLL_PASSED;
1992 }
1993
1994 // Finish configuration poll
1995 poller->setStatus(_T("cleanup"));
1996 if (dwRqId == 0)
1997 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_CONFIG_POLL;
1998 m_dwDynamicFlags &= ~NDF_RECHECK_CAPABILITIES;
1999 pollerUnlock();
2000 DbgPrintf(4, _T("Finished configuration poll for node %s (ID: %d)"), m_name, m_id);
2001
2002 if (hasChanges)
2003 {
2004 lockProperties();
2005 setModified();
2006 unlockProperties();
2007 }
2008 }
2009
2010 /**
2011 * Configuration poll: check for NetXMS agent
2012 */
2013 bool Node::confPollAgent(UINT32 dwRqId)
2014 {
2015 DbgPrintf(5, _T("ConfPoll(%s): checking for NetXMS agent Flags={%08X} DynamicFlags={%08X}"), m_name, m_dwFlags, m_dwDynamicFlags);
2016 if (((m_dwFlags & NF_IS_NATIVE_AGENT) && (m_dwDynamicFlags & NDF_AGENT_UNREACHABLE)) ||
2017 !m_ipAddress.isValidUnicast() || (m_dwFlags & NF_DISABLE_NXCP))
2018 return false;
2019
2020 bool hasChanges = false;
2021
2022 sendPollerMsg(dwRqId, _T(" Checking NetXMS agent...\r\n"));
2023 AgentConnection *pAgentConn = new AgentConnectionEx(m_id, m_ipAddress, m_agentPort, m_agentAuthMethod, m_szSharedSecret);
2024 setAgentProxy(pAgentConn);
2025 DbgPrintf(5, _T("ConfPoll(%s): checking for NetXMS agent - connecting"), m_name);
2026
2027 // Try to connect to agent
2028 UINT32 rcc;
2029 if (!pAgentConn->connect(g_pServerKey, FALSE, &rcc))
2030 {
2031 // If there are authentication problem, try default shared secret
2032 if ((rcc == ERR_AUTH_REQUIRED) || (rcc == ERR_AUTH_FAILED))
2033 {
2034 TCHAR secret[MAX_SECRET_LENGTH];
2035 ConfigReadStr(_T("AgentDefaultSharedSecret"), secret, MAX_SECRET_LENGTH, _T("netxms"));
2036 pAgentConn->setAuthData(AUTH_SHA1_HASH, secret);
2037 if (pAgentConn->connect(g_pServerKey, FALSE, &rcc))
2038 {
2039 m_agentAuthMethod = AUTH_SHA1_HASH;
2040 nx_strncpy(m_szSharedSecret, secret, MAX_SECRET_LENGTH);
2041 DbgPrintf(5, _T("ConfPoll(%s): checking for NetXMS agent - shared secret changed to system default"), m_name);
2042 }
2043 }
2044 }
2045
2046 if (rcc == ERR_SUCCESS)
2047 {
2048 DbgPrintf(5, _T("ConfPoll(%s): checking for NetXMS agent - connected"), m_name);
2049 lockProperties();
2050 m_dwFlags |= NF_IS_NATIVE_AGENT;
2051 if (m_dwDynamicFlags & NDF_AGENT_UNREACHABLE)
2052 {
2053 m_dwDynamicFlags &= ~NDF_AGENT_UNREACHABLE;
2054 PostEvent(EVENT_AGENT_OK, m_id, NULL);
2055 sendPollerMsg(dwRqId, POLLER_INFO _T(" Connectivity with NetXMS agent restored\r\n"));
2056 }
2057 else
2058 {
2059 sendPollerMsg(dwRqId, POLLER_INFO _T(" NetXMS native agent is active\r\n"));
2060 }
2061 unlockProperties();
2062
2063 TCHAR buffer[MAX_RESULT_LENGTH];
2064 if (pAgentConn->getParameter(_T("Agent.Version"), MAX_AGENT_VERSION_LEN, buffer) == ERR_SUCCESS)
2065 {
2066 lockProperties();
2067 if (_tcscmp(m_szAgentVersion, buffer))
2068 {
2069 _tcscpy(m_szAgentVersion, buffer);
2070 hasChanges = true;
2071 sendPollerMsg(dwRqId, _T(" NetXMS agent version changed to %s\r\n"), m_szAgentVersion);
2072 }
2073 unlockProperties();
2074 }
2075
2076 if (pAgentConn->getParameter(_T("System.PlatformName"), MAX_PLATFORM_NAME_LEN, buffer) == ERR_SUCCESS)
2077 {
2078 lockProperties();
2079 if (_tcscmp(m_szPlatformName, buffer))
2080 {
2081 _tcscpy(m_szPlatformName, buffer);
2082 hasChanges = true;
2083 sendPollerMsg(dwRqId, _T(" Platform name changed to %s\r\n"), m_szPlatformName);
2084 }
2085 unlockProperties();
2086 }
2087
2088 // Check IP forwarding status
2089 if (pAgentConn->getParameter(_T("Net.IP.Forwarding"), 16, buffer) == ERR_SUCCESS)
2090 {
2091 if (_tcstoul(buffer, NULL, 10) != 0)
2092 m_dwFlags |= NF_IS_ROUTER;
2093 else
2094 m_dwFlags &= ~NF_IS_ROUTER;
2095 }
2096
2097 // Get uname
2098 if (pAgentConn->getParameter(_T("System.Uname"), MAX_DB_STRING, buffer) == ERR_SUCCESS)
2099 {
2100 TranslateStr(buffer, _T("\r\n"), _T(" "));
2101 TranslateStr(buffer, _T("\n"), _T(" "));
2102 TranslateStr(buffer, _T("\r"), _T(" "));
2103 lockProperties();
2104 if ((m_sysDescription == NULL) || _tcscmp(m_sysDescription, buffer))
2105 {
2106 safe_free(m_sysDescription);
2107 m_sysDescription = _tcsdup(buffer);
2108 hasChanges = true;
2109 sendPollerMsg(dwRqId, _T(" System description changed to %s\r\n"), m_sysDescription);
2110 }
2111 unlockProperties();
2112 }
2113
2114 // Check for 64 bit counter support.
2115 // if Net.Interface.64BitCounters not supported by agent then use
2116 // only presence of 64 bit parameters as indicator
2117 bool netIf64bitCounters = true;
2118 if (pAgentConn->getParameter(_T("Net.Interface.64BitCounters"), MAX_DB_STRING, buffer) == ERR_SUCCESS)
2119 {
2120 netIf64bitCounters = _tcstol(buffer, NULL, 10) ? true : false;
2121 }
2122
2123 ObjectArray<AgentParameterDefinition> *plist;
2124 ObjectArray<AgentTableDefinition> *tlist;
2125 UINT32 rcc = pAgentConn->getSupportedParameters(&plist, &tlist);
2126 if (rcc == ERR_SUCCESS)
2127 {
2128 lockProperties();
2129 delete m_paramList;
2130 delete m_tableList;
2131 m_paramList = plist;
2132 m_tableList = tlist;
2133
2134 // Check for 64-bit interface counters
2135 m_dwFlags &= ~NF_HAS_AGENT_IFXCOUNTERS;
2136 if (netIf64bitCounters)
2137 {
2138 for(int i = 0; i < plist->size(); i++)
2139 {
2140 if (!_tcsicmp(plist->get(i)->getName(), _T("Net.Interface.BytesIn64(*)")))
2141 {
2142 m_dwFlags |= NF_HAS_AGENT_IFXCOUNTERS;
2143 break;
2144 }
2145 }
2146 }
2147
2148 unlockProperties();
2149 }
2150 else
2151 {
2152 DbgPrintf(5, _T("ConfPoll(%s): AgentConnection::getSupportedParameters() failed: rcc=%d"), m_name, rcc);
2153 }
2154
2155 // Get supported Windows Performance Counters
2156 if (!_tcsncmp(m_szPlatformName, _T("windows-"), 8))
2157 {
2158 sendPollerMsg(dwRqId, _T(" Reading list of available Windows Performance Counters...\r\n"));
2159 ObjectArray<WinPerfObject> *perfObjects = WinPerfObject::getWinPerfObjectsFromNode(this, pAgentConn);
2160 lockProperties();
2161 delete m_winPerfObjects;
2162 m_winPerfObjects = perfObjects;
2163 if (m_winPerfObjects != NULL)
2164 {
2165 sendPollerMsg(dwRqId, POLLER_INFO _T(" %d counters read\r\n"), m_winPerfObjects->size());
2166 if (!(m_dwFlags & NF_HAS_WINPDH))
2167 {
2168 m_dwFlags |= NF_HAS_WINPDH;
2169 hasChanges = true;
2170 }
2171 }
2172 else
2173 {
2174 sendPollerMsg(dwRqId, POLLER_ERROR _T(" unable to get Windows Performance Counters list\r\n"));
2175 if (m_dwFlags & NF_HAS_WINPDH)
2176 {
2177 m_dwFlags &= ~NF_HAS_WINPDH;
2178 hasChanges = true;
2179 }
2180 }
2181 unlockProperties();
2182 }
2183
2184 checkAgentPolicyBinding(pAgentConn);
2185
2186 pAgentConn->disconnect();
2187 }
2188 else
2189 {
2190 DbgPrintf(5, _T("ConfPoll(%s): checking for NetXMS agent - failed to connect (error %d)"), m_name, rcc);
2191 }
2192 delete pAgentConn;
2193 DbgPrintf(5, _T("ConfPoll(%s): checking for NetXMS agent - finished"), m_name);
2194 return hasChanges;
2195 }
2196
2197 /**
2198 * SNMP walker callback which just counts number of varbinds
2199 */
2200 static UINT32 CountingSnmpWalkerCallback(UINT32 version, SNMP_Variable *var, SNMP_Transport *transport, void *arg)
2201 {
2202 (*((int *)arg))++;
2203 return SNMP_ERR_SUCCESS;
2204 }
2205
2206 /**
2207 * Configuration poll: check for SNMP
2208 */
2209 bool Node::confPollSnmp(UINT32 dwRqId)
2210 {
2211 if (((m_dwFlags & NF_IS_SNMP) && (m_dwDynamicFlags & NDF_SNMP_UNREACHABLE)) ||
2212 !m_ipAddress.isValidUnicast() || (m_dwFlags & NF_DISABLE_SNMP))
2213 return false;
2214
2215 bool hasChanges = false;
2216
2217 sendPollerMsg(dwRqId, _T(" Checking SNMP...\r\n"));
2218 DbgPrintf(5, _T("ConfPoll(%s): calling SnmpCheckCommSettings()"), m_name);
2219 SNMP_Transport *pTransport = createSnmpTransport();
2220 if (pTransport == NULL)
2221 {
2222 DbgPrintf(5, _T("ConfPoll(%s): unable to create SNMP transport"), m_name);
2223 return false;
2224 }
2225
2226 StringList oids;
2227 const TCHAR *customOid = m_customAttributes.get(_T("snmp.testoid"));
2228 if (customOid != NULL)
2229 oids.add(customOid);
2230 oids.add(_T(".1.3.6.1.2.1.1.2.0"));
2231 oids.add(_T(".1.3.6.1.2.1.1.1.0"));
2232 AddDriverSpecificOids(&oids);
2233 SNMP_SecurityContext *newCtx = SnmpCheckCommSettings(pTransport, &m_snmpVersion, m_snmpSecurity, &oids);
2234 if (newCtx != NULL)
2235 {
2236 lockProperties();
2237 delete m_snmpSecurity;
2238 m_snmpSecurity = newCtx;
2239 m_dwFlags |= NF_IS_SNMP;
2240 if (m_dwDynamicFlags & NDF_SNMP_UNREACHABLE)
2241 {
2242 m_dwDynamicFlags &= ~NDF_SNMP_UNREACHABLE;
2243 PostEvent(EVENT_SNMP_OK, m_id, NULL);
2244 sendPollerMsg(dwRqId, POLLER_INFO _T(" Connectivity with SNMP agent restored\r\n"));
2245 }
2246 unlockProperties();
2247 sendPollerMsg(dwRqId, _T(" SNMP agent is active (version %s)\r\n"),
2248 (m_snmpVersion == SNMP_VERSION_3) ? _T("3") : ((m_snmpVersion == SNMP_VERSION_2C) ? _T("2c") : _T("1")));
2249
2250 TCHAR szBuffer[4096];
2251 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.1.2.0"), NULL, 0, szBuffer, sizeof(szBuffer), SG_STRING_RESULT) != SNMP_ERR_SUCCESS)
2252 {
2253 // Set snmp object ID to .0.0 if it cannot be read
2254 _tcscpy(szBuffer, _T(".0.0"));
2255 }
2256 lockProperties();
2257 if (_tcscmp(m_szObjectId, szBuffer))
2258 {
2259 nx_strncpy(m_szObjectId, szBuffer, MAX_OID_LEN * 4);
2260 hasChanges = true;
2261 }
2262 unlockProperties();
2263
2264 // Get system description
2265 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.1.1.0"), NULL, 0, szBuffer, sizeof(szBuffer), SG_STRING_RESULT) == SNMP_ERR_SUCCESS)
2266 {
2267 TranslateStr(szBuffer, _T("\r\n"), _T(" "));
2268 TranslateStr(szBuffer, _T("\n"), _T(" "));
2269 TranslateStr(szBuffer, _T("\r"), _T(" "));
2270 lockProperties();
2271 if ((m_sysDescription == NULL) || _tcscmp(m_sysDescription, szBuffer))
2272 {
2273 safe_free(m_sysDescription);
2274 m_sysDescription = _tcsdup(szBuffer);
2275 hasChanges = true;
2276 sendPollerMsg(dwRqId, _T(" System description changed to %s\r\n"), m_sysDescription);
2277 }
2278 unlockProperties();
2279 }
2280
2281 // Select device driver
2282 NetworkDeviceDriver *driver = FindDriverForNode(this, pTransport);
2283 DbgPrintf(5, _T("ConfPoll(%s): selected device driver %s"), m_name, driver->getName());
2284 lockProperties();
2285 if (driver != m_driver)
2286 {
2287 m_driver = driver;
2288 sendPollerMsg(dwRqId, _T(" New network device driver selected: %s\r\n"), m_driver->getName());
2289 }
2290 unlockProperties();
2291
2292 // Allow driver to gather additional info
2293 m_driver->analyzeDevice(pTransport, m_szObjectId, &m_customAttributes, &m_driverData);
2294
2295 // Get sysName
2296 if (SnmpGet(m_snmpVersion, pTransport,
2297 _T(".1.3.6.1.2.1.1.5.0"), NULL, 0, szBuffer, sizeof(szBuffer), SG_STRING_RESULT) == SNMP_ERR_SUCCESS)
2298 {
2299 lockProperties();
2300 if ((m_sysName == NULL) || _tcscmp(m_sysName, szBuffer))
2301 {
2302 safe_free(m_sysName);
2303 m_sysName = _tcsdup(szBuffer);
2304 hasChanges = true;
2305 sendPollerMsg(dwRqId, _T(" System name changed to %s\r\n"), m_sysName);
2306 }
2307 unlockProperties();
2308 }
2309
2310 // Check IP forwarding
2311 if (checkSNMPIntegerValue(pTransport, _T(".1.3.6.1.2.1.4.1.0"), 1))
2312 {
2313 lockProperties();
2314 m_dwFlags |= NF_IS_ROUTER;
2315 unlockProperties();
2316 }
2317 else
2318 {
2319 lockProperties();
2320 m_dwFlags &= ~NF_IS_ROUTER;
2321 unlockProperties();
2322 }
2323
2324 checkIfXTable(pTransport);
2325 checkBridgeMib(pTransport);
2326
2327 // Check for ENTITY-MIB support
2328 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.47.1.4.1.0"), NULL, 0, szBuffer, sizeof(szBuffer), SG_RAW_RESULT) == SNMP_ERR_SUCCESS)
2329 {
2330 lockProperties();
2331 m_dwFlags |= NF_HAS_ENTITY_MIB;
2332 unlockProperties();
2333
2334 ComponentTree *components = BuildComponentTree(this, pTransport);
2335 lockProperties();
2336 if (m_components != NULL)
2337 m_components->decRefCount();
2338 m_components = components;
2339 unlockProperties();
2340 }
2341 else
2342 {
2343 lockProperties();
2344 m_dwFlags &= ~NF_HAS_ENTITY_MIB;
2345 if (m_components != NULL)
2346 {
2347 m_components->decRefCount();
2348 m_components = NULL;
2349 }
2350 unlockProperties();
2351 }
2352
2353 // Check for printer MIB support
2354 int count = 0;
2355 SnmpWalk(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.43.5.1.1.17"), CountingSnmpWalkerCallback, &count, FALSE);
2356 if (count > 0)
2357 {
2358 lockProperties();
2359 m_dwFlags |= NF_IS_PRINTER;
2360 unlockProperties();
2361 }
2362 else
2363 {
2364 lockProperties();
2365 m_dwFlags &= ~NF_IS_PRINTER;
2366 unlockProperties();
2367 }
2368
2369 // Check for CDP (Cisco Discovery Protocol) support
2370 if (checkSNMPIntegerValue(pTransport, _T(".1.3.6.1.4.1.9.9.23.1.3.1.0"), 1))
2371 {
2372 lockProperties();
2373 m_dwFlags |= NF_IS_CDP;
2374 unlockProperties();
2375 }
2376 else
2377 {
2378 lockProperties();
2379 m_dwFlags &= ~NF_IS_CDP;
2380 unlockProperties();
2381 }
2382
2383 // Check for NDP (Nortel Discovery Protocol) support
2384 if (checkSNMPIntegerValue(pTransport, _T(".1.3.6.1.4.1.45.1.6.13.1.2.0"), 1))
2385 {
2386 lockProperties();
2387 m_dwFlags |= NF_IS_NDP;
2388 unlockProperties();
2389 }
2390 else
2391 {
2392 lockProperties();
2393 m_dwFlags &= ~NF_IS_NDP;
2394 unlockProperties();
2395 }
2396
2397 // Check for LLDP (Link Layer Discovery Protocol) support
2398 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.0.8802.1.1.2.1.3.2.0"), NULL, 0, szBuffer, sizeof(szBuffer), 0) == SNMP_ERR_SUCCESS)
2399 {
2400 lockProperties();
2401 m_dwFlags |= NF_IS_LLDP;
2402 unlockProperties();
2403
2404 INT32 type;
2405 BYTE data[256];
2406 UINT32 dataLen;
2407 if ((SnmpGetEx(pTransport, _T(".1.0.8802.1.1.2.1.3.1.0"), NULL, 0, &type, sizeof(INT32), 0, NULL) == SNMP_ERR_SUCCESS) &&
2408 (SnmpGetEx(pTransport, _T(".1.0.8802.1.1.2.1.3.2.0"), NULL, 0, data, 256, SG_RAW_RESULT, &dataLen) == SNMP_ERR_SUCCESS))
2409 {
2410 BuildLldpId(type, data, dataLen, szBuffer, 1024);
2411 lockProperties();
2412 if ((m_lldpNodeId == NULL) || _tcscmp(m_lldpNodeId, szBuffer))
2413 {
2414 safe_free(m_lldpNodeId);
2415 m_lldpNodeId = _tcsdup(szBuffer);
2416 hasChanges = true;
2417 sendPollerMsg(dwRqId, _T(" LLDP node ID changed to %s\r\n"), m_lldpNodeId);
2418 }
2419 unlockProperties();
2420 }
2421
2422 ObjectArray<LLDP_LOCAL_PORT_INFO> *lldpPorts = GetLLDPLocalPortInfo(pTransport);
2423 lockProperties();
2424 delete m_lldpLocalPortInfo;
2425 m_lldpLocalPortInfo = lldpPorts;
2426 unlockProperties();
2427 }
2428 else
2429 {
2430 lockProperties();
2431 m_dwFlags &= ~NF_IS_LLDP;
2432 unlockProperties();
2433 }
2434
2435 // Check for 802.1x support
2436 if (checkSNMPIntegerValue(pTransport, _T(".1.0.8802.1.1.1.1.1.1.0"), 1))
2437 {
2438 lockProperties();
2439 m_dwFlags |= NF_IS_8021X;
2440 unlockProperties();
2441 }
2442 else
2443 {
2444 lockProperties();
2445 m_dwFlags &= ~NF_IS_8021X;
2446 unlockProperties();
2447 }
2448
2449 checkOSPFSupport(pTransport);
2450
2451 // Get VRRP information
2452 VrrpInfo *vrrpInfo = GetVRRPInfo(this);
2453 if (vrrpInfo != NULL)
2454 {
2455 lockProperties();
2456 m_dwFlags |= NF_IS_VRRP;
2457 delete m_vrrpInfo;
2458 m_vrrpInfo = vrrpInfo;
2459 unlockProperties();
2460 }
2461 else
2462 {
2463 lockProperties();
2464 m_dwFlags &= ~NF_IS_VRRP;
2465 unlockProperties();
2466 }
2467
2468 // Get wireless controller data
2469 if ((m_driver != NULL) && m_driver->isWirelessController(pTransport, &m_customAttributes, m_driverData))
2470 {
2471 DbgPrintf(5, _T("ConfPoll(%s): node is wireless controller, reading access point information"), m_name);
2472 sendPollerMsg(dwRqId, _T(" Reading wireless access point information\r\n"));
2473 lockProperties();
2474 m_dwFlags |= NF_IS_WIFI_CONTROLLER;
2475 unlockProperties();
2476
2477 int clusterMode = m_driver->getClusterMode(pTransport, &m_customAttributes, m_driverData);
2478
2479 ObjectArray<AccessPointInfo> *aps = m_driver->getAccessPoints(pTransport, &m_customAttributes, m_driverData);
2480 if (aps != NULL)
2481 {
2482 sendPollerMsg(dwRqId, POLLER_INFO _T(" %d wireless access points found\r\n"), aps->size());
2483 DbgPrintf(5, _T("ConfPoll(%s): got information about %d access points"), m_name, aps->size());
2484 int adopted = 0;
2485 for(int i = 0; i < aps->size(); i++)
2486 {
2487 AccessPointInfo *info = aps->get(i);
2488 if (info->getState() == AP_ADOPTED)
2489 adopted++;
2490
2491 bool newAp = false;
2492 AccessPoint *ap = (clusterMode == CLUSTER_MODE_STANDALONE) ? findAccessPointByMAC(info->getMacAddr()) : FindAccessPointByMAC(info->getMacAddr());
2493 if (ap == NULL)
2494 {
2495 String name;
2496
2497 if (info->getName() != NULL)
2498 {
2499 name = info->getName();
2500 }
2501 else
2502 {
2503 for(int j = 0; j < info->getRadioInterfaces()->size(); j++)
2504 {
2505 if (j > 0)
2506 name += _T("/");
2507 name += info->getRadioInterfaces()->get(j)->name;
2508 }
2509 }
2510 ap = new AccessPoint((const TCHAR *)name, info->getIndex(), info->getMacAddr());
2511 NetObjInsert(ap, TRUE);
2512 DbgPrintf(5, _T("ConfPoll(%s): created new access point object %s [%d]"), m_name, ap->getName(), ap->getId());
2513 newAp = true;
2514 }
2515 ap->attachToNode(m_id);
2516 ap->setIpAddress(info->getIpAddr());
2517 if ((info->getState() == AP_ADOPTED) || newAp)
2518 {
2519 ap->updateRadioInterfaces(info->getRadioInterfaces());
2520 ap->updateInfo(info->getVendor(), info->getModel(), info->getSerial());
2521 }
2522 ap->unhide();
2523 ap->updateState(info->getState());
2524 }
2525
2526 lockProperties();
2527 m_adoptedApCount = adopted;
2528 m_totalApCount = aps->size();
2529 unlockProperties();
2530
2531 delete aps;
2532 }
2533 else
2534 {
2535 DbgPrintf(5, _T("ConfPoll(%s): failed to read access point information"), m_name);
2536 sendPollerMsg(dwRqId, POLLER_ERROR _T(" Failed to read access point information\r\n"));
2537 }
2538 }
2539 else
2540 {
2541 lockProperties();
2542 m_dwFlags &= ~NF_IS_WIFI_CONTROLLER;
2543 unlockProperties();
2544 }
2545 }
2546 else if (ConfigReadInt(_T("EnableCheckPointSNMP"), 0))
2547 {
2548 // Check for CheckPoint SNMP agent on port 161
2549 DbgPrintf(5, _T("ConfPoll(%s): checking for CheckPoint SNMP"), m_name);
2550 TCHAR szBuffer[4096];
2551 if (SnmpGet(SNMP_VERSION_1, pTransport, _T(".1.3.6.1.4.1.2620.1.1.10.0"), NULL, 0, szBuffer, sizeof(szBuffer), 0) == SNMP_ERR_SUCCESS)
2552 {
2553 lockProperties();
2554 if (_tcscmp(m_szObjectId, _T(".1.3.6.1.4.1.2620.1.1")))
2555 {
2556 nx_strncpy(m_szObjectId, _T(".1.3.6.1.4.1.2620.1.1"), MAX_OID_LEN * 4);
2557 hasChanges = true;
2558 }
2559
2560 m_dwFlags |= NF_IS_SNMP | NF_IS_ROUTER;
2561 m_dwDynamicFlags &= ~NDF_SNMP_UNREACHABLE;
2562 unlockProperties();
2563 sendPollerMsg(dwRqId, POLLER_INFO _T(" CheckPoint SNMP agent on port 161 is active\r\n"));
2564 }
2565 }
2566 delete pTransport;
2567 return hasChanges;
2568 }
2569
2570 /**
2571 * Configuration poll: check for BRIDGE MIB
2572 */
2573 void Node::checkBridgeMib(SNMP_Transport *pTransport)
2574 {
2575 TCHAR szBuffer[4096];
2576 if (SnmpGet(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.17.1.1.0"), NULL, 0, szBuffer, sizeof(szBuffer), SG_RAW_RESULT) == SNMP_ERR_SUCCESS)
2577 {
2578 lockProperties();
2579 m_dwFlags |= NF_IS_BRIDGE;
2580 memcpy(m_baseBridgeAddress, szBuffer, 6);
2581 unlockProperties();
2582
2583 // Check for Spanning Tree (IEEE 802.1d) MIB support
2584 if (checkSNMPIntegerValue(pTransport, _T(".1.3.6.1.2.1.17.2.1.0"), 3))
2585 {
2586 lockProperties();
2587 m_dwFlags |= NF_IS_STP;
2588 unlockProperties();
2589 }
2590 else
2591 {
2592 lockProperties();
2593 m_dwFlags &= ~NF_IS_STP;
2594 unlockProperties();
2595 }
2596 }
2597 else
2598 {
2599 lockProperties();
2600 m_dwFlags &= ~(NF_IS_BRIDGE | NF_IS_STP);
2601 unlockProperties();
2602 }
2603 }
2604
2605 /**
2606 * Configuration poll: check for ifXTable
2607 */
2608 void Node::checkIfXTable(SNMP_Transport *pTransport)
2609 {
2610 int count = 0;
2611 SnmpWalk(m_snmpVersion, pTransport, _T(".1.3.6.1.2.1.31.1.1.1.1"), CountingSnmpWalkerCallback, &count, FALSE);
2612 if (count > 0)
2613 {
2614 lockProperties();
2615 m_dwFlags |= NF_HAS_IFXTABLE;
2616 unlockProperties();
2617 }
2618 else
2619 {
2620 lockProperties();
2621 m_dwFlags &= ~NF_HAS_IFXTABLE;
2622 unlockProperties();
2623 }
2624 }
2625
2626 /**
2627 * Delete duplicate interfaces
2628 * (find and delete multiple interfaces with same ifIndex value created by version prior to 2.0-M3)
2629 */
2630 bool Node::deleteDuplicateInterfaces(UINT32 rqid)
2631 {
2632 ObjectArray<Interface> deleteList(16, 16, false);
2633
2634 LockChildList(FALSE);
2635 for(UINT32 i = 0; i < m_dwChildCount; i++)
2636 {
2637 if ((m_pChildList[i]->getObjectClass() != OBJECT_INTERFACE) ||
2638 ((Interface *)m_pChildList[i])->isManuallyCreated())
2639 continue;
2640 Interface *iface = (Interface *)m_pChildList[i];
2641 for(UINT32 j = i + 1; j < m_dwChildCount; j++)
2642 {
2643 if ((m_pChildList[j]->getObjectClass() != OBJECT_INTERFACE) ||
2644 ((Interface *)m_pChildList[j])->isManuallyCreated() ||
2645 (deleteList.contains((Interface *)m_pChildList[j])))
2646 continue;
2647 if (iface->getIfIndex() == ((Interface *)m_pChildList[j])->getIfIndex())
2648 {
2649 deleteList.add((Interface *)m_pChildList[j]);
2650 DbgPrintf(6, _T("Node::deleteDuplicateInterfaces(%s [%d]): found duplicate interface %s [%d], original %s [%d], ifIndex=%d"),
2651 m_name, m_id, m_pChildList[j]->getName(), m_pChildList[j]->getId(), iface->getName(), iface->getId(), iface->getIfIndex());
2652 }
2653 }
2654 }
2655 UnlockChildList();
2656
2657 for(int i = 0; i < deleteList.size(); i++)
2658 {
2659 Interface *iface = deleteList.get(i);
2660 sendPollerMsg(rqid, POLLER_WARNING _T(" Duplicate interface \"%s\" deleted\r\n"), iface->getName());
2661 deleteInterface(iface);
2662 }
2663
2664 return deleteList.size() > 0;
2665 }
2666
2667 /**
2668 * Update interface configuration
2669 */
2670 bool Node::updateInterfaceConfiguration(UINT32 rqid, int maskBits)
2671 {
2672 sendPollerMsg(rqid, _T("Checking interface configuration...\r\n"));
2673
2674 bool hasChanges = deleteDuplicateInterfaces(rqid);
2675
2676 InterfaceList *pIfList = getInterfaceList();
2677 if (pIfList != NULL)
2678 {
2679 DbgPrintf(6, _T("Node::updateInterfaceConfiguration(%s [%u]): got %d interfaces"), m_name, m_id, pIfList->size());
2680
2681 // Find non-existing interfaces
2682 LockChildList(FALSE);
2683 ObjectArray<Interface> deleteList(m_dwChildCount, 8, false);
2684 for(UINT32 i = 0; i < m_dwChildCount; i++)
2685 {
2686 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
2687 {
2688 Interface *pInterface = (Interface *)m_pChildList[i];
2689 if (!pInterface->isManuallyCreated())
2690 {
2691 int j;
2692 for(j = 0; j < pIfList->size(); j++)
2693 {
2694 if (pIfList->get(j)->index == pInterface->getIfIndex())
2695 break;
2696 }
2697
2698 if (j == pIfList->size())
2699 {
2700 // No such interface in current configuration, add it to delete list
2701 deleteList.add(pInterface);
2702 }
2703 }
2704 }
2705 }
2706 UnlockChildList();
2707
2708 // Delete non-existent interfaces
2709 if (deleteList.size() > 0)
2710 {
2711 for(int j = 0; j < deleteList.size(); j++)
2712 {
2713 Interface *iface = deleteList.get(j);
2714 sendPollerMsg(rqid, POLLER_WARNING _T(" Interface \"%s\" is no longer exist\r\n"), iface->getName());
2715 const InetAddress& addr = iface->getFirstIpAddress();
2716 PostEvent(EVENT_INTERFACE_DELETED, m_id, "dsAd", iface->getIfIndex(), iface->getName(), &addr, addr.getMaskBits());
2717 deleteInterface(iface);
2718 }
2719 hasChanges = true;
2720 }
2721
2722 // Add new interfaces and check configuration of existing
2723 for(int j = 0; j < pIfList->size(); j++)
2724 {
2725 InterfaceInfo *ifInfo = pIfList->get(j);
2726 BOOL bNewInterface = TRUE;
2727
2728 LockChildList(FALSE);
2729 for(UINT32 i = 0; i < m_dwChildCount; i++)
2730 {
2731 if (m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE)
2732 {
2733 Interface *pInterface = (Interface *)m_pChildList[i];
2734
2735 if (ifInfo->index == pInterface->getIfIndex())
2736 {
2737 // Existing interface, check configuration
2738 if (memcmp(ifInfo->macAddr, "\x00\x00\x00\x00\x00\x00", MAC_ADDR_LENGTH) &&
2739 memcmp(ifInfo->macAddr, pInterface->getMacAddr(), MAC_ADDR_LENGTH))
2740 {
2741 TCHAR szOldMac[16], szNewMac[16];
2742
2743 BinToStr((BYTE *)pInterface->getMacAddr(), MAC_ADDR_LENGTH, szOldMac);
2744 BinToStr(ifInfo->macAddr, MAC_ADDR_LENGTH, szNewMac);
2745 PostEvent(EVENT_MAC_ADDR_CHANGED, m_id, "idsss",
2746 pInterface->getId(), pInterface->getIfIndex(),
2747 pInterface->getName(), szOldMac, szNewMac);
2748 pInterface->setMacAddr(ifInfo->macAddr);
2749 }
2750 if (_tcscmp(ifInfo->name, pInterface->getName()))
2751 {
2752 pInterface->setName(ifInfo->name);
2753 }
2754 if (_tcscmp(ifInfo->description, pInterface->getDescription()))
2755 {
2756 pInterface->setDescription(ifInfo->description);
2757 }
2758 if (_tcscmp(ifInfo->alias, pInterface->getAlias()))
2759 {
2760 pInterface->setAlias(ifInfo->alias);
2761 }
2762 if (ifInfo->bridgePort != pInterface->getBridgePortNumber())
2763 {
2764 pInterface->setBridgePortNumber(ifInfo->bridgePort);
2765 }
2766 if (ifInfo->slot != pInterface->getSlotNumber())
2767 {
2768 pInterface->setSlotNumber(ifInfo->slot);
2769 }
2770 if (ifInfo->port != pInterface->getPortNumber())
2771 {
2772 pInterface->setPortNumber(ifInfo->port);
2773 }
2774 if (ifInfo->isPhysicalPort != pInterface->isPhysicalPort())
2775 {
2776 pInterface->setPhysicalPortFlag(ifInfo->isPhysicalPort);
2777 }
2778 if (ifInfo->mtu != pInterface->getMTU())
2779 {
2780 pInterface->setMTU(ifInfo->mtu);
2781 }
2782
2783 // Check for deleted IPs and changed masks
2784 const InetAddressList *ifList = pInterface->getIpAddressList();
2785 for(int n = 0; n < ifList->size(); n++)
2786 {
2787 const InetAddress& ifAddr = ifList->get(n);
2788 const InetAddress& addr = ifInfo->ipAddrList.findAddress(ifAddr);
2789 if (addr.isValid())
2790 {
2791 if (addr.getMaskBits() != ifAddr.getMaskBits())
2792 {
2793 PostEvent(EVENT_IF_MASK_CHANGED, m_id, "dsAddd", pInterface->getId(), pInterface->getName(),
2794 &addr, addr.getMaskBits(), pInterface->getIfIndex(), ifAddr.getMaskBits());
2795 pInterface->setNetMask(addr);
2796 sendPollerMsg(rqid, POLLER_INFO _T(" IP network mask changed to /%d on interface \"%s\" address %s\r\n"),
2797 addr.getMaskBits(), pInterface->getName(), (const TCHAR *)ifAddr.toString());
2798 }
2799 }
2800 else
2801 {
2802 sendPollerMsg(rqid, POLLER_WARNING _T(" IP address %s removed from interface \"%s\"\r\n"),
2803 (const TCHAR *)ifAddr.toString(), pInterface->getName());
2804 PostEvent(EVENT_IF_IPADDR_DELETED, m_id, "dsAdd", pInterface->getId(), pInterface->getName(),
2805 &ifAddr, ifAddr.getMaskBits(), pInterface->getIfIndex());
2806 pInterface->deleteIpAddress(ifAddr);
2807 }
2808 }
2809
2810 // Check for added IPs
2811 for(int m = 0; m < ifInfo->ipAddrList.size(); m++)
2812 {
2813 const InetAddress& addr = ifInfo->ipAddrList.get(m);
2814 if (!ifList->hasAddress(addr))
2815 {
2816 pInterface->addIpAddress(addr);
2817 PostEvent(EVENT_IF_IPADDR_ADDED, m_id, "dsAdd", pInterface->getId(), pInterface->getName(),
2818 &addr, addr.getMaskBits(), pInterface->getIfIndex());
2819 sendPollerMsg(rqid, POLLER_INFO _T(" IP address %s added to interface \"%s\"\r\n"),
2820 (const TCHAR *)addr.toString(), pInterface->getName());
2821 }
2822 }
2823
2824 bNewInterface = FALSE;
2825 break;
2826 }
2827 }
2828 }
2829 UnlockChildList();
2830
2831 if (bNewInterface)
2832 {
2833 // New interface
2834 sendPollerMsg(rqid, POLLER_INFO _T(" Found new interface \"%s\"\r\n"), ifInfo->name);
2835 createNewInterface(ifInfo, false);
2836 hasChanges = true;
2837 }
2838 }
2839 }
2840 else if (!(m_dwFlags & NF_REMOTE_AGENT)) /* pIfList == NULL */
2841 {
2842 Interface *pInterface;
2843 UINT32 dwCount;
2844
2845 sendPollerMsg(rqid, POLLER_ERROR _T("Unable to get interface list from node\r\n"));
2846 DbgPrintf(6, _T("Node::updateInterfaceConfiguration(%s [%u]): Unable to get interface list from node"), m_name, m_id);
2847
2848 // Delete all existing interfaces in case of forced capability recheck
2849 if (m_dwDynamicFlags & NDF_RECHECK_CAPABILITIES)
2850 {
2851 LockChildList(FALSE);
2852 Interface **ppDeleteList = (Interface **)malloc(sizeof(Interface *) * m_dwChildCount);
2853 int delCount = 0;
2854 for(UINT32 i = 0; i < m_dwChildCount; i++)
2855 {
2856 if ((m_pChildList[i]->getObjectClass() == OBJECT_INTERFACE) && !((Interface *)m_pChildList[i])->isManuallyCreated())
2857 ppDeleteList[delCount++] = (Interface *)m_pChildList[i];
2858 }
2859 UnlockChildList();
2860 for(int j = 0; j < delCount; j++)
2861 {
2862 sendPollerMsg(rqid, POLLER_WARNING _T(" Interface \"%s\" is no longer exist\r\n"),
2863 ppDeleteList[j]->getName());
2864 const InetAddress& addr = ppDeleteList[j]->getIpAddressList()->getFirstUnicastAddress();
2865 PostEvent(EVENT_INTERFACE_DELETED, m_id, "dsAd", ppDeleteList[j]->getIfIndex(),
2866 ppDeleteList[j]->getName(), &addr, addr.getMaskBits());
2867 deleteInterface(ppDeleteList[j]);
2868 }
2869 safe_free(ppDeleteList);
2870 }
2871
2872 // Check if we have pseudo-interface object
2873 BYTE macAddr[MAC_ADDR_LENGTH];
2874 BYTE *pMacAddr;
2875 dwCount = getInterfaceCount(&pInterface);
2876 if (dwCount == 1)
2877 {
2878 if (pInterface->isFake())
2879 {
2880 // Check if primary IP is different from interface's IP
2881 if (!pInterface->getIpAddressList()->hasAddress(m_ipAddress))
2882 {
2883 deleteInterface(pInterface);
2884 if (m_ipAddress.isValidUnicast())
2885 {
2886 memset(macAddr, 0, MAC_ADDR_LENGTH);
2887 Subnet *pSubnet = FindSubnetForNode(m_zoneId, m_ipAddress);
2888 if (pSubnet != NULL)
2889 pSubnet->findMacAddress(m_ipAddress, macAddr);
2890 pMacAddr = !memcmp(macAddr, "\x00\x00\x00\x00\x00\x00", MAC_ADDR_LENGTH) ? NULL : macAddr;
2891 TCHAR szMac[20];
2892 MACToStr(macAddr, szMac);
2893 DbgPrintf(5, _T("Node::updateInterfaceConfiguration(%s [%u]): got MAC for unknown interface: %s"), m_name, m_id, szMac);
2894 InetAddress ifaceAddr = m_ipAddress;
2895 ifaceAddr.setMaskBits(maskBits);
2896 createNewInterface(ifaceAddr, pMacAddr);
2897 }
2898 }
2899 else
2900 {
2901 // check MAC address
2902 memset(macAddr, 0, MAC_ADDR_LENGTH);
2903 Subnet *pSubnet = FindSubnetForNode(m_zoneId, m_ipAddress);
2904 if (pSubnet != NULL)
2905 pSubnet->findMacAddress(m_ipAddress, macAddr);
2906 if (memcmp(macAddr, "\x00\x00\x00\x00\x00\x00", MAC_ADDR_LENGTH) && memcmp(macAddr, pInterface->getMacAddr(), MAC_ADDR_LENGTH))
2907 {
2908 TCHAR szOldMac[16], szNewMac[16];
2909
2910 BinToStr((BYTE *)pInterface->getMacAddr(), MAC_ADDR_LENGTH, szOldMac);
2911 BinToStr(macAddr, MAC_ADDR_LENGTH, szNewMac);
2912 DbgPrintf(5, _T("Node::updateInterfaceConfiguration(%s [%u]): MAC change for unknown interface: %s to %s"),
2913 m_name, m_id, szOldMac, szNewMac);
2914 PostEvent(EVENT_MAC_ADDR_CHANGED, m_id, "idsss",
2915 pInterface->getId(), pInterface->getIfIndex(),
2916 pInterface->getName(), szOldMac, szNewMac);
2917 pInterface->setMacAddr(macAddr);
2918 }
2919 }
2920 }
2921 }
2922 else if (dwCount == 0)
2923 {
2924 // No interfaces at all, create pseudo-interface
2925 if (m_ipAddress.isValidUnicast())
2926 {
2927 memset(macAddr, 0, MAC_ADDR_LENGTH);
2928 Subnet *pSubnet = FindSubnetForNode(m_zoneId, m_ipAddress);
2929 if (pSubnet != NULL)
2930 pSubnet->findMacAddress(m_ipAddress, macAddr);
2931 pMacAddr = !memcmp(macAddr, "\x00\x00\x00\x00\x00\x00", MAC_ADDR_LENGTH) ? NULL : macAddr;
2932 TCHAR szMac[20];
2933 MACToStr(macAddr, szMac);
2934 DbgPrintf(5, _T("Node::updateInterfaceConfiguration(%s [%u]): got MAC for unknown interface: %s"), m_name, m_id, szMac);
2935 InetAddress ifaceAddr = m_ipAddress;
2936 ifaceAddr.setMaskBits(maskBits);
2937 createNewInterface(ifaceAddr, pMacAddr);
2938 }
2939 }
2940 DbgPrintf(6, _T("Node::updateInterfaceConfiguration(%s [%u]): pflist == NULL, dwCount = %u"), m_name, m_id, dwCount);
2941 }
2942
2943 delete pIfList;
2944 checkSubnetBinding();
2945
2946 sendPollerMsg(rqid, _T("Interface configuration check finished\r\n"));
2947 return hasChanges;
2948 }
2949
2950 /**
2951 * Callback: apply template to nodes
2952 */
2953 static void ApplyTemplate(NetObj *object, void *node)
2954 {
2955 if ((object->getObjectClass() == OBJECT_TEMPLATE) && !object->isDeleted())
2956 {
2957 Template *pTemplate = (Template *)object;
2958 AutoBindDecision decision = pTemplate->isApplicable((Node *)node);
2959 if (decision == AutoBindDecision_Bind)
2960 {
2961 if (!pTemplate->isChild(((Node *)node)->getId()))
2962 {
2963 DbgPrintf(4, _T("Node::ApplyUserTemplates(): applying template %d \"%s\" to node %d \"%s\""),
2964 pTemplate->getId(), pTemplate->getName(), ((Node *)node)->getId(), ((Node *)node)->getName());
2965 pTemplate->applyToTarget((Node *)node);
2966 PostEvent(EVENT_TEMPLATE_AUTOAPPLY, g_dwMgmtNode, "isis", ((Node *)node)->getId(), ((Node *)node)->getName(), pTemplate->getId(), pTemplate->getName());
2967 }
2968 }
2969 else if (decision == AutoBindDecision_Unbind)
2970 {
2971 if (pTemplate->isAutoRemoveEnabled() && pTemplate->isChild(((Node *)node)->getId()))
2972 {
2973 DbgPrintf(4, _T("Node::ApplyUserTemplates(): removing template %d \"%s\" from node %d \"%s\""),
2974 pTemplate->getId(), pTemplate->getName(), ((Node *)node)->getId(), ((Node *)node)->getName());
2975 pTemplate->DeleteChild((Node *)node);
2976 ((Node *)node)->DeleteParent(pTemplate);
2977 pTemplate->queueRemoveFromTarget(((Node *)node)->getId(), TRUE);
2978 PostEvent(EVENT_TEMPLATE_AUTOREMOVE, g_dwMgmtNode, "isis", ((Node *)node)->getId(), ((Node *)node)->getName(), pTemplate->getId(), pTemplate->getName());
2979 }
2980 }
2981 }
2982 }
2983
2984 /**
2985 * Apply user templates
2986 */
2987 void Node::applyUserTemplates()
2988 {
2989 g_idxObjectById.forEach(ApplyTemplate, this);
2990 }
2991
2992 /**
2993 * Filter for selecting containers from objects
2994 */
2995 static bool ContainerSelectionFilter(NetObj *object, void *userData)
2996 {
2997 return (object->getObjectClass() == OBJECT_CONTAINER) && !object->isDeleted() && ((Container *)object)->isAutoBindEnabled();
2998 }
2999
3000 /**
3001 * Update container membership
3002 */
3003 void Node::updateContainerMembership()
3004 {
3005 ObjectArray<NetObj> *containers = g_idxObjectById.getObjects(true, ContainerSelectionFilter);
3006 for(int i = 0; i < containers->size(); i++)
3007 {
3008 Container *pContainer = (Container *)containers->get(i);
3009 AutoBindDecision decision = pContainer->isSuitableForNode(this);
3010 if (decision == AutoBindDecision_Bind)
3011 {
3012 if (!pContainer->isChild(m_id))
3013 {
3014 DbgPrintf(4, _T("Node::updateContainerMembership(): binding node %d \"%s\" to container %d \"%s\""),
3015 m_id, m_name, pContainer->getId(), pContainer->getName());
3016 pContainer->AddChild(this);
3017 AddParent(pContainer);
3018 PostEvent(EVENT_CONTAINER_AUTOBIND, g_dwMgmtNode, "isis", m_id, m_name, pContainer->getId(), pContainer->getName());
3019 pContainer->calculateCompoundStatus();
3020 }
3021 }
3022 else if (decision == AutoBindDecision_Unbind)
3023 {
3024 if (pContainer->isAutoUnbindEnabled() && pContainer->isChild(m_id))
3025 {
3026 DbgPrintf(4, _T("Node::updateContainerMembership(): removing node %d \"%s\" from container %d \"%s\""),
3027 m_id, m_name, pContainer->getId(), pContainer->getName());
3028 pContainer->DeleteChild(this);
3029 DeleteParent(pContainer);
3030 PostEvent(EVENT_CONTAINER_AUTOUNBIND, g_dwMgmtNode, "isis", m_id, m_name, pContainer->getId(), pContainer->getName());
3031 pContainer->calculateCompoundStatus();
3032 }
3033 }
3034 pContainer->decRefCount();
3035 }
3036 delete containers;
3037 }
3038
3039 /**
3040 * Entry point for instance discovery poller
3041 */
3042 void Node::instanceDiscoveryPoll(PollerInfo *poller)
3043 {
3044 poller->startExecution();
3045 ObjectTransactionStart();
3046 instanceDiscoveryPoll(NULL, 0, poller);
3047 ObjectTransactionEnd();
3048 delete poller;
3049 }
3050
3051 /**
3052 * Perform instance discovery poll on node
3053 */
3054 void Node::instanceDiscoveryPoll(ClientSession *session, UINT32 requestId, PollerInfo *poller)
3055 {
3056 if (m_dwDynamicFlags & NDF_DELETE_IN_PROGRESS)
3057 {
3058 if (requestId == 0)
3059 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_INSTANCE_POLL;
3060 return;
3061 }
3062
3063 poller->setStatus(_T("wait for lock"));
3064 pollerLock();
3065 m_pollRequestor = session;
3066 sendPollerMsg(requestId, _T("Starting instance discovery poll for node %s\r\n"), m_name);
3067 DbgPrintf(4, _T("Starting instance discovery poll for node %s (ID: %d)"), m_name, m_id);
3068
3069 // Check if node is marked as unreachable
3070 if (!(m_dwDynamicFlags & NDF_UNREACHABLE))
3071 {
3072 poller->setStatus(_T("instance discovery"));
3073 doInstanceDiscovery(requestId);
3074
3075 // Execute hook script
3076 poller->setStatus(_T("hook"));
3077 executeHookScript(_T("InstancePoll"));
3078 }
3079 else
3080 {
3081 sendPollerMsg(requestId, POLLER_WARNING _T("Node is marked as unreachable, instance discovery poll aborted\r\n"));
3082 DbgPrintf(4, _T("Node is marked as unreachable, instance discovery poll aborted"));
3083 }
3084
3085 m_lastInstancePoll = time(NULL);
3086
3087 // Finish instance discovery poll
3088 poller->setStatus(_T("cleanup"));
3089 if (requestId == 0)
3090 m_dwDynamicFlags &= ~NDF_QUEUED_FOR_INSTANCE_POLL;
3091 pollerUnlock();
3092 DbgPrintf(4, _T("Finished instance discovery poll for node %s (ID: %d)"), m_name, m_id);
3093 }
3094
3095 /**
3096 * Do instance discovery
3097 */
3098 void Node::doInstanceDiscovery(UINT32 requestId)
3099 {
3100 sendPollerMsg(requestId, _T("Running DCI instance discovery\r\n"));
3101
3102 // collect instance discovery DCIs
3103 ObjectArray<DCItem> rootItems;
3104 lockDciAccess(false);
3105 for(int i = 0; i < m_dcObjects->size(); i++)
3106 {
3107 DCObject *object = m_dcObjects->get(i);
3108 if ((object->getType() == DCO_TYPE_ITEM) && (((DCItem *)object)->getInstanceDiscoveryMethod() != IDM_NONE))
3109 {
3110 object->setBusyFlag(TRUE);
3111 rootItems.add((DCItem *)object);
3112 }
3113 }
3114 unlockDciAccess();
3115
3116 // process instance discovery DCIs
3117 // it should be done that way to prevent DCI list lock for long time
3118 for(int i = 0; i < rootItems.size(); i++)
3119 {
3120 DCItem *dci = rootItems.get(i);
3121 DbgPrintf(5, _T("Node::doInstanceDiscovery(%s [%u]): Updating instances for instance discovery DCI %s [%d]"),
3122 m_name, m_id, dci->getName(), dci->getId());
3123 sendPollerMsg(requestId, _T(" Updating instances for %s [%d]\r\n"), dci->getName(), dci->getId());
3124 StringMap *instances = getInstanceList(dci);
3125 if (instances != NULL)
3126 {
3127 DbgPrintf(5, _T("Node::doInstanceDiscovery(%s [%u]): read %d values"), m_name, m_id, instances->size());
3128 dci->filterInstanceList(instances);
3129 updateInstances(dci, instances, requestId);
3130 delete instances;
3131 }
3132 else
3133 {
3134 DbgPrintf(5, _T("Node::doInstanceDiscovery(%s [%u]): failed to get instance list for DCI %s [%d]"),
3135 m_name, m_id, dci->getName(), dci->getId());
3136 sendPollerMsg(requestId, POLLER_ERROR _T(" Failed to get instance list\r\n"));
3137 }
3138 dci->setBusyFlag(FALSE);
3139 }
3140 }
3141
3142 /**
3143 * Get instances for instance discovery DCI
3144 */
3145 StringMap *Node::getInstanceList(DCItem *dci)
3146 {
3147 if (dci->getInstanceDiscoveryData() == NULL)
3148 return NULL;
3149
3150 Node *node;
3151 if (dci->getProxyNode() != 0)
3152 {
3153 node = (Node *)FindObjectById(dci->getProxyNode(), OBJECT_NODE);
3154 if (node == NULL)
3155 {
3156 DbgPrintf(6, _T("Node::getInstanceList(%s [%d]): proxy node [%d] not found"), dci->getName(), dci->getId(), dci->getProxyNode());
3157 return NULL;
3158 }
3159 if (!node->isTrustedNode(m_id))
3160 {
3161 DbgPrintf(6, _T("Node::getInstanceList(%s [%d]): this node (%s [%d]) is not trusted by proxy node %s [%d] not found"),
3162 dci->getName(), dci->getId(), m_name, m_id, node->getName(), node->getId());
3163 return NULL;
3164 }
3165 }
3166 else
3167 {
3168 node = this;
3169 }
3170
3171 StringList *instances = NULL;
3172 StringMap *instanceMap = NULL;
3173 switch(dci->getInstanceDiscoveryMethod())
3174 {
3175 case IDM_AGENT_LIST:
3176 node->getListFromAgent(dci->getInstanceDiscoveryData(), &instances);
3177 break;
3178 case IDM_SNMP_WALK_VALUES:
3179 node->getListFromSNMP(dci->getSnmpPort(), dci->getInstanceDiscoveryData(), &instances);
3180 break;
3181 case IDM_SNMP_WALK_OIDS:
3182 node->getOIDSuffixListFromSNMP(dci->getSnmpPort(), dci->getInstanceDiscoveryData(), &instanceMap);
3183 break;
3184 default:
3185 instances = NULL;
3186 break;
3187 }
3188 if ((instances == NULL) && (instanceMap == NULL))
3189 return NULL;
3190
3191 if (instanceMap == NULL)
3192 {
3193 instanceMap = new StringMap;
3194 for(int i = 0; i < instances->size(); i++)
3195 instanceMap->set(instances->get(i), instances->get(i));
3196 }
3197 delete instances;
3198 return instanceMap;
3199 }
3200
3201 /**
3202 * Callback for finding instance
3203 */
3204 static EnumerationCallbackResult FindInstanceCallback(const TCHAR *key, const void *value, void *data)
3205 {
3206 return !_tcscmp((const TCHAR *)data, key) ? _STOP : _CONTINUE;
3207 }
3208
3209 /**
3210 * Data for CreateInstanceDCI
3211 */
3212 struct CreateInstanceDCIData
3213 {
3214 DCItem *root;
3215 Node *object;
3216 UINT32 requestId;
3217 };
3218
3219 /**
3220 * Callback for creating instance DCIs
3221 */
3222 static EnumerationCallbackResult CreateInstanceDCI(const TCHAR *key, const void *value, void *data)
3223 {
3224 Node *object = ((CreateInstanceDCIData *)data)->object;
3225 DCItem *root = ((CreateInstanceDCIData *)data)->root;
3226
3227 DbgPrintf(5, _T("Node::updateInstances(%s [%u], %s [%u]): creating new DCI for instance \"%s\""),
3228 object->getName(), object->getId(), root->getName(), root->getId(), key);
3229 object->sendPollerMsg(((CreateInstanceDCIData *)data)->requestId, _T(" Creating new DCI for instance \"%s\"\r\n"), key);
3230
3231 DCItem *dci = new DCItem(root);
3232 dci->setTemplateId(object->getId(), root->getId());
3233 dci->setInstance((const TCHAR *)value);
3234 dci->setInstanceDiscoveryMethod(IDM_NONE);
3235 dci->setInstanceDiscoveryData(key);
3236 dci->setInstanceFilter(NULL);
3237 dci->expandInstance();
3238 dci->changeBinding(CreateUniqueId(IDG_ITEM), object, FALSE);
3239 object->addDCObject(dci, true);
3240 return _CONTINUE;
3241 }
3242
3243 /**
3244 * Update instance DCIs created from instance discovery DCI
3245 */
3246 void Node::updateInstances(DCItem *root, StringMap *instances, UINT32 requestId)
3247 {
3248 lockDciAccess(true);
3249
3250 // Delete DCIs for missing instances and update existing
3251 IntegerArray<UINT32> deleteList;
3252 for(int i = 0; i < m_dcObjects->size(); i++)
3253 {
3254 DCObject *object = m_dcObjects->get(i);
3255 if ((object->getType() != DCO_TYPE_ITEM) ||
3256 (object->getTemplateId() != m_id) ||
3257 (object->getTemplateItemId() != root->getId()))
3258 continue;
3259
3260 const TCHAR *dciInstance = ((DCItem *)object)->getInstanceDiscoveryData();
3261 if (instances->forEach(FindInstanceCallback, (void *)dciInstance) == _STOP)
3262 {
3263 // found, remove value from instances
3264 DbgPrintf(5, _T("Node::updateInstances(%s [%u], %s [%u]): instance \"%s\" found"),
3265 m_name, m_id, root->getName(), root->getId(), dciInstance);
3266 instances->remove(dciInstance);
3267 }
3268 else
3269 {
3270 // not found, delete DCI
3271 DbgPrintf(5, _T("Node::updateInstances(%s [%u], %s [%u]): instance \"%s\" not found, instance DCI will be deleted"),
3272 m_name, m_id, root->getName(), root->getId(), dciInstance);
3273 sendPollerMsg(requestId, _T(" Existing instance \"%s\" not found and will be deleted\r\n"), dciInstance);
3274 deleteList.add(object->getId());
3275 }
3276 }
3277
3278 for(int i = 0; i < deleteList.size(); i++)
3279 deleteDCObject(deleteList.get(i), false);
3280
3281 // Create new instances
3282 CreateInstanceDCIData data;
3283 data.root = root;
3284 data.object = this;
3285 data.requestId = requestId;
3286 instances->forEach(CreateInstanceDCI, &data);
3287
3288 unlockDciAccess();
3289 }
3290
3291 /**
3292 * Connect to SM-CLP agent. Assumes that access to SM-CLP connection is already locked.
3293 */
3294 bool Node::connectToSMCLP()
3295 {
3296 // Create new connection object if needed
3297 if (m_smclpConnection == NULL)
3298 {
3299 m_smclpConnection = new SMCLP_Connection(m_ipAddress.getAddressV4(), 23);
3300 DbgPrintf(7, _T("Node::connectToSMCLP(%s [%d]): new connection created"), m_name, m_id);
3301 }
3302 else
3303 {
3304 // Check if we already connected
3305 if (m_smclpConnection->checkConnection())
3306 {
3307 DbgPrintf(7, _T("Node::connectToSMCLP(%s [%d]): already connected"), m_name, m_id);
3308 return true;
3309 }
3310
3311 // Close current connection or clean up after broken connection
3312 m_smclpConnection->disconnect();
3313 delete m_smclpConnection;
3314 m_smclpConnection = new SMCLP_Connection(m_ipAddress.getAddressV4(), 23);
3315 DbgPrintf(7, _T("Node::connectToSMCLP(%s [%d]): existing connection reset"), m_name, m_id);
3316 }
3317
3318 const TCHAR *login = getCustomAttribute(_T("iLO.login"));
3319 const TCHAR *password = getCustomAttribute(_T("iLO.password"));
3320
3321 if ((login != NULL) && (password != NULL))
3322 return m_smclpConnection->connect(login, password);
3323 return false;
3324 }
3325
3326 /**
3327 * Connect to native agent. Assumes that access to agent connection is already locked.
3328 */
3329 bool Node::connectToAgent(UINT32 *error, UINT32 *socketError, bool *newConnection)
3330 {
3331 bool success;
3332
3333 // Create new agent connection object if needed
3334 if (m_pAgentConnection == NULL)
3335 {
3336 m_pAgentConnection = new AgentConnectionEx(m_id, m_ipAddress, m_agentPort, m_agentAuthMethod, m_szSharedSecret);
3337 DbgPrintf(7, _T("Node::connectToAgent(%s [%d]): new agent connection created"), m_name, m_id);
3338 }
3339 else
3340 {
3341 // Check if we already connected
3342 if (m_pAgentConnection->nop() == ERR_SUCCESS)
3343 {
3344 DbgPrintf(7, _T("Node::connectToAgent(%s [%d]): already connected"), m_name, m_id);
3345 if (newConnection != NULL)
3346 *newConnection = false;
3347 return TRUE;
3348 }
3349
3350 // Close current connection or clean up after broken connection
3351 m_pAgentConnection->disconnect();
3352 DbgPrintf(7, _T("Node::connectToAgent(%s [%d]): existing connection reset"), m_name, m_id);
3353 }
3354 if (newConnection != NULL)
3355 *newConnection = true;
3356 m_pAgentConnection->setPort(m_agentPort);
3357 m_pAgentConnection->setAuthData(m_agentAuthMethod, m_szSharedSecret);
3358 setAgentProxy(m_pAgentConnection);
3359 DbgPrintf(7, _T("Node::connectToAgent(%s [%d]): calling connect on port %d"), m_name, m_id, (int)m_agentPort);
3360 success = m_pAgentConnection->connect(g_pServerKey, FALSE, error, socketError);
3361 if (success)
3362 {
3363 m_pAgentConnection->setCommandTimeout(g_agentCommandTimeout);
3364 UINT32 rcc = m_pAgentConnection->setServerId(g_serverId);
3365 if (rcc == ERR_SUCCESS)
3366 {
3367 syncDataCollectionWithAgent(m_pAgentConnection);
3368 }
3369 else
3370 {
3371 DbgPrintf(5, _T("Node::connectToAgent(%s [%d]): cannot set server ID on agent (%s)"), m_name, m_id, AgentErrorCodeToText(rcc));
3372 }
3373 m_pAgentConnection->enableTraps();
3374 CALL_ALL_MODULES(pfOnConnectToAgent, (this, m_pAgentConnection));
3375 }
3376 return success;
3377 }
3378
3379 /**
3380 * Get DCI value via SNMP
3381 */
3382 UINT32 Node::getItemFromSNMP(WORD port, const TCHAR *param, size_t bufSize, TCHAR *buffer, int interpretRawValue)
3383 {
3384 UINT32 dwResult;
3385
3386 if ((((m_dwDynamicFlags & NDF_SNMP_UNREACHABLE) || !(m_dwFlags & NF_IS_SNMP)) && (port == 0)) ||
3387 (m_dwDynamicFlags & NDF_UNREACHABLE) ||
3388 (m_dwFlags & NF_DISABLE_SNMP))
3389 {
3390 dwResult = SNMP_ERR_COMM;
3391 }
3392 else
3393 {
3394 SNMP_Transport *pTransport;
3395
3396 pTransport = createSnmpTransport(port);
3397 if (pTransport != NULL)
3398 {
3399 if (interpretRawValue == SNMP_RAWTYPE_NONE)
3400 {
3401 dwResult = SnmpGet(m_snmpVersion, pTransport, param, NULL, 0, buffer, bufSize * sizeof(TCHAR), SG_PSTRING_RESULT);
3402 }
3403 else
3404 {
3405 BYTE rawValue[1024];
3406 memset(rawValue, 0, 1024);
3407 dwResult = SnmpGet(m_snmpVersion, pTransport, param, NULL, 0, rawValue, 1024, SG_RAW_RESULT);
3408 if (dwResult == SNMP_ERR_SUCCESS)
3409 {
3410 switch(interpretRawValue)
3411 {