func()

in controllers/daemon/staticgatewayconfiguration_controller.go [997:1034]


func (r *StaticGatewayConfigurationReconciler) removeIPTablesChains(
	ctx context.Context,
	table utiliptables.Table,
	targetChains []utiliptables.Chain,
	sourceChains []utiliptables.Chain,
	jumpRuleComments []string,
) error {
	log := log.FromContext(ctx)

	iptablesData := bytes.NewBuffer(nil)
	if err := r.IPTables.SaveInto(table, iptablesData); err != nil {
		return fmt.Errorf("failed to save iptables data for table %s: %w", table, err)
	}

	existingChains := utiliptables.GetChainsFromTable(iptablesData.Bytes())
	for i, targetChain := range targetChains {
		sourceChain := sourceChains[i]
		jumpRuleComment := jumpRuleComments[i]
		if _, ok := existingChains[targetChain]; ok {
			// delete jump rule first
			log.Info("Deleting jump rule", "source chain", sourceChain, "target chain", targetChain)
			if err := r.IPTables.DeleteRule(table, sourceChain, "-m", "comment", "--comment", jumpRuleComment, "-j", string(targetChain)); err != nil {
				return fmt.Errorf("failed to delete jump rule from chain %s to chain %s in table %s: %w", sourceChain, targetChain, table, err)
			}

			log.Info("Flushing and deleting chain", "table", table, "target chain", targetChain)
			lines := bytes.NewBuffer(nil)
			writeLine(lines, "*"+string(table))
			writeLine(lines, utiliptables.MakeChainLine(targetChain))
			writeLine(lines, "-X", string(targetChain))
			writeLine(lines, "COMMIT")
			if err := r.IPTables.Restore(table, lines.Bytes(), utiliptables.NoFlushTables, utiliptables.NoRestoreCounters); err != nil {
				return fmt.Errorf("failed to restore iptables table %s: %w", table, err)
			}
		}
	}
	return nil
}