1717package ocihook
1818
1919import (
20+ "fmt"
21+ "os/exec"
22+ "strings"
23+
24+ cniutils "github.com/containernetworking/plugins/pkg/utils"
25+
2026 "github.com/containerd/containerd/v2/contrib/apparmor"
2127 "github.com/containerd/log"
2228
@@ -37,3 +43,51 @@ func loadAppArmor() {
3743 // but the profile was not actually loaded, runc will fail.
3844 }
3945}
46+
47+ // cleanupIptablesRules cleans up iptables rules related to the container
48+ func cleanupIptablesRules (containerID string , cniNames []string ) error {
49+ // Check if iptables command exists
50+ if _ , err := exec .LookPath ("iptables" ); err != nil {
51+ return fmt .Errorf ("iptables command not found: %w" , err )
52+ }
53+
54+ // Tables to check for rules
55+ tables := []string {"nat" , "filter" , "mangle" }
56+
57+ for _ , table := range tables {
58+ // Get all iptables rules for this table
59+ cmd := exec .Command ("iptables" , "-t" , table , "-S" )
60+ output , err := cmd .CombinedOutput ()
61+ if err != nil {
62+ log .L .WithError (err ).Warnf ("failed to list iptables rules for table %s" , table )
63+ continue
64+ }
65+
66+ // Find and delete rules related to the container
67+ rules := strings .Split (string (output ), "\n " )
68+ for _ , rule := range rules {
69+ if strings .Contains (rule , containerID ) {
70+ // Execute delete command
71+ deleteCmd := exec .Command ("sh" , "-c" , "--" , fmt .Sprintf (`iptables -t %s -D %s` , table , rule [3 :]))
72+ if deleteOutput , err := deleteCmd .CombinedOutput (); err != nil {
73+ log .L .WithError (err ).Warnf ("failed to delete iptables rule: %s, output: %s" , rule , string (deleteOutput ))
74+ } else {
75+ log .L .Debugf ("deleted iptables rule: %s" , rule )
76+ }
77+ }
78+ }
79+ }
80+
81+ // Delete CNI chains related to the container
82+ for _ , cniName := range cniNames {
83+ chain := cniutils .FormatChainName (cniName , containerID )
84+ deleteCmd := exec .Command ("iptables" , "-t" , "nat" , "-X" , chain )
85+ if deleteOutput , err := deleteCmd .CombinedOutput (); err != nil {
86+ log .L .WithError (err ).Warnf ("failed to delete iptables chain: %s, output: %s" , chain , string (deleteOutput ))
87+ } else {
88+ log .L .Debugf ("deleted iptables chain: %s" , chain )
89+ }
90+ }
91+
92+ return nil
93+ }
0 commit comments