|
| 1 | +package sys |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/prometheus/procfs" |
| 5 | +) |
| 6 | + |
| 7 | +type netStatser struct { |
| 8 | + fs procfs.FS |
| 9 | +} |
| 10 | + |
| 11 | +// NewNetUsage returns an object that can interpreted as an `ftdc.Statser`. |
| 12 | +// |
| 13 | +//nolint:revive |
| 14 | +func NewNetUsage() (*netStatser, error) { |
| 15 | + fs, err := procfs.NewDefaultFS() |
| 16 | + if err != nil { |
| 17 | + return nil, err |
| 18 | + } |
| 19 | + |
| 20 | + return &netStatser{fs}, nil |
| 21 | +} |
| 22 | + |
| 23 | +type netDevLine struct { |
| 24 | + RxBytes uint64 |
| 25 | + RxPackets uint64 |
| 26 | + RxErrors uint64 |
| 27 | + RxDropped uint64 |
| 28 | + TxBytes uint64 |
| 29 | + TxPackets uint64 |
| 30 | + TxErrors uint64 |
| 31 | + TxDropped uint64 |
| 32 | +} |
| 33 | + |
| 34 | +type ifaceStats struct { |
| 35 | + TxQueueLength uint64 |
| 36 | + RxQueueLength uint64 |
| 37 | + UsedSockets uint64 |
| 38 | + Drops uint64 |
| 39 | +} |
| 40 | + |
| 41 | +type networkStats struct { |
| 42 | + Ifaces map[string]netDevLine |
| 43 | + TCP ifaceStats |
| 44 | + UDP ifaceStats |
| 45 | +} |
| 46 | + |
| 47 | +func (netStatser *netStatser) Stats() any { |
| 48 | + ret := networkStats{ |
| 49 | + Ifaces: make(map[string]netDevLine), |
| 50 | + } |
| 51 | + if dev, err := netStatser.fs.NetDev(); err == nil { |
| 52 | + for ifaceName, stats := range dev { |
| 53 | + ret.Ifaces[ifaceName] = netDevLine{ |
| 54 | + stats.RxBytes, stats.RxPackets, stats.RxErrors, stats.RxDropped, |
| 55 | + stats.TxBytes, stats.TxPackets, stats.TxErrors, stats.TxDropped, |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + if netTCPSummary, err := netStatser.fs.NetTCPSummary(); err == nil { |
| 61 | + ret.TCP.TxQueueLength = netTCPSummary.TxQueueLength |
| 62 | + ret.TCP.RxQueueLength = netTCPSummary.RxQueueLength |
| 63 | + ret.TCP.UsedSockets = netTCPSummary.UsedSockets |
| 64 | + } |
| 65 | + |
| 66 | + if netUDPSummary, err := netStatser.fs.NetUDPSummary(); err == nil { |
| 67 | + ret.UDP.TxQueueLength = netUDPSummary.TxQueueLength |
| 68 | + ret.UDP.RxQueueLength = netUDPSummary.RxQueueLength |
| 69 | + ret.UDP.UsedSockets = netUDPSummary.UsedSockets |
| 70 | + ret.UDP.Drops = *netUDPSummary.Drops |
| 71 | + } |
| 72 | + |
| 73 | + return ret |
| 74 | +} |
0 commit comments