Skip to content

Commit 6b21e75

Browse files
committed
handle: configure package-global handle using ConfigureHandle
This commit introduces the funcion ConfigureHandle to replace the global package handle with one configured using the given HandleOptions. It can only be called once per process. Signed-off-by: Timo Beckers <timo@incline.eu>
1 parent 378a48c commit 6b21e75

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

handle_linux.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package netlink
22

33
import (
44
"fmt"
5+
"sync"
56
"sync/atomic"
67
"time"
78

@@ -13,6 +14,37 @@ import (
1314
// Empty handle used by the netlink package methods
1415
var pkgHandle = &Handle{}
1516

17+
var configMu sync.Mutex
18+
var configDone bool
19+
20+
// ConfigureHandle configures the default, package-wide netlink handle used by
21+
// the netlink package's global functions like [LinkList] and [AddrList] with
22+
// the given opts. It does not affect any existing or future [Handle] returned
23+
// by the library.
24+
//
25+
// This function is not safe to call concurrently with any netlink operations
26+
// using the global package handle. Invoke it from init() functions only.
27+
//
28+
// Returns an error if called more than once per process.
29+
func ConfigureHandle(opts HandleOptions) error {
30+
configMu.Lock()
31+
defer configMu.Unlock()
32+
33+
if configDone {
34+
return fmt.Errorf("netlink package handle already configured")
35+
}
36+
37+
h, err := NewHandleWithOptions(opts)
38+
if err != nil {
39+
return fmt.Errorf("creating handle: %w", err)
40+
}
41+
42+
configDone = true
43+
pkgHandle = h
44+
45+
return nil
46+
}
47+
1648
// HandleOptions defines the options for creating a netlink Handle, allowing the
1749
// caller to customize its behaviour.
1850
type HandleOptions struct {

handle_linux_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ package netlink
33
import (
44
"testing"
55
"time"
6+
7+
"github.com/stretchr/testify/assert"
68
)
79

810
func TestSetGetSocketTimeout(t *testing.T) {
@@ -15,3 +17,20 @@ func TestSetGetSocketTimeout(t *testing.T) {
1517
t.Fatalf("Unexpected socket timeout value: got=%v, expected=%v", val, timeout)
1618
}
1719
}
20+
21+
func TestConfigureHandle(t *testing.T) {
22+
orig := pkgHandle
23+
origDone := configDone
24+
t.Cleanup(func() {
25+
configMu.Lock()
26+
defer configMu.Unlock()
27+
28+
pkgHandle = orig
29+
configDone = origDone
30+
})
31+
32+
assert.NoError(t, ConfigureHandle(HandleOptions{DisableVFInfoCollection: true}))
33+
assert.NotEqual(t, orig, pkgHandle)
34+
assert.NoError(t, pkgHandle.Close())
35+
assert.Error(t, ConfigureHandle(HandleOptions{}))
36+
}

0 commit comments

Comments
 (0)