net_ip_socket.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Copyright 2020 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package procfs
  14. import (
  15. "bufio"
  16. "encoding/hex"
  17. "fmt"
  18. "io"
  19. "net"
  20. "os"
  21. "strconv"
  22. "strings"
  23. )
  24. const (
  25. // Maximum size limit used by io.LimitReader while reading the content of the
  26. // /proc/net/udp{,6} files. The number of lines inside such a file is dynamic
  27. // as each line represents a single used socket.
  28. // In theory, the number of available sockets is 65535 (2^16 - 1) per IP.
  29. // With e.g. 150 Byte per line and the maximum number of 65535,
  30. // the reader needs to handle 150 Byte * 65535 =~ 10 MB for a single IP.
  31. readLimit = 4294967296 // Byte -> 4 GiB
  32. )
  33. // This contains generic data structures for both udp and tcp sockets.
  34. type (
  35. // NetIPSocket represents the contents of /proc/net/{t,u}dp{,6} file without the header.
  36. NetIPSocket []*netIPSocketLine
  37. // NetIPSocketSummary provides already computed values like the total queue lengths or
  38. // the total number of used sockets. In contrast to NetIPSocket it does not collect
  39. // the parsed lines into a slice.
  40. NetIPSocketSummary struct {
  41. // TxQueueLength shows the total queue length of all parsed tx_queue lengths.
  42. TxQueueLength uint64
  43. // RxQueueLength shows the total queue length of all parsed rx_queue lengths.
  44. RxQueueLength uint64
  45. // UsedSockets shows the total number of parsed lines representing the
  46. // number of used sockets.
  47. UsedSockets uint64
  48. // Drops shows the total number of dropped packets of all UDP sockets.
  49. Drops *uint64
  50. }
  51. // A single line parser for fields from /proc/net/{t,u}dp{,6}.
  52. // Fields which are not used by IPSocket are skipped.
  53. // Drops is non-nil for udp{,6}, but nil for tcp{,6}.
  54. // For the proc file format details, see https://linux.die.net/man/5/proc.
  55. netIPSocketLine struct {
  56. Sl uint64
  57. LocalAddr net.IP
  58. LocalPort uint64
  59. RemAddr net.IP
  60. RemPort uint64
  61. St uint64
  62. TxQueue uint64
  63. RxQueue uint64
  64. UID uint64
  65. Inode uint64
  66. Drops *uint64
  67. }
  68. )
  69. func newNetIPSocket(file string) (NetIPSocket, error) {
  70. f, err := os.Open(file)
  71. if err != nil {
  72. return nil, err
  73. }
  74. defer f.Close()
  75. var netIPSocket NetIPSocket
  76. isUDP := strings.Contains(file, "udp")
  77. lr := io.LimitReader(f, readLimit)
  78. s := bufio.NewScanner(lr)
  79. s.Scan() // skip first line with headers
  80. for s.Scan() {
  81. fields := strings.Fields(s.Text())
  82. line, err := parseNetIPSocketLine(fields, isUDP)
  83. if err != nil {
  84. return nil, err
  85. }
  86. netIPSocket = append(netIPSocket, line)
  87. }
  88. if err := s.Err(); err != nil {
  89. return nil, err
  90. }
  91. return netIPSocket, nil
  92. }
  93. // newNetIPSocketSummary creates a new NetIPSocket{,6} from the contents of the given file.
  94. func newNetIPSocketSummary(file string) (*NetIPSocketSummary, error) {
  95. f, err := os.Open(file)
  96. if err != nil {
  97. return nil, err
  98. }
  99. defer f.Close()
  100. var netIPSocketSummary NetIPSocketSummary
  101. var udpPacketDrops uint64
  102. isUDP := strings.Contains(file, "udp")
  103. lr := io.LimitReader(f, readLimit)
  104. s := bufio.NewScanner(lr)
  105. s.Scan() // skip first line with headers
  106. for s.Scan() {
  107. fields := strings.Fields(s.Text())
  108. line, err := parseNetIPSocketLine(fields, isUDP)
  109. if err != nil {
  110. return nil, err
  111. }
  112. netIPSocketSummary.TxQueueLength += line.TxQueue
  113. netIPSocketSummary.RxQueueLength += line.RxQueue
  114. netIPSocketSummary.UsedSockets++
  115. if isUDP {
  116. udpPacketDrops += *line.Drops
  117. netIPSocketSummary.Drops = &udpPacketDrops
  118. }
  119. }
  120. if err := s.Err(); err != nil {
  121. return nil, err
  122. }
  123. return &netIPSocketSummary, nil
  124. }
  125. // the /proc/net/{t,u}dp{,6} files are network byte order for ipv4 and for ipv6 the address is four words consisting of four bytes each. In each of those four words the four bytes are written in reverse order.
  126. func parseIP(hexIP string) (net.IP, error) {
  127. var byteIP []byte
  128. byteIP, err := hex.DecodeString(hexIP)
  129. if err != nil {
  130. return nil, fmt.Errorf("%w: Cannot parse socket field in %q: %w", ErrFileParse, hexIP, err)
  131. }
  132. switch len(byteIP) {
  133. case 4:
  134. return net.IP{byteIP[3], byteIP[2], byteIP[1], byteIP[0]}, nil
  135. case 16:
  136. i := net.IP{
  137. byteIP[3], byteIP[2], byteIP[1], byteIP[0],
  138. byteIP[7], byteIP[6], byteIP[5], byteIP[4],
  139. byteIP[11], byteIP[10], byteIP[9], byteIP[8],
  140. byteIP[15], byteIP[14], byteIP[13], byteIP[12],
  141. }
  142. return i, nil
  143. default:
  144. return nil, fmt.Errorf("%w: Unable to parse IP %s: %v", ErrFileParse, hexIP, nil)
  145. }
  146. }
  147. // parseNetIPSocketLine parses a single line, represented by a list of fields.
  148. func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error) {
  149. line := &netIPSocketLine{}
  150. if len(fields) < 10 {
  151. return nil, fmt.Errorf(
  152. "%w: Less than 10 columns found %q",
  153. ErrFileParse,
  154. strings.Join(fields, " "),
  155. )
  156. }
  157. var err error // parse error
  158. // sl
  159. s := strings.Split(fields[0], ":")
  160. if len(s) != 2 {
  161. return nil, fmt.Errorf("%w: Unable to parse sl field in line %q", ErrFileParse, fields[0])
  162. }
  163. if line.Sl, err = strconv.ParseUint(s[0], 0, 64); err != nil {
  164. return nil, fmt.Errorf("%w: Unable to parse sl field in %q: %w", ErrFileParse, line.Sl, err)
  165. }
  166. // local_address
  167. l := strings.Split(fields[1], ":")
  168. if len(l) != 2 {
  169. return nil, fmt.Errorf("%w: Unable to parse local_address field in %q", ErrFileParse, fields[1])
  170. }
  171. if line.LocalAddr, err = parseIP(l[0]); err != nil {
  172. return nil, err
  173. }
  174. if line.LocalPort, err = strconv.ParseUint(l[1], 16, 64); err != nil {
  175. return nil, fmt.Errorf("%w: Unable to parse local_address port value line %q: %w", ErrFileParse, line.LocalPort, err)
  176. }
  177. // remote_address
  178. r := strings.Split(fields[2], ":")
  179. if len(r) != 2 {
  180. return nil, fmt.Errorf("%w: Unable to parse rem_address field in %q", ErrFileParse, fields[1])
  181. }
  182. if line.RemAddr, err = parseIP(r[0]); err != nil {
  183. return nil, err
  184. }
  185. if line.RemPort, err = strconv.ParseUint(r[1], 16, 64); err != nil {
  186. return nil, fmt.Errorf("%w: Cannot parse rem_address port value in %q: %w", ErrFileParse, line.RemPort, err)
  187. }
  188. // st
  189. if line.St, err = strconv.ParseUint(fields[3], 16, 64); err != nil {
  190. return nil, fmt.Errorf("%w: Cannot parse st value in %q: %w", ErrFileParse, line.St, err)
  191. }
  192. // tx_queue and rx_queue
  193. q := strings.Split(fields[4], ":")
  194. if len(q) != 2 {
  195. return nil, fmt.Errorf(
  196. "%w: Missing colon for tx/rx queues in socket line %q",
  197. ErrFileParse,
  198. fields[4],
  199. )
  200. }
  201. if line.TxQueue, err = strconv.ParseUint(q[0], 16, 64); err != nil {
  202. return nil, fmt.Errorf("%w: Cannot parse tx_queue value in %q: %w", ErrFileParse, line.TxQueue, err)
  203. }
  204. if line.RxQueue, err = strconv.ParseUint(q[1], 16, 64); err != nil {
  205. return nil, fmt.Errorf("%w: Cannot parse trx_queue value in %q: %w", ErrFileParse, line.RxQueue, err)
  206. }
  207. // uid
  208. if line.UID, err = strconv.ParseUint(fields[7], 0, 64); err != nil {
  209. return nil, fmt.Errorf("%w: Cannot parse UID value in %q: %w", ErrFileParse, line.UID, err)
  210. }
  211. // inode
  212. if line.Inode, err = strconv.ParseUint(fields[9], 0, 64); err != nil {
  213. return nil, fmt.Errorf("%w: Cannot parse inode value in %q: %w", ErrFileParse, line.Inode, err)
  214. }
  215. // drops
  216. if isUDP {
  217. drops, err := strconv.ParseUint(fields[12], 0, 64)
  218. if err != nil {
  219. return nil, fmt.Errorf("%w: Cannot parse drops value in %q: %w", ErrFileParse, drops, err)
  220. }
  221. line.Drops = &drops
  222. }
  223. return line, nil
  224. }