Refactor code: clear old OIDs in the Session before updating them

This commit is contained in:
Pim van Pelt
2025-11-22 06:17:23 +01:00
parent b6d2e3b629
commit 4935f5a8ef

View File

@@ -5,6 +5,7 @@ package ifmib
import (
"fmt"
"os"
"reflect"
"sync"
"time"
@@ -161,14 +162,32 @@ func (m *InterfaceMIB) UpdateInterfaceDetails(details []vpp.InterfaceDetails) {
logger.Debugf("Interface details updated for %d interfaces", len(details))
}
func (m *InterfaceMIB) clearHandler() {
// Use reflection to access and clear the private fields of ListHandler
// since it doesn't have a Clear() method
handlerValue := reflect.ValueOf(m.handler).Elem()
oidsField := handlerValue.FieldByName("oids")
itemsField := handlerValue.FieldByName("items")
if oidsField.IsValid() && oidsField.CanSet() {
oidsField.Set(reflect.Zero(oidsField.Type()))
}
if itemsField.IsValid() && itemsField.CanSet() {
itemsField.Set(reflect.Zero(itemsField.Type()))
}
}
func (m *InterfaceMIB) UpdateStats(interfaceStats *api.InterfaceStats) {
m.mutex.Lock()
defer m.mutex.Unlock()
logger.Debugf("Updating IF-MIB with %d interfaces", len(interfaceStats.Interfaces))
// Clear existing entries
m.handler = &agentx.ListHandler{}
// Clear existing entries while preserving the handler reference
// Since go-agentx 0.3.0 binds handlers to sessions at creation time
m.clearHandler()
m.stats = make(map[uint32]*api.InterfaceCounters)
// Add new entries
@@ -178,11 +197,7 @@ func (m *InterfaceMIB) UpdateStats(interfaceStats *api.InterfaceStats) {
m.addInterfaceToMIB(&iface)
}
// Note: With go-agentx 0.3.0, handlers are set during session creation and cannot be changed
if m.ifXTableSession != nil {
logger.Printf("Updated IF-MIB data for %d interfaces", len(m.stats))
}
logger.Debugf("IF-MIB now contains %d interfaces", len(m.stats))
}