net_ip_socket.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. // readLimit is 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. }
  49. // netIPSocketLine represents the fields parsed from a single line
  50. // in /proc/net/{t,u}dp{,6}. Fields which are not used by IPSocket are skipped.
  51. // For the proc file format details, see https://linux.die.net/man/5/proc.
  52. netIPSocketLine struct {
  53. Sl uint64
  54. LocalAddr net.IP
  55. LocalPort uint64
  56. RemAddr net.IP
  57. RemPort uint64
  58. St uint64
  59. TxQueue uint64
  60. RxQueue uint64
  61. UID uint64
  62. Inode uint64
  63. }
  64. )
  65. func newNetIPSocket(file string) (NetIPSocket, error) {
  66. f, err := os.Open(file)
  67. if err != nil {
  68. return nil, err
  69. }
  70. defer f.Close()
  71. var netIPSocket NetIPSocket
  72. lr := io.LimitReader(f, readLimit)
  73. s := bufio.NewScanner(lr)
  74. s.Scan() // skip first line with headers
  75. for s.Scan() {
  76. fields := strings.Fields(s.Text())
  77. line, err := parseNetIPSocketLine(fields)
  78. if err != nil {
  79. return nil, err
  80. }
  81. netIPSocket = append(netIPSocket, line)
  82. }
  83. if err := s.Err(); err != nil {
  84. return nil, err
  85. }
  86. return netIPSocket, nil
  87. }
  88. // newNetIPSocketSummary creates a new NetIPSocket{,6} from the contents of the given file.
  89. func newNetIPSocketSummary(file string) (*NetIPSocketSummary, error) {
  90. f, err := os.Open(file)
  91. if err != nil {
  92. return nil, err
  93. }
  94. defer f.Close()
  95. var netIPSocketSummary NetIPSocketSummary
  96. lr := io.LimitReader(f, readLimit)
  97. s := bufio.NewScanner(lr)
  98. s.Scan() // skip first line with headers
  99. for s.Scan() {
  100. fields := strings.Fields(s.Text())
  101. line, err := parseNetIPSocketLine(fields)
  102. if err != nil {
  103. return nil, err
  104. }
  105. netIPSocketSummary.TxQueueLength += line.TxQueue
  106. netIPSocketSummary.RxQueueLength += line.RxQueue
  107. netIPSocketSummary.UsedSockets++
  108. }
  109. if err := s.Err(); err != nil {
  110. return nil, err
  111. }
  112. return &netIPSocketSummary, nil
  113. }
  114. // 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.
  115. func parseIP(hexIP string) (net.IP, error) {
  116. var byteIP []byte
  117. byteIP, err := hex.DecodeString(hexIP)
  118. if err != nil {
  119. return nil, fmt.Errorf("cannot parse address field in socket line %q", hexIP)
  120. }
  121. switch len(byteIP) {
  122. case 4:
  123. return net.IP{byteIP[3], byteIP[2], byteIP[1], byteIP[0]}, nil
  124. case 16:
  125. i := net.IP{
  126. byteIP[3], byteIP[2], byteIP[1], byteIP[0],
  127. byteIP[7], byteIP[6], byteIP[5], byteIP[4],
  128. byteIP[11], byteIP[10], byteIP[9], byteIP[8],
  129. byteIP[15], byteIP[14], byteIP[13], byteIP[12],
  130. }
  131. return i, nil
  132. default:
  133. return nil, fmt.Errorf("Unable to parse IP %s", hexIP)
  134. }
  135. }
  136. // parseNetIPSocketLine parses a single line, represented by a list of fields.
  137. func parseNetIPSocketLine(fields []string) (*netIPSocketLine, error) {
  138. line := &netIPSocketLine{}
  139. if len(fields) < 10 {
  140. return nil, fmt.Errorf(
  141. "cannot parse net socket line as it has less then 10 columns %q",
  142. strings.Join(fields, " "),
  143. )
  144. }
  145. var err error // parse error
  146. // sl
  147. s := strings.Split(fields[0], ":")
  148. if len(s) != 2 {
  149. return nil, fmt.Errorf("cannot parse sl field in socket line %q", fields[0])
  150. }
  151. if line.Sl, err = strconv.ParseUint(s[0], 0, 64); err != nil {
  152. return nil, fmt.Errorf("cannot parse sl value in socket line: %w", err)
  153. }
  154. // local_address
  155. l := strings.Split(fields[1], ":")
  156. if len(l) != 2 {
  157. return nil, fmt.Errorf("cannot parse local_address field in socket line %q", fields[1])
  158. }
  159. if line.LocalAddr, err = parseIP(l[0]); err != nil {
  160. return nil, err
  161. }
  162. if line.LocalPort, err = strconv.ParseUint(l[1], 16, 64); err != nil {
  163. return nil, fmt.Errorf("cannot parse local_address port value in socket line: %w", err)
  164. }
  165. // remote_address
  166. r := strings.Split(fields[2], ":")
  167. if len(r) != 2 {
  168. return nil, fmt.Errorf("cannot parse rem_address field in socket line %q", fields[1])
  169. }
  170. if line.RemAddr, err = parseIP(r[0]); err != nil {
  171. return nil, err
  172. }
  173. if line.RemPort, err = strconv.ParseUint(r[1], 16, 64); err != nil {
  174. return nil, fmt.Errorf("cannot parse rem_address port value in socket line: %w", err)
  175. }
  176. // st
  177. if line.St, err = strconv.ParseUint(fields[3], 16, 64); err != nil {
  178. return nil, fmt.Errorf("cannot parse st value in socket line: %w", err)
  179. }
  180. // tx_queue and rx_queue
  181. q := strings.Split(fields[4], ":")
  182. if len(q) != 2 {
  183. return nil, fmt.Errorf(
  184. "cannot parse tx/rx queues in socket line as it has a missing colon %q",
  185. fields[4],
  186. )
  187. }
  188. if line.TxQueue, err = strconv.ParseUint(q[0], 16, 64); err != nil {
  189. return nil, fmt.Errorf("cannot parse tx_queue value in socket line: %w", err)
  190. }
  191. if line.RxQueue, err = strconv.ParseUint(q[1], 16, 64); err != nil {
  192. return nil, fmt.Errorf("cannot parse rx_queue value in socket line: %w", err)
  193. }
  194. // uid
  195. if line.UID, err = strconv.ParseUint(fields[7], 0, 64); err != nil {
  196. return nil, fmt.Errorf("cannot parse uid value in socket line: %w", err)
  197. }
  198. // inode
  199. if line.Inode, err = strconv.ParseUint(fields[9], 0, 64); err != nil {
  200. return nil, fmt.Errorf("cannot parse inode value in socket line: %w", err)
  201. }
  202. return line, nil
  203. }