ifTable.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. package snmp
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "github.com/gosnmp/gosnmp"
  7. )
  8. type PortStats struct {
  9. Index int
  10. Name string
  11. Descr string
  12. Alias string
  13. Type int
  14. // Familia de la interfaz para las NO físicas (#1125): "lag", "vlan",
  15. // "bridge", "tunnel" o "virtual". Vacío = boca física (o ifType no
  16. // reportado por walk fallido: se conserva en el grupo físico, la misma
  17. // defensa de la #1115). El frontend las agrupa colapsadas al pie de la
  18. // tarjeta de puertos en vez de ocultarlas.
  19. Family string
  20. SpeedBps uint64
  21. HighSpeedMbps uint32
  22. OperUp bool
  23. RxBytes uint64
  24. TxBytes uint64
  25. RxErrors uint64
  26. TxErrors uint64
  27. }
  28. func (p PortStats) SpeedString() string {
  29. if !p.OperUp {
  30. return ""
  31. }
  32. var bps uint64
  33. if p.HighSpeedMbps > 0 {
  34. bps = uint64(p.HighSpeedMbps) * 1_000_000
  35. } else {
  36. bps = p.SpeedBps
  37. }
  38. if bps == 0 {
  39. return ""
  40. }
  41. if bps >= 1_000_000_000 {
  42. // #1280: un decimal cuando no es múltiplo exacto de 1 Gbps. La
  43. // división entera truncaba un 2.5 GE a "2 Gbps" (ifSpeed reporta
  44. // 2500000000 y el dígito se perdía aquí).
  45. if bps%1_000_000_000 != 0 {
  46. return fmt.Sprintf("%.1f Gbps", float64(bps)/1_000_000_000)
  47. }
  48. return fmt.Sprintf("%d Gbps", bps/1_000_000_000)
  49. }
  50. if bps >= 1_000_000 {
  51. return fmt.Sprintf("%d Mbps", bps/1_000_000)
  52. }
  53. return fmt.Sprintf("%d Kbps", bps/1_000)
  54. }
  55. func (p PortStats) DisplayName() string {
  56. // #1077: algunos vendors (p.ej. TP-Link Omada) persisten un espacio en
  57. // blanco como port label y lo emiten en ifAlias; un alias vacío tras
  58. // recortar NO cuenta como etiqueta.
  59. if a := strings.TrimSpace(p.Alias); a != "" {
  60. return a
  61. }
  62. if p.Name != "" {
  63. return p.Name
  64. }
  65. if p.Descr != "" {
  66. return p.Descr
  67. }
  68. return fmt.Sprintf("port-%d", p.Index)
  69. }
  70. func PollIfTable(s *gosnmp.GoSNMP) ([]PortStats, error) {
  71. oids := []string{
  72. OidIfIndex, OidIfDescr, OidIfType, OidIfSpeed, OidIfOperStatus,
  73. OidIfInOctets, OidIfInErrors, OidIfOutOctets, OidIfOutErrors,
  74. OidIfName, OidIfHighSpeed, OidIfAlias,
  75. }
  76. byIdx := map[int]*PortStats{}
  77. for _, oid := range oids {
  78. pdus, err := walkSafe(s, oid)
  79. if err != nil {
  80. continue
  81. }
  82. for _, pdu := range pdus {
  83. idx := trailingIndex(pdu.Name, oid)
  84. if idx <= 0 {
  85. continue
  86. }
  87. ps, ok := byIdx[idx]
  88. if !ok {
  89. ps = &PortStats{Index: idx}
  90. byIdx[idx] = ps
  91. }
  92. applyPortField(ps, oid, pdu)
  93. }
  94. }
  95. out := make([]PortStats, 0, len(byIdx))
  96. for _, ps := range byIdx {
  97. ps.Family = ifFamilyFor(*ps)
  98. out = append(out, *ps)
  99. }
  100. sortByIndex(out)
  101. return out, nil
  102. }
  103. // nonPhysicalIfTypeFamilies: ifTypes (IANA) que NO son una boca física del
  104. // switch, con su familia para el grupo colapsado de la tarjeta (#1125,
  105. // alternativa a ocultarlas de la #1115: nada se pierde y las referencias
  106. // FDB/LLDP por ifIndex siguen resolviendo). Verificado en un Linksys LGS310C
  107. // real: po1-8 llegan como ieee8023adLag(161) y vlan1 como l3ipvlan(136).
  108. // Todo ifType que NO esté en el mapa (incluido Type=0 por walk fallido) se
  109. // trata como físico: la defensa por exclusión de la #1115 se conserva.
  110. var nonPhysicalIfTypeFamilies = map[int]string{
  111. 24: "virtual", // softwareLoopback
  112. 53: "virtual", // propVirtual
  113. 131: "tunnel", // tunnel
  114. 135: "vlan", // l2vlan
  115. 136: "vlan", // l3ipvlan
  116. 161: "lag", // ieee8023adLag
  117. 209: "bridge", // bridge
  118. }
  119. // ifFamily clasifica una interfaz por su ifType: "" = física (o desconocida),
  120. // en otro caso la familia del grupo virtual (#1125).
  121. func ifFamily(t int) string {
  122. return nonPhysicalIfTypeFamilies[t]
  123. }
  124. // ifTypeOther: IANA other(1). No está en el mapa a propósito (la defensa por
  125. // exclusión de #1115 lo deja como físico), pero hay un caso en que no lo es.
  126. const ifTypeOther = 1
  127. // ifFamilyFor clasifica la interfaz con lo que el walk dio de ella: el ifType
  128. // manda, y para other(1) se mira el nombre (#2009).
  129. func ifFamilyFor(ps PortStats) string {
  130. if fam := ifFamily(ps.Type); fam != "" {
  131. return fam
  132. }
  133. // #2009: los Netgear FastPath exponen la interfaz de CPU como other(1) y
  134. // con nombre inconfundible ("CPU Interface for Slot: 3 Port: 1" en
  135. // ifDescr, "CPU Interface: 3/1" en ifName). Al no estar other(1) en el
  136. // mapa pasaba el filtro de físico y sumaba un puerto fantasma al rack y
  137. // al panel de puertos. Se reconoce SOLO other(1) con nombre de CPU:
  138. // mapear other(1) en bloque rompería #1115, porque hay vendors con
  139. // puertos reales en other.
  140. if ps.Type == ifTypeOther && (looksLikeCPUInterface(ps.Name) || looksLikeCPUInterface(ps.Descr)) {
  141. return "cpu"
  142. }
  143. return ""
  144. }
  145. // looksLikeCPUInterface reconoce el nombre de una interfaz de CPU/gestión
  146. // ("CPU Interface: 0/5/1", "cpu0", "cpu/0"). No se usa como filtro suelto:
  147. // solo descarta un puerto cuando además su ifType es other(1).
  148. func looksLikeCPUInterface(s string) bool {
  149. s = strings.ToLower(strings.TrimSpace(s))
  150. if !strings.HasPrefix(s, "cpu") {
  151. return false
  152. }
  153. if len(s) == 3 {
  154. return true
  155. }
  156. switch c := s[3]; {
  157. case c == ' ' || c == '\t' || c == ':' || c == '/' || c == '-' || c == '_':
  158. return true
  159. case c >= '0' && c <= '9':
  160. return true
  161. }
  162. return false
  163. }
  164. func applyPortField(ps *PortStats, oid string, pdu gosnmp.SnmpPDU) {
  165. switch oid {
  166. case OidIfIndex:
  167. ps.Index = int(uint64Val(pdu))
  168. case OidIfDescr:
  169. ps.Descr = stringVal(pdu)
  170. case OidIfType:
  171. ps.Type = int(uint64Val(pdu))
  172. case OidIfSpeed:
  173. ps.SpeedBps = uint64Val(pdu)
  174. case OidIfOperStatus:
  175. ps.OperUp = uint64Val(pdu) == 1
  176. case OidIfInOctets:
  177. ps.RxBytes = uint64Val(pdu)
  178. case OidIfInErrors:
  179. ps.RxErrors = uint64Val(pdu)
  180. case OidIfOutOctets:
  181. ps.TxBytes = uint64Val(pdu)
  182. case OidIfOutErrors:
  183. ps.TxErrors = uint64Val(pdu)
  184. case OidIfName:
  185. ps.Name = stringVal(pdu)
  186. case OidIfHighSpeed:
  187. v := uint64Val(pdu)
  188. if v <= 0xFFFFFFFF {
  189. ps.HighSpeedMbps = uint32(v)
  190. }
  191. case OidIfAlias:
  192. // #1077: recortar siempre; un ifAlias de solo espacios (Omada guarda
  193. // el label vacío como " ") no debe ganarle al ifName en DisplayName.
  194. ps.Alias = strings.TrimSpace(stringVal(pdu))
  195. }
  196. }
  197. func walkSafe(s *gosnmp.GoSNMP, oid string) ([]gosnmp.SnmpPDU, error) {
  198. out, err := s.BulkWalkAll(oid)
  199. if err != nil {
  200. out2, err2 := s.WalkAll(oid)
  201. if err2 != nil {
  202. return nil, err
  203. }
  204. return out2, nil
  205. }
  206. return out, nil
  207. }
  208. func trailingIndex(name, prefix string) int {
  209. if !strings.HasPrefix(name, prefix+".") {
  210. return 0
  211. }
  212. suffix := name[len(prefix)+1:]
  213. if strings.Contains(suffix, ".") {
  214. return 0
  215. }
  216. n, err := strconv.Atoi(suffix)
  217. if err != nil {
  218. return 0
  219. }
  220. return n
  221. }
  222. func sortByIndex(ps []PortStats) {
  223. for i := 1; i < len(ps); i++ {
  224. for j := i; j > 0 && ps[j-1].Index > ps[j].Index; j-- {
  225. ps[j-1], ps[j] = ps[j], ps[j-1]
  226. }
  227. }
  228. }