master
go 104 lines 2.66 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package ddsnmp
4
5 import "maps"
6
7 import "sync"
8
9 // DeviceConnectionInfo holds SNMP connection parameters for a device.
10 // Registered by SNMP collector jobs, consumed by the topology collector.
11 type DeviceConnectionInfo struct {
12 Hostname string
13 Port int
14 SNMPVersion string
15 Community string
16 V3User string
17 V3SecurityLevel string
18 V3AuthProto string
19 V3AuthKey string
20 V3PrivProto string
21 V3PrivKey string
22 V3ContextName string
23 MaxRepetitions uint32
24 MaxOIDs int
25 Timeout int
26 Retries int
27 SysObjectID string
28 SysDescr string
29 SysName string
30 SysContact string
31 SysLocation string
32 Vendor string
33 Model string
34
35 DisableBulkWalk bool
36
37 ManualProfiles []string
38
39 VnodeGUID string
40 VnodeLabels map[string]string
41 }
42
43 // DeviceRegistry is a global registry where SNMP jobs register their connection
44 // info so the topology collector can discover which devices to poll.
45 var DeviceRegistry = &deviceRegistry{
46 devices: make(map[string]DeviceConnectionInfo),
47 }
48
49 type deviceRegistry struct {
50 mu sync.RWMutex
51 devices map[string]DeviceConnectionInfo
52 }
53
54 // Register adds or updates a device in the registry.
55 // Reference types are deep-copied to prevent data races with the caller.
56 func (r *deviceRegistry) Register(key string, info DeviceConnectionInfo) {
57 dev := info
58 if info.ManualProfiles != nil {
59 dev.ManualProfiles = make([]string, len(info.ManualProfiles))
60 copy(dev.ManualProfiles, info.ManualProfiles)
61 }
62 if info.VnodeLabels != nil {
63 dev.VnodeLabels = make(map[string]string, len(info.VnodeLabels))
64 maps.Copy(dev.VnodeLabels, info.VnodeLabels)
65 }
66 r.mu.Lock()
67 r.devices[key] = dev
68 r.mu.Unlock()
69 }
70
71 // Unregister removes a device from the registry.
72 func (r *deviceRegistry) Unregister(key string) {
73 r.mu.Lock()
74 delete(r.devices, key)
75 r.mu.Unlock()
76 }
77
78 // Devices returns a deep-copied snapshot of all registered devices.
79 func (r *deviceRegistry) Devices() []DeviceConnectionInfo {
80 r.mu.RLock()
81 defer r.mu.RUnlock()
82
83 devices := make([]DeviceConnectionInfo, 0, len(r.devices))
84 for _, info := range r.devices {
85 dev := info
86 if info.ManualProfiles != nil {
87 dev.ManualProfiles = make([]string, len(info.ManualProfiles))
88 copy(dev.ManualProfiles, info.ManualProfiles)
89 }
90 if info.VnodeLabels != nil {
91 dev.VnodeLabels = make(map[string]string, len(info.VnodeLabels))
92 maps.Copy(dev.VnodeLabels, info.VnodeLabels)
93 }
94 devices = append(devices, dev)
95 }
96 return devices
97 }
98
99 // Len returns the number of registered devices.
100 func (r *deviceRegistry) Len() int {
101 r.mu.RLock()
102 defer r.mu.RUnlock()
103 return len(r.devices)
104 }