net.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package node
  2. import (
  3. "github.com/coroot/coroot-node-agent/proc"
  4. "github.com/vishvananda/netlink"
  5. "golang.org/x/sys/unix"
  6. "inet.af/netaddr"
  7. "regexp"
  8. )
  9. var netDeviceFilterRe = regexp.MustCompile(`^(enp\d+s\d+(f\d+)?|eth\d+|eno\d+|ens\d+|em\d+|bond\d+|p\d+p\d+|enx[0-9a-f]{12})`)
  10. func netDeviceFilter(name string) bool {
  11. return netDeviceFilterRe.MatchString(name)
  12. }
  13. type NetDeviceInfo struct {
  14. Name string
  15. Up float64
  16. IPPrefixes []netaddr.IPPrefix
  17. RxBytes float64
  18. TxBytes float64
  19. RxPackets float64
  20. TxPackets float64
  21. }
  22. func NetDevices() ([]NetDeviceInfo, error) {
  23. hostNs, err := proc.GetHostNetNs()
  24. if err != nil {
  25. return nil, err
  26. }
  27. defer hostNs.Close()
  28. h, err := netlink.NewHandleAt(hostNs)
  29. if err != nil {
  30. return nil, err
  31. }
  32. defer h.Delete()
  33. links, err := h.LinkList()
  34. if err != nil {
  35. return nil, err
  36. }
  37. var res []NetDeviceInfo
  38. for _, link := range links {
  39. attrs := link.Attrs()
  40. if !netDeviceFilter(attrs.Name) {
  41. continue
  42. }
  43. info := NetDeviceInfo{
  44. Name: attrs.Name,
  45. RxBytes: float64(attrs.Statistics.RxBytes),
  46. TxBytes: float64(attrs.Statistics.TxBytes),
  47. RxPackets: float64(attrs.Statistics.RxPackets),
  48. TxPackets: float64(attrs.Statistics.TxPackets),
  49. }
  50. if attrs.OperState == netlink.OperUp {
  51. info.Up = 1
  52. }
  53. addrs, err := h.AddrList(link, unix.AF_UNSPEC)
  54. if err != nil {
  55. return nil, err
  56. }
  57. for _, addr := range addrs {
  58. ip := addr.IP
  59. if ip.IsLinkLocalUnicast() || ip.IsMulticast() || ip.IsLinkLocalMulticast() {
  60. continue
  61. }
  62. if prefix, ok := netaddr.FromStdIPNet(addr.IPNet); ok {
  63. info.IPPrefixes = append(info.IPPrefixes, prefix)
  64. }
  65. }
  66. res = append(res, info)
  67. }
  68. return res, nil
  69. }