// Copyright 2020 The Prometheus Authors// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.package procfsimport ()const (// Maximum size limit used by io.LimitReader while reading the content of the // /proc/net/udp{,6} files. The number of lines inside such a file is dynamic // as each line represents a single used socket. // In theory, the number of available sockets is 65535 (2^16 - 1) per IP. // With e.g. 150 Byte per line and the maximum number of 65535, // the reader needs to handle 150 Byte * 65535 =~ 10 MB for a single IP. readLimit = 4294967296// Byte -> 4 GiB)// This contains generic data structures for both udp and tcp sockets.type (// NetIPSocket represents the contents of /proc/net/{t,u}dp{,6} file without the header.NetIPSocket []*netIPSocketLine// NetIPSocketSummary provides already computed values like the total queue lengths or // the total number of used sockets. In contrast to NetIPSocket it does not collect // the parsed lines into a slice.NetIPSocketSummarystruct {// TxQueueLength shows the total queue length of all parsed tx_queue lengths. TxQueueLength uint64// RxQueueLength shows the total queue length of all parsed rx_queue lengths. RxQueueLength uint64// UsedSockets shows the total number of parsed lines representing the // number of used sockets. UsedSockets uint64// Drops shows the total number of dropped packets of all UDP sockets. Drops *uint64 }// A single line parser for fields from /proc/net/{t,u}dp{,6}. // Fields which are not used by IPSocket are skipped. // Drops is non-nil for udp{,6}, but nil for tcp{,6}. // For the proc file format details, see https://linux.die.net/man/5/proc. netIPSocketLine struct { Sl uint64 LocalAddr net.IP LocalPort uint64 RemAddr net.IP RemPort uint64 St uint64 TxQueue uint64 RxQueue uint64 UID uint64 Inode uint64 Drops *uint64 })func newNetIPSocket( string) (NetIPSocket, error) { , := os.Open()if != nil {returnnil, }defer .Close()varNetIPSocket := strings.Contains(, "udp") := io.LimitReader(, readLimit) := bufio.NewScanner() .Scan() // skip first line with headersfor .Scan() { := strings.Fields(.Text()) , := parseNetIPSocketLine(, )if != nil {returnnil, } = append(, ) }if := .Err(); != nil {returnnil, }return , nil}// newNetIPSocketSummary creates a new NetIPSocket{,6} from the contents of the given file.func newNetIPSocketSummary( string) (*NetIPSocketSummary, error) { , := os.Open()if != nil {returnnil, }defer .Close()varNetIPSocketSummaryvaruint64 := strings.Contains(, "udp") := io.LimitReader(, readLimit) := bufio.NewScanner() .Scan() // skip first line with headersfor .Scan() { := strings.Fields(.Text()) , := parseNetIPSocketLine(, )if != nil {returnnil, } .TxQueueLength += .TxQueue .RxQueueLength += .RxQueue .UsedSockets++if { += *.Drops .Drops = & } }if := .Err(); != nil {returnnil, }return &, nil}// 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.func parseIP( string) (net.IP, error) {var []byte , := hex.DecodeString()if != nil {returnnil, fmt.Errorf("%w: Cannot parse socket field in %q: %w", ErrFileParse, , ) }switchlen() {case4:returnnet.IP{[3], [2], [1], [0]}, nilcase16: := net.IP{ [3], [2], [1], [0], [7], [6], [5], [4], [11], [10], [9], [8], [15], [14], [13], [12], }return , nildefault:returnnil, fmt.Errorf("%w: Unable to parse IP %s: %v", ErrFileParse, , nil) }}// parseNetIPSocketLine parses a single line, represented by a list of fields.func parseNetIPSocketLine( []string, bool) (*netIPSocketLine, error) { := &netIPSocketLine{}iflen() < 10 {returnnil, fmt.Errorf("%w: Less than 10 columns found %q",ErrFileParse,strings.Join(, " "), ) }varerror// parse error// sl := strings.Split([0], ":")iflen() != 2 {returnnil, fmt.Errorf("%w: Unable to parse sl field in line %q", ErrFileParse, [0]) }if .Sl, = strconv.ParseUint([0], 0, 64); != nil {returnnil, fmt.Errorf("%w: Unable to parse sl field in %q: %w", ErrFileParse, .Sl, ) }// local_address := strings.Split([1], ":")iflen() != 2 {returnnil, fmt.Errorf("%w: Unable to parse local_address field in %q", ErrFileParse, [1]) }if .LocalAddr, = parseIP([0]); != nil {returnnil, }if .LocalPort, = strconv.ParseUint([1], 16, 64); != nil {returnnil, fmt.Errorf("%w: Unable to parse local_address port value line %q: %w", ErrFileParse, .LocalPort, ) }// remote_address := strings.Split([2], ":")iflen() != 2 {returnnil, fmt.Errorf("%w: Unable to parse rem_address field in %q", ErrFileParse, [1]) }if .RemAddr, = parseIP([0]); != nil {returnnil, }if .RemPort, = strconv.ParseUint([1], 16, 64); != nil {returnnil, fmt.Errorf("%w: Cannot parse rem_address port value in %q: %w", ErrFileParse, .RemPort, ) }// stif .St, = strconv.ParseUint([3], 16, 64); != nil {returnnil, fmt.Errorf("%w: Cannot parse st value in %q: %w", ErrFileParse, .St, ) }// tx_queue and rx_queue := strings.Split([4], ":")iflen() != 2 {returnnil, fmt.Errorf("%w: Missing colon for tx/rx queues in socket line %q",ErrFileParse, [4], ) }if .TxQueue, = strconv.ParseUint([0], 16, 64); != nil {returnnil, fmt.Errorf("%w: Cannot parse tx_queue value in %q: %w", ErrFileParse, .TxQueue, ) }if .RxQueue, = strconv.ParseUint([1], 16, 64); != nil {returnnil, fmt.Errorf("%w: Cannot parse trx_queue value in %q: %w", ErrFileParse, .RxQueue, ) }// uidif .UID, = strconv.ParseUint([7], 0, 64); != nil {returnnil, fmt.Errorf("%w: Cannot parse UID value in %q: %w", ErrFileParse, .UID, ) }// inodeif .Inode, = strconv.ParseUint([9], 0, 64); != nil {returnnil, fmt.Errorf("%w: Cannot parse inode value in %q: %w", ErrFileParse, .Inode, ) }// dropsif { , := strconv.ParseUint([12], 0, 64)if != nil {returnnil, fmt.Errorf("%w: Cannot parse drops value in %q: %w", ErrFileParse, , ) } .Drops = & }return , nil}
The pages are generated with Goldsv0.8.2. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.