//将table中所有来自srcChain链中的数据包跳转到dstChain链中
type iptablesJumpChain struct {
table utiliptables.Table //iptables的表
dstChain utiliptables.Chain //需要创建的chain的名字
srcChain utiliptables.Chain //需要进行判定的chain的名字
comment string //添加的注释
extraArgs []string //额外的参数
}
var iptablesJumpChains = []iptablesJumpChain{
{utiliptables.TableFilter, kubeExternalServicesChain, utiliptables.ChainInput, "kubernetes externally-visible service portals", []string{"-m", "conntrack", "--ctstate", "NEW"}},
{utiliptables.TableFilter, kubeExternalServicesChain, utiliptables.ChainForward, "kubernetes externally-visible service portals", []string{"-m", "conntrack", "--ctstate", "NEW"}},
{utiliptables.TableFilter, kubeNodePortsChain, utiliptables.ChainInput, "kubernetes health check service ports", nil},
{utiliptables.TableFilter, kubeServicesChain, utiliptables.ChainForward, "kubernetes service portals", []string{"-m", "conntrack", "--ctstate", "NEW"}},
{utiliptables.TableFilter, kubeServicesChain, utiliptables.ChainOutput, "kubernetes service portals", []string{"-m", "conntrack", "--ctstate", "NEW"}},
{utiliptables.TableFilter, kubeForwardChain, utiliptables.ChainForward, "kubernetes forwarding rules", nil},
{utiliptables.TableNAT, kubeServicesChain, utiliptables.ChainOutput, "kubernetes service portals", nil},
{utiliptables.TableNAT, kubeServicesChain, utiliptables.ChainPrerouting, "kubernetes service portals", nil},
{utiliptables.TableNAT, kubePostroutingChain, utiliptables.ChainPostrouting, "kubernetes postrouting rules", nil},
}
//对k8s相关链添加和创建rule
for _, jump := range iptablesJumpChains {
//执行 iptables -N dstChain链名 -t 表名 额外的参数
//比如 iptables -N KUBE-EXTERNAL-SERVICES -t filter -m conntrack ctstate NEW
if _, err := proxier.iptables.EnsureChain(jump.table, jump.dstChain); err != nil {
klog.ErrorS(err, "Failed to ensure chain exists", "table", jump.table, "chain", jump.dstChain)
return
}
args := append(jump.extraArgs,
"-m", "comment", "--comment", jump.comment,
"-j", string(jump.dstChain),
)
//为相应的链编写规则,并规定跳转链 执行 iptables -I srcChain链名 -t 表名 额外的参数 -m comment --comment 注释 -j 跳转的dstChain名
//比如 iptables -I INPUT -t filter -m conntrack ctstate NEW -m comment --comment "kubernetes externally-visible service portals" -j KUBE-EXTERNAL-SERVICES
if _, err := proxier.iptables.EnsureRule(utiliptables.Prepend, jump.table, jump.srcChain, args...); err != nil {
klog.ErrorS(err, "Failed to ensure chain jumps", "table", jump.table, "srcChain", jump.srcChain, "dstChain", jump.dstChain)
return
}
}
调用
func (proxier *Proxier) syncProxyRules()
函数的时候会在函数里面对iptables的链进行添加,主要是对filter表、nat表的链添加。