Skip to content

Commit

Permalink
monitor: add example and documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
stapelberg committed Dec 13, 2023
1 parent 5555df3 commit 6d4c531
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
14 changes: 12 additions & 2 deletions monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ var (
1<<unix.NFT_MSG_DELOBJ,
},
}
monitorFlagsInitOnce sync.Once
)

type MonitorEventType int
Expand All @@ -110,6 +109,12 @@ const (
MonitorEventTypeOOB MonitorEventType = math.MaxInt // out of band event
)

// A MonitorEvent represents a single change received via a [Monitor].
//
// Depending on the Type, the Data field can be type-asserted to the specific
// data type for this event, e.g. when Type is
// nftables.MonitorEventTypeNewTable, you can access the corresponding table
// details via Data.(*nftables.Table).
type MonitorEvent struct {
Type MonitorEventType
Data any
Expand All @@ -121,7 +126,9 @@ const (
monitorClosed
)

// A Monitor to track actions on objects.
// A Monitor is an event-based nftables monitor that will receive one event per
// new (or deleted) table, chain, rule, set, etc., depending on the monitor
// configuration.
type Monitor struct {
action MonitorAction
object MonitorObject
Expand Down Expand Up @@ -159,6 +166,9 @@ func WithMonitorObject(object MonitorObject) MonitorOption {
}

// NewMonitor returns a Monitor with options to be started.
//
// Note that NewMonitor only prepares a Monitor. To install the monitor, call
// [Conn.AddMonitor].
func NewMonitor(opts ...MonitorOption) *Monitor {
monitor := &Monitor{
status: monitorOK,
Expand Down
24 changes: 24 additions & 0 deletions monitor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package nftables_test

import (
"fmt"
"log"
"net"
"sync"
"sync/atomic"
Expand All @@ -12,6 +13,29 @@ import (
"github.com/google/nftables/internal/nftest"
)

func ExampleNewMonitor() {
conn, err := nftables.New()
if err != nil {
log.Fatal(err)
}

mon := nftables.NewMonitor()
defer mon.Close()
events, err := conn.AddMonitor(mon)
if err != nil {
log.Fatal(err)
}
for ev := range events {
log.Printf("ev: %+v, data = %T", ev, ev.Data)
switch ev.Type {
case nftables.MonitorEventTypeNewTable:
log.Printf("data = %+v", ev.Data.(*nftables.Table))

// …more cases if needed…
}
}
}

func TestMonitor(t *testing.T) {
// Create a new network namespace to test these operations,
// and tear down the namespace at test completion.
Expand Down

0 comments on commit 6d4c531

Please sign in to comment.