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