blob: 19e3378f72d78d7b93d02412befa89d7b5ddc797 [file] [log] [blame]
khenaidoo26721882021-08-11 17:42:52 -04001// 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
14package procfs
15
16import (
17 "bufio"
18 "encoding/hex"
19 "fmt"
20 "io"
21 "net"
22 "os"
23 "strconv"
24 "strings"
25)
26
27const (
Abhay Kumar40252eb2025-10-13 13:25:53 +000028 // Maximum size limit used by io.LimitReader while reading the content of the
khenaidoo26721882021-08-11 17:42:52 -040029 // /proc/net/udp{,6} files. The number of lines inside such a file is dynamic
30 // as each line represents a single used socket.
31 // In theory, the number of available sockets is 65535 (2^16 - 1) per IP.
32 // With e.g. 150 Byte per line and the maximum number of 65535,
33 // the reader needs to handle 150 Byte * 65535 =~ 10 MB for a single IP.
34 readLimit = 4294967296 // Byte -> 4 GiB
35)
36
Abhay Kumar40252eb2025-10-13 13:25:53 +000037// This contains generic data structures for both udp and tcp sockets.
khenaidoo26721882021-08-11 17:42:52 -040038type (
39 // NetIPSocket represents the contents of /proc/net/{t,u}dp{,6} file without the header.
40 NetIPSocket []*netIPSocketLine
41
42 // NetIPSocketSummary provides already computed values like the total queue lengths or
43 // the total number of used sockets. In contrast to NetIPSocket it does not collect
44 // the parsed lines into a slice.
45 NetIPSocketSummary struct {
46 // TxQueueLength shows the total queue length of all parsed tx_queue lengths.
47 TxQueueLength uint64
48 // RxQueueLength shows the total queue length of all parsed rx_queue lengths.
49 RxQueueLength uint64
50 // UsedSockets shows the total number of parsed lines representing the
51 // number of used sockets.
52 UsedSockets uint64
Abhay Kumar40252eb2025-10-13 13:25:53 +000053 // Drops shows the total number of dropped packets of all UDP sockets.
54 Drops *uint64
khenaidoo26721882021-08-11 17:42:52 -040055 }
56
Abhay Kumar40252eb2025-10-13 13:25:53 +000057 // A single line parser for fields from /proc/net/{t,u}dp{,6}.
58 // Fields which are not used by IPSocket are skipped.
59 // Drops is non-nil for udp{,6}, but nil for tcp{,6}.
khenaidoo26721882021-08-11 17:42:52 -040060 // For the proc file format details, see https://linux.die.net/man/5/proc.
61 netIPSocketLine struct {
62 Sl uint64
63 LocalAddr net.IP
64 LocalPort uint64
65 RemAddr net.IP
66 RemPort uint64
67 St uint64
68 TxQueue uint64
69 RxQueue uint64
70 UID uint64
Abhay Kumar40252eb2025-10-13 13:25:53 +000071 Inode uint64
72 Drops *uint64
khenaidoo26721882021-08-11 17:42:52 -040073 }
74)
75
76func newNetIPSocket(file string) (NetIPSocket, error) {
77 f, err := os.Open(file)
78 if err != nil {
79 return nil, err
80 }
81 defer f.Close()
82
83 var netIPSocket NetIPSocket
Abhay Kumar40252eb2025-10-13 13:25:53 +000084 isUDP := strings.Contains(file, "udp")
khenaidoo26721882021-08-11 17:42:52 -040085
86 lr := io.LimitReader(f, readLimit)
87 s := bufio.NewScanner(lr)
88 s.Scan() // skip first line with headers
89 for s.Scan() {
90 fields := strings.Fields(s.Text())
Abhay Kumar40252eb2025-10-13 13:25:53 +000091 line, err := parseNetIPSocketLine(fields, isUDP)
khenaidoo26721882021-08-11 17:42:52 -040092 if err != nil {
93 return nil, err
94 }
95 netIPSocket = append(netIPSocket, line)
96 }
97 if err := s.Err(); err != nil {
98 return nil, err
99 }
100 return netIPSocket, nil
101}
102
103// newNetIPSocketSummary creates a new NetIPSocket{,6} from the contents of the given file.
104func newNetIPSocketSummary(file string) (*NetIPSocketSummary, error) {
105 f, err := os.Open(file)
106 if err != nil {
107 return nil, err
108 }
109 defer f.Close()
110
111 var netIPSocketSummary NetIPSocketSummary
Abhay Kumar40252eb2025-10-13 13:25:53 +0000112 var udpPacketDrops uint64
113 isUDP := strings.Contains(file, "udp")
khenaidoo26721882021-08-11 17:42:52 -0400114
115 lr := io.LimitReader(f, readLimit)
116 s := bufio.NewScanner(lr)
117 s.Scan() // skip first line with headers
118 for s.Scan() {
119 fields := strings.Fields(s.Text())
Abhay Kumar40252eb2025-10-13 13:25:53 +0000120 line, err := parseNetIPSocketLine(fields, isUDP)
khenaidoo26721882021-08-11 17:42:52 -0400121 if err != nil {
122 return nil, err
123 }
124 netIPSocketSummary.TxQueueLength += line.TxQueue
125 netIPSocketSummary.RxQueueLength += line.RxQueue
126 netIPSocketSummary.UsedSockets++
Abhay Kumar40252eb2025-10-13 13:25:53 +0000127 if isUDP {
128 udpPacketDrops += *line.Drops
129 netIPSocketSummary.Drops = &udpPacketDrops
130 }
khenaidoo26721882021-08-11 17:42:52 -0400131 }
132 if err := s.Err(); err != nil {
133 return nil, err
134 }
135 return &netIPSocketSummary, nil
136}
137
138// 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.
139
140func parseIP(hexIP string) (net.IP, error) {
141 var byteIP []byte
142 byteIP, err := hex.DecodeString(hexIP)
143 if err != nil {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000144 return nil, fmt.Errorf("%w: Cannot parse socket field in %q: %w", ErrFileParse, hexIP, err)
khenaidoo26721882021-08-11 17:42:52 -0400145 }
146 switch len(byteIP) {
147 case 4:
148 return net.IP{byteIP[3], byteIP[2], byteIP[1], byteIP[0]}, nil
149 case 16:
150 i := net.IP{
151 byteIP[3], byteIP[2], byteIP[1], byteIP[0],
152 byteIP[7], byteIP[6], byteIP[5], byteIP[4],
153 byteIP[11], byteIP[10], byteIP[9], byteIP[8],
154 byteIP[15], byteIP[14], byteIP[13], byteIP[12],
155 }
156 return i, nil
157 default:
Abhay Kumar40252eb2025-10-13 13:25:53 +0000158 return nil, fmt.Errorf("%w: Unable to parse IP %s: %v", ErrFileParse, hexIP, nil)
khenaidoo26721882021-08-11 17:42:52 -0400159 }
160}
161
162// parseNetIPSocketLine parses a single line, represented by a list of fields.
Abhay Kumar40252eb2025-10-13 13:25:53 +0000163func parseNetIPSocketLine(fields []string, isUDP bool) (*netIPSocketLine, error) {
khenaidoo26721882021-08-11 17:42:52 -0400164 line := &netIPSocketLine{}
Abhay Kumar40252eb2025-10-13 13:25:53 +0000165 if len(fields) < 10 {
khenaidoo26721882021-08-11 17:42:52 -0400166 return nil, fmt.Errorf(
Abhay Kumar40252eb2025-10-13 13:25:53 +0000167 "%w: Less than 10 columns found %q",
168 ErrFileParse,
khenaidoo26721882021-08-11 17:42:52 -0400169 strings.Join(fields, " "),
170 )
171 }
172 var err error // parse error
173
174 // sl
175 s := strings.Split(fields[0], ":")
176 if len(s) != 2 {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000177 return nil, fmt.Errorf("%w: Unable to parse sl field in line %q", ErrFileParse, fields[0])
khenaidoo26721882021-08-11 17:42:52 -0400178 }
179
180 if line.Sl, err = strconv.ParseUint(s[0], 0, 64); err != nil {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000181 return nil, fmt.Errorf("%w: Unable to parse sl field in %q: %w", ErrFileParse, line.Sl, err)
khenaidoo26721882021-08-11 17:42:52 -0400182 }
183 // local_address
184 l := strings.Split(fields[1], ":")
185 if len(l) != 2 {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000186 return nil, fmt.Errorf("%w: Unable to parse local_address field in %q", ErrFileParse, fields[1])
khenaidoo26721882021-08-11 17:42:52 -0400187 }
188 if line.LocalAddr, err = parseIP(l[0]); err != nil {
189 return nil, err
190 }
191 if line.LocalPort, err = strconv.ParseUint(l[1], 16, 64); err != nil {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000192 return nil, fmt.Errorf("%w: Unable to parse local_address port value line %q: %w", ErrFileParse, line.LocalPort, err)
khenaidoo26721882021-08-11 17:42:52 -0400193 }
194
195 // remote_address
196 r := strings.Split(fields[2], ":")
197 if len(r) != 2 {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000198 return nil, fmt.Errorf("%w: Unable to parse rem_address field in %q", ErrFileParse, fields[1])
khenaidoo26721882021-08-11 17:42:52 -0400199 }
200 if line.RemAddr, err = parseIP(r[0]); err != nil {
201 return nil, err
202 }
203 if line.RemPort, err = strconv.ParseUint(r[1], 16, 64); err != nil {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000204 return nil, fmt.Errorf("%w: Cannot parse rem_address port value in %q: %w", ErrFileParse, line.RemPort, err)
khenaidoo26721882021-08-11 17:42:52 -0400205 }
206
207 // st
208 if line.St, err = strconv.ParseUint(fields[3], 16, 64); err != nil {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000209 return nil, fmt.Errorf("%w: Cannot parse st value in %q: %w", ErrFileParse, line.St, err)
khenaidoo26721882021-08-11 17:42:52 -0400210 }
211
212 // tx_queue and rx_queue
213 q := strings.Split(fields[4], ":")
214 if len(q) != 2 {
215 return nil, fmt.Errorf(
Abhay Kumar40252eb2025-10-13 13:25:53 +0000216 "%w: Missing colon for tx/rx queues in socket line %q",
217 ErrFileParse,
khenaidoo26721882021-08-11 17:42:52 -0400218 fields[4],
219 )
220 }
221 if line.TxQueue, err = strconv.ParseUint(q[0], 16, 64); err != nil {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000222 return nil, fmt.Errorf("%w: Cannot parse tx_queue value in %q: %w", ErrFileParse, line.TxQueue, err)
khenaidoo26721882021-08-11 17:42:52 -0400223 }
224 if line.RxQueue, err = strconv.ParseUint(q[1], 16, 64); err != nil {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000225 return nil, fmt.Errorf("%w: Cannot parse trx_queue value in %q: %w", ErrFileParse, line.RxQueue, err)
khenaidoo26721882021-08-11 17:42:52 -0400226 }
227
228 // uid
229 if line.UID, err = strconv.ParseUint(fields[7], 0, 64); err != nil {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000230 return nil, fmt.Errorf("%w: Cannot parse UID value in %q: %w", ErrFileParse, line.UID, err)
231 }
232
233 // inode
234 if line.Inode, err = strconv.ParseUint(fields[9], 0, 64); err != nil {
235 return nil, fmt.Errorf("%w: Cannot parse inode value in %q: %w", ErrFileParse, line.Inode, err)
236 }
237
238 // drops
239 if isUDP {
240 drops, err := strconv.ParseUint(fields[12], 0, 64)
241 if err != nil {
242 return nil, fmt.Errorf("%w: Cannot parse drops value in %q: %w", ErrFileParse, drops, err)
243 }
244 line.Drops = &drops
khenaidoo26721882021-08-11 17:42:52 -0400245 }
246
247 return line, nil
248}