Skip to content

Commit

Permalink
fix: same TCP connection appears twice
Browse files Browse the repository at this point in the history
```
TCP, TCP6, UDP, and UDP6 are dynamically changing,
and when we read these files, we should read them all at once.
there will be data consistency issues if using line by lin reading

fix: #576
```

Signed-off-by: weidongkl <weidong@uniontech.com>
  • Loading branch information
weidongkl committed Apr 9, 2024
1 parent 3387ec6 commit 4a06db8
Showing 1 changed file with 25 additions and 29 deletions.
54 changes: 25 additions & 29 deletions net_ip_socket.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@
package procfs

import (
"bufio"
"encoding/hex"
"fmt"
"io"
"net"
"os"
"strconv"
Expand Down Expand Up @@ -74,49 +72,50 @@ type (
)

func newNetIPSocket(file string) (NetIPSocket, error) {
f, err := os.Open(file)
var netIPSocket NetIPSocket
isUDP := strings.Contains(file, "udp")
content, err := os.ReadFile(file)
if err != nil {
return nil, err
}
defer f.Close()

var netIPSocket NetIPSocket
isUDP := strings.Contains(file, "udp")
lines := strings.Split(string(content), "\n")
if len(lines) < 1 {
return nil, ErrFileParse
}

lr := io.LimitReader(f, readLimit)
s := bufio.NewScanner(lr)
s.Scan() // skip first line with headers
for s.Scan() {
fields := strings.Fields(s.Text())
for _, line := range lines[1:] {
fields := strings.Fields(line)
if len(fields) == 0 {
continue
}
line, err := parseNetIPSocketLine(fields, isUDP)
if err != nil {
return nil, err
}
netIPSocket = append(netIPSocket, line)
}
if err := s.Err(); err != nil {
return nil, err
}
return netIPSocket, nil
}

// newNetIPSocketSummary creates a new NetIPSocket{,6} from the contents of the given file.
func newNetIPSocketSummary(file string) (*NetIPSocketSummary, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()

var netIPSocketSummary NetIPSocketSummary
var udpPacketDrops uint64
isUDP := strings.Contains(file, "udp")
content, err := os.ReadFile(file)
if err != nil {
return nil, err
}
lines := strings.Split(string(content), "\n")
if len(lines) < 1 {
return nil, ErrFileParse
}

lr := io.LimitReader(f, readLimit)
s := bufio.NewScanner(lr)
s.Scan() // skip first line with headers
for s.Scan() {
fields := strings.Fields(s.Text())
for _, line := range lines[1:] {
fields := strings.Fields(line)
if len(fields) == 0 {
continue
}
line, err := parseNetIPSocketLine(fields, isUDP)
if err != nil {
return nil, err
Expand All @@ -129,9 +128,6 @@ func newNetIPSocketSummary(file string) (*NetIPSocketSummary, error) {
netIPSocketSummary.Drops = &udpPacketDrops
}
}
if err := s.Err(); err != nil {
return nil, err
}
return &netIPSocketSummary, nil
}

Expand Down

0 comments on commit 4a06db8

Please sign in to comment.