Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

net_ip_socket.go 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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("%s: Cannot parse socket field in %q: %w", ErrFileParse, hexIP, err)
  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("%s: Unable to parse IP %s: %w", ErrFileParse, hexIP, nil)
  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. "%w: Less than 10 columns found %q",
  142. ErrFileParse,
  143. strings.Join(fields, " "),
  144. )
  145. }
  146. var err error // parse error
  147. // sl
  148. s := strings.Split(fields[0], ":")
  149. if len(s) != 2 {
  150. return nil, fmt.Errorf("%w: Unable to parse sl field in line %q", ErrFileParse, fields[0])
  151. }
  152. if line.Sl, err = strconv.ParseUint(s[0], 0, 64); err != nil {
  153. return nil, fmt.Errorf("%s: Unable to parse sl field in %q: %w", ErrFileParse, line.Sl, err)
  154. }
  155. // local_address
  156. l := strings.Split(fields[1], ":")
  157. if len(l) != 2 {
  158. return nil, fmt.Errorf("%w: Unable to parse local_address field in %q", ErrFileParse, fields[1])
  159. }
  160. if line.LocalAddr, err = parseIP(l[0]); err != nil {
  161. return nil, err
  162. }
  163. if line.LocalPort, err = strconv.ParseUint(l[1], 16, 64); err != nil {
  164. return nil, fmt.Errorf("%s: Unable to parse local_address port value line %q: %w", ErrFileParse, line.LocalPort, err)
  165. }
  166. // remote_address
  167. r := strings.Split(fields[2], ":")
  168. if len(r) != 2 {
  169. return nil, fmt.Errorf("%w: Unable to parse rem_address field in %q", ErrFileParse, fields[1])
  170. }
  171. if line.RemAddr, err = parseIP(r[0]); err != nil {
  172. return nil, err
  173. }
  174. if line.RemPort, err = strconv.ParseUint(r[1], 16, 64); err != nil {
  175. return nil, fmt.Errorf("%s: Cannot parse rem_address port value in %q: %w", ErrFileParse, line.RemPort, err)
  176. }
  177. // st
  178. if line.St, err = strconv.ParseUint(fields[3], 16, 64); err != nil {
  179. return nil, fmt.Errorf("%s: Cannot parse st value in %q: %w", ErrFileParse, line.St, err)
  180. }
  181. // tx_queue and rx_queue
  182. q := strings.Split(fields[4], ":")
  183. if len(q) != 2 {
  184. return nil, fmt.Errorf(
  185. "%w: Missing colon for tx/rx queues in socket line %q",
  186. ErrFileParse,
  187. fields[4],
  188. )
  189. }
  190. if line.TxQueue, err = strconv.ParseUint(q[0], 16, 64); err != nil {
  191. return nil, fmt.Errorf("%s: Cannot parse tx_queue value in %q: %w", ErrFileParse, line.TxQueue, err)
  192. }
  193. if line.RxQueue, err = strconv.ParseUint(q[1], 16, 64); err != nil {
  194. return nil, fmt.Errorf("%s: Cannot parse trx_queue value in %q: %w", ErrFileParse, line.RxQueue, err)
  195. }
  196. // uid
  197. if line.UID, err = strconv.ParseUint(fields[7], 0, 64); err != nil {
  198. return nil, fmt.Errorf("%s: Cannot parse UID value in %q: %w", ErrFileParse, line.UID, err)
  199. }
  200. // inode
  201. if line.Inode, err = strconv.ParseUint(fields[9], 0, 64); err != nil {
  202. return nil, fmt.Errorf("%s: Cannot parse inode value in %q: %w", ErrFileParse, line.Inode, err)
  203. }
  204. return line, nil
  205. }