monitor: add example and documentation
This commit is contained in:
parent
5555df300c
commit
6d4c531bb6
14
monitor.go
14
monitor.go
|
@ -89,7 +89,6 @@ var (
|
|||
1<<unix.NFT_MSG_DELOBJ,
|
||||
},
|
||||
}
|
||||
monitorFlagsInitOnce sync.Once
|
||||
)
|
||||
|
||||
type MonitorEventType int
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
@ -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,
|
||||
|
|
|
@ -2,6 +2,7 @@ package nftables_test
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
@ -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.
|
||||
|
|
Loading…
Reference in New Issue