Skip to content

Commit

Permalink
fix(selftest): use channel for sync
Browse files Browse the repository at this point in the history
attachgenericfd and perfbuffers selftests were using a goroutine without
any syncronization mechanism.
  • Loading branch information
geyslan committed Aug 8, 2023
1 parent 0c41af2 commit c53ef37
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
15 changes: 15 additions & 0 deletions selftest/attachgenericfd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"net"
"os"
"time"
"unsafe"

bpf "github.com/aquasecurity/libbpfgo"
Expand Down Expand Up @@ -70,6 +71,8 @@ func main() {
}
}()

mapUpdateChan := make(chan struct{}, 1)

go func() {
acceptedFD, _, err := unix.Accept(serverFD)
if err != nil {
Expand All @@ -82,6 +85,8 @@ func main() {
fmt.Fprintln(os.Stderr, err)
os.Exit(-1)
}

mapUpdateChan <- struct{}{}
}()

c, err := net.Dial("tcp", "127.0.0.1:22345")
Expand All @@ -94,6 +99,16 @@ func main() {
fmt.Fprintln(os.Stderr, err)
os.Exit(-1)
}

// Wait for the bpf map to be updated
select {
case <-mapUpdateChan:
// Continue with reading data from the socket
case <-time.After(15 * time.Second): // Same of the selftest
fmt.Fprintln(os.Stderr, "bpf map timeout")
os.Exit(-1)
}

data := make([]byte, 10)
if _, err = c.Read(data); err != nil {
fmt.Fprintln(os.Stderr, err)
Expand Down
19 changes: 11 additions & 8 deletions selftest/perfbuffers/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,26 +67,29 @@ func main() {

pb.Poll(300)

numberOfEventsReceived := 0
stop := make(chan struct{})

go func() {
for {
syscall.Mmap(999, 999, 999, 1, 1)
select {
case <-stop:
return
default:
syscall.Mmap(999, 999, 999, 1, 1)
}
}
}()
recvLoop:
for {

for eReceived := 0; eReceived < 5; eReceived++ {
b := <-eventsChannel
if binary.LittleEndian.Uint32(b) != 2021 {
fmt.Fprintf(os.Stderr, "invalid data retrieved\n")
os.Exit(-1)
}
numberOfEventsReceived++
if numberOfEventsReceived > 5 {
break recvLoop
}
}

close(stop)

// Test that it won't cause a panic or block if Stop or Close called multiple times
pb.Stop()
pb.Stop()
Expand Down

0 comments on commit c53ef37

Please sign in to comment.