浏览代码

Implement ClearAndDeleteChain

Make use of the newly introduced ChainExists function to implement a
combination of ClearChain and DeleteChain that doesn't cause needless
overhead in case the chain doesn't exist.
Phil Sutter 4 年之前
父节点
当前提交
d20c681f41
共有 2 个文件被更改,包括 37 次插入0 次删除
  1. 12 0
      iptables/iptables.go
  2. 25 0
      iptables/iptables_test.go

+ 12 - 0
iptables/iptables.go

@@ -422,6 +422,18 @@ func (ipt *IPTables) DeleteChain(table, chain string) error {
 	return ipt.run("-t", table, "-X", chain)
 }
 
+func (ipt *IPTables) ClearAndDeleteChain(table, chain string) error {
+	exists, err := ipt.ChainExists(table, chain)
+	if err != nil || !exists {
+		return err
+	}
+	err = ipt.run("-t", table, "-F", chain)
+	if err == nil {
+		err = ipt.run("-t", table, "-X", chain)
+	}
+	return err
+}
+
 // ChangePolicy changes policy on chain to target
 func (ipt *IPTables) ChangePolicy(table, chain, target string) error {
 	return ipt.run("-t", table, "-P", chain, target)

+ 25 - 0
iptables/iptables_test.go

@@ -195,6 +195,31 @@ func runChainTests(t *testing.T, ipt *IPTables) {
 	} else if exists {
 		t.Fatalf("ChainExists finds non-existing chain")
 	}
+
+	// test ClearAndDelete
+	err = ipt.NewChain("filter", chain)
+	if err != nil {
+		t.Fatalf("NewChain failed: %v", err)
+	}
+	err = ipt.Append("filter", chain, "-j", "ACCEPT")
+	if err != nil {
+		t.Fatalf("Append failed: %v", err)
+	}
+	err = ipt.ClearAndDeleteChain("filter", chain)
+	if err != nil {
+		t.Fatalf("ClearAndDelete failed: %v", err)
+	}
+	exists, err = ipt.ChainExists("filter", chain)
+	if err != nil {
+		t.Fatalf("ChainExists failed: %v", err)
+	}
+	if exists {
+		t.Fatalf("ClearAndDelete didn't delete the chain")
+	}
+	err = ipt.ClearAndDeleteChain("filter", chain)
+	if err != nil {
+		t.Fatalf("ClearAndDelete failed for non-existing chain: %v", err)
+	}
 }
 
 func TestRules(t *testing.T) {