From 719f60bb914e209d4c15f11e75bfaa58198913a9 Mon Sep 17 00:00:00 2001 From: Phil Sutter Date: Wed, 5 Jul 2023 22:14:38 +0200 Subject: [PATCH] utils: iptables: Use go-iptables' ChainExists() Starting with v0.5.0, go-iptables exports a fast ChainExists() which does not rely upon listing all chains and searching the results but probes chain existence by listing its first rule. This should make a significant difference in rulesets with thousands of chains. Signed-off-by: Phil Sutter --- pkg/utils/iptables.go | 22 ++-------------------- plugins/meta/portmap/chain.go | 2 +- 2 files changed, 3 insertions(+), 21 deletions(-) diff --git a/pkg/utils/iptables.go b/pkg/utils/iptables.go index 6aec8bca..b83e6d26 100644 --- a/pkg/utils/iptables.go +++ b/pkg/utils/iptables.go @@ -29,9 +29,9 @@ func EnsureChain(ipt *iptables.IPTables, table, chain string) error { if ipt == nil { return errors.New("failed to ensure iptable chain: IPTables was nil") } - exists, err := ChainExists(ipt, table, chain) + exists, err := ipt.ChainExists(table, chain) if err != nil { - return fmt.Errorf("failed to list iptables chains: %v", err) + return fmt.Errorf("failed to check iptables chain existence: %v", err) } if !exists { err = ipt.NewChain(table, chain) @@ -45,24 +45,6 @@ func EnsureChain(ipt *iptables.IPTables, table, chain string) error { return nil } -// ChainExists checks whether an iptables chain exists. -func ChainExists(ipt *iptables.IPTables, table, chain string) (bool, error) { - if ipt == nil { - return false, errors.New("failed to check iptable chain: IPTables was nil") - } - chains, err := ipt.ListChains(table) - if err != nil { - return false, err - } - - for _, ch := range chains { - if ch == chain { - return true, nil - } - } - return false, nil -} - // DeleteRule idempotently delete the iptables rule in the specified table/chain. // It does not return an error if the referring chain doesn't exist func DeleteRule(ipt *iptables.IPTables, table, chain string, rulespec ...string) error { diff --git a/plugins/meta/portmap/chain.go b/plugins/meta/portmap/chain.go index d7b10d5a..5aad9332 100644 --- a/plugins/meta/portmap/chain.go +++ b/plugins/meta/portmap/chain.go @@ -103,7 +103,7 @@ func (c *chain) teardown(ipt *iptables.IPTables) error { // check the chain. func (c *chain) check(ipt *iptables.IPTables) error { - exists, err := utils.ChainExists(ipt, c.table, c.name) + exists, err := ipt.ChainExists(c.table, c.name) if err != nil { return err }