diff --git a/.github/workflows/build-x86-image.yaml b/.github/workflows/build-x86-image.yaml index 7fbfa241a5f..468e0e1da57 100644 --- a/.github/workflows/build-x86-image.yaml +++ b/.github/workflows/build-x86-image.yaml @@ -1942,6 +1942,19 @@ jobs: working-directory: ${{ env.E2E_DIR }} run: make iptables-vpc-nat-gw-conformance-e2e + - name: kubectl ko log + if: failure() + run: | + make kubectl-ko-log + mv kubectl-ko-log.tar.gz iptables-vpc-nat-gw-conformance-e2e-ko-log.tar.gz + + - name: upload kubectl ko log + uses: actions/upload-artifact@v3 + if: failure() + with: + name: iptables-vpc-nat-gw-conformance-e2e-ko-log + path: iptables-vpc-nat-gw-conformance-e2e-ko-log.tar.gz + ovn-vpc-nat-gw-conformance-e2e: name: OVN VPC NAT Gateway E2E needs: diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index a9df9406e8c..bd2bb1be7bb 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -38,7 +38,6 @@ jobs: # working-directory: somedir # Optional: golangci-lint command line arguments. - args: --timeout 20m - + args: --timeout 20m --verbose # Optional: show only new issues if it's a pull request. The default value is `false`. # only-new-issues: true diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 00000000000..369ec879945 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,44 @@ +run: + timeout: 15m + +output: + sort-results: true + +linters: + enable: + - gocritic + - gofumpt + - goimports + - misspell + - predeclared + - revive + - unconvert + - unused + - errcheck + +issues: + max-same-issues: 0 + exclude-rules: + - linters: + - gocritic + text: "appendAssign" + - linters: + - revive + text: "don't use an underscore in package name" # package name not change + - path: test/unittest/ + linters: + - revive + text: "should not use dot imports" # ginkgo coding style + - linters: + - revive + text: "VpcDns should be VpcDNS" # api param not change + - linters: + - revive + text: "VpcDnsList should be VpcDNSList" # api param not change + +linters-settings: + goimports: + local-prefixes: github.com/kubeovn/kube-ovn + gofumpt: + extra-rules: true + diff --git a/Makefile b/Makefile index 374e8be08d7..da27ba297b2 100644 --- a/Makefile +++ b/Makefile @@ -827,6 +827,10 @@ lint: @GOOS=linux go vet ./... @GOOS=linux gosec -exclude=G204,G306,G404,G601,G301 -exclude-dir=test -exclude-dir=pkg/client ./... +.PHONY: gofumpt +gofumpt: gofumpt + gofumpt -w -extra . + .PHONY: lint-windows lint-windows: @GOOS=windows go vet ./cmd/windows/... diff --git a/cmd/cni/cni.go b/cmd/cni/cni.go index bb658474c49..d3f4fe8663e 100644 --- a/cmd/cni/cni.go +++ b/cmd/cni/cni.go @@ -82,14 +82,14 @@ func generateCNIResult(cniResponse *request.CniResponse, netns string) current.R } switch cniResponse.Protocol { case kubeovnv1.ProtocolIPv4: - ip, route := assignV4Address(cniResponse.IpAddress, cniResponse.Gateway, mask) + ip, route := assignV4Address(cniResponse.IPAddress, cniResponse.Gateway, mask) result.IPs = []*current.IPConfig{ip} if route != nil { result.Routes = []*types.Route{route} } result.Interfaces = []*current.Interface{&podIface} case kubeovnv1.ProtocolIPv6: - ip, route := assignV6Address(cniResponse.IpAddress, cniResponse.Gateway, mask) + ip, route := assignV6Address(cniResponse.IPAddress, cniResponse.Gateway, mask) result.IPs = []*current.IPConfig{ip} if route != nil { result.Routes = []*types.Route{route} @@ -102,7 +102,7 @@ func generateCNIResult(cniResponse *request.CniResponse, netns string) current.R _, netMask, _ = net.ParseCIDR(cidrBlock) gwStr = "" if util.CheckProtocol(cidrBlock) == kubeovnv1.ProtocolIPv4 { - ipStr := strings.Split(cniResponse.IpAddress, ",")[0] + ipStr := strings.Split(cniResponse.IPAddress, ",")[0] if cniResponse.Gateway != "" { gwStr = strings.Split(cniResponse.Gateway, ",")[0] } @@ -113,7 +113,7 @@ func generateCNIResult(cniResponse *request.CniResponse, netns string) current.R result.Routes = append(result.Routes, route) } } else if util.CheckProtocol(cidrBlock) == kubeovnv1.ProtocolIPv6 { - ipStr := strings.Split(cniResponse.IpAddress, ",")[1] + ipStr := strings.Split(cniResponse.IPAddress, ",")[1] if cniResponse.Gateway != "" { gwStr = strings.Split(cniResponse.Gateway, ",")[1] } diff --git a/cmd/daemon/cniserver.go b/cmd/daemon/cniserver.go index 318916db456..a8776c09beb 100644 --- a/cmd/daemon/cniserver.go +++ b/cmd/daemon/cniserver.go @@ -132,10 +132,10 @@ func mvCNIConf(configDir, configFile, confName string) error { } cniConfPath := filepath.Join(configDir, confName) - return os.WriteFile(cniConfPath, data, 0644) + return os.WriteFile(cniConfPath, data, 0o644) } -func Retry(attempts int, sleep int, f func(configuration *daemon.Configuration) error, ctrl *daemon.Configuration) (err error) { +func Retry(attempts, sleep int, f func(configuration *daemon.Configuration) error, ctrl *daemon.Configuration) (err error) { for i := 0; ; i++ { err = f(ctrl) if err == nil { @@ -174,13 +174,11 @@ func initChassisAnno(cfg *daemon.Configuration) error { if annoChassesName, ok := node.Annotations[util.ChassisAnnotation]; ok { if annoChassesName == chassesName { return nil - } else { - klog.Infof("chassis id changed, old: %s, new: %s", annoChassesName, chassesName) } + klog.Infof("chassis id changed, old: %s, new: %s", annoChassesName, chassesName) } node.Annotations[util.ChassisAnnotation] = chassesName - patchPayloadTemplate := - `[{ + patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/annotations", "value": %s diff --git a/mocks/pkg/ovs/interface.go b/mocks/pkg/ovs/interface.go index 3b2a9eed704..2d1d73d7854 100644 --- a/mocks/pkg/ovs/interface.go +++ b/mocks/pkg/ovs/interface.go @@ -1182,32 +1182,32 @@ func (m *MockACL) EXPECT() *MockACLMockRecorder { return m.recorder } -// CreateGatewayAcl mocks base method. -func (m *MockACL) CreateGatewayAcl(lsName, pgName, gateway string) error { +// CreateGatewayACL mocks base method. +func (m *MockACL) CreateGatewayACL(lsName, pgName, gateway string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateGatewayAcl", lsName, pgName, gateway) + ret := m.ctrl.Call(m, "CreateGatewayACL", lsName, pgName, gateway) ret0, _ := ret[0].(error) return ret0 } -// CreateGatewayAcl indicates an expected call of CreateGatewayAcl. -func (mr *MockACLMockRecorder) CreateGatewayAcl(lsName, pgName, gateway interface{}) *gomock.Call { +// CreateGatewayACL indicates an expected call of CreateGatewayACL. +func (mr *MockACLMockRecorder) CreateGatewayACL(lsName, pgName, gateway interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateGatewayAcl", reflect.TypeOf((*MockACL)(nil).CreateGatewayAcl), lsName, pgName, gateway) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateGatewayACL", reflect.TypeOf((*MockACL)(nil).CreateGatewayACL), lsName, pgName, gateway) } -// CreateNodeAcl mocks base method. -func (m *MockACL) CreateNodeAcl(pgName, nodeIpStr, joinIpStr string) error { +// CreateNodeACL mocks base method. +func (m *MockACL) CreateNodeACL(pgName, nodeIPStr, joinIPStr string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateNodeAcl", pgName, nodeIpStr, joinIpStr) + ret := m.ctrl.Call(m, "CreateNodeACL", pgName, nodeIPStr, joinIPStr) ret0, _ := ret[0].(error) return ret0 } -// CreateNodeAcl indicates an expected call of CreateNodeAcl. -func (mr *MockACLMockRecorder) CreateNodeAcl(pgName, nodeIpStr, joinIpStr interface{}) *gomock.Call { +// CreateNodeACL indicates an expected call of CreateNodeACL. +func (mr *MockACLMockRecorder) CreateNodeACL(pgName, nodeIPStr, joinIPStr interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateNodeAcl", reflect.TypeOf((*MockACL)(nil).CreateNodeAcl), pgName, nodeIpStr, joinIpStr) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateNodeACL", reflect.TypeOf((*MockACL)(nil).CreateNodeACL), pgName, nodeIPStr, joinIPStr) } // CreateSgBaseACL mocks base method. @@ -1224,18 +1224,18 @@ func (mr *MockACLMockRecorder) CreateSgBaseACL(sgName, direction interface{}) *g return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSgBaseACL", reflect.TypeOf((*MockACL)(nil).CreateSgBaseACL), sgName, direction) } -// CreateSgDenyAllAcl mocks base method. -func (m *MockACL) CreateSgDenyAllAcl(sgName string) error { +// CreateSgDenyAllACL mocks base method. +func (m *MockACL) CreateSgDenyAllACL(sgName string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateSgDenyAllAcl", sgName) + ret := m.ctrl.Call(m, "CreateSgDenyAllACL", sgName) ret0, _ := ret[0].(error) return ret0 } -// CreateSgDenyAllAcl indicates an expected call of CreateSgDenyAllAcl. -func (mr *MockACLMockRecorder) CreateSgDenyAllAcl(sgName interface{}) *gomock.Call { +// CreateSgDenyAllACL indicates an expected call of CreateSgDenyAllACL. +func (mr *MockACLMockRecorder) CreateSgDenyAllACL(sgName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSgDenyAllAcl", reflect.TypeOf((*MockACL)(nil).CreateSgDenyAllAcl), sgName) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSgDenyAllACL", reflect.TypeOf((*MockACL)(nil).CreateSgDenyAllACL), sgName) } // DeleteAcls mocks base method. @@ -1267,18 +1267,18 @@ func (mr *MockACLMockRecorder) DeleteAclsOps(parentName, parentType, direction, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAclsOps", reflect.TypeOf((*MockACL)(nil).DeleteAclsOps), parentName, parentType, direction, externalIDs) } -// SetAclLog mocks base method. -func (m *MockACL) SetAclLog(pgName, protocol string, logEnable, isIngress bool) error { +// SetACLLog mocks base method. +func (m *MockACL) SetACLLog(pgName, protocol string, logEnable, isIngress bool) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetAclLog", pgName, protocol, logEnable, isIngress) + ret := m.ctrl.Call(m, "SetACLLog", pgName, protocol, logEnable, isIngress) ret0, _ := ret[0].(error) return ret0 } -// SetAclLog indicates an expected call of SetAclLog. -func (mr *MockACLMockRecorder) SetAclLog(pgName, protocol, logEnable, isIngress interface{}) *gomock.Call { +// SetACLLog indicates an expected call of SetACLLog. +func (mr *MockACLMockRecorder) SetACLLog(pgName, protocol, logEnable, isIngress interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAclLog", reflect.TypeOf((*MockACL)(nil).SetAclLog), pgName, protocol, logEnable, isIngress) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetACLLog", reflect.TypeOf((*MockACL)(nil).SetACLLog), pgName, protocol, logEnable, isIngress) } // SetLogicalSwitchPrivate mocks base method. @@ -1295,62 +1295,62 @@ func (mr *MockACLMockRecorder) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSw return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLogicalSwitchPrivate", reflect.TypeOf((*MockACL)(nil).SetLogicalSwitchPrivate), lsName, cidrBlock, nodeSwitchCIDR, allowSubnets) } -// UpdateEgressAclOps mocks base method. -func (m *MockACL) UpdateEgressAclOps(pgName, asEgressName, asExceptName, protocol string, npp []v10.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { +// UpdateEgressACLOps mocks base method. +func (m *MockACL) UpdateEgressACLOps(pgName, asEgressName, asExceptName, protocol string, npp []v10.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateEgressAclOps", pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap) + ret := m.ctrl.Call(m, "UpdateEgressACLOps", pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap) ret0, _ := ret[0].([]ovsdb.Operation) ret1, _ := ret[1].(error) return ret0, ret1 } -// UpdateEgressAclOps indicates an expected call of UpdateEgressAclOps. -func (mr *MockACLMockRecorder) UpdateEgressAclOps(pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap interface{}) *gomock.Call { +// UpdateEgressACLOps indicates an expected call of UpdateEgressACLOps. +func (mr *MockACLMockRecorder) UpdateEgressACLOps(pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateEgressAclOps", reflect.TypeOf((*MockACL)(nil).UpdateEgressAclOps), pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateEgressACLOps", reflect.TypeOf((*MockACL)(nil).UpdateEgressACLOps), pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap) } -// UpdateIngressAclOps mocks base method. -func (m *MockACL) UpdateIngressAclOps(pgName, asIngressName, asExceptName, protocol string, npp []v10.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { +// UpdateIngressACLOps mocks base method. +func (m *MockACL) UpdateIngressACLOps(pgName, asIngressName, asExceptName, protocol string, npp []v10.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateIngressAclOps", pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap) + ret := m.ctrl.Call(m, "UpdateIngressACLOps", pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap) ret0, _ := ret[0].([]ovsdb.Operation) ret1, _ := ret[1].(error) return ret0, ret1 } -// UpdateIngressAclOps indicates an expected call of UpdateIngressAclOps. -func (mr *MockACLMockRecorder) UpdateIngressAclOps(pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap interface{}) *gomock.Call { +// UpdateIngressACLOps indicates an expected call of UpdateIngressACLOps. +func (mr *MockACLMockRecorder) UpdateIngressACLOps(pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateIngressAclOps", reflect.TypeOf((*MockACL)(nil).UpdateIngressAclOps), pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateIngressACLOps", reflect.TypeOf((*MockACL)(nil).UpdateIngressACLOps), pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap) } -// UpdateLogicalSwitchAcl mocks base method. -func (m *MockACL) UpdateLogicalSwitchAcl(lsName string, subnetAcls []v1.Acl) error { +// UpdateLogicalSwitchACL mocks base method. +func (m *MockACL) UpdateLogicalSwitchACL(lsName string, subnetAcls []v1.ACL) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateLogicalSwitchAcl", lsName, subnetAcls) + ret := m.ctrl.Call(m, "UpdateLogicalSwitchACL", lsName, subnetAcls) ret0, _ := ret[0].(error) return ret0 } -// UpdateLogicalSwitchAcl indicates an expected call of UpdateLogicalSwitchAcl. -func (mr *MockACLMockRecorder) UpdateLogicalSwitchAcl(lsName, subnetAcls interface{}) *gomock.Call { +// UpdateLogicalSwitchACL indicates an expected call of UpdateLogicalSwitchACL. +func (mr *MockACLMockRecorder) UpdateLogicalSwitchACL(lsName, subnetAcls interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateLogicalSwitchAcl", reflect.TypeOf((*MockACL)(nil).UpdateLogicalSwitchAcl), lsName, subnetAcls) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateLogicalSwitchACL", reflect.TypeOf((*MockACL)(nil).UpdateLogicalSwitchACL), lsName, subnetAcls) } -// UpdateSgAcl mocks base method. -func (m *MockACL) UpdateSgAcl(sg *v1.SecurityGroup, direction string) error { +// UpdateSgACL mocks base method. +func (m *MockACL) UpdateSgACL(sg *v1.SecurityGroup, direction string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateSgAcl", sg, direction) + ret := m.ctrl.Call(m, "UpdateSgACL", sg, direction) ret0, _ := ret[0].(error) return ret0 } -// UpdateSgAcl indicates an expected call of UpdateSgAcl. -func (mr *MockACLMockRecorder) UpdateSgAcl(sg, direction interface{}) *gomock.Call { +// UpdateSgACL indicates an expected call of UpdateSgACL. +func (mr *MockACLMockRecorder) UpdateSgACL(sg, direction interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateSgAcl", reflect.TypeOf((*MockACL)(nil).UpdateSgAcl), sg, direction) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateSgACL", reflect.TypeOf((*MockACL)(nil).UpdateSgACL), sg, direction) } // MockAddressSet is a mock of AddressSet interface. @@ -1476,9 +1476,9 @@ func (m *MockLogicalRouterStaticRoute) EXPECT() *MockLogicalRouterStaticRouteMoc } // AddLogicalRouterStaticRoute mocks base method. -func (m *MockLogicalRouterStaticRoute) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix string, bfdId *string, nexthops ...string) error { +func (m *MockLogicalRouterStaticRoute) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix string, bfdID *string, nexthops ...string) error { m.ctrl.T.Helper() - varargs := []interface{}{lrName, routeTable, policy, ipPrefix, bfdId} + varargs := []interface{}{lrName, routeTable, policy, ipPrefix, bfdID} for _, a := range nexthops { varargs = append(varargs, a) } @@ -1488,9 +1488,9 @@ func (m *MockLogicalRouterStaticRoute) AddLogicalRouterStaticRoute(lrName, route } // AddLogicalRouterStaticRoute indicates an expected call of AddLogicalRouterStaticRoute. -func (mr *MockLogicalRouterStaticRouteMockRecorder) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, bfdId interface{}, nexthops ...interface{}) *gomock.Call { +func (mr *MockLogicalRouterStaticRouteMockRecorder) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, bfdID interface{}, nexthops ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{lrName, routeTable, policy, ipPrefix, bfdId}, nexthops...) + varargs := append([]interface{}{lrName, routeTable, policy, ipPrefix, bfdID}, nexthops...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddLogicalRouterStaticRoute", reflect.TypeOf((*MockLogicalRouterStaticRoute)(nil).AddLogicalRouterStaticRoute), varargs...) } @@ -1965,9 +1965,9 @@ func (mr *MockNbClientMockRecorder) AddLogicalRouterPolicy(lrName, priority, mat } // AddLogicalRouterStaticRoute mocks base method. -func (m *MockNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix string, bfdId *string, nexthops ...string) error { +func (m *MockNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix string, bfdID *string, nexthops ...string) error { m.ctrl.T.Helper() - varargs := []interface{}{lrName, routeTable, policy, ipPrefix, bfdId} + varargs := []interface{}{lrName, routeTable, policy, ipPrefix, bfdID} for _, a := range nexthops { varargs = append(varargs, a) } @@ -1977,9 +1977,9 @@ func (m *MockNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, i } // AddLogicalRouterStaticRoute indicates an expected call of AddLogicalRouterStaticRoute. -func (mr *MockNbClientMockRecorder) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, bfdId interface{}, nexthops ...interface{}) *gomock.Call { +func (mr *MockNbClientMockRecorder) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, bfdID interface{}, nexthops ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{lrName, routeTable, policy, ipPrefix, bfdId}, nexthops...) + varargs := append([]interface{}{lrName, routeTable, policy, ipPrefix, bfdID}, nexthops...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddLogicalRouterStaticRoute", reflect.TypeOf((*MockNbClient)(nil).AddLogicalRouterStaticRoute), varargs...) } @@ -2101,18 +2101,18 @@ func (mr *MockNbClientMockRecorder) CreateBareLogicalSwitchPort(lsName, lspName, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateBareLogicalSwitchPort", reflect.TypeOf((*MockNbClient)(nil).CreateBareLogicalSwitchPort), lsName, lspName, ip, mac) } -// CreateGatewayAcl mocks base method. -func (m *MockNbClient) CreateGatewayAcl(lsName, pgName, gateway string) error { +// CreateGatewayACL mocks base method. +func (m *MockNbClient) CreateGatewayACL(lsName, pgName, gateway string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateGatewayAcl", lsName, pgName, gateway) + ret := m.ctrl.Call(m, "CreateGatewayACL", lsName, pgName, gateway) ret0, _ := ret[0].(error) return ret0 } -// CreateGatewayAcl indicates an expected call of CreateGatewayAcl. -func (mr *MockNbClientMockRecorder) CreateGatewayAcl(lsName, pgName, gateway interface{}) *gomock.Call { +// CreateGatewayACL indicates an expected call of CreateGatewayACL. +func (mr *MockNbClientMockRecorder) CreateGatewayACL(lsName, pgName, gateway interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateGatewayAcl", reflect.TypeOf((*MockNbClient)(nil).CreateGatewayAcl), lsName, pgName, gateway) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateGatewayACL", reflect.TypeOf((*MockNbClient)(nil).CreateGatewayACL), lsName, pgName, gateway) } // CreateGatewayLogicalSwitch mocks base method. @@ -2237,18 +2237,18 @@ func (mr *MockNbClientMockRecorder) CreateLogicalSwitchPort(lsName, lspName, ip, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateLogicalSwitchPort", reflect.TypeOf((*MockNbClient)(nil).CreateLogicalSwitchPort), lsName, lspName, ip, mac, podName, namespace, portSecurity, securityGroups, vips, enableDHCP, dhcpOptions, vpc) } -// CreateNodeAcl mocks base method. -func (m *MockNbClient) CreateNodeAcl(pgName, nodeIpStr, joinIpStr string) error { +// CreateNodeACL mocks base method. +func (m *MockNbClient) CreateNodeACL(pgName, nodeIPStr, joinIPStr string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateNodeAcl", pgName, nodeIpStr, joinIpStr) + ret := m.ctrl.Call(m, "CreateNodeACL", pgName, nodeIPStr, joinIPStr) ret0, _ := ret[0].(error) return ret0 } -// CreateNodeAcl indicates an expected call of CreateNodeAcl. -func (mr *MockNbClientMockRecorder) CreateNodeAcl(pgName, nodeIpStr, joinIpStr interface{}) *gomock.Call { +// CreateNodeACL indicates an expected call of CreateNodeACL. +func (mr *MockNbClientMockRecorder) CreateNodeACL(pgName, nodeIPStr, joinIPStr interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateNodeAcl", reflect.TypeOf((*MockNbClient)(nil).CreateNodeAcl), pgName, nodeIpStr, joinIpStr) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateNodeACL", reflect.TypeOf((*MockNbClient)(nil).CreateNodeACL), pgName, nodeIPStr, joinIPStr) } // CreatePeerRouterPort mocks base method. @@ -2293,18 +2293,18 @@ func (mr *MockNbClientMockRecorder) CreateSgBaseACL(sgName, direction interface{ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSgBaseACL", reflect.TypeOf((*MockNbClient)(nil).CreateSgBaseACL), sgName, direction) } -// CreateSgDenyAllAcl mocks base method. -func (m *MockNbClient) CreateSgDenyAllAcl(sgName string) error { +// CreateSgDenyAllACL mocks base method. +func (m *MockNbClient) CreateSgDenyAllACL(sgName string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateSgDenyAllAcl", sgName) + ret := m.ctrl.Call(m, "CreateSgDenyAllACL", sgName) ret0, _ := ret[0].(error) return ret0 } -// CreateSgDenyAllAcl indicates an expected call of CreateSgDenyAllAcl. -func (mr *MockNbClientMockRecorder) CreateSgDenyAllAcl(sgName interface{}) *gomock.Call { +// CreateSgDenyAllACL indicates an expected call of CreateSgDenyAllACL. +func (mr *MockNbClientMockRecorder) CreateSgDenyAllACL(sgName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSgDenyAllAcl", reflect.TypeOf((*MockNbClient)(nil).CreateSgDenyAllAcl), sgName) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSgDenyAllACL", reflect.TypeOf((*MockNbClient)(nil).CreateSgDenyAllACL), sgName) } // CreateVirtualLogicalSwitchPorts mocks base method. @@ -3297,18 +3297,18 @@ func (mr *MockNbClientMockRecorder) RemoveLogicalPatchPort(lspName, lrpName inte return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveLogicalPatchPort", reflect.TypeOf((*MockNbClient)(nil).RemoveLogicalPatchPort), lspName, lrpName) } -// SetAclLog mocks base method. -func (m *MockNbClient) SetAclLog(pgName, protocol string, logEnable, isIngress bool) error { +// SetACLLog mocks base method. +func (m *MockNbClient) SetACLLog(pgName, protocol string, logEnable, isIngress bool) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetAclLog", pgName, protocol, logEnable, isIngress) + ret := m.ctrl.Call(m, "SetACLLog", pgName, protocol, logEnable, isIngress) ret0, _ := ret[0].(error) return ret0 } -// SetAclLog indicates an expected call of SetAclLog. -func (mr *MockNbClientMockRecorder) SetAclLog(pgName, protocol, logEnable, isIngress interface{}) *gomock.Call { +// SetACLLog indicates an expected call of SetACLLog. +func (mr *MockNbClientMockRecorder) SetACLLog(pgName, protocol, logEnable, isIngress interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetAclLog", reflect.TypeOf((*MockNbClient)(nil).SetAclLog), pgName, protocol, logEnable, isIngress) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetACLLog", reflect.TypeOf((*MockNbClient)(nil).SetACLLog), pgName, protocol, logEnable, isIngress) } // SetAzName mocks base method. @@ -3527,34 +3527,34 @@ func (mr *MockNbClientMockRecorder) UpdateDnatAndSnat(lrName, externalIP, logica return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateDnatAndSnat", reflect.TypeOf((*MockNbClient)(nil).UpdateDnatAndSnat), lrName, externalIP, logicalIP, lspName, externalMac, gatewayType) } -// UpdateEgressAclOps mocks base method. -func (m *MockNbClient) UpdateEgressAclOps(pgName, asEgressName, asExceptName, protocol string, npp []v10.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { +// UpdateEgressACLOps mocks base method. +func (m *MockNbClient) UpdateEgressACLOps(pgName, asEgressName, asExceptName, protocol string, npp []v10.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateEgressAclOps", pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap) + ret := m.ctrl.Call(m, "UpdateEgressACLOps", pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap) ret0, _ := ret[0].([]ovsdb.Operation) ret1, _ := ret[1].(error) return ret0, ret1 } -// UpdateEgressAclOps indicates an expected call of UpdateEgressAclOps. -func (mr *MockNbClientMockRecorder) UpdateEgressAclOps(pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap interface{}) *gomock.Call { +// UpdateEgressACLOps indicates an expected call of UpdateEgressACLOps. +func (mr *MockNbClientMockRecorder) UpdateEgressACLOps(pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateEgressAclOps", reflect.TypeOf((*MockNbClient)(nil).UpdateEgressAclOps), pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateEgressACLOps", reflect.TypeOf((*MockNbClient)(nil).UpdateEgressACLOps), pgName, asEgressName, asExceptName, protocol, npp, logEnable, namedPortMap) } -// UpdateIngressAclOps mocks base method. -func (m *MockNbClient) UpdateIngressAclOps(pgName, asIngressName, asExceptName, protocol string, npp []v10.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { +// UpdateIngressACLOps mocks base method. +func (m *MockNbClient) UpdateIngressACLOps(pgName, asIngressName, asExceptName, protocol string, npp []v10.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateIngressAclOps", pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap) + ret := m.ctrl.Call(m, "UpdateIngressACLOps", pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap) ret0, _ := ret[0].([]ovsdb.Operation) ret1, _ := ret[1].(error) return ret0, ret1 } -// UpdateIngressAclOps indicates an expected call of UpdateIngressAclOps. -func (mr *MockNbClientMockRecorder) UpdateIngressAclOps(pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap interface{}) *gomock.Call { +// UpdateIngressACLOps indicates an expected call of UpdateIngressACLOps. +func (mr *MockNbClientMockRecorder) UpdateIngressACLOps(pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateIngressAclOps", reflect.TypeOf((*MockNbClient)(nil).UpdateIngressAclOps), pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateIngressACLOps", reflect.TypeOf((*MockNbClient)(nil).UpdateIngressACLOps), pgName, asIngressName, asExceptName, protocol, npp, logEnable, namedPortMap) } // UpdateLogicalRouterPortOptions mocks base method. @@ -3585,18 +3585,18 @@ func (mr *MockNbClientMockRecorder) UpdateLogicalRouterPortRA(lrpName, ipv6RACon return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateLogicalRouterPortRA", reflect.TypeOf((*MockNbClient)(nil).UpdateLogicalRouterPortRA), lrpName, ipv6RAConfigsStr, enableIPv6RA) } -// UpdateLogicalSwitchAcl mocks base method. -func (m *MockNbClient) UpdateLogicalSwitchAcl(lsName string, subnetAcls []v1.Acl) error { +// UpdateLogicalSwitchACL mocks base method. +func (m *MockNbClient) UpdateLogicalSwitchACL(lsName string, subnetAcls []v1.ACL) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateLogicalSwitchAcl", lsName, subnetAcls) + ret := m.ctrl.Call(m, "UpdateLogicalSwitchACL", lsName, subnetAcls) ret0, _ := ret[0].(error) return ret0 } -// UpdateLogicalSwitchAcl indicates an expected call of UpdateLogicalSwitchAcl. -func (mr *MockNbClientMockRecorder) UpdateLogicalSwitchAcl(lsName, subnetAcls interface{}) *gomock.Call { +// UpdateLogicalSwitchACL indicates an expected call of UpdateLogicalSwitchACL. +func (mr *MockNbClientMockRecorder) UpdateLogicalSwitchACL(lsName, subnetAcls interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateLogicalSwitchAcl", reflect.TypeOf((*MockNbClient)(nil).UpdateLogicalSwitchAcl), lsName, subnetAcls) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateLogicalSwitchACL", reflect.TypeOf((*MockNbClient)(nil).UpdateLogicalSwitchACL), lsName, subnetAcls) } // UpdateNbGlobal mocks base method. @@ -3618,18 +3618,18 @@ func (mr *MockNbClientMockRecorder) UpdateNbGlobal(nbGlobal interface{}, fields return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateNbGlobal", reflect.TypeOf((*MockNbClient)(nil).UpdateNbGlobal), varargs...) } -// UpdateSgAcl mocks base method. -func (m *MockNbClient) UpdateSgAcl(sg *v1.SecurityGroup, direction string) error { +// UpdateSgACL mocks base method. +func (m *MockNbClient) UpdateSgACL(sg *v1.SecurityGroup, direction string) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateSgAcl", sg, direction) + ret := m.ctrl.Call(m, "UpdateSgACL", sg, direction) ret0, _ := ret[0].(error) return ret0 } -// UpdateSgAcl indicates an expected call of UpdateSgAcl. -func (mr *MockNbClientMockRecorder) UpdateSgAcl(sg, direction interface{}) *gomock.Call { +// UpdateSgACL indicates an expected call of UpdateSgACL. +func (mr *MockNbClientMockRecorder) UpdateSgACL(sg, direction interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateSgAcl", reflect.TypeOf((*MockNbClient)(nil).UpdateSgAcl), sg, direction) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateSgACL", reflect.TypeOf((*MockNbClient)(nil).UpdateSgACL), sg, direction) } // UpdateSnat mocks base method. diff --git a/pkg/apis/kubeovn/v1/types.go b/pkg/apis/kubeovn/v1/types.go index f1dcea75b88..d81c123ebc6 100644 --- a/pkg/apis/kubeovn/v1/types.go +++ b/pkg/apis/kubeovn/v1/types.go @@ -158,7 +158,7 @@ type SubnetSpec struct { EnableIPv6RA bool `json:"enableIPv6RA,omitempty"` IPv6RAConfigs string `json:"ipv6RAConfigs,omitempty"` - Acls []Acl `json:"acls,omitempty"` + Acls []ACL `json:"acls,omitempty"` NatOutgoingPolicyRules []NatOutgoingPolicyRule `json:"natOutgoingPolicyRules,omitempty"` @@ -171,7 +171,7 @@ type SubnetSpec struct { RouteTable string `json:"routeTable,omitempty"` } -type Acl struct { +type ACL struct { Direction string `json:"direction,omitempty"` Priority int `json:"priority,omitempty"` Match string `json:"match,omitempty"` @@ -313,7 +313,7 @@ type Vlan struct { type VlanSpec struct { // deprecated fields, use ID & Provider instead - VlanId int `json:"vlanId,omitempty"` + VlanID int `json:"vlanId,omitempty"` ProviderInterfaceName string `json:"providerInterfaceName,omitempty"` ID int `json:"id"` @@ -440,7 +440,7 @@ type StaticRoute struct { CIDR string `json:"cidr"` NextHopIP string `json:"nextHopIP"` ECMPMode string `json:"ecmpMode"` - BfdId string `json:"bfdId"` + BfdID string `json:"bfdId"` RouteTable string `json:"routeTable"` } @@ -472,11 +472,11 @@ type VpcStatus struct { Default bool `json:"default"` DefaultLogicalSwitch string `json:"defaultLogicalSwitch"` Router string `json:"router"` - TcpLoadBalancer string `json:"tcpLoadBalancer"` - UdpLoadBalancer string `json:"udpLoadBalancer"` + TCPLoadBalancer string `json:"tcpLoadBalancer"` + UDPLoadBalancer string `json:"udpLoadBalancer"` SctpLoadBalancer string `json:"sctpLoadBalancer"` - TcpSessionLoadBalancer string `json:"tcpSessionLoadBalancer"` - UdpSessionLoadBalancer string `json:"udpSessionLoadBalancer"` + TCPSessionLoadBalancer string `json:"tcpSessionLoadBalancer"` + UDPSessionLoadBalancer string `json:"udpSessionLoadBalancer"` SctpSessionLoadBalancer string `json:"sctpSessionLoadBalancer"` Subnets []string `json:"subnets"` VpcPeerings []string `json:"vpcPeerings"` @@ -514,7 +514,7 @@ type VpcNatSpec struct { Vpc string `json:"vpc"` Subnet string `json:"subnet"` ExternalSubnets []string `json:"externalSubnets"` - LanIp string `json:"lanIp"` + LanIP string `json:"lanIp"` Selector []string `json:"selector"` Tolerations []corev1.Toleration `json:"tolerations"` Affinity corev1.Affinity `json:"affinity"` @@ -592,7 +592,7 @@ type IptablesFIPRule struct { } type IptablesFIPRuleSpec struct { EIP string `json:"eip"` - InternalIp string `json:"internalIp"` + InternalIP string `json:"internalIp"` } // IptablesFIPRuleCondition describes the state of an object at a certain point. @@ -607,7 +607,7 @@ type IptablesFIPRuleStatus struct { V6ip string `json:"v6ip" patchStrategy:"merge"` NatGwDp string `json:"natGwDp" patchStrategy:"merge"` Redo string `json:"redo" patchStrategy:"merge"` - InternalIp string `json:"internalIp" patchStrategy:"merge"` + InternalIP string `json:"internalIp" patchStrategy:"merge"` // Conditions represents the latest state of the object // +optional @@ -688,7 +688,7 @@ type IptablesDnatRuleSpec struct { EIP string `json:"eip"` ExternalPort string `json:"externalPort"` Protocol string `json:"protocol,omitempty"` - InternalIp string `json:"internalIp"` + InternalIP string `json:"internalIp"` InternalPort string `json:"internalPort"` } @@ -705,7 +705,7 @@ type IptablesDnatRuleStatus struct { NatGwDp string `json:"natGwDp" patchStrategy:"merge"` Redo string `json:"redo" patchStrategy:"merge"` Protocol string `json:"protocol" patchStrategy:"merge"` - InternalIp string `json:"internalIp" patchStrategy:"merge"` + InternalIP string `json:"internalIp" patchStrategy:"merge"` InternalPort string `json:"internalPort" patchStrategy:"merge"` ExternalPort string `json:"externalPort" patchStrategy:"merge"` @@ -848,11 +848,11 @@ type VpcDns struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` - Spec VpcDnsSpec `json:"spec"` - Status VpcDnsStatus `json:"status,omitempty"` + Spec VpcDNSSpec `json:"spec"` + Status VpcDNSStatus `json:"status,omitempty"` } -type VpcDnsSpec struct { +type VpcDNSSpec struct { Vpc string `json:"vpc"` Subnet string `json:"subnet"` } @@ -866,18 +866,18 @@ type VpcDnsList struct { Items []VpcDns `json:"items"` } -type VpcDnsStatus struct { +type VpcDNSStatus struct { // +optional // +patchMergeKey=type // +patchStrategy=merge - Conditions []VpcDnsCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` + Conditions []VpcDNSCondition `json:"conditions,omitempty" patchStrategy:"merge" patchMergeKey:"type"` Active bool `json:"active" patchStrategy:"merge"` } -// VpcDnsCondition describes the state of an object at a certain point. +// VpcDNSCondition describes the state of an object at a certain point. // +k8s:deepcopy-gen=true -type VpcDnsCondition Condition +type VpcDNSCondition Condition type SlrPort struct { Name string `json:"name"` @@ -998,8 +998,8 @@ type OvnFip struct { } type OvnFipSpec struct { OvnEip string `json:"ovnEip"` - IpType string `json:"ipType"` // vip, ip - IpName string `json:"ipName"` // vip, ip crd name + IPType string `json:"ipType"` // vip, ip + IPName string `json:"ipName"` // vip, ip crd name } // OvnFipCondition describes the state of an object at a certain point. @@ -1047,7 +1047,7 @@ type OvnSnatRule struct { type OvnSnatRuleSpec struct { OvnEip string `json:"ovnEip"` VpcSubnet string `json:"vpcSubnet"` - IpName string `json:"ipName"` + IPName string `json:"ipName"` } // OvnSnatRuleCondition describes the state of an object at a certain point. @@ -1093,8 +1093,8 @@ type OvnDnatRule struct { type OvnDnatRuleSpec struct { OvnEip string `json:"ovnEip"` - IpType string `json:"ipType"` // vip, ip - IpName string `json:"ipName"` // vip, ip crd name + IPType string `json:"ipType"` // vip, ip + IPName string `json:"ipName"` // vip, ip crd name InternalPort string `json:"internalPort"` ExternalPort string `json:"externalPort"` Protocol string `json:"protocol,omitempty"` @@ -1116,7 +1116,7 @@ type OvnDnatRuleStatus struct { InternalPort string `json:"internalPort"` ExternalPort string `json:"externalPort"` Protocol string `json:"protocol,omitempty"` - IpName string `json:"ipName"` + IPName string `json:"ipName"` // Conditions represents the latest state of the object // +optional diff --git a/pkg/apis/kubeovn/v1/zz_generated.deepcopy.go b/pkg/apis/kubeovn/v1/zz_generated.deepcopy.go index eb1ea7ded00..4e859d6d4e7 100644 --- a/pkg/apis/kubeovn/v1/zz_generated.deepcopy.go +++ b/pkg/apis/kubeovn/v1/zz_generated.deepcopy.go @@ -27,17 +27,17 @@ import ( ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Acl) DeepCopyInto(out *Acl) { +func (in *ACL) DeepCopyInto(out *ACL) { *out = *in return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Acl. -func (in *Acl) DeepCopy() *Acl { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ACL. +func (in *ACL) DeepCopy() *ACL { if in == nil { return nil } - out := new(Acl) + out := new(ACL) in.DeepCopyInto(out) return out } @@ -1907,7 +1907,7 @@ func (in *SubnetSpec) DeepCopyInto(out *SubnetSpec) { } if in.Acls != nil { in, out := &in.Acls, &out.Acls - *out = make([]Acl, len(*in)) + *out = make([]ACL, len(*in)) copy(*out, *in) } if in.NatOutgoingPolicyRules != nil { @@ -2415,19 +2415,19 @@ func (in *VpcDns) DeepCopyObject() runtime.Object { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *VpcDnsCondition) DeepCopyInto(out *VpcDnsCondition) { +func (in *VpcDNSCondition) DeepCopyInto(out *VpcDNSCondition) { *out = *in in.LastUpdateTime.DeepCopyInto(&out.LastUpdateTime) in.LastTransitionTime.DeepCopyInto(&out.LastTransitionTime) return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VpcDnsCondition. -func (in *VpcDnsCondition) DeepCopy() *VpcDnsCondition { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VpcDNSCondition. +func (in *VpcDNSCondition) DeepCopy() *VpcDNSCondition { if in == nil { return nil } - out := new(VpcDnsCondition) + out := new(VpcDNSCondition) in.DeepCopyInto(out) return out } @@ -2466,27 +2466,27 @@ func (in *VpcDnsList) DeepCopyObject() runtime.Object { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *VpcDnsSpec) DeepCopyInto(out *VpcDnsSpec) { +func (in *VpcDNSSpec) DeepCopyInto(out *VpcDNSSpec) { *out = *in return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VpcDnsSpec. -func (in *VpcDnsSpec) DeepCopy() *VpcDnsSpec { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VpcDNSSpec. +func (in *VpcDNSSpec) DeepCopy() *VpcDNSSpec { if in == nil { return nil } - out := new(VpcDnsSpec) + out := new(VpcDNSSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *VpcDnsStatus) DeepCopyInto(out *VpcDnsStatus) { +func (in *VpcDNSStatus) DeepCopyInto(out *VpcDNSStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]VpcDnsCondition, len(*in)) + *out = make([]VpcDNSCondition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -2494,12 +2494,12 @@ func (in *VpcDnsStatus) DeepCopyInto(out *VpcDnsStatus) { return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VpcDnsStatus. -func (in *VpcDnsStatus) DeepCopy() *VpcDnsStatus { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VpcDNSStatus. +func (in *VpcDNSStatus) DeepCopy() *VpcDNSStatus { if in == nil { return nil } - out := new(VpcDnsStatus) + out := new(VpcDNSStatus) in.DeepCopyInto(out) return out } diff --git a/pkg/client/clientset/versioned/fake/register.go b/pkg/client/clientset/versioned/fake/register.go index fa092d649c1..d364c67845d 100644 --- a/pkg/client/clientset/versioned/fake/register.go +++ b/pkg/client/clientset/versioned/fake/register.go @@ -27,8 +27,10 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" ) -var scheme = runtime.NewScheme() -var codecs = serializer.NewCodecFactory(scheme) +var ( + scheme = runtime.NewScheme() + codecs = serializer.NewCodecFactory(scheme) +) var localSchemeBuilder = runtime.SchemeBuilder{ kubeovnv1.AddToScheme, diff --git a/pkg/client/clientset/versioned/scheme/register.go b/pkg/client/clientset/versioned/scheme/register.go index 0aa2b12abff..47246e09959 100644 --- a/pkg/client/clientset/versioned/scheme/register.go +++ b/pkg/client/clientset/versioned/scheme/register.go @@ -27,12 +27,14 @@ import ( utilruntime "k8s.io/apimachinery/pkg/util/runtime" ) -var Scheme = runtime.NewScheme() -var Codecs = serializer.NewCodecFactory(Scheme) -var ParameterCodec = runtime.NewParameterCodec(Scheme) -var localSchemeBuilder = runtime.SchemeBuilder{ - kubeovnv1.AddToScheme, -} +var ( + Scheme = runtime.NewScheme() + Codecs = serializer.NewCodecFactory(Scheme) + ParameterCodec = runtime.NewParameterCodec(Scheme) + localSchemeBuilder = runtime.SchemeBuilder{ + kubeovnv1.AddToScheme, + } +) // AddToScheme adds all types of this clientset into the given scheme. This allows composition // of clientsets, like in: diff --git a/pkg/client/clientset/versioned/typed/kubeovn/v1/fake/fake_vpcdns.go b/pkg/client/clientset/versioned/typed/kubeovn/v1/fake/fake_vpcdns.go index 69127f7e2c4..aaff48e784f 100644 --- a/pkg/client/clientset/versioned/typed/kubeovn/v1/fake/fake_vpcdns.go +++ b/pkg/client/clientset/versioned/typed/kubeovn/v1/fake/fake_vpcdns.go @@ -39,7 +39,7 @@ var vpcdnsesResource = schema.GroupVersionResource{Group: "kubeovn.io", Version: var vpcdnsesKind = schema.GroupVersionKind{Group: "kubeovn.io", Version: "v1", Kind: "VpcDns"} -// Get takes name of the vpcDns, and returns the corresponding vpcDns object, and an error if there is any. +// Get takes name of the vpcDNS, and returns the corresponding vpcDNS object, and an error if there is any. func (c *FakeVpcDnses) Get(ctx context.Context, name string, options v1.GetOptions) (result *kubeovnv1.VpcDns, err error) { obj, err := c.Fake. Invokes(testing.NewRootGetAction(vpcdnsesResource, name), &kubeovnv1.VpcDns{}) @@ -76,20 +76,20 @@ func (c *FakeVpcDnses) Watch(ctx context.Context, opts v1.ListOptions) (watch.In InvokesWatch(testing.NewRootWatchAction(vpcdnsesResource, opts)) } -// Create takes the representation of a vpcDns and creates it. Returns the server's representation of the vpcDns, and an error, if there is any. -func (c *FakeVpcDnses) Create(ctx context.Context, vpcDns *kubeovnv1.VpcDns, opts v1.CreateOptions) (result *kubeovnv1.VpcDns, err error) { +// Create takes the representation of a vpcDNS and creates it. Returns the server's representation of the vpcDNS, and an error, if there is any. +func (c *FakeVpcDnses) Create(ctx context.Context, vpcDNS *kubeovnv1.VpcDns, opts v1.CreateOptions) (result *kubeovnv1.VpcDns, err error) { obj, err := c.Fake. - Invokes(testing.NewRootCreateAction(vpcdnsesResource, vpcDns), &kubeovnv1.VpcDns{}) + Invokes(testing.NewRootCreateAction(vpcdnsesResource, vpcDNS), &kubeovnv1.VpcDns{}) if obj == nil { return nil, err } return obj.(*kubeovnv1.VpcDns), err } -// Update takes the representation of a vpcDns and updates it. Returns the server's representation of the vpcDns, and an error, if there is any. -func (c *FakeVpcDnses) Update(ctx context.Context, vpcDns *kubeovnv1.VpcDns, opts v1.UpdateOptions) (result *kubeovnv1.VpcDns, err error) { +// Update takes the representation of a vpcDNS and updates it. Returns the server's representation of the vpcDNS, and an error, if there is any. +func (c *FakeVpcDnses) Update(ctx context.Context, vpcDNS *kubeovnv1.VpcDns, opts v1.UpdateOptions) (result *kubeovnv1.VpcDns, err error) { obj, err := c.Fake. - Invokes(testing.NewRootUpdateAction(vpcdnsesResource, vpcDns), &kubeovnv1.VpcDns{}) + Invokes(testing.NewRootUpdateAction(vpcdnsesResource, vpcDNS), &kubeovnv1.VpcDns{}) if obj == nil { return nil, err } @@ -98,16 +98,16 @@ func (c *FakeVpcDnses) Update(ctx context.Context, vpcDns *kubeovnv1.VpcDns, opt // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *FakeVpcDnses) UpdateStatus(ctx context.Context, vpcDns *kubeovnv1.VpcDns, opts v1.UpdateOptions) (*kubeovnv1.VpcDns, error) { +func (c *FakeVpcDnses) UpdateStatus(ctx context.Context, vpcDNS *kubeovnv1.VpcDns, opts v1.UpdateOptions) (*kubeovnv1.VpcDns, error) { obj, err := c.Fake. - Invokes(testing.NewRootUpdateSubresourceAction(vpcdnsesResource, "status", vpcDns), &kubeovnv1.VpcDns{}) + Invokes(testing.NewRootUpdateSubresourceAction(vpcdnsesResource, "status", vpcDNS), &kubeovnv1.VpcDns{}) if obj == nil { return nil, err } return obj.(*kubeovnv1.VpcDns), err } -// Delete takes name of the vpcDns and deletes it. Returns an error if one occurs. +// Delete takes name of the vpcDNS and deletes it. Returns an error if one occurs. func (c *FakeVpcDnses) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewRootDeleteActionWithOptions(vpcdnsesResource, name, opts), &kubeovnv1.VpcDns{}) @@ -122,7 +122,7 @@ func (c *FakeVpcDnses) DeleteCollection(ctx context.Context, opts v1.DeleteOptio return err } -// Patch applies the patch and returns the patched vpcDns. +// Patch applies the patch and returns the patched vpcDNS. func (c *FakeVpcDnses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *kubeovnv1.VpcDns, err error) { obj, err := c.Fake. Invokes(testing.NewRootPatchSubresourceAction(vpcdnsesResource, name, pt, data, subresources...), &kubeovnv1.VpcDns{}) diff --git a/pkg/client/clientset/versioned/typed/kubeovn/v1/vpcdns.go b/pkg/client/clientset/versioned/typed/kubeovn/v1/vpcdns.go index a5190ce56af..93210509fcb 100644 --- a/pkg/client/clientset/versioned/typed/kubeovn/v1/vpcdns.go +++ b/pkg/client/clientset/versioned/typed/kubeovn/v1/vpcdns.go @@ -38,9 +38,9 @@ type VpcDnsesGetter interface { // VpcDnsInterface has methods to work with VpcDns resources. type VpcDnsInterface interface { - Create(ctx context.Context, vpcDns *v1.VpcDns, opts metav1.CreateOptions) (*v1.VpcDns, error) - Update(ctx context.Context, vpcDns *v1.VpcDns, opts metav1.UpdateOptions) (*v1.VpcDns, error) - UpdateStatus(ctx context.Context, vpcDns *v1.VpcDns, opts metav1.UpdateOptions) (*v1.VpcDns, error) + Create(ctx context.Context, vpcDNS *v1.VpcDns, opts metav1.CreateOptions) (*v1.VpcDns, error) + Update(ctx context.Context, vpcDNS *v1.VpcDns, opts metav1.UpdateOptions) (*v1.VpcDns, error) + UpdateStatus(ctx context.Context, vpcDNS *v1.VpcDns, opts metav1.UpdateOptions) (*v1.VpcDns, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.VpcDns, error) @@ -62,7 +62,7 @@ func newVpcDnses(c *KubeovnV1Client) *vpcDnses { } } -// Get takes name of the vpcDns, and returns the corresponding vpcDns object, and an error if there is any. +// Get takes name of the vpcDNS, and returns the corresponding vpcDNS object, and an error if there is any. func (c *vpcDnses) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.VpcDns, err error) { result = &v1.VpcDns{} err = c.client.Get(). @@ -104,26 +104,26 @@ func (c *vpcDnses) Watch(ctx context.Context, opts metav1.ListOptions) (watch.In Watch(ctx) } -// Create takes the representation of a vpcDns and creates it. Returns the server's representation of the vpcDns, and an error, if there is any. -func (c *vpcDnses) Create(ctx context.Context, vpcDns *v1.VpcDns, opts metav1.CreateOptions) (result *v1.VpcDns, err error) { +// Create takes the representation of a vpcDNS and creates it. Returns the server's representation of the vpcDNS, and an error, if there is any. +func (c *vpcDnses) Create(ctx context.Context, vpcDNS *v1.VpcDns, opts metav1.CreateOptions) (result *v1.VpcDns, err error) { result = &v1.VpcDns{} err = c.client.Post(). Resource("vpc-dnses"). VersionedParams(&opts, scheme.ParameterCodec). - Body(vpcDns). + Body(vpcDNS). Do(ctx). Into(result) return } -// Update takes the representation of a vpcDns and updates it. Returns the server's representation of the vpcDns, and an error, if there is any. -func (c *vpcDnses) Update(ctx context.Context, vpcDns *v1.VpcDns, opts metav1.UpdateOptions) (result *v1.VpcDns, err error) { +// Update takes the representation of a vpcDNS and updates it. Returns the server's representation of the vpcDNS, and an error, if there is any. +func (c *vpcDnses) Update(ctx context.Context, vpcDNS *v1.VpcDns, opts metav1.UpdateOptions) (result *v1.VpcDns, err error) { result = &v1.VpcDns{} err = c.client.Put(). Resource("vpc-dnses"). - Name(vpcDns.Name). + Name(vpcDNS.Name). VersionedParams(&opts, scheme.ParameterCodec). - Body(vpcDns). + Body(vpcDNS). Do(ctx). Into(result) return @@ -131,20 +131,20 @@ func (c *vpcDnses) Update(ctx context.Context, vpcDns *v1.VpcDns, opts metav1.Up // UpdateStatus was generated because the type contains a Status member. // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). -func (c *vpcDnses) UpdateStatus(ctx context.Context, vpcDns *v1.VpcDns, opts metav1.UpdateOptions) (result *v1.VpcDns, err error) { +func (c *vpcDnses) UpdateStatus(ctx context.Context, vpcDNS *v1.VpcDns, opts metav1.UpdateOptions) (result *v1.VpcDns, err error) { result = &v1.VpcDns{} err = c.client.Put(). Resource("vpc-dnses"). - Name(vpcDns.Name). + Name(vpcDNS.Name). SubResource("status"). VersionedParams(&opts, scheme.ParameterCodec). - Body(vpcDns). + Body(vpcDNS). Do(ctx). Into(result) return } -// Delete takes name of the vpcDns and deletes it. Returns an error if one occurs. +// Delete takes name of the vpcDNS and deletes it. Returns an error if one occurs. func (c *vpcDnses) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error { return c.client.Delete(). Resource("vpc-dnses"). @@ -169,7 +169,7 @@ func (c *vpcDnses) DeleteCollection(ctx context.Context, opts metav1.DeleteOptio Error() } -// Patch applies the patch and returns the patched vpcDns. +// Patch applies the patch and returns the patched vpcDNS. func (c *vpcDnses) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.VpcDns, err error) { result = &v1.VpcDns{} err = c.client.Patch(pt). diff --git a/pkg/client/informers/externalversions/kubeovn/v1/interface.go b/pkg/client/informers/externalversions/kubeovn/v1/interface.go index 2b13d05651d..faa41c15ac4 100644 --- a/pkg/client/informers/externalversions/kubeovn/v1/interface.go +++ b/pkg/client/informers/externalversions/kubeovn/v1/interface.go @@ -169,7 +169,7 @@ func (v *version) Vpcs() VpcInformer { // VpcDnses returns a VpcDnsInformer. func (v *version) VpcDnses() VpcDnsInformer { - return &vpcDnsInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} + return &vpcDNSInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} } // VpcNatGateways returns a VpcNatGatewayInformer. diff --git a/pkg/client/informers/externalversions/kubeovn/v1/vpcdns.go b/pkg/client/informers/externalversions/kubeovn/v1/vpcdns.go index 57ec5af21e5..47ab5339f62 100644 --- a/pkg/client/informers/externalversions/kubeovn/v1/vpcdns.go +++ b/pkg/client/informers/externalversions/kubeovn/v1/vpcdns.go @@ -39,7 +39,7 @@ type VpcDnsInformer interface { Lister() v1.VpcDnsLister } -type vpcDnsInformer struct { +type vpcDNSInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc } @@ -76,14 +76,14 @@ func NewFilteredVpcDnsInformer(client versioned.Interface, resyncPeriod time.Dur ) } -func (f *vpcDnsInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { +func (f *vpcDNSInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return NewFilteredVpcDnsInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) } -func (f *vpcDnsInformer) Informer() cache.SharedIndexInformer { +func (f *vpcDNSInformer) Informer() cache.SharedIndexInformer { return f.factory.InformerFor(&kubeovnv1.VpcDns{}, f.defaultInformer) } -func (f *vpcDnsInformer) Lister() v1.VpcDnsLister { +func (f *vpcDNSInformer) Lister() v1.VpcDnsLister { return v1.NewVpcDnsLister(f.Informer().GetIndexer()) } diff --git a/pkg/client/listers/kubeovn/v1/vpcdns.go b/pkg/client/listers/kubeovn/v1/vpcdns.go index 5eaf1929c5f..fd6e3715941 100644 --- a/pkg/client/listers/kubeovn/v1/vpcdns.go +++ b/pkg/client/listers/kubeovn/v1/vpcdns.go @@ -37,18 +37,18 @@ type VpcDnsLister interface { VpcDnsListerExpansion } -// vpcDnsLister implements the VpcDnsLister interface. -type vpcDnsLister struct { +// vpcDNSLister implements the VpcDnsLister interface. +type vpcDNSLister struct { indexer cache.Indexer } // NewVpcDnsLister returns a new VpcDnsLister. func NewVpcDnsLister(indexer cache.Indexer) VpcDnsLister { - return &vpcDnsLister{indexer: indexer} + return &vpcDNSLister{indexer: indexer} } // List lists all VpcDnses in the indexer. -func (s *vpcDnsLister) List(selector labels.Selector) (ret []*v1.VpcDns, err error) { +func (s *vpcDNSLister) List(selector labels.Selector) (ret []*v1.VpcDns, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1.VpcDns)) }) @@ -56,7 +56,7 @@ func (s *vpcDnsLister) List(selector labels.Selector) (ret []*v1.VpcDns, err err } // Get retrieves the VpcDns from the index for a given name. -func (s *vpcDnsLister) Get(name string) (*v1.VpcDns, error) { +func (s *vpcDNSLister) Get(name string) (*v1.VpcDns, error) { obj, exists, err := s.indexer.GetByKey(name) if err != nil { return nil, err diff --git a/pkg/controller/config.go b/pkg/controller/config.go index b567e8ee6f3..e8bf142fd2f 100644 --- a/pkg/controller/config.go +++ b/pkg/controller/config.go @@ -53,11 +53,11 @@ type Configuration struct { ServiceClusterIPRange string - ClusterTcpLoadBalancer string - ClusterUdpLoadBalancer string + ClusterTCPLoadBalancer string + ClusterUDPLoadBalancer string ClusterSctpLoadBalancer string - ClusterTcpSessionLoadBalancer string - ClusterUdpSessionLoadBalancer string + ClusterTCPSessionLoadBalancer string + ClusterUDPSessionLoadBalancer string ClusterSctpSessionLoadBalancer string PodName string @@ -84,7 +84,7 @@ type Configuration struct { EnableEipSnat bool EnableExternalVpc bool EnableEcmp bool - EnableKeepVmIP bool + EnableKeepVMIP bool EnableLbSvc bool EnableMetrics bool @@ -100,7 +100,7 @@ type Configuration struct { BfdMinRx int BfdDetectMult int - NodeLocalDnsIP string + NodeLocalDNSIP string } // ParseFlags parses cmd args then init kubeclient and conf @@ -130,11 +130,11 @@ func ParseFlags() (*Configuration, error) { argServiceClusterIPRange = pflag.String("service-cluster-ip-range", "10.96.0.0/12", "The kubernetes service cluster ip range") - argClusterTcpLoadBalancer = pflag.String("cluster-tcp-loadbalancer", "cluster-tcp-loadbalancer", "The name for cluster tcp loadbalancer") - argClusterUdpLoadBalancer = pflag.String("cluster-udp-loadbalancer", "cluster-udp-loadbalancer", "The name for cluster udp loadbalancer") + argClusterTCPLoadBalancer = pflag.String("cluster-tcp-loadbalancer", "cluster-tcp-loadbalancer", "The name for cluster tcp loadbalancer") + argClusterUDPLoadBalancer = pflag.String("cluster-udp-loadbalancer", "cluster-udp-loadbalancer", "The name for cluster udp loadbalancer") argClusterSctpLoadBalancer = pflag.String("cluster-sctp-loadbalancer", "cluster-sctp-loadbalancer", "The name for cluster sctp loadbalancer") - argClusterTcpSessionLoadBalancer = pflag.String("cluster-tcp-session-loadbalancer", "cluster-tcp-session-loadbalancer", "The name for cluster tcp session loadbalancer") - argClusterUdpSessionLoadBalancer = pflag.String("cluster-udp-session-loadbalancer", "cluster-udp-session-loadbalancer", "The name for cluster udp session loadbalancer") + argClusterTCPSessionLoadBalancer = pflag.String("cluster-tcp-session-loadbalancer", "cluster-tcp-session-loadbalancer", "The name for cluster tcp session loadbalancer") + argClusterUDPSessionLoadBalancer = pflag.String("cluster-udp-session-loadbalancer", "cluster-udp-session-loadbalancer", "The name for cluster udp session loadbalancer") argClusterSctpSessionLoadBalancer = pflag.String("cluster-sctp-session-loadbalancer", "cluster-sctp-session-loadbalancer", "The name for cluster sctp session loadbalancer") argWorkerNum = pflag.Int("worker-num", 3, "The parallelism of each worker") @@ -156,7 +156,7 @@ func ParseFlags() (*Configuration, error) { argEnableEipSnat = pflag.Bool("enable-eip-snat", true, "Enable EIP and SNAT") argEnableExternalVpc = pflag.Bool("enable-external-vpc", true, "Enable external vpc support") argEnableEcmp = pflag.Bool("enable-ecmp", false, "Enable ecmp route for centralized subnet") - argKeepVmIP = pflag.Bool("keep-vm-ip", true, "Whether to keep ip for kubevirt pod when pod is rebuild") + argKeepVMIP = pflag.Bool("keep-vm-ip", true, "Whether to keep ip for kubevirt pod when pod is rebuild") argEnableLbSvc = pflag.Bool("enable-lb-svc", false, "Whether to support loadbalancer service") argEnableMetrics = pflag.Bool("enable-metrics", true, "Whether to support metrics query") @@ -164,7 +164,7 @@ func ParseFlags() (*Configuration, error) { argExternalGatewaySwitch = pflag.String("external-gateway-switch", "external", "The name of the external gateway switch which is a ovs bridge to provide external network, default: external") argExternalGatewayNet = pflag.String("external-gateway-net", "external", "The name of the external network which mappings with an ovs bridge, default: external") argExternalGatewayVlanID = pflag.Int("external-gateway-vlanid", 0, "The vlanId of port ln-ovn-external, default: 0") - argNodeLocalDnsIP = pflag.String("node-local-dns-ip", "", "The node local dns ip , this feature is using the local dns cache in k8s") + argNodeLocalDNSIP = pflag.String("node-local-dns-ip", "", "The node local dns ip , this feature is using the local dns cache in k8s") argGCInterval = pflag.Int("gc-interval", 360, "The interval between GC processes, default 360 seconds") argInspectInterval = pflag.Int("inspect-interval", 20, "The interval between inspect processes, default 20 seconds") @@ -211,11 +211,11 @@ func ParseFlags() (*Configuration, error) { NodeSwitchCIDR: *argNodeSwitchCIDR, NodeSwitchGateway: *argNodeSwitchGateway, ServiceClusterIPRange: *argServiceClusterIPRange, - ClusterTcpLoadBalancer: *argClusterTcpLoadBalancer, - ClusterUdpLoadBalancer: *argClusterUdpLoadBalancer, + ClusterTCPLoadBalancer: *argClusterTCPLoadBalancer, + ClusterUDPLoadBalancer: *argClusterUDPLoadBalancer, ClusterSctpLoadBalancer: *argClusterSctpLoadBalancer, - ClusterTcpSessionLoadBalancer: *argClusterTcpSessionLoadBalancer, - ClusterUdpSessionLoadBalancer: *argClusterUdpSessionLoadBalancer, + ClusterTCPSessionLoadBalancer: *argClusterTCPSessionLoadBalancer, + ClusterUDPSessionLoadBalancer: *argClusterUDPSessionLoadBalancer, ClusterSctpSessionLoadBalancer: *argClusterSctpSessionLoadBalancer, WorkerNum: *argWorkerNum, EnablePprof: *argEnablePprof, @@ -240,7 +240,7 @@ func ParseFlags() (*Configuration, error) { ExternalGatewayNet: *argExternalGatewayNet, ExternalGatewayVlanID: *argExternalGatewayVlanID, EnableEcmp: *argEnableEcmp, - EnableKeepVmIP: *argKeepVmIP, + EnableKeepVMIP: *argKeepVMIP, NodePgProbeTime: *argNodePgProbeTime, GCInterval: *argGCInterval, InspectInterval: *argInspectInterval, @@ -249,7 +249,7 @@ func ParseFlags() (*Configuration, error) { BfdMinTx: *argBfdMinTx, BfdMinRx: *argBfdMinRx, BfdDetectMult: *argBfdDetectMult, - NodeLocalDnsIP: *argNodeLocalDnsIP, + NodeLocalDNSIP: *argNodeLocalDNSIP, } if config.NetworkType == util.NetworkTypeVlan && config.DefaultHostInterface == "" { @@ -309,7 +309,7 @@ func (config *Configuration) initKubeClient() error { } // try to connect to apiserver's tcp port - if err = util.DialApiServer(cfg.Host); err != nil { + if err = util.DialAPIServer(cfg.Host); err != nil { klog.Errorf("failed to dial apiserver: %v", err) return err } diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index de3332d6be7..b81481ecb45 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -48,15 +48,16 @@ const ( type Controller struct { config *Configuration vpcs *sync.Map - //subnetVpcMap *sync.Map + + // subnetVpcMap *sync.Map podSubnetMap *sync.Map ipam *ovnipam.IPAM namedPort *NamedPort ovnLegacyClient *ovs.LegacyClient - ovnNbClient ovs.NbClient - ovnSbClient ovs.SbClient + OVNNbClient ovs.NbClient + OVNSbClient ovs.SbClient // ExternalGatewayType define external gateway type, centralized ExternalGatewayType string @@ -82,7 +83,7 @@ type Controller struct { delVpcNatGatewayQueue workqueue.RateLimitingInterface initVpcNatGatewayQueue workqueue.RateLimitingInterface updateVpcEipQueue workqueue.RateLimitingInterface - updateVpcFloatingIpQueue workqueue.RateLimitingInterface + updateVpcFloatingIPQueue workqueue.RateLimitingInterface updateVpcDnatQueue workqueue.RateLimitingInterface updateVpcSnatQueue workqueue.RateLimitingInterface updateVpcSubnetQueue workqueue.RateLimitingInterface @@ -94,10 +95,10 @@ type Controller struct { UpdateSwitchLBRuleQueue workqueue.RateLimitingInterface delSwitchLBRuleQueue workqueue.RateLimitingInterface - vpcDnsLister kubeovnlister.VpcDnsLister - vpcDnsSynced cache.InformerSynced - addOrUpdateVpcDnsQueue workqueue.RateLimitingInterface - delVpcDnsQueue workqueue.RateLimitingInterface + vpcDNSLister kubeovnlister.VpcDnsLister + vpcDNSSynced cache.InformerSynced + addOrUpdateVpcDNSQueue workqueue.RateLimitingInterface + delVpcDNSQueue workqueue.RateLimitingInterface subnetsLister kubeovnlister.SubnetLister subnetSynced cache.InformerSynced @@ -119,9 +120,9 @@ type Controller struct { virtualIpsLister kubeovnlister.VipLister virtualIpsSynced cache.InformerSynced - addVirtualIpQueue workqueue.RateLimitingInterface - updateVirtualIpQueue workqueue.RateLimitingInterface - delVirtualIpQueue workqueue.RateLimitingInterface + addVirtualIPQueue workqueue.RateLimitingInterface + updateVirtualIPQueue workqueue.RateLimitingInterface + delVirtualIPQueue workqueue.RateLimitingInterface iptablesEipsLister kubeovnlister.IptablesEIPLister iptablesEipSynced cache.InformerSynced @@ -278,7 +279,7 @@ func Run(ctx context.Context, config *Configuration) { subnetInformer := kubeovnInformerFactory.Kubeovn().V1().Subnets() ippoolInformer := kubeovnInformerFactory.Kubeovn().V1().IPPools() ipInformer := kubeovnInformerFactory.Kubeovn().V1().IPs() - virtualIpInformer := kubeovnInformerFactory.Kubeovn().V1().Vips() + virtualIPInformer := kubeovnInformerFactory.Kubeovn().V1().Vips() iptablesEipInformer := kubeovnInformerFactory.Kubeovn().V1().IptablesEIPs() iptablesFipInformer := kubeovnInformerFactory.Kubeovn().V1().IptablesFIPRules() iptablesDnatRuleInformer := kubeovnInformerFactory.Kubeovn().V1().IptablesDnatRules() @@ -297,7 +298,7 @@ func Run(ctx context.Context, config *Configuration) { configMapInformer := cmInformerFactory.Core().V1().ConfigMaps() npInformer := informerFactory.Networking().V1().NetworkPolicies() switchLBRuleInformer := kubeovnInformerFactory.Kubeovn().V1().SwitchLBRules() - vpcDnsInformer := kubeovnInformerFactory.Kubeovn().V1().VpcDnses() + vpcDNSInformer := kubeovnInformerFactory.Kubeovn().V1().VpcDnses() ovnEipInformer := kubeovnInformerFactory.Kubeovn().V1().OvnEips() ovnFipInformer := kubeovnInformerFactory.Kubeovn().V1().OvnFips() ovnSnatRuleInformer := kubeovnInformerFactory.Kubeovn().V1().OvnSnatRules() @@ -329,7 +330,7 @@ func Run(ctx context.Context, config *Configuration) { initVpcNatGatewayQueue: workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "InitVpcNatGw"), delVpcNatGatewayQueue: workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "DeleteVpcNatGw"), updateVpcEipQueue: workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "UpdateVpcEip"), - updateVpcFloatingIpQueue: workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "UpdateVpcFloatingIp"), + updateVpcFloatingIPQueue: workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "UpdateVpcFloatingIp"), updateVpcDnatQueue: workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "UpdateVpcDnat"), updateVpcSnatQueue: workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "UpdateVpcSnat"), updateVpcSubnetQueue: workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "UpdateVpcSubnet"), @@ -353,11 +354,11 @@ func Run(ctx context.Context, config *Configuration) { ipsLister: ipInformer.Lister(), ipSynced: ipInformer.Informer().HasSynced, - virtualIpsLister: virtualIpInformer.Lister(), - virtualIpsSynced: virtualIpInformer.Informer().HasSynced, - addVirtualIpQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "AddVirtualIp"), - updateVirtualIpQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "UpdateVirtualIp"), - delVirtualIpQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "DeleteVirtualIp"), + virtualIpsLister: virtualIPInformer.Lister(), + virtualIpsSynced: virtualIPInformer.Informer().HasSynced, + addVirtualIPQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "AddVirtualIp"), + updateVirtualIPQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "UpdateVirtualIp"), + delVirtualIPQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "DeleteVirtualIp"), iptablesEipsLister: iptablesEipInformer.Lister(), iptablesEipSynced: iptablesEipInformer.Informer().HasSynced, @@ -488,10 +489,10 @@ func Run(ctx context.Context, config *Configuration) { } var err error - if controller.ovnNbClient, err = ovs.NewOvnNbClient(config.OvnNbAddr, config.OvnTimeout); err != nil { + if controller.OVNNbClient, err = ovs.NewOvnNbClient(config.OvnNbAddr, config.OvnTimeout); err != nil { util.LogFatalAndExit(err, "failed to create ovn nb client") } - if controller.ovnSbClient, err = ovs.NewOvnSbClient(config.OvnSbAddr, config.OvnTimeout); err != nil { + if controller.OVNSbClient, err = ovs.NewOvnSbClient(config.OvnSbAddr, config.OvnTimeout); err != nil { util.LogFatalAndExit(err, "failed to create ovn sb client") } if config.EnableLb { @@ -501,10 +502,10 @@ func Run(ctx context.Context, config *Configuration) { controller.delSwitchLBRuleQueue = workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "delSwitchLBRule") controller.UpdateSwitchLBRuleQueue = workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "updateSwitchLBRule") - controller.vpcDnsLister = vpcDnsInformer.Lister() - controller.vpcDnsSynced = vpcDnsInformer.Informer().HasSynced - controller.addOrUpdateVpcDnsQueue = workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "AddOrUpdateVpcDns") - controller.delVpcDnsQueue = workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "DeleteVpcDns") + controller.vpcDNSLister = vpcDNSInformer.Lister() + controller.vpcDNSSynced = vpcDNSInformer.Informer().HasSynced + controller.addOrUpdateVpcDNSQueue = workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "AddOrUpdateVpcDns") + controller.delVpcDNSQueue = workqueue.NewNamedRateLimitingQueue(custCrdRateLimiter, "DeleteVpcDns") } if config.EnableNP { @@ -535,7 +536,7 @@ func Run(ctx context.Context, config *Configuration) { controller.ovnDnatRuleSynced, } if controller.config.EnableLb { - cacheSyncs = append(cacheSyncs, controller.switchLBRuleSynced, controller.vpcDnsSynced) + cacheSyncs = append(cacheSyncs, controller.switchLBRuleSynced, controller.vpcDNSSynced) } if controller.config.EnableNP { cacheSyncs = append(cacheSyncs, controller.npsSynced) @@ -639,10 +640,10 @@ func Run(ctx context.Context, config *Configuration) { util.LogFatalAndExit(err, "failed to add security group event handler") } - if _, err = virtualIpInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: controller.enqueueAddVirtualIp, - UpdateFunc: controller.enqueueUpdateVirtualIp, - DeleteFunc: controller.enqueueDelVirtualIp, + if _, err = virtualIPInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ + AddFunc: controller.enqueueAddVirtualIP, + UpdateFunc: controller.enqueueUpdateVirtualIP, + DeleteFunc: controller.enqueueDelVirtualIP, }); err != nil { util.LogFatalAndExit(err, "failed to add virtual ip event handler") } @@ -743,10 +744,10 @@ func Run(ctx context.Context, config *Configuration) { util.LogFatalAndExit(err, "failed to add switch lb rule event handler") } - if _, err = vpcDnsInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ - AddFunc: controller.enqueueAddVpcDns, - UpdateFunc: controller.enqueueUpdateVpcDns, - DeleteFunc: controller.enqueueDeleteVpcDns, + if _, err = vpcDNSInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ + AddFunc: controller.enqueueAddVpcDNS, + UpdateFunc: controller.enqueueUpdateVpcDNS, + DeleteFunc: controller.enqueueDeleteVPCDNS, }); err != nil { util.LogFatalAndExit(err, "failed to add vpc dns event handler") } @@ -772,11 +773,11 @@ func Run(ctx context.Context, config *Configuration) { func (c *Controller) Run(ctx context.Context) { // The init process can only be placed here if the init process do really affect the normal process of controller, such as Nodes/Pods/Subnets... // Otherwise, the init process should be placed after all workers have already started working - if err := c.ovnNbClient.SetLsDnatModDlDst(c.config.LsDnatModDlDst); err != nil { + if err := c.OVNNbClient.SetLsDnatModDlDst(c.config.LsDnatModDlDst); err != nil { util.LogFatalAndExit(err, "failed to set NB_Global option ls_dnat_mod_dl_dst") } - if err := c.ovnNbClient.SetUseCtInvMatch(); err != nil { + if err := c.OVNNbClient.SetUseCtInvMatch(); err != nil { util.LogFatalAndExit(err, "failed to set NB_Global option use_ct_inv_match to false") } @@ -859,7 +860,7 @@ func (c *Controller) shutdown() { c.initVpcNatGatewayQueue.ShutDown() c.delVpcNatGatewayQueue.ShutDown() c.updateVpcEipQueue.ShutDown() - c.updateVpcFloatingIpQueue.ShutDown() + c.updateVpcFloatingIPQueue.ShutDown() c.updateVpcDnatQueue.ShutDown() c.updateVpcSnatQueue.ShutDown() c.updateVpcSubnetQueue.ShutDown() @@ -869,13 +870,13 @@ func (c *Controller) shutdown() { c.delSwitchLBRuleQueue.ShutDown() c.UpdateSwitchLBRuleQueue.ShutDown() - c.addOrUpdateVpcDnsQueue.ShutDown() - c.delVpcDnsQueue.ShutDown() + c.addOrUpdateVpcDNSQueue.ShutDown() + c.delVpcDNSQueue.ShutDown() } - c.addVirtualIpQueue.ShutDown() - c.updateVirtualIpQueue.ShutDown() - c.delVirtualIpQueue.ShutDown() + c.addVirtualIPQueue.ShutDown() + c.updateVirtualIPQueue.ShutDown() + c.delVirtualIPQueue.ShutDown() c.addIptablesEipQueue.ShutDown() c.updateIptablesEipQueue.ShutDown() @@ -941,7 +942,7 @@ func (c *Controller) startWorkers(ctx context.Context) { go wait.Until(c.runAddOrUpdateVpcNatGwWorker, time.Second, ctx.Done()) go wait.Until(c.runInitVpcNatGwWorker, time.Second, ctx.Done()) go wait.Until(c.runDelVpcNatGwWorker, time.Second, ctx.Done()) - go wait.Until(c.runUpdateVpcFloatingIpWorker, time.Second, ctx.Done()) + go wait.Until(c.runUpdateVpcFloatingIPWorker, time.Second, ctx.Done()) go wait.Until(c.runUpdateVpcEipWorker, time.Second, ctx.Done()) go wait.Until(c.runUpdateVpcDnatWorker, time.Second, ctx.Done()) go wait.Until(c.runUpdateVpcSnatWorker, time.Second, ctx.Done()) @@ -1003,10 +1004,10 @@ func (c *Controller) startWorkers(ctx context.Context) { go wait.Until(c.runDelSwitchLBRuleWorker, time.Second, ctx.Done()) go wait.Until(c.runUpdateSwitchLBRuleWorker, time.Second, ctx.Done()) - go wait.Until(c.runAddOrUpdateVpcDnsWorker, time.Second, ctx.Done()) - go wait.Until(c.runDelVpcDnsWorker, time.Second, ctx.Done()) + go wait.Until(c.runAddOrUpdateVPCDNSWorker, time.Second, ctx.Done()) + go wait.Until(c.runDelVPCDNSWorker, time.Second, ctx.Done()) go wait.Until(func() { - c.resyncVpcDnsConfig() + c.resyncVpcDNSConfig() }, 5*time.Second, ctx.Done()) } @@ -1094,9 +1095,9 @@ func (c *Controller) startWorkers(ctx context.Context) { go wait.Until(c.CheckNodePortGroup, time.Duration(c.config.NodePgProbeTime)*time.Minute, ctx.Done()) } - go wait.Until(c.runAddVirtualIpWorker, time.Second, ctx.Done()) - go wait.Until(c.runUpdateVirtualIpWorker, time.Second, ctx.Done()) - go wait.Until(c.runDelVirtualIpWorker, time.Second, ctx.Done()) + go wait.Until(c.runAddVirtualIPWorker, time.Second, ctx.Done()) + go wait.Until(c.runUpdateVirtualIPWorker, time.Second, ctx.Done()) + go wait.Until(c.runDelVirtualIPWorker, time.Second, ctx.Done()) go wait.Until(c.runAddIptablesEipWorker, time.Second, ctx.Done()) go wait.Until(c.runUpdateIptablesEipWorker, time.Second, ctx.Done()) @@ -1130,7 +1131,7 @@ func (c *Controller) startWorkers(ctx context.Context) { func (c *Controller) allSubnetReady(subnets ...string) (bool, error) { for _, lsName := range subnets { - exist, err := c.ovnNbClient.LogicalSwitchExists(lsName) + exist, err := c.OVNNbClient.LogicalSwitchExists(lsName) if err != nil { return false, fmt.Errorf("check logical switch %s exist: %v", lsName, err) } @@ -1161,7 +1162,7 @@ func (c *Controller) initResourceOnce() { } if c.config.EnableLb { - if err := c.initVpcDnsConfig(); err != nil { + if err := c.initVpcDNSConfig(); err != nil { util.LogFatalAndExit(err, "failed to initialize vpc-dns") } } diff --git a/pkg/controller/controller_test.go b/pkg/controller/controller_test.go index b19c463840d..f5e62425469 100644 --- a/pkg/controller/controller_test.go +++ b/pkg/controller/controller_test.go @@ -58,7 +58,7 @@ func newFakeController(t *testing.T) *fakeController { vpcSynced: alwaysReady, subnetsLister: sbunetInformer.Lister(), subnetSynced: alwaysReady, - ovnNbClient: mockOvnClient, + OVNNbClient: mockOvnClient, syncVirtualPortsQueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), ""), } diff --git a/pkg/controller/endpoint.go b/pkg/controller/endpoint.go index 642b495fa1b..ed51d477b6b 100644 --- a/pkg/controller/endpoint.go +++ b/pkg/controller/endpoint.go @@ -26,10 +26,9 @@ func (c *Controller) enqueueAddEndpoint(obj interface{}) { c.updateEndpointQueue.Add(key) } -func (c *Controller) enqueueUpdateEndpoint(old, new interface{}) { - - oldEp := old.(*v1.Endpoints) - newEp := new.(*v1.Endpoints) +func (c *Controller) enqueueUpdateEndpoint(oldObj, newObj interface{}) { + oldEp := oldObj.(*v1.Endpoints) + newEp := newObj.(*v1.Endpoints) if oldEp.ResourceVersion == newEp.ResourceVersion { return } @@ -40,7 +39,7 @@ func (c *Controller) enqueueUpdateEndpoint(old, new interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } @@ -76,7 +75,6 @@ func (c *Controller) processNextUpdateEndpointWorkItem() bool { c.updateEndpointQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -173,10 +171,10 @@ func (c *Controller) handleUpdateEndpoint(key string) error { } } - tcpLb, udpLb, sctpLb := vpc.Status.TcpLoadBalancer, vpc.Status.UdpLoadBalancer, vpc.Status.SctpLoadBalancer - oldTcpLb, oldUdpLb, oldSctpLb := vpc.Status.TcpSessionLoadBalancer, vpc.Status.UdpSessionLoadBalancer, vpc.Status.SctpSessionLoadBalancer + tcpLb, udpLb, sctpLb := vpc.Status.TCPLoadBalancer, vpc.Status.UDPLoadBalancer, vpc.Status.SctpLoadBalancer + oldTCPLb, oldUDPLb, oldSctpLb := vpc.Status.TCPSessionLoadBalancer, vpc.Status.UDPSessionLoadBalancer, vpc.Status.SctpSessionLoadBalancer if svc.Spec.SessionAffinity == v1.ServiceAffinityClientIP { - tcpLb, udpLb, sctpLb, oldTcpLb, oldUdpLb, oldSctpLb = oldTcpLb, oldUdpLb, oldSctpLb, tcpLb, udpLb, sctpLb + tcpLb, udpLb, sctpLb, oldTCPLb, oldUDPLb, oldSctpLb = oldTCPLb, oldUDPLb, oldSctpLb, tcpLb, udpLb, sctpLb } for _, settingIP := range LbIPs { @@ -184,9 +182,9 @@ func (c *Controller) handleUpdateEndpoint(key string) error { var lb, oldLb string switch port.Protocol { case v1.ProtocolTCP: - lb, oldLb = tcpLb, oldTcpLb + lb, oldLb = tcpLb, oldTCPLb case v1.ProtocolUDP: - lb, oldLb = udpLb, oldUdpLb + lb, oldLb = udpLb, oldUDPLb case v1.ProtocolSCTP: lb, oldLb = sctpLb, oldSctpLb } @@ -197,18 +195,18 @@ func (c *Controller) handleUpdateEndpoint(key string) error { // for performance reason delete lb with no backends if len(backends) != 0 { klog.V(3).Infof("update vip %s with backends %s to LB %s", vip, backends, lb) - if err = c.ovnNbClient.LoadBalancerAddVip(lb, vip, backends...); err != nil { + if err = c.OVNNbClient.LoadBalancerAddVip(lb, vip, backends...); err != nil { klog.Errorf("failed to add vip %s with backends %s to LB %s: %v", vip, backends, lb, err) return err } } else { klog.V(3).Infof("delete vip %s from LB %s", vip, lb) - if err := c.ovnNbClient.LoadBalancerDeleteVip(lb, vip); err != nil { + if err := c.OVNNbClient.LoadBalancerDeleteVip(lb, vip); err != nil { klog.Errorf("failed to delete vip %s from LB %s: %v", vip, lb, err) return err } klog.V(3).Infof("delete vip %s from old LB %s", vip, lb) - if err := c.ovnNbClient.LoadBalancerDeleteVip(oldLb, vip); err != nil { + if err := c.OVNNbClient.LoadBalancerDeleteVip(oldLb, vip); err != nil { klog.Errorf("failed to delete vip %s from LB %s: %v", vip, lb, err) return err } diff --git a/pkg/controller/exporter.go b/pkg/controller/exporter.go index e5399dfdf64..a493fb5ed85 100644 --- a/pkg/controller/exporter.go +++ b/pkg/controller/exporter.go @@ -40,11 +40,12 @@ func (c *Controller) exportSubnetMetrics() bool { func (c *Controller) exportSubnetAvailableIPsGauge(subnet *kubeovnv1.Subnet) { var availableIPs float64 - if subnet.Spec.Protocol == kubeovnv1.ProtocolIPv4 { + switch subnet.Spec.Protocol { + case kubeovnv1.ProtocolIPv4: availableIPs = subnet.Status.V4AvailableIPs - } else if subnet.Spec.Protocol == kubeovnv1.ProtocolIPv6 { + case kubeovnv1.ProtocolIPv6: availableIPs = subnet.Status.V6AvailableIPs - } else { + default: availableIPs = math.Min(subnet.Status.V4AvailableIPs, subnet.Status.V6AvailableIPs) } metricSubnetAvailableIPs.WithLabelValues(subnet.Name, subnet.Spec.Protocol, subnet.Spec.CIDRBlock).Set(availableIPs) diff --git a/pkg/controller/external-gw.go b/pkg/controller/external-gw.go index 02b96ca279f..10e25310bf0 100644 --- a/pkg/controller/external-gw.go +++ b/pkg/controller/external-gw.go @@ -17,8 +17,8 @@ import ( ) var ( - exGwEnabled = "unknown" - lastExGwCM map[string]string = nil + exGwEnabled = "unknown" + lastExGwCM map[string]string ) func (c *Controller) resyncExternalGateway() { @@ -45,33 +45,33 @@ func (c *Controller) resyncExternalGateway() { lastExGwCM = nil klog.Info("finish remove ovn external gw") return - } else { - if exGwEnabled == "true" && lastExGwCM != nil && reflect.DeepEqual(cm.Data, lastExGwCM) { - return - } - klog.Infof("last external gw configmap: %v", lastExGwCM) - if (lastExGwCM["type"] == "distributed" && cm.Data["type"] == "centralized") || - lastExGwCM != nil && !reflect.DeepEqual(lastExGwCM["external-gw-nodes"], cm.Data["external-gw-nodes"]) { - klog.Info("external gw nodes list changed, start to remove ovn external gw") - if err := c.removeExternalGateway(); err != nil { - klog.Errorf("failed to remove old ovn external gw, %v", err) - return - } - } - klog.Info("start to establish ovn external gw") - if err := c.establishExternalGateway(cm.Data); err != nil { - klog.Errorf("failed to establish ovn-external-gw, %v", err) - return - } - exGwEnabled = "true" - lastExGwCM = cm.Data - c.ExternalGatewayType = cm.Data["type"] - if err := c.updateDefaultVpcExternal(true); err != nil { - klog.Error("failed to update default vpc, %v", err) + } + + if exGwEnabled == "true" && lastExGwCM != nil && reflect.DeepEqual(cm.Data, lastExGwCM) { + return + } + klog.Infof("last external gw configmap: %v", lastExGwCM) + if (lastExGwCM["type"] == "distributed" && cm.Data["type"] == "centralized") || + lastExGwCM != nil && !reflect.DeepEqual(lastExGwCM["external-gw-nodes"], cm.Data["external-gw-nodes"]) { + klog.Info("external gw nodes list changed, start to remove ovn external gw") + if err := c.removeExternalGateway(); err != nil { + klog.Errorf("failed to remove old ovn external gw, %v", err) return } - klog.Info("finish establishing ovn external gw") } + klog.Info("start to establish ovn external gw") + if err := c.establishExternalGateway(cm.Data); err != nil { + klog.Errorf("failed to establish ovn-external-gw, %v", err) + return + } + exGwEnabled = "true" + lastExGwCM = cm.Data + c.ExternalGatewayType = cm.Data["type"] + if err := c.updateDefaultVpcExternal(true); err != nil { + klog.Error("failed to update default vpc, %v", err) + return + } + klog.Info("finish establishing ovn external gw") } func (c *Controller) removeExternalGateway() error { @@ -83,8 +83,7 @@ func (c *Controller) removeExternalGateway() error { } for _, cachedNode := range nodes { no := cachedNode.DeepCopy() - patchPayloadTemplate := - `[{ + patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/labels", "value": %s @@ -118,7 +117,7 @@ func (c *Controller) removeExternalGateway() error { if !keepExternalSubnet { klog.Infof("delete external gateway switch %s", c.config.ExternalGatewaySwitch) - if err := c.ovnNbClient.DeleteLogicalGatewaySwitch(util.ExternalGatewaySwitch, c.config.ClusterRouter); err != nil { + if err := c.OVNNbClient.DeleteLogicalGatewaySwitch(util.ExternalGatewaySwitch, c.config.ClusterRouter); err != nil { klog.Errorf("delete external gateway switch %s: %v", util.ExternalGatewaySwitch, err) return err } @@ -126,7 +125,7 @@ func (c *Controller) removeExternalGateway() error { klog.Infof("should keep provider network vlan underlay external gateway switch %s", c.config.ExternalGatewaySwitch) lrpName := fmt.Sprintf("%s-%s", c.config.ClusterRouter, c.config.ExternalGatewaySwitch) klog.Infof("delete logical router port %s", lrpName) - if err := c.ovnNbClient.DeleteLogicalRouterPort(lrpName); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPort(lrpName); err != nil { klog.Errorf("failed to delete lrp %s, %v", lrpName, err) return err } @@ -140,27 +139,30 @@ func (c *Controller) establishExternalGateway(config map[string]string) error { klog.Errorf("failed to get gateway chassis, %v", err) return err } - var lrpIp, lrpMac string + var lrpIP, lrpMac string lrpName := fmt.Sprintf("%s-%s", c.config.ClusterRouter, c.config.ExternalGatewaySwitch) - lrp, err := c.ovnNbClient.GetLogicalRouterPort(lrpName, true) + lrp, err := c.OVNNbClient.GetLogicalRouterPort(lrpName, true) if err != nil { klog.Errorf("failed to get lrp %s, %v", lrpName, err) return err } - if lrp != nil { + + switch { + case lrp != nil: klog.Infof("lrp %s already exist", lrpName) lrpMac = lrp.MAC - lrpIp = lrp.Networks[0] - } else if config["nic-ip"] == "" { - if lrpIp, lrpMac, err = c.createDefaultVpcLrpEip(config); err != nil { + lrpIP = lrp.Networks[0] + case config["nic-ip"] == "": + if lrpIP, lrpMac, err = c.createDefaultVpcLrpEip(); err != nil { klog.Errorf("failed to create ovn eip for default vpc lrp: %v", err) return err } - } else { - lrpIp = config["nic-ip"] + default: + lrpIP = config["nic-ip"] lrpMac = config["nic-mac"] } - if err := c.ovnNbClient.CreateGatewayLogicalSwitch(c.config.ExternalGatewaySwitch, c.config.ClusterRouter, c.config.ExternalGatewayNet, lrpIp, lrpMac, c.config.ExternalGatewayVlanID, chassises...); err != nil { + + if err := c.OVNNbClient.CreateGatewayLogicalSwitch(c.config.ExternalGatewaySwitch, c.config.ClusterRouter, c.config.ExternalGatewayNet, lrpIP, lrpMac, c.config.ExternalGatewayVlanID, chassises...); err != nil { klog.Errorf("create external gateway switch %s: %v", c.config.ExternalGatewaySwitch, err) return err } @@ -168,7 +170,7 @@ func (c *Controller) establishExternalGateway(config map[string]string) error { return nil } -func (c *Controller) createDefaultVpcLrpEip(config map[string]string) (string, string, error) { +func (c *Controller) createDefaultVpcLrpEip() (string, string, error) { cachedSubnet, err := c.subnetsLister.Get(c.config.ExternalGatewaySwitch) if err != nil { klog.Errorf("failed to get subnet %s, %v", c.config.ExternalGatewaySwitch, err) @@ -195,7 +197,7 @@ func (c *Controller) createDefaultVpcLrpEip(config map[string]string) (string, s } } else { var v6ip string - v4ip, v6ip, mac, err = c.acquireIpAddress(c.config.ExternalGatewaySwitch, lrpEipName, lrpEipName) + v4ip, v6ip, mac, err = c.acquireIPAddress(c.config.ExternalGatewaySwitch, lrpEipName, lrpEipName) if err != nil { klog.Errorf("failed to acquire ip address for default vpc lrp %s, %v", lrpEipName, err) return "", "", err @@ -205,7 +207,7 @@ func (c *Controller) createDefaultVpcLrpEip(config map[string]string) (string, s return "", "", err } } - v4ipCidr := util.GetIpAddrWithMask(v4ip, cachedSubnet.Spec.CIDRBlock) + v4ipCidr := util.GetIPAddrWithMask(v4ip, cachedSubnet.Spec.CIDRBlock) return v4ipCidr, mac, nil } @@ -231,8 +233,7 @@ func (c *Controller) getGatewayChassis(config map[string]string) ([]string, erro return chassises, err } node := cachedNode.DeepCopy() - patchPayloadTemplate := - `[{ + patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/labels", "value": %s @@ -256,7 +257,7 @@ func (c *Controller) getGatewayChassis(config map[string]string) ([]string, erro return chassises, err } klog.Infof("get node %s chassis: %s", gw, annoChassisName) - chassis, err := c.ovnSbClient.GetChassis(annoChassisName, false) + chassis, err := c.OVNSbClient.GetChassis(annoChassisName, false) if err != nil { klog.Errorf("failed to get node %s chassis: %s, %v", node.Name, annoChassisName, err) return chassises, err diff --git a/pkg/controller/external_vpc.go b/pkg/controller/external_vpc.go index aa9e56935ac..5061b2a1cf1 100644 --- a/pkg/controller/external_vpc.go +++ b/pkg/controller/external_vpc.go @@ -83,7 +83,7 @@ func (c *Controller) syncExternalVpc() { func (c *Controller) getRouterStatus() (logicalRouters map[string]util.LogicalRouter, err error) { logicalRouters = make(map[string]util.LogicalRouter) - externalOvnRouters, err := c.ovnNbClient.ListLogicalRouter(false, func(lr *ovnnb.LogicalRouter) bool { + externalOvnRouters, err := c.OVNNbClient.ListLogicalRouter(false, func(lr *ovnnb.LogicalRouter) bool { return len(lr.ExternalIDs) == 0 || lr.ExternalIDs["vendor"] != util.CniTypeName }) if err != nil { @@ -101,7 +101,7 @@ func (c *Controller) getRouterStatus() (logicalRouters map[string]util.LogicalRo Ports: make([]util.Port, 0, len(externalLR.Ports)), } for _, uuid := range externalLR.Ports { - lrp, err := c.ovnNbClient.GetLogicalRouterPortByUUID(uuid) + lrp, err := c.OVNNbClient.GetLogicalRouterPortByUUID(uuid) if err != nil { klog.Warningf("failed to get LRP by UUID %s: %v", uuid, err) continue @@ -113,7 +113,7 @@ func (c *Controller) getRouterStatus() (logicalRouters map[string]util.LogicalRo for routerName, logicalRouter := range logicalRouters { tmpRouter := logicalRouter for _, port := range logicalRouter.Ports { - peerPorts, err := c.ovnNbClient.ListLogicalSwitchPorts(false, nil, func(lsp *ovnnb.LogicalSwitchPort) bool { + peerPorts, err := c.OVNNbClient.ListLogicalSwitchPorts(false, nil, func(lsp *ovnnb.LogicalSwitchPort) bool { return len(lsp.Options) != 0 && lsp.Options["router-port"] == port.Name }) if err != nil || len(peerPorts) > 1 { @@ -124,7 +124,7 @@ func (c *Controller) getRouterStatus() (logicalRouters map[string]util.LogicalRo continue } lsp := peerPorts[0] - switches, err := c.ovnNbClient.ListLogicalSwitch(false, func(ls *ovnnb.LogicalSwitch) bool { + switches, err := c.OVNNbClient.ListLogicalSwitch(false, func(ls *ovnnb.LogicalSwitch) bool { return util.ContainsString(ls.Ports, lsp.UUID) }) if err != nil || len(switches) > 1 { diff --git a/pkg/controller/gc.go b/pkg/controller/gc.go index 9807f5cf229..359be0d27ec 100644 --- a/pkg/controller/gc.go +++ b/pkg/controller/gc.go @@ -36,7 +36,7 @@ func (c *Controller) gc() error { c.gcLogicalRouterPort, c.gcVip, c.gcLbSvcPods, - c.gcVpcDns, + c.gcVPCDNS, } for _, gcFunc := range gcFunctions { if err := gcFunc(); err != nil { @@ -61,7 +61,7 @@ func (c *Controller) gcLogicalRouterPort() error { } } - if err = c.ovnNbClient.DeleteLogicalRouterPorts(nil, logicalRouterPortFilter(exceptPeerPorts)); err != nil { + if err = c.OVNNbClient.DeleteLogicalRouterPorts(nil, logicalRouterPortFilter(exceptPeerPorts)); err != nil { klog.Errorf("delete non-existent peer logical router port: %v", err) return err } @@ -126,7 +126,7 @@ func (c *Controller) gcLogicalSwitch() error { subnetNames.Add(s.Name) } - lss, err := c.ovnNbClient.ListLogicalSwitch(c.config.EnableExternalVpc, nil) + lss, err := c.OVNNbClient.ListLogicalSwitch(c.config.EnableExternalVpc, nil) if err != nil { klog.Errorf("list logical switch: %v", err) return err @@ -152,12 +152,12 @@ func (c *Controller) gcLogicalSwitch() error { } klog.Infof("start to gc dhcp options") - dhcpOptions, err := c.ovnNbClient.ListDHCPOptions(c.config.EnableExternalVpc, nil) + dhcpOptions, err := c.OVNNbClient.ListDHCPOptions(c.config.EnableExternalVpc, nil) if err != nil { klog.Errorf("failed to list dhcp options, %v", err) return err } - var uuidToDeleteList = []string{} + uuidToDeleteList := []string{} for _, item := range dhcpOptions { if len(item.ExternalIDs) == 0 || !subnetNames.Has(item.ExternalIDs["ls"]) { uuidToDeleteList = append(uuidToDeleteList, item.UUID) @@ -165,7 +165,7 @@ func (c *Controller) gcLogicalSwitch() error { } klog.Infof("gc dhcp options %v", uuidToDeleteList) if len(uuidToDeleteList) > 0 { - if err = c.ovnNbClient.DeleteDHCPOptionsByUUIDs(uuidToDeleteList...); err != nil { + if err = c.OVNNbClient.DeleteDHCPOptionsByUUIDs(uuidToDeleteList...); err != nil { klog.Errorf("failed to delete dhcp options by uuids, %v", err) return err } @@ -185,7 +185,7 @@ func (c *Controller) gcCustomLogicalRouter() error { vpcNames = append(vpcNames, s.Name) } - lrs, err := c.ovnNbClient.ListLogicalRouter(c.config.EnableExternalVpc, nil) + lrs, err := c.OVNNbClient.ListLogicalRouter(c.config.EnableExternalVpc, nil) if err != nil { klog.Errorf("failed to list logical router, %v", err) return err @@ -245,9 +245,9 @@ func (c *Controller) gcNode() error { func (c *Controller) gcVip() error { klog.Infof("start to gc vips") - selector, err := util.LabelSelectorNotEmpty(util.IpReservedLabel) + selector, err := util.LabelSelectorNotEmpty(util.IPReservedLabel) if err != nil { - klog.Errorf("failed to generate selector for label %s: %v", util.IpReservedLabel, err) + klog.Errorf("failed to generate selector for label %s: %v", util.IPReservedLabel, err) return err } vips, err := c.virtualIpsLister.List(selector) @@ -256,7 +256,7 @@ func (c *Controller) gcVip() error { return err } for _, vip := range vips { - portName := vip.Labels[util.IpReservedLabel] + portName := vip.Labels[util.IPReservedLabel] portNameSplits := strings.Split(portName, ".") if len(portNameSplits) >= 2 { podName := portNameSplits[0] @@ -327,9 +327,9 @@ func (c *Controller) markAndCleanLSP() error { } // The lsp for vm pod should not be deleted if vm still exists - ipMap.Add(c.getVmLsps()...) + ipMap.Add(c.getVMLsps()...) - lsps, err := c.ovnNbClient.ListNormalLogicalSwitchPorts(c.config.EnableExternalVpc, nil) + lsps, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(c.config.EnableExternalVpc, nil) if err != nil { klog.Errorf("failed to list logical switch port, %v", err) return err @@ -353,7 +353,7 @@ func (c *Controller) markAndCleanLSP() error { } klog.Infof("gc logical switch port %s", lsp.Name) - if err := c.ovnNbClient.DeleteLogicalSwitchPort(lsp.Name); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(lsp.Name); err != nil { klog.Errorf("failed to delete lsp %s: %v", lsp.Name, err) return err } @@ -404,17 +404,16 @@ func (c *Controller) gcLoadBalancer() error { if !isOvnSubnet(subnet) { continue } - - lbs := []string{vpc.Status.TcpLoadBalancer, vpc.Status.TcpSessionLoadBalancer, vpc.Status.UdpLoadBalancer, vpc.Status.UdpSessionLoadBalancer, vpc.Status.SctpLoadBalancer, vpc.Status.SctpSessionLoadBalancer} - if err := c.ovnNbClient.LogicalSwitchUpdateLoadBalancers(subnetName, ovsdb.MutateOperationDelete, lbs...); err != nil { + lbs := []string{vpc.Status.TCPLoadBalancer, vpc.Status.TCPSessionLoadBalancer, vpc.Status.UDPLoadBalancer, vpc.Status.UDPSessionLoadBalancer, vpc.Status.SctpLoadBalancer, vpc.Status.SctpSessionLoadBalancer} + if err := c.OVNNbClient.LogicalSwitchUpdateLoadBalancers(subnetName, ovsdb.MutateOperationDelete, lbs...); err != nil { return err } } - vpc.Status.TcpLoadBalancer = "" - vpc.Status.TcpSessionLoadBalancer = "" - vpc.Status.UdpLoadBalancer = "" - vpc.Status.UdpSessionLoadBalancer = "" + vpc.Status.TCPLoadBalancer = "" + vpc.Status.TCPSessionLoadBalancer = "" + vpc.Status.UDPLoadBalancer = "" + vpc.Status.UDPSessionLoadBalancer = "" vpc.Status.SctpLoadBalancer = "" vpc.Status.SctpSessionLoadBalancer = "" bytes, err := vpc.Status.Bytes() @@ -430,7 +429,7 @@ func (c *Controller) gcLoadBalancer() error { } // lbs will remove from logical switch automatically when delete lbs - if err = c.ovnNbClient.DeleteLoadBalancers(nil); err != nil { + if err = c.OVNNbClient.DeleteLoadBalancers(nil); err != nil { klog.Errorf("delete all load balancers: %v", err) return err } @@ -488,8 +487,8 @@ func (c *Controller) gcLoadBalancer() error { } var vpcLbs []string for _, vpc := range vpcs { - tcpLb, udpLb, sctpLb := vpc.Status.TcpLoadBalancer, vpc.Status.UdpLoadBalancer, vpc.Status.SctpLoadBalancer - tcpSessLb, udpSessLb, sctpSessLb := vpc.Status.TcpSessionLoadBalancer, vpc.Status.UdpSessionLoadBalancer, vpc.Status.SctpSessionLoadBalancer + tcpLb, udpLb, sctpLb := vpc.Status.TCPLoadBalancer, vpc.Status.UDPLoadBalancer, vpc.Status.SctpLoadBalancer + tcpSessLb, udpSessLb, sctpSessLb := vpc.Status.TCPSessionLoadBalancer, vpc.Status.UDPSessionLoadBalancer, vpc.Status.SctpSessionLoadBalancer vpcLbs = append(vpcLbs, tcpLb, udpLb, sctpLb, tcpSessLb, udpSessLb, sctpSessLb) removeVIP := func(lbName string, svcVips *strset.Set) error { @@ -497,7 +496,7 @@ func (c *Controller) gcLoadBalancer() error { return nil } - lb, err := c.ovnNbClient.GetLoadBalancer(lbName, true) + lb, err := c.OVNNbClient.GetLoadBalancer(lbName, true) if err != nil { klog.Errorf("get LB %s: %v", lbName, err) return err @@ -509,7 +508,7 @@ func (c *Controller) gcLoadBalancer() error { for vip := range lb.Vips { if !svcVips.Has(vip) { - if err = c.ovnNbClient.LoadBalancerDeleteVip(lbName, vip); err != nil { + if err = c.OVNNbClient.LoadBalancerDeleteVip(lbName, vip); err != nil { klog.Errorf("failed to delete vip %s from LB %s: %v", vip, lbName, err) return err } @@ -539,7 +538,7 @@ func (c *Controller) gcLoadBalancer() error { } // delete lbs - if err = c.ovnNbClient.DeleteLoadBalancers(func(lb *ovnnb.LoadBalancer) bool { + if err = c.OVNNbClient.DeleteLoadBalancers(func(lb *ovnnb.LoadBalancer) bool { return !util.ContainsString(vpcLbs, lb.Name) }); err != nil { klog.Errorf("delete load balancers: %v", err) @@ -593,7 +592,7 @@ func (c *Controller) gcPortGroup() error { } // list all np port groups which externalIDs[np]!="" - pgs, err := c.ovnNbClient.ListPortGroups(map[string]string{networkPolicyKey: ""}) + pgs, err := c.OVNNbClient.ListPortGroups(map[string]string{networkPolicyKey: ""}) if err != nil { klog.Errorf("list np port group: %v", err) return err @@ -617,7 +616,7 @@ func (c *Controller) gcPortGroup() error { func (c *Controller) gcStaticRoute() error { klog.Infof("start to gc static routes") - routes, err := c.ovnNbClient.ListLogicalRouterStaticRoutes(c.config.ClusterRouter, nil, nil, "", nil) + routes, err := c.OVNNbClient.ListLogicalRouterStaticRoutes(c.config.ClusterRouter, nil, nil, "", nil) if err != nil { klog.Errorf("failed to list static route %v", err) return err @@ -640,7 +639,7 @@ func (c *Controller) gcStaticRoute() error { continue } if route.IPPrefix != "0.0.0.0/0" && route.IPPrefix != "::/0" && c.ipam.ContainAddress(route.IPPrefix) { - exist, err := c.ovnNbClient.NatExists(c.config.ClusterRouter, "", "", route.IPPrefix) + exist, err := c.OVNNbClient.NatExists(c.config.ClusterRouter, "", "", route.IPPrefix) if err != nil { klog.Errorf("failed to get NatRule by LogicalIP %s, %v", route.IPPrefix, err) continue @@ -649,7 +648,7 @@ func (c *Controller) gcStaticRoute() error { continue } klog.Infof("gc static route %s %v %s %s", route.RouteTable, route.Policy, route.IPPrefix, route.Nexthop) - if err = c.ovnNbClient.DeleteLogicalRouterStaticRoute(c.config.ClusterRouter, &route.RouteTable, route.Policy, route.IPPrefix, route.Nexthop); err != nil { + if err = c.OVNNbClient.DeleteLogicalRouterStaticRoute(c.config.ClusterRouter, &route.RouteTable, route.Policy, route.IPPrefix, route.Nexthop); err != nil { klog.Errorf("failed to delete stale route %s %v %s %s: %v", route.RouteTable, route.Policy, route.IPPrefix, route.Nexthop, err) } } @@ -659,7 +658,7 @@ func (c *Controller) gcStaticRoute() error { func (c *Controller) gcChassis() error { klog.Infof("start to gc chassis") - chassises, err := c.ovnSbClient.GetKubeOvnChassisses() + chassises, err := c.OVNSbClient.GetKubeOvnChassisses() if err != nil { klog.Errorf("failed to get all chassis, %v", err) } @@ -682,13 +681,12 @@ func (c *Controller) gcChassis() error { if hostname == node.Name { // node is alive, matched chassis should be alive continue - } else { - // maybe node name changed, delete chassis - klog.Infof("gc node %s chassis %s", node.Name, chassisName) - if err := c.ovnSbClient.DeleteChassis(chassisName); err != nil { - klog.Errorf("failed to delete node %s chassis %s %v", node.Name, chassisName, err) - return err - } + } + // maybe node name changed, delete chassis + klog.Infof("gc node %s chassis %s", node.Name, chassisName) + if err := c.OVNSbClient.DeleteChassis(chassisName); err != nil { + klog.Errorf("failed to delete node %s chassis %s %v", node.Name, chassisName, err) + return err } } } @@ -710,10 +708,10 @@ func (c *Controller) isOVNProvided(providerName string, pod *corev1.Pod) (bool, return false, nil } -func (c *Controller) getVmLsps() []string { +func (c *Controller) getVMLsps() []string { var vmLsps []string - if !c.config.EnableKeepVmIP { + if !c.config.EnableKeepVMIP { return vmLsps } @@ -730,34 +728,32 @@ func (c *Controller) getVmLsps() []string { klog.Errorf("failed to list vm in namespace %s, %v", ns, err) } continue - } else { - for _, vm := range vms.Items { - vmLsp := ovs.PodNameToPortName(vm.Name, ns.Name, util.OvnProvider) + } + for _, vm := range vms.Items { + vmLsp := ovs.PodNameToPortName(vm.Name, ns.Name, util.OvnProvider) + vmLsps = append(vmLsps, vmLsp) + + attachNets, err := util.ParsePodNetworkAnnotation(vm.Spec.Template.ObjectMeta.Annotations[util.AttachmentNetworkAnnotation], vm.Namespace) + if err != nil { + klog.Errorf("failed to get attachment subnet of vm %s, %v", vm.Name, err) + continue + } + for _, multiNet := range attachNets { + provider := fmt.Sprintf("%s.%s.ovn", multiNet.Name, multiNet.Namespace) + vmLsp := ovs.PodNameToPortName(vm.Name, ns.Name, provider) vmLsps = append(vmLsps, vmLsp) + } - attachNets, err := util.ParsePodNetworkAnnotation(vm.Spec.Template.ObjectMeta.Annotations[util.AttachmentNetworkAnnotation], vm.Namespace) - if err != nil { - klog.Errorf("failed to get attachment subnet of vm %s, %v", vm.Name, err) - continue - } - for _, multiNet := range attachNets { - provider := fmt.Sprintf("%s.%s.ovn", multiNet.Name, multiNet.Namespace) + for _, network := range vm.Spec.Template.Spec.Networks { + if network.Multus != nil && network.Multus.NetworkName != "" { + items := strings.Split(network.Multus.NetworkName, "/") + if len(items) != 2 { + continue + } + provider := fmt.Sprintf("%s.%s.ovn", items[1], items[0]) vmLsp := ovs.PodNameToPortName(vm.Name, ns.Name, provider) vmLsps = append(vmLsps, vmLsp) } - - for _, network := range vm.Spec.Template.Spec.Networks { - if network.Multus != nil && network.Multus.NetworkName != "" { - items := strings.Split(network.Multus.NetworkName, "/") - if len(items) != 2 { - continue - } - provider := fmt.Sprintf("%s.%s.ovn", items[1], items[0]) - vmLsp := ovs.PodNameToPortName(vm.Name, ns.Name, provider) - vmLsps = append(vmLsps, vmLsp) - } - } - } } } @@ -805,19 +801,19 @@ func (c *Controller) gcLbSvcPods() error { return nil } -func (c *Controller) gcVpcDns() error { +func (c *Controller) gcVPCDNS() error { if !c.config.EnableLb { return nil } klog.Infof("start to gc vpc dns") - vds, err := c.vpcDnsLister.List(labels.Everything()) + vds, err := c.vpcDNSLister.List(labels.Everything()) if err != nil { klog.Errorf("failed to list vpc-dns, %v", err) return err } - sel, _ := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{MatchLabels: map[string]string{util.VpcDnsNameLabel: "true"}}) + sel, _ := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{MatchLabels: map[string]string{util.VpcDNSNameLabel: "true"}}) deps, err := c.config.KubeClient.AppsV1().Deployments(c.config.PodNamespace).List(context.Background(), metav1.ListOptions{ LabelSelector: sel.String(), @@ -830,7 +826,7 @@ func (c *Controller) gcVpcDns() error { for _, dep := range deps.Items { canFind := false for _, vd := range vds { - name := genVpcDnsDpName(vd.Name) + name := genVpcDNSDpName(vd.Name) if dep.Name == name { canFind = true break @@ -855,7 +851,7 @@ func (c *Controller) gcVpcDns() error { for _, slr := range slrs { canFind := false for _, vd := range vds { - name := genVpcDnsDpName(vd.Name) + name := genVpcDNSDpName(vd.Name) if slr.Name == name { canFind = true break diff --git a/pkg/controller/init.go b/pkg/controller/init.go index 1d834140909..414c6cb01cf 100644 --- a/pkg/controller/init.go +++ b/pkg/controller/init.go @@ -67,10 +67,10 @@ func (c *Controller) InitDefaultVpc() error { vpc.Status.DefaultLogicalSwitch = c.config.DefaultLogicalSwitch vpc.Status.Router = c.config.ClusterRouter if c.config.EnableLb { - vpc.Status.TcpLoadBalancer = c.config.ClusterTcpLoadBalancer - vpc.Status.TcpSessionLoadBalancer = c.config.ClusterTcpSessionLoadBalancer - vpc.Status.UdpLoadBalancer = c.config.ClusterUdpLoadBalancer - vpc.Status.UdpSessionLoadBalancer = c.config.ClusterUdpSessionLoadBalancer + vpc.Status.TCPLoadBalancer = c.config.ClusterTCPLoadBalancer + vpc.Status.TCPSessionLoadBalancer = c.config.ClusterTCPSessionLoadBalancer + vpc.Status.UDPLoadBalancer = c.config.ClusterUDPLoadBalancer + vpc.Status.UDPSessionLoadBalancer = c.config.ClusterUDPSessionLoadBalancer vpc.Status.SctpLoadBalancer = c.config.ClusterSctpLoadBalancer vpc.Status.SctpSessionLoadBalancer = c.config.ClusterSctpSessionLoadBalancer } @@ -193,7 +193,7 @@ func (c *Controller) initNodeSwitch() error { // InitClusterRouter init cluster router to connect different logical switches func (c *Controller) initClusterRouter() error { - return c.ovnNbClient.CreateLogicalRouter(c.config.ClusterRouter) + return c.OVNNbClient.CreateLogicalRouter(c.config.ClusterRouter) } func (c *Controller) initLB(name, protocol string, sessionAffinity bool) error { @@ -201,16 +201,16 @@ func (c *Controller) initLB(name, protocol string, sessionAffinity bool) error { var selectFields string if sessionAffinity { - selectFields = string(ovnnb.LoadBalancerSelectionFieldsIPSrc) + selectFields = ovnnb.LoadBalancerSelectionFieldsIPSrc } - if err := c.ovnNbClient.CreateLoadBalancer(name, protocol, selectFields); err != nil { + if err := c.OVNNbClient.CreateLoadBalancer(name, protocol, selectFields); err != nil { klog.Errorf("create load balancer %s: %v", name, err) return err } if sessionAffinity { - if err := c.ovnNbClient.SetLoadBalancerAffinityTimeout(name, util.DefaultServiceSessionStickinessTimeout); err != nil { + if err := c.OVNNbClient.SetLoadBalancerAffinityTimeout(name, util.DefaultServiceSessionStickinessTimeout); err != nil { klog.Errorf("failed to set affinity timeout of %s load balancer %s: %v", protocol, name, err) return err } @@ -230,16 +230,16 @@ func (c *Controller) initLoadBalancer() error { for _, cachedVpc := range vpcs { vpc := cachedVpc.DeepCopy() vpcLb := c.GenVpcLoadBalancer(vpc.Name) - if err = c.initLB(vpcLb.TcpLoadBalancer, string(v1.ProtocolTCP), false); err != nil { + if err = c.initLB(vpcLb.TCPLoadBalancer, string(v1.ProtocolTCP), false); err != nil { return err } - if err = c.initLB(vpcLb.TcpSessLoadBalancer, string(v1.ProtocolTCP), true); err != nil { + if err = c.initLB(vpcLb.TCPSessLoadBalancer, string(v1.ProtocolTCP), true); err != nil { return err } - if err = c.initLB(vpcLb.UdpLoadBalancer, string(v1.ProtocolUDP), false); err != nil { + if err = c.initLB(vpcLb.UDPLoadBalancer, string(v1.ProtocolUDP), false); err != nil { return err } - if err = c.initLB(vpcLb.UdpSessLoadBalancer, string(v1.ProtocolUDP), true); err != nil { + if err = c.initLB(vpcLb.UDPSessLoadBalancer, string(v1.ProtocolUDP), true); err != nil { return err } if err = c.initLB(vpcLb.SctpLoadBalancer, string(v1.ProtocolSCTP), false); err != nil { @@ -249,10 +249,10 @@ func (c *Controller) initLoadBalancer() error { return err } - vpc.Status.TcpLoadBalancer = vpcLb.TcpLoadBalancer - vpc.Status.TcpSessionLoadBalancer = vpcLb.TcpSessLoadBalancer - vpc.Status.UdpLoadBalancer = vpcLb.UdpLoadBalancer - vpc.Status.UdpSessionLoadBalancer = vpcLb.UdpSessLoadBalancer + vpc.Status.TCPLoadBalancer = vpcLb.TCPLoadBalancer + vpc.Status.TCPSessionLoadBalancer = vpcLb.TCPSessLoadBalancer + vpc.Status.UDPLoadBalancer = vpcLb.UDPLoadBalancer + vpc.Status.UDPSessionLoadBalancer = vpcLb.UDPSessLoadBalancer vpc.Status.SctpLoadBalancer = vpcLb.SctpLoadBalancer vpc.Status.SctpSessionLoadBalancer = vpcLb.SctpSessLoadBalancer bytes, err := vpc.Status.Bytes() @@ -317,7 +317,7 @@ func (c *Controller) InitIPAM() error { for _, ip := range ips { ipsMap[ip.Name] = ip // recover sts and kubevirt vm ip, other ip recover in later pod loop - if ip.Spec.PodType != "StatefulSet" && ip.Spec.PodType != util.Vm { + if ip.Spec.PodType != "StatefulSet" && ip.Spec.PodType != util.VM { continue } @@ -345,7 +345,7 @@ func (c *Controller) InitIPAM() error { podNets, err := c.getPodKubeovnNets(pod) if err != nil { - klog.Errorf("failed to get pod kubeovn nets %s.%s address %s: %v", pod.Name, pod.Namespace, pod.Annotations[util.IpAddressAnnotation], err) + klog.Errorf("failed to get pod kubeovn nets %s.%s address %s: %v", pod.Name, pod.Namespace, pod.Annotations[util.IPAddressAnnotation], err) continue } @@ -355,11 +355,11 @@ func (c *Controller) InitIPAM() error { for _, podNet := range podNets { if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)] == "true" { portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName) - ip := pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)] + ip := pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] mac := pod.Annotations[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)] _, _, _, err := c.ipam.GetStaticAddress(key, portName, ip, &mac, podNet.Subnet.Name, true) if err != nil { - klog.Errorf("failed to init pod %s.%s address %s: %v", podName, pod.Namespace, pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)], err) + klog.Errorf("failed to init pod %s.%s address %s: %v", podName, pod.Namespace, pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)], err) } else { ipCR := ipsMap[portName] err = c.createOrUpdateCrdIPs(podName, ip, mac, podNet.Subnet.Name, pod.Namespace, pod.Spec.NodeName, podNet.ProviderName, podType, &ipCR) @@ -423,13 +423,13 @@ func (c *Controller) InitIPAM() error { portName := fmt.Sprintf("node-%s", node.Name) mac := node.Annotations[util.MacAddressAnnotation] v4IP, v6IP, _, err := c.ipam.GetStaticAddress(portName, portName, - node.Annotations[util.IpAddressAnnotation], &mac, + node.Annotations[util.IPAddressAnnotation], &mac, node.Annotations[util.LogicalSwitchAnnotation], true) if err != nil { - klog.Errorf("failed to init node %s.%s address %s: %v", node.Name, node.Namespace, node.Annotations[util.IpAddressAnnotation], err) + klog.Errorf("failed to init node %s.%s address %s: %v", node.Name, node.Namespace, node.Annotations[util.IPAddressAnnotation], err) } if v4IP != "" && v6IP != "" { - node.Annotations[util.IpAddressAnnotation] = util.GetStringIP(v4IP, v6IP) + node.Annotations[util.IPAddressAnnotation] = util.GetStringIP(v4IP, v6IP) } } } @@ -570,13 +570,13 @@ func (c *Controller) initSyncCrdIPs() error { return err } - ipMap := strset.New(c.getVmLsps()...) + ipMap := strset.New(c.getVMLsps()...) for _, ipCr := range ips { ip := ipCr.DeepCopy() changed := false if ipMap.Has(ip.Name) && ip.Spec.PodType == "" { - ip.Spec.PodType = util.Vm + ip.Spec.PodType = util.VM changed = true } @@ -692,9 +692,9 @@ func (c *Controller) initSyncCrdVlans() error { for _, vlan := range vlans { var needUpdate bool newVlan := vlan.DeepCopy() - if newVlan.Spec.VlanId != 0 && newVlan.Spec.ID == 0 { - newVlan.Spec.ID = newVlan.Spec.VlanId - newVlan.Spec.VlanId = 0 + if newVlan.Spec.VlanID != 0 && newVlan.Spec.ID == 0 { + newVlan.Spec.ID = newVlan.Spec.VlanID + newVlan.Spec.VlanID = 0 needUpdate = true } if newVlan.Spec.ProviderInterfaceName != "" && newVlan.Spec.Provider == "" { @@ -722,13 +722,13 @@ func (c *Controller) migrateNodeRoute(af int, node, ip, nexthop string) error { } klog.V(3).Infof("add policy route for router: %s, priority: %d, match %s, action %s, nexthop %s, extrenalID %v", c.config.ClusterRouter, util.NodeRouterPolicyPriority, match, action, nexthop, externalIDs) - if err := c.ovnNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.NodeRouterPolicyPriority, match, action, []string{nexthop}, externalIDs); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.NodeRouterPolicyPriority, match, action, []string{nexthop}, externalIDs); err != nil { klog.Errorf("failed to add logical router policy for node %s: %v", node, err) return err } routeTable := util.MainRouteTable - if err := c.ovnNbClient.DeleteLogicalRouterStaticRoute(c.config.ClusterRouter, &routeTable, nil, ip, ""); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterStaticRoute(c.config.ClusterRouter, &routeTable, nil, ip, ""); err != nil { klog.Errorf("failed to delete obsolete static route for node %s: %v", node, err) return err } @@ -736,12 +736,12 @@ func (c *Controller) migrateNodeRoute(af int, node, ip, nexthop string) error { asName := nodeUnderlayAddressSetName(node, af) obsoleteMatch := fmt.Sprintf("ip%d.dst == %s && ip%d.src != $%s", af, ip, af, asName) klog.V(3).Infof("delete policy route for router: %s, priority: %d, match %s", c.config.ClusterRouter, util.NodeRouterPolicyPriority, obsoleteMatch) - if err := c.ovnNbClient.DeleteLogicalRouterPolicy(c.config.ClusterRouter, util.NodeRouterPolicyPriority, obsoleteMatch); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPolicy(c.config.ClusterRouter, util.NodeRouterPolicyPriority, obsoleteMatch); err != nil { klog.Errorf("failed to delete obsolete logical router policy for node %s: %v", node, err) return err } - if err := c.ovnNbClient.DeleteAddressSet(asName); err != nil { + if err := c.OVNNbClient.DeleteAddressSet(asName); err != nil { klog.Errorf("delete obsolete address set %s for node %s: %v", asName, node, err) return err } @@ -760,7 +760,7 @@ func (c *Controller) initNodeRoutes() error { continue } nodeIPv4, nodeIPv6 := util.GetNodeInternalIP(*node) - joinAddrV4, joinAddrV6 := util.SplitStringIP(node.Annotations[util.IpAddressAnnotation]) + joinAddrV4, joinAddrV6 := util.SplitStringIP(node.Annotations[util.IPAddressAnnotation]) if nodeIPv4 != "" && joinAddrV4 != "" { if err = c.migrateNodeRoute(4, node.Name, nodeIPv4, joinAddrV4); err != nil { klog.Errorf("failed to migrate IPv4 route for node %s: %v", node.Name, err) @@ -782,7 +782,7 @@ func (c *Controller) initNodeChassis() error { klog.Errorf("failed to list nodes: %v", err) return err } - chassises, err := c.ovnSbClient.GetKubeOvnChassisses() + chassises, err := c.OVNSbClient.GetKubeOvnChassisses() if err != nil { klog.Errorf("failed to get chassis nodes: %v", err) return err diff --git a/pkg/controller/inspection.go b/pkg/controller/inspection.go index 0ff212b6915..20ebba0926a 100644 --- a/pkg/controller/inspection.go +++ b/pkg/controller/inspection.go @@ -41,7 +41,7 @@ func (c *Controller) inspectPod() error { for _, podNet := range filterSubnets(pod, podNets) { if podNet.Type != providerTypeIPAM { portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName) - exists, err := c.ovnNbClient.LogicalSwitchPortExists(portName) + exists, err := c.OVNNbClient.LogicalSwitchPortExists(portName) if err != nil { klog.Errorf("failed to check port %s exists, %v", portName, err) return err @@ -63,14 +63,11 @@ func (c *Controller) inspectPod() error { klog.V(5).Infof("finish remove annotation for %s", portName) c.addOrUpdatePodQueue.Add(fmt.Sprintf("%s/%s", pod.Namespace, pod.Name)) break - } else { - if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)] == "true" && pod.Spec.NodeName != "" { - if pod.Annotations[fmt.Sprintf(util.RoutedAnnotationTemplate, podNet.ProviderName)] != "true" { - klog.V(5).Infof("enqueue update pod %s/%s", pod.Namespace, pod.Name) - c.addOrUpdatePodQueue.Add(fmt.Sprintf("%s/%s", pod.Namespace, pod.Name)) - break - } - } + } else if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)] == "true" && pod.Spec.NodeName != "" && + pod.Annotations[fmt.Sprintf(util.RoutedAnnotationTemplate, podNet.ProviderName)] != "true" { + klog.V(5).Infof("enqueue update pod %s/%s", pod.Namespace, pod.Name) + c.addOrUpdatePodQueue.Add(fmt.Sprintf("%s/%s", pod.Namespace, pod.Name)) + break } } } @@ -79,7 +76,6 @@ func (c *Controller) inspectPod() error { } func filterSubnets(pod *v1.Pod, nets []*kubeovnNet) []*kubeovnNet { - if pod.Annotations == nil { return nets } diff --git a/pkg/controller/ip.go b/pkg/controller/ip.go index 616f463d473..6de106e6a9e 100644 --- a/pkg/controller/ip.go +++ b/pkg/controller/ip.go @@ -1,15 +1,15 @@ package controller import ( - "github.com/kubeovn/kube-ovn/pkg/util" - "k8s.io/klog/v2" "strings" + "k8s.io/klog/v2" + kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1" + "github.com/kubeovn/kube-ovn/pkg/util" ) func (c *Controller) enqueueAddOrDelIP(obj interface{}) { - ipObj := obj.(*kubeovnv1.IP) klog.V(3).Infof("enqueue update status subnet %s", ipObj.Spec.Subnet) if strings.HasPrefix(ipObj.Name, util.U2OInterconnName[0:19]) { @@ -22,9 +22,8 @@ func (c *Controller) enqueueAddOrDelIP(obj interface{}) { } } -func (c *Controller) enqueueUpdateIP(old, new interface{}) { - - ipObj := new.(*kubeovnv1.IP) +func (c *Controller) enqueueUpdateIP(_, newObj interface{}) { + ipObj := newObj.(*kubeovnv1.IP) klog.V(3).Infof("enqueue update status subnet %s", ipObj.Spec.Subnet) for _, as := range ipObj.Spec.AttachSubnets { klog.V(3).Infof("enqueue update status subnet %s", as) diff --git a/pkg/controller/ippool.go b/pkg/controller/ippool.go index 32213dfba32..899dc9f8a31 100644 --- a/pkg/controller/ippool.go +++ b/pkg/controller/ippool.go @@ -38,10 +38,10 @@ func (c *Controller) enqueueDeleteIPPool(obj interface{}) { c.deleteIPPoolQueue.Add(obj) } -func (c *Controller) enqueueUpdateIPPool(old, new interface{}) { - oldIPPool := old.(*kubeovnv1.IPPool) - newIPPool := new.(*kubeovnv1.IPPool) - key, err := cache.MetaNamespaceKeyFunc(new) +func (c *Controller) enqueueUpdateIPPool(oldObj, newObj interface{}) { + oldIPPool := oldObj.(*kubeovnv1.IPPool) + newIPPool := newObj.(*kubeovnv1.IPPool) + key, err := cache.MetaNamespaceKeyFunc(newObj) if err != nil { utilruntime.HandleError(err) return @@ -90,7 +90,6 @@ func (c *Controller) processNextAddIPPoolWorkItem() bool { c.addOrUpdateIPPoolQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -119,7 +118,6 @@ func (c *Controller) processNextUpdateIPPoolStatusWorkItem() bool { } return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -148,7 +146,6 @@ func (c *Controller) processNextDeleteIPPoolWorkItem() bool { c.deleteIPPoolQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -218,7 +215,7 @@ func (c *Controller) handleDeleteIPPool(ippool *kubeovnv1.IPPool) error { if len(ns.Annotations) == 0 { continue } - if ns.Annotations[util.IpPoolAnnotation] == ippool.Name { + if ns.Annotations[util.IPPoolAnnotation] == ippool.Name { c.enqueueAddNamespace(ns) } } diff --git a/pkg/controller/namespace.go b/pkg/controller/namespace.go index ae069d5242e..7f4df556df1 100644 --- a/pkg/controller/namespace.go +++ b/pkg/controller/namespace.go @@ -19,7 +19,6 @@ import ( ) func (c *Controller) enqueueAddNamespace(obj interface{}) { - if c.config.EnableNP { for _, np := range c.namespaceMatchNetworkPolicies(obj.(*v1.Namespace)) { c.updateNpQueue.Add(np) @@ -35,7 +34,6 @@ func (c *Controller) enqueueAddNamespace(obj interface{}) { } func (c *Controller) enqueueDeleteNamespace(obj interface{}) { - if c.config.EnableNP { for _, np := range c.namespaceMatchNetworkPolicies(obj.(*v1.Namespace)) { c.updateNpQueue.Add(np) @@ -43,9 +41,9 @@ func (c *Controller) enqueueDeleteNamespace(obj interface{}) { } } -func (c *Controller) enqueueUpdateNamespace(old, new interface{}) { - oldNs := old.(*v1.Namespace) - newNs := new.(*v1.Namespace) +func (c *Controller) enqueueUpdateNamespace(oldObj, newObj interface{}) { + oldNs := oldObj.(*v1.Namespace) + newNs := newObj.(*v1.Namespace) if oldNs.ResourceVersion == newNs.ResourceVersion { return } @@ -97,7 +95,6 @@ func (c *Controller) processNextAddNamespaceWorkItem() bool { c.addNamespaceQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -188,22 +185,21 @@ func (c *Controller) handleAddNamespace(key string) error { if namespace.Annotations == nil || len(namespace.Annotations) == 0 { namespace.Annotations = map[string]string{} - } else { - if namespace.Annotations[util.LogicalSwitchAnnotation] == strings.Join(lss, ",") && - namespace.Annotations[util.CidrAnnotation] == strings.Join(cidrs, ";") && - namespace.Annotations[util.ExcludeIpsAnnotation] == strings.Join(excludeIps, ";") && - namespace.Annotations[util.IpPoolAnnotation] == ippool { - return nil - } + } else if namespace.Annotations[util.LogicalSwitchAnnotation] == strings.Join(lss, ",") && + namespace.Annotations[util.CidrAnnotation] == strings.Join(cidrs, ";") && + namespace.Annotations[util.ExcludeIpsAnnotation] == strings.Join(excludeIps, ";") && + namespace.Annotations[util.IPPoolAnnotation] == ippool { + return nil } + namespace.Annotations[util.LogicalSwitchAnnotation] = strings.Join(lss, ",") namespace.Annotations[util.CidrAnnotation] = strings.Join(cidrs, ";") namespace.Annotations[util.ExcludeIpsAnnotation] = strings.Join(excludeIps, ";") if ippool == "" { - delete(namespace.Annotations, util.IpPoolAnnotation) + delete(namespace.Annotations, util.IPPoolAnnotation) } else { - namespace.Annotations[util.IpPoolAnnotation] = ippool + namespace.Annotations[util.IPPoolAnnotation] = ippool } patch, err := util.GenerateStrategicMergePatchPayload(cachedNs, namespace) diff --git a/pkg/controller/network_policy.go b/pkg/controller/network_policy.go index 7e80afbbf46..80b7d61a1b1 100644 --- a/pkg/controller/network_policy.go +++ b/pkg/controller/network_policy.go @@ -23,7 +23,6 @@ import ( ) func (c *Controller) enqueueAddNp(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -45,14 +44,14 @@ func (c *Controller) enqueueDeleteNp(obj interface{}) { c.deleteNpQueue.Add(key) } -func (c *Controller) enqueueUpdateNp(old, new interface{}) { - oldNp := old.(*netv1.NetworkPolicy) - newNp := new.(*netv1.NetworkPolicy) +func (c *Controller) enqueueUpdateNp(oldObj, newObj interface{}) { + oldNp := oldObj.(*netv1.NetworkPolicy) + newNp := newObj.(*netv1.NetworkPolicy) if !reflect.DeepEqual(oldNp.Spec, newNp.Spec) || !reflect.DeepEqual(oldNp.Annotations, newNp.Annotations) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } @@ -94,7 +93,6 @@ func (c *Controller) processNextUpdateNpWorkItem() bool { c.updateNpQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -125,7 +123,6 @@ func (c *Controller) processNextDeleteNpWorkItem() bool { c.deleteNpQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -171,13 +168,13 @@ func (c *Controller) handleUpdateNp(key string) error { // TODO: ovn acl doesn't support address_set name with '-', now we replace '-' by '.'. // This may cause conflict if two np with name test-np and test.np. Maybe hash is a better solution, // but we do not want to lost the readability now. - pgName := strings.Replace(fmt.Sprintf("%s.%s", np.Name, np.Namespace), "-", ".", -1) - ingressAllowAsNamePrefix := strings.Replace(fmt.Sprintf("%s.%s.ingress.allow", np.Name, np.Namespace), "-", ".", -1) - ingressExceptAsNamePrefix := strings.Replace(fmt.Sprintf("%s.%s.ingress.except", np.Name, np.Namespace), "-", ".", -1) - egressAllowAsNamePrefix := strings.Replace(fmt.Sprintf("%s.%s.egress.allow", np.Name, np.Namespace), "-", ".", -1) - egressExceptAsNamePrefix := strings.Replace(fmt.Sprintf("%s.%s.egress.except", np.Name, np.Namespace), "-", ".", -1) + pgName := strings.ReplaceAll(fmt.Sprintf("%s.%s", np.Name, np.Namespace), "-", ".") + ingressAllowAsNamePrefix := strings.ReplaceAll(fmt.Sprintf("%s.%s.ingress.allow", np.Name, np.Namespace), "-", ".") + ingressExceptAsNamePrefix := strings.ReplaceAll(fmt.Sprintf("%s.%s.ingress.except", np.Name, np.Namespace), "-", ".") + egressAllowAsNamePrefix := strings.ReplaceAll(fmt.Sprintf("%s.%s.egress.allow", np.Name, np.Namespace), "-", ".") + egressExceptAsNamePrefix := strings.ReplaceAll(fmt.Sprintf("%s.%s.egress.except", np.Name, np.Namespace), "-", ".") - if err = c.ovnNbClient.CreatePortGroup(pgName, map[string]string{networkPolicyKey: np.Namespace + "/" + np.Name}); err != nil { + if err = c.OVNNbClient.CreatePortGroup(pgName, map[string]string{networkPolicyKey: np.Namespace + "/" + np.Name}); err != nil { klog.Errorf("create port group for np %s: %v", key, err) return err } @@ -199,14 +196,14 @@ func (c *Controller) handleUpdateNp(key string) error { subnets = append(subnets, subnet) } - if err = c.ovnNbClient.PortGroupSetPorts(pgName, ports); err != nil { + if err = c.OVNNbClient.PortGroupSetPorts(pgName, ports); err != nil { klog.Errorf("failed to set ports of port group %s to %v: %v", pgName, ports, err) return err } // set svc address_set - svcAsNameIPv4 := strings.Replace(fmt.Sprintf("%s.%s.service.%s", npName, np.Namespace, kubeovnv1.ProtocolIPv4), "-", ".", -1) - svcAsNameIPv6 := strings.Replace(fmt.Sprintf("%s.%s.service.%s", npName, np.Namespace, kubeovnv1.ProtocolIPv6), "-", ".", -1) + svcAsNameIPv4 := strings.ReplaceAll(fmt.Sprintf("%s.%s.service.%s", npName, np.Namespace, kubeovnv1.ProtocolIPv4), "-", ".") + svcAsNameIPv6 := strings.ReplaceAll(fmt.Sprintf("%s.%s.service.%s", npName, np.Namespace, kubeovnv1.ProtocolIPv6), "-", ".") svcIpv4s, svcIpv6s, err := c.fetchSelectedSvc(np.Namespace, &np.Spec.PodSelector) if err != nil { klog.Errorf("failed to fetchSelectedSvc svcIPs result %v", err) @@ -222,30 +219,30 @@ func (c *Controller) handleUpdateNp(key string) error { svcIPs = svcIpv6s } - if err = c.ovnNbClient.CreateAddressSet(svcAsName, map[string]string{ + if err = c.OVNNbClient.CreateAddressSet(svcAsName, map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "service"), }); err != nil { klog.Errorf("create address set %s for np %s: %v", svcAsName, key, err) return err } - if err = c.ovnNbClient.AddressSetUpdateAddress(svcAsName, svcIPs...); err != nil { + if err = c.OVNNbClient.AddressSetUpdateAddress(svcAsName, svcIPs...); err != nil { klog.Errorf("set service ips to address set %s: %v", svcAsName, err) return err } } } - var ingressAclOps []ovsdb.Operation + var ingressACLOps []ovsdb.Operation - clearIngressAclOps, err := c.ovnNbClient.DeleteAclsOps(pgName, portGroupKey, "to-lport", nil) + clearIngressACLOps, err := c.OVNNbClient.DeleteAclsOps(pgName, portGroupKey, "to-lport", nil) if err != nil { klog.Errorf("generate operations that clear np %s ingress acls: %v", key, err) return err } // put clear acl and update acl in a single transaction to imitate update acl - ingressAclOps = append(ingressAclOps, clearIngressAclOps...) + ingressACLOps = append(ingressACLOps, clearIngressACLOps...) if hasIngressRule(np) { for _, subnet := range subnets { @@ -277,26 +274,26 @@ func (c *Controller) handleUpdateNp(key string) error { } klog.Infof("UpdateNp Ingress, allows is %v, excepts is %v, log %v", allows, excepts, logEnable) - if err = c.ovnNbClient.CreateAddressSet(ingressAllowAsName, map[string]string{ + if err = c.OVNNbClient.CreateAddressSet(ingressAllowAsName, map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "ingress"), }); err != nil { klog.Errorf("create address set %s for np %s: %v", ingressAllowAsName, key, err) return err } - if err = c.ovnNbClient.AddressSetUpdateAddress(ingressAllowAsName, allows...); err != nil { + if err = c.OVNNbClient.AddressSetUpdateAddress(ingressAllowAsName, allows...); err != nil { klog.Errorf("set ingress allow ips to address set %s: %v", ingressAllowAsName, err) return err } - if err = c.ovnNbClient.CreateAddressSet(ingressExceptAsName, map[string]string{ + if err = c.OVNNbClient.CreateAddressSet(ingressExceptAsName, map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "ingress"), }); err != nil { klog.Errorf("create address set %s for np %s: %v", ingressExceptAsName, key, err) return err } - if err = c.ovnNbClient.AddressSetUpdateAddress(ingressExceptAsName, excepts...); err != nil { + if err = c.OVNNbClient.AddressSetUpdateAddress(ingressExceptAsName, excepts...); err != nil { klog.Errorf("set ingress except ips to address set %s: %v", ingressExceptAsName, err) return err } @@ -306,53 +303,53 @@ func (c *Controller) handleUpdateNp(key string) error { npp = npr.Ports } - ops, err := c.ovnNbClient.UpdateIngressAclOps(pgName, ingressAllowAsName, ingressExceptAsName, protocol, npp, logEnable, namedPortMap) + ops, err := c.OVNNbClient.UpdateIngressACLOps(pgName, ingressAllowAsName, ingressExceptAsName, protocol, npp, logEnable, namedPortMap) if err != nil { klog.Errorf("generate operations that add ingress acls to np %s: %v", key, err) return err } - ingressAclOps = append(ingressAclOps, ops...) + ingressACLOps = append(ingressACLOps, ops...) } if len(np.Spec.Ingress) == 0 { ingressAllowAsName := fmt.Sprintf("%s.%s.all", ingressAllowAsNamePrefix, protocol) ingressExceptAsName := fmt.Sprintf("%s.%s.all", ingressExceptAsNamePrefix, protocol) - if err = c.ovnNbClient.CreateAddressSet(ingressAllowAsName, map[string]string{ + if err = c.OVNNbClient.CreateAddressSet(ingressAllowAsName, map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "ingress"), }); err != nil { klog.Errorf("create address set %s for np %s: %v", ingressAllowAsName, key, err) return err } - if err = c.ovnNbClient.CreateAddressSet(ingressExceptAsName, map[string]string{ + if err = c.OVNNbClient.CreateAddressSet(ingressExceptAsName, map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "ingress"), }); err != nil { klog.Errorf("create address set %s for np %s: %v", ingressExceptAsName, key, err) return err } - ops, err := c.ovnNbClient.UpdateIngressAclOps(pgName, ingressAllowAsName, ingressExceptAsName, protocol, []netv1.NetworkPolicyPort{}, logEnable, namedPortMap) + ops, err := c.OVNNbClient.UpdateIngressACLOps(pgName, ingressAllowAsName, ingressExceptAsName, protocol, []netv1.NetworkPolicyPort{}, logEnable, namedPortMap) if err != nil { klog.Errorf("generate operations that add ingress acls to np %s: %v", key, err) return err } - ingressAclOps = append(ingressAclOps, ops...) + ingressACLOps = append(ingressACLOps, ops...) } - if err = c.ovnNbClient.Transact("add-ingress-acls", ingressAclOps); err != nil { + if err = c.OVNNbClient.Transact("add-ingress-acls", ingressACLOps); err != nil { return fmt.Errorf("add ingress acls to %s: %v", pgName, err) } - if err = c.ovnNbClient.SetAclLog(pgName, protocol, logEnable, true); err != nil { + if err = c.OVNNbClient.SetACLLog(pgName, protocol, logEnable, true); err != nil { // just log and do not return err here klog.Errorf("failed to set ingress acl log for np %s, %v", key, err) } } } - ass, err := c.ovnNbClient.ListAddressSets(map[string]string{ + ass, err := c.OVNNbClient.ListAddressSets(map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "ingress"), }) if err != nil { @@ -372,19 +369,19 @@ func (c *Controller) handleUpdateNp(key string) error { } idx, _ := strconv.Atoi(idxStr) if idx >= len(np.Spec.Ingress) { - if err = c.ovnNbClient.DeleteAddressSet(as.Name); err != nil { + if err = c.OVNNbClient.DeleteAddressSet(as.Name); err != nil { klog.Errorf("failed to delete np %s address set, %v", key, err) return err } } } } else { - if err = c.ovnNbClient.DeleteAcls(pgName, portGroupKey, "to-lport", nil); err != nil { + if err = c.OVNNbClient.DeleteAcls(pgName, portGroupKey, "to-lport", nil); err != nil { klog.Errorf("delete np %s ingress acls: %v", key, err) return err } - if err := c.ovnNbClient.DeleteAddressSets(map[string]string{ + if err := c.OVNNbClient.DeleteAddressSets(map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "ingress"), }); err != nil { klog.Errorf("delete np %s ingress address set: %v", key, err) @@ -392,16 +389,16 @@ func (c *Controller) handleUpdateNp(key string) error { } } - var egressAclOps []ovsdb.Operation + var egressACLOps []ovsdb.Operation - clearEgressAclOps, err := c.ovnNbClient.DeleteAclsOps(pgName, portGroupKey, "from-lport", nil) + clearEgressACLOps, err := c.OVNNbClient.DeleteAclsOps(pgName, portGroupKey, "from-lport", nil) if err != nil { klog.Errorf("generate operations that clear np %s egress acls: %v", key, err) return err } // put clear and add acl in a single transaction to imitate acl update - egressAclOps = append(egressAclOps, clearEgressAclOps...) + egressACLOps = append(egressACLOps, clearEgressACLOps...) if hasEgressRule(np) { for _, subnet := range subnets { @@ -433,79 +430,79 @@ func (c *Controller) handleUpdateNp(key string) error { } klog.Infof("UpdateNp Egress, allows is %v, excepts is %v, log %v", allows, excepts, logEnable) - if err = c.ovnNbClient.CreateAddressSet(egressAllowAsName, map[string]string{ + if err = c.OVNNbClient.CreateAddressSet(egressAllowAsName, map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "egress"), }); err != nil { klog.Errorf("create address set %s for np %s: %v", egressAllowAsName, key, err) return err } - if err = c.ovnNbClient.AddressSetUpdateAddress(egressAllowAsName, allows...); err != nil { + if err = c.OVNNbClient.AddressSetUpdateAddress(egressAllowAsName, allows...); err != nil { klog.Errorf("set egress allow ips to address set %s: %v", egressAllowAsName, err) return err } - if err = c.ovnNbClient.CreateAddressSet(egressExceptAsName, map[string]string{ + if err = c.OVNNbClient.CreateAddressSet(egressExceptAsName, map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "egress"), }); err != nil { klog.Errorf("create address set %s for np %s: %v", egressExceptAsName, key, err) return err } - if err = c.ovnNbClient.AddressSetUpdateAddress(egressExceptAsName, excepts...); err != nil { + if err = c.OVNNbClient.AddressSetUpdateAddress(egressExceptAsName, excepts...); err != nil { klog.Errorf("set egress except ips to address set %s: %v", egressExceptAsName, err) return err } if len(allows) != 0 || len(excepts) != 0 { - ops, err := c.ovnNbClient.UpdateEgressAclOps(pgName, egressAllowAsName, egressExceptAsName, protocol, npr.Ports, logEnable, namedPortMap) + ops, err := c.OVNNbClient.UpdateEgressACLOps(pgName, egressAllowAsName, egressExceptAsName, protocol, npr.Ports, logEnable, namedPortMap) if err != nil { klog.Errorf("generate operations that add egress acls to np %s: %v", key, err) return err } - egressAclOps = append(egressAclOps, ops...) + egressACLOps = append(egressACLOps, ops...) } } if len(np.Spec.Egress) == 0 { egressAllowAsName := fmt.Sprintf("%s.%s.all", egressAllowAsNamePrefix, protocol) egressExceptAsName := fmt.Sprintf("%s.%s.all", egressExceptAsNamePrefix, protocol) - if err = c.ovnNbClient.CreateAddressSet(egressAllowAsName, map[string]string{ + if err = c.OVNNbClient.CreateAddressSet(egressAllowAsName, map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "egress"), }); err != nil { klog.Errorf("create address set %s for np %s: %v", egressAllowAsName, key, err) return err } - if err = c.ovnNbClient.CreateAddressSet(egressExceptAsName, map[string]string{ + if err = c.OVNNbClient.CreateAddressSet(egressExceptAsName, map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "egress"), }); err != nil { klog.Errorf("create address set %s for np %s: %v", egressExceptAsName, key, err) return err } - ops, err := c.ovnNbClient.UpdateEgressAclOps(pgName, egressAllowAsName, egressExceptAsName, protocol, []netv1.NetworkPolicyPort{}, logEnable, namedPortMap) + ops, err := c.OVNNbClient.UpdateEgressACLOps(pgName, egressAllowAsName, egressExceptAsName, protocol, []netv1.NetworkPolicyPort{}, logEnable, namedPortMap) if err != nil { klog.Errorf("generate operations that add egress acls to np %s: %v", key, err) return err } - egressAclOps = append(egressAclOps, ops...) + egressACLOps = append(egressACLOps, ops...) } - if err = c.ovnNbClient.Transact("add-egress-acls", egressAclOps); err != nil { + if err = c.OVNNbClient.Transact("add-egress-acls", egressACLOps); err != nil { return fmt.Errorf("add egress acls to %s: %v", pgName, err) } - if err = c.ovnNbClient.SetAclLog(pgName, protocol, logEnable, false); err != nil { + if err = c.OVNNbClient.SetACLLog(pgName, protocol, logEnable, false); err != nil { // just log and do not return err here klog.Errorf("failed to set egress acl log for np %s, %v", key, err) } } } - ass, err := c.ovnNbClient.ListAddressSets(map[string]string{ + ass, err := c.OVNNbClient.ListAddressSets(map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "egress"), }) if err != nil { @@ -526,19 +523,19 @@ func (c *Controller) handleUpdateNp(key string) error { idx, _ := strconv.Atoi(idxStr) if idx >= len(np.Spec.Egress) { - if err = c.ovnNbClient.DeleteAddressSet(as.Name); err != nil { + if err = c.OVNNbClient.DeleteAddressSet(as.Name); err != nil { klog.Errorf("delete np %s address set: %v", key, err) return err } } } } else { - if err = c.ovnNbClient.DeleteAcls(pgName, portGroupKey, "from-lport", nil); err != nil { + if err = c.OVNNbClient.DeleteAcls(pgName, portGroupKey, "from-lport", nil); err != nil { klog.Errorf("delete np %s egress acls: %v", key, err) return err } - if err := c.ovnNbClient.DeleteAddressSets(map[string]string{ + if err := c.OVNNbClient.DeleteAddressSets(map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", np.Namespace, np.Name, "egress"), }); err != nil { klog.Errorf("delete np %s egress address set: %v", key, err) @@ -547,7 +544,7 @@ func (c *Controller) handleUpdateNp(key string) error { } for _, subnet := range subnets { - if err = c.ovnNbClient.CreateGatewayAcl("", pgName, subnet.Spec.Gateway); err != nil { + if err = c.OVNNbClient.CreateGatewayACL("", pgName, subnet.Spec.Gateway); err != nil { klog.Errorf("create gateway acl: %v", err) return err } @@ -572,26 +569,26 @@ func (c *Controller) handleDeleteNp(key string) error { npName = "np" + name } - pgName := strings.Replace(fmt.Sprintf("%s.%s", name, namespace), "-", ".", -1) - if err = c.ovnNbClient.DeletePortGroup(pgName); err != nil { + pgName := strings.ReplaceAll(fmt.Sprintf("%s.%s", name, namespace), "-", ".") + if err = c.OVNNbClient.DeletePortGroup(pgName); err != nil { klog.Errorf("delete np %s port group: %v", key, err) } - if err := c.ovnNbClient.DeleteAddressSets(map[string]string{ + if err := c.OVNNbClient.DeleteAddressSets(map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", namespace, npName, "service"), }); err != nil { klog.Errorf("delete np %s service address set: %v", key, err) return err } - if err := c.ovnNbClient.DeleteAddressSets(map[string]string{ + if err := c.OVNNbClient.DeleteAddressSets(map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", namespace, npName, "ingress"), }); err != nil { klog.Errorf("delete np %s ingress address set: %v", key, err) return err } - if err := c.ovnNbClient.DeleteAddressSets(map[string]string{ + if err := c.OVNNbClient.DeleteAddressSets(map[string]string{ networkPolicyKey: fmt.Sprintf("%s/%s/%s", namespace, npName, "egress"), }); err != nil { klog.Errorf("delete np %s egress address set: %v", key, err) @@ -753,7 +750,7 @@ func (c *Controller) fetchPolicySelectedAddresses(namespace, protocol string, np return nil, nil, err } for _, podNet := range podNets { - podIPAnnotation := pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)] + podIPAnnotation := pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] podIPs := strings.Split(podIPAnnotation, ",") for _, podIP := range podIPs { if podIP != "" && util.CheckProtocol(podIP) == protocol { @@ -785,7 +782,7 @@ func svcMatchPods(svcs []*corev1.Service, pod *corev1.Pod, protocol string) ([]s } if isMatch { clusterIPs := util.ServiceClusterIPs(*svc) - protocolClusterIPs := getProtocolSvcIp(clusterIPs, protocol) + protocolClusterIPs := getProtocolSvcIP(clusterIPs, protocol) if len(protocolClusterIPs) != 0 { matchSvcs = append(matchSvcs, protocolClusterIPs...) } @@ -793,7 +790,8 @@ func svcMatchPods(svcs []*corev1.Service, pod *corev1.Pod, protocol string) ([]s } return matchSvcs, nil } -func getProtocolSvcIp(clusterIPs []string, protocol string) []string { + +func getProtocolSvcIP(clusterIPs []string, protocol string) []string { protocolClusterIPs := []string{} for _, clusterIP := range clusterIPs { if clusterIP != "" && clusterIP != corev1.ClusterIPNone && util.CheckProtocol(clusterIP) == protocol { @@ -802,6 +800,7 @@ func getProtocolSvcIp(clusterIPs []string, protocol string) []string { } return protocolClusterIPs } + func isSvcMatchPod(svc *corev1.Service, pod *corev1.Pod) (bool, error) { ss := metav1.SetAsLabelSelector(svc.Spec.Selector) sel, err := metav1.LabelSelectorAsSelector(ss) @@ -899,7 +898,6 @@ func isPodMatchPolicyPeer(pod *corev1.Pod, podNs corev1.Namespace, policyPeer ne if policyNs != podNs.Name { return false } - } else { nsSel, _ := metav1.LabelSelectorAsSelector(policyPeer.NamespaceSelector) if podNs.Labels == nil { diff --git a/pkg/controller/node.go b/pkg/controller/node.go index 9289ed971ef..196f2574d7d 100644 --- a/pkg/controller/node.go +++ b/pkg/controller/node.go @@ -27,7 +27,6 @@ import ( ) func (c *Controller) enqueueAddNode(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -48,7 +47,6 @@ func nodeReady(node *v1.Node) bool { } func (c *Controller) enqueueUpdateNode(oldObj, newObj interface{}) { - oldNode := oldObj.(*v1.Node) newNode := newObj.(*v1.Node) @@ -118,7 +116,6 @@ func (c *Controller) processNextAddNodeWorkItem() bool { c.addNodeQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -149,7 +146,6 @@ func (c *Controller) processNextUpdateNodeWorkItem() bool { c.updateNodeQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -180,7 +176,6 @@ func (c *Controller) processNextDeleteNodeWorkItem() bool { c.deleteNodeQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -240,9 +235,9 @@ func (c *Controller) handleAddNode(key string) error { var v4IP, v6IP, mac string portName := fmt.Sprintf("node-%s", key) - if node.Annotations[util.AllocatedAnnotation] == "true" && node.Annotations[util.IpAddressAnnotation] != "" && node.Annotations[util.MacAddressAnnotation] != "" { + if node.Annotations[util.AllocatedAnnotation] == "true" && node.Annotations[util.IPAddressAnnotation] != "" && node.Annotations[util.MacAddressAnnotation] != "" { macStr := node.Annotations[util.MacAddressAnnotation] - v4IP, v6IP, mac, err = c.ipam.GetStaticAddress(portName, portName, node.Annotations[util.IpAddressAnnotation], + v4IP, v6IP, mac, err = c.ipam.GetStaticAddress(portName, portName, node.Annotations[util.IPAddressAnnotation], &macStr, node.Annotations[util.LogicalSwitchAnnotation], true) if err != nil { klog.Errorf("failed to alloc static ip addrs for node %v: %v", node.Name, err) @@ -257,7 +252,7 @@ func (c *Controller) handleAddNode(key string) error { } ipStr := util.GetStringIP(v4IP, v6IP) - if err := c.ovnNbClient.CreateBareLogicalSwitchPort(c.config.NodeSwitch, portName, ipStr, mac); err != nil { + if err := c.OVNNbClient.CreateBareLogicalSwitchPort(c.config.NodeSwitch, portName, ipStr, mac); err != nil { return err } @@ -279,17 +274,17 @@ func (c *Controller) handleAddNode(key string) error { "address-family": strconv.Itoa(af), } klog.Infof("add policy route for router: %s, match %s, action %s, nexthop %s, externalID %v", c.config.ClusterRouter, match, action, ip, externalIDs) - if err = c.ovnNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.NodeRouterPolicyPriority, match, action, []string{ip}, externalIDs); err != nil { + if err = c.OVNNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.NodeRouterPolicyPriority, match, action, []string{ip}, externalIDs); err != nil { klog.Errorf("failed to add logical router policy for node %s: %v", node.Name, err) return err } - if err = c.deletePolicyRouteForLocalDnsCacheOnNode(node.Name, af); err != nil { + if err = c.deletePolicyRouteForLocalDNSCacheOnNode(node.Name, af); err != nil { return err } - if c.config.NodeLocalDnsIP != "" { - if err = c.addPolicyRouteForLocalDnsCacheOnNode(portName, ip, node.Name, af); err != nil { + if c.config.NodeLocalDNSIP != "" { + if err = c.addPolicyRouteForLocalDNSCacheOnNode(portName, ip, node.Name, af); err != nil { return err } } @@ -301,8 +296,7 @@ func (c *Controller) handleAddNode(key string) error { return err } - patchPayloadTemplate := - `[{ + patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/annotations", "value": %s @@ -313,7 +307,7 @@ func (c *Controller) handleAddNode(key string) error { op = "add" } - node.Annotations[util.IpAddressAnnotation] = ipStr + node.Annotations[util.IPAddressAnnotation] = ipStr node.Annotations[util.MacAddressAnnotation] = mac node.Annotations[util.CidrAnnotation] = subnet.Spec.CIDRBlock node.Annotations[util.GatewayAnnotation] = subnet.Spec.Gateway @@ -350,8 +344,8 @@ func (c *Controller) handleAddNode(key string) error { } // ovn acl doesn't support address_set name with '-', so replace '-' by '.' - pgName := strings.Replace(node.Annotations[util.PortNameAnnotation], "-", ".", -1) - if err = c.ovnNbClient.CreatePortGroup(pgName, map[string]string{networkPolicyKey: "node" + "/" + key}); err != nil { + pgName := strings.ReplaceAll(node.Annotations[util.PortNameAnnotation], "-", ".") + if err = c.OVNNbClient.CreatePortGroup(pgName, map[string]string{networkPolicyKey: "node" + "/" + key}); err != nil { klog.Errorf("create port group %s for node %s: %v", pgName, key, err) return err } @@ -365,11 +359,7 @@ func (c *Controller) handleAddNode(key string) error { return err } - if err := c.retryDelDupChassis(util.ChasRetryTime, util.ChasRetryIntev+2, c.cleanDuplicatedChassis, node); err != nil { - return err - } - - return nil + return c.retryDelDupChassis(util.ChasRetryTime, util.ChasRetryIntev+2, c.cleanDuplicatedChassis, node) } func (c *Controller) handleNodeAnnotationsForProviderNetworks(node *v1.Node) error { @@ -465,11 +455,11 @@ func (c *Controller) handleDeleteNode(key string) error { portName := fmt.Sprintf("node-%s", key) klog.Infof("delete logical switch port %s", portName) - if err := c.ovnNbClient.DeleteLogicalSwitchPort(portName); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(portName); err != nil { klog.Errorf("failed to delete node switch port node-%s: %v", key, err) return err } - if err := c.ovnSbClient.DeleteChassisByHost(key); err != nil { + if err := c.OVNSbClient.DeleteChassisByHost(key); err != nil { klog.Errorf("failed to delete chassis for node %s: %v", key, err) return err } @@ -478,15 +468,16 @@ func (c *Controller) handleDeleteNode(key string) error { return err } - for _, af := range [...]int{4, 6} { - if err := c.deletePolicyRouteForLocalDnsCacheOnNode(key, af); err != nil { + afs := []int{4, 6} + for _, af := range afs { + if err := c.deletePolicyRouteForLocalDNSCacheOnNode(key, af); err != nil { return err } } // ovn acl doesn't support address_set name with '-', so replace '-' by '.' - pgName := strings.Replace(portName, "-", ".", -1) - if err := c.ovnNbClient.DeletePortGroup(pgName); err != nil { + pgName := strings.ReplaceAll(portName, "-", ".") + if err := c.OVNNbClient.DeletePortGroup(pgName); err != nil { klog.Errorf("delete port group %s for node: %v", portName, err) return err } @@ -498,19 +489,19 @@ func (c *Controller) handleDeleteNode(key string) error { addresses := c.ipam.GetPodAddress(portName) for _, addr := range addresses { - if addr.Ip == "" { + if addr.IP == "" { continue } - if err := c.ovnNbClient.DeleteLogicalRouterPolicyByNexthop(c.config.ClusterRouter, util.NodeRouterPolicyPriority, addr.Ip); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPolicyByNexthop(c.config.ClusterRouter, util.NodeRouterPolicyPriority, addr.IP); err != nil { klog.Errorf("failed to delete router policy for node %s: %v", key, err) return err } } - if err := c.ovnNbClient.DeleteAddressSet(nodeUnderlayAddressSetName(key, 4)); err != nil { + if err := c.OVNNbClient.DeleteAddressSet(nodeUnderlayAddressSetName(key, 4)); err != nil { klog.Errorf("failed to delete address set for node %s: %v", key, err) return err } - if err := c.ovnNbClient.DeleteAddressSet(nodeUnderlayAddressSetName(key, 6)); err != nil { + if err := c.OVNNbClient.DeleteAddressSet(nodeUnderlayAddressSetName(key, 6)); err != nil { klog.Errorf("failed to delete address set for node %s: %v", key, err) return err } @@ -631,13 +622,15 @@ func (c *Controller) handleUpdateNode(key string) error { func (c *Controller) createOrUpdateCrdIPs(podName, ip, mac, subnetName, ns, nodeName, providerName, podType string, existingCR **kubeovnv1.IP) error { var key, ipName string - if subnetName == c.config.NodeSwitch { + + switch { + case subnetName == c.config.NodeSwitch: key = nodeName ipName = fmt.Sprintf("node-%s", nodeName) - } else if strings.HasPrefix(podName, util.U2OInterconnName[0:19]) { + case strings.HasPrefix(podName, util.U2OInterconnName[0:19]): key = podName ipName = podName - } else { + default: key = podName ipName = ovs.PodNameToPortName(podName, ns, providerName) } @@ -691,35 +684,35 @@ func (c *Controller) createOrUpdateCrdIPs(podName, ip, mac, subnetName, ns, node return errMsg } } else { - newIpCr := ipCr.DeepCopy() - if newIpCr.Labels != nil { - newIpCr.Labels[util.SubnetNameLabel] = subnetName - newIpCr.Labels[util.NodeNameLabel] = nodeName + newIPCr := ipCr.DeepCopy() + if newIPCr.Labels != nil { + newIPCr.Labels[util.SubnetNameLabel] = subnetName + newIPCr.Labels[util.NodeNameLabel] = nodeName } else { - newIpCr.Labels = map[string]string{ + newIPCr.Labels = map[string]string{ util.SubnetNameLabel: subnetName, util.NodeNameLabel: nodeName, } } - newIpCr.Spec.PodName = key - newIpCr.Spec.Namespace = ns - newIpCr.Spec.Subnet = subnetName - newIpCr.Spec.NodeName = nodeName - newIpCr.Spec.IPAddress = ip - newIpCr.Spec.V4IPAddress = v4IP - newIpCr.Spec.V6IPAddress = v6IP - newIpCr.Spec.MacAddress = mac - newIpCr.Spec.AttachIPs = []string{} - newIpCr.Spec.AttachMacs = []string{} - newIpCr.Spec.AttachSubnets = []string{} - newIpCr.Spec.PodType = podType - if reflect.DeepEqual(newIpCr.Labels, ipCr.Labels) && reflect.DeepEqual(newIpCr.Spec, ipCr.Spec) { + newIPCr.Spec.PodName = key + newIPCr.Spec.Namespace = ns + newIPCr.Spec.Subnet = subnetName + newIPCr.Spec.NodeName = nodeName + newIPCr.Spec.IPAddress = ip + newIPCr.Spec.V4IPAddress = v4IP + newIPCr.Spec.V6IPAddress = v6IP + newIPCr.Spec.MacAddress = mac + newIPCr.Spec.AttachIPs = []string{} + newIPCr.Spec.AttachMacs = []string{} + newIPCr.Spec.AttachSubnets = []string{} + newIPCr.Spec.PodType = podType + if reflect.DeepEqual(newIPCr.Labels, ipCr.Labels) && reflect.DeepEqual(newIPCr.Spec, ipCr.Spec) { return nil } - _, err := c.config.KubeOvnClient.KubeovnV1().IPs().Update(context.Background(), newIpCr, metav1.UpdateOptions{}) + _, err := c.config.KubeOvnClient.KubeovnV1().IPs().Update(context.Background(), newIPCr, metav1.UpdateOptions{}) if err != nil { - errMsg := fmt.Errorf("failed to update ip CR %s: %v", newIpCr.Name, err) + errMsg := fmt.Errorf("failed to update ip CR %s: %v", newIPCr.Name, err) klog.Error(errMsg) return errMsg } @@ -768,7 +761,7 @@ func (c *Controller) checkGatewayReady() error { } for _, node := range nodes { - ipStr := node.Annotations[util.IpAddressAnnotation] + ipStr := node.Annotations[util.IPAddressAnnotation] for _, ip := range strings.Split(ipStr, ",") { for _, cidrBlock := range strings.Split(subnet.Spec.CIDRBlock, ",") { if util.CheckProtocol(cidrBlock) != util.CheckProtocol(ip) { @@ -780,7 +773,7 @@ func (c *Controller) checkGatewayReady() error { klog.Errorf("check ecmp policy route exist for subnet %v, error %v", subnet.Name, err) break } - nextHops, nameIpMap, err := c.getPolicyRouteParas(cidrBlock, util.GatewayRouterPolicyPriority) + nextHops, nameIPMap, err := c.getPolicyRouteParas(cidrBlock, util.GatewayRouterPolicyPriority) if err != nil { klog.Errorf("get ecmp policy route paras for subnet %v, error %v", subnet.Name, err) break @@ -817,9 +810,9 @@ func (c *Controller) checkGatewayReady() error { if exist { klog.Warningf("failed to ping ovn0 %s or node %s is not ready, delete ecmp policy route for node", ip, node.Name) nextHops.Remove(ip) - delete(nameIpMap, node.Name) + delete(nameIPMap, node.Name) klog.Infof("update policy route for centralized subnet %s, nextHops %s", subnet.Name, nextHops) - if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIpMap); err != nil { + if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIPMap); err != nil { klog.Errorf("failed to delete ecmp policy route for subnet %s on node %s, %v", subnet.Name, node.Name, err) return err } @@ -828,27 +821,25 @@ func (c *Controller) checkGatewayReady() error { klog.V(3).Infof("succeed to ping gw %s", ip) if !exist { nextHops.Add(ip) - if nameIpMap == nil { - nameIpMap = make(map[string]string, 1) + if nameIPMap == nil { + nameIPMap = make(map[string]string, 1) } - nameIpMap[node.Name] = ip + nameIPMap[node.Name] = ip klog.Infof("update policy route for centralized subnet %s, nextHops %s", subnet.Name, nextHops) - if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIpMap); err != nil { + if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIPMap); err != nil { klog.Errorf("failed to add ecmp policy route for subnet %s on node %s, %v", subnet.Name, node.Name, err) return err } } } - } else { - if exist { - klog.Infof("subnet %s gatewayNode does not contains node %v, delete policy route for node ip %s", subnet.Name, node.Name, ip) - nextHops.Remove(ip) - delete(nameIpMap, node.Name) - klog.Infof("update policy route for centralized subnet %s, nextHops %s", subnet.Name, nextHops) - if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIpMap); err != nil { - klog.Errorf("failed to delete ecmp policy route for subnet %s on node %s, %v", subnet.Name, node.Name, err) - return err - } + } else if exist { + klog.Infof("subnet %s gatewayNode does not contains node %v, delete policy route for node ip %s", subnet.Name, node.Name, ip) + nextHops.Remove(ip) + delete(nameIPMap, node.Name) + klog.Infof("update policy route for centralized subnet %s, nextHops %s", subnet.Name, nextHops) + if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIPMap); err != nil { + klog.Errorf("failed to delete ecmp policy route for subnet %s on node %s, %v", subnet.Name, node.Name, err) + return err } } } @@ -860,14 +851,14 @@ func (c *Controller) checkGatewayReady() error { func (c *Controller) cleanDuplicatedChassis(node *v1.Node) error { // if multi chassis has the same node name, delete all of them - chassises, err := c.ovnSbClient.GetAllChassisByHost(node.Name) + chassises, err := c.OVNSbClient.GetAllChassisByHost(node.Name) if err != nil { klog.Errorf("failed to list chassis %v", err) return err } if len(*chassises) > 1 { klog.Warningf("node %s has multiple chassis", node.Name) - if err := c.ovnSbClient.DeleteChassisByHost(node.Name); err != nil { + if err := c.OVNSbClient.DeleteChassisByHost(node.Name); err != nil { klog.Errorf("failed to delete chassis for node %s: %v", node.Name, err) return err } @@ -875,7 +866,7 @@ func (c *Controller) cleanDuplicatedChassis(node *v1.Node) error { return nil } -func (c *Controller) retryDelDupChassis(attempts int, sleep int, f func(node *v1.Node) error, node *v1.Node) (err error) { +func (c *Controller) retryDelDupChassis(attempts, sleep int, f func(node *v1.Node) error, node *v1.Node) (err error) { i := 0 for ; ; i++ { err = f(node) @@ -948,11 +939,11 @@ func (c *Controller) checkAndUpdateNodePortGroup() error { for _, node := range nodes { // The port-group should already created when add node - pgName := strings.Replace(node.Annotations[util.PortNameAnnotation], "-", ".", -1) + pgName := strings.ReplaceAll(node.Annotations[util.PortNameAnnotation], "-", ".") // use join IP only when no internal IP exists nodeIPv4, nodeIPv6 := util.GetNodeInternalIP(*node) - joinIP := node.Annotations[util.IpAddressAnnotation] + joinIP := node.Annotations[util.IPAddressAnnotation] joinIPv4, joinIPv6 := util.SplitStringIP(joinIP) if nodeIPv4 == "" { nodeIPv4 = joinIPv4 @@ -968,18 +959,18 @@ func (c *Controller) checkAndUpdateNodePortGroup() error { return err } - if err = c.ovnNbClient.PortGroupSetPorts(pgName, nodePorts); err != nil { + if err = c.OVNNbClient.PortGroupSetPorts(pgName, nodePorts); err != nil { klog.Errorf("add ports to port group %s: %v", pgName, err) return err } if networkPolicyExists { - if err := c.ovnNbClient.CreateNodeAcl(pgName, nodeIP, joinIP); err != nil { + if err := c.OVNNbClient.CreateNodeACL(pgName, nodeIP, joinIP); err != nil { klog.Errorf("create node acl for node pg %s: %v", pgName, err) } } else { // clear all acl - if err = c.ovnNbClient.DeleteAcls(pgName, portGroupKey, "", nil); err != nil { + if err = c.OVNNbClient.DeleteAcls(pgName, portGroupKey, "", nil); err != nil { klog.Errorf("delete node acl for node pg %s: %v", pgName, err) } } @@ -994,14 +985,14 @@ func (c *Controller) UpdateChassisTag(node *v1.Node) error { // kube-ovn-cni not ready to set chassis return nil } - chassis, err := c.ovnSbClient.GetChassis(annoChassisName, false) + chassis, err := c.OVNSbClient.GetChassis(annoChassisName, false) if err != nil { klog.Errorf("failed to get node %s chassis: %s, %v", node.Name, annoChassisName, err) return err } if chassis.ExternalIDs == nil || chassis.ExternalIDs["vendor"] != util.CniTypeName { klog.Infof("init tag %s for node %s chassis", util.CniTypeName, node.Name) - if err = c.ovnSbClient.UpdateChassisTag(chassis.Name, node.Name); err != nil { + if err = c.OVNSbClient.UpdateChassisTag(chassis.Name, node.Name); err != nil { return fmt.Errorf("failed to init chassis tag, %v", err) } return nil @@ -1012,7 +1003,7 @@ func (c *Controller) UpdateChassisTag(node *v1.Node) error { func (c *Controller) addNodeGwStaticRoute() error { // If user not manage static route for default vpc, just add route about ovn-default to join if vpc, err := c.vpcsLister.Get(c.config.ClusterRouter); err != nil || vpc.Spec.StaticRoutes != nil { - existRoute, err := c.ovnNbClient.ListLogicalRouterStaticRoutes(c.config.ClusterRouter, nil, nil, "", nil) + existRoute, err := c.OVNNbClient.ListLogicalRouterStaticRoutes(c.config.ClusterRouter, nil, nil, "", nil) if err != nil { klog.Errorf("failed to get vpc %s static route list, %v", c.config.ClusterRouter, err) } @@ -1027,7 +1018,7 @@ func (c *Controller) addNodeGwStaticRoute() error { if util.CheckProtocol(cidrBlock) != util.CheckProtocol(nextHop) { continue } - if err := c.ovnNbClient.AddLogicalRouterStaticRoute(c.config.ClusterRouter, util.MainRouteTable, ovnnb.LogicalRouterStaticRoutePolicyDstIP, cidrBlock, nil, nextHop); err != nil { + if err := c.OVNNbClient.AddLogicalRouterStaticRoute(c.config.ClusterRouter, util.MainRouteTable, ovnnb.LogicalRouterStaticRoutePolicyDstIP, cidrBlock, nil, nextHop); err != nil { klog.Errorf("failed to add static route for node gw: %v", err) return err } @@ -1042,7 +1033,7 @@ func (c *Controller) getPolicyRouteParas(cidr string, priority int) (*strset.Set ipSuffix = "ip6" } match := fmt.Sprintf("%s.src == %s", ipSuffix, cidr) - policyList, err := c.ovnNbClient.GetLogicalRouterPolicy(c.config.ClusterRouter, priority, match, true) + policyList, err := c.OVNNbClient.GetLogicalRouterPolicy(c.config.ClusterRouter, priority, match, true) if err != nil { klog.Errorf("failed to get logical router policy: %v", err) return nil, nil, err @@ -1054,12 +1045,12 @@ func (c *Controller) getPolicyRouteParas(cidr string, priority int) (*strset.Set } func (c *Controller) checkPolicyRouteExistForNode(nodeName, cidr, nexthop string, priority int) (bool, error) { - _, nameIpMap, err := c.getPolicyRouteParas(cidr, priority) + _, nameIPMap, err := c.getPolicyRouteParas(cidr, priority) if err != nil { klog.Errorf("failed to get policy route paras, %v", err) return false, err } - if nodeIp, ok := nameIpMap[nodeName]; ok && nodeIp == nexthop { + if nodeIP, ok := nameIPMap[nodeName]; ok && nodeIP == nexthop { return true, nil } return false, nil @@ -1079,7 +1070,7 @@ func (c *Controller) deletePolicyRouteForNode(nodeName string) error { if subnet.Spec.GatewayType == kubeovnv1.GWDistributedType { pgName := getOverlaySubnetsPortGroupName(subnet.Name, nodeName) - if err = c.ovnNbClient.DeletePortGroup(pgName); err != nil { + if err = c.OVNNbClient.DeletePortGroup(pgName); err != nil { klog.Errorf("delete port group for subnet %s and node %s: %v", subnet.Name, nodeName, err) return err } @@ -1094,20 +1085,20 @@ func (c *Controller) deletePolicyRouteForNode(nodeName string) error { if subnet.Spec.GatewayType == kubeovnv1.GWCentralizedType { if subnet.Spec.EnableEcmp { for _, cidrBlock := range strings.Split(subnet.Spec.CIDRBlock, ",") { - nextHops, nameIpMap, err := c.getPolicyRouteParas(cidrBlock, util.GatewayRouterPolicyPriority) + nextHops, nameIPMap, err := c.getPolicyRouteParas(cidrBlock, util.GatewayRouterPolicyPriority) if err != nil { klog.Errorf("get ecmp policy route paras for subnet %v, error %v", subnet.Name, err) continue } exist := false - if _, ok := nameIpMap[nodeName]; ok { + if _, ok := nameIPMap[nodeName]; ok { exist = true } if exist { - nextHops.Remove(nameIpMap[nodeName]) - delete(nameIpMap, nodeName) + nextHops.Remove(nameIPMap[nodeName]) + delete(nameIPMap, nodeName) if nextHops.Size() == 0 { klog.Infof("delete policy route for centralized subnet %s, nextHops %s", subnet.Name, nextHops) @@ -1117,7 +1108,7 @@ func (c *Controller) deletePolicyRouteForNode(nodeName string) error { } } else { klog.Infof("update policy route for centralized subnet %s, nextHops %s", subnet.Name, nextHops) - if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIpMap); err != nil { + if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIPMap); err != nil { klog.Errorf("failed to update policy route for subnet %s on node %s, %v", subnet.Name, nodeName, err) return err } @@ -1167,18 +1158,18 @@ func (c *Controller) addPolicyRouteForCentralizedSubnetOnNode(nodeName, nodeIP s continue } - nextHops, nameIpMap, err := c.getPolicyRouteParas(cidrBlock, util.GatewayRouterPolicyPriority) + nextHops, nameIPMap, err := c.getPolicyRouteParas(cidrBlock, util.GatewayRouterPolicyPriority) if err != nil { klog.Errorf("get ecmp policy route paras for subnet %v, error %v", subnet.Name, err) continue } nextHops.Add(nextHop) - if nameIpMap == nil { - nameIpMap = make(map[string]string, 1) + if nameIPMap == nil { + nameIPMap = make(map[string]string, 1) } - nameIpMap[nodeName] = nextHop + nameIPMap[nodeName] = nextHop klog.Infof("update policy route for centralized subnet %s, nextHops %s", subnet.Name, nextHops) - if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIpMap); err != nil { + if err = c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops.List(), nameIPMap); err != nil { klog.Errorf("failed to update policy route for subnet %s on node %s, %v", subnet.Name, nodeName, err) return err } @@ -1198,7 +1189,7 @@ func (c *Controller) addPolicyRouteForCentralizedSubnetOnNode(nodeName, nodeIP s return nil } -func (c *Controller) addPolicyRouteForLocalDnsCacheOnNode(nodePortName, nodeIP, nodeName string, af int) error { +func (c *Controller) addPolicyRouteForLocalDNSCacheOnNode(nodePortName, nodeIP, nodeName string, af int) error { externalIDs := map[string]string{ "vendor": util.CniTypeName, "node": nodeName, @@ -1206,19 +1197,19 @@ func (c *Controller) addPolicyRouteForLocalDnsCacheOnNode(nodePortName, nodeIP, "isLocalDnsCache": "true", } - pgAs := strings.Replace(fmt.Sprintf("%s_ip%d", nodePortName, af), "-", ".", -1) - match := fmt.Sprintf("ip%d.src == $%s && ip%d.dst == %s", af, pgAs, af, c.config.NodeLocalDnsIP) + pgAs := strings.ReplaceAll(fmt.Sprintf("%s_ip%d", nodePortName, af), "-", ".") + match := fmt.Sprintf("ip%d.src == $%s && ip%d.dst == %s", af, pgAs, af, c.config.NodeLocalDNSIP) action := ovnnb.LogicalRouterPolicyActionReroute klog.Infof("add node local dns cache policy route for router: %s, match %s, action %s, nexthop %s, externalID %v", c.config.ClusterRouter, match, action, nodeIP, externalIDs) - if err := c.ovnNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.NodeLocalDnsPolicyPriority, match, action, []string{nodeIP}, externalIDs); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.NodeLocalDNSPolicyPriority, match, action, []string{nodeIP}, externalIDs); err != nil { klog.Errorf("failed to add logical router policy for node %s: %v", nodeName, err) return err } return nil } -func (c *Controller) deletePolicyRouteForLocalDnsCacheOnNode(nodeName string, af int) error { - policies, err := c.ovnNbClient.ListLogicalRouterPolicies(c.config.ClusterRouter, -1, map[string]string{ +func (c *Controller) deletePolicyRouteForLocalDNSCacheOnNode(nodeName string, af int) error { + policies, err := c.OVNNbClient.ListLogicalRouterPolicies(c.config.ClusterRouter, -1, map[string]string{ "vendor": util.CniTypeName, "node": nodeName, "address-family": strconv.Itoa(af), @@ -1235,7 +1226,7 @@ func (c *Controller) deletePolicyRouteForLocalDnsCacheOnNode(nodeName string, af for _, policy := range policies { klog.Infof("delete node local dns cache policy route for router %s with match %s", c.config.ClusterRouter, policy.Match) - if err := c.ovnNbClient.DeleteLogicalRouterPolicyByUUID(c.config.ClusterRouter, policy.UUID); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPolicyByUUID(c.config.ClusterRouter, policy.UUID); err != nil { klog.Errorf("failed to delete policy route for node local dns in router %s with match %s: %v", c.config.ClusterRouter, policy.Match, err) return err } diff --git a/pkg/controller/ovn-ic.go b/pkg/controller/ovn-ic.go index c6267f822f1..e3a60651c8b 100644 --- a/pkg/controller/ovn-ic.go +++ b/pkg/controller/ovn-ic.go @@ -58,84 +58,82 @@ func (c *Controller) resyncInterConnection() { klog.Info("finish removing ovn-ic") return - } else { - blackList := []string{} - autoRoute := false - if cm.Data["auto-route"] == "true" { - autoRoute = true - } - subnets, err := c.subnetsLister.List(labels.Everything()) - if err != nil { - klog.Errorf("failed to list subnets, %v", err) - return - } - for _, subnet := range subnets { - if subnet.Spec.DisableInterConnection || subnet.Name == c.config.NodeSwitch { - blackList = append(blackList, subnet.Spec.CIDRBlock) - } - } - nodes, err := c.nodesLister.List(labels.Everything()) - if err != nil { - klog.Errorf("failed to list node, %v", err) - return + } + blackList := []string{} + autoRoute := false + if cm.Data["auto-route"] == "true" { + autoRoute = true + } + subnets, err := c.subnetsLister.List(labels.Everything()) + if err != nil { + klog.Errorf("failed to list subnets, %v", err) + return + } + for _, subnet := range subnets { + if subnet.Spec.DisableInterConnection || subnet.Name == c.config.NodeSwitch { + blackList = append(blackList, subnet.Spec.CIDRBlock) } - for _, node := range nodes { - ipv4, ipv6 := util.GetNodeInternalIP(*node) - if ipv4 != "" { - blackList = append(blackList, ipv4) - } - if ipv6 != "" { - blackList = append(blackList, ipv6) - } + } + nodes, err := c.nodesLister.List(labels.Everything()) + if err != nil { + klog.Errorf("failed to list node, %v", err) + return + } + for _, node := range nodes { + ipv4, ipv6 := util.GetNodeInternalIP(*node) + if ipv4 != "" { + blackList = append(blackList, ipv4) } - if err := c.ovnNbClient.SetICAutoRoute(autoRoute, blackList); err != nil { - klog.Errorf("failed to config auto route, %v", err) - return + if ipv6 != "" { + blackList = append(blackList, ipv6) } + } + if err := c.OVNNbClient.SetICAutoRoute(autoRoute, blackList); err != nil { + klog.Errorf("failed to config auto route, %v", err) + return + } - isCMEqual := reflect.DeepEqual(cm.Data, lastIcCm) - if icEnabled == "true" && lastIcCm != nil && isCMEqual { + isCMEqual := reflect.DeepEqual(cm.Data, lastIcCm) + if icEnabled == "true" && lastIcCm != nil && isCMEqual { + return + } + if icEnabled == "true" && lastIcCm != nil && !isCMEqual { + if err := c.removeInterConnection(lastIcCm["az-name"]); err != nil { + klog.Errorf("failed to remove ovn-ic, %v", err) return } - if icEnabled == "true" && lastIcCm != nil && !isCMEqual { - if err := c.removeInterConnection(lastIcCm["az-name"]); err != nil { - klog.Errorf("failed to remove ovn-ic, %v", err) - return - } - if err := c.delLearnedRoute(); err != nil { - klog.Errorf("failed to remove learned static routes, %v", err) - return - } - c.ovnLegacyClient.OvnICSbAddress = genHostAddress(cm.Data["ic-db-host"], cm.Data["ic-sb-port"]) - - c.ovnLegacyClient.OvnICNbAddress = genHostAddress(cm.Data["ic-db-host"], cm.Data["ic-nb-port"]) - klog.Info("start to reestablish ovn-ic") - if err := c.establishInterConnection(cm.Data); err != nil { - klog.Errorf("failed to reestablish ovn-ic, %v", err) - return - } - - if err := c.RemoveOldChassisInSbDB(lastIcCm["az-name"]); err != nil { - klog.Errorf("failed to remove remote chassis: %v", err) - } - - icEnabled = "true" - lastIcCm = cm.Data - klog.Info("finish reestablishing ovn-ic") + if err := c.delLearnedRoute(); err != nil { + klog.Errorf("failed to remove learned static routes, %v", err) return } + c.ovnLegacyClient.OvnICSbAddress = genHostAddress(cm.Data["ic-db-host"], cm.Data["ic-sb-port"]) c.ovnLegacyClient.OvnICNbAddress = genHostAddress(cm.Data["ic-db-host"], cm.Data["ic-nb-port"]) - klog.Info("start to establish ovn-ic") + klog.Info("start to reestablish ovn-ic") if err := c.establishInterConnection(cm.Data); err != nil { - klog.Errorf("failed to establish ovn-ic, %v", err) + klog.Errorf("failed to reestablish ovn-ic, %v", err) return } + + if err := c.RemoveOldChassisInSbDB(lastIcCm["az-name"]); err != nil { + klog.Errorf("failed to remove remote chassis: %v", err) + } + icEnabled = "true" lastIcCm = cm.Data - klog.Info("finish establishing ovn-ic") + klog.Info("finish reestablishing ovn-ic") + return + } + + c.ovnLegacyClient.OvnICNbAddress = genHostAddress(cm.Data["ic-db-host"], cm.Data["ic-nb-port"]) + klog.Info("start to establish ovn-ic") + if err := c.establishInterConnection(cm.Data); err != nil { + klog.Errorf("failed to establish ovn-ic, %v", err) return } + icEnabled = "true" + lastIcCm = cm.Data + klog.Info("finish establishing ovn-ic") } func (c *Controller) removeInterConnection(azName string) error { @@ -147,8 +145,7 @@ func (c *Controller) removeInterConnection(azName string) error { } for _, cachedNode := range nodes { no := cachedNode.DeepCopy() - patchPayloadTemplate := - `[{ + patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/labels", "value": %s @@ -170,7 +167,7 @@ func (c *Controller) removeInterConnection(azName string) error { if azName != "" { lspName := fmt.Sprintf("ts-%s", azName) lrpName := fmt.Sprintf("%s-ts", azName) - if err := c.ovnNbClient.RemoveLogicalPatchPort(lspName, lrpName); err != nil { + if err := c.OVNNbClient.RemoveLogicalPatchPort(lspName, lrpName); err != nil { klog.Errorf("delete ovn-ic logical port %s and %s: %v", lspName, lrpName, err) return err } @@ -191,7 +188,7 @@ func (c *Controller) establishInterConnection(config map[string]string) error { } tsPort := fmt.Sprintf("ts-%s", config["az-name"]) - exist, err := c.ovnNbClient.LogicalSwitchPortExists(tsPort) + exist, err := c.OVNNbClient.LogicalSwitchPortExists(tsPort) if err != nil { klog.Errorf("failed to list logical switch ports, %v", err) return err @@ -202,7 +199,7 @@ func (c *Controller) establishInterConnection(config map[string]string) error { return nil } - if err := c.ovnNbClient.SetAzName(config["az-name"]); err != nil { + if err := c.OVNNbClient.SetAzName(config["az-name"]); err != nil { klog.Errorf("failed to set az name. %v", err) return err } @@ -217,8 +214,7 @@ func (c *Controller) establishInterConnection(config map[string]string) error { return err } node := cachedNode.DeepCopy() - patchPayloadTemplate := - `[{ + patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/labels", "value": %s @@ -242,7 +238,7 @@ func (c *Controller) establishInterConnection(config map[string]string) error { return err } klog.Infof("gw node %s chassis %s", gw, annoChassisName) - chassis, err := c.ovnSbClient.GetChassis(annoChassisName, false) + chassis, err := c.OVNSbClient.GetChassis(annoChassisName, false) if err != nil { klog.Errorf("failed to get node chassis %s, %v", annoChassisName, err) return err @@ -265,7 +261,7 @@ func (c *Controller) establishInterConnection(config map[string]string) error { } lrpName := fmt.Sprintf("%s-ts", config["az-name"]) - if err := c.ovnNbClient.CreateLogicalPatchPort(util.InterconnectionSwitch, c.config.ClusterRouter, tsPort, lrpName, lrpIP, util.GenerateMac(), chassises...); err != nil { + if err := c.OVNNbClient.CreateLogicalPatchPort(util.InterconnectionSwitch, c.config.ClusterRouter, tsPort, lrpName, lrpIP, util.GenerateMac(), chassises...); err != nil { klog.Errorf("failed to create ovn-ic lrp %v", err) return err } @@ -358,25 +354,25 @@ func (c *Controller) waitTsReady() error { klog.Info("wait for logical switch %s ready", util.InterconnectionSwitch) time.Sleep(5 * time.Second) - retry = retry - 1 + retry-- } return fmt.Errorf("timeout to wait for logical switch %s ready", util.InterconnectionSwitch) } func (c *Controller) delLearnedRoute() error { - lrList, err := c.ovnNbClient.ListLogicalRouter(false, nil) + lrList, err := c.OVNNbClient.ListLogicalRouter(false, nil) if err != nil { klog.Errorf("failed to list logical routers: %v", err) return err } for _, lr := range lrList { - routeList, err := c.ovnNbClient.ListLogicalRouterStaticRoutes(lr.Name, nil, nil, "", map[string]string{"ic-learned-route": ""}) + routeList, err := c.OVNNbClient.ListLogicalRouterStaticRoutes(lr.Name, nil, nil, "", map[string]string{"ic-learned-route": ""}) if err != nil { klog.Errorf("failed to list learned static routes on logical router %s: %v", lr.Name, err) return err } for _, r := range routeList { - if err = c.ovnNbClient.DeleteLogicalRouterStaticRoute(lr.Name, &r.RouteTable, r.Policy, r.IPPrefix, r.Nexthop); err != nil { + if err = c.OVNNbClient.DeleteLogicalRouterStaticRoute(lr.Name, &r.RouteTable, r.Policy, r.IPPrefix, r.Nexthop); err != nil { klog.Errorf("failed to delete learned static route %#v on logical router %s: %v", r, lr.Name, err) return err } @@ -387,7 +383,7 @@ func (c *Controller) delLearnedRoute() error { return nil } -func genHostAddress(host string, port string) (hostAddress string) { +func genHostAddress(host, port string) (hostAddress string) { hostList := strings.Split(host, ",") if len(hostList) == 1 { hostAddress = fmt.Sprintf("tcp:[%s]:%s", hostList[0], port) @@ -396,7 +392,7 @@ func genHostAddress(host string, port string) (hostAddress string) { i := 0 for i < len(hostList)-1 { builder.WriteString(fmt.Sprintf("tcp:[%s]:%s,", hostList[i], port)) - i += 1 + i++ } builder.WriteString(fmt.Sprintf("tcp:[%s]:%s", hostList[i], port)) hostAddress = builder.String() @@ -430,37 +426,36 @@ func (c *Controller) RemoveOldChassisInSbDB(azName string) error { c.ovnLegacyClient.DestroyGateways(gateways) c.ovnLegacyClient.DestroyRoutes(routes) - if err := c.ovnLegacyClient.DestroyChassis(azUUID); err != nil { - return err - } - return nil + return c.ovnLegacyClient.DestroyChassis(azUUID) } func stripPrefix(policyMatch string) (string, error) { matches := strings.Split(policyMatch, "==") - if strings.Trim(matches[0], " ") == util.MatchV4Dst { + + switch { + case strings.Trim(matches[0], " ") == util.MatchV4Dst: return strings.Trim(matches[1], " "), nil - } else if strings.Trim(matches[0], " ") == util.MatchV6Dst { + case strings.Trim(matches[0], " ") == util.MatchV6Dst: return strings.Trim(matches[1], " "), nil - } else { + default: return "", fmt.Errorf("policy %s is mismatched", policyMatch) } } func (c *Controller) syncOneRouteToPolicy(key, value string) { - lr, err := c.ovnNbClient.GetLogicalRouter(c.config.ClusterRouter, false) + lr, err := c.OVNNbClient.GetLogicalRouter(c.config.ClusterRouter, false) if err != nil { klog.Errorf("logical router does not exist %v at %v", err, time.Now()) return } - lrRouteList, err := c.ovnNbClient.ListLogicalRouterStaticRoutesByOption(lr.Name, util.MainRouteTable, key, value) + lrRouteList, err := c.OVNNbClient.ListLogicalRouterStaticRoutesByOption(lr.Name, util.MainRouteTable, key, value) if err != nil { klog.Errorf("failed to list lr ovn-ic route %v", err) return } if len(lrRouteList) == 0 { klog.V(5).Info("lr ovn-ic route does not exist") - err := c.ovnNbClient.DeleteLogicalRouterPolicies(lr.Name, util.OvnICPolicyPriority, map[string]string{key: value}) + err := c.OVNNbClient.DeleteLogicalRouterPolicies(lr.Name, util.OvnICPolicyPriority, map[string]string{key: value}) if err != nil { klog.Errorf("failed to delete ovn-ic lr policy: %v", err) return @@ -469,7 +464,7 @@ func (c *Controller) syncOneRouteToPolicy(key, value string) { } policyMap := map[string]string{} - lrPolicyList, err := c.ovnNbClient.ListLogicalRouterPolicies(lr.Name, util.OvnICPolicyPriority, map[string]string{key: value}) + lrPolicyList, err := c.OVNNbClient.ListLogicalRouterPolicies(lr.Name, util.OvnICPolicyPriority, map[string]string{key: value}) if err != nil { klog.Errorf("failed to list ovn-ic lr policy ", err) return @@ -489,28 +484,28 @@ func (c *Controller) syncOneRouteToPolicy(key, value string) { var matchFiled string if util.CheckProtocol(lrRoute.IPPrefix) == kubeovnv1.ProtocolIPv4 { matchFiled = util.MatchV4Dst + " == " + lrRoute.IPPrefix - if err := c.ovnNbClient.AddLogicalRouterPolicy(lr.Name, util.OvnICPolicyPriority, matchFiled, ovnnb.LogicalRouterPolicyActionAllow, nil, map[string]string{key: value, "vendor": util.CniTypeName}); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(lr.Name, util.OvnICPolicyPriority, matchFiled, ovnnb.LogicalRouterPolicyActionAllow, nil, map[string]string{key: value, "vendor": util.CniTypeName}); err != nil { klog.Errorf("adding router policy failed %v", err) } } if util.CheckProtocol(lrRoute.IPPrefix) == kubeovnv1.ProtocolIPv6 { matchFiled = util.MatchV6Dst + " == " + lrRoute.IPPrefix - if err := c.ovnNbClient.AddLogicalRouterPolicy(lr.Name, util.OvnICPolicyPriority, matchFiled, ovnnb.LogicalRouterPolicyActionAllow, nil, map[string]string{key: value, "vendor": util.CniTypeName}); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(lr.Name, util.OvnICPolicyPriority, matchFiled, ovnnb.LogicalRouterPolicyActionAllow, nil, map[string]string{key: value, "vendor": util.CniTypeName}); err != nil { klog.Errorf("adding router policy failed %v", err) } } } } for _, uuid := range policyMap { - if err := c.ovnNbClient.DeleteLogicalRouterPolicyByUUID(lr.Name, uuid); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPolicyByUUID(lr.Name, uuid); err != nil { klog.Errorf("deleting router policy failed %v", err) } } } func (c *Controller) listRemoteLogicalSwitchPortAddress() (*strset.Set, error) { - lsps, err := c.ovnNbClient.ListLogicalSwitchPorts(true, nil, func(lsp *ovnnb.LogicalSwitchPort) bool { + lsps, err := c.OVNNbClient.ListLogicalSwitchPorts(true, nil, func(lsp *ovnnb.LogicalSwitchPort) bool { return lsp.Type == "remote" }) if err != nil { diff --git a/pkg/controller/ovn_dnat.go b/pkg/controller/ovn_dnat.go index 52417b28595..329ea12a7dd 100644 --- a/pkg/controller/ovn_dnat.go +++ b/pkg/controller/ovn_dnat.go @@ -31,32 +31,31 @@ func (c *Controller) enqueueAddOvnDnatRule(obj interface{}) { c.addOvnDnatRuleQueue.Add(key) } -func (c *Controller) enqueueUpdateOvnDnatRule(old, new interface{}) { +func (c *Controller) enqueueUpdateOvnDnatRule(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - newDnat := new.(*kubeovnv1.OvnDnatRule) + newDnat := newObj.(*kubeovnv1.OvnDnatRule) if !newDnat.DeletionTimestamp.IsZero() { if len(newDnat.Finalizers) == 0 { // avoid delete twice return - } else { - klog.Infof("enqueue del ovn dnat %s", key) - c.delOvnDnatRuleQueue.Add(key) - return } + klog.Infof("enqueue del ovn dnat %s", key) + c.delOvnDnatRuleQueue.Add(key) + return } - oldDnat := old.(*kubeovnv1.OvnDnatRule) + oldDnat := oldObj.(*kubeovnv1.OvnDnatRule) if oldDnat.Spec.OvnEip != newDnat.Spec.OvnEip { c.resetOvnEipQueue.Add(oldDnat.Spec.OvnEip) } if oldDnat.Spec.OvnEip != newDnat.Spec.OvnEip || oldDnat.Spec.Protocol != newDnat.Spec.Protocol || - oldDnat.Spec.IpName != newDnat.Spec.IpName || + oldDnat.Spec.IPName != newDnat.Spec.IPName || oldDnat.Spec.InternalPort != newDnat.Spec.InternalPort || oldDnat.Spec.ExternalPort != newDnat.Spec.ExternalPort { klog.Infof("enqueue update dnat %s", key) @@ -112,7 +111,6 @@ func (c *Controller) processNextAddOvnDnatRuleWorkItem() bool { c.addOvnDnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -142,7 +140,6 @@ func (c *Controller) processNextUpdateOvnDnatRuleWorkItem() bool { c.updateOvnDnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -172,7 +169,6 @@ func (c *Controller) processNextDeleteOvnDnatRuleWorkItem() bool { c.delOvnDnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -218,24 +214,24 @@ func (c *Controller) handleAddOvnDnatRule(key string) error { } klog.Infof("handle add dnat %s", key) var internalV4Ip, mac, subnetName string - if cachedDnat.Spec.IpType == util.Vip { - internalVip, err := c.virtualIpsLister.Get(cachedDnat.Spec.IpName) + if cachedDnat.Spec.IPType == util.Vip { + internalVip, err := c.virtualIpsLister.Get(cachedDnat.Spec.IPName) if err != nil { - klog.Errorf("failed to get vip %s, %v", cachedDnat.Spec.IpName, err) + klog.Errorf("failed to get vip %s, %v", cachedDnat.Spec.IPName, err) return err } internalV4Ip = internalVip.Status.V4ip mac = internalVip.Status.Mac subnetName = internalVip.Spec.Subnet } else { - internalIp, err := c.ipsLister.Get(cachedDnat.Spec.IpName) + internalIP, err := c.ipsLister.Get(cachedDnat.Spec.IPName) if err != nil { - klog.Errorf("failed to get ip %s, %v", cachedDnat.Spec.IpName, err) + klog.Errorf("failed to get ip %s, %v", cachedDnat.Spec.IPName, err) return err } - internalV4Ip = internalIp.Spec.V4IPAddress - mac = internalIp.Spec.MacAddress - subnetName = internalIp.Spec.Subnet + internalV4Ip = internalIP.Spec.V4IPAddress + mac = internalIP.Spec.MacAddress + subnetName = internalIP.Spec.Subnet } eipName := cachedDnat.Spec.OvnEip @@ -362,24 +358,24 @@ func (c *Controller) handleUpdateOvnDnatRule(key string) error { klog.Infof("handle update dnat %s", key) var internalV4Ip, mac, subnetName string - if cachedDnat.Spec.IpType == util.Vip { - internalVip, err := c.virtualIpsLister.Get(cachedDnat.Spec.IpName) + if cachedDnat.Spec.IPType == util.Vip { + internalVip, err := c.virtualIpsLister.Get(cachedDnat.Spec.IPName) if err != nil { - klog.Errorf("failed to get vip %s, %v", cachedDnat.Spec.IpName, err) + klog.Errorf("failed to get vip %s, %v", cachedDnat.Spec.IPName, err) return err } internalV4Ip = internalVip.Status.V4ip mac = internalVip.Status.Mac subnetName = internalVip.Spec.Subnet } else { - internalIp, err := c.ipsLister.Get(cachedDnat.Spec.IpName) + internalIP, err := c.ipsLister.Get(cachedDnat.Spec.IPName) if err != nil { - klog.Errorf("failed to get ip %s, %v", cachedDnat.Spec.IpName, err) + klog.Errorf("failed to get ip %s, %v", cachedDnat.Spec.IPName, err) return err } - internalV4Ip = internalIp.Spec.V4IPAddress - mac = internalIp.Spec.MacAddress - subnetName = internalIp.Spec.Subnet + internalV4Ip = internalIP.Spec.V4IPAddress + mac = internalIP.Spec.MacAddress + subnetName = internalIP.Spec.Subnet } eipName := cachedDnat.Spec.OvnEip @@ -496,7 +492,7 @@ func (c *Controller) patchOvnDnatAnnotations(key, eipName string) error { return nil } -func (c *Controller) patchOvnDnatStatus(key, vpcName, v4Eip, podIp, podMac string, ready bool) error { +func (c *Controller) patchOvnDnatStatus(key, vpcName, v4Eip, podIP, podMac string, ready bool) error { oriDnat, err := c.ovnDnatRulesLister.Get(key) if err != nil { if k8serrors.IsNotFound(err) { @@ -538,11 +534,11 @@ func (c *Controller) patchOvnDnatStatus(key, vpcName, v4Eip, podIp, podMac strin if (v4Eip != "" && dnat.Status.V4Eip != v4Eip) || (vpcName != "" && dnat.Status.Vpc != vpcName) || - (podIp != "" && dnat.Status.V4Ip != podIp) || + (podIP != "" && dnat.Status.V4Ip != podIP) || (podMac != "" && dnat.Status.MacAddress != podMac) { dnat.Status.Vpc = vpcName dnat.Status.V4Eip = v4Eip - dnat.Status.V4Ip = podIp + dnat.Status.V4Ip = podIP dnat.Status.MacAddress = podMac changed = true } @@ -552,8 +548,8 @@ func (c *Controller) patchOvnDnatStatus(key, vpcName, v4Eip, podIp, podMac strin changed = true } - if ready && dnat.Spec.IpName != "" && dnat.Spec.IpName != dnat.Status.IpName { - dnat.Status.IpName = dnat.Spec.IpName + if ready && dnat.Spec.IPName != "" && dnat.Spec.IPName != dnat.Status.IPName { + dnat.Status.IPName = dnat.Spec.IPName changed = true } @@ -582,36 +578,36 @@ func (c *Controller) patchOvnDnatStatus(key, vpcName, v4Eip, podIp, podMac strin return nil } -func (c *Controller) AddDnatRule(vpcName, dnatName, externalIp, internalIp, externalPort, internalPort, protocol string) error { - externalEndpoint := net.JoinHostPort(externalIp, externalPort) - internalEndpoint := net.JoinHostPort(internalIp, internalPort) +func (c *Controller) AddDnatRule(vpcName, dnatName, externalIP, internalIP, externalPort, internalPort, protocol string) error { + externalEndpoint := net.JoinHostPort(externalIP, externalPort) + internalEndpoint := net.JoinHostPort(internalIP, internalPort) - if err := c.ovnNbClient.CreateLoadBalancer(dnatName, protocol, ""); err != nil { + if err := c.OVNNbClient.CreateLoadBalancer(dnatName, protocol, ""); err != nil { klog.Errorf("create loadBalancer %s: %v", dnatName, err) return err } - if err := c.ovnNbClient.LoadBalancerAddVip(dnatName, externalEndpoint, internalEndpoint); err != nil { + if err := c.OVNNbClient.LoadBalancerAddVip(dnatName, externalEndpoint, internalEndpoint); err != nil { klog.Errorf("add vip %s with backends %s to LB %s: %v", externalEndpoint, internalEndpoint, dnatName, err) return err } - if err := c.ovnNbClient.LogicalRouterUpdateLoadBalancers(vpcName, ovsdb.MutateOperationInsert, dnatName); err != nil { + if err := c.OVNNbClient.LogicalRouterUpdateLoadBalancers(vpcName, ovsdb.MutateOperationInsert, dnatName); err != nil { klog.Errorf("add lb %s to vpc %s: %v", dnatName, vpcName, err) return err } return nil } -func (c *Controller) DelDnatRule(vpcName, dnatName, externalIp, externalPort string) error { - externalEndpoint := net.JoinHostPort(externalIp, externalPort) +func (c *Controller) DelDnatRule(vpcName, dnatName, externalIP, externalPort string) error { + externalEndpoint := net.JoinHostPort(externalIP, externalPort) - if err := c.ovnNbClient.LoadBalancerDeleteVip(dnatName, externalEndpoint); err != nil { + if err := c.OVNNbClient.LoadBalancerDeleteVip(dnatName, externalEndpoint); err != nil { klog.Errorf("delete loadBalancer vips %s: %v", externalEndpoint, err) return err } - if err := c.ovnNbClient.LogicalRouterUpdateLoadBalancers(vpcName, ovsdb.MutateOperationDelete, dnatName); err != nil { + if err := c.OVNNbClient.LogicalRouterUpdateLoadBalancers(vpcName, ovsdb.MutateOperationDelete, dnatName); err != nil { klog.Errorf("failed to remove lb %s from vpc %s: %v", dnatName, vpcName, err) return err } diff --git a/pkg/controller/ovn_eip.go b/pkg/controller/ovn_eip.go index 89444a86ccf..62026af63cf 100644 --- a/pkg/controller/ovn_eip.go +++ b/pkg/controller/ovn_eip.go @@ -22,7 +22,6 @@ import ( ) func (c *Controller) enqueueAddOvnEip(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -33,25 +32,24 @@ func (c *Controller) enqueueAddOvnEip(obj interface{}) { c.addOvnEipQueue.Add(key) } -func (c *Controller) enqueueUpdateOvnEip(old, new interface{}) { +func (c *Controller) enqueueUpdateOvnEip(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - newEip := new.(*kubeovnv1.OvnEip) + newEip := newObj.(*kubeovnv1.OvnEip) if newEip.DeletionTimestamp != nil { if len(newEip.Finalizers) == 0 { // avoid delete eip twice return - } else { - klog.Infof("enqueue del ovn eip %s", key) - c.delOvnEipQueue.Add(key) - return } + klog.Infof("enqueue del ovn eip %s", key) + c.delOvnEipQueue.Add(key) + return } - oldEip := old.(*kubeovnv1.OvnEip) + oldEip := oldObj.(*kubeovnv1.OvnEip) if oldEip.Spec.V4Ip != "" && oldEip.Spec.V4Ip != newEip.Spec.V4Ip || oldEip.Spec.MacAddress != "" && oldEip.Spec.MacAddress != newEip.Spec.MacAddress { klog.Infof("not support change ip or mac for eip %s", key) @@ -201,7 +199,6 @@ func (c *Controller) processNextDeleteOvnEipWorkItem() bool { c.delOvnEipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -235,10 +232,10 @@ func (c *Controller) handleAddOvnEip(key string) error { } portName := cachedEip.Name if cachedEip.Spec.V4Ip != "" { - v4ip, v6ip, mac, err = c.acquireStaticIpAddress(subnet.Name, cachedEip.Name, portName, cachedEip.Spec.V4Ip) + v4ip, v6ip, mac, err = c.acquireStaticIPAddress(subnet.Name, cachedEip.Name, portName, cachedEip.Spec.V4Ip) } else { // random allocate - v4ip, v6ip, mac, err = c.acquireIpAddress(subnet.Name, cachedEip.Name, portName) + v4ip, v6ip, mac, err = c.acquireIPAddress(subnet.Name, cachedEip.Name, portName) } if err != nil { klog.Errorf("failed to acquire ip address, %v", err) @@ -246,8 +243,8 @@ func (c *Controller) handleAddOvnEip(key string) error { } if cachedEip.Spec.Type == util.Lsp { - mergedIp := util.GetStringIP(v4ip, v6ip) - if err := c.ovnNbClient.CreateBareLogicalSwitchPort(subnet.Name, portName, mergedIp, mac); err != nil { + mergedIP := util.GetStringIP(v4ip, v6ip) + if err := c.OVNNbClient.CreateBareLogicalSwitchPort(subnet.Name, portName, mergedIP, mac); err != nil { klog.Error("failed to create lsp for ovn eip %s, %v", key, err) return err } @@ -267,7 +264,7 @@ func (c *Controller) handleAddOvnEip(key string) error { return err } } - if err = c.subnetCountIp(subnet); err != nil { + if err = c.subnetCountIP(subnet); err != nil { klog.Errorf("failed to count ovn eip '%s' in subnet, %v", cachedEip.Name, err) return err } @@ -294,7 +291,7 @@ func (c *Controller) handleUpdateOvnEip(key string) error { klog.Errorf("failed to get external subnet, %v", err) return err } - if err = c.subnetCountIp(subnet); err != nil { + if err = c.subnetCountIP(subnet); err != nil { klog.Errorf("failed to count ovn eip '%s' in subnet, %v", cachedEip.Name, err) return err } @@ -346,14 +343,14 @@ func (c *Controller) handleDelOvnEip(key string) error { } if eip.Spec.Type == util.Lsp { - if err := c.ovnNbClient.DeleteLogicalSwitchPort(eip.Name); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(eip.Name); err != nil { klog.Errorf("failed to delete lsp %s, %v", eip.Name, err) return err } } if eip.Spec.Type == util.Lrp { - if err := c.ovnNbClient.DeleteLogicalRouterPort(eip.Name); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPort(eip.Name); err != nil { klog.Errorf("failed to delete lrp %s, %v", eip.Name, err) return err } diff --git a/pkg/controller/ovn_fip.go b/pkg/controller/ovn_fip.go index ecf1dbebef2..b35a71d2985 100644 --- a/pkg/controller/ovn_fip.go +++ b/pkg/controller/ovn_fip.go @@ -22,7 +22,6 @@ import ( ) func (c *Controller) enqueueAddOvnFip(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -33,32 +32,31 @@ func (c *Controller) enqueueAddOvnFip(obj interface{}) { c.addOvnFipQueue.Add(key) } -func (c *Controller) enqueueUpdateOvnFip(old, new interface{}) { +func (c *Controller) enqueueUpdateOvnFip(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - newFip := new.(*kubeovnv1.OvnFip) + newFip := newObj.(*kubeovnv1.OvnFip) if !newFip.DeletionTimestamp.IsZero() { if len(newFip.Finalizers) == 0 { // avoid delete twice return - } else { - klog.Infof("enqueue del ovn fip %s", key) - c.delOvnFipQueue.Add(key) - return } + klog.Infof("enqueue del ovn fip %s", key) + c.delOvnFipQueue.Add(key) + return } - oldFip := old.(*kubeovnv1.OvnFip) + oldFip := oldObj.(*kubeovnv1.OvnFip) if oldFip.Spec.OvnEip != newFip.Spec.OvnEip { // enqueue to reset eip to be clean klog.Infof("enqueue reset old ovn eip %s", oldFip.Spec.OvnEip) c.resetOvnEipQueue.Add(oldFip.Spec.OvnEip) } - if !reflect.DeepEqual(oldFip.Spec.IpName, newFip.Spec.IpName) || - !reflect.DeepEqual(oldFip.Spec.IpType, newFip.Spec.IpType) { + if !reflect.DeepEqual(oldFip.Spec.IPName, newFip.Spec.IPName) || + !reflect.DeepEqual(oldFip.Spec.IPType, newFip.Spec.IPType) { klog.Infof("enqueue update fip %s", key) c.updateOvnFipQueue.Add(key) return @@ -141,7 +139,6 @@ func (c *Controller) processNextUpdateOvnFipWorkItem() bool { c.updateOvnFipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -210,24 +207,24 @@ func (c *Controller) handleAddOvnFip(key string) error { } klog.Infof("handle add fip %s", key) var internalV4Ip, mac, subnetName string - if cachedFip.Spec.IpType == util.Vip { - internalVip, err := c.virtualIpsLister.Get(cachedFip.Spec.IpName) + if cachedFip.Spec.IPType == util.Vip { + internalVip, err := c.virtualIpsLister.Get(cachedFip.Spec.IPName) if err != nil { - klog.Errorf("failed to get vip %s, %v", cachedFip.Spec.IpName, err) + klog.Errorf("failed to get vip %s, %v", cachedFip.Spec.IPName, err) return err } internalV4Ip = internalVip.Status.V4ip mac = internalVip.Status.Mac subnetName = internalVip.Spec.Subnet } else { - internalIp, err := c.ipsLister.Get(cachedFip.Spec.IpName) + internalIP, err := c.ipsLister.Get(cachedFip.Spec.IPName) if err != nil { - klog.Errorf("failed to get ip %s, %v", cachedFip.Spec.IpName, err) + klog.Errorf("failed to get ip %s, %v", cachedFip.Spec.IPName, err) return err } - internalV4Ip = internalIp.Spec.V4IPAddress - mac = internalIp.Spec.MacAddress - subnetName = internalIp.Spec.Subnet + internalV4Ip = internalIP.Spec.V4IPAddress + mac = internalIP.Spec.MacAddress + subnetName = internalIP.Spec.Subnet } // get eip @@ -287,8 +284,8 @@ func (c *Controller) handleAddOvnFip(key string) error { return err } // ovn add fip - if err = c.ovnNbClient.AddNat(vpcName, ovnnb.NATTypeDNATAndSNAT, cachedEip.Status.V4Ip, - internalV4Ip, mac, cachedFip.Spec.IpName, + if err = c.OVNNbClient.AddNat(vpcName, ovnnb.NATTypeDNATAndSNAT, cachedEip.Status.V4Ip, + internalV4Ip, mac, cachedFip.Spec.IPName, map[string]string{"staleless": strconv.FormatBool(c.ExternalGatewayType == kubeovnv1.GWDistributedType)}); err != nil { klog.Errorf("failed to create v4 fip, %v", err) return err @@ -330,24 +327,24 @@ func (c *Controller) handleUpdateOvnFip(key string) error { } klog.Infof("handle update fip %s", key) var internalV4Ip, mac, subnetName string - if cachedFip.Spec.IpType == util.Vip { - internalVip, err := c.virtualIpsLister.Get(cachedFip.Spec.IpName) + if cachedFip.Spec.IPType == util.Vip { + internalVip, err := c.virtualIpsLister.Get(cachedFip.Spec.IPName) if err != nil { - klog.Errorf("failed to get vip %s, %v", cachedFip.Spec.IpName, err) + klog.Errorf("failed to get vip %s, %v", cachedFip.Spec.IPName, err) return err } internalV4Ip = internalVip.Status.V4ip mac = internalVip.Status.Mac subnetName = internalVip.Spec.Subnet } else { - internalIp, err := c.ipsLister.Get(cachedFip.Spec.IpName) + internalIP, err := c.ipsLister.Get(cachedFip.Spec.IPName) if err != nil { - klog.Errorf("failed to get ip %s, %v", cachedFip.Spec.IpName, err) + klog.Errorf("failed to get ip %s, %v", cachedFip.Spec.IPName, err) return err } - internalV4Ip = internalIp.Spec.V4IPAddress - mac = internalIp.Spec.MacAddress - subnetName = internalIp.Spec.Subnet + internalV4Ip = internalIP.Spec.V4IPAddress + mac = internalIP.Spec.MacAddress + subnetName = internalIP.Spec.Subnet } // get eip eipName := cachedFip.Spec.OvnEip @@ -383,8 +380,8 @@ func (c *Controller) handleUpdateOvnFip(key string) error { return err } vpcName := subnet.Spec.Vpc - if err = c.ovnNbClient.AddNat(vpcName, ovnnb.NATTypeDNATAndSNAT, cachedEip.Status.V4Ip, - internalV4Ip, mac, cachedFip.Spec.IpName, + if err = c.OVNNbClient.AddNat(vpcName, ovnnb.NATTypeDNATAndSNAT, cachedEip.Status.V4Ip, + internalV4Ip, mac, cachedFip.Spec.IPName, map[string]string{"staleless": strconv.FormatBool(c.ExternalGatewayType == kubeovnv1.GWDistributedType)}); err != nil { klog.Errorf("failed to create v4 fip, %v", err) return err @@ -393,13 +390,13 @@ func (c *Controller) handleUpdateOvnFip(key string) error { // fip change eip if c.ovnFipChangeEip(fip, cachedEip) { klog.Infof("fip change ip, old ip '%s', new ip %s", fip.Status.V4Ip, cachedEip.Status.V4Ip) - if err = c.ovnNbClient.DeleteNat(vpcName, ovnnb.NATTypeDNATAndSNAT, fip.Status.V4Ip, internalV4Ip); err != nil { + if err = c.OVNNbClient.DeleteNat(vpcName, ovnnb.NATTypeDNATAndSNAT, fip.Status.V4Ip, internalV4Ip); err != nil { klog.Errorf("failed to create fip, %v", err) return err } // ovn add fip - if err = c.ovnNbClient.AddNat(vpcName, ovnnb.NATTypeDNATAndSNAT, cachedEip.Status.V4Ip, - internalV4Ip, mac, cachedFip.Spec.IpName, + if err = c.OVNNbClient.AddNat(vpcName, ovnnb.NATTypeDNATAndSNAT, cachedEip.Status.V4Ip, + internalV4Ip, mac, cachedFip.Spec.IPName, map[string]string{"staleless": strconv.FormatBool(c.ExternalGatewayType == kubeovnv1.GWDistributedType)}); err != nil { klog.Errorf("failed to create fip, %v", err) return err @@ -434,7 +431,7 @@ func (c *Controller) handleDelOvnFip(key string) error { } // ovn delete fip nat if cachedFip.Status.Vpc != "" && cachedFip.Status.V4Eip != "" && cachedFip.Status.V4Ip != "" { - if err = c.ovnNbClient.DeleteNat(cachedFip.Status.Vpc, ovnnb.NATTypeDNATAndSNAT, cachedFip.Status.V4Eip, cachedFip.Status.V4Ip); err != nil { + if err = c.OVNNbClient.DeleteNat(cachedFip.Status.Vpc, ovnnb.NATTypeDNATAndSNAT, cachedFip.Status.V4Eip, cachedFip.Status.V4Ip); err != nil { klog.Errorf("failed to delete fip %s, %v", key, err) return err } @@ -487,7 +484,7 @@ func (c *Controller) patchOvnFipAnnotations(key, eipName string) error { return nil } -func (c *Controller) patchOvnFipStatus(key, vpcName, v4Eip, podIp, podMac string, ready bool) error { +func (c *Controller) patchOvnFipStatus(key, vpcName, v4Eip, podIP, podMac string, ready bool) error { oriFip, err := c.ovnFipsLister.Get(key) if err != nil { if k8serrors.IsNotFound(err) { @@ -527,11 +524,11 @@ func (c *Controller) patchOvnFipStatus(key, vpcName, v4Eip, podIp, podMac string } if (v4Eip != "" && fip.Status.V4Eip != v4Eip) || (vpcName != "" && fip.Status.Vpc != vpcName) || - (podIp != "" && fip.Status.V4Ip != podIp) || + (podIP != "" && fip.Status.V4Ip != podIP) || (podMac != "" && fip.Status.MacAddress != podMac) { fip.Status.Vpc = vpcName fip.Status.V4Eip = v4Eip - fip.Status.V4Ip = podIp + fip.Status.V4Ip = podIP fip.Status.MacAddress = podMac changed = true } diff --git a/pkg/controller/ovn_snat.go b/pkg/controller/ovn_snat.go index d43234d239b..86a1ca683b8 100644 --- a/pkg/controller/ovn_snat.go +++ b/pkg/controller/ovn_snat.go @@ -19,7 +19,6 @@ import ( ) func (c *Controller) enqueueAddOvnSnatRule(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -29,32 +28,31 @@ func (c *Controller) enqueueAddOvnSnatRule(obj interface{}) { c.addOvnSnatRuleQueue.Add(key) } -func (c *Controller) enqueueUpdateOvnSnatRule(old, new interface{}) { +func (c *Controller) enqueueUpdateOvnSnatRule(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - newSnat := new.(*kubeovnv1.OvnSnatRule) + newSnat := newObj.(*kubeovnv1.OvnSnatRule) if !newSnat.DeletionTimestamp.IsZero() { if len(newSnat.Finalizers) == 0 { // avoid delete twice return - } else { - klog.Infof("enqueue del ovn snat %s", key) - c.delOvnSnatRuleQueue.Add(key) - return } + klog.Infof("enqueue del ovn snat %s", key) + c.delOvnSnatRuleQueue.Add(key) + return } - oldSnat := old.(*kubeovnv1.OvnSnatRule) + oldSnat := oldObj.(*kubeovnv1.OvnSnatRule) if oldSnat.Spec.OvnEip != newSnat.Spec.OvnEip { // enqueue to reset eip to be clean c.resetOvnEipQueue.Add(oldSnat.Spec.OvnEip) } if oldSnat.Spec.OvnEip != newSnat.Spec.OvnEip || oldSnat.Spec.VpcSubnet != newSnat.Spec.VpcSubnet || - oldSnat.Spec.IpName != newSnat.Spec.IpName { + oldSnat.Spec.IPName != newSnat.Spec.IPName { klog.Infof("enqueue update snat %s", key) c.updateOvnSnatRuleQueue.Add(key) return @@ -109,7 +107,6 @@ func (c *Controller) processNextAddOvnSnatRuleWorkItem() bool { c.addOvnSnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -139,7 +136,6 @@ func (c *Controller) processNextUpdateOvnSnatRuleWorkItem() bool { c.updateOvnSnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -169,7 +165,6 @@ func (c *Controller) processNextDeleteOvnSnatRuleWorkItem() bool { c.delOvnSnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -220,19 +215,19 @@ func (c *Controller) handleAddOvnSnatRule(key string) error { vpcName = subnet.Spec.Vpc v4IpCidr = subnet.Spec.CIDRBlock } - if cachedSnat.Spec.IpName != "" { - vpcPodIp, err := c.ipsLister.Get(cachedSnat.Spec.IpName) + if cachedSnat.Spec.IPName != "" { + vpcPodIP, err := c.ipsLister.Get(cachedSnat.Spec.IPName) if err != nil { - klog.Errorf("failed to get pod ip %s, %v", cachedSnat.Spec.IpName, err) + klog.Errorf("failed to get pod ip %s, %v", cachedSnat.Spec.IPName, err) return err } - subnet, err := c.subnetsLister.Get(vpcPodIp.Spec.Subnet) + subnet, err := c.subnetsLister.Get(vpcPodIP.Spec.Subnet) if err != nil { - klog.Errorf("failed to get vpc subnet %s, %v", vpcPodIp.Spec.Subnet, err) + klog.Errorf("failed to get vpc subnet %s, %v", vpcPodIP.Spec.Subnet, err) return err } vpcName = subnet.Spec.Vpc - v4IpCidr = vpcPodIp.Spec.V4IPAddress + v4IpCidr = vpcPodIP.Spec.V4IPAddress } if v4IpCidr == "" { @@ -252,7 +247,7 @@ func (c *Controller) handleAddOvnSnatRule(key string) error { return err } // ovn add snat - if err = c.ovnNbClient.AddNat(vpcName, ovnnb.NATTypeSNAT, cachedEip.Spec.V4Ip, v4IpCidr, "", "", nil); err != nil { + if err = c.OVNNbClient.AddNat(vpcName, ovnnb.NATTypeSNAT, cachedEip.Spec.V4Ip, v4IpCidr, "", "", nil); err != nil { klog.Errorf("failed to create snat, %v", err) return err } @@ -305,7 +300,7 @@ func (c *Controller) handleUpdateOvnSnatRule(key string) error { klog.V(3).Infof("ovn delete snat %s", key) // ovn delete snat if cachedSnat.Status.Vpc != "" && cachedSnat.Status.V4Eip != "" && cachedSnat.Status.V4IpCidr != "" { - if err = c.ovnNbClient.DeleteNat(cachedSnat.Status.Vpc, ovnnb.NATTypeSNAT, cachedSnat.Status.V4Eip, cachedSnat.Status.V4IpCidr); err != nil { + if err = c.OVNNbClient.DeleteNat(cachedSnat.Status.Vpc, ovnnb.NATTypeSNAT, cachedSnat.Status.V4Eip, cachedSnat.Status.V4IpCidr); err != nil { klog.Errorf("failed to delete snat, %v", err) return err } @@ -332,19 +327,19 @@ func (c *Controller) handleUpdateOvnSnatRule(key string) error { vpcName = subnet.Spec.Vpc v4IpCidr = subnet.Spec.CIDRBlock } - if cachedSnat.Spec.IpName != "" { - vpcPodIp, err := c.ipsLister.Get(cachedSnat.Spec.IpName) + if cachedSnat.Spec.IPName != "" { + vpcPodIP, err := c.ipsLister.Get(cachedSnat.Spec.IPName) if err != nil { - klog.Errorf("failed to get pod ip %s, %v", cachedSnat.Spec.IpName, err) + klog.Errorf("failed to get pod ip %s, %v", cachedSnat.Spec.IPName, err) return err } - subnet, err := c.subnetsLister.Get(vpcPodIp.Spec.Subnet) + subnet, err := c.subnetsLister.Get(vpcPodIP.Spec.Subnet) if err != nil { - klog.Errorf("failed to get vpc subnet %s, %v", vpcPodIp.Spec.Subnet, err) + klog.Errorf("failed to get vpc subnet %s, %v", vpcPodIP.Spec.Subnet, err) return err } vpcName = subnet.Spec.Vpc - v4IpCidr = vpcPodIp.Spec.V4IPAddress + v4IpCidr = vpcPodIP.Spec.V4IPAddress } if v4IpCidr == "" { @@ -355,12 +350,12 @@ func (c *Controller) handleUpdateOvnSnatRule(key string) error { // snat change eip if c.ovnSnatChangeEip(cachedSnat, cachedEip) { klog.Infof("snat change ip, old ip %s, new ip %s", cachedEip.Status.V4Ip, cachedEip.Spec.V4Ip) - if err = c.ovnNbClient.DeleteNat(vpcName, ovnnb.NATTypeSNAT, cachedEip.Status.V4Ip, v4IpCidr); err != nil { + if err = c.OVNNbClient.DeleteNat(vpcName, ovnnb.NATTypeSNAT, cachedEip.Status.V4Ip, v4IpCidr); err != nil { klog.Errorf("failed to delte snat, %v", err) return err } // ovn add snat with new eip - if err = c.ovnNbClient.AddNat(vpcName, ovnnb.NATTypeSNAT, cachedEip.Spec.V4Ip, v4IpCidr, "", "", nil); err != nil { + if err = c.OVNNbClient.AddNat(vpcName, ovnnb.NATTypeSNAT, cachedEip.Spec.V4Ip, v4IpCidr, "", "", nil); err != nil { klog.Errorf("failed to create snat, %v", err) return err } @@ -393,7 +388,7 @@ func (c *Controller) handleDelOvnSnatRule(key string) error { } // ovn delete snat if cachedSnat.Status.Vpc != "" && cachedSnat.Status.V4Eip != "" && cachedSnat.Status.V4IpCidr != "" { - if err = c.ovnNbClient.DeleteNat(cachedSnat.Status.Vpc, ovnnb.NATTypeSNAT, + if err = c.OVNNbClient.DeleteNat(cachedSnat.Status.Vpc, ovnnb.NATTypeSNAT, cachedSnat.Status.V4Eip, cachedSnat.Status.V4IpCidr); err != nil { klog.Errorf("failed to delete snat %s, %v", key, err) return err diff --git a/pkg/controller/pod.go b/pkg/controller/pod.go index 8b108419f4c..1c6b5e58b9f 100644 --- a/pkg/controller/pod.go +++ b/pkg/controller/pod.go @@ -66,11 +66,11 @@ func (n *NamedPort) AddNamedPortByPod(pod *v1.Pod) { if _, ok := n.namedPortMap[ns]; ok { if _, ok := n.namedPortMap[ns][port.Name]; ok { - if n.namedPortMap[ns][port.Name].PortId == port.ContainerPort { + if n.namedPortMap[ns][port.Name].PortID == port.ContainerPort { n.namedPortMap[ns][port.Name].Pods.Add(podName) } else { klog.Warningf("named port %s has already be defined with portID %d", - port.Name, n.namedPortMap[ns][port.Name].PortId) + port.Name, n.namedPortMap[ns][port.Name].PortID) } continue } @@ -78,7 +78,7 @@ func (n *NamedPort) AddNamedPortByPod(pod *v1.Pod) { n.namedPortMap[ns] = make(map[string]*util.NamedPortInfo) } n.namedPortMap[ns][port.Name] = &util.NamedPortInfo{ - PortId: port.ContainerPort, + PortID: port.ContainerPort, Pods: strset.New(podName), } } @@ -170,7 +170,6 @@ func isPodStatusPhaseAlive(p *v1.Pod) bool { } func (c *Controller) enqueueAddPod(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -195,14 +194,14 @@ func (c *Controller) enqueueAddPod(obj interface{}) { if !isPodAlive(p) { isStateful, statefulSetName := isStatefulSetPod(p) - isVmPod, vmName := isVmPod(p) - if isStateful || (isVmPod && c.config.EnableKeepVmIP) { + isVMPod, vmName := isVMPod(p) + if isStateful || (isVMPod && c.config.EnableKeepVMIP) { if isStateful && isStatefulSetPodToDel(c.config.KubeClient, p, statefulSetName) { klog.V(3).Infof("enqueue delete pod %s", key) c.deletingPodObjMap.Store(key, p) c.deletePodQueue.Add(key) } - if isVmPod && c.isVmPodToDel(p, vmName) { + if isVMPod && c.isVMPodToDel(p, vmName) { klog.V(3).Infof("enqueue delete pod %s", key) c.deletingPodObjMap.Store(key, p) c.deletePodQueue.Add(key) @@ -298,8 +297,8 @@ func (c *Controller) enqueueUpdatePod(oldObj, newObj interface{}) { } isStateful, statefulSetName := isStatefulSetPod(newPod) - isVmPod, vmName := isVmPod(newPod) - if !isPodStatusPhaseAlive(newPod) && !isStateful && !isVmPod { + isVMPod, vmName := isVMPod(newPod) + if !isPodStatusPhaseAlive(newPod) && !isStateful && !isVMPod { klog.V(3).Infof("enqueue delete pod %s", key) c.deletingPodObjMap.Store(key, newPod) c.deletePodQueue.Add(key) @@ -316,7 +315,7 @@ func (c *Controller) enqueueUpdatePod(oldObj, newObj interface{}) { } } - if newPod.DeletionTimestamp != nil && !isStateful && !isVmPod { + if newPod.DeletionTimestamp != nil && !isStateful && !isVMPod { go func() { // In case node get lost and pod can not be deleted, // the ip address will not be recycled @@ -336,7 +335,7 @@ func (c *Controller) enqueueUpdatePod(oldObj, newObj interface{}) { }() return } - if isVmPod && c.isVmPodToDel(newPod, vmName) { + if isVMPod && c.isVMPodToDel(newPod, vmName) { go func() { klog.V(3).Infof("enqueue delete pod %s after %v", key, delay) c.deletingPodObjMap.Store(key, newPod) @@ -402,7 +401,6 @@ func (c *Controller) processNextAddOrUpdatePodWorkItem() bool { c.addOrUpdatePodQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -445,7 +443,6 @@ func (c *Controller) processNextDeletePodWorkItem() bool { }() return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -476,7 +473,6 @@ func (c *Controller) processNextUpdatePodSecurityWorkItem() bool { c.updatePodSecurityQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -525,7 +521,7 @@ func (c *Controller) changeVMSubnet(vmName, namespace, providerName, subnetName if ipCr != nil { if ipCr.Spec.Subnet != subnetName { key := fmt.Sprintf("%s/%s", pod.Namespace, vmName) - ports, err := c.ovnNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": key}) + ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": key}) if err != nil { klog.Errorf("failed to list lsps of pod '%s', %v", pod.Name, err) return err @@ -533,7 +529,7 @@ func (c *Controller) changeVMSubnet(vmName, namespace, providerName, subnetName for _, port := range ports { // when lsp is deleted, the port of pod is deleted from any port-group automatically. klog.Infof("gc logical switch port %s", port.Name) - if err := c.ovnNbClient.DeleteLogicalSwitchPort(port.Name); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(port.Name); err != nil { klog.Errorf("failed to delete lsp %s, %v", port.Name, err) return err } @@ -609,7 +605,7 @@ func (c *Controller) handleAddOrUpdatePod(key string) (err error) { func (c *Controller) reconcileAllocateSubnets(cachedPod, pod *v1.Pod, needAllocatePodNets []*kubeovnNet) (*v1.Pod, error) { namespace := pod.Namespace name := pod.Name - isVmPod, vmName := isVmPod(pod) + isVMPod, vmName := isVMPod(pod) klog.Infof("sync pod %s/%s allocated", namespace, name) @@ -623,7 +619,7 @@ func (c *Controller) reconcileAllocateSubnets(cachedPod, pod *v1.Pod, needAlloca return nil, err } ipStr := util.GetStringIP(v4IP, v6IP) - pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)] = ipStr + pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] = ipStr if mac == "" { delete(pod.Annotations, fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)) } else { @@ -641,8 +637,8 @@ func (c *Controller) reconcileAllocateSubnets(cachedPod, pod *v1.Pod, needAlloca delete(pod.Annotations, fmt.Sprintf(util.PodNicAnnotationTemplate, podNet.ProviderName)) } pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, podNet.ProviderName)] = "true" - if isVmPod && c.config.EnableKeepVmIP { - pod.Annotations[fmt.Sprintf(util.VmTemplate, podNet.ProviderName)] = vmName + if isVMPod && c.config.EnableKeepVMIP { + pod.Annotations[fmt.Sprintf(util.VMTemplate, podNet.ProviderName)] = vmName if err := c.changeVMSubnet(vmName, namespace, podNet.ProviderName, subnet.Name, pod); err != nil { klog.Errorf("change subnet of pod %s/%s to %s failed: %v", namespace, name, subnet.Name, err) return nil, err @@ -675,7 +671,7 @@ func (c *Controller) reconcileAllocateSubnets(cachedPod, pod *v1.Pod, needAlloca c.recorder.Eventf(pod, v1.EventTypeWarning, "GetVlanInfoFailed", err.Error()) return nil, err } - pod.Annotations[fmt.Sprintf(util.VlanIdAnnotationTemplate, podNet.ProviderName)] = strconv.Itoa(vlan.Spec.ID) + pod.Annotations[fmt.Sprintf(util.VlanIDAnnotationTemplate, podNet.ProviderName)] = strconv.Itoa(vlan.Spec.ID) pod.Annotations[fmt.Sprintf(util.ProviderNetworkTemplate, podNet.ProviderName)] = vlan.Spec.Provider } @@ -700,7 +696,7 @@ func (c *Controller) reconcileAllocateSubnets(cachedPod, pod *v1.Pod, needAlloca DHCPv6OptionsUUID: subnet.Status.DHCPv6OptionsUUID, } - if err := c.ovnNbClient.CreateLogicalSwitchPort(subnet.Name, portName, ipStr, mac, podName, pod.Namespace, portSecurity, securityGroupAnnotation, vips, podNet.Subnet.Spec.EnableDHCP, dhcpOptions, subnet.Spec.Vpc); err != nil { + if err := c.OVNNbClient.CreateLogicalSwitchPort(subnet.Name, portName, ipStr, mac, podName, pod.Namespace, portSecurity, securityGroupAnnotation, vips, podNet.Subnet.Spec.EnableDHCP, dhcpOptions, subnet.Spec.Vpc); err != nil { c.recorder.Eventf(pod, v1.EventTypeWarning, "CreateOVNPortFailed", err.Error()) klog.Errorf("%v", err) return nil, err @@ -768,7 +764,7 @@ func (c *Controller) reconcileRouteSubnets(cachedPod, pod *v1.Pod, needRoutePodN return fmt.Errorf("no address has been allocated to %s/%s", namespace, name) } - podIP = pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)] + podIP = pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] subnet = podNet.Subnet if podIP != "" && (subnet.Spec.Vlan == "" || subnet.Spec.LogicalGateway) && subnet.Spec.Vpc == c.config.ClusterRouter { @@ -802,7 +798,7 @@ func (c *Controller) reconcileRouteSubnets(cachedPod, pod *v1.Pod, needRoutePodN nextHop = strings.Split(nextHop, "/")[0] } - if err := c.ovnNbClient.AddLogicalRouterStaticRoute( + if err := c.OVNNbClient.AddLogicalRouterStaticRoute( c.config.ClusterRouter, subnet.Spec.RouteTable, ovnnb.LogicalRouterStaticRoutePolicySrcIP, podIP, nil, nextHop, ); err != nil { klog.Errorf("failed to add static route, %v", err) @@ -811,7 +807,7 @@ func (c *Controller) reconcileRouteSubnets(cachedPod, pod *v1.Pod, needRoutePodN // remove lsp from port group to make EIP/SNAT work portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName) - if err = c.ovnNbClient.PortGroupRemovePorts(pgName, portName); err != nil { + if err = c.OVNNbClient.PortGroupRemovePorts(pgName, portName); err != nil { return err } @@ -831,7 +827,7 @@ func (c *Controller) reconcileRouteSubnets(cachedPod, pod *v1.Pod, needRoutePodN } portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName) - if err := c.ovnNbClient.PortGroupAddPorts(pgName, portName); err != nil { + if err := c.OVNNbClient.PortGroupAddPorts(pgName, portName); err != nil { klog.Errorf("add port to port group %s: %v", pgName, err) return err } @@ -846,14 +842,14 @@ func (c *Controller) reconcileRouteSubnets(cachedPod, pod *v1.Pod, needRoutePodN } if pod.Annotations[util.NorthGatewayAnnotation] != "" { - if err := c.ovnNbClient.AddLogicalRouterStaticRoute( + if err := c.OVNNbClient.AddLogicalRouterStaticRoute( c.config.ClusterRouter, subnet.Spec.RouteTable, ovnnb.LogicalRouterStaticRoutePolicySrcIP, podIP, nil, pod.Annotations[util.NorthGatewayAnnotation], ); err != nil { klog.Errorf("failed to add static route, %v", err) return err } } else if c.config.EnableEipSnat { - if err = c.ovnNbClient.DeleteLogicalRouterStaticRoute( + if err = c.OVNNbClient.DeleteLogicalRouterStaticRoute( c.config.ClusterRouter, &subnet.Spec.RouteTable, nil, podIP, "", ); err != nil { return err @@ -864,21 +860,21 @@ func (c *Controller) reconcileRouteSubnets(cachedPod, pod *v1.Pod, needRoutePodN if c.config.EnableEipSnat { for _, ipStr := range strings.Split(podIP, ",") { if eip := pod.Annotations[util.EipAnnotation]; eip == "" { - if err = c.ovnNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeDNATAndSNAT, ipStr); err != nil { + if err = c.OVNNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeDNATAndSNAT, ipStr); err != nil { klog.Errorf("failed to delete nat rules: %v", err) } } else if util.CheckProtocol(eip) == util.CheckProtocol(ipStr) { - if err = c.ovnNbClient.UpdateDnatAndSnat(c.config.ClusterRouter, eip, ipStr, fmt.Sprintf("%s.%s", podName, pod.Namespace), pod.Annotations[util.MacAddressAnnotation], c.ExternalGatewayType); err != nil { + if err = c.OVNNbClient.UpdateDnatAndSnat(c.config.ClusterRouter, eip, ipStr, fmt.Sprintf("%s.%s", podName, pod.Namespace), pod.Annotations[util.MacAddressAnnotation], c.ExternalGatewayType); err != nil { klog.Errorf("failed to add nat rules, %v", err) return err } } if eip := pod.Annotations[util.SnatAnnotation]; eip == "" { - if err = c.ovnNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeSNAT, ipStr); err != nil { + if err = c.OVNNbClient.DeleteNats(c.config.ClusterRouter, ovnnb.NATTypeSNAT, ipStr); err != nil { klog.Errorf("failed to delete nat rules: %v", err) } } else if util.CheckProtocol(eip) == util.CheckProtocol(ipStr) { - if err = c.ovnNbClient.UpdateSnat(c.config.ClusterRouter, eip, ipStr); err != nil { + if err = c.OVNNbClient.UpdateSnat(c.config.ClusterRouter, eip, ipStr); err != nil { klog.Errorf("failed to add nat rules, %v", err) return err } @@ -927,7 +923,7 @@ func (c *Controller) handleDeletePod(key string) error { return nil } - ports, err := c.ovnNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": key}) + ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": key}) if err != nil { klog.Errorf("failed to list lsps of pod '%s', %v", pod.Name, err) return err @@ -936,7 +932,7 @@ func (c *Controller) handleDeletePod(key string) error { if len(ports) != 0 { addresses := c.ipam.GetPodAddress(key) for _, address := range addresses { - if strings.TrimSpace(address.Ip) == "" { + if strings.TrimSpace(address.IP) == "" { continue } subnet, err := c.subnetsLister.Get(address.Subnet.Name) @@ -955,37 +951,37 @@ func (c *Controller) handleDeletePod(key string) error { } // If pod has snat or eip, also need delete staticRoute when delete pod if vpc.Name == c.config.ClusterRouter { - if err = c.ovnNbClient.DeleteLogicalRouterStaticRoute(vpc.Name, &subnet.Spec.RouteTable, nil, address.Ip, ""); err != nil { + if err = c.OVNNbClient.DeleteLogicalRouterStaticRoute(vpc.Name, &subnet.Spec.RouteTable, nil, address.IP, ""); err != nil { return err } } if exGwEnabled == "true" { - if err := c.ovnNbClient.DeleteNat(vpc.Name, "", "", address.Ip); err != nil { + if err := c.OVNNbClient.DeleteNat(vpc.Name, "", "", address.IP); err != nil { return err } } } } - var keepIpCR bool + var keepIPCR bool if ok, sts := isStatefulSetPod(pod); ok { toDel := isStatefulSetPodToDel(c.config.KubeClient, pod, sts) - delete, err := appendCheckPodToDel(c, pod, sts, "StatefulSet") + isDelete, err := appendCheckPodToDel(c, pod, sts, "StatefulSet") if pod.DeletionTimestamp != nil { // triggered by delete event - if !(toDel || (delete && err == nil)) { + if !(toDel || (isDelete && err == nil)) { return nil } } - keepIpCR = !toDel && !delete && err == nil + keepIPCR = !toDel && !isDelete && err == nil } - isVmPod, vmName := isVmPod(pod) - if isVmPod && c.config.EnableKeepVmIP { - toDel := c.isVmPodToDel(pod, vmName) - delete, err := appendCheckPodToDel(c, pod, vmName, util.VmInstance) + isVMPod, vmName := isVMPod(pod) + if isVMPod && c.config.EnableKeepVMIP { + toDel := c.isVMPodToDel(pod, vmName) + isDelete, err := appendCheckPodToDel(c, pod, vmName, util.VMInstance) if pod.DeletionTimestamp != nil { // triggered by delete event - if !(toDel || (delete && err == nil)) { + if !(toDel || (isDelete && err == nil)) { return nil } klog.Infof("delete vm pod %s", podName) @@ -995,7 +991,7 @@ func (c *Controller) handleDeletePod(key string) error { for _, port := range ports { // when lsp is deleted, the port of pod is deleted from any port-group automatically. klog.Infof("gc logical switch port %s", port.Name) - if err := c.ovnNbClient.DeleteLogicalSwitchPort(port.Name); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(port.Name); err != nil { klog.Errorf("failed to delete lsp %s, %v", port.Name, err) return err } @@ -1007,7 +1003,7 @@ func (c *Controller) handleDeletePod(key string) error { if err != nil { klog.Errorf("failed to get pod nets %v", err) } - if !keepIpCR { + if !keepIPCR { for _, podNet := range podNets { if err = c.deleteCrdIPs(podName, pod.Namespace, podNet.ProviderName); err != nil { klog.Errorf("failed to delete ip for pod %s, %v, please delete manually", pod.Name, err) @@ -1062,10 +1058,10 @@ func (c *Controller) handleUpdatePodSecurity(key string) error { } mac := pod.Annotations[fmt.Sprintf(util.MacAddressAnnotationTemplate, podNet.ProviderName)] - ipStr := pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)] + ipStr := pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] vips := pod.Annotations[fmt.Sprintf(util.PortVipAnnotationTemplate, podNet.ProviderName)] - if err = c.ovnNbClient.SetLogicalSwitchPortSecurity(portSecurity, ovs.PodNameToPortName(podName, namespace, podNet.ProviderName), mac, ipStr, vips); err != nil { + if err = c.OVNNbClient.SetLogicalSwitchPortSecurity(portSecurity, ovs.PodNameToPortName(podName, namespace, podNet.ProviderName), mac, ipStr, vips); err != nil { klog.Errorf("set logical switch port security: %v", err) return err } @@ -1084,6 +1080,7 @@ func (c *Controller) handleUpdatePodSecurity(key string) error { } return nil } + func (c *Controller) syncKubeOvnNet(cachedPod, pod *v1.Pod, podNets []*kubeovnNet) (*v1.Pod, error) { podName := c.getNameByPod(pod) key := fmt.Sprintf("%s/%s", pod.Namespace, podName) @@ -1097,7 +1094,7 @@ func (c *Controller) syncKubeOvnNet(cachedPod, pod *v1.Pod, podNets []*kubeovnNe targetPortNameList.Add(portName) } - ports, err := c.ovnNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": key}) + ports, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{"pod": key}) if err != nil { klog.Errorf("failed to list lsps of pod '%s', %v", pod.Name, err) return nil, err @@ -1126,7 +1123,7 @@ func (c *Controller) syncKubeOvnNet(cachedPod, pod *v1.Pod, podNets []*kubeovnNe subnet.ReleaseAddressWithNicName(podName, portNeedDel) } - if err := c.ovnNbClient.DeleteLogicalSwitchPort(portNeedDel); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(portNeedDel); err != nil { klog.Errorf("failed to delete lsp %s, %v", portNeedDel, err) return nil, err } @@ -1184,9 +1181,8 @@ func isStatefulSetPodToDel(c kubernetes.Interface, pod *v1.Pod, statefulSetName // statefulset is deleted if k8serrors.IsNotFound(err) { return true - } else { - klog.Errorf("failed to get statefulset %v", err) } + klog.Errorf("failed to get statefulset %v", err) return false } @@ -1209,7 +1205,7 @@ func isStatefulSetPodToDel(c kubernetes.Interface, pod *v1.Pod, statefulSetName func getNodeTunlIP(node *v1.Node) ([]net.IP, error) { var nodeTunlIPAddr []net.IP - nodeTunlIP := node.Annotations[util.IpAddressAnnotation] + nodeTunlIP := node.Annotations[util.IPAddressAnnotation] if nodeTunlIP == "" { return nil, fmt.Errorf("node has no tunnel ip annotation") } @@ -1519,7 +1515,7 @@ func (c *Controller) acquireAddress(pod *v1.Pod, podNet *kubeovnNet) (string, st podName := c.getNameByPod(pod) key := fmt.Sprintf("%s/%s", pod.Namespace, podName) - var isVMPod bool + var checkVMPod bool isStsPod, _ := isStatefulSetPod(pod) // if pod has static vip vipName := pod.Annotations[util.VipAnnotation] @@ -1530,10 +1526,10 @@ func (c *Controller) acquireAddress(pod *v1.Pod, podNet *kubeovnNet) (string, st return "", "", "", podNet.Subnet, err } portName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName) - if c.config.EnableKeepVmIP { - isVMPod, _ = isVmPod(pod) + if c.config.EnableKeepVMIP { + checkVMPod, _ = isVMPod(pod) } - if err = c.podReuseVip(vipName, portName, isStsPod || isVMPod); err != nil { + if err = c.podReuseVip(vipName, portName, isStsPod || checkVMPod); err != nil { return "", "", "", podNet.Subnet, err } return vip.Status.V4ip, vip.Status.V6ip, vip.Status.Mac, podNet.Subnet, nil @@ -1553,7 +1549,7 @@ func (c *Controller) acquireAddress(pod *v1.Pod, podNet *kubeovnNet) (string, st *macStr = "" } - ippoolStr := pod.Annotations[fmt.Sprintf(util.IpPoolAnnotationTemplate, podNet.ProviderName)] + ippoolStr := pod.Annotations[fmt.Sprintf(util.IPPoolAnnotationTemplate, podNet.ProviderName)] if ippoolStr == "" { ns, err := c.namespacesLister.Get(pod.Namespace) if err != nil { @@ -1561,12 +1557,12 @@ func (c *Controller) acquireAddress(pod *v1.Pod, podNet *kubeovnNet) (string, st return "", "", "", podNet.Subnet, err } if len(ns.Annotations) != 0 { - ippoolStr = ns.Annotations[util.IpPoolAnnotation] + ippoolStr = ns.Annotations[util.IPPoolAnnotation] } } // Random allocate - if pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)] == "" && + if pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] == "" && ippoolStr == "" { var skippedAddrs []string for { @@ -1603,8 +1599,8 @@ func (c *Controller) acquireAddress(pod *v1.Pod, podNet *kubeovnNet) (string, st var err error // Static allocate - if pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)] != "" { - ipStr := pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)] + if pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] != "" { + ipStr := pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] for _, net := range nsNets { v4IP, v6IP, mac, err = c.acquireStaticAddress(key, portName, ipStr, macStr, net.Subnet.Name, net.AllowLiveMigration) @@ -1731,23 +1727,21 @@ func appendCheckPodToDel(c *Controller, pod *v1.Pod, ownerRefName, ownerRefKind if err != nil { if k8serrors.IsNotFound(err) { return true, nil - } else { - klog.Errorf("failed to get StatefulSet %s, %v", ownerRefName, err) } + klog.Errorf("failed to get StatefulSet %s, %v", ownerRefName, err) } if ss.Spec.Template.ObjectMeta.Annotations[util.LogicalSwitchAnnotation] != "" { ownerRefSubnetExist = true ownerRefSubnet = ss.Spec.Template.ObjectMeta.Annotations[util.LogicalSwitchAnnotation] } - case util.VmInstance: + case util.VMInstance: vm, err := c.config.KubevirtClient.VirtualMachine(pod.Namespace).Get(ownerRefName, &metav1.GetOptions{}) if err != nil { if k8serrors.IsNotFound(err) { return true, nil - } else { - klog.Errorf("failed to get VirtualMachine %s, %v", ownerRefName, err) } + klog.Errorf("failed to get VirtualMachine %s, %v", ownerRefName, err) } if vm != nil && vm.Spec.Template != nil && @@ -1772,8 +1766,8 @@ func appendCheckPodToDel(c *Controller, pod *v1.Pod, ownerRefName, ownerRefKind klog.Errorf("failed to get subnet %s, %v", pod.Annotations[util.LogicalSwitchAnnotation], err) return false, err } - if podSubnet != nil && !util.CIDRContainIP(podSubnet.Spec.CIDRBlock, pod.Annotations[util.IpAddressAnnotation]) { - klog.Infof("pod's ip %s is not in the range of subnet %s, delete pod", pod.Annotations[util.IpAddressAnnotation], podSubnet.Name) + if podSubnet != nil && !util.CIDRContainIP(podSubnet.Spec.CIDRBlock, pod.Annotations[util.IPAddressAnnotation]) { + klog.Infof("pod's ip %s is not in the range of subnet %s, delete pod", pod.Annotations[util.IPAddressAnnotation], podSubnet.Name) return true, nil } // subnet of ownerReference(sts/vm) has been changed, it needs to handle delete pod and create port on the new logical switch @@ -1785,10 +1779,10 @@ func appendCheckPodToDel(c *Controller, pod *v1.Pod, ownerRefName, ownerRefKind return false, nil } -func isVmPod(pod *v1.Pod) (bool, string) { +func isVMPod(pod *v1.Pod) (bool, string) { for _, owner := range pod.OwnerReferences { // The name of vmi is consistent with vm's name. - if owner.Kind == util.VmInstance && strings.HasPrefix(owner.APIVersion, "kubevirt.io") { + if owner.Kind == util.VMInstance && strings.HasPrefix(owner.APIVersion, "kubevirt.io") { return true, owner.Name } } @@ -1797,14 +1791,14 @@ func isVmPod(pod *v1.Pod) (bool, string) { func isOwnsByTheVM(vmi metav1.Object) (bool, string) { for _, owner := range vmi.GetOwnerReferences() { - if owner.Kind == util.Vm && strings.HasPrefix(owner.APIVersion, "kubevirt.io") { + if owner.Kind == util.VM && strings.HasPrefix(owner.APIVersion, "kubevirt.io") { return true, owner.Name } } return false, "" } -func (c *Controller) isVmPodToDel(pod *v1.Pod, vmiName string) bool { +func (c *Controller) isVMPodToDel(pod *v1.Pod, vmiName string) bool { var ( vmiAlive bool vmName string @@ -1841,9 +1835,8 @@ func (c *Controller) isVmPodToDel(pod *v1.Pod, vmiName string) bool { if k8serrors.IsNotFound(err) { klog.V(4).ErrorS(err, "failed to get vm", "name", vmName) return true - } else { - klog.ErrorS(err, "failed to get vm", "name", vmName) } + klog.ErrorS(err, "failed to get vm", "name", vmName) return false } @@ -1856,8 +1849,8 @@ func (c *Controller) isVmPodToDel(pod *v1.Pod, vmiName string) bool { } func (c *Controller) getNameByPod(pod *v1.Pod) string { - if c.config.EnableKeepVmIP { - if isVmPod, vmName := isVmPod(pod); isVmPod { + if c.config.EnableKeepVMIP { + if isVMPod, vmName := isVMPod(pod); isVMPod { return vmName } } @@ -1905,8 +1898,8 @@ func getPodType(pod *v1.Pod) string { return "StatefulSet" } - if isVmPod, _ := isVmPod(pod); isVmPod { - return util.Vm + if isVMPod, _ := isVMPod(pod); isVMPod { + return util.VM } return "" } diff --git a/pkg/controller/pod_iptables_eip.go b/pkg/controller/pod_iptables_eip.go index df897e1cb4d..37a8e9bfe56 100644 --- a/pkg/controller/pod_iptables_eip.go +++ b/pkg/controller/pod_iptables_eip.go @@ -5,8 +5,6 @@ import ( "fmt" "strings" - kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1" - "github.com/kubeovn/kube-ovn/pkg/util" v1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -15,10 +13,12 @@ import ( "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/cache" "k8s.io/klog/v2" + + kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1" + "github.com/kubeovn/kube-ovn/pkg/util" ) func (c *Controller) enqueueAddPodAnnotatedIptablesEip(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -42,14 +42,14 @@ func (c *Controller) enqueueAddPodAnnotatedIptablesEip(obj interface{}) { // delete eip if pod not alive if !isPodAlive(p) { isStateful, statefulSetName := isStatefulSetPod(p) - isVmPod, vmName := isVmPod(p) - if isStateful || (isVmPod && c.config.EnableKeepVmIP) { + isVMPod, vmName := isVMPod(p) + if isStateful || (isVMPod && c.config.EnableKeepVMIP) { if isStateful && isStatefulSetDeleted(c.config.KubeClient, p, statefulSetName) { klog.V(3).Infof("enqueue delete pod annotated iptables eip %s", eipName) c.delPodAnnotatedIptablesEipQueue.Add(obj) return } - if isVmPod && c.isVmPodToDel(p, vmName) { + if isVMPod && c.isVMPodToDel(p, vmName) { klog.V(3).Infof("enqueue delete pod annotated iptables eip %s", eipName) c.delPodAnnotatedIptablesEipQueue.Add(obj) return @@ -97,16 +97,16 @@ func (c *Controller) enqueueUpdatePodAnnotatedIptablesEip(oldObj, newObj interfa return } isStateful, _ := isStatefulSetPod(newPod) - isVmPod, vmName := isVmPod(newPod) + isVMPod, vmName := isVMPod(newPod) if newPod.DeletionTimestamp != nil && isStateful { c.delPodAnnotatedIptablesEipQueue.Add(newObj) return } - if !isPodAlive(newPod) && !isStateful && !isVmPod { + if !isPodAlive(newPod) && !isStateful && !isVMPod { c.delPodAnnotatedIptablesEipQueue.Add(newObj) return } - if c.config.EnableKeepVmIP && isVmPod && c.isVmPodToDel(newPod, vmName) { + if c.config.EnableKeepVMIP && isVMPod && c.isVMPodToDel(newPod, vmName) { c.delPodAnnotatedIptablesEipQueue.Add(newObj) return } @@ -126,26 +126,27 @@ func (c *Controller) enqueueDeletePodAnnotatedIptablesEip(obj interface{}) { return } isStateful, statefulSetName := isStatefulSetPod(p) - isVmPod, vmName := isVmPod(p) - if isStateful { + isVMPod, vmName := isVMPod(p) + switch { + case isStateful: if isStatefulSetDeleted(c.config.KubeClient, p, statefulSetName) { c.delPodAnnotatedIptablesEipQueue.Add(obj) return } - if delete, err := appendCheckPodToDel(c, p, statefulSetName, "StatefulSet"); delete && err == nil { + if isDelete, err := appendCheckPodToDel(c, p, statefulSetName, "StatefulSet"); isDelete && err == nil { c.delPodAnnotatedIptablesEipQueue.Add(obj) return } - } else if c.config.EnableKeepVmIP && isVmPod { - if c.isVmPodToDel(p, vmName) { + case c.config.EnableKeepVMIP && isVMPod: + if c.isVMPodToDel(p, vmName) { c.delPodAnnotatedIptablesEipQueue.Add(obj) return } - if delete, err := appendCheckPodToDel(c, p, vmName, util.VmInstance); delete && err == nil { + if isDelete, err := appendCheckPodToDel(c, p, vmName, util.VMInstance); isDelete && err == nil { c.delPodAnnotatedIptablesEipQueue.Add(obj) return } - } else { + default: c.delPodAnnotatedIptablesEipQueue.Add(obj) return } @@ -182,7 +183,6 @@ func (c *Controller) processNextAddPodAnnotatedIptablesEipWorkItem() bool { c.addPodAnnotatedIptablesEipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -211,7 +211,6 @@ func (c *Controller) processNextDeletePodAnnotatedIptablesEipWorkItem() bool { c.delPodAnnotatedIptablesEipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -343,10 +342,9 @@ func isStatefulSetDeleted(c kubernetes.Interface, pod *v1.Pod, statefulSetName s if k8serrors.IsNotFound(err) { // statefulset is deleted return true - } else { - klog.Errorf("failed to get statefulset %v", err) - return false } + klog.Errorf("failed to get statefulset %v", err) + return false } // statefulset is deleting if ss.DeletionTimestamp != nil { diff --git a/pkg/controller/pod_iptables_fip.go b/pkg/controller/pod_iptables_fip.go index 73ac83a80cb..aae9adaa6a8 100644 --- a/pkg/controller/pod_iptables_fip.go +++ b/pkg/controller/pod_iptables_fip.go @@ -6,7 +6,6 @@ import ( "strings" "time" - "github.com/kubeovn/kube-ovn/pkg/util" v1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -15,10 +14,11 @@ import ( "k8s.io/client-go/tools/cache" "k8s.io/klog/v2" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + "github.com/kubeovn/kube-ovn/pkg/util" ) func (c *Controller) enqueueAddPodAnnotatedIptablesFip(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -34,13 +34,13 @@ func (c *Controller) enqueueAddPodAnnotatedIptablesFip(obj interface{}) { } if !isPodAlive(p) { isStateful, statefulSetName := isStatefulSetPod(p) - isVmPod, vmName := isVmPod(p) - if isStateful || (isVmPod && c.config.EnableKeepVmIP) { + isVMPod, vmName := isVMPod(p) + if isStateful || (isVMPod && c.config.EnableKeepVMIP) { if isStateful && isStatefulSetPodToDel(c.config.KubeClient, p, statefulSetName) { c.delPodAnnotatedIptablesFipQueue.Add(obj) return } - if isVmPod && c.isVmPodToDel(p, vmName) { + if isVMPod && c.isVMPodToDel(p, vmName) { c.delPodAnnotatedIptablesFipQueue.Add(obj) return } @@ -85,8 +85,8 @@ func (c *Controller) enqueueUpdatePodAnnotatedIptablesFip(oldObj, newObj interfa } isStateful, _ := isStatefulSetPod(newPod) - isVmPod, vmName := isVmPod(newPod) - if !isPodAlive(newPod) && !isStateful && !isVmPod { + isVMPod, vmName := isVMPod(newPod) + if !isPodAlive(newPod) && !isStateful && !isVMPod { c.delPodAnnotatedIptablesFipQueue.Add(newObj) return } @@ -94,7 +94,7 @@ func (c *Controller) enqueueUpdatePodAnnotatedIptablesFip(oldObj, newObj interfa c.delPodAnnotatedIptablesFipQueue.Add(newObj) return } - if c.config.EnableKeepVmIP && isVmPod && c.isVmPodToDel(newPod, vmName) { + if c.config.EnableKeepVMIP && isVMPod && c.isVMPodToDel(newPod, vmName) { c.delPodAnnotatedIptablesFipQueue.Add(newObj) return } @@ -114,26 +114,27 @@ func (c *Controller) enqueueDeletePodAnnotatedIptablesFip(obj interface{}) { return } isStateful, statefulSetName := isStatefulSetPod(p) - isVmPod, vmName := isVmPod(p) - if isStateful { + isVMPod, vmName := isVMPod(p) + switch { + case isStateful: if isStatefulSetPodToDel(c.config.KubeClient, p, statefulSetName) { c.delPodAnnotatedIptablesFipQueue.Add(obj) return } - if delete, err := appendCheckPodToDel(c, p, statefulSetName, "StatefulSet"); delete && err == nil { + if isDelete, err := appendCheckPodToDel(c, p, statefulSetName, "StatefulSet"); isDelete && err == nil { c.delPodAnnotatedIptablesFipQueue.Add(obj) return } - } else if c.config.EnableKeepVmIP && isVmPod { - if c.isVmPodToDel(p, vmName) { + case c.config.EnableKeepVMIP && isVMPod: + if c.isVMPodToDel(p, vmName) { c.delPodAnnotatedIptablesFipQueue.Add(obj) return } - if delete, err := appendCheckPodToDel(c, p, vmName, util.VmInstance); delete && err == nil { + if isDelete, err := appendCheckPodToDel(c, p, vmName, util.VMInstance); isDelete && err == nil { c.delPodAnnotatedIptablesFipQueue.Add(obj) return } - } else { + default: c.delPodAnnotatedIptablesFipQueue.Add(obj) return } @@ -198,7 +199,6 @@ func (c *Controller) processNextDeletePodAnnotatedIptablesFipWorkItem() bool { c.delPodAnnotatedIptablesFipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -247,7 +247,7 @@ func (c *Controller) handleAddPodAnnotatedIptablesFip(key string) error { return err } klog.V(3).Infof("handle add pod annotated iptables fip %s", fipName) - if err := c.createOrUpdateCrdFip(fipName, fipName, cachedPod.Annotations[util.IpAddressAnnotation]); err != nil { + if err := c.createOrUpdateCrdFip(fipName, fipName, cachedPod.Annotations[util.IPAddressAnnotation]); err != nil { klog.Errorf("failed to create fip %s: %v", fipName, err) return err } @@ -275,8 +275,8 @@ func (c *Controller) handleDeletePodAnnotatedIptablesFip(pod *v1.Pod) error { var keepFipCR bool klog.V(3).Infof("handle delete annotated iptables fip for pod %s/%s", pod.Namespace, pod.Name) if ok, sts := isStatefulSetPod(pod); ok { - delete, err := appendCheckPodToDel(c, pod, sts, "StatefulSet") - keepFipCR = !isStatefulSetPodToDel(c.config.KubeClient, pod, sts) && !delete && err == nil + isDelete, err := appendCheckPodToDel(c, pod, sts, "StatefulSet") + keepFipCR = !isStatefulSetPodToDel(c.config.KubeClient, pod, sts) && !isDelete && err == nil } if !keepFipCR { fipName := PodNameToEipName(pod.Name, pod.Namespace) @@ -294,10 +294,7 @@ func (c *Controller) handleDeletePodAnnotatedIptablesFip(pod *v1.Pod) error { } } } - if err = c.handleDelPodAnnotatedIptablesFipFinalizer(pod); err != nil { - return err - } - return nil + return c.handleDelPodAnnotatedIptablesFipFinalizer(pod) } func (c *Controller) handleAddPodAnnotatedIptablesFipFinalizer(pod *v1.Pod) error { diff --git a/pkg/controller/qos_policy.go b/pkg/controller/qos_policy.go index 42e8c199b46..780c3f9c144 100644 --- a/pkg/controller/qos_policy.go +++ b/pkg/controller/qos_policy.go @@ -32,26 +32,26 @@ func (c *Controller) enqueueAddQoSPolicy(obj interface{}) { c.addQoSPolicyQueue.Add(key) } -func compareQoSPolicyBandwidthLimitRules(old, new kubeovnv1.QoSPolicyBandwidthLimitRules) bool { - if len(old) != len(new) { +func compareQoSPolicyBandwidthLimitRules(oldObj, newObj kubeovnv1.QoSPolicyBandwidthLimitRules) bool { + if len(oldObj) != len(newObj) { return false } - sort.Slice(new, func(i, j int) bool { - return new[i].Name < new[j].Name + sort.Slice(newObj, func(i, j int) bool { + return newObj[i].Name < newObj[j].Name }) - return reflect.DeepEqual(old, new) + return reflect.DeepEqual(oldObj, newObj) } -func (c *Controller) enqueueUpdateQoSPolicy(old, new interface{}) { +func (c *Controller) enqueueUpdateQoSPolicy(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - oldQos := old.(*kubeovnv1.QoSPolicy) - newQos := new.(*kubeovnv1.QoSPolicy) + oldQos := oldObj.(*kubeovnv1.QoSPolicy) + newQos := newObj.(*kubeovnv1.QoSPolicy) if !newQos.DeletionTimestamp.IsZero() { klog.V(3).Infof("enqueue update to clean qos %s", key) c.updateQoSPolicyQueue.Add(key) @@ -114,7 +114,6 @@ func (c *Controller) processNextAddQoSPolicyWorkItem() bool { c.addQoSPolicyQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -144,7 +143,6 @@ func (c *Controller) processNextUpdateQoSPolicyWorkItem() bool { c.updateQoSPolicyQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -174,7 +172,6 @@ func (c *Controller) processNextDeleteQoSPolicyWorkItem() bool { c.delQoSPolicyQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -224,7 +221,8 @@ func (c *Controller) handleAddQoSPolicy(key string) error { } func (c *Controller) patchQoSStatus( - key string, shared bool, qosType kubeovnv1.QoSPolicyBindingType, bandwidthRules kubeovnv1.QoSPolicyBandwidthLimitRules) error { + key string, shared bool, qosType kubeovnv1.QoSPolicyBindingType, bandwidthRules kubeovnv1.QoSPolicyBandwidthLimitRules, +) error { oriQoS, err := c.qosPoliciesLister.Get(key) if err != nil { if k8serrors.IsNotFound(err) { @@ -319,7 +317,8 @@ func (c *Controller) reconcileEIPBandtithLimitRules( eip *kubeovnv1.IptablesEIP, added kubeovnv1.QoSPolicyBandwidthLimitRules, deleted kubeovnv1.QoSPolicyBandwidthLimitRules, - updated kubeovnv1.QoSPolicyBandwidthLimitRules) error { + updated kubeovnv1.QoSPolicyBandwidthLimitRules, +) error { var err error // in this case, we must delete rules first, then add or update rules if len(deleted) > 0 { @@ -466,40 +465,41 @@ func (c *Controller) handleUpdateQoSPolicy(key string) error { err := fmt.Errorf("not support shared qos %s change rule ", key) klog.Error(err) return err - } else { - if cachedQos.Status.BindingType == kubeovnv1.QoSBindingTypeEIP { - // filter to eip - eips, err := c.iptablesEipsLister.List( - labels.SelectorFromSet(labels.Set{util.QoSLabel: key})) - if err != nil { - klog.Errorf("failed to get eip list, %v", err) - return err - } - if len(eips) == 0 { - // not thing to do - } else if len(eips) == 1 { - eip := eips[0] - if err = c.reconcileEIPBandtithLimitRules(eip, added, deleted, updated); err != nil { - klog.Errorf("failed to reconcile eip %s bandwidth limit rules, %v", eip.Name, err) - return err - } - } else { - err := fmt.Errorf("not support qos %s change rule, related eip more than one", key) - klog.Error(err) + } + + if cachedQos.Status.BindingType == kubeovnv1.QoSBindingTypeEIP { + // filter to eip + eips, err := c.iptablesEipsLister.List( + labels.SelectorFromSet(labels.Set{util.QoSLabel: key})) + if err != nil { + klog.Errorf("failed to get eip list, %v", err) + return err + } + switch { + case len(eips) == 0: + // not thing to do + case len(eips) == 1: + eip := eips[0] + if err = c.reconcileEIPBandtithLimitRules(eip, added, deleted, updated); err != nil { + klog.Errorf("failed to reconcile eip %s bandwidth limit rules, %v", eip.Name, err) return err } + default: + err := fmt.Errorf("not support qos %s change rule, related eip more than one", key) + klog.Error(err) + return err } + } - sortedNewRules := cachedQos.Spec.BandwidthLimitRules - sort.Slice(sortedNewRules, func(i, j int) bool { - return sortedNewRules[i].Name < sortedNewRules[j].Name - }) + sortedNewRules := cachedQos.Spec.BandwidthLimitRules + sort.Slice(sortedNewRules, func(i, j int) bool { + return sortedNewRules[i].Name < sortedNewRules[j].Name + }) - // .Status.Shared and .Status.BindingType are not supported to change - if err = c.patchQoSStatus(key, cachedQos.Status.Shared, cachedQos.Status.BindingType, sortedNewRules); err != nil { - klog.Errorf("failed to patch status for qos %s, %v", key, err) - return err - } + // .Status.Shared and .Status.BindingType are not supported to change + if err = c.patchQoSStatus(key, cachedQos.Status.Shared, cachedQos.Status.BindingType, sortedNewRules); err != nil { + klog.Errorf("failed to patch status for qos %s, %v", key, err) + return err } } return nil diff --git a/pkg/controller/security_group.go b/pkg/controller/security_group.go index 6b338ae9acd..c4dabea105f 100644 --- a/pkg/controller/security_group.go +++ b/pkg/controller/security_group.go @@ -22,7 +22,6 @@ import ( ) func (c *Controller) enqueueAddSg(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -33,13 +32,13 @@ func (c *Controller) enqueueAddSg(obj interface{}) { c.addOrUpdateSgQueue.Add(key) } -func (c *Controller) enqueueUpdateSg(old, new interface{}) { - oldSg := old.(*kubeovnv1.SecurityGroup) - newSg := new.(*kubeovnv1.SecurityGroup) +func (c *Controller) enqueueUpdateSg(oldObj, newObj interface{}) { + oldSg := oldObj.(*kubeovnv1.SecurityGroup) + newSg := newObj.(*kubeovnv1.SecurityGroup) if !reflect.DeepEqual(oldSg.Spec, newSg.Spec) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } @@ -96,7 +95,6 @@ func (c *Controller) processNextSyncSgPortsWorkItem() bool { c.syncSgPortsQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -127,7 +125,6 @@ func (c *Controller) processNextAddOrUpdateSgWorkItem() bool { c.addOrUpdateSgQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -158,7 +155,6 @@ func (c *Controller) processNextDeleteSgWorkItem() bool { c.delSgQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -168,7 +164,7 @@ func (c *Controller) processNextDeleteSgWorkItem() bool { func (c *Controller) initDenyAllSecurityGroup() error { pgName := ovs.GetSgPortGroupName(util.DenyAllSecurityGroup) - if err := c.ovnNbClient.CreatePortGroup(pgName, map[string]string{ + if err := c.OVNNbClient.CreatePortGroup(pgName, map[string]string{ "type": "security_group", sgKey: util.DenyAllSecurityGroup, }); err != nil { @@ -176,7 +172,7 @@ func (c *Controller) initDenyAllSecurityGroup() error { return err } - if err := c.ovnNbClient.CreateSgDenyAllAcl(util.DenyAllSecurityGroup); err != nil { + if err := c.OVNNbClient.CreateSgDenyAllACL(util.DenyAllSecurityGroup); err != nil { klog.Errorf("create deny all acl for sg %s: %v", util.DenyAllSecurityGroup, err) return err } @@ -188,7 +184,7 @@ func (c *Controller) initDenyAllSecurityGroup() error { // updateDenyAllSgPorts set lsp to deny which security_groups is not empty func (c *Controller) updateDenyAllSgPorts() error { // list all lsp which security_groups is not empty - lsps, err := c.ovnNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{sgsKey: ""}) + lsps, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, map[string]string{sgsKey: ""}) if err != nil { klog.Errorf("list logical switch ports with security_groups is not empty: %v", err) return err @@ -219,7 +215,7 @@ func (c *Controller) updateDenyAllSgPorts() error { pgName := ovs.GetSgPortGroupName(util.DenyAllSecurityGroup) klog.V(6).Infof("setting ports of port group %s to %v", pgName, addPorts) - if err = c.ovnNbClient.PortGroupSetPorts(pgName, addPorts); err != nil { + if err = c.OVNNbClient.PortGroupSetPorts(pgName, addPorts); err != nil { klog.Error(err) return err } @@ -255,7 +251,7 @@ func (c *Controller) handleAddOrUpdateSg(key string) error { } pgName := ovs.GetSgPortGroupName(sg.Name) - if err := c.ovnNbClient.CreatePortGroup(pgName, map[string]string{ + if err := c.OVNNbClient.CreatePortGroup(pgName, map[string]string{ "type": "security_group", sgKey: sg.Name, }); err != nil { @@ -269,12 +265,12 @@ func (c *Controller) handleAddOrUpdateSg(key string) error { sgKey: sg.Name, } - if err = c.ovnNbClient.CreateAddressSet(v4AsName, externalIDs); err != nil { + if err = c.OVNNbClient.CreateAddressSet(v4AsName, externalIDs); err != nil { klog.Errorf("create address set %s for sg %s: %v", v4AsName, key, err) return err } - if err = c.ovnNbClient.CreateAddressSet(v6AsName, externalIDs); err != nil { + if err = c.OVNNbClient.CreateAddressSet(v6AsName, externalIDs); err != nil { klog.Errorf("create address set %s for sg %s: %v", v6AsName, key, err) return err } @@ -303,13 +299,13 @@ func (c *Controller) handleAddOrUpdateSg(key string) error { // update sg rule if ingressNeedUpdate { - if err = c.ovnNbClient.UpdateSgAcl(sg, ovnnb.ACLDirectionToLport); err != nil { + if err = c.OVNNbClient.UpdateSgACL(sg, ovnnb.ACLDirectionToLport); err != nil { sg.Status.IngressLastSyncSuccess = false c.patchSgStatus(sg) return err } - if err := c.ovnNbClient.CreateSgBaseACL(sg.Name, ovnnb.ACLDirectionToLport); err != nil { + if err := c.OVNNbClient.CreateSgBaseACL(sg.Name, ovnnb.ACLDirectionToLport); err != nil { return err } sg.Status.IngressMd5 = newIngressMd5 @@ -317,13 +313,13 @@ func (c *Controller) handleAddOrUpdateSg(key string) error { c.patchSgStatus(sg) } if egressNeedUpdate { - if err = c.ovnNbClient.UpdateSgAcl(sg, ovnnb.ACLDirectionFromLport); err != nil { + if err = c.OVNNbClient.UpdateSgACL(sg, ovnnb.ACLDirectionFromLport); err != nil { sg.Status.IngressLastSyncSuccess = false c.patchSgStatus(sg) return err } - if err := c.ovnNbClient.CreateSgBaseACL(sg.Name, ovnnb.ACLDirectionFromLport); err != nil { + if err := c.OVNNbClient.CreateSgBaseACL(sg.Name, ovnnb.ACLDirectionFromLport); err != nil { return err } @@ -389,10 +385,9 @@ func (c *Controller) patchSgStatus(sg *kubeovnv1.SecurityGroup) { if err != nil { klog.Error(err) return - } else { - if _, err = c.config.KubeOvnClient.KubeovnV1().SecurityGroups().Patch(context.Background(), sg.Name, types.MergePatchType, bytes, metav1.PatchOptions{}, "status"); err != nil { - klog.Error("patch security group status failed", err) - } + } + if _, err = c.config.KubeOvnClient.KubeovnV1().SecurityGroups().Patch(context.Background(), sg.Name, types.MergePatchType, bytes, metav1.PatchOptions{}, "status"); err != nil { + klog.Error("patch security group status failed", err) } } @@ -401,7 +396,7 @@ func (c *Controller) handleDeleteSg(key string) error { defer func() { _ = c.sgKeyMutex.UnlockKey(key) }() klog.Infof("handle delete security group %s", key) - if err := c.ovnNbClient.DeleteSecurityGroup(key); err != nil { + if err := c.OVNNbClient.DeleteSecurityGroup(key); err != nil { klog.Errorf("delete sg %s: %v", key, err) return err } @@ -424,7 +419,7 @@ func (c *Controller) syncSgLogicalPort(key string) error { return err } - results, err := c.ovnNbClient.ListLogicalSwitchPorts(false, map[string]string{"external_ids:associated_sg_" + key: "true"}, nil) + results, err := c.OVNNbClient.ListLogicalSwitchPorts(false, map[string]string{"external_ids:associated_sg_" + key: "true"}, nil) if err != nil { klog.Errorf("failed to find logical port, %v", err) return err @@ -451,19 +446,19 @@ func (c *Controller) syncSgLogicalPort(key string) error { } } - if err = c.ovnNbClient.PortGroupSetPorts(sg.Status.PortGroup, ports); err != nil { + if err = c.OVNNbClient.PortGroupSetPorts(sg.Status.PortGroup, ports); err != nil { klog.Errorf("add ports to port group %s: %v", sg.Status.PortGroup, err) return err } v4AsName := ovs.GetSgV4AssociatedName(key) - if err := c.ovnNbClient.AddressSetUpdateAddress(v4AsName, v4s...); err != nil { + if err := c.OVNNbClient.AddressSetUpdateAddress(v4AsName, v4s...); err != nil { klog.Errorf("set ips to address set %s: %v", v4AsName, err) return err } v6AsName := ovs.GetSgV6AssociatedName(key) - if err := c.ovnNbClient.AddressSetUpdateAddress(v6AsName, v6s...); err != nil { + if err := c.OVNNbClient.AddressSetUpdateAddress(v6AsName, v6s...); err != nil { klog.Errorf("set ips to address set %s: %v", v6AsName, err) return err } @@ -484,7 +479,7 @@ func (c *Controller) getPortSg(port *ovnnb.LogicalSwitchPort) ([]string, error) } func (c *Controller) reconcilePortSg(portName, securityGroups string) error { - port, err := c.ovnNbClient.GetLogicalSwitchPort(portName, false) + port, err := c.OVNNbClient.GetLogicalSwitchPort(portName, false) if err != nil { klog.Errorf("failed to get logical switch port %s: %v", portName, err) return err @@ -507,14 +502,14 @@ func (c *Controller) reconcilePortSg(portName, securityGroups string) error { needAssociated = "true" } - if err = c.ovnNbClient.SetLogicalSwitchPortExternalIds(portName, map[string]string{fmt.Sprintf("associated_sg_%s", sgName): needAssociated}); err != nil { + if err = c.OVNNbClient.SetLogicalSwitchPortExternalIds(portName, map[string]string{fmt.Sprintf("associated_sg_%s", sgName): needAssociated}); err != nil { klog.Errorf("set logical switch port %s external_ids: %v", portName, err) return err } c.syncSgPortsQueue.Add(sgName) } - if err = c.ovnNbClient.SetLogicalSwitchPortExternalIds(portName, map[string]string{"security_groups": strings.ReplaceAll(securityGroups, ",", "/")}); err != nil { + if err = c.OVNNbClient.SetLogicalSwitchPortExternalIds(portName, map[string]string{"security_groups": strings.ReplaceAll(securityGroups, ",", "/")}); err != nil { klog.Errorf("set logical switch port %s external_ids: %v", portName, err) return err } @@ -531,7 +526,7 @@ func (c *Controller) securityGroupAllNotExist(sgs []string) (bool, error) { notExistsCount := 0 // sgs format: sg1/sg2/sg3 for _, sg := range sgs { - ok, err := c.ovnNbClient.PortGroupExists(ovs.GetSgPortGroupName(sg)) + ok, err := c.OVNNbClient.PortGroupExists(ovs.GetSgPortGroupName(sg)) if err != nil { klog.Error(err) return true, err diff --git a/pkg/controller/service.go b/pkg/controller/service.go index 044b91e2482..c41ed3fee30 100644 --- a/pkg/controller/service.go +++ b/pkg/controller/service.go @@ -26,7 +26,6 @@ type vpcService struct { } func (c *Controller) enqueueAddService(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -94,16 +93,16 @@ func (c *Controller) enqueueDeleteService(obj interface{}) { } } -func (c *Controller) enqueueUpdateService(old, new interface{}) { - oldSvc := old.(*v1.Service) - newSvc := new.(*v1.Service) +func (c *Controller) enqueueUpdateService(oldObj, newObj interface{}) { + oldSvc := oldObj.(*v1.Service) + newSvc := newObj.(*v1.Service) if oldSvc.ResourceVersion == newSvc.ResourceVersion { return } var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } @@ -111,9 +110,9 @@ func (c *Controller) enqueueUpdateService(old, new interface{}) { oldClusterIps := getVipIps(oldSvc) newClusterIps := getVipIps(newSvc) var ipsToDel []string - for _, oldClusterIp := range oldClusterIps { - if !util.ContainsString(newClusterIps, oldClusterIp) { - ipsToDel = append(ipsToDel, oldClusterIp) + for _, oldClusterIP := range oldClusterIps { + if !util.ContainsString(newClusterIps, oldClusterIP) { + ipsToDel = append(ipsToDel, oldClusterIP) } } @@ -163,7 +162,6 @@ func (c *Controller) processNextAddServiceWorkItem() bool { c.addServiceQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -194,7 +192,6 @@ func (c *Controller) processNextDeleteServiceWorkItem() bool { c.deleteServiceQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -225,7 +222,6 @@ func (c *Controller) processNextUpdateServiceWorkItem() bool { c.updateServiceQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -255,9 +251,9 @@ func (c *Controller) handleDeleteService(service *vpcService) error { var vpcLB [2]string switch service.Protocol { case v1.ProtocolTCP: - vpcLB = [2]string{vpcLbConfig.TcpLoadBalancer, vpcLbConfig.TcpSessLoadBalancer} + vpcLB = [2]string{vpcLbConfig.TCPLoadBalancer, vpcLbConfig.TCPSessLoadBalancer} case v1.ProtocolUDP: - vpcLB = [2]string{vpcLbConfig.UdpLoadBalancer, vpcLbConfig.UdpSessLoadBalancer} + vpcLB = [2]string{vpcLbConfig.UDPLoadBalancer, vpcLbConfig.UDPSessLoadBalancer} case v1.ProtocolSCTP: vpcLB = [2]string{vpcLbConfig.SctpLoadBalancer, vpcLbConfig.SctpSessLoadBalancer} } @@ -276,7 +272,7 @@ func (c *Controller) handleDeleteService(service *vpcService) error { } for _, lb := range vpcLB { - if err := c.ovnNbClient.LoadBalancerDeleteVip(lb, vip); err != nil { + if err := c.OVNNbClient.LoadBalancerDeleteVip(lb, vip); err != nil { klog.Errorf("failed to delete vip %s from LB %s: %v", vip, lb, err) return err } @@ -334,10 +330,10 @@ func (c *Controller) handleUpdateService(key string) error { return err } - tcpLb, udpLb, sctpLb := vpc.Status.TcpLoadBalancer, vpc.Status.UdpLoadBalancer, vpc.Status.SctpLoadBalancer - oTcpLb, oUdpLb, oSctpLb := vpc.Status.TcpSessionLoadBalancer, vpc.Status.UdpSessionLoadBalancer, vpc.Status.SctpSessionLoadBalancer + tcpLb, udpLb, sctpLb := vpc.Status.TCPLoadBalancer, vpc.Status.UDPLoadBalancer, vpc.Status.SctpLoadBalancer + oTCPLb, oUDPLb, oSctpLb := vpc.Status.TCPSessionLoadBalancer, vpc.Status.UDPSessionLoadBalancer, vpc.Status.SctpSessionLoadBalancer if svc.Spec.SessionAffinity == v1.ServiceAffinityClientIP { - tcpLb, udpLb, sctpLb, oTcpLb, oUdpLb, oSctpLb = oTcpLb, oUdpLb, oSctpLb, tcpLb, udpLb, sctpLb + tcpLb, udpLb, sctpLb, oTCPLb, oUDPLb, oSctpLb = oTCPLb, oUDPLb, oSctpLb, tcpLb, udpLb, sctpLb } var tcpVips, udpVips, sctpVips []string @@ -360,14 +356,14 @@ func (c *Controller) handleUpdateService(key string) error { return nil } - lb, err := c.ovnNbClient.GetLoadBalancer(lbName, false) + lb, err := c.OVNNbClient.GetLoadBalancer(lbName, false) if err != nil { klog.Errorf("failed to get LB %s: %v", lbName, err) return err } klog.V(3).Infof("existing vips of LB %s: %v", lbName, lb.Vips) for _, vip := range svcVips { - if err := c.ovnNbClient.LoadBalancerDeleteVip(oLbName, vip); err != nil { + if err := c.OVNNbClient.LoadBalancerDeleteVip(oLbName, vip); err != nil { klog.Errorf("failed to delete vip %s from LB %s: %v", vip, oLbName, err) return err } @@ -382,7 +378,7 @@ func (c *Controller) handleUpdateService(key string) error { for vip := range lb.Vips { if ip := parseVipAddr(vip); (util.ContainsString(ips, ip) && !util.IsStringIn(vip, svcVips)) || util.ContainsString(ipsToDel, ip) { klog.Infof("remove stale vip %s from LB %s", vip, lb) - if err := c.ovnNbClient.LoadBalancerDeleteVip(lbName, vip); err != nil { + if err := c.OVNNbClient.LoadBalancerDeleteVip(lbName, vip); err != nil { klog.Errorf("failed to delete vip %s from LB %s: %v", vip, lb, err) return err } @@ -393,7 +389,7 @@ func (c *Controller) handleUpdateService(key string) error { return nil } - oLb, err := c.ovnNbClient.GetLoadBalancer(oLbName, false) + oLb, err := c.OVNNbClient.GetLoadBalancer(oLbName, false) if err != nil { klog.Errorf("failed to get LB %s: %v", oLbName, err) return err @@ -402,7 +398,7 @@ func (c *Controller) handleUpdateService(key string) error { for vip := range oLb.Vips { if ip := parseVipAddr(vip); util.ContainsString(ips, ip) || util.ContainsString(ipsToDel, ip) { klog.Infof("remove stale vip %s from LB %s", vip, oLbName) - if err = c.ovnNbClient.LoadBalancerDeleteVip(oLbName, vip); err != nil { + if err = c.OVNNbClient.LoadBalancerDeleteVip(oLbName, vip); err != nil { klog.Errorf("failed to delete vip %s from LB %s: %v", vip, oLbName, err) return err } @@ -411,10 +407,10 @@ func (c *Controller) handleUpdateService(key string) error { return nil } - if err = updateVip(tcpLb, oTcpLb, tcpVips); err != nil { + if err = updateVip(tcpLb, oTCPLb, tcpVips); err != nil { return err } - if err = updateVip(udpLb, oUdpLb, udpVips); err != nil { + if err = updateVip(udpLb, oUDPLb, udpVips); err != nil { return err } if err = updateVip(sctpLb, oSctpLb, sctpVips); err != nil { diff --git a/pkg/controller/service_lb.go b/pkg/controller/service_lb.go index db318a73a7c..7e819f7cb9e 100644 --- a/pkg/controller/service_lb.go +++ b/pkg/controller/service_lb.go @@ -18,11 +18,11 @@ import ( ) const ( - INIT_ROUTE_TABLE = "init" - POD_EIP_ADD = "eip-add" - POD_DNAT_ADD = "dnat-add" - ATTACHMENT_NAME = "lb-svc-attachment" - ATTACHMENT_NS = "kube-system" + initRouteTable = "init" + podEIPAdd = "eip-add" + podDNATAdd = "dnat-add" + attachmentName = "lb-svc-attachment" + attachmentNs = "kube-system" ) func genLbSvcDpName(name string) string { @@ -30,7 +30,7 @@ func genLbSvcDpName(name string) string { } func getAttachNetworkProvider(svc *corev1.Service) string { - providerName := fmt.Sprintf("%s.%s", ATTACHMENT_NAME, ATTACHMENT_NS) + providerName := fmt.Sprintf("%s.%s", attachmentName, attachmentNs) if svc.Annotations[util.AttachmentProvider] != "" { providerName = svc.Annotations[util.AttachmentProvider] } @@ -84,13 +84,13 @@ func (c *Controller) genLbSvcDeployment(svc *corev1.Service) (dp *v1.Deployment) attachmentName, attachmentNs := parseAttachNetworkProvider(svc) providerName := getAttachNetworkProvider(svc) attachSubnetAnnotation := fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, providerName) - attachIpAnnotation := fmt.Sprintf(util.IpAddressAnnotationTemplate, providerName) + attachIPAnnotation := fmt.Sprintf(util.IPAddressAnnotationTemplate, providerName) podAnnotations := map[string]string{ util.AttachmentNetworkAnnotation: fmt.Sprintf("%s/%s", attachmentNs, attachmentName), attachSubnetAnnotation: svc.Annotations[attachSubnetAnnotation], } if svc.Spec.LoadBalancerIP != "" { - podAnnotations[attachIpAnnotation] = svc.Spec.LoadBalancerIP + podAnnotations[attachIPAnnotation] = svc.Spec.LoadBalancerIP } if v, ok := svc.Annotations[util.LogicalSwitchAnnotation]; ok { podAnnotations[util.LogicalSwitchAnnotation] = v @@ -138,13 +138,13 @@ func (c *Controller) updateLbSvcDeployment(svc *corev1.Service, dp *v1.Deploymen attachmentName, attachmentNs := parseAttachNetworkProvider(svc) providerName := getAttachNetworkProvider(svc) attachSubnetAnnotation := fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, providerName) - attachIpAnnotation := fmt.Sprintf(util.IpAddressAnnotationTemplate, providerName) + attachIPAnnotation := fmt.Sprintf(util.IPAddressAnnotationTemplate, providerName) podAnnotations := map[string]string{ util.AttachmentNetworkAnnotation: fmt.Sprintf("%s/%s", attachmentNs, attachmentName), attachSubnetAnnotation: svc.Annotations[attachSubnetAnnotation], } if svc.Spec.LoadBalancerIP != "" { - podAnnotations[attachIpAnnotation] = svc.Spec.LoadBalancerIP + podAnnotations[attachIPAnnotation] = svc.Spec.LoadBalancerIP } dp.Spec.Template.Annotations = podAnnotations @@ -186,16 +186,17 @@ func (c *Controller) getLbSvcPod(svcName, svcNamespace string) (*corev1.Pod, err }) pods, err := c.podsLister.Pods(svcNamespace).List(sel) - if err != nil { + switch { + case err != nil: klog.Error(err) return nil, err - } else if len(pods) == 0 { + case len(pods) == 0: time.Sleep(2 * time.Second) return nil, fmt.Errorf("pod '%s' not exist", genLbSvcDpName(svcName)) - } else if len(pods) != 1 { + case len(pods) != 1: time.Sleep(2 * time.Second) return nil, fmt.Errorf("too many pod") - } else if pods[0].Status.Phase != "Running" { + case pods[0].Status.Phase != "Running": time.Sleep(2 * time.Second) return nil, fmt.Errorf("pod is not active now") } @@ -232,10 +233,10 @@ func (c *Controller) getPodAttachIP(pod *corev1.Pod, svc *corev1.Service) (strin var err error providerName := getAttachNetworkProvider(svc) - attachIpAnnotation := fmt.Sprintf(util.IpAddressAnnotationTemplate, providerName) + attachIPAnnotation := fmt.Sprintf(util.IPAddressAnnotationTemplate, providerName) - if pod.Annotations[attachIpAnnotation] != "" { - loadBalancerIP = pod.Annotations[attachIpAnnotation] + if pod.Annotations[attachIPAnnotation] != "" { + loadBalancerIP = pod.Annotations[attachIPAnnotation] } else { err = fmt.Errorf("failed to get attachment ip from pod's annotation") } @@ -247,10 +248,9 @@ func (c *Controller) deleteLbSvc(svc *corev1.Service) error { if err := c.config.KubeClient.AppsV1().Deployments(svc.Namespace).Delete(context.Background(), genLbSvcDpName(svc.Name), metav1.DeleteOptions{}); err != nil { if k8serrors.IsNotFound(err) { return nil - } else { - klog.Errorf("failed to delete deployment %s, err: %v", genLbSvcDpName(svc.Name), err) - return err } + klog.Errorf("failed to delete deployment %s, err: %v", genLbSvcDpName(svc.Name), err) + return err } return nil @@ -260,7 +260,6 @@ func (c *Controller) execNatRules(pod *corev1.Pod, operation string, rules []str cmd := fmt.Sprintf("bash /kube-ovn/lb-svc.sh %s %s", operation, strings.Join(rules, " ")) klog.V(3).Infof(cmd) stdOutput, errOutput, err := util.ExecuteCommandInContainer(c.config.KubeClient, c.config.KubeRestConfig, pod.Namespace, pod.Name, "lb-svc", []string{"/bin/bash", "-c", cmd}...) - if err != nil { if len(errOutput) > 0 { klog.Errorf("failed to ExecuteCommandInContainer, errOutput: %v", errOutput) @@ -284,13 +283,13 @@ func (c *Controller) execNatRules(pod *corev1.Pod, operation string, rules []str } func (c *Controller) updatePodAttachNets(pod *corev1.Pod, svc *corev1.Service) error { - if err := c.execNatRules(pod, INIT_ROUTE_TABLE, []string{}); err != nil { + if err := c.execNatRules(pod, initRouteTable, []string{}); err != nil { klog.Errorf("failed to init route table, err: %v", err) return err } providerName := getAttachNetworkProvider(svc) - attachIpAnnotation := fmt.Sprintf(util.IpAddressAnnotationTemplate, providerName) + attachIPAnnotation := fmt.Sprintf(util.IPAddressAnnotationTemplate, providerName) attachCidrAnnotation := fmt.Sprintf(util.CidrAnnotationTemplate, providerName) attachGatewayAnnotation := fmt.Sprintf(util.GatewayAnnotationTemplate, providerName) @@ -298,13 +297,13 @@ func (c *Controller) updatePodAttachNets(pod *corev1.Pod, svc *corev1.Service) e return fmt.Errorf("failed to get attachment network info for pod %s", pod.Name) } - loadBalancerIP := pod.Annotations[attachIpAnnotation] - ipAddr := util.GetIpAddrWithMask(loadBalancerIP, pod.Annotations[attachCidrAnnotation]) + loadBalancerIP := pod.Annotations[attachIPAnnotation] + ipAddr := util.GetIPAddrWithMask(loadBalancerIP, pod.Annotations[attachCidrAnnotation]) var addRules []string addRules = append(addRules, fmt.Sprintf("%s,%s", ipAddr, pod.Annotations[attachGatewayAnnotation])) klog.Infof("add eip rules for lb svc pod, %v", addRules) - if err := c.execNatRules(pod, POD_EIP_ADD, addRules); err != nil { + if err := c.execNatRules(pod, podEIPAdd, addRules); err != nil { klog.Errorf("failed to add eip for pod, err: %v", err) return err } @@ -324,7 +323,7 @@ func (c *Controller) updatePodAttachNets(pod *corev1.Pod, svc *corev1.Service) e var rules []string rules = append(rules, fmt.Sprintf("%s,%d,%s,%s,%d,%s", loadBalancerIP, port.Port, protocol, svc.Spec.ClusterIP, port.Port, defaultGateway)) klog.Infof("add dnat rules for lb svc pod, %v", rules) - if err := c.execNatRules(pod, POD_DNAT_ADD, rules); err != nil { + if err := c.execNatRules(pod, podDNATAdd, rules); err != nil { klog.Errorf("failed to add dnat for pod, err: %v", err) return err } diff --git a/pkg/controller/subnet.go b/pkg/controller/subnet.go index f02fa6cf684..e41d8f42eaa 100644 --- a/pkg/controller/subnet.go +++ b/pkg/controller/subnet.go @@ -28,7 +28,6 @@ import ( ) func (c *Controller) enqueueAddSubnet(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -40,7 +39,6 @@ func (c *Controller) enqueueAddSubnet(obj interface{}) { } func (c *Controller) enqueueDeleteSubnet(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -51,13 +49,13 @@ func (c *Controller) enqueueDeleteSubnet(obj interface{}) { c.deleteSubnetQueue.Add(obj) } -func (c *Controller) enqueueUpdateSubnet(old, new interface{}) { - oldSubnet := old.(*kubeovnv1.Subnet) - newSubnet := new.(*kubeovnv1.Subnet) +func (c *Controller) enqueueUpdateSubnet(oldObj, newObj interface{}) { + oldSubnet := oldObj.(*kubeovnv1.Subnet) + newSubnet := newObj.(*kubeovnv1.Subnet) var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } @@ -166,7 +164,6 @@ func (c *Controller) processNextSyncVirtualPortsWorkItem() bool { c.syncVirtualPortsQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -196,7 +193,6 @@ func (c *Controller) processNextAddSubnetWorkItem() bool { c.addOrUpdateSubnetQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -226,7 +222,6 @@ func (c *Controller) processNextUpdateSubnetStatusWorkItem() bool { c.updateSubnetStatusQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -256,7 +251,6 @@ func (c *Controller) processNextDeleteSubnetWorkItem() bool { c.deleteSubnetQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -411,11 +405,12 @@ func checkAndUpdateGateway(subnet *kubeovnv1.Subnet) (bool, error) { changed := false var gw string var err error - if subnet.Spec.Gateway == "" { + switch { + case subnet.Spec.Gateway == "": gw, err = util.GetGwByCidr(subnet.Spec.CIDRBlock) - } else if util.CheckProtocol(subnet.Spec.Gateway) != util.CheckProtocol(subnet.Spec.CIDRBlock) { + case util.CheckProtocol(subnet.Spec.Gateway) != util.CheckProtocol(subnet.Spec.CIDRBlock): gw, err = util.AppendGwByCidr(subnet.Spec.Gateway, subnet.Spec.CIDRBlock) - } else { + default: gw = subnet.Spec.Gateway } if err != nil { @@ -488,7 +483,7 @@ func (c *Controller) handleSubnetFinalizer(subnet *kubeovnv1.Subnet) (bool, erro return false, nil } -func (c Controller) patchSubnetStatus(subnet *kubeovnv1.Subnet, reason string, errStr string) { +func (c Controller) patchSubnetStatus(subnet *kubeovnv1.Subnet, reason, errStr string) { if errStr != "" { subnet.Status.SetError(reason, errStr) subnet.Status.NotValidated(reason, errStr) @@ -619,7 +614,7 @@ func (c *Controller) updateSubnetDHCPOption(subnet *kubeovnv1.Subnet, needRouter } } - dhcpOptionsUUIDs, err := c.ovnNbClient.UpdateDHCPOptions(subnet, mtu) + dhcpOptionsUUIDs, err := c.OVNNbClient.UpdateDHCPOptions(subnet, mtu) if err != nil { klog.Errorf("failed to update dhcp options for switch %s, %v", subnet.Name, err) return err @@ -633,7 +628,7 @@ func (c *Controller) updateSubnetDHCPOption(subnet *kubeovnv1.Subnet, needRouter if needRouter { lrpName := fmt.Sprintf("%s-%s", vpc.Status.Router, subnet.Name) - if err := c.ovnNbClient.UpdateLogicalRouterPortRA(lrpName, subnet.Spec.IPv6RAConfigs, subnet.Spec.EnableIPv6RA); err != nil { + if err := c.OVNNbClient.UpdateLogicalRouterPortRA(lrpName, subnet.Spec.IPv6RAConfigs, subnet.Spec.EnableIPv6RA); err != nil { klog.Errorf("update ipv6 ra configs for logical router port %s, %v", lrpName, err) return err } @@ -646,11 +641,10 @@ func (c *Controller) updateSubnetDHCPOption(subnet *kubeovnv1.Subnet, needRouter if err != nil { klog.Error(err) return err - } else { - if _, err := c.config.KubeOvnClient.KubeovnV1().Subnets().Patch(context.Background(), subnet.Name, types.MergePatchType, bytes, metav1.PatchOptions{}, "status"); err != nil { - klog.Error("patch subnet %s dhcp options failed: %v", subnet.Name, err) - return err - } + } + if _, err := c.config.KubeOvnClient.KubeovnV1().Subnets().Patch(context.Background(), subnet.Name, types.MergePatchType, bytes, metav1.PatchOptions{}, "status"); err != nil { + klog.Error("patch subnet %s dhcp options failed: %v", subnet.Name, err) + return err } } @@ -690,9 +684,8 @@ func (c *Controller) handleAddOrUpdateSubnet(key string) error { klog.Errorf("failed to validate subnet %s, %v", subnet.Name, err) c.patchSubnetStatus(subnet, "ValidateLogicalSwitchFailed", err.Error()) return err - } else { - c.patchSubnetStatus(subnet, "ValidateLogicalSwitchSuccess", "") } + c.patchSubnetStatus(subnet, "ValidateLogicalSwitchSuccess", "") if subnet.Spec.Protocol == kubeovnv1.ProtocolDual { err = calcDualSubnetStatusIP(subnet, c) @@ -754,19 +747,19 @@ func (c *Controller) handleAddOrUpdateSubnet(key string) error { } // create or update logical switch - if err := c.ovnNbClient.CreateLogicalSwitch(subnet.Name, vpc.Status.Router, subnet.Spec.CIDRBlock, gateway, needRouter, randomAllocateGW); err != nil { + if err := c.OVNNbClient.CreateLogicalSwitch(subnet.Name, vpc.Status.Router, subnet.Spec.CIDRBlock, gateway, needRouter, randomAllocateGW); err != nil { klog.Errorf("create logical switch %s: %v", subnet.Name, err) return err } multicastSnoopFlag := map[string]string{"mcast_snoop": "true", "mcast_querier": "false"} if subnet.Spec.EnableMulicastSnoop { - if err := c.ovnNbClient.LogicalSwitchUpdateOtherConfig(subnet.Name, ovsdb.MutateOperationInsert, multicastSnoopFlag); err != nil { + if err := c.OVNNbClient.LogicalSwitchUpdateOtherConfig(subnet.Name, ovsdb.MutateOperationInsert, multicastSnoopFlag); err != nil { klog.Errorf("enable logical switch multicast snoop %s: %v", subnet.Name, err) return err } } else { - if err := c.ovnNbClient.LogicalSwitchUpdateOtherConfig(subnet.Name, ovsdb.MutateOperationDelete, multicastSnoopFlag); err != nil { + if err := c.OVNNbClient.LogicalSwitchUpdateOtherConfig(subnet.Name, ovsdb.MutateOperationDelete, multicastSnoopFlag); err != nil { klog.Errorf("disable logical switch multicast snoop %s: %v", subnet.Name, err) return err } @@ -781,20 +774,20 @@ func (c *Controller) handleAddOrUpdateSubnet(key string) error { if c.config.EnableLb && subnet.Name != c.config.NodeSwitch { lbs := []string{ - vpc.Status.TcpLoadBalancer, - vpc.Status.TcpSessionLoadBalancer, - vpc.Status.UdpLoadBalancer, - vpc.Status.UdpSessionLoadBalancer, + vpc.Status.TCPLoadBalancer, + vpc.Status.TCPSessionLoadBalancer, + vpc.Status.UDPLoadBalancer, + vpc.Status.UDPSessionLoadBalancer, vpc.Status.SctpLoadBalancer, vpc.Status.SctpSessionLoadBalancer, } if subnet.Spec.EnableLb != nil && *subnet.Spec.EnableLb { - if err := c.ovnNbClient.LogicalSwitchUpdateLoadBalancers(subnet.Name, ovsdb.MutateOperationInsert, lbs...); err != nil { + if err := c.OVNNbClient.LogicalSwitchUpdateLoadBalancers(subnet.Name, ovsdb.MutateOperationInsert, lbs...); err != nil { c.patchSubnetStatus(subnet, "AddLbToLogicalSwitchFailed", err.Error()) return err } } else { - if err := c.ovnNbClient.LogicalSwitchUpdateLoadBalancers(subnet.Name, ovsdb.MutateOperationDelete, lbs...); err != nil { + if err := c.OVNNbClient.LogicalSwitchUpdateLoadBalancers(subnet.Name, ovsdb.MutateOperationDelete, lbs...); err != nil { klog.Error("remove load-balancer from subnet %s failed: %v", subnet.Name, err) return err } @@ -817,7 +810,7 @@ func (c *Controller) handleAddOrUpdateSubnet(key string) error { } if subnet.Spec.Private { - if err := c.ovnNbClient.SetLogicalSwitchPrivate(subnet.Name, subnet.Spec.CIDRBlock, c.config.NodeSwitchCIDR, subnet.Spec.AllowSubnets); err != nil { + if err := c.OVNNbClient.SetLogicalSwitchPrivate(subnet.Name, subnet.Spec.CIDRBlock, c.config.NodeSwitchCIDR, subnet.Spec.AllowSubnets); err != nil { c.patchSubnetStatus(subnet, "SetPrivateLogicalSwitchFailed", err.Error()) return err } @@ -825,7 +818,7 @@ func (c *Controller) handleAddOrUpdateSubnet(key string) error { c.patchSubnetStatus(subnet, "SetPrivateLogicalSwitchSuccess", "") } else { // clear acl when direction is "" - if err = c.ovnNbClient.DeleteAcls(subnet.Name, logicalSwitchKey, "", nil); err != nil { + if err = c.OVNNbClient.DeleteAcls(subnet.Name, logicalSwitchKey, "", nil); err != nil { c.patchSubnetStatus(subnet, "ResetLogicalSwitchAclFailed", err.Error()) return err } @@ -833,7 +826,7 @@ func (c *Controller) handleAddOrUpdateSubnet(key string) error { c.patchSubnetStatus(subnet, "ResetLogicalSwitchAclSuccess", "") } - if err := c.ovnNbClient.UpdateLogicalSwitchAcl(subnet.Name, subnet.Spec.Acls); err != nil { + if err := c.OVNNbClient.UpdateLogicalSwitchACL(subnet.Name, subnet.Spec.Acls); err != nil { c.patchSubnetStatus(subnet, "SetLogicalSwitchAclsFailed", err.Error()) return err } @@ -882,15 +875,14 @@ func (c *Controller) handleUpdateSubnetStatus(key string) error { if util.CheckProtocol(subnet.Spec.CIDRBlock) == kubeovnv1.ProtocolDual { return calcDualSubnetStatusIP(subnet, c) - } else { - return calcSubnetStatusIP(subnet, c) } + return calcSubnetStatusIP(subnet, c) } func (c *Controller) handleDeleteLogicalSwitch(key string) (err error) { c.ipam.DeleteSubnet(key) - exist, err := c.ovnNbClient.LogicalSwitchExists(key) + exist, err := c.OVNNbClient.LogicalSwitchExists(key) if err != nil { klog.Errorf("check logical switch %s exist: %v", key, err) return err @@ -902,17 +894,17 @@ func (c *Controller) handleDeleteLogicalSwitch(key string) (err error) { } // clear acl when direction is "" - if err = c.ovnNbClient.DeleteAcls(key, logicalSwitchKey, "", nil); err != nil { + if err = c.OVNNbClient.DeleteAcls(key, logicalSwitchKey, "", nil); err != nil { klog.Errorf("clear logical switch %s acls: %v", key, err) return err } - if err = c.ovnNbClient.DeleteDHCPOptions(key, kubeovnv1.ProtocolDual); err != nil { + if err = c.OVNNbClient.DeleteDHCPOptions(key, kubeovnv1.ProtocolDual); err != nil { klog.Errorf("failed to delete dhcp options of logical switch %s %v", key, err) return err } - if err = c.ovnNbClient.DeleteLogicalSwitch(key); err != nil { + if err = c.OVNNbClient.DeleteLogicalSwitch(key); err != nil { klog.Errorf("delete logical switch %s: %v", key, err) return err } @@ -990,7 +982,7 @@ func (c *Controller) handleDeleteSubnet(subnet *kubeovnv1.Subnet) error { lspName := fmt.Sprintf("%s-%s", subnet.Name, router) lrpName := fmt.Sprintf("%s-%s", router, subnet.Name) - if err = c.ovnNbClient.RemoveLogicalPatchPort(lspName, lrpName); err != nil { + if err = c.OVNNbClient.RemoveLogicalPatchPort(lspName, lrpName); err != nil { klog.Errorf("delete router port %s and %s:%v", lspName, lrpName, err) return err } @@ -1065,10 +1057,9 @@ func (c *Controller) reconcileSubnet(subnet *kubeovnv1.Subnet) error { func (c *Controller) reconcileVips(subnet *kubeovnv1.Subnet) error { /* get all virtual port belongs to this logical switch */ - lsps, err := c.ovnNbClient.ListLogicalSwitchPorts(true, map[string]string{logicalSwitchKey: subnet.Name}, func(lsp *ovnnb.LogicalSwitchPort) bool { + lsps, err := c.OVNNbClient.ListLogicalSwitchPorts(true, map[string]string{logicalSwitchKey: subnet.Name}, func(lsp *ovnnb.LogicalSwitchPort) bool { return lsp.Type == "virtual" }) - if err != nil { klog.Errorf("failed to find virtual port for subnet %s: %v", subnet.Name, err) return err @@ -1103,14 +1094,14 @@ func (c *Controller) reconcileVips(subnet *kubeovnv1.Subnet) error { // delete old virtual ports for _, lspName := range existVips { - if err = c.ovnNbClient.DeleteLogicalSwitchPort(lspName); err != nil { + if err = c.OVNNbClient.DeleteLogicalSwitchPort(lspName); err != nil { klog.Errorf("delete virtual port %s lspName from logical switch %s: %v", lspName, subnet.Name, err) return err } } // add new virtual port - if err = c.ovnNbClient.CreateVirtualLogicalSwitchPorts(subnet.Name, newVips...); err != nil { + if err = c.OVNNbClient.CreateVirtualLogicalSwitchPorts(subnet.Name, newVips...); err != nil { klog.Errorf("create virtual port with vips %v from logical switch %s: %v", newVips, subnet.Name, err) return err } @@ -1124,10 +1115,9 @@ func (c *Controller) syncVirtualPort(key string) error { if err != nil { if k8serrors.IsNotFound(err) { return nil - } else { - klog.Errorf("failed to get subnet %s, %v", key, err) - return err } + klog.Errorf("failed to get subnet %s, %v", key, err) + return err } if len(subnet.Spec.Vips) == 0 { return nil @@ -1138,7 +1128,7 @@ func (c *Controller) syncVirtualPort(key string) error { "attach-vips": "true", } - lsps, err := c.ovnNbClient.ListNormalLogicalSwitchPorts(true, externalIDs) + lsps, err := c.OVNNbClient.ListNormalLogicalSwitchPorts(true, externalIDs) if err != nil { klog.Errorf("list logical switch %s ports: %v", subnet.Name, err) return err @@ -1167,7 +1157,7 @@ func (c *Controller) syncVirtualPort(key string) error { continue } - if err = c.ovnNbClient.SetLogicalSwitchPortVirtualParents(subnet.Name, strings.Join(virtualParents, ","), vip); err != nil { + if err = c.OVNNbClient.SetLogicalSwitchPortVirtualParents(subnet.Name, strings.Join(virtualParents, ","), vip); err != nil { klog.Errorf("set vip %s virtual parents %v: %v", vip, virtualParents, err) return err } @@ -1248,7 +1238,7 @@ func (c *Controller) reconcileCustomVpcBfdStaticRoute(vpcName, subnetName string klog.Error(err) return err } - bfd, err := c.ovnNbClient.CreateBFD(lrpEipName, eip.Status.V4Ip, c.config.BfdMinRx, c.config.BfdMinTx, c.config.BfdDetectMult) + bfd, err := c.OVNNbClient.CreateBFD(lrpEipName, eip.Status.V4Ip, c.config.BfdMinRx, c.config.BfdMinTx, c.config.BfdDetectMult) if err != nil { klog.Error(err) return err @@ -1272,7 +1262,7 @@ func (c *Controller) reconcileCustomVpcBfdStaticRoute(vpcName, subnetName string CIDR: subnet.Spec.CIDRBlock, NextHopIP: eip.Status.V4Ip, ECMPMode: util.StaticRouteBfdEcmp, - BfdId: bfd.UUID, + BfdID: bfd.UUID, RouteTable: subnet.Spec.RouteTable, } klog.Infof("add ecmp bfd static route %v", route) @@ -1489,15 +1479,15 @@ func (c *Controller) reconcileDistributedSubnetRouteInDefaultVpc(subnet *kubeovn continue } - if pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)] == "" || pod.Annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, podNet.ProviderName)] != subnet.Name { + if pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)] == "" || pod.Annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, podNet.ProviderName)] != subnet.Name { continue } if pod.Annotations[util.NorthGatewayAnnotation] != "" { nextHop := pod.Annotations[util.NorthGatewayAnnotation] - if err := c.ovnNbClient.AddLogicalRouterStaticRoute( + if err := c.OVNNbClient.AddLogicalRouterStaticRoute( c.config.ClusterRouter, util.MainRouteTable, ovnnb.LogicalRouterStaticRoutePolicySrcIP, - pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podNet.ProviderName)], nil, nextHop, + pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podNet.ProviderName)], nil, nextHop, ); err != nil { klog.Errorf("add static route failed, %v", err) return err @@ -1516,7 +1506,7 @@ func (c *Controller) reconcileDistributedSubnetRouteInDefaultVpc(subnet *kubeovn pgName := getOverlaySubnetsPortGroupName(subnet.Name, pod.Spec.NodeName) portsToAdd := make([]string, 0, len(podPorts)) for _, port := range podPorts { - exist, err := c.ovnNbClient.LogicalSwitchPortExists(port) + exist, err := c.OVNNbClient.LogicalSwitchPortExists(port) if err != nil { klog.Error(err) return err @@ -1530,7 +1520,7 @@ func (c *Controller) reconcileDistributedSubnetRouteInDefaultVpc(subnet *kubeovn portsToAdd = append(portsToAdd, port) } - if err = c.ovnNbClient.PortGroupAddPorts(pgName, portsToAdd...); err != nil { + if err = c.OVNNbClient.PortGroupAddPorts(pgName, portsToAdd...); err != nil { klog.Errorf("add ports to port group %s: %v", pgName, err) return err } @@ -1630,7 +1620,7 @@ func (c *Controller) reconcileEcmpCentralizedSubnetRouteInDefaultVpc(subnet *kub } if nodeReady(node) { - nexthopNodeIP := strings.TrimSpace(node.Annotations[util.IpAddressAnnotation]) + nexthopNodeIP := strings.TrimSpace(node.Annotations[util.IPAddressAnnotation]) if nexthopNodeIP == "" { klog.Errorf("gateway node %v has no ip annotation", node.Name) continue @@ -1694,9 +1684,9 @@ func (c *Controller) reconcileOvnDefaultVpcRoute(subnet *kubeovnv1.Subnet) error return err } for _, pod := range pods { - if pod.Annotations[util.LogicalSwitchAnnotation] == subnet.Name && pod.Annotations[util.IpAddressAnnotation] != "" { + if pod.Annotations[util.LogicalSwitchAnnotation] == subnet.Name && pod.Annotations[util.IPAddressAnnotation] != "" { if err := c.deleteStaticRoute( - pod.Annotations[util.IpAddressAnnotation], c.config.ClusterRouter, subnet.Spec.RouteTable); err != nil { + pod.Annotations[util.IPAddressAnnotation], c.config.ClusterRouter, subnet.Spec.RouteTable); err != nil { klog.Errorf("failed to delete static route %v", err) return err } @@ -1706,13 +1696,13 @@ func (c *Controller) reconcileOvnDefaultVpcRoute(subnet *kubeovnv1.Subnet) error if !subnet.Spec.LogicalGateway && subnet.Name != c.config.ExternalGatewaySwitch && !subnet.Spec.U2OInterconnection { lspName := fmt.Sprintf("%s-%s", subnet.Name, c.config.ClusterRouter) klog.Infof("delete logical switch port %s", lspName) - if err := c.ovnNbClient.DeleteLogicalSwitchPort(lspName); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(lspName); err != nil { klog.Errorf("failed to delete lsp %s-%s, %v", subnet.Name, c.config.ClusterRouter, err) return err } lrpName := fmt.Sprintf("%s-%s", c.config.ClusterRouter, subnet.Name) klog.Infof("delete logical router port %s", lrpName) - if err := c.ovnNbClient.DeleteLogicalRouterPort(lrpName); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPort(lrpName); err != nil { klog.Errorf("failed to delete lrp %s: %v", lrpName, err) return err } @@ -1826,7 +1816,7 @@ func (c *Controller) reconcileCustomVpcStaticRoute(subnet *kubeovnv1.Subnet) err func (c *Controller) deleteStaticRoute(ip, router, routeTable string) error { for _, ipStr := range strings.Split(ip, ",") { - if err := c.ovnNbClient.DeleteLogicalRouterStaticRoute(router, &routeTable, nil, ipStr, ""); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterStaticRoute(router, &routeTable, nil, ipStr, ""); err != nil { klog.Errorf("failed to delete static route %s, %v", ipStr, err) return err } @@ -1854,7 +1844,7 @@ func (c *Controller) reconcileVlan(subnet *kubeovnv1.Subnet) error { } localnetPort := ovs.GetLocalnetName(subnet.Name) - if err := c.ovnNbClient.CreateLocalnetLogicalSwitchPort(subnet.Name, localnetPort, vlan.Spec.Provider, vlan.Spec.ID); err != nil { + if err := c.OVNNbClient.CreateLocalnetLogicalSwitchPort(subnet.Name, localnetPort, vlan.Spec.Provider, vlan.Spec.ID); err != nil { klog.Errorf("create localnet port for subnet %s: %v", subnet.Name, err) return err } @@ -1873,7 +1863,6 @@ func (c *Controller) reconcileVlan(subnet *kubeovnv1.Subnet) error { } func (c *Controller) reconcileU2OInterconnectionIP(subnet *kubeovnv1.Subnet) error { - needCalcIP := false if subnet.Spec.U2OInterconnection { u2oInterconnName := fmt.Sprintf(util.U2OInterconnName, subnet.Spec.Vpc, subnet.Name) @@ -1881,7 +1870,7 @@ func (c *Controller) reconcileU2OInterconnectionIP(subnet *kubeovnv1.Subnet) err var v4ip, v6ip string var err error if subnet.Spec.U2OInterconnectionIP == "" && subnet.Status.U2OInterconnectionIP == "" { - v4ip, v6ip, _, err = c.acquireIpAddress(subnet.Name, u2oInterconnName, u2oInterconnLrpName) + v4ip, v6ip, _, err = c.acquireIPAddress(subnet.Name, u2oInterconnName, u2oInterconnLrpName) if err != nil { klog.Errorf("failed to acquire underlay to overlay interconnection ip address for subnet %s, %v", subnet.Name, err) return err @@ -1891,7 +1880,7 @@ func (c *Controller) reconcileU2OInterconnectionIP(subnet *kubeovnv1.Subnet) err c.ipam.ReleaseAddressByPod(u2oInterconnName) } - v4ip, v6ip, _, err = c.acquireStaticIpAddress(subnet.Name, u2oInterconnName, u2oInterconnLrpName, subnet.Spec.U2OInterconnectionIP) + v4ip, v6ip, _, err = c.acquireStaticIPAddress(subnet.Name, u2oInterconnName, u2oInterconnLrpName, subnet.Spec.U2OInterconnectionIP) if err != nil { klog.Errorf("failed to acquire static underlay to overlay interconnection ip address for subnet %s, %v", subnet.Name, err) return err @@ -1914,21 +1903,19 @@ func (c *Controller) reconcileU2OInterconnectionIP(subnet *kubeovnv1.Subnet) err needCalcIP = true } - } else { - if subnet.Status.U2OInterconnectionIP != "" { - u2oInterconnName := fmt.Sprintf(util.U2OInterconnName, subnet.Spec.Vpc, subnet.Name) - c.ipam.ReleaseAddressByPod(u2oInterconnName) - subnet.Status.U2OInterconnectionIP = "" - - if err := c.config.KubeOvnClient.KubeovnV1().IPs().Delete(context.Background(), u2oInterconnName, metav1.DeleteOptions{}); err != nil { - if !k8serrors.IsNotFound(err) { - klog.Errorf("failed to delete ip %s, %v", u2oInterconnName, err) - return err - } - } + } else if subnet.Status.U2OInterconnectionIP != "" { + u2oInterconnName := fmt.Sprintf(util.U2OInterconnName, subnet.Spec.Vpc, subnet.Name) + c.ipam.ReleaseAddressByPod(u2oInterconnName) + subnet.Status.U2OInterconnectionIP = "" - needCalcIP = true + if err := c.config.KubeOvnClient.KubeovnV1().IPs().Delete(context.Background(), u2oInterconnName, metav1.DeleteOptions{}); err != nil { + if !k8serrors.IsNotFound(err) { + klog.Errorf("failed to delete ip %s, %v", u2oInterconnName, err) + return err + } } + + needCalcIP = true } if needCalcIP { @@ -1966,14 +1953,14 @@ func calcDualSubnetStatusIP(subnet *kubeovnv1.Subnet, c *Controller) error { v6toSubIPs := util.ExpandExcludeIPs(v6ExcludeIps, cidrBlocks[1]) _, v4CIDR, _ := net.ParseCIDR(cidrBlocks[0]) _, v6CIDR, _ := net.ParseCIDR(cidrBlocks[1]) - v4availableIPs := util.AddressCount(v4CIDR) - util.CountIpNums(v4toSubIPs) - v6availableIPs := util.AddressCount(v6CIDR) - util.CountIpNums(v6toSubIPs) + v4availableIPs := util.AddressCount(v4CIDR) - util.CountIPNums(v4toSubIPs) + v6availableIPs := util.AddressCount(v6CIDR) - util.CountIPNums(v6toSubIPs) usingIPs := float64(len(podUsedIPs)) vips, err := c.virtualIpsLister.List(labels.SelectorFromSet(labels.Set{ util.SubnetNameLabel: subnet.Name, - util.IpReservedLabel: "", + util.IPReservedLabel: "", })) if err != nil { klog.Error(err) @@ -1990,11 +1977,11 @@ func calcDualSubnetStatusIP(subnet *kubeovnv1.Subnet, c *Controller) error { } usingIPs += float64(len(eips)) } - v4availableIPs = v4availableIPs - usingIPs + v4availableIPs -= usingIPs if v4availableIPs < 0 { v4availableIPs = 0 } - v6availableIPs = v6availableIPs - usingIPs + v6availableIPs -= usingIPs if v6availableIPs < 0 { v6availableIPs = 0 } @@ -2043,11 +2030,11 @@ func calcSubnetStatusIP(subnet *kubeovnv1.Subnet, c *Controller) error { } // gateway always in excludeIPs toSubIPs := util.ExpandExcludeIPs(subnet.Spec.ExcludeIps, subnet.Spec.CIDRBlock) - availableIPs := util.AddressCount(cidr) - util.CountIpNums(toSubIPs) + availableIPs := util.AddressCount(cidr) - util.CountIPNums(toSubIPs) usingIPs := float64(len(podUsedIPs)) vips, err := c.virtualIpsLister.List(labels.SelectorFromSet(labels.Set{ util.SubnetNameLabel: subnet.Name, - util.IpReservedLabel: "", + util.IPReservedLabel: "", })) if err != nil { klog.Error(err) @@ -2064,7 +2051,7 @@ func calcSubnetStatusIP(subnet *kubeovnv1.Subnet, c *Controller) error { usingIPs += float64(len(eips)) } - availableIPs = availableIPs - usingIPs + availableIPs -= usingIPs if availableIPs < 0 { availableIPs = 0 } @@ -2247,7 +2234,7 @@ func (c *Controller) addCommonRoutesForSubnet(subnet *kubeovnv1.Subnet) error { action := ovnnb.LogicalRouterPolicyActionAllow externalIDs := map[string]string{"vendor": util.CniTypeName, "subnet": subnet.Name} klog.Infof("add policy route for router: %s, match %s, action %s, externalID %v", subnet.Spec.Vpc, match, action, externalIDs) - if err := c.ovnNbClient.AddLogicalRouterPolicy(subnet.Spec.Vpc, util.SubnetRouterPolicyPriority, match, action, nil, externalIDs); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(subnet.Spec.Vpc, util.SubnetRouterPolicyPriority, match, action, nil, externalIDs); err != nil { klog.Errorf("failed to add logical router policy for CIDR %s of subnet %s: %v", cidr, subnet.Name, err) return err } @@ -2256,7 +2243,7 @@ func (c *Controller) addCommonRoutesForSubnet(subnet *kubeovnv1.Subnet) error { } func getOverlaySubnetsPortGroupName(subnetName, nodeName string) string { - return strings.Replace(fmt.Sprintf("%s.%s", subnetName, nodeName), "-", ".", -1) + return strings.ReplaceAll(fmt.Sprintf("%s.%s", subnetName, nodeName), "-", ".") } func (c *Controller) createPortGroupForDistributedSubnet(node *v1.Node, subnet *kubeovnv1.Subnet) error { @@ -2268,7 +2255,7 @@ func (c *Controller) createPortGroupForDistributedSubnet(node *v1.Node, subnet * } pgName := getOverlaySubnetsPortGroupName(subnet.Name, node.Name) - if err := c.ovnNbClient.CreatePortGroup(pgName, map[string]string{networkPolicyKey: subnet.Name + "/" + node.Name}); err != nil { + if err := c.OVNNbClient.CreatePortGroup(pgName, map[string]string{networkPolicyKey: subnet.Name + "/" + node.Name}); err != nil { klog.Errorf("create port group for subnet %s and node %s: %v", subnet.Name, node.Name, err) return err } @@ -2276,7 +2263,7 @@ func (c *Controller) createPortGroupForDistributedSubnet(node *v1.Node, subnet * return nil } -func (c *Controller) updatePolicyRouteForCentralizedSubnet(subnetName, cidr string, nextHops []string, nameIpMap map[string]string) error { +func (c *Controller) updatePolicyRouteForCentralizedSubnet(subnetName, cidr string, nextHops []string, nameIPMap map[string]string) error { ipSuffix := "ip4" if util.CheckProtocol(cidr) == kubeovnv1.ProtocolIPv6 { ipSuffix = "ip6" @@ -2293,11 +2280,11 @@ func (c *Controller) updatePolicyRouteForCentralizedSubnet(subnetName, cidr stri } // It's difficult to delete policy route when delete node, // add map nodeName:nodeIP to external_ids to help process when delete node - for node, ip := range nameIpMap { + for node, ip := range nameIPMap { externalIDs[node] = ip } klog.Infof("add policy route for router: %s, match %s, action %s, nexthops %v, extrenalID %s", c.config.ClusterRouter, match, action, nextHops, externalIDs) - if err := c.ovnNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match, action, nextHops, externalIDs); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match, action, nextHops, externalIDs); err != nil { klog.Errorf("failed to add policy route for centralized subnet %s: %v", subnetName, err) return err } @@ -2314,14 +2301,14 @@ func (c *Controller) addPolicyRouteForCentralizedSubnet(subnet *kubeovnv1.Subnet // Check for repeat policy route is processed in AddPolicyRoute var nextHops []string - nameIpMap := map[string]string{} + nameIPMap := map[string]string{} nextHops = append(nextHops, nodeIP) tmpName := nodeName if nodeName == "" { tmpName = ipNameMap[nodeIP] } - nameIpMap[tmpName] = nodeIP - if err := c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops, nameIpMap); err != nil { + nameIPMap[tmpName] = nodeIP + if err := c.updatePolicyRouteForCentralizedSubnet(subnet.Name, cidrBlock, nextHops, nameIPMap); err != nil { return err } } @@ -2337,7 +2324,7 @@ func (c *Controller) deletePolicyRouteForCentralizedSubnet(subnet *kubeovnv1.Sub } match := fmt.Sprintf("%s.src == %s", ipSuffix, cidr) klog.Infof("delete policy route for router: %s, priority: %d, match %s", c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match) - if err := c.ovnNbClient.DeleteLogicalRouterPolicy(c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPolicy(c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match); err != nil { klog.Errorf("failed to delete policy route for centralized subnet %s: %v", subnet.Name, err) return err } @@ -2372,7 +2359,7 @@ func (c *Controller) addPolicyRouteForDistributedSubnet(subnet *kubeovnv1.Subnet "node": nodeName, } klog.Infof("add policy route for router: %s, match %s, action %s, extrenalID %v", c.config.ClusterRouter, match, action, externalIDs) - if err := c.ovnNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match, action, []string{nodeIP}, externalIDs); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match, action, []string{nodeIP}, externalIDs); err != nil { klog.Errorf("failed to add logical router policy for port-group address-set %s: %v", pgAs, err) return err } @@ -2390,7 +2377,7 @@ func (c *Controller) deletePolicyRouteForDistributedSubnet(subnet *kubeovnv1.Sub pgAs := fmt.Sprintf("%s_%s", pgName, ipSuffix) match := fmt.Sprintf("%s.src == $%s", ipSuffix, pgAs) klog.Infof("delete policy route for router: %s, priority: %d, match %s", c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match) - if err := c.ovnNbClient.DeleteLogicalRouterPolicy(c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPolicy(c.config.ClusterRouter, util.GatewayRouterPolicyPriority, match); err != nil { klog.Errorf("failed to delete policy route for subnet %s: %v", subnet.Name, err) return err } @@ -2414,7 +2401,7 @@ func (c *Controller) deletePolicyRouteByGatewayType(subnet *kubeovnv1.Subnet, ga } match := fmt.Sprintf("ip%d.dst == %s", af, cidr) klog.Infof("delete policy route for router: %s, priority: %d, match %s", c.config.ClusterRouter, util.SubnetRouterPolicyPriority, match) - if err := c.ovnNbClient.DeleteLogicalRouterPolicy(c.config.ClusterRouter, util.SubnetRouterPolicyPriority, match); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPolicy(c.config.ClusterRouter, util.SubnetRouterPolicyPriority, match); err != nil { klog.Errorf("failed to delete logical router policy for CIDR %s of subnet %s: %v", cidr, subnet.Name, err) return err } @@ -2431,7 +2418,7 @@ func (c *Controller) deletePolicyRouteByGatewayType(subnet *kubeovnv1.Subnet, ga } for _, node := range nodes { pgName := getOverlaySubnetsPortGroupName(subnet.Name, node.Name) - if err = c.ovnNbClient.DeletePortGroup(pgName); err != nil { + if err = c.OVNNbClient.DeletePortGroup(pgName); err != nil { klog.Errorf("delete port group for subnet %s and node %s: %v", subnet.Name, node.Name, err) return err } @@ -2455,7 +2442,6 @@ func (c *Controller) deletePolicyRouteByGatewayType(subnet *kubeovnv1.Subnet, ga } func (c *Controller) addPolicyRouteForU2OInterconn(subnet *kubeovnv1.Subnet) error { - var v4Gw, v6Gw string for _, gw := range strings.Split(subnet.Spec.Gateway, ",") { switch util.CheckProtocol(gw) { @@ -2490,29 +2476,29 @@ func (c *Controller) addPolicyRouteForU2OInterconn(subnet *kubeovnv1.Subnet) err } } - u2oExcludeIp4Ag := strings.Replace(fmt.Sprintf(util.U2OExcludeIPAg, subnet.Name, "ip4"), "-", ".", -1) - u2oExcludeIp6Ag := strings.Replace(fmt.Sprintf(util.U2OExcludeIPAg, subnet.Name, "ip6"), "-", ".", -1) + u2oExcludeIP4Ag := strings.ReplaceAll(fmt.Sprintf(util.U2OExcludeIPAg, subnet.Name, "ip4"), "-", ".") + u2oExcludeIP6Ag := strings.ReplaceAll(fmt.Sprintf(util.U2OExcludeIPAg, subnet.Name, "ip6"), "-", ".") - if err := c.ovnNbClient.CreateAddressSet(u2oExcludeIp4Ag, externalIDs); err != nil { - klog.Errorf("create address set %s: %v", u2oExcludeIp4Ag, err) + if err := c.OVNNbClient.CreateAddressSet(u2oExcludeIP4Ag, externalIDs); err != nil { + klog.Errorf("create address set %s: %v", u2oExcludeIP4Ag, err) return err } - if err := c.ovnNbClient.CreateAddressSet(u2oExcludeIp6Ag, externalIDs); err != nil { - klog.Errorf("create address set %s: %v", u2oExcludeIp6Ag, err) + if err := c.OVNNbClient.CreateAddressSet(u2oExcludeIP6Ag, externalIDs); err != nil { + klog.Errorf("create address set %s: %v", u2oExcludeIP6Ag, err) return err } if len(nodesIPv4) > 0 { - if err := c.ovnNbClient.AddressSetUpdateAddress(u2oExcludeIp4Ag, nodesIPv4...); err != nil { - klog.Errorf("set v4 address set %s with address %v: %v", u2oExcludeIp4Ag, nodesIPv4, err) + if err := c.OVNNbClient.AddressSetUpdateAddress(u2oExcludeIP4Ag, nodesIPv4...); err != nil { + klog.Errorf("set v4 address set %s with address %v: %v", u2oExcludeIP4Ag, nodesIPv4, err) return err } } if len(nodesIPv6) > 0 { - if err := c.ovnNbClient.AddressSetUpdateAddress(u2oExcludeIp6Ag, nodesIPv6...); err != nil { - klog.Errorf("set v6 address set %s with address %v: %v", u2oExcludeIp6Ag, nodesIPv6, err) + if err := c.OVNNbClient.AddressSetUpdateAddress(u2oExcludeIP6Ag, nodesIPv6...); err != nil { + klog.Errorf("set v6 address set %s with address %v: %v", u2oExcludeIP6Ag, nodesIPv6, err) return err } } @@ -2520,11 +2506,11 @@ func (c *Controller) addPolicyRouteForU2OInterconn(subnet *kubeovnv1.Subnet) err for _, cidrBlock := range strings.Split(subnet.Spec.CIDRBlock, ",") { ipSuffix := "ip4" nextHop := v4Gw - U2OexcludeIPAs := u2oExcludeIp4Ag + U2OexcludeIPAs := u2oExcludeIP4Ag if util.CheckProtocol(cidrBlock) == kubeovnv1.ProtocolIPv6 { ipSuffix = "ip6" nextHop = v6Gw - U2OexcludeIPAs = u2oExcludeIp6Ag + U2OexcludeIPAs = u2oExcludeIP6Ag } match1 := fmt.Sprintf("%s.dst == %s", ipSuffix, cidrBlock) @@ -2548,14 +2534,14 @@ func (c *Controller) addPolicyRouteForU2OInterconn(subnet *kubeovnv1.Subnet) err action := ovnnb.LogicalRouterPolicyActionAllow if subnet.Spec.Vpc == c.config.ClusterRouter { klog.Infof("add u2o interconnection policy for router: %s, match %s, action %s", subnet.Spec.Vpc, match1, action) - if err := c.ovnNbClient.AddLogicalRouterPolicy(subnet.Spec.Vpc, util.U2OSubnetPolicyPriority, match1, action, nil, externalIDs); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(subnet.Spec.Vpc, util.U2OSubnetPolicyPriority, match1, action, nil, externalIDs); err != nil { klog.Errorf("failed to add u2o interconnection policy1 for subnet %s %v", subnet.Name, err) return err } action = ovnnb.LogicalRouterPolicyActionReroute klog.Infof("add u2o interconnection policy for router: %s, match %s, action %s", subnet.Spec.Vpc, match2, action) - if err := c.ovnNbClient.AddLogicalRouterPolicy(subnet.Spec.Vpc, util.SubnetRouterPolicyPriority, match2, action, []string{nextHop}, externalIDs); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(subnet.Spec.Vpc, util.SubnetRouterPolicyPriority, match2, action, []string{nextHop}, externalIDs); err != nil { klog.Errorf("failed to add u2o interconnection policy2 for subnet %s %v", subnet.Name, err) return err } @@ -2563,7 +2549,7 @@ func (c *Controller) addPolicyRouteForU2OInterconn(subnet *kubeovnv1.Subnet) err action = ovnnb.LogicalRouterPolicyActionReroute klog.Infof("add u2o interconnection policy for router: %s, match %s, action %s, nexthop %s", subnet.Spec.Vpc, match3, action, nextHop) - if err := c.ovnNbClient.AddLogicalRouterPolicy(subnet.Spec.Vpc, util.GatewayRouterPolicyPriority, match3, action, []string{nextHop}, externalIDs); err != nil { + if err := c.OVNNbClient.AddLogicalRouterPolicy(subnet.Spec.Vpc, util.GatewayRouterPolicyPriority, match3, action, []string{nextHop}, externalIDs); err != nil { klog.Errorf("failed to add u2o interconnection policy3 for subnet %s %v", subnet.Name, err) return err } @@ -2572,12 +2558,12 @@ func (c *Controller) addPolicyRouteForU2OInterconn(subnet *kubeovnv1.Subnet) err } func (c *Controller) deletePolicyRouteForU2OInterconn(subnet *kubeovnv1.Subnet) error { - logicalRouter, err := c.ovnNbClient.GetLogicalRouter(subnet.Spec.Vpc, true) + logicalRouter, err := c.OVNNbClient.GetLogicalRouter(subnet.Spec.Vpc, true) if err == nil && logicalRouter == nil { klog.Infof("logical router %s already deleted", subnet.Spec.Vpc) return nil } - policies, err := c.ovnNbClient.ListLogicalRouterPolicies(subnet.Spec.Vpc, -1, map[string]string{ + policies, err := c.OVNNbClient.ListLogicalRouterPolicies(subnet.Spec.Vpc, -1, map[string]string{ "isU2ORoutePolicy": "true", "vendor": util.CniTypeName, "subnet": subnet.Name, @@ -2598,22 +2584,22 @@ func (c *Controller) deletePolicyRouteForU2OInterconn(subnet *kubeovnv1.Subnet) for _, policy := range policies { klog.Infof("delete u2o interconnection policy for router %s with match %s priority %d", lr, policy.Match, policy.Priority) - if err = c.ovnNbClient.DeleteLogicalRouterPolicyByUUID(lr, policy.UUID); err != nil { + if err = c.OVNNbClient.DeleteLogicalRouterPolicyByUUID(lr, policy.UUID); err != nil { klog.Errorf("failed to delete u2o interconnection policy for subnet %s: %v", subnet.Name, err) return err } } - u2oExcludeIp4Ag := strings.Replace(fmt.Sprintf(util.U2OExcludeIPAg, subnet.Name, "ip4"), "-", ".", -1) - u2oExcludeIp6Ag := strings.Replace(fmt.Sprintf(util.U2OExcludeIPAg, subnet.Name, "ip6"), "-", ".", -1) + u2oExcludeIP4Ag := strings.ReplaceAll(fmt.Sprintf(util.U2OExcludeIPAg, subnet.Name, "ip4"), "-", ".") + u2oExcludeIP6Ag := strings.ReplaceAll(fmt.Sprintf(util.U2OExcludeIPAg, subnet.Name, "ip6"), "-", ".") - if err := c.ovnNbClient.DeleteAddressSet(u2oExcludeIp4Ag); err != nil { - klog.Errorf("delete address set %s: %v", u2oExcludeIp4Ag, err) + if err := c.OVNNbClient.DeleteAddressSet(u2oExcludeIP4Ag); err != nil { + klog.Errorf("delete address set %s: %v", u2oExcludeIP4Ag, err) return err } - if err := c.ovnNbClient.DeleteAddressSet(u2oExcludeIp6Ag); err != nil { - klog.Errorf("delete address set %s: %v", u2oExcludeIp6Ag, err) + if err := c.OVNNbClient.DeleteAddressSet(u2oExcludeIP6Ag); err != nil { + klog.Errorf("delete address set %s: %v", u2oExcludeIP6Ag, err) return err } @@ -2626,7 +2612,7 @@ func (c *Controller) reconcileRouteTableForSubnet(subnet *kubeovnv1.Subnet) erro } routerPortName := ovs.LogicalRouterPortName(subnet.Spec.Vpc, subnet.Name) - lrp, err := c.ovnNbClient.GetLogicalRouterPort(routerPortName, false) + lrp, err := c.OVNNbClient.GetLogicalRouterPort(routerPortName, false) if err != nil { klog.Error(err) return err @@ -2641,7 +2627,7 @@ func (c *Controller) reconcileRouteTableForSubnet(subnet *kubeovnv1.Subnet) erro klog.Infof("reconcile route table %q for subnet %s", subnet.Spec.RouteTable, subnet.Name) opt := map[string]string{"route_table": subnet.Spec.RouteTable} - if err = c.ovnNbClient.UpdateLogicalRouterPortOptions(routerPortName, opt); err != nil { + if err = c.OVNNbClient.UpdateLogicalRouterPortOptions(routerPortName, opt); err != nil { klog.Errorf("failed to set route table of logical router port %s to %s: %v", routerPortName, subnet.Spec.RouteTable, err) return err } @@ -2654,7 +2640,7 @@ func (c *Controller) addCustomVPCPolicyRoutesForSubnet(subnet *kubeovnv1.Subnet) } func (c *Controller) deleteCustomVPCPolicyRoutesForSubnet(subnet *kubeovnv1.Subnet) error { - logicalRouter, err := c.ovnNbClient.GetLogicalRouter(subnet.Spec.Vpc, true) + logicalRouter, err := c.OVNNbClient.GetLogicalRouter(subnet.Spec.Vpc, true) if err == nil && logicalRouter == nil { klog.Infof("logical router %s already deleted", subnet.Spec.Vpc) return nil @@ -2666,7 +2652,7 @@ func (c *Controller) deleteCustomVPCPolicyRoutesForSubnet(subnet *kubeovnv1.Subn } match := fmt.Sprintf("ip%d.dst == %s", af, cidr) klog.Infof("delete policy route for router: %s, priority: %d, match %s", subnet.Spec.Vpc, util.SubnetRouterPolicyPriority, match) - if err := c.ovnNbClient.DeleteLogicalRouterPolicy(subnet.Spec.Vpc, util.SubnetRouterPolicyPriority, match); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPolicy(subnet.Spec.Vpc, util.SubnetRouterPolicyPriority, match); err != nil { klog.Errorf("failed to delete logical router policy for CIDR %s of subnet %s: %v", cidr, subnet.Name, err) return err } @@ -2681,12 +2667,12 @@ func (c *Controller) clearOldU2OResource(subnet *kubeovnv1.Subnet) error { lspName := fmt.Sprintf("%s-%s", subnet.Name, subnet.Status.U2OInterconnectionVPC) lrpName := fmt.Sprintf("%s-%s", subnet.Status.U2OInterconnectionVPC, subnet.Name) klog.Infof("clean subnet %s old u2o resource with lsp %s lrp %s ", subnet.Name, lspName, lrpName) - if err := c.ovnNbClient.DeleteLogicalSwitchPort(lspName); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(lspName); err != nil { klog.Errorf("failed to delete u2o logical switch port %s: %v", lspName, err) return err } - if err := c.ovnNbClient.DeleteLogicalRouterPort(lrpName); err != nil { + if err := c.OVNNbClient.DeleteLogicalRouterPort(lrpName); err != nil { klog.Errorf("failed to delete u2o logical router port %s: %v", lrpName, err) return err } diff --git a/pkg/controller/switch_lb_rule.go b/pkg/controller/switch_lb_rule.go index a621084ddf8..24b9ca9ee8f 100644 --- a/pkg/controller/switch_lb_rule.go +++ b/pkg/controller/switch_lb_rule.go @@ -19,7 +19,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -type slrInfo struct { +type SlrInfo struct { Name string Namespace string IsRecreate bool @@ -29,8 +29,8 @@ func generateSvcName(name string) string { return fmt.Sprintf("slr-%s", name) } -func NewSlrInfo(slr *kubeovnv1.SwitchLBRule) *slrInfo { - return &slrInfo{ +func NewSlrInfo(slr *kubeovnv1.SwitchLBRule) *SlrInfo { + return &SlrInfo{ Name: slr.Name, Namespace: slr.Spec.Namespace, IsRecreate: false, @@ -38,7 +38,6 @@ func NewSlrInfo(slr *kubeovnv1.SwitchLBRule) *slrInfo { } func (c *Controller) enqueueAddSwitchLBRule(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -49,9 +48,9 @@ func (c *Controller) enqueueAddSwitchLBRule(obj interface{}) { c.addSwitchLBRuleQueue.Add(key) } -func (c *Controller) enqueueUpdateSwitchLBRule(old, new interface{}) { - oldSlr := old.(*kubeovnv1.SwitchLBRule) - newSlr := new.(*kubeovnv1.SwitchLBRule) +func (c *Controller) enqueueUpdateSwitchLBRule(oldObj, newObj interface{}) { + oldSlr := oldObj.(*kubeovnv1.SwitchLBRule) + newSlr := newObj.(*kubeovnv1.SwitchLBRule) info := NewSlrInfo(oldSlr) if oldSlr.ResourceVersion == newSlr.ResourceVersion || @@ -81,7 +80,7 @@ func (c *Controller) enqueueDeleteSwitchLBRule(obj interface{}) { c.delSwitchLBRuleQueue.Add(info) } -func (c *Controller) processSwitchLBRuleWorkItem(processName string, queue workqueue.RateLimitingInterface, handler func(key *slrInfo) error) bool { +func (c *Controller) processSwitchLBRuleWorkItem(processName string, queue workqueue.RateLimitingInterface, handler func(key *SlrInfo) error) bool { obj, shutdown := queue.Get() if shutdown { return false @@ -89,7 +88,7 @@ func (c *Controller) processSwitchLBRuleWorkItem(processName string, queue workq err := func(obj interface{}) error { defer queue.Done(obj) - key, ok := obj.(*slrInfo) + key, ok := obj.(*SlrInfo) if !ok { queue.Forget(obj) utilruntime.HandleError(fmt.Errorf("expected switchLBRule in workqueue but got %#v", obj)) @@ -101,7 +100,6 @@ func (c *Controller) processSwitchLBRuleWorkItem(processName string, queue workq queue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(fmt.Errorf("process: %s. err: %v", processName, err)) queue.AddRateLimited(obj) @@ -224,7 +222,7 @@ func (c *Controller) handleAddOrUpdateSwitchLBRule(key string) error { return nil } -func (c *Controller) handleDelSwitchLBRule(info *slrInfo) error { +func (c *Controller) handleDelSwitchLBRule(info *SlrInfo) error { klog.V(3).Infof("handleDelSwitchLBRule %s", info.Name) name := generateSvcName(info.Name) @@ -239,7 +237,7 @@ func (c *Controller) handleDelSwitchLBRule(info *slrInfo) error { return nil } -func (c *Controller) handleUpdateSwitchLBRule(info *slrInfo) error { +func (c *Controller) handleUpdateSwitchLBRule(info *SlrInfo) error { klog.V(3).Infof("handleUpdateSwitchLBRule %s", info.Name) if info.IsRecreate { if err := c.handleDelSwitchLBRule(info); err != nil { @@ -308,7 +306,6 @@ func generateHeadlessService(slr *kubeovnv1.SwitchLBRule, oldSvc *corev1.Service SessionAffinity: corev1.ServiceAffinity(slr.Spec.SessionAffinity), }, } - } return newSvc } diff --git a/pkg/controller/vip.go b/pkg/controller/vip.go index 3c4b987c508..42128dfcea8 100644 --- a/pkg/controller/vip.go +++ b/pkg/controller/vip.go @@ -20,8 +20,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -func (c *Controller) enqueueAddVirtualIp(obj interface{}) { - +func (c *Controller) enqueueAddVirtualIP(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -29,29 +28,29 @@ func (c *Controller) enqueueAddVirtualIp(obj interface{}) { return } klog.Infof("enqueue add vip %s", key) - c.addVirtualIpQueue.Add(key) + c.addVirtualIPQueue.Add(key) } -func (c *Controller) enqueueUpdateVirtualIp(old, new interface{}) { +func (c *Controller) enqueueUpdateVirtualIP(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - oldVip := old.(*kubeovnv1.Vip) - newVip := new.(*kubeovnv1.Vip) + oldVip := oldObj.(*kubeovnv1.Vip) + newVip := newObj.(*kubeovnv1.Vip) if !newVip.DeletionTimestamp.IsZero() || oldVip.Spec.MacAddress != newVip.Spec.MacAddress || oldVip.Spec.ParentMac != newVip.Spec.ParentMac || oldVip.Spec.ParentV4ip != newVip.Spec.ParentV4ip || oldVip.Spec.V4ip != newVip.Spec.V4ip { klog.Infof("enqueue update vip %s", key) - c.updateVirtualIpQueue.Add(key) + c.updateVirtualIPQueue.Add(key) } } -func (c *Controller) enqueueDelVirtualIp(obj interface{}) { +func (c *Controller) enqueueDelVirtualIP(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -60,47 +59,46 @@ func (c *Controller) enqueueDelVirtualIp(obj interface{}) { } klog.Infof("enqueue del vip %s", key) vip := obj.(*kubeovnv1.Vip) - c.delVirtualIpQueue.Add(vip) + c.delVirtualIPQueue.Add(vip) } -func (c *Controller) runAddVirtualIpWorker() { - for c.processNextAddVirtualIpWorkItem() { +func (c *Controller) runAddVirtualIPWorker() { + for c.processNextAddVirtualIPWorkItem() { } } -func (c *Controller) runUpdateVirtualIpWorker() { - for c.processNextUpdateVirtualIpWorkItem() { +func (c *Controller) runUpdateVirtualIPWorker() { + for c.processNextUpdateVirtualIPWorkItem() { } } -func (c *Controller) runDelVirtualIpWorker() { - for c.processNextDeleteVirtualIpWorkItem() { +func (c *Controller) runDelVirtualIPWorker() { + for c.processNextDeleteVirtualIPWorkItem() { } } -func (c *Controller) processNextAddVirtualIpWorkItem() bool { - obj, shutdown := c.addVirtualIpQueue.Get() +func (c *Controller) processNextAddVirtualIPWorkItem() bool { + obj, shutdown := c.addVirtualIPQueue.Get() if shutdown { return false } err := func(obj interface{}) error { - defer c.addVirtualIpQueue.Done(obj) + defer c.addVirtualIPQueue.Done(obj) var key string var ok bool if key, ok = obj.(string); !ok { - c.addVirtualIpQueue.Forget(obj) + c.addVirtualIPQueue.Forget(obj) utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) return nil } - if err := c.handleAddVirtualIp(key); err != nil { - c.addVirtualIpQueue.AddRateLimited(key) + if err := c.handleAddVirtualIP(key); err != nil { + c.addVirtualIPQueue.AddRateLimited(key) return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error()) } - c.addVirtualIpQueue.Forget(obj) + c.addVirtualIPQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -108,25 +106,25 @@ func (c *Controller) processNextAddVirtualIpWorkItem() bool { return true } -func (c *Controller) processNextUpdateVirtualIpWorkItem() bool { - obj, shutdown := c.updateVirtualIpQueue.Get() +func (c *Controller) processNextUpdateVirtualIPWorkItem() bool { + obj, shutdown := c.updateVirtualIPQueue.Get() if shutdown { return false } err := func(obj interface{}) error { - defer c.updateVirtualIpQueue.Done(obj) + defer c.updateVirtualIPQueue.Done(obj) var key string var ok bool if key, ok = obj.(string); !ok { - c.updateVirtualIpQueue.Forget(obj) + c.updateVirtualIPQueue.Forget(obj) utilruntime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) return nil } - if err := c.handleUpdateVirtualIp(key); err != nil { - c.updateVirtualIpQueue.AddRateLimited(key) + if err := c.handleUpdateVirtualIP(key); err != nil { + c.updateVirtualIPQueue.AddRateLimited(key) return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error()) } - c.updateVirtualIpQueue.Forget(obj) + c.updateVirtualIPQueue.Forget(obj) return nil }(obj) if err != nil { @@ -136,29 +134,28 @@ func (c *Controller) processNextUpdateVirtualIpWorkItem() bool { return true } -func (c *Controller) processNextDeleteVirtualIpWorkItem() bool { - obj, shutdown := c.delVirtualIpQueue.Get() +func (c *Controller) processNextDeleteVirtualIPWorkItem() bool { + obj, shutdown := c.delVirtualIPQueue.Get() if shutdown { return false } err := func(obj interface{}) error { - defer c.delVirtualIpQueue.Done(obj) + defer c.delVirtualIPQueue.Done(obj) var vip *kubeovnv1.Vip var ok bool if vip, ok = obj.(*kubeovnv1.Vip); !ok { - c.delVirtualIpQueue.Forget(obj) + c.delVirtualIPQueue.Forget(obj) utilruntime.HandleError(fmt.Errorf("expected vip in workqueue but got %#v", obj)) return nil } - if err := c.handleDelVirtualIp(vip); err != nil { - c.delVirtualIpQueue.AddRateLimited(obj) + if err := c.handleDelVirtualIP(vip); err != nil { + c.delVirtualIPQueue.AddRateLimited(obj) return fmt.Errorf("error syncing '%s': %s, requeuing", vip.Name, err.Error()) } - c.delVirtualIpQueue.Forget(obj) + c.delVirtualIPQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -166,7 +163,7 @@ func (c *Controller) processNextDeleteVirtualIpWorkItem() bool { return true } -func (c *Controller) handleAddVirtualIp(key string) error { +func (c *Controller) handleAddVirtualIP(key string) error { cachedVip, err := c.virtualIpsLister.Get(key) if err != nil { if k8serrors.IsNotFound(err) { @@ -193,10 +190,10 @@ func (c *Controller) handleAddVirtualIp(key string) error { portName := ovs.PodNameToPortName(vip.Name, vip.Spec.Namespace, subnet.Spec.Provider) sourceV4Ip = vip.Spec.V4ip if sourceV4Ip != "" { - v4ip, v6ip, mac, err = c.acquireStaticIpAddress(subnet.Name, vip.Name, portName, sourceV4Ip) + v4ip, v6ip, mac, err = c.acquireStaticIPAddress(subnet.Name, vip.Name, portName, sourceV4Ip) } else { // Random allocate - v4ip, v6ip, mac, err = c.acquireIpAddress(subnet.Name, vip.Name, portName) + v4ip, v6ip, mac, err = c.acquireIPAddress(subnet.Name, vip.Name, portName) } if err != nil { klog.Error(err) @@ -207,7 +204,7 @@ func (c *Controller) handleAddVirtualIp(key string) error { // create a lsp use subnet gw mac, and set it option as arp_proxy lrpName := fmt.Sprintf("%s-%s", subnet.Spec.Vpc, subnet.Name) klog.Infof("get logical router port %s", lrpName) - lrp, err := c.ovnNbClient.GetLogicalRouterPort(lrpName, false) + lrp, err := c.OVNNbClient.GetLogicalRouterPort(lrpName, false) if err != nil { klog.Errorf("failed to get lrp %s: %v", lrpName, err) return err @@ -219,12 +216,12 @@ func (c *Controller) handleAddVirtualIp(key string) error { } mac = lrp.MAC ipStr := util.GetStringIP(v4ip, v6ip) - if err := c.ovnNbClient.CreateLogicalSwitchPort(subnet.Name, portName, ipStr, mac, vip.Name, vip.Spec.Namespace, false, "", "", false, nil, subnet.Spec.Vpc); err != nil { + if err := c.OVNNbClient.CreateLogicalSwitchPort(subnet.Name, portName, ipStr, mac, vip.Name, vip.Spec.Namespace, false, "", "", false, nil, subnet.Spec.Vpc); err != nil { err = fmt.Errorf("failed to create lsp %s: %v", portName, err) klog.Error(err) return err } - if err := c.ovnNbClient.SetLogicalSwitchPortArpProxy(portName, true); err != nil { + if err := c.OVNNbClient.SetLogicalSwitchPortArpProxy(portName, true); err != nil { err = fmt.Errorf("failed to enable lsp arp proxy for vip %s: %v", portName, err) klog.Error(err) return err @@ -244,14 +241,14 @@ func (c *Controller) handleAddVirtualIp(key string) error { klog.Errorf("failed to create or update vip '%s', %v", vip.Name, err) return err } - if err = c.subnetCountIp(subnet); err != nil { + if err = c.subnetCountIP(subnet); err != nil { klog.Errorf("failed to count vip '%s' in subnet, %v", vip.Name, err) return err } return nil } -func (c *Controller) handleUpdateVirtualIp(key string) error { +func (c *Controller) handleUpdateVirtualIP(key string) error { cachedVip, err := c.virtualIpsLister.Get(key) if err != nil { if k8serrors.IsNotFound(err) { @@ -297,7 +294,7 @@ func (c *Controller) handleUpdateVirtualIp(key string) error { return nil } -func (c *Controller) handleDelVirtualIp(vip *kubeovnv1.Vip) error { +func (c *Controller) handleDelVirtualIP(vip *kubeovnv1.Vip) error { klog.Infof("handle delete vip %s", vip.Name) // TODO:// clean vip in its parent port aap list if vip.Spec.Type == util.SwitchLBRuleVip { @@ -308,7 +305,7 @@ func (c *Controller) handleDelVirtualIp(vip *kubeovnv1.Vip) error { } portName := ovs.PodNameToPortName(vip.Name, vip.Spec.Namespace, subnet.Spec.Provider) klog.Infof("delete vip arp proxy lsp %s", portName) - if err := c.ovnNbClient.DeleteLogicalSwitchPort(portName); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(portName); err != nil { err = fmt.Errorf("failed to delete lsp %s: %v", vip.Name, err) klog.Error(err) return err @@ -319,7 +316,7 @@ func (c *Controller) handleDelVirtualIp(vip *kubeovnv1.Vip) error { return nil } -func (c *Controller) acquireStaticIpAddress(subnetName, name, nicName, ip string) (string, string, string, error) { +func (c *Controller) acquireStaticIPAddress(subnetName, name, nicName, ip string) (string, string, string, error) { checkConflict := true var v4ip, v6ip, mac string var err error @@ -336,7 +333,7 @@ func (c *Controller) acquireStaticIpAddress(subnetName, name, nicName, ip string return v4ip, v6ip, mac, nil } -func (c *Controller) acquireIpAddress(subnetName, name, nicName string) (string, string, string, error) { +func (c *Controller) acquireIPAddress(subnetName, name, nicName string) (string, string, string, error) { var skippedAddrs []string var v4ip, v6ip, mac string checkConflict := true @@ -367,7 +364,7 @@ func (c *Controller) acquireIpAddress(subnetName, name, nicName string) (string, } } -func (c *Controller) subnetCountIp(subnet *kubeovnv1.Subnet) error { +func (c *Controller) subnetCountIP(subnet *kubeovnv1.Subnet) error { var err error if util.CheckProtocol(subnet.Spec.CIDRBlock) == kubeovnv1.ProtocolDual { err = calcDualSubnetStatusIP(subnet, c) @@ -386,7 +383,7 @@ func (c *Controller) createOrUpdateCrdVip(key, ns, subnet, v4ip, v6ip, mac, pV4i Name: key, Labels: map[string]string{ util.SubnetNameLabel: subnet, - util.IpReservedLabel: "", + util.IPReservedLabel: "", }, Namespace: ns, }, @@ -442,7 +439,7 @@ func (c *Controller) createOrUpdateCrdVip(key, ns, subnet, v4ip, v6ip, mac, pV4i op = "add" vip.Labels = map[string]string{ util.SubnetNameLabel: subnet, - util.IpReservedLabel: "", + util.IPReservedLabel: "", } needUpdateLabel = true } @@ -508,15 +505,14 @@ func (c *Controller) podReuseVip(key, portName string, keepVIP bool) error { vip := oriVip.DeepCopy() var op string - if vip.Labels[util.IpReservedLabel] != "" { - if keepVIP && vip.Labels[util.IpReservedLabel] == portName { + if vip.Labels[util.IPReservedLabel] != "" { + if keepVIP && vip.Labels[util.IPReservedLabel] == portName { return nil - } else { - return fmt.Errorf("vip '%s' is in use by pod %s", vip.Name, vip.Labels[util.IpReservedLabel]) } + return fmt.Errorf("vip '%s' is in use by pod %s", vip.Name, vip.Labels[util.IPReservedLabel]) } op = "replace" - vip.Labels[util.IpReservedLabel] = portName + vip.Labels[util.IPReservedLabel] = portName patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/labels", "value": %s }]` raw, _ := json.Marshal(vip.Labels) patchPayload := fmt.Sprintf(patchPayloadTemplate, op, raw) @@ -542,13 +538,12 @@ func (c *Controller) releaseVip(key string) error { vip := oriVip.DeepCopy() var needUpdateLabel bool var op string - if vip.Labels[util.IpReservedLabel] == "" { + if vip.Labels[util.IPReservedLabel] == "" { return nil - } else { - op = "replace" - vip.Labels[util.IpReservedLabel] = "" - needUpdateLabel = true } + op = "replace" + vip.Labels[util.IPReservedLabel] = "" + needUpdateLabel = true if needUpdateLabel { klog.V(3).Infof("clean reserved label from vip %s", key) patchPayloadTemplate := `[{ "op": "%s", "path": "/metadata/labels", "value": %s }]` diff --git a/pkg/controller/vlan.go b/pkg/controller/vlan.go index a24c206c18a..b9df03f7ae6 100644 --- a/pkg/controller/vlan.go +++ b/pkg/controller/vlan.go @@ -17,7 +17,6 @@ import ( ) func (c *Controller) enqueueAddVlan(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -28,9 +27,8 @@ func (c *Controller) enqueueAddVlan(obj interface{}) { c.addVlanQueue.Add(key) } -func (c *Controller) enqueueUpdateVlan(old, new interface{}) { - - key, err := cache.MetaNamespaceKeyFunc(new) +func (c *Controller) enqueueUpdateVlan(_, newObj interface{}) { + key, err := cache.MetaNamespaceKeyFunc(newObj) if err != nil { utilruntime.HandleError(err) return @@ -89,7 +87,6 @@ func (c *Controller) processNextAddVlanWorkItem() bool { c.addVlanQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -123,7 +120,6 @@ func (c *Controller) processNextUpdateVlanWorkItem() bool { c.updateVlanQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -158,7 +154,6 @@ func (c *Controller) processNextDelVlanWorkItem() bool { c.delVlanQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -318,7 +313,7 @@ func (c *Controller) updateProviderNetworkStatusForVlanDeletion(pn *kubeovnv1.Pr func (c *Controller) setLocalnetTag(subnet string, vlanID int) error { localnetPort := ovs.GetLocalnetName(subnet) - if err := c.ovnNbClient.SetLogicalSwitchPortVlanTag(localnetPort, vlanID); err != nil { + if err := c.OVNNbClient.SetLogicalSwitchPortVlanTag(localnetPort, vlanID); err != nil { klog.Errorf("set localnet port %s vlan tag %d: %v", localnetPort, vlanID, err) return err } @@ -328,7 +323,7 @@ func (c *Controller) setLocalnetTag(subnet string, vlanID int) error { func (c *Controller) delLocalnet(subnet string) error { localnetPort := ovs.GetLocalnetName(subnet) - if err := c.ovnNbClient.DeleteLogicalSwitchPort(localnetPort); err != nil { + if err := c.OVNNbClient.DeleteLogicalSwitchPort(localnetPort); err != nil { klog.Errorf("delete localnet port %s: %v", localnetPort, err) return err } diff --git a/pkg/controller/vpc.go b/pkg/controller/vpc.go index 553991c41c2..79b34f333e8 100644 --- a/pkg/controller/vpc.go +++ b/pkg/controller/vpc.go @@ -22,7 +22,6 @@ import ( ) func (c *Controller) enqueueAddVpc(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -36,13 +35,13 @@ func (c *Controller) enqueueAddVpc(obj interface{}) { } } -func (c *Controller) enqueueUpdateVpc(old, new interface{}) { - oldVpc := old.(*kubeovnv1.Vpc) - newVpc := new.(*kubeovnv1.Vpc) +func (c *Controller) enqueueUpdateVpc(oldObj, newObj interface{}) { + oldVpc := oldObj.(*kubeovnv1.Vpc) + newVpc := newObj.(*kubeovnv1.Vpc) var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } @@ -170,10 +169,10 @@ func (c *Controller) handleUpdateVpcStatus(key string) error { } type VpcLoadBalancer struct { - TcpLoadBalancer string - TcpSessLoadBalancer string - UdpLoadBalancer string - UdpSessLoadBalancer string + TCPLoadBalancer string + TCPSessLoadBalancer string + UDPLoadBalancer string + UDPSessLoadBalancer string SctpLoadBalancer string SctpSessLoadBalancer string } @@ -181,37 +180,36 @@ type VpcLoadBalancer struct { func (c *Controller) GenVpcLoadBalancer(vpcKey string) *VpcLoadBalancer { if vpcKey == c.config.ClusterRouter || vpcKey == "" { return &VpcLoadBalancer{ - TcpLoadBalancer: c.config.ClusterTcpLoadBalancer, - TcpSessLoadBalancer: c.config.ClusterTcpSessionLoadBalancer, - UdpLoadBalancer: c.config.ClusterUdpLoadBalancer, - UdpSessLoadBalancer: c.config.ClusterUdpSessionLoadBalancer, + TCPLoadBalancer: c.config.ClusterTCPLoadBalancer, + TCPSessLoadBalancer: c.config.ClusterTCPSessionLoadBalancer, + UDPLoadBalancer: c.config.ClusterUDPLoadBalancer, + UDPSessLoadBalancer: c.config.ClusterUDPSessionLoadBalancer, SctpLoadBalancer: c.config.ClusterSctpLoadBalancer, SctpSessLoadBalancer: c.config.ClusterSctpSessionLoadBalancer, } - } else { - return &VpcLoadBalancer{ - TcpLoadBalancer: fmt.Sprintf("vpc-%s-tcp-load", vpcKey), - TcpSessLoadBalancer: fmt.Sprintf("vpc-%s-tcp-sess-load", vpcKey), - UdpLoadBalancer: fmt.Sprintf("vpc-%s-udp-load", vpcKey), - UdpSessLoadBalancer: fmt.Sprintf("vpc-%s-udp-sess-load", vpcKey), - SctpLoadBalancer: fmt.Sprintf("vpc-%s-sctp-load", vpcKey), - SctpSessLoadBalancer: fmt.Sprintf("vpc-%s-sctp-sess-load", vpcKey), - } + } + return &VpcLoadBalancer{ + TCPLoadBalancer: fmt.Sprintf("vpc-%s-tcp-load", vpcKey), + TCPSessLoadBalancer: fmt.Sprintf("vpc-%s-tcp-sess-load", vpcKey), + UDPLoadBalancer: fmt.Sprintf("vpc-%s-udp-load", vpcKey), + UDPSessLoadBalancer: fmt.Sprintf("vpc-%s-udp-sess-load", vpcKey), + SctpLoadBalancer: fmt.Sprintf("vpc-%s-sctp-load", vpcKey), + SctpSessLoadBalancer: fmt.Sprintf("vpc-%s-sctp-sess-load", vpcKey), } } func (c *Controller) addLoadBalancer(vpc string) (*VpcLoadBalancer, error) { vpcLbConfig := c.GenVpcLoadBalancer(vpc) - if err := c.initLB(vpcLbConfig.TcpLoadBalancer, string(v1.ProtocolTCP), false); err != nil { + if err := c.initLB(vpcLbConfig.TCPLoadBalancer, string(v1.ProtocolTCP), false); err != nil { return nil, err } - if err := c.initLB(vpcLbConfig.TcpSessLoadBalancer, string(v1.ProtocolTCP), true); err != nil { + if err := c.initLB(vpcLbConfig.TCPSessLoadBalancer, string(v1.ProtocolTCP), true); err != nil { return nil, err } - if err := c.initLB(vpcLbConfig.UdpLoadBalancer, string(v1.ProtocolUDP), false); err != nil { + if err := c.initLB(vpcLbConfig.UDPLoadBalancer, string(v1.ProtocolUDP), false); err != nil { return nil, err } - if err := c.initLB(vpcLbConfig.UdpSessLoadBalancer, string(v1.ProtocolUDP), true); err != nil { + if err := c.initLB(vpcLbConfig.UDPSessLoadBalancer, string(v1.ProtocolUDP), true); err != nil { return nil, err } if err := c.initLB(vpcLbConfig.SctpLoadBalancer, string(v1.ProtocolSCTP), false); err != nil { @@ -256,14 +254,14 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { } newPeers = append(newPeers, peering.RemoteVpc) - if err := c.ovnNbClient.CreatePeerRouterPort(vpc.Name, peering.RemoteVpc, peering.LocalConnectIP); err != nil { + if err := c.OVNNbClient.CreatePeerRouterPort(vpc.Name, peering.RemoteVpc, peering.LocalConnectIP); err != nil { klog.Errorf("create peer router port for vpc %s, %v", vpc.Name, err) return err } } for _, oldPeer := range vpc.Status.VpcPeerings { if !util.ContainsString(newPeers, oldPeer) { - if err = c.ovnNbClient.DeleteLogicalRouterPort(fmt.Sprintf("%s-%s", vpc.Name, oldPeer)); err != nil { + if err = c.OVNNbClient.DeleteLogicalRouterPort(fmt.Sprintf("%s-%s", vpc.Name, oldPeer)); err != nil { klog.Errorf("delete peer router port for vpc %s, %v", vpc.Name, err) return err } @@ -271,7 +269,7 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { } // handle static route - existRoute, err := c.ovnNbClient.ListLogicalRouterStaticRoutes(vpc.Name, nil, nil, "", nil) + existRoute, err := c.OVNNbClient.ListLogicalRouterStaticRoutes(vpc.Name, nil, nil, "", nil) if err != nil { klog.Errorf("failed to get vpc %s static route list, %v", vpc.Name, err) return err @@ -332,14 +330,14 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { nextHop = strings.Split(nextHop, "/")[0] } - lr, err := c.ovnNbClient.GetLogicalRouter(vpc.Name, false) + lr, err := c.OVNNbClient.GetLogicalRouter(vpc.Name, false) if err != nil { klog.Errorf("failed to get logical router %s: %v", vpc.Name, err) return err } for _, nat := range lr.Nat { - info, err := c.ovnNbClient.GetNATByUUID(nat) + info, err := c.OVNNbClient.GetNATByUUID(nat) if err != nil { klog.Errorf("failed to get nat ip info for vpc %s, %v", vpc.Name, err) return err @@ -367,24 +365,24 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { for _, item := range routeNeedDel { klog.Infof("vpc %s del static route: %v", vpc.Name, item) policy := convertPolicy(item.Policy) - if err = c.ovnNbClient.DeleteLogicalRouterStaticRoute(vpc.Name, &item.RouteTable, &policy, item.CIDR, item.NextHopIP); err != nil { + if err = c.OVNNbClient.DeleteLogicalRouterStaticRoute(vpc.Name, &item.RouteTable, &policy, item.CIDR, item.NextHopIP); err != nil { klog.Errorf("del vpc %s static route failed, %v", vpc.Name, err) return err } } for _, item := range routeNeedAdd { - if item.BfdId != "" { + if item.BfdID != "" { klog.Infof("vpc %s add static ecmp route: %+v", vpc.Name, item) - if err = c.ovnNbClient.AddLogicalRouterStaticRoute( - vpc.Name, item.RouteTable, convertPolicy(item.Policy), item.CIDR, &item.BfdId, item.NextHopIP, + if err = c.OVNNbClient.AddLogicalRouterStaticRoute( + vpc.Name, item.RouteTable, convertPolicy(item.Policy), item.CIDR, &item.BfdID, item.NextHopIP, ); err != nil { klog.Errorf("failed to add bfd static route to vpc %s , %v", vpc.Name, err) return err } } else { klog.Infof("vpc %s add static route: %+v", vpc.Name, item) - if err = c.ovnNbClient.AddLogicalRouterStaticRoute( + if err = c.OVNNbClient.AddLogicalRouterStaticRoute( vpc.Name, item.RouteTable, convertPolicy(item.Policy), item.CIDR, nil, item.NextHopIP, ); err != nil { klog.Errorf("failed to add normal static route to vpc %s , %v", vpc.Name, err) @@ -395,7 +393,7 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { if vpc.Name != c.config.ClusterRouter && vpc.Spec.PolicyRoutes == nil { // do not clean default vpc policy routes - if err = c.ovnNbClient.ClearLogicalRouterPolicy(vpc.Name); err != nil { + if err = c.OVNNbClient.ClearLogicalRouterPolicy(vpc.Name); err != nil { klog.Errorf("clean all vpc %s policy route failed, %v", vpc.Name, err) return err } @@ -403,7 +401,7 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { if vpc.Spec.PolicyRoutes != nil { // diff update vpc policy route - policyList, err := c.ovnNbClient.ListLogicalRouterPolicies(vpc.Name, -1, nil) + policyList, err := c.OVNNbClient.ListLogicalRouterPolicies(vpc.Name, -1, nil) if err != nil { klog.Errorf("failed to get vpc %s policy route list, %v", vpc.Name, err) return err @@ -415,7 +413,7 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { } for _, item := range policyRouteNeedDel { klog.Infof("delete policy route for router: %s, priority: %d, match %s", vpc.Name, item.Priority, item.Match) - if err = c.ovnNbClient.DeleteLogicalRouterPolicy(vpc.Name, item.Priority, item.Match); err != nil { + if err = c.OVNNbClient.DeleteLogicalRouterPolicy(vpc.Name, item.Priority, item.Match); err != nil { klog.Errorf("del vpc %s policy route failed, %v", vpc.Name, err) return err } @@ -423,7 +421,7 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { for _, item := range policyRouteNeedAdd { externalIDs := map[string]string{"vendor": util.CniTypeName} klog.Infof("add policy route for router: %s, match %s, action %s, nexthop %s, externalID %v", c.config.ClusterRouter, item.Match, string(item.Action), item.NextHopIP, externalIDs) - if err = c.ovnNbClient.AddLogicalRouterPolicy(vpc.Name, item.Priority, item.Match, string(item.Action), []string{item.NextHopIP}, externalIDs); err != nil { + if err = c.OVNNbClient.AddLogicalRouterPolicy(vpc.Name, item.Priority, item.Match, string(item.Action), []string{item.NextHopIP}, externalIDs); err != nil { klog.Errorf("add policy route to vpc %s failed, %v", vpc.Name, err) return err } @@ -439,10 +437,10 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { klog.Error(err) return err } - vpc.Status.TcpLoadBalancer = vpcLb.TcpLoadBalancer - vpc.Status.TcpSessionLoadBalancer = vpcLb.TcpSessLoadBalancer - vpc.Status.UdpLoadBalancer = vpcLb.UdpLoadBalancer - vpc.Status.UdpSessionLoadBalancer = vpcLb.UdpSessLoadBalancer + vpc.Status.TCPLoadBalancer = vpcLb.TCPLoadBalancer + vpc.Status.TCPSessionLoadBalancer = vpcLb.TCPSessLoadBalancer + vpc.Status.UDPLoadBalancer = vpcLb.UDPLoadBalancer + vpc.Status.UDPSessionLoadBalancer = vpcLb.UDPSessLoadBalancer vpc.Status.SctpLoadBalancer = vpcLb.SctpLoadBalancer vpc.Status.SctpSessionLoadBalancer = vpcLb.SctpSessLoadBalancer } @@ -506,7 +504,7 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { if !cachedVpc.Spec.EnableBfd && cachedVpc.Status.EnableBfd { lrpEipName := fmt.Sprintf("%s-%s", key, c.config.ExternalGatewaySwitch) - if err := c.ovnNbClient.DeleteBFD(lrpEipName, ""); err != nil { + if err := c.OVNNbClient.DeleteBFD(lrpEipName, ""); err != nil { klog.Error(err) return err } @@ -576,7 +574,7 @@ func diffStaticRoute(exist []*ovnnb.LogicalRouterStaticRoute, target []*kubeovnv ECMPMode: util.StaticRouteBfdEcmp, } if item.BFD != nil { - route.BfdId = *item.BFD + route.BfdID = *item.BFD } existRouteMap[getStaticRouteItemKey(route)] = route } @@ -598,9 +596,8 @@ func diffStaticRoute(exist []*ovnnb.LogicalRouterStaticRoute, target []*kubeovnv func getStaticRouteItemKey(item *kubeovnv1.StaticRoute) (key string) { if item.Policy == kubeovnv1.PolicyDst { return fmt.Sprintf("%s:dst:%s=>%s", item.RouteTable, item.CIDR, item.NextHopIP) - } else { - return fmt.Sprintf("%s:src:%s=>%s", item.RouteTable, item.CIDR, item.NextHopIP) } + return fmt.Sprintf("%s:src:%s=>%s", item.RouteTable, item.CIDR, item.NextHopIP) } func formatVpc(vpc *kubeovnv1.Vpc, c *Controller) error { @@ -685,7 +682,6 @@ func (c *Controller) processNextUpdateStatusVpcWorkItem() bool { c.updateVpcStatusQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -715,7 +711,6 @@ func (c *Controller) processNextAddVpcWorkItem() bool { c.addOrUpdateVpcQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) c.addOrUpdateVpcQueue.AddRateLimited(obj) @@ -746,7 +741,6 @@ func (c *Controller) processNextDeleteVpcWorkItem() bool { c.delVpcQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -777,12 +771,12 @@ func (c *Controller) getVpcSubnets(vpc *kubeovnv1.Vpc) (subnets []string, defaul // createVpcRouter create router to connect logical switches in vpc func (c *Controller) createVpcRouter(lr string) error { - return c.ovnNbClient.CreateLogicalRouter(lr) + return c.OVNNbClient.CreateLogicalRouter(lr) } // deleteVpcRouter delete router to connect logical switches in vpc func (c *Controller) deleteVpcRouter(lr string) error { - return c.ovnNbClient.DeleteLogicalRouter(lr) + return c.OVNNbClient.DeleteLogicalRouter(lr) } func (c *Controller) handleAddVpcExternal(key string) error { @@ -803,7 +797,7 @@ func (c *Controller) handleAddVpcExternal(key string) error { var v4ip, v6ip, mac string klog.V(3).Infof("create vpc lrp eip %s", lrpEipName) if needCreateEip { - if v4ip, v6ip, mac, err = c.acquireIpAddress(c.config.ExternalGatewaySwitch, lrpEipName, lrpEipName); err != nil { + if v4ip, v6ip, mac, err = c.acquireIPAddress(c.config.ExternalGatewaySwitch, lrpEipName, lrpEipName); err != nil { klog.Errorf("failed to acquire ip address for lrp eip %s, %v", lrpEipName, err) return err } @@ -840,11 +834,11 @@ func (c *Controller) handleAddVpcExternal(key string) error { return err } - v4ipCidr := util.GetIpAddrWithMask(v4ip, cachedSubnet.Spec.CIDRBlock) + v4ipCidr := util.GetIPAddrWithMask(v4ip, cachedSubnet.Spec.CIDRBlock) lspName := fmt.Sprintf("%s-%s", c.config.ExternalGatewaySwitch, key) lrpName := fmt.Sprintf("%s-%s", key, c.config.ExternalGatewaySwitch) - if err := c.ovnNbClient.CreateLogicalPatchPort(c.config.ExternalGatewaySwitch, key, lspName, lrpName, v4ipCidr, mac, chassises...); err != nil { + if err := c.OVNNbClient.CreateLogicalPatchPort(c.config.ExternalGatewaySwitch, key, lspName, lrpName, v4ipCidr, mac, chassises...); err != nil { klog.Errorf("failed to connect router '%s' to external: %v", key, err) return err } @@ -914,7 +908,7 @@ func (c *Controller) handleDelVpcExternal(key string) error { lspName := fmt.Sprintf("%s-%s", c.config.ExternalGatewaySwitch, key) lrpName := fmt.Sprintf("%s-%s", key, c.config.ExternalGatewaySwitch) klog.V(3).Infof("delete vpc lrp %s", lrpName) - if err := c.ovnNbClient.RemoveLogicalPatchPort(lspName, lrpName); err != nil { + if err := c.OVNNbClient.RemoveLogicalPatchPort(lspName, lrpName); err != nil { klog.Errorf("failed to disconnect router '%s' to external, %v", key, err) return err } @@ -925,7 +919,7 @@ func (c *Controller) handleDelVpcExternal(key string) error { return err } } - if err := c.ovnNbClient.DeleteBFD(lrpName, ""); err != nil { + if err := c.OVNNbClient.DeleteBFD(lrpName, ""); err != nil { klog.Error(err) return err } diff --git a/pkg/controller/vpc_dns.go b/pkg/controller/vpc_dns.go index 451fbb874cb..cee1dd15760 100644 --- a/pkg/controller/vpc_dns.go +++ b/pkg/controller/vpc_dns.go @@ -49,7 +49,7 @@ const ( CorednsTemplateDep = "coredns-template.yaml" ) -func genVpcDnsDpName(name string) string { +func genVpcDNSDpName(name string) string { return fmt.Sprintf("vpc-dns-%s", name) } @@ -83,8 +83,7 @@ func hostConfigFromReader() error { return err } -func (c *Controller) enqueueAddVpcDns(obj interface{}) { - +func (c *Controller) enqueueAddVpcDNS(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -92,27 +91,27 @@ func (c *Controller) enqueueAddVpcDns(obj interface{}) { return } klog.V(3).Infof("enqueue add vpc-dns %s", key) - c.addOrUpdateVpcDnsQueue.Add(key) + c.addOrUpdateVpcDNSQueue.Add(key) } -func (c *Controller) enqueueUpdateVpcDns(old, new interface{}) { +func (c *Controller) enqueueUpdateVpcDNS(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - oldVpcDns := old.(*kubeovnv1.VpcDns) - newVpcDns := new.(*kubeovnv1.VpcDns) - if oldVpcDns.ResourceVersion != newVpcDns.ResourceVersion && - !reflect.DeepEqual(oldVpcDns.Spec, newVpcDns.Spec) { + oldVPCDNS := oldObj.(*kubeovnv1.VpcDns) + newVPCDNS := newObj.(*kubeovnv1.VpcDns) + if oldVPCDNS.ResourceVersion != newVPCDNS.ResourceVersion && + !reflect.DeepEqual(oldVPCDNS.Spec, newVPCDNS.Spec) { klog.V(3).Infof("enqueue update vpc-dns %s", key) - c.addOrUpdateVpcDnsQueue.Add(key) + c.addOrUpdateVpcDNSQueue.Add(key) } } -func (c *Controller) enqueueDeleteVpcDns(obj interface{}) { +func (c *Controller) enqueueDeleteVPCDNS(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -120,21 +119,21 @@ func (c *Controller) enqueueDeleteVpcDns(obj interface{}) { return } klog.V(3).Infof("enqueue delete vpc-dns %s", key) - c.delVpcDnsQueue.Add(key) + c.delVpcDNSQueue.Add(key) } -func (c *Controller) runAddOrUpdateVpcDnsWorker() { - for c.processNextWorkItem("addOrUpdateVpcDns", c.addOrUpdateVpcDnsQueue, c.handleAddOrUpdateVpcDns) { +func (c *Controller) runAddOrUpdateVPCDNSWorker() { + for c.processNextWorkItem("addOrUpdateVpcDns", c.addOrUpdateVpcDNSQueue, c.handleAddOrUpdateVPCDNS) { } } -func (c *Controller) runDelVpcDnsWorker() { - for c.processNextWorkItem("delVpcDns", c.delVpcDnsQueue, c.handleDelVpcDns) { +func (c *Controller) runDelVPCDNSWorker() { + for c.processNextWorkItem("delVpcDns", c.delVpcDNSQueue, c.handleDelVpcDNS) { } } -func (c *Controller) handleAddOrUpdateVpcDns(key string) error { - klog.V(3).Infof("handleAddOrUpdateVpcDns %s", key) +func (c *Controller) handleAddOrUpdateVPCDNS(key string) error { + klog.V(3).Infof("handleAddOrUpdateVPCDNS %s", key) if !enableCoredns { time.Sleep(10 * time.Second) if !enableCoredns { @@ -142,7 +141,7 @@ func (c *Controller) handleAddOrUpdateVpcDns(key string) error { } } - vpcDns, err := c.vpcDnsLister.Get(key) + vpcDNS, err := c.vpcDNSLister.Get(key) if err != nil { if k8serrors.IsNotFound(err) { return nil @@ -151,14 +150,14 @@ func (c *Controller) handleAddOrUpdateVpcDns(key string) error { } defer func() { - newVpcDns := vpcDns.DeepCopy() - newVpcDns.Status.Active = true + newVPCDNS := vpcDNS.DeepCopy() + newVPCDNS.Status.Active = true if err != nil { - newVpcDns.Status.Active = false + newVPCDNS.Status.Active = false } if _, err = c.config.KubeOvnClient.KubeovnV1().VpcDnses().UpdateStatus(context.Background(), - newVpcDns, metav1.UpdateOptions{}); err != nil { + newVPCDNS, metav1.UpdateOptions{}); err != nil { err := fmt.Errorf("failed to update vpc dns status, %v", err) klog.Error(err) } @@ -176,14 +175,14 @@ func (c *Controller) handleAddOrUpdateVpcDns(key string) error { return err } - if _, err := c.vpcsLister.Get(vpcDns.Spec.Vpc); err != nil { - err := fmt.Errorf("failed to get vpc '%s', err: %v", vpcDns.Spec.Vpc, err) + if _, err := c.vpcsLister.Get(vpcDNS.Spec.Vpc); err != nil { + err := fmt.Errorf("failed to get vpc '%s', err: %v", vpcDNS.Spec.Vpc, err) klog.Error(err) return err } - if _, err := c.subnetsLister.Get(vpcDns.Spec.Subnet); err != nil { - err := fmt.Errorf("failed to get subnet '%s', err: %v", vpcDns.Spec.Subnet, err) + if _, err := c.subnetsLister.Get(vpcDNS.Spec.Subnet); err != nil { + err := fmt.Errorf("failed to get subnet '%s', err: %v", vpcDNS.Spec.Subnet, err) klog.Error(err) return err } @@ -200,20 +199,20 @@ func (c *Controller) handleAddOrUpdateVpcDns(key string) error { return err } - if err := c.checkVpcDnsDuplicated(vpcDns); err != nil { - err = fmt.Errorf("failed to deploy %s, %v", vpcDns.Name, err) + if err := c.checkVpcDNSDuplicated(vpcDNS); err != nil { + err = fmt.Errorf("failed to deploy %s, %v", vpcDNS.Name, err) klog.Error(err) return err } - if err := c.createOrUpdateVpcDnsDep(vpcDns); err != nil { - err = fmt.Errorf("failed to create or update vpc dns %s, %v", vpcDns.Name, err) + if err := c.createOrUpdateVpcDNSDep(vpcDNS); err != nil { + err = fmt.Errorf("failed to create or update vpc dns %s, %v", vpcDNS.Name, err) klog.Error(err) return err } - if err := c.createOrUpdateVpcDnsSlr(vpcDns); err != nil { - err = fmt.Errorf("failed to create or update slr for vpc dns %s, %v", vpcDns.Name, err) + if err := c.createOrUpdateVpcDNSSlr(vpcDNS); err != nil { + err = fmt.Errorf("failed to create or update slr for vpc dns %s, %v", vpcDNS.Name, err) klog.Error(err) return err } @@ -221,9 +220,9 @@ func (c *Controller) handleAddOrUpdateVpcDns(key string) error { return err } -func (c *Controller) handleDelVpcDns(key string) error { - klog.V(3).Infof("handleDelVpcDns,%s", key) - name := genVpcDnsDpName(key) +func (c *Controller) handleDelVpcDNS(key string) error { + klog.V(3).Infof("handleDelVpcDNS,%s", key) + name := genVpcDNSDpName(key) err := c.config.KubeClient.AppsV1().Deployments(c.config.PodNamespace).Delete(context.Background(), name, metav1.DeleteOptions{}) if err != nil && !k8serrors.IsNotFound(err) { err := fmt.Errorf("failed to delete vpc dns deployment: %v", err) @@ -240,8 +239,8 @@ func (c *Controller) handleDelVpcDns(key string) error { return nil } -func (c *Controller) checkVpcDnsDuplicated(vpcDns *kubeovnv1.VpcDns) error { - vpcDnsList, err := c.vpcDnsLister.List(labels.Everything()) +func (c *Controller) checkVpcDNSDuplicated(vpcDNS *kubeovnv1.VpcDns) error { + vpcDNSList, err := c.vpcDNSLister.List(labels.Everything()) if err != nil { if k8serrors.IsNotFound(err) { return nil @@ -249,10 +248,10 @@ func (c *Controller) checkVpcDnsDuplicated(vpcDns *kubeovnv1.VpcDns) error { return err } - for _, item := range vpcDnsList { + for _, item := range vpcDNSList { if item.Status.Active && - item.Name != vpcDns.Name && - item.Spec.Vpc == vpcDns.Spec.Vpc { + item.Name != vpcDNS.Name && + item.Spec.Vpc == vpcDNS.Spec.Vpc { err = fmt.Errorf("only one vpc-dns can be deployed in a vpc") return err } @@ -260,11 +259,10 @@ func (c *Controller) checkVpcDnsDuplicated(vpcDns *kubeovnv1.VpcDns) error { return nil } -func (c *Controller) createOrUpdateVpcDnsDep(vpcDns *kubeovnv1.VpcDns) error { +func (c *Controller) createOrUpdateVpcDNSDep(vpcDNS *kubeovnv1.VpcDns) error { needToCreateDp := false oldDp, err := c.config.KubeClient.AppsV1().Deployments(c.config.PodNamespace). - Get(context.Background(), genVpcDnsDpName(vpcDns.Name), metav1.GetOptions{}) - + Get(context.Background(), genVpcDNSDpName(vpcDNS.Name), metav1.GetOptions{}) if err != nil { if k8serrors.IsNotFound(err) { needToCreateDp = true @@ -273,7 +271,7 @@ func (c *Controller) createOrUpdateVpcDnsDep(vpcDns *kubeovnv1.VpcDns) error { } } - newDp, err := c.genVpcDnsDeployment(vpcDns, oldDp) + newDp, err := c.genVpcDNSDeployment(vpcDNS, oldDp) if err != nil { klog.Errorf("failed to generate vpc-dns deployment, %v", err) return err @@ -282,7 +280,6 @@ func (c *Controller) createOrUpdateVpcDnsDep(vpcDns *kubeovnv1.VpcDns) error { if needToCreateDp { _, err := c.config.KubeClient.AppsV1().Deployments(c.config.PodNamespace). Create(context.Background(), newDp, metav1.CreateOptions{}) - if err != nil { klog.Errorf("failed to create deployment '%s', err: %s", newDp.Name, err) return err @@ -290,7 +287,6 @@ func (c *Controller) createOrUpdateVpcDnsDep(vpcDns *kubeovnv1.VpcDns) error { } else { _, err := c.config.KubeClient.AppsV1().Deployments(c.config.PodNamespace). Update(context.Background(), newDp, metav1.UpdateOptions{}) - if err != nil { klog.Errorf("failed to update deployment '%s', err: %v", newDp.Name, err) return err @@ -299,9 +295,9 @@ func (c *Controller) createOrUpdateVpcDnsDep(vpcDns *kubeovnv1.VpcDns) error { return nil } -func (c *Controller) createOrUpdateVpcDnsSlr(vpcDns *kubeovnv1.VpcDns) error { +func (c *Controller) createOrUpdateVpcDNSSlr(vpcDNS *kubeovnv1.VpcDns) error { needToCreateSlr := false - oldSlr, err := c.switchLBRuleLister.Get(genVpcDnsDpName(vpcDns.Name)) + oldSlr, err := c.switchLBRuleLister.Get(genVpcDNSDpName(vpcDNS.Name)) if err != nil { if k8serrors.IsNotFound(err) { needToCreateSlr = true @@ -311,7 +307,7 @@ func (c *Controller) createOrUpdateVpcDnsSlr(vpcDns *kubeovnv1.VpcDns) error { } } - newSlr, err := c.genVpcDnsSlr(vpcDns.Name, c.config.PodNamespace) + newSlr, err := c.genVpcDNSSlr(vpcDNS.Name, c.config.PodNamespace) if err != nil { klog.Errorf("failed to generate vpc-dns switchLBRule, %v", err) return err @@ -338,7 +334,7 @@ func (c *Controller) createOrUpdateVpcDnsSlr(vpcDns *kubeovnv1.VpcDns) error { return nil } -func (c *Controller) genVpcDnsDeployment(vpcDns *kubeovnv1.VpcDns, oldDeploy *v1.Deployment) (*v1.Deployment, error) { +func (c *Controller) genVpcDNSDeployment(vpcDNS *kubeovnv1.VpcDns, oldDeploy *v1.Deployment) (*v1.Deployment, error) { if _, err := os.Stat(CorednsTemplateDep); errors.Is(err, os.ErrNotExist) { klog.Errorf("failed to get coredns template file, %v", err) return nil, err @@ -351,7 +347,7 @@ func (c *Controller) genVpcDnsDeployment(vpcDns *kubeovnv1.VpcDns, oldDeploy *v1 } buffer := new(bytes.Buffer) - name := genVpcDnsDpName(vpcDns.Name) + name := genVpcDNSDpName(vpcDNS.Name) if err := tmp.Execute(buffer, map[string]interface{}{ "DeployName": name, "CorednsImage": corednsImage, @@ -360,13 +356,13 @@ func (c *Controller) genVpcDnsDeployment(vpcDns *kubeovnv1.VpcDns, oldDeploy *v1 } dep := &v1.Deployment{} - retJson, err := yaml.ToJSON(buffer.Bytes()) + retJSON, err := yaml.ToJSON(buffer.Bytes()) if err != nil { klog.Errorf("failed to switch yaml, %v", err) return nil, err } - if err := json.Unmarshal(retJson, dep); err != nil { + if err := json.Unmarshal(retJSON, dep); err != nil { klog.Errorf("failed to switch json, %v", err) return nil, err } @@ -378,11 +374,11 @@ func (c *Controller) genVpcDnsDeployment(vpcDns *kubeovnv1.VpcDns, oldDeploy *v1 } dep.ObjectMeta.Labels = map[string]string{ - util.VpcDnsNameLabel: "true", + util.VpcDNSNameLabel: "true", } - setCoreDnsEnv(dep) - setVpcDnsInterface(dep, vpcDns.Spec.Subnet) + setCoreDNSEnv(dep) + setVpcDNSInterface(dep, vpcDNS.Spec.Subnet) defaultSubnet, err := c.subnetsLister.Get(util.DefaultSubnet) if err != nil { @@ -393,12 +389,12 @@ func (c *Controller) genVpcDnsDeployment(vpcDns *kubeovnv1.VpcDns, oldDeploy *v1 klog.Errorf("failed to resync vpc nat config, err: %v", err) return nil, err } - setVpcDnsRoute(dep, defaultSubnet.Spec.Gateway) + setVpcDNSRoute(dep, defaultSubnet.Spec.Gateway) return dep, nil } -func (c *Controller) genVpcDnsSlr(vpcName, namespace string) (*kubeovnv1.SwitchLBRule, error) { - name := genVpcDnsDpName(vpcName) +func (c *Controller) genVpcDNSSlr(vpcName, namespace string) (*kubeovnv1.SwitchLBRule, error) { + name := genVpcDNSDpName(vpcName) label := fmt.Sprintf("%s:%s", CorednsLabelKey, name) ports := []kubeovnv1.SlrPort{ @@ -411,7 +407,7 @@ func (c *Controller) genVpcDnsSlr(vpcName, namespace string) (*kubeovnv1.SwitchL ObjectMeta: metav1.ObjectMeta{ Name: name, Labels: map[string]string{ - util.VpcDnsNameLabel: "true", + util.VpcDNSNameLabel: "true", }, }, Spec: kubeovnv1.SwitchLBRuleSpec{ @@ -426,14 +422,14 @@ func (c *Controller) genVpcDnsSlr(vpcName, namespace string) (*kubeovnv1.SwitchL return slr, nil } -func setVpcDnsInterface(dp *v1.Deployment, subnetName string) { +func setVpcDNSInterface(dp *v1.Deployment, subnetName string) { annotations := dp.Spec.Template.Annotations annotations[util.LogicalSwitchAnnotation] = subnetName annotations[util.AttachmentNetworkAnnotation] = fmt.Sprintf("%s/%s", corev1.NamespaceDefault, nadName) annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, nadProvider)] = util.DefaultSubnet } -func setCoreDnsEnv(dp *v1.Deployment) { +func setCoreDNSEnv(dp *v1.Deployment) { var env []corev1.EnvVar if len(k8sServiceHost) != 0 { @@ -452,7 +448,7 @@ func setCoreDnsEnv(dp *v1.Deployment) { } } -func setVpcDnsRoute(dp *v1.Deployment, subnetGw string) { +func setVpcDNSRoute(dp *v1.Deployment, subnetGw string) { var serviceHost string if len(k8sServiceHost) == 0 { serviceHost = os.Getenv("KUBERNETES_SERVICE_HOST") @@ -509,17 +505,17 @@ func (c *Controller) checkOvnDefaultSpecProvider() error { return nil } -func (c *Controller) resyncVpcDnsConfig() { - cm, err := c.configMapsLister.ConfigMaps(c.config.PodNamespace).Get(util.VpcDnsConfig) +func (c *Controller) resyncVpcDNSConfig() { + cm, err := c.configMapsLister.ConfigMaps(c.config.PodNamespace).Get(util.VpcDNSConfig) if err != nil && !k8serrors.IsNotFound(err) { - klog.Errorf("failed to get %s, %v", util.VpcDnsConfig, err) + klog.Errorf("failed to get %s, %v", util.VpcDNSConfig, err) return } if k8serrors.IsNotFound(err) { klog.V(3).Infof("the vpc-dns configuration is not set ") if len(cmVersion) != 0 { - if err := c.cleanVpcDns(); err != nil { + if err := c.cleanVpcDNS(); err != nil { klog.Errorf("failed to clear all vpc-dns, %v", err) return } @@ -530,10 +526,9 @@ func (c *Controller) resyncVpcDnsConfig() { if cmVersion == cm.ResourceVersion { return - } else { - cmVersion = cm.ResourceVersion - klog.V(3).Infof("the vpc-dns ConfigMap update") } + cmVersion = cm.ResourceVersion + klog.V(3).Infof("the vpc-dns ConfigMap update") getValue := func(key string) string { if v, ok := cm.Data[key]; ok { @@ -544,7 +539,7 @@ func (c *Controller) resyncVpcDnsConfig() { corednsImage = getValue("coredns-image") if len(corednsImage) == 0 { - defaultImage, err := c.getDefaultCoreDnsImage() + defaultImage, err := c.getDefaultCoreDNSImage() if err != nil { klog.Errorf("failed to get kube-system/coredns image, %s", err) return @@ -553,7 +548,7 @@ func (c *Controller) resyncVpcDnsConfig() { klog.V(3).Infof("use the cluster default coredns image version, %s", corednsImage) } - if err := os.WriteFile(CorednsTemplateDep, corednsTemplateContent, 0644); err != nil { + if err := os.WriteFile(CorednsTemplateDep, corednsTemplateContent, 0o644); err != nil { klog.Errorf("failed to wirite local coredns-template.yaml file, %v", err) return } @@ -575,12 +570,12 @@ func (c *Controller) resyncVpcDnsConfig() { } if enableCoredns && !newEnableCoredns { - if err := c.cleanVpcDns(); err != nil { + if err := c.cleanVpcDNS(); err != nil { klog.Errorf("failed to clear all vpc-dns, %v", err) return } } else { - if err := c.updateVpcDns(); err != nil { + if err := c.updateVpcDNS(); err != nil { klog.Errorf("failed to update vpc-dns deployment") return } @@ -588,7 +583,7 @@ func (c *Controller) resyncVpcDnsConfig() { enableCoredns = newEnableCoredns } -func (c *Controller) getDefaultCoreDnsImage() (string, error) { +func (c *Controller) getDefaultCoreDNSImage() (string, error) { dp, err := c.config.KubeClient.AppsV1().Deployments("kube-system"). Get(context.Background(), "coredns", metav1.GetOptions{}) if err != nil { @@ -605,17 +600,17 @@ func (c *Controller) getDefaultCoreDnsImage() (string, error) { return "", fmt.Errorf("coredns container no found") } -func (c *Controller) initVpcDnsConfig() error { +func (c *Controller) initVpcDNSConfig() error { if err := hostConfigFromReader(); err != nil { klog.Errorf("failed to get get host nameserver, %v", err) return err } - c.resyncVpcDnsConfig() + c.resyncVpcDNSConfig() return nil } -func (c *Controller) cleanVpcDns() error { +func (c *Controller) cleanVpcDNS() error { klog.Infof("clear all vpc-dns") err := c.config.KubeOvnClient.KubeovnV1().VpcDnses().DeleteCollection(context.Background(), metav1.DeleteOptions{}, metav1.ListOptions{}) @@ -627,15 +622,15 @@ func (c *Controller) cleanVpcDns() error { return nil } -func (c *Controller) updateVpcDns() error { - list, err := c.vpcDnsLister.List(labels.Everything()) +func (c *Controller) updateVpcDNS() error { + list, err := c.vpcDNSLister.List(labels.Everything()) if err != nil { klog.Errorf("failed to get vpc-dns list, %s", err) return err } for _, vd := range list { - c.addOrUpdateVpcDnsQueue.Add(vd.Name) + c.addOrUpdateVpcDNSQueue.Add(vd.Name) } return nil } diff --git a/pkg/controller/vpc_nat.go b/pkg/controller/vpc_nat.go index 3d39b769127..a32693c0b6d 100644 --- a/pkg/controller/vpc_nat.go +++ b/pkg/controller/vpc_nat.go @@ -8,9 +8,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -var ( - vpcNatImage = "" -) +var vpcNatImage = "" func (c *Controller) resyncVpcNatImage() error { cm, err := c.configMapsLister.ConfigMaps(c.config.PodNamespace).Get(util.VpcNatConfig) diff --git a/pkg/controller/vpc_nat_gateway.go b/pkg/controller/vpc_nat_gateway.go index 65bc1a791f2..0596b8c577f 100644 --- a/pkg/controller/vpc_nat_gateway.go +++ b/pkg/controller/vpc_nat_gateway.go @@ -26,9 +26,9 @@ import ( ) var ( - vpcNatEnabled = "unknown" - VpcNatCmVersion = "" - NAT_GW_CREATED_AT = "" + vpcNatEnabled = "unknown" + VpcNatCmVersion = "" + natGwCreatedAT = "" ) const ( @@ -74,31 +74,28 @@ func (c *Controller) resyncVpcNatGwConfig() { VpcNatCmVersion = "" klog.Info("finish clean up vpc nat gateway") return - } else { - if vpcNatEnabled == "true" && VpcNatCmVersion == cm.ResourceVersion { - return - } - gws, err := c.vpcNatGatewayLister.List(labels.Everything()) - if err != nil { - klog.Errorf("failed to get vpc nat gateway, %v", err) - return - } - if err = c.resyncVpcNatImage(); err != nil { - klog.Errorf("failed to resync vpc nat config, err: %v", err) - return - } - vpcNatEnabled = "true" - VpcNatCmVersion = cm.ResourceVersion - for _, gw := range gws { - c.addOrUpdateVpcNatGatewayQueue.Add(gw.Name) - } - klog.Info("finish establishing vpc-nat-gateway") + } + if vpcNatEnabled == "true" && VpcNatCmVersion == cm.ResourceVersion { + return + } + gws, err := c.vpcNatGatewayLister.List(labels.Everything()) + if err != nil { + klog.Errorf("failed to get vpc nat gateway, %v", err) return } + if err = c.resyncVpcNatImage(); err != nil { + klog.Errorf("failed to resync vpc nat config, err: %v", err) + return + } + vpcNatEnabled = "true" + VpcNatCmVersion = cm.ResourceVersion + for _, gw := range gws { + c.addOrUpdateVpcNatGatewayQueue.Add(gw.Name) + } + klog.Info("finish establishing vpc-nat-gateway") } func (c *Controller) enqueueAddVpcNatGw(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -109,10 +106,10 @@ func (c *Controller) enqueueAddVpcNatGw(obj interface{}) { c.addOrUpdateVpcNatGatewayQueue.Add(key) } -func (c *Controller) enqueueUpdateVpcNatGw(old, new interface{}) { +func (c *Controller) enqueueUpdateVpcNatGw(_, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } @@ -146,8 +143,8 @@ func (c *Controller) runDelVpcNatGwWorker() { } } -func (c *Controller) runUpdateVpcFloatingIpWorker() { - for c.processNextWorkItem("updateVpcFloatingIp", c.updateVpcFloatingIpQueue, c.handleUpdateVpcFloatingIp) { +func (c *Controller) runUpdateVpcFloatingIPWorker() { + for c.processNextWorkItem("updateVpcFloatingIp", c.updateVpcFloatingIPQueue, c.handleUpdateVpcFloatingIP) { } } @@ -192,7 +189,6 @@ func (c *Controller) processNextWorkItem(processName string, queue workqueue.Rat queue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(fmt.Errorf("process: %s. err: %v", processName, err)) queue.AddRateLimited(obj) @@ -217,7 +213,6 @@ func (c *Controller) handleDelVpcNatGw(key string) error { } func isVpcNatGwChanged(gw *kubeovnv1.VpcNatGateway) bool { - if !reflect.DeepEqual(gw.Spec.ExternalSubnets, gw.Status.ExternalSubnets) { gw.Status.ExternalSubnets = gw.Spec.ExternalSubnets return true @@ -270,7 +265,6 @@ func (c *Controller) handleAddOrUpdateVpcNatGw(key string) error { needToUpdate := false oldSts, err := c.config.KubeClient.AppsV1().StatefulSets(c.config.PodNamespace). Get(context.Background(), util.GenNatGwStsName(gw.Name), metav1.GetOptions{}) - if err != nil { if k8serrors.IsNotFound(err) { needToCreate = true @@ -284,7 +278,8 @@ func (c *Controller) handleAddOrUpdateVpcNatGw(key string) error { needToUpdate = true } - if needToCreate { + switch { + case needToCreate: // if pod create successfully, will add initVpcNatGatewayQueue if _, err := c.config.KubeClient.AppsV1().StatefulSets(c.config.PodNamespace). Create(context.Background(), newSts, metav1.CreateOptions{}); err != nil { @@ -297,7 +292,7 @@ func (c *Controller) handleAddOrUpdateVpcNatGw(key string) error { return err } return nil - } else if needToUpdate { + case needToUpdate: if _, err := c.config.KubeClient.AppsV1().StatefulSets(c.config.PodNamespace). Update(context.Background(), newSts, metav1.UpdateOptions{}); err != nil { err := fmt.Errorf("failed to update statefulset '%s', err: %v", newSts.Name, err) @@ -308,7 +303,7 @@ func (c *Controller) handleAddOrUpdateVpcNatGw(key string) error { klog.Errorf("failed to patch nat gw sts status for nat gw %s, %v", key, err) return err } - } else { + default: // check if need to change qos if gw.Spec.QoSPolicy != gw.Status.QoSPolicy { if gw.Status.QoSPolicy != "" { @@ -374,8 +369,8 @@ func (c *Controller) handleInitVpcNatGw(key string) error { if _, hasInit := pod.Annotations[util.VpcNatGatewayInitAnnotation]; hasInit { return nil } - NAT_GW_CREATED_AT = pod.CreationTimestamp.Format("2006-01-02T15:04:05") - klog.V(3).Infof("nat gw pod '%s' inited at %s", key, NAT_GW_CREATED_AT) + natGwCreatedAT = pod.CreationTimestamp.Format("2006-01-02T15:04:05") + klog.V(3).Infof("nat gw pod '%s' inited at %s", key, natGwCreatedAT) if err = c.execNatGwRules(pod, natGwInit, []string{fmt.Sprintf("%s,%s", c.config.ServiceClusterIPRange, pod.Annotations[util.GatewayAnnotation])}); err != nil { err = fmt.Errorf("failed to init vpc nat gateway, %v", err) klog.Error(err) @@ -402,7 +397,7 @@ func (c *Controller) handleInitVpcNatGw(key string) error { return err } - c.updateVpcFloatingIpQueue.Add(key) + c.updateVpcFloatingIPQueue.Add(key) c.updateVpcDnatQueue.Add(key) c.updateVpcSnatQueue.Add(key) c.updateVpcSubnetQueue.Add(key) @@ -422,7 +417,7 @@ func (c *Controller) handleInitVpcNatGw(key string) error { return nil } -func (c *Controller) handleUpdateVpcFloatingIp(natGwKey string) error { +func (c *Controller) handleUpdateVpcFloatingIP(natGwKey string) error { if vpcNatEnabled != "true" { return fmt.Errorf("iptables nat gw not enable") } @@ -446,9 +441,9 @@ func (c *Controller) handleUpdateVpcFloatingIp(natGwKey string) error { } for _, fip := range fips { - if fip.Status.Redo != NAT_GW_CREATED_AT { + if fip.Status.Redo != natGwCreatedAT { klog.V(3).Infof("redo fip %s", fip.Name) - if err = c.redoFip(fip.Name, NAT_GW_CREATED_AT, false); err != nil { + if err = c.redoFip(fip.Name, natGwCreatedAT, false); err != nil { klog.Errorf("failed to update eip '%s' to re-apply, %v", fip.Spec.EIP, err) return err } @@ -479,9 +474,9 @@ func (c *Controller) handleUpdateVpcEip(natGwKey string) error { return err } for _, eip := range eips { - if eip.Spec.NatGwDp == natGwKey && eip.Status.Redo != NAT_GW_CREATED_AT { + if eip.Spec.NatGwDp == natGwKey && eip.Status.Redo != natGwCreatedAT { klog.V(3).Infof("redo eip %s", eip.Name) - if err = c.patchEipStatus(eip.Name, "", NAT_GW_CREATED_AT, "", false); err != nil { + if err = c.patchEipStatus(eip.Name, "", natGwCreatedAT, "", false); err != nil { klog.Errorf("failed to update eip '%s' to re-apply, %v", eip.Name, err) return err } @@ -512,9 +507,9 @@ func (c *Controller) handleUpdateVpcSnat(natGwKey string) error { return err } for _, snat := range snats { - if snat.Status.Redo != NAT_GW_CREATED_AT { + if snat.Status.Redo != natGwCreatedAT { klog.V(3).Infof("redo snat %s", snat.Name) - if err = c.redoSnat(snat.Name, NAT_GW_CREATED_AT, false); err != nil { + if err = c.redoSnat(snat.Name, natGwCreatedAT, false); err != nil { err = fmt.Errorf("failed to update eip '%s' to re-apply, %v", snat.Spec.EIP, err) klog.Error(err) return err @@ -547,9 +542,9 @@ func (c *Controller) handleUpdateVpcDnat(natGwKey string) error { return err } for _, dnat := range dnats { - if dnat.Status.Redo != NAT_GW_CREATED_AT { + if dnat.Status.Redo != natGwCreatedAT { klog.V(3).Infof("redo dnat %s", dnat.Name) - if err = c.redoDnat(dnat.Name, NAT_GW_CREATED_AT, false); err != nil { + if err = c.redoDnat(dnat.Name, natGwCreatedAT, false); err != nil { err := fmt.Errorf("failed to update dnat '%s' to redo, %v", dnat.Name, err) klog.Error(err) return err @@ -564,7 +559,6 @@ func (c *Controller) getIptablesVersion(pod *corev1.Pod) (version string, err er cmd := fmt.Sprintf("bash /kube-ovn/nat-gateway.sh %s", operation) klog.V(3).Infof(cmd) stdOutput, errOutput, err := util.ExecuteCommandInContainer(c.config.KubeClient, c.config.KubeRestConfig, pod.Namespace, pod.Name, "vpc-nat-gw", []string{"/bin/bash", "-c", cmd}...) - if err != nil { if len(errOutput) > 0 { klog.Errorf("failed to ExecuteCommandInContainer, errOutput: %v", errOutput) @@ -718,7 +712,6 @@ func (c *Controller) execNatGwRules(pod *corev1.Pod, operation string, rules []s cmd := fmt.Sprintf("bash /kube-ovn/nat-gateway.sh %s %s", operation, strings.Join(rules, " ")) klog.V(3).Infof(cmd) stdOutput, errOutput, err := util.ExecuteCommandInContainer(c.config.KubeClient, c.config.KubeRestConfig, pod.Namespace, pod.Name, "vpc-nat-gw", []string{"/bin/bash", "-c", cmd}...) - if err != nil { if len(errOutput) > 0 { klog.Errorf("failed to ExecuteCommandInContainer, errOutput: %v", errOutput) @@ -759,7 +752,7 @@ func (c *Controller) genNatGwStatefulSet(gw *kubeovnv1.VpcNatGateway, oldSts *v1 util.VpcNatGatewayAnnotation: gw.Name, util.AttachmentNetworkAnnotation: fmt.Sprintf("%s/%s", c.config.PodNamespace, externalNetwork), util.LogicalSwitchAnnotation: gw.Spec.Subnet, - util.IpAddressAnnotation: gw.Spec.LanIp, + util.IPAddressAnnotation: gw.Spec.LanIP, } for key, value := range podAnnotations { newPodAnnotations[key] = value @@ -835,15 +828,17 @@ func (c *Controller) getNatGwPod(name string) (*corev1.Pod, error) { }) pods, err := c.podsLister.Pods(c.config.PodNamespace).List(sel) - if err != nil { + + switch { + case err != nil: klog.Error(err) return nil, err - } else if len(pods) == 0 { + case len(pods) == 0: return nil, k8serrors.NewNotFound(v1.Resource("pod"), name) - } else if len(pods) != 1 { + case len(pods) != 1: time.Sleep(5 * time.Second) return nil, fmt.Errorf("too many pod") - } else if pods[0].Status.Phase != "Running" { + case pods[0].Status.Phase != "Running": time.Sleep(5 * time.Second) return nil, fmt.Errorf("pod is not active now") } @@ -852,7 +847,7 @@ func (c *Controller) getNatGwPod(name string) (*corev1.Pod, error) { } func (c *Controller) initCreateAt(key string) (err error) { - if NAT_GW_CREATED_AT != "" { + if natGwCreatedAT != "" { return nil } pod, err := c.getNatGwPod(key) @@ -860,11 +855,11 @@ func (c *Controller) initCreateAt(key string) (err error) { klog.Error(err) return err } - NAT_GW_CREATED_AT = pod.CreationTimestamp.Format("2006-01-02T15:04:05") + natGwCreatedAT = pod.CreationTimestamp.Format("2006-01-02T15:04:05") return nil } -func (c *Controller) updateCrdNatGwLabels(key string, qos string) error { +func (c *Controller) updateCrdNatGwLabels(key, qos string) error { gw, err := c.vpcNatGatewayLister.Get(key) if err != nil { errMsg := fmt.Errorf("failed to get vpc nat gw '%s', %v", key, err) @@ -1012,7 +1007,7 @@ func (c *Controller) patchNatGwStatus(key string) error { return nil } -func (c *Controller) execNatGwQoS(gw *kubeovnv1.VpcNatGateway, qos string, operation string) error { +func (c *Controller) execNatGwQoS(gw *kubeovnv1.VpcNatGateway, qos, operation string) error { qosPolicy, err := c.qosPoliciesLister.Get(qos) if err != nil { klog.Errorf("get qos policy %s failed: %v", qos, err) @@ -1043,7 +1038,8 @@ func (c *Controller) execNatGwBandtithLimitRules(gw *kubeovnv1.VpcNatGateway, ru } func (c *Controller) execNatGwQoSInPod( - dp string, r *kubeovnv1.QoSPolicyBandwidthLimitRule, operation string) error { + dp string, r *kubeovnv1.QoSPolicyBandwidthLimitRule, operation string, +) error { gwPod, err := c.getNatGwPod(dp) if err != nil { klog.Errorf("failed to get nat gw pod, %v", err) @@ -1051,7 +1047,8 @@ func (c *Controller) execNatGwQoSInPod( } var addRules []string var classifierType, matchDirection, cidr string - if r.MatchType == "ip" { + switch { + case r.MatchType == "ip": classifierType = "u32" // matchValue: dst xxx.xxx.xxx.xxx/32 splitStr := strings.Split(r.MatchValue, " ") @@ -1062,9 +1059,9 @@ func (c *Controller) execNatGwQoSInPod( } matchDirection = splitStr[0] cidr = splitStr[1] - } else if r.MatchType == "" { + case r.MatchType == "": classifierType = "matchall" - } else { + default: err := fmt.Errorf("MatchType %s format error", r.MatchType) klog.Error(err) return err diff --git a/pkg/controller/vpc_nat_gw_eip.go b/pkg/controller/vpc_nat_gw_eip.go index 35927b5cbbd..1bbaf75b90c 100644 --- a/pkg/controller/vpc_nat_gw_eip.go +++ b/pkg/controller/vpc_nat_gw_eip.go @@ -21,7 +21,6 @@ import ( ) func (c *Controller) enqueueAddIptablesEip(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -32,15 +31,15 @@ func (c *Controller) enqueueAddIptablesEip(obj interface{}) { c.addIptablesEipQueue.Add(key) } -func (c *Controller) enqueueUpdateIptablesEip(old, new interface{}) { +func (c *Controller) enqueueUpdateIptablesEip(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - oldEip := old.(*kubeovnv1.IptablesEIP) - newEip := new.(*kubeovnv1.IptablesEIP) + oldEip := oldObj.(*kubeovnv1.IptablesEIP) + newEip := newObj.(*kubeovnv1.IptablesEIP) if !newEip.DeletionTimestamp.IsZero() || oldEip.Status.Redo != newEip.Status.Redo || oldEip.Spec.QoSPolicy != newEip.Spec.QoSPolicy { @@ -107,7 +106,6 @@ func (c *Controller) processNextAddIptablesEipWorkItem() bool { c.addIptablesEipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -137,7 +135,6 @@ func (c *Controller) processNextResetIptablesEipWorkItem() bool { c.resetIptablesEipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -194,7 +191,6 @@ func (c *Controller) processNextDeleteIptablesEipWorkItem() bool { c.delIptablesEipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -224,7 +220,7 @@ func (c *Controller) handleAddIptablesEip(key string) error { } var v4ip, v6ip, mac, eipV4Cidr, v4Gw string externalNetwork := util.GetExternalNetwork(cachedEip.Spec.ExternalSubnet) - externalProvider := fmt.Sprintf("%s.%s", externalNetwork, ATTACHMENT_NS) + externalProvider := fmt.Sprintf("%s.%s", externalNetwork, attachmentNs) portName := ovs.PodNameToPortName(cachedEip.Name, cachedEip.Namespace, externalProvider) if cachedEip.Spec.V4ip != "" { @@ -431,10 +427,7 @@ func (c *Controller) createEipInPod(dp, gw, v4Cidr string) error { var addRules []string rule := fmt.Sprintf("%s,%s", v4Cidr, gw) addRules = append(addRules, rule) - if err = c.execNatGwRules(gwPod, natGwEipAdd, addRules); err != nil { - return err - } - return nil + return c.execNatGwRules(gwPod, natGwEipAdd, addRules) } func (c *Controller) deleteEipInPod(dp, v4Cidr string) error { @@ -518,8 +511,9 @@ func (c *Controller) delEipQoS(eip *kubeovnv1.IptablesEIP, v4ip string) error { } func (c *Controller) addEipQoSInPod( - dp string, v4ip string, direction kubeovnv1.QoSPolicyRuleDirection, priority int, rate string, - burst string) error { + dp, v4ip string, direction kubeovnv1.QoSPolicyRuleDirection, priority int, rate string, + burst string, +) error { var operation string gwPod, err := c.getNatGwPod(dp) if err != nil { @@ -537,13 +531,10 @@ func (c *Controller) addEipQoSInPod( operation = natGwEipEgressQoSAdd } - if err = c.execNatGwRules(gwPod, operation, addRules); err != nil { - return err - } - return nil + return c.execNatGwRules(gwPod, operation, addRules) } -func (c *Controller) delEipQoSInPod(dp string, v4ip string, direction kubeovnv1.QoSPolicyRuleDirection) error { +func (c *Controller) delEipQoSInPod(dp, v4ip string, direction kubeovnv1.QoSPolicyRuleDirection) error { var operation string gwPod, err := c.getNatGwPod(dp) if err != nil { @@ -560,13 +551,10 @@ func (c *Controller) delEipQoSInPod(dp string, v4ip string, direction kubeovnv1. operation = natGwEipEgressQoSDel } - if err = c.execNatGwRules(gwPod, operation, delRules); err != nil { - return err - } - return nil + return c.execNatGwRules(gwPod, operation, delRules) } -func (c *Controller) acquireStaticEip(name, namespace, nicName, ip, externalSubnet string) (string, string, string, error) { +func (c *Controller) acquireStaticEip(name, _, nicName, ip, externalSubnet string) (string, string, string, error) { checkConflict := true var v4ip, v6ip, mac string var err error @@ -583,7 +571,7 @@ func (c *Controller) acquireStaticEip(name, namespace, nicName, ip, externalSubn return v4ip, v6ip, mac, nil } -func (c *Controller) acquireEip(name, namespace, nicName, externalSubnet string) (string, string, string, error) { +func (c *Controller) acquireEip(name, _, nicName, externalSubnet string) (string, string, string, error) { var skippedAddrs []string for { ipv4, ipv6, mac, err := c.ipam.GetRandomAddress(name, nicName, nil, externalSubnet, "", skippedAddrs, true) @@ -633,9 +621,8 @@ func (c *Controller) getEipV4Cidr(v4ip, externalSubnet string) (string, error) { func (c *Controller) GetGwBySubnet(name string) (string, string, error) { if subnet, ok := c.ipam.Subnets[name]; ok { return subnet.V4Gw, subnet.V6Gw, nil - } else { - return "", "", fmt.Errorf("failed to get subnet %s", name) } + return "", "", fmt.Errorf("failed to get subnet %s", name) } func (c *Controller) createOrUpdateCrdEip(key, v4ip, v6ip, mac, natGwDp, qos, externalNet string) error { @@ -660,7 +647,6 @@ func (c *Controller) createOrUpdateCrdEip(key, v4ip, v6ip, mac, natGwDp, qos, ex NatGwDp: natGwDp, }, }, metav1.CreateOptions{}) - if err != nil { errMsg := fmt.Errorf("failed to create eip crd %s, %v", key, err) klog.Error(errMsg) diff --git a/pkg/controller/vpc_nat_gw_nat.go b/pkg/controller/vpc_nat_gw_nat.go index 90a5c24014f..c78b02553e9 100644 --- a/pkg/controller/vpc_nat_gw_nat.go +++ b/pkg/controller/vpc_nat_gw_nat.go @@ -20,7 +20,6 @@ import ( ) func (c *Controller) enqueueAddIptablesFip(obj interface{}) { - var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { @@ -31,16 +30,15 @@ func (c *Controller) enqueueAddIptablesFip(obj interface{}) { c.addIptablesFipQueue.Add(key) } -func (c *Controller) enqueueUpdateIptablesFip(old, new interface{}) { - +func (c *Controller) enqueueUpdateIptablesFip(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - oldFip := old.(*kubeovnv1.IptablesFIPRule) - newFip := new.(*kubeovnv1.IptablesFIPRule) + oldFip := oldObj.(*kubeovnv1.IptablesFIPRule) + newFip := newObj.(*kubeovnv1.IptablesFIPRule) if !newFip.DeletionTimestamp.IsZero() { klog.V(3).Infof("enqueue update to clean fip %s", key) c.updateIptablesFipQueue.Add(key) @@ -53,7 +51,7 @@ func (c *Controller) enqueueUpdateIptablesFip(old, new interface{}) { if oldFip.Status.V4ip != newFip.Status.V4ip || oldFip.Spec.EIP != newFip.Spec.EIP || oldFip.Status.Redo != newFip.Status.Redo || - oldFip.Spec.InternalIp != newFip.Spec.InternalIp { + oldFip.Spec.InternalIP != newFip.Spec.InternalIP { klog.V(3).Infof("enqueue update fip %s", key) c.updateIptablesFipQueue.Add(key) return @@ -81,15 +79,15 @@ func (c *Controller) enqueueAddIptablesDnatRule(obj interface{}) { c.addIptablesDnatRuleQueue.Add(key) } -func (c *Controller) enqueueUpdateIptablesDnatRule(old, new interface{}) { +func (c *Controller) enqueueUpdateIptablesDnatRule(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - oldDnat := old.(*kubeovnv1.IptablesDnatRule) - newDnat := new.(*kubeovnv1.IptablesDnatRule) + oldDnat := oldObj.(*kubeovnv1.IptablesDnatRule) + newDnat := newObj.(*kubeovnv1.IptablesDnatRule) if !newDnat.DeletionTimestamp.IsZero() { klog.V(3).Infof("enqueue update to clean dnat %s", key) c.updateIptablesDnatRuleQueue.Add(key) @@ -105,7 +103,7 @@ func (c *Controller) enqueueUpdateIptablesDnatRule(old, new interface{}) { oldDnat.Spec.EIP != newDnat.Spec.EIP || oldDnat.Status.Redo != newDnat.Status.Redo || oldDnat.Spec.Protocol != newDnat.Spec.Protocol || - oldDnat.Spec.InternalIp != newDnat.Spec.InternalIp || + oldDnat.Spec.InternalIP != newDnat.Spec.InternalIP || oldDnat.Spec.InternalPort != newDnat.Spec.InternalPort || oldDnat.Spec.ExternalPort != newDnat.Spec.ExternalPort { klog.V(3).Infof("enqueue update dnat %s", key) @@ -134,15 +132,15 @@ func (c *Controller) enqueueAddIptablesSnatRule(obj interface{}) { c.addIptablesSnatRuleQueue.Add(key) } -func (c *Controller) enqueueUpdateIptablesSnatRule(old, new interface{}) { +func (c *Controller) enqueueUpdateIptablesSnatRule(oldObj, newObj interface{}) { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } - oldSnat := old.(*kubeovnv1.IptablesSnatRule) - newSnat := new.(*kubeovnv1.IptablesSnatRule) + oldSnat := oldObj.(*kubeovnv1.IptablesSnatRule) + newSnat := newObj.(*kubeovnv1.IptablesSnatRule) if !newSnat.DeletionTimestamp.IsZero() { klog.V(3).Infof("enqueue update to clean snat %s", key) c.updateIptablesSnatRuleQueue.Add(key) @@ -216,6 +214,7 @@ func (c *Controller) runDelIptablesSnatRuleWorker() { for c.processNextDeleteIptablesSnatRuleWorkItem() { } } + func (c *Controller) processNextAddIptablesFipWorkItem() bool { obj, shutdown := c.addIptablesFipQueue.Get() if shutdown { @@ -238,7 +237,6 @@ func (c *Controller) processNextAddIptablesFipWorkItem() bool { c.addIptablesFipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -268,7 +266,6 @@ func (c *Controller) processNextUpdateIptablesFipWorkItem() bool { c.updateIptablesFipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -298,7 +295,6 @@ func (c *Controller) processNextDeleteIptablesFipWorkItem() bool { c.delIptablesFipQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -328,7 +324,6 @@ func (c *Controller) processNextAddIptablesDnatRuleWorkItem() bool { c.addIptablesDnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -358,7 +353,6 @@ func (c *Controller) processNextUpdateIptablesDnatRuleWorkItem() bool { c.updateIptablesDnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -388,7 +382,6 @@ func (c *Controller) processNextDeleteIptablesDnatRuleWorkItem() bool { c.delIptablesDnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -418,7 +411,6 @@ func (c *Controller) processNextAddIptablesSnatRuleWorkItem() bool { c.addIptablesSnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -448,7 +440,6 @@ func (c *Controller) processNextUpdateIptablesSnatRuleWorkItem() bool { c.updateIptablesSnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -478,7 +469,6 @@ func (c *Controller) processNextDeleteIptablesSnatRuleWorkItem() bool { c.delIptablesSnatRuleQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -526,7 +516,7 @@ func (c *Controller) handleAddIptablesFip(key string) error { } // create fip nat - if err = c.createFipInPod(eip.Spec.NatGwDp, eip.Status.IP, fip.Spec.InternalIp); err != nil { + if err = c.createFipInPod(eip.Spec.NatGwDp, eip.Status.IP, fip.Spec.InternalIP); err != nil { klog.Errorf("failed to create fip, %v", err) return err } @@ -586,7 +576,7 @@ func (c *Controller) handleUpdateIptablesFip(key string) error { if !cachedFip.DeletionTimestamp.IsZero() { if vpcNatEnabled == "true" { klog.V(3).Infof("clean fip '%s' in pod", key) - if err = c.deleteFipInPod(cachedFip.Status.NatGwDp, cachedFip.Status.V4ip, cachedFip.Status.InternalIp); err != nil { + if err = c.deleteFipInPod(cachedFip.Status.NatGwDp, cachedFip.Status.V4ip, cachedFip.Status.InternalIP); err != nil { klog.Errorf("failed to delete fip %s, %v", key, err) return err } @@ -621,11 +611,11 @@ func (c *Controller) handleUpdateIptablesFip(key string) error { } klog.V(3).Infof("fip change ip, old ip '%s', new ip %s", cachedFip.Status.V4ip, eip.Status.IP) - if err = c.deleteFipInPod(cachedFip.Status.NatGwDp, cachedFip.Status.V4ip, cachedFip.Status.InternalIp); err != nil { + if err = c.deleteFipInPod(cachedFip.Status.NatGwDp, cachedFip.Status.V4ip, cachedFip.Status.InternalIP); err != nil { klog.Errorf("failed to delete old fip, %v", err) return err } - if err = c.createFipInPod(eip.Spec.NatGwDp, eip.Status.IP, cachedFip.Spec.InternalIp); err != nil { + if err = c.createFipInPod(eip.Spec.NatGwDp, eip.Status.IP, cachedFip.Spec.InternalIP); err != nil { klog.Errorf("failed to create new fip, %v", err) return err } @@ -653,7 +643,7 @@ func (c *Controller) handleUpdateIptablesFip(key string) error { cachedFip.Status.V4ip != "" && cachedFip.DeletionTimestamp.IsZero() { klog.V(3).Infof("reapply fip '%s' in pod ", key) - if err = c.createFipInPod(eip.Spec.NatGwDp, cachedFip.Status.V4ip, cachedFip.Spec.InternalIp); err != nil { + if err = c.createFipInPod(eip.Spec.NatGwDp, cachedFip.Status.V4ip, cachedFip.Spec.InternalIP); err != nil { klog.Errorf("failed to create fip, %v", err) return err } @@ -711,7 +701,7 @@ func (c *Controller) handleAddIptablesDnatRule(key string) error { } // create nat if err = c.createDnatInPod(eip.Spec.NatGwDp, dnat.Spec.Protocol, - eip.Status.IP, dnat.Spec.InternalIp, + eip.Status.IP, dnat.Spec.InternalIP, dnat.Spec.ExternalPort, dnat.Spec.InternalPort); err != nil { klog.Errorf("failed to create dnat, %v", err) return err @@ -755,7 +745,7 @@ func (c *Controller) handleUpdateIptablesDnatRule(key string) error { klog.V(3).Infof("clean dnat '%s' in pod", key) if vpcNatEnabled == "true" { if err = c.deleteDnatInPod(cachedDnat.Status.NatGwDp, cachedDnat.Status.Protocol, - cachedDnat.Status.V4ip, cachedDnat.Status.InternalIp, + cachedDnat.Status.V4ip, cachedDnat.Status.InternalIP, cachedDnat.Status.ExternalPort, cachedDnat.Status.InternalPort); err != nil { klog.Errorf("failed to delete dnat, %v", err) return err @@ -789,13 +779,13 @@ func (c *Controller) handleUpdateIptablesDnatRule(key string) error { } if err = c.deleteDnatInPod(cachedDnat.Status.NatGwDp, cachedDnat.Status.Protocol, - cachedDnat.Status.V4ip, cachedDnat.Status.InternalIp, + cachedDnat.Status.V4ip, cachedDnat.Status.InternalIP, cachedDnat.Status.ExternalPort, cachedDnat.Status.InternalPort); err != nil { klog.Errorf("failed to delete old dnat, %v", err) return err } if err = c.createDnatInPod(eip.Spec.NatGwDp, cachedDnat.Spec.Protocol, - eip.Status.IP, cachedDnat.Spec.InternalIp, + eip.Status.IP, cachedDnat.Spec.InternalIP, cachedDnat.Spec.ExternalPort, cachedDnat.Spec.InternalPort); err != nil { klog.Errorf("failed to create new dnat %s, %v", key, err) return err @@ -825,7 +815,7 @@ func (c *Controller) handleUpdateIptablesDnatRule(key string) error { cachedDnat.DeletionTimestamp.IsZero() { klog.V(3).Infof("reapply dnat in pod for %s", key) if err = c.createDnatInPod(eip.Spec.NatGwDp, cachedDnat.Spec.Protocol, - cachedDnat.Status.V4ip, cachedDnat.Spec.InternalIp, + cachedDnat.Status.V4ip, cachedDnat.Spec.InternalIP, cachedDnat.Spec.ExternalPort, cachedDnat.Spec.InternalPort); err != nil { klog.Errorf("failed to create dnat %s, %v", key, err) return err @@ -1280,8 +1270,8 @@ func (c *Controller) patchFipStatus(key, v4ip, v6ip, natGwDp, redo string, ready fip.Status.NatGwDp = natGwDp changed = true } - if ready && fip.Spec.InternalIp != "" && fip.Status.InternalIp != fip.Spec.InternalIp { - fip.Status.InternalIp = fip.Spec.InternalIp + if ready && fip.Spec.InternalIP != "" && fip.Status.InternalIP != fip.Spec.InternalIP { + fip.Status.InternalIP = fip.Spec.InternalIP changed = true } @@ -1416,8 +1406,8 @@ func (c *Controller) patchDnatStatus(key, v4ip, v6ip, natGwDp, redo string, read dnat.Status.Protocol = dnat.Spec.Protocol changed = true } - if ready && dnat.Spec.InternalIp != "" && dnat.Status.InternalIp != dnat.Spec.InternalIp { - dnat.Status.InternalIp = dnat.Spec.InternalIp + if ready && dnat.Spec.InternalIP != "" && dnat.Status.InternalIP != dnat.Spec.InternalIP { + dnat.Status.InternalIP = dnat.Spec.InternalIP changed = true } if ready && dnat.Spec.InternalPort != "" && dnat.Status.InternalPort != dnat.Spec.InternalPort { @@ -1641,14 +1631,14 @@ func (c *Controller) deleteFipInPod(dp, v4ip, internalIP string) error { return nil } -func (c *Controller) createDnatInPod(dp, protocol, v4ip, internalIp, externalPort, internalPort string) error { +func (c *Controller) createDnatInPod(dp, protocol, v4ip, internalIP, externalPort, internalPort string) error { gwPod, err := c.getNatGwPod(dp) if err != nil { klog.Errorf("failed to get nat gw pod, %v", err) return err } var addRules []string - rule := fmt.Sprintf("%s,%s,%s,%s,%s", v4ip, externalPort, protocol, internalIp, internalPort) + rule := fmt.Sprintf("%s,%s,%s,%s,%s", v4ip, externalPort, protocol, internalIP, internalPort) addRules = append(addRules, rule) if err = c.execNatGwRules(gwPod, natGwDnatAdd, addRules); err != nil { @@ -1658,7 +1648,7 @@ func (c *Controller) createDnatInPod(dp, protocol, v4ip, internalIp, externalPor return nil } -func (c *Controller) deleteDnatInPod(dp, protocol, v4ip, internalIp, externalPort, internalPort string) error { +func (c *Controller) deleteDnatInPod(dp, protocol, v4ip, internalIP, externalPort, internalPort string) error { gwPod, err := c.getNatGwPod(dp) if err != nil { if k8serrors.IsNotFound(err) { @@ -1670,7 +1660,7 @@ func (c *Controller) deleteDnatInPod(dp, protocol, v4ip, internalIp, externalPor // del nat var delRules []string - rule := fmt.Sprintf("%s,%s,%s,%s,%s", v4ip, externalPort, protocol, internalIp, internalPort) + rule := fmt.Sprintf("%s,%s,%s,%s,%s", v4ip, externalPort, protocol, internalIP, internalPort) delRules = append(delRules, rule) if err = c.execNatGwRules(gwPod, natGwDnatDel, delRules); err != nil { klog.Errorf("failed to delete dnat, err: %v", err) @@ -1780,7 +1770,7 @@ func (c *Controller) isDnatDuplicated(gwName, eipName, dnatName, externalPort st return false, nil } -func (c *Controller) createOrUpdateCrdFip(key, eipName, internalIp string) error { +func (c *Controller) createOrUpdateCrdFip(key, eipName, internalIP string) error { cachedFip, err := c.iptablesFipsLister.Get(key) if err != nil { klog.V(3).Infof("create fip cr %s", key) @@ -1791,7 +1781,7 @@ func (c *Controller) createOrUpdateCrdFip(key, eipName, internalIp string) error }, Spec: kubeovnv1.IptablesFIPRuleSpec{ EIP: eipName, - InternalIp: internalIp, + InternalIP: internalIP, }, }, metav1.CreateOptions{}); err != nil { errMsg := fmt.Errorf("failed to create fip crd %s, %v", key, err) @@ -1806,9 +1796,9 @@ func (c *Controller) createOrUpdateCrdFip(key, eipName, internalIp string) error } else { klog.V(3).Infof("update fip cr %s", key) fip := cachedFip.DeepCopy() - if fip.Spec.EIP != eipName || fip.Spec.InternalIp != internalIp { + if fip.Spec.EIP != eipName || fip.Spec.InternalIP != internalIP { fip.Spec.EIP = eipName - fip.Spec.InternalIp = internalIp + fip.Spec.InternalIP = internalIP if _, err := c.config.KubeOvnClient.KubeovnV1().IptablesFIPRules().Update(context.Background(), fip, metav1.UpdateOptions{}); err != nil { errMsg := fmt.Errorf("failed to update eip crd %s, %v", key, err) klog.Error(errMsg) diff --git a/pkg/controller/workqueue_metrics.go b/pkg/controller/workqueue_metrics.go index 01adf67dca8..eebb6217074 100644 --- a/pkg/controller/workqueue_metrics.go +++ b/pkg/controller/workqueue_metrics.go @@ -31,7 +31,7 @@ func InitWorkQueueMetrics() { workqueue.SetProvider(workqueueMetricsProvider{}) } -func registerWorkqueueMetric(c prometheus.Collector, name, queue string) { +func registerWorkqueueMetric(c prometheus.Collector, _, _ string) { prometheus.MustRegister(c) } @@ -138,27 +138,27 @@ func (workqueueMetricsProvider) NewDeprecatedLongestRunningProcessorMicroseconds // NOTE: The following deprecated metrics are noops because they were never // included in controller-runtime. -func (workqueueMetricsProvider) NewDeprecatedDepthMetric(queue string) workqueue.GaugeMetric { +func (workqueueMetricsProvider) NewDeprecatedDepthMetric(_ string) workqueue.GaugeMetric { return noopMetric{} } -func (workqueueMetricsProvider) NewDeprecatedAddsMetric(queue string) workqueue.CounterMetric { +func (workqueueMetricsProvider) NewDeprecatedAddsMetric(_ string) workqueue.CounterMetric { return noopMetric{} } -func (workqueueMetricsProvider) NewDeprecatedLatencyMetric(queue string) workqueue.SummaryMetric { +func (workqueueMetricsProvider) NewDeprecatedLatencyMetric(_ string) workqueue.SummaryMetric { return noopMetric{} } -func (workqueueMetricsProvider) NewDeprecatedWorkDurationMetric(queue string) workqueue.SummaryMetric { +func (workqueueMetricsProvider) NewDeprecatedWorkDurationMetric(_ string) workqueue.SummaryMetric { return noopMetric{} } -func (workqueueMetricsProvider) NewDeprecatedUnfinishedWorkSecondsMetric(queue string) workqueue.SettableGaugeMetric { +func (workqueueMetricsProvider) NewDeprecatedUnfinishedWorkSecondsMetric(_ string) workqueue.SettableGaugeMetric { return noopMetric{} } -func (workqueueMetricsProvider) NewDeprecatedRetriesMetric(queue string) workqueue.CounterMetric { +func (workqueueMetricsProvider) NewDeprecatedRetriesMetric(_ string) workqueue.CounterMetric { return noopMetric{} } diff --git a/pkg/daemon/config.go b/pkg/daemon/config.go index ca694dd6f1a..6396caa6dd0 100644 --- a/pkg/daemon/config.go +++ b/pkg/daemon/config.go @@ -274,7 +274,7 @@ func (config *Configuration) initNicConfig(nicBridgeMappings map[string]string) } } - config.MSS = config.MTU - util.TcpIpHeaderLength + config.MSS = config.MTU - util.TCPIPHeaderLength if !config.EncapChecksum { if err := disableChecksum(); err != nil { klog.Errorf("failed to set checksum offload, %v", err) @@ -290,7 +290,7 @@ func (config *Configuration) initNicConfig(nicBridgeMappings map[string]string) } func (config *Configuration) getEncapIP(node *corev1.Node) string { - if podIP := os.Getenv(util.POD_IP); podIP != "" { + if podIP := os.Getenv(util.PodIP); podIP != "" { return podIP } @@ -345,7 +345,7 @@ func (config *Configuration) initKubeClient() error { } // try to connect to apiserver's tcp port - if err = util.DialApiServer(cfg.Host); err != nil { + if err = util.DialAPIServer(cfg.Host); err != nil { klog.Errorf("failed to dial apiserver: %v", err) return err } diff --git a/pkg/daemon/config_linux.go b/pkg/daemon/config_linux.go index fa4976df59a..eeadc6cdb19 100644 --- a/pkg/daemon/config_linux.go +++ b/pkg/daemon/config_linux.go @@ -50,7 +50,7 @@ func getIfaceByIP(ip string) (string, int, error) { return "", 0, fmt.Errorf("failed to find interface by address %s", ip) } -func (config *Configuration) initRuntimeConfig(node *corev1.Node) error { +func (config *Configuration) initRuntimeConfig(_ *corev1.Node) error { // nothing to do on Linux return nil } diff --git a/pkg/daemon/controller.go b/pkg/daemon/controller.go index 97f4d714fd9..5fbcbfbde15 100644 --- a/pkg/daemon/controller.go +++ b/pkg/daemon/controller.go @@ -66,7 +66,7 @@ type Controller struct { } // NewController init a daemon controller -func NewController(config *Configuration, stopCh <-chan struct{}, podInformerFactory informers.SharedInformerFactory, nodeInformerFactory informers.SharedInformerFactory, kubeovnInformerFactory kubeovninformer.SharedInformerFactory) (*Controller, error) { +func NewController(config *Configuration, stopCh <-chan struct{}, podInformerFactory, nodeInformerFactory informers.SharedInformerFactory, kubeovnInformerFactory kubeovninformer.SharedInformerFactory) (*Controller, error) { eventBroadcaster := record.NewBroadcaster() eventBroadcaster.StartLogging(klog.Infof) eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{Interface: config.KubeClient.CoreV1().Events("")}) @@ -108,7 +108,7 @@ func NewController(config *Configuration, stopCh <-chan struct{}, podInformerFac if err != nil { util.LogFatalAndExit(err, "failed to get node %s info", config.NodeName) } - controller.protocol = util.CheckProtocol(node.Annotations[util.IpAddressAnnotation]) + controller.protocol = util.CheckProtocol(node.Annotations[util.IPAddressAnnotation]) if err = controller.initRuntime(); err != nil { return nil, err @@ -158,8 +158,8 @@ func (c *Controller) enqueueAddProviderNetwork(obj interface{}) { c.addOrUpdateProviderNetworkQueue.Add(key) } -func (c *Controller) enqueueUpdateProviderNetwork(old, new interface{}) { - key, err := cache.MetaNamespaceKeyFunc(new) +func (c *Controller) enqueueUpdateProviderNetwork(_, newObj interface{}) { + key, err := cache.MetaNamespaceKeyFunc(newObj) if err != nil { utilruntime.HandleError(err) return @@ -205,7 +205,6 @@ func (c *Controller) processNextAddOrUpdateProviderNetworkWorkItem() bool { c.addOrUpdateProviderNetworkQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) c.addOrUpdateProviderNetworkQueue.AddRateLimited(obj) @@ -235,7 +234,6 @@ func (c *Controller) processNextDeleteProviderNetworkWorkItem() bool { c.deleteProviderNetworkQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) c.deleteProviderNetworkQueue.AddRateLimited(obj) @@ -317,7 +315,7 @@ func (c *Controller) initProviderNetwork(pn *kubeovnv1.ProviderNetwork, node *v1 return nil } -func (c *Controller) recordProviderNetworkErr(providerNetwork string, errMsg string) { +func (c *Controller) recordProviderNetworkErr(providerNetwork, errMsg string) { var currentPod *v1.Pod var err error if c.localPodName == "" { @@ -391,11 +389,7 @@ func (c *Controller) cleanProviderNetwork(pn *kubeovnv1.ProviderNetwork, node *v return err } - if err = c.ovsCleanProviderNetwork(pn.Name); err != nil { - return err - } - - return nil + return c.ovsCleanProviderNetwork(pn.Name) } func (c *Controller) handleDeleteProviderNetwork(pn *kubeovnv1.ProviderNetwork) error { @@ -429,19 +423,19 @@ func (c *Controller) handleDeleteProviderNetwork(pn *kubeovnv1.ProviderNetwork) } type subnetEvent struct { - old, new interface{} + oldObj, newObj interface{} } func (c *Controller) enqueueAddSubnet(obj interface{}) { - c.subnetQueue.Add(subnetEvent{new: obj}) + c.subnetQueue.Add(subnetEvent{newObj: obj}) } -func (c *Controller) enqueueUpdateSubnet(old, new interface{}) { - c.subnetQueue.Add(subnetEvent{old: old, new: new}) +func (c *Controller) enqueueUpdateSubnet(oldObj, newObj interface{}) { + c.subnetQueue.Add(subnetEvent{oldObj: oldObj, newObj: newObj}) } func (c *Controller) enqueueDeleteSubnet(obj interface{}) { - c.subnetQueue.Add(subnetEvent{old: obj}) + c.subnetQueue.Add(subnetEvent{oldObj: obj}) } func (c *Controller) runSubnetWorker() { @@ -470,7 +464,6 @@ func (c *Controller) processNextSubnetWorkItem() bool { c.subnetQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -478,9 +471,9 @@ func (c *Controller) processNextSubnetWorkItem() bool { return true } -func (c *Controller) enqueuePod(old, new interface{}) { - oldPod := old.(*v1.Pod) - newPod := new.(*v1.Pod) +func (c *Controller) enqueuePod(oldObj, newObj interface{}) { + oldPod := oldObj.(*v1.Pod) + newPod := newObj.(*v1.Pod) if oldPod.Annotations[util.IngressRateAnnotation] != newPod.Annotations[util.IngressRateAnnotation] || oldPod.Annotations[util.EgressRateAnnotation] != newPod.Annotations[util.EgressRateAnnotation] || @@ -491,7 +484,7 @@ func (c *Controller) enqueuePod(old, new interface{}) { oldPod.Annotations[util.MirrorControlAnnotation] != newPod.Annotations[util.MirrorControlAnnotation] { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } @@ -514,7 +507,7 @@ func (c *Controller) enqueuePod(old, new interface{}) { oldPod.Annotations[fmt.Sprintf(util.MirrorControlAnnotationTemplate, provider)] != newPod.Annotations[fmt.Sprintf(util.MirrorControlAnnotationTemplate, provider)] { var key string var err error - if key, err = cache.MetaNamespaceKeyFunc(new); err != nil { + if key, err = cache.MetaNamespaceKeyFunc(newObj); err != nil { utilruntime.HandleError(err) return } @@ -552,7 +545,6 @@ func (c *Controller) processNextPodWorkItem() bool { c.podQueue.Forget(obj) return nil }(obj) - if err != nil { utilruntime.HandleError(err) return true @@ -612,7 +604,7 @@ func (c *Controller) Run(stopCh <-chan struct{}) { go wait.Until(c.runSubnetWorker, time.Second, stopCh) go wait.Until(c.runPodWorker, time.Second, stopCh) go wait.Until(c.runGateway, 3*time.Second, stopCh) - go wait.Until(c.loopEncapIpCheck, 3*time.Second, stopCh) + go wait.Until(c.loopEncapIPCheck, 3*time.Second, stopCh) go wait.Until(c.ovnMetricsUpdate, 3*time.Second, stopCh) go wait.Until(func() { if err := c.reconcileRouters(nil); err != nil { diff --git a/pkg/daemon/controller_linux.go b/pkg/daemon/controller_linux.go index 2a6d186ac03..6d624f2e8ba 100644 --- a/pkg/daemon/controller_linux.go +++ b/pkg/daemon/controller_linux.go @@ -131,15 +131,15 @@ func (c *Controller) reconcileRouters(event *subnetEvent) error { if event != nil { var ok bool var oldSubnet, newSubnet *kubeovnv1.Subnet - if event.old != nil { - if oldSubnet, ok = event.old.(*kubeovnv1.Subnet); !ok { - klog.Errorf("expected old subnet in subnetEvent but got %#v", event.old) + if event.oldObj != nil { + if oldSubnet, ok = event.oldObj.(*kubeovnv1.Subnet); !ok { + klog.Errorf("expected old subnet in subnetEvent but got %#v", event.oldObj) return nil } } - if event.new != nil { - if newSubnet, ok = event.new.(*kubeovnv1.Subnet); !ok { - klog.Errorf("expected new subnet in subnetEvent but got %#v", event.new) + if event.newObj != nil { + if newSubnet, ok = event.newObj.(*kubeovnv1.Subnet); !ok { + klog.Errorf("expected new subnet in subnetEvent but got %#v", event.newObj) return nil } } @@ -524,8 +524,8 @@ func (c *Controller) handlePod(key string) error { } podName := pod.Name - if pod.Annotations[fmt.Sprintf(util.VmTemplate, util.OvnProvider)] != "" { - podName = pod.Annotations[fmt.Sprintf(util.VmTemplate, util.OvnProvider)] + if pod.Annotations[fmt.Sprintf(util.VMTemplate, util.OvnProvider)] != "" { + podName = pod.Annotations[fmt.Sprintf(util.VMTemplate, util.OvnProvider)] } // set default nic bandwidth @@ -551,8 +551,8 @@ func (c *Controller) handlePod(key string) error { } for _, multiNet := range attachNets { provider := fmt.Sprintf("%s.%s.ovn", multiNet.Name, multiNet.Namespace) - if pod.Annotations[fmt.Sprintf(util.VmTemplate, provider)] != "" { - podName = pod.Annotations[fmt.Sprintf(util.VmTemplate, provider)] + if pod.Annotations[fmt.Sprintf(util.VMTemplate, provider)] != "" { + podName = pod.Annotations[fmt.Sprintf(util.VMTemplate, provider)] } if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, provider)] == "true" { ifaceID = ovs.PodNameToPortName(podName, pod.Namespace, provider) @@ -574,7 +574,7 @@ func (c *Controller) handlePod(key string) error { return nil } -func (c *Controller) loopEncapIpCheck() { +func (c *Controller) loopEncapIPCheck() { node, err := c.nodesLister.Get(c.config.NodeName) if err != nil { klog.Errorf("failed to get node %s %v", c.config.NodeName, err) @@ -733,7 +733,7 @@ func readKos(dir string) (*[]string, error) { return kos, nil } -func isFile(filename string, dir string) (bool, string) { +func isFile(filename, dir string) (bool, string) { isFile := false fileFullName := "" err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { diff --git a/pkg/daemon/controller_windows.go b/pkg/daemon/controller_windows.go index 65921999a64..87c45ab44ce 100644 --- a/pkg/daemon/controller_windows.go +++ b/pkg/daemon/controller_windows.go @@ -158,8 +158,8 @@ func (c *Controller) handlePod(key string) error { } podName := pod.Name - if pod.Annotations[fmt.Sprintf(util.VmTemplate, util.OvnProvider)] != "" { - podName = pod.Annotations[fmt.Sprintf(util.VmTemplate, util.OvnProvider)] + if pod.Annotations[fmt.Sprintf(util.VMTemplate, util.OvnProvider)] != "" { + podName = pod.Annotations[fmt.Sprintf(util.VMTemplate, util.OvnProvider)] } // set default nic bandwidth @@ -180,8 +180,8 @@ func (c *Controller) handlePod(key string) error { } for _, multiNet := range attachNets { provider := fmt.Sprintf("%s.%s.ovn", multiNet.Name, multiNet.Namespace) - if pod.Annotations[fmt.Sprintf(util.VmTemplate, provider)] != "" { - podName = pod.Annotations[fmt.Sprintf(util.VmTemplate, provider)] + if pod.Annotations[fmt.Sprintf(util.VMTemplate, provider)] != "" { + podName = pod.Annotations[fmt.Sprintf(util.VMTemplate, provider)] } if pod.Annotations[fmt.Sprintf(util.AllocatedAnnotationTemplate, provider)] == "true" { ifaceID = ovs.PodNameToPortName(podName, pod.Namespace, provider) @@ -202,7 +202,7 @@ func (c *Controller) handlePod(key string) error { return nil } -func (c *Controller) loopEncapIpCheck() { +func (c *Controller) loopEncapIPCheck() { // TODO } diff --git a/pkg/daemon/gateway.go b/pkg/daemon/gateway.go index 5f82c23a62d..94cf73f10f1 100644 --- a/pkg/daemon/gateway.go +++ b/pkg/daemon/gateway.go @@ -46,13 +46,13 @@ func (c *Controller) setGatewayBandwidth() error { return err } ingress, egress := node.Annotations[util.IngressRateAnnotation], node.Annotations[util.EgressRateAnnotation] - ifaceId := fmt.Sprintf("node-%s", c.config.NodeName) + ifaceID := fmt.Sprintf("node-%s", c.config.NodeName) if ingress == "" && egress == "" { - if htbQos, _ := ovs.IsHtbQos(ifaceId); !htbQos { + if htbQos, _ := ovs.IsHtbQos(ifaceID); !htbQos { return nil } } - return ovs.SetInterfaceBandwidth("", "", ifaceId, egress, ingress) + return ovs.SetInterfaceBandwidth("", "", ifaceID, egress, ingress) } func (c *Controller) setICGateway() error { @@ -218,12 +218,12 @@ func getCidrByProtocol(cidr, protocol string) string { return cidrStr } -func (c *Controller) getEgressNatIpByNode(nodeName string) (map[string]string, error) { - var subnetsNatIp = make(map[string]string) +func (c *Controller) getEgressNatIPByNode(nodeName string) (map[string]string, error) { + subnetsNatIP := make(map[string]string) subnetList, err := c.subnetsLister.List(labels.Everything()) if err != nil { klog.Errorf("failed to list subnets %v", err) - return subnetsNatIp, err + return subnetsNatIP, err } for _, subnet := range subnetList { @@ -240,20 +240,19 @@ func (c *Controller) getEgressNatIpByNode(nodeName string) (map[string]string, e for _, gw := range strings.Split(subnet.Spec.GatewayNode, ",") { if strings.Contains(gw, ":") && util.GatewayContains(gw, nodeName) && util.CheckProtocol(cidr) == util.CheckProtocol(strings.Split(gw, ":")[1]) { if subnet.Spec.EnableEcmp { - subnetsNatIp[cidr] = strings.TrimSpace(strings.Split(gw, ":")[1]) + subnetsNatIP[cidr] = strings.TrimSpace(strings.Split(gw, ":")[1]) } else if subnet.Status.ActivateGateway == nodeName { - subnetsNatIp[cidr] = strings.TrimSpace(strings.Split(gw, ":")[1]) + subnetsNatIP[cidr] = strings.TrimSpace(strings.Split(gw, ":")[1]) } break } } } } - return subnetsNatIp, nil + return subnetsNatIP, nil } func (c *Controller) getTProxyConditionPod(needSort bool) ([]*v1.Pod, error) { - var filteredPods []*v1.Pod pods, err := c.podsLister.List(labels.Everything()) if err != nil { diff --git a/pkg/daemon/gateway_linux.go b/pkg/daemon/gateway_linux.go index 652ced1fe80..e55492bf1fe 100644 --- a/pkg/daemon/gateway_linux.go +++ b/pkg/daemon/gateway_linux.go @@ -367,7 +367,7 @@ func (c *Controller) addPolicyRouting(family int, gateway string, priority, tabl return nil } -func (c *Controller) deletePolicyRouting(family int, gateway string, priority, tableID uint32, ips ...string) error { +func (c *Controller) deletePolicyRouting(family int, _ string, priority, tableID uint32, ips ...string) error { maskBits := 32 if family == netlink.FAMILY_V6 { maskBits = 128 @@ -506,7 +506,7 @@ func (c *Controller) setIptables() error { kubeovnv1.ProtocolIPv6: nodeIPv6, } - centralGwNatIPs, err := c.getEgressNatIpByNode(c.config.NodeName) + centralGwNatIPs, err := c.getEgressNatIPByNode(c.config.NodeName) if err != nil { klog.Errorf("failed to get centralized subnets nat ips on node %s, %v", c.config.NodeName, err) return err @@ -997,15 +997,17 @@ func (c *Controller) generateNatOutgoingPolicyChainRules(protocol string) ([]uti dstMatch := getNatOutGoingPolicyRuleIPSetName(rule.RuleID, "dst", protocol, true) var ovnNatoutGoingPolicyRule util.IPTableRule - if rule.Match.DstIPs != "" && rule.Match.SrcIPs != "" { + + switch { + case rule.Match.DstIPs != "" && rule.Match.SrcIPs != "": ovnNatoutGoingPolicyRule = util.IPTableRule{Table: NAT, Chain: ovnNatPolicySubnetChainName, Rule: strings.Fields(fmt.Sprintf(`-m set --match-set %s src -m set --match-set %s dst -j MARK --set-xmark %s`, srcMatch, dstMatch, markCode))} - } else if rule.Match.SrcIPs != "" { + case rule.Match.SrcIPs != "": protocol = getMatchProtocol(rule.Match.SrcIPs) ovnNatoutGoingPolicyRule = util.IPTableRule{Table: NAT, Chain: ovnNatPolicySubnetChainName, Rule: strings.Fields(fmt.Sprintf(`-m set --match-set %s src -j MARK --set-xmark %s`, srcMatch, markCode))} - } else if rule.Match.DstIPs != "" { + case rule.Match.DstIPs != "": protocol = getMatchProtocol(rule.Match.DstIPs) ovnNatoutGoingPolicyRule = util.IPTableRule{Table: NAT, Chain: ovnNatPolicySubnetChainName, Rule: strings.Fields(fmt.Sprintf(`-m set --match-set %s dst -j MARK --set-xmark %s`, dstMatch, markCode))} - } else { + default: continue } natPolicyRuleIptables = append(natPolicyRuleIptables, ovnNatoutGoingPolicyRule) @@ -1212,11 +1214,13 @@ func (c *Controller) setOvnSubnetGatewayMetric() { for _, item := range items { if strings.Contains(item, util.OvnSubnetGatewayIptables) { cidr = items[3] - if items[2] == "-s" { + + switch items[2] { + case "-s": direction = "egress" - } else if items[2] == "-d" { + case "-d": direction = "ingress" - } else { + default: break } @@ -1458,7 +1462,7 @@ func (c *Controller) getLocalPodIPsNeedPR(protocol string) (map[policyRouteMeta] pod.DeletionTimestamp != nil || pod.Spec.NodeName != nodeName || pod.Annotations[util.LogicalSwitchAnnotation] == "" || - pod.Annotations[util.IpAddressAnnotation] == "" { + pod.Annotations[util.IPAddressAnnotation] == "" { continue } @@ -1485,7 +1489,7 @@ func (c *Controller) getLocalPodIPsNeedPR(protocol string) (map[policyRouteMeta] ips = append(ips, pod.Status.PodIP) } } else { - ipv4, ipv6 := util.SplitStringIP(pod.Annotations[util.IpAddressAnnotation]) + ipv4, ipv6 := util.SplitStringIP(pod.Annotations[util.IPAddressAnnotation]) if ipv4 != "" && protocol == kubeovnv1.ProtocolIPv4 { ips = append(ips, ipv4) } @@ -1586,17 +1590,17 @@ func (c *Controller) appendMssRule() { } } -func (c *Controller) updateMssRuleByProtocol(protocol string, MssMangleRule util.IPTableRule) { - exists, err := c.iptables[protocol].Exists(MssMangleRule.Table, MssMangleRule.Chain, MssMangleRule.Rule...) +func (c *Controller) updateMssRuleByProtocol(protocol string, mssMangleRule util.IPTableRule) { + exists, err := c.iptables[protocol].Exists(mssMangleRule.Table, mssMangleRule.Chain, mssMangleRule.Rule...) if err != nil { - klog.Errorf("check iptables rule %v failed, %+v", MssMangleRule.Rule, err) + klog.Errorf("check iptables rule %v failed, %+v", mssMangleRule.Rule, err) return } if !exists { - klog.Infof("iptables rules %s not exist, append iptables rules", strings.Join(MssMangleRule.Rule, " ")) - if err := c.iptables[protocol].Append(MssMangleRule.Table, MssMangleRule.Chain, MssMangleRule.Rule...); err != nil { - klog.Errorf("append iptables rule %v failed, %+v", MssMangleRule.Rule, err) + klog.Infof("iptables rules %s not exist, append iptables rules", strings.Join(mssMangleRule.Rule, " ")) + if err := c.iptables[protocol].Append(mssMangleRule.Table, mssMangleRule.Chain, mssMangleRule.Rule...); err != nil { + klog.Errorf("append iptables rule %v failed, %+v", mssMangleRule.Rule, err) return } } diff --git a/pkg/daemon/handler.go b/pkg/daemon/handler.go index c8d493d9248..55d784fde81 100644 --- a/pkg/daemon/handler.go +++ b/pkg/daemon/handler.go @@ -117,7 +117,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon time.Sleep(1 * time.Second) continue } - ip = pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podRequest.Provider)] + ip = pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podRequest.Provider)] cidr = pod.Annotations[fmt.Sprintf(util.CidrAnnotationTemplate, podRequest.Provider)] gw = pod.Annotations[fmt.Sprintf(util.GatewayAnnotationTemplate, podRequest.Provider)] subnet = pod.Annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, podRequest.Provider)] @@ -128,8 +128,8 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon loss = pod.Annotations[fmt.Sprintf(util.NetemQosLossAnnotationTemplate, podRequest.Provider)] jitter = pod.Annotations[fmt.Sprintf(util.NetemQosJitterAnnotationTemplate, podRequest.Provider)] providerNetwork = pod.Annotations[fmt.Sprintf(util.ProviderNetworkTemplate, podRequest.Provider)] - vmName = pod.Annotations[fmt.Sprintf(util.VmTemplate, podRequest.Provider)] - ipAddr = util.GetIpAddrWithMask(ip, cidr) + vmName = pod.Annotations[fmt.Sprintf(util.VMTemplate, podRequest.Provider)] + ipAddr = util.GetIPAddrWithMask(ip, cidr) if s := pod.Annotations[fmt.Sprintf(util.RoutesAnnotationTemplate, podRequest.Provider)]; s != "" { if err = json.Unmarshal([]byte(s), &routes); err != nil { errMsg := fmt.Errorf("invalid routes for pod %s/%s: %v", pod.Namespace, pod.Name, err) @@ -143,9 +143,11 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon if ifName = podRequest.IfName; ifName == "" { ifName = "eth0" } - if podRequest.DeviceID != "" { + + switch { + case podRequest.DeviceID != "": nicType = util.OffloadType - } else if podRequest.VhostUserSocketVolumeName != "" { + case podRequest.VhostUserSocketVolumeName != "": nicType = util.DpdkType if err = createShortSharedDir(pod, podRequest.VhostUserSocketVolumeName, csh.Config.KubeletDir); err != nil { klog.Error(err.Error()) @@ -154,7 +156,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon } return } - } else { + default: nicType = pod.Annotations[fmt.Sprintf(util.PodNicAnnotationTemplate, podRequest.Provider)] } @@ -281,11 +283,12 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon routes = append(podRequest.Routes, routes...) macAddr = pod.Annotations[fmt.Sprintf(util.MacAddressAnnotationTemplate, podRequest.Provider)] klog.Infof("create container interface %s mac %s, ip %s, cidr %s, gw %s, custom routes %v", ifName, macAddr, ipAddr, cidr, gw, routes) - if nicType == util.InternalType { + switch nicType { + case util.InternalType: podNicName, err = csh.configureNicWithInternalPort(podRequest.PodName, podRequest.PodNamespace, podRequest.Provider, podRequest.NetNs, podRequest.ContainerID, ifName, macAddr, mtu, ipAddr, gw, isDefaultRoute, detectIPConflict, routes, podRequest.DNS.Nameservers, podRequest.DNS.Search, ingress, egress, podRequest.DeviceID, nicType, latency, limit, loss, jitter, gatewayCheckMode, u2oInterconnectionIP) - } else if nicType == util.DpdkType { + case util.DpdkType: err = csh.configureDpdkNic(podRequest.PodName, podRequest.PodNamespace, podRequest.Provider, podRequest.NetNs, podRequest.ContainerID, ifName, macAddr, mtu, ipAddr, gw, ingress, egress, getShortSharedDir(pod.UID, podRequest.VhostUserSocketVolumeName), podRequest.VhostUserSocketName) - } else { + default: podNicName = ifName err = csh.configureNic(podRequest.PodName, podRequest.PodNamespace, podRequest.Provider, podRequest.NetNs, podRequest.ContainerID, podRequest.VfDriver, ifName, macAddr, mtu, ipAddr, gw, isDefaultRoute, detectIPConflict, routes, podRequest.DNS.Nameservers, podRequest.DNS.Search, ingress, egress, podRequest.DeviceID, nicType, latency, limit, loss, jitter, gatewayCheckMode, u2oInterconnectionIP) } @@ -316,7 +319,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon response := &request.CniResponse{ Protocol: util.CheckProtocol(cidr), - IpAddress: ip, + IPAddress: ip, MacAddress: macAddr, CIDR: cidr, PodNicName: podNicName, @@ -332,25 +335,23 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon func (csh cniServerHandler) UpdateIPCr(podRequest request.CniRequest, subnet, ip string) error { ipCrName := ovs.PodNameToPortName(podRequest.PodName, podRequest.PodNamespace, podRequest.Provider) for i := 0; i < 20; i++ { - oriIpCr, err := csh.KubeOvnClient.KubeovnV1().IPs().Get(context.Background(), ipCrName, metav1.GetOptions{}) + oriIPCr, err := csh.KubeOvnClient.KubeovnV1().IPs().Get(context.Background(), ipCrName, metav1.GetOptions{}) if err != nil { err = fmt.Errorf("failed to get ip crd for %s, %v", ip, err) // maybe create a backup pod with previous annotations klog.Error(err) - } else { - if oriIpCr.Spec.NodeName != csh.Config.NodeName { - ipCr := oriIpCr.DeepCopy() - ipCr.Spec.NodeName = csh.Config.NodeName - ipCr.Spec.AttachIPs = []string{} - ipCr.Labels[subnet] = "" - ipCr.Spec.AttachSubnets = []string{} - ipCr.Spec.AttachMacs = []string{} - if _, err := csh.KubeOvnClient.KubeovnV1().IPs().Update(context.Background(), ipCr, metav1.UpdateOptions{}); err != nil { - err = fmt.Errorf("failed to update ip crd for %s, %v", ip, err) - klog.Error(err) - } else { - return nil - } + } else if oriIPCr.Spec.NodeName != csh.Config.NodeName { + ipCr := oriIPCr.DeepCopy() + ipCr.Spec.NodeName = csh.Config.NodeName + ipCr.Spec.AttachIPs = []string{} + ipCr.Labels[subnet] = "" + ipCr.Spec.AttachSubnets = []string{} + ipCr.Spec.AttachMacs = []string{} + if _, err := csh.KubeOvnClient.KubeovnV1().IPs().Update(context.Background(), ipCr, metav1.UpdateOptions{}); err != nil { + err = fmt.Errorf("failed to update ip crd for %s, %v", ip, err) + klog.Error(err) + } else { + return nil } } if err != nil { @@ -402,7 +403,7 @@ func (csh cniServerHandler) handleDel(req *restful.Request, resp *restful.Respon if pod.Annotations != nil && (podRequest.Provider == util.OvnProvider || podRequest.CniType == util.CniTypeName) { subnet := pod.Annotations[fmt.Sprintf(util.LogicalSwitchAnnotationTemplate, podRequest.Provider)] if subnet != "" { - ip := pod.Annotations[fmt.Sprintf(util.IpAddressAnnotationTemplate, podRequest.Provider)] + ip := pod.Annotations[fmt.Sprintf(util.IPAddressAnnotationTemplate, podRequest.Provider)] if err = csh.Controller.removeEgressConfig(subnet, ip); err != nil { errMsg := fmt.Errorf("failed to remove egress configuration: %v", err) klog.Error(errMsg) @@ -414,9 +415,10 @@ func (csh cniServerHandler) handleDel(req *restful.Request, resp *restful.Respon } var nicType string - if podRequest.DeviceID != "" { + switch { + case podRequest.DeviceID != "": nicType = util.OffloadType - } else if podRequest.VhostUserSocketVolumeName != "" { + case podRequest.VhostUserSocketVolumeName != "": nicType = util.DpdkType if err = removeShortSharedDir(pod, podRequest.VhostUserSocketVolumeName); err != nil { klog.Error(err.Error()) @@ -425,11 +427,10 @@ func (csh cniServerHandler) handleDel(req *restful.Request, resp *restful.Respon } return } - - } else { + default: nicType = pod.Annotations[fmt.Sprintf(util.PodNicAnnotationTemplate, podRequest.Provider)] } - vmName := pod.Annotations[fmt.Sprintf(util.VmTemplate, podRequest.Provider)] + vmName := pod.Annotations[fmt.Sprintf(util.VMTemplate, podRequest.Provider)] if vmName != "" { podRequest.PodName = vmName } diff --git a/pkg/daemon/handler_linux.go b/pkg/daemon/handler_linux.go index 2a77a243602..9be5a988a00 100644 --- a/pkg/daemon/handler_linux.go +++ b/pkg/daemon/handler_linux.go @@ -8,21 +8,21 @@ import ( "strings" "syscall" + "github.com/moby/sys/mountinfo" "golang.org/x/sys/unix" v1 "k8s.io/api/core/v1" "k8s.io/klog/v2" "github.com/kubeovn/kube-ovn/pkg/request" "github.com/kubeovn/kube-ovn/pkg/util" - "github.com/moby/sys/mountinfo" ) -func (csh cniServerHandler) validatePodRequest(req *request.CniRequest) error { +func (csh cniServerHandler) validatePodRequest(_ *request.CniRequest) error { // nothing to do on linux return nil } -func createShortSharedDir(pod *v1.Pod, volumeName string, kubeletDir string) (err error) { +func createShortSharedDir(pod *v1.Pod, volumeName, kubeletDir string) (err error) { var volume *v1.Volume for index, v := range pod.Spec.Volumes { if v.Name == volumeName { @@ -42,7 +42,7 @@ func createShortSharedDir(pod *v1.Pod, volumeName string, kubeletDir string) (er mask := syscall.Umask(0) defer syscall.Umask(mask) if _, err = os.Stat(newSharedDir); os.IsNotExist(err) { - err = os.MkdirAll(newSharedDir, 0777) + err = os.MkdirAll(newSharedDir, 0o777) if err != nil { return fmt.Errorf("createSharedDir: Failed to create dir (%s): %v", newSharedDir, err) } diff --git a/pkg/daemon/handler_windows.go b/pkg/daemon/handler_windows.go index 72595d1a5ac..70a32d143e9 100644 --- a/pkg/daemon/handler_windows.go +++ b/pkg/daemon/handler_windows.go @@ -19,7 +19,7 @@ func (csh cniServerHandler) validatePodRequest(req *request.CniRequest) error { return nil } -func createShortSharedDir(pod *v1.Pod, volumeName string, kubeletDir string) error { +func createShortSharedDir(pod *v1.Pod, volumeName, kubeletDir string) error { // nothing to do on Windows return nil } diff --git a/pkg/daemon/init.go b/pkg/daemon/init.go index 32215901370..86fe5aaad71 100644 --- a/pkg/daemon/init.go +++ b/pkg/daemon/init.go @@ -59,7 +59,7 @@ func InitNodeGateway(config *Configuration) error { klog.Errorf("failed to get node %s info %v", nodeName, err) return err } - if node.Annotations[util.IpAddressAnnotation] == "" { + if node.Annotations[util.IPAddressAnnotation] == "" { klog.Warningf("no ovn0 address for node %s, please check kube-ovn-controller logs", nodeName) time.Sleep(3 * time.Second) continue @@ -68,21 +68,20 @@ func InitNodeGateway(config *Configuration) error { klog.Errorf("validate node %s address annotation failed, %v", nodeName, err) time.Sleep(3 * time.Second) continue - } else { - macAddr = node.Annotations[util.MacAddressAnnotation] - ip = node.Annotations[util.IpAddressAnnotation] - cidr = node.Annotations[util.CidrAnnotation] - portName = node.Annotations[util.PortNameAnnotation] - gw = node.Annotations[util.GatewayAnnotation] - break } + macAddr = node.Annotations[util.MacAddressAnnotation] + ip = node.Annotations[util.IPAddressAnnotation] + cidr = node.Annotations[util.CidrAnnotation] + portName = node.Annotations[util.PortNameAnnotation] + gw = node.Annotations[util.GatewayAnnotation] + break } mac, err := net.ParseMAC(macAddr) if err != nil { return fmt.Errorf("failed to parse mac %s %v", mac, err) } - ipAddr = util.GetIpAddrWithMask(ip, cidr) + ipAddr = util.GetIPAddrWithMask(ip, cidr) return configureNodeNic(portName, ipAddr, gw, mac, config.MTU) } @@ -196,9 +195,5 @@ func (c *Controller) ovsCleanProviderNetwork(provider string) error { if err := removeOvnMapping("ovn-chassis-mac-mappings", provider); err != nil { return err } - if err := removeOvnMapping("ovn-bridge-mappings", provider); err != nil { - return err - } - - return nil + return removeOvnMapping("ovn-bridge-mappings", provider) } diff --git a/pkg/daemon/netns_linux.go b/pkg/daemon/netns_linux.go index 493c234d919..43e7217aafb 100644 --- a/pkg/daemon/netns_linux.go +++ b/pkg/daemon/netns_linux.go @@ -5,8 +5,9 @@ import ( "os" "path" - "github.com/kubeovn/kube-ovn/pkg/util" "golang.org/x/sys/unix" + + "github.com/kubeovn/kube-ovn/pkg/util" ) // NsHandle is a handle to a network namespace. It can be cast directly diff --git a/pkg/daemon/ovs.go b/pkg/daemon/ovs.go index 4fe01c5175d..30eeade3e53 100644 --- a/pkg/daemon/ovs.go +++ b/pkg/daemon/ovs.go @@ -141,11 +141,7 @@ func addOvnMapping(name, key, value string, overwrite bool) error { } mappings[key] = value - if err = setOvnMappings(name, mappings); err != nil { - return err - } - - return nil + return setOvnMappings(name, mappings) } func removeOvnMapping(name, key string) error { @@ -159,11 +155,7 @@ func removeOvnMapping(name, key string) error { if len(mappings) == length { return nil } - if err = setOvnMappings(name, mappings); err != nil { - return err - } - - return nil + return setOvnMappings(name, mappings) } func (c *Controller) configExternalBridge(provider, bridge, nic string, exchangeLinkName, macLearningFallback bool) error { diff --git a/pkg/daemon/ovs_linux.go b/pkg/daemon/ovs_linux.go index 4a820d36eb7..7b771ec354b 100644 --- a/pkg/daemon/ovs_linux.go +++ b/pkg/daemon/ovs_linux.go @@ -34,11 +34,11 @@ import ( var pciAddrRegexp = regexp.MustCompile(`\b([0-9a-fA-F]{4}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}.\d{1}\S*)`) -func (csh cniServerHandler) configureDpdkNic(podName, podNamespace, provider, netns, containerID, ifName, mac string, mtu int, ip, gateway, ingress, egress, shortSharedDir, socketName string) error { +func (csh cniServerHandler) configureDpdkNic(podName, podNamespace, provider, netns, containerID, ifName, _ string, _ int, ip, _, ingress, egress, shortSharedDir, socketName string) error { sharedDir := filepath.Join("/var", shortSharedDir) hostNicName, _ := generateNicName(containerID, ifName) - ipStr := util.GetIpWithoutMask(ip) + ipStr := util.GetIPWithoutMask(ip) ifaceID := ovs.PodNameToPortName(podName, podNamespace, provider) ovs.CleanDuplicatePort(ifaceID, hostNicName) // Add veth pair host end to ovs port @@ -54,30 +54,27 @@ func (csh cniServerHandler) configureDpdkNic(podName, podNamespace, provider, ne if err != nil { return fmt.Errorf("add nic to ovs failed %v: %q", err, output) } - if err = ovs.SetInterfaceBandwidth(podName, podNamespace, ifaceID, egress, ingress); err != nil { - return err - } - return nil + return ovs.SetInterfaceBandwidth(podName, podNamespace, ifaceID, egress, ingress) } -func (csh cniServerHandler) configureNic(podName, podNamespace, provider, netns, containerID, vfDriver, ifName, mac string, mtu int, ip, gateway string, isDefaultRoute, detectIPConflict bool, routes []request.Route, dnsServer, dnsSuffix []string, ingress, egress, DeviceID, nicType, latency, limit, loss, jitter string, gwCheckMode int, u2oInterconnectionIP string) error { +func (csh cniServerHandler) configureNic(podName, podNamespace, provider, netns, containerID, vfDriver, ifName, mac string, mtu int, ip, gateway string, isDefaultRoute, detectIPConflict bool, routes []request.Route, _, _ []string, ingress, egress, deviceID, nicType, latency, limit, loss, jitter string, gwCheckMode int, u2oInterconnectionIP string) error { var err error var hostNicName, containerNicName string - if DeviceID == "" { + if deviceID == "" { hostNicName, containerNicName, err = setupVethPair(containerID, ifName, mtu) if err != nil { klog.Errorf("failed to create veth pair %v", err) return err } } else { - hostNicName, containerNicName, err = setupSriovInterface(containerID, DeviceID, vfDriver, ifName, mtu, mac) + hostNicName, containerNicName, err = setupSriovInterface(containerID, deviceID, vfDriver, ifName, mtu, mac) if err != nil { klog.Errorf("failed to create sriov interfaces %v", err) return err } } - ipStr := util.GetIpWithoutMask(ip) + ipStr := util.GetIPWithoutMask(ip) ifaceID := ovs.PodNameToPortName(podName, podNamespace, provider) ovs.CleanDuplicatePort(ifaceID, hostNicName) // Add veth pair host end to ovs port @@ -126,13 +123,10 @@ func (csh cniServerHandler) configureNic(podName, podNamespace, provider, netns, if err != nil { return fmt.Errorf("failed to open netns %q: %v", netns, err) } - if err = configureContainerNic(containerNicName, ifName, ip, gateway, isDefaultRoute, detectIPConflict, routes, macAddr, podNS, mtu, nicType, gwCheckMode, u2oInterconnectionIP); err != nil { - return err - } - return nil + return configureContainerNic(containerNicName, ifName, ip, gateway, isDefaultRoute, detectIPConflict, routes, macAddr, podNS, mtu, nicType, gwCheckMode, u2oInterconnectionIP) } -func (csh cniServerHandler) deleteNic(podName, podNamespace, containerID, netns, deviceID, ifName, nicType string) error { +func (csh cniServerHandler) deleteNic(podName, podNamespace, containerID, _, deviceID, ifName, nicType string) error { var nicName string hostNicName, containerNicName := generateNicName(containerID, ifName) @@ -217,7 +211,7 @@ func configureHostNic(nicName string) error { return nil } -func configureContainerNic(nicName, ifName string, ipAddr, gateway string, isDefaultRoute, detectIPConflict bool, routes []request.Route, macAddr net.HardwareAddr, netns ns.NetNS, mtu int, nicType string, gwCheckMode int, u2oInterconnectionIP string) error { +func configureContainerNic(nicName, ifName, ipAddr, gateway string, isDefaultRoute, detectIPConflict bool, routes []request.Route, macAddr net.HardwareAddr, netns ns.NetNS, mtu int, nicType string, gwCheckMode int, u2oInterconnectionIP string) error { containerLink, err := netlink.LinkByName(nicName) if err != nil { return fmt.Errorf("can not find container nic %s: %v", nicName, err) @@ -381,7 +375,7 @@ func waitNetworkReady(nic, ipAddr, gateway string, underlayGateway, verbose bool } func configureNodeNic(portName, ip, gw string, macAddr net.HardwareAddr, mtu int) error { - ipStr := util.GetIpWithoutMask(ip) + ipStr := util.GetIPWithoutMask(ip) raw, err := ovs.Exec(ovs.MayExist, "add-port", "br-int", util.NodeNic, "--", "set", "interface", util.NodeNic, "type=internal", "--", "set", "interface", util.NodeNic, fmt.Sprintf("external_ids:iface-id=%s", portName), @@ -430,14 +424,14 @@ func (c *Controller) loopOvn0Check() { klog.Errorf("failed to get node %s: %v", c.config.NodeName, err) return } - ip := node.Annotations[util.IpAddressAnnotation] + ip := node.Annotations[util.IPAddressAnnotation] gw := node.Annotations[util.GatewayAnnotation] if err := waitNetworkReady(util.NodeNic, ip, gw, false, false, 5); err != nil { util.LogFatalAndExit(err, "failed to ping ovn0 gateway %s", gw) } } -func (c *Controller) checkNodeGwNicInNs(nodeExtIp, ip, gw string, gwNS ns.NetNS) error { +func (c *Controller) checkNodeGwNicInNs(nodeExtIP, ip, gw string, gwNS ns.NetNS) error { exists, err := ovs.PortExists(util.NodeGwNic) if err != nil { klog.Error(err) @@ -466,11 +460,11 @@ func (c *Controller) checkNodeGwNicInNs(nodeExtIp, ip, gw string, gwNS ns.NetNS) } for _, eip := range ovnEips { if eip.Status.Ready { - cmd := exec.Command("sh", "-c", fmt.Sprintf("bfdd-control status remote %s local %s", eip.Spec.V4Ip, nodeExtIp)) + cmd := exec.Command("sh", "-c", fmt.Sprintf("bfdd-control status remote %s local %s", eip.Spec.V4Ip, nodeExtIP)) var outb bytes.Buffer cmd.Stdout = &outb if err := cmd.Run(); err == nil { - out := string(outb.String()) + out := outb.String() klog.V(3).Info(out) if strings.Contains(out, "No session") { // not exist @@ -482,7 +476,7 @@ func (c *Controller) checkNodeGwNicInNs(nodeExtIp, ip, gw string, gwNS ns.NetNS) } } } else { - err := fmt.Errorf("faild to check bfd status remote %s local %s", eip.Spec.V4Ip, nodeExtIp) + err := fmt.Errorf("faild to check bfd status remote %s local %s", eip.Spec.V4Ip, nodeExtIP) klog.Error(err) return err } @@ -492,15 +486,15 @@ func (c *Controller) checkNodeGwNicInNs(nodeExtIp, ip, gw string, gwNS ns.NetNS) } return err }) - } else { - err := fmt.Errorf("node external gw not ready") - klog.Error(err) - return err } + + err = fmt.Errorf("node external gw not ready") + klog.Error(err) + return err } func configureNodeGwNic(portName, ip, gw string, macAddr net.HardwareAddr, mtu int, gwNS ns.NetNS) error { - ipStr := util.GetIpWithoutMask(ip) + ipStr := util.GetIPWithoutMask(ip) output, err := ovs.Exec(ovs.MayExist, "add-port", "br-int", util.NodeGwNic, "--", "set", "interface", util.NodeGwNic, "type=internal", "--", "set", "interface", util.NodeGwNic, fmt.Sprintf("external_ids:iface-id=%s", portName), @@ -686,9 +680,9 @@ func (c *Controller) loopOvnExt0Check() { return } } - nodeExtIp := cachedEip.Spec.V4Ip - ipAddr := util.GetIpAddrWithMask(ips, cachedSubnet.Spec.CIDRBlock) - if err := c.checkNodeGwNicInNs(nodeExtIp, ipAddr, gw, gwNS); err == nil { + nodeExtIP := cachedEip.Spec.V4Ip + ipAddr := util.GetIPAddrWithMask(ips, cachedSubnet.Spec.CIDRBlock) + if err := c.checkNodeGwNicInNs(nodeExtIP, ipAddr, gw, gwNS); err == nil { // add all lrp ip in bfd listening list return } @@ -762,7 +756,7 @@ func (c *Controller) patchNodeExternalGwLabel(key string, enabled bool) error { return nil } -func configureMirrorLink(portName string, mtu int) error { +func configureMirrorLink(portName string, _ int) error { mirrorLink, err := netlink.LinkByName(portName) if err != nil { return fmt.Errorf("can not find mirror nic %s: %v", portName, err) @@ -1215,7 +1209,7 @@ func setupVethPair(containerID, ifName string, mtu int) (string, string, error) // Setup sriov interface in the pod // https://github.com/ovn-org/ovn-kubernetes/commit/6c96467d0d3e58cab05641293d1c1b75e5914795 func setupSriovInterface(containerID, deviceID, vfDriver, ifName string, mtu int, mac string) (string, string, error) { - var isVfioPciDriver = false + isVfioPciDriver := false if vfDriver == "vfio-pci" { matches, err := filepath.Glob(filepath.Join(util.VfioSysDir, "*")) if err != nil { @@ -1312,16 +1306,12 @@ func renameLink(curName, newName string) error { if err := netlink.LinkSetName(link, newName); err != nil { return err } - if err := netlink.LinkSetUp(link); err != nil { - return err - } - - return nil + return netlink.LinkSetUp(link) } -func (csh cniServerHandler) configureNicWithInternalPort(podName, podNamespace, provider, netns, containerID, ifName, mac string, mtu int, ip, gateway string, isDefaultRoute, detectIPConflict bool, routes []request.Route, dnsServer, dnsSuffix []string, ingress, egress, DeviceID, nicType, latency, limit, loss, jitter string, gwCheckMode int, u2oInterconnectionIP string) (string, error) { +func (csh cniServerHandler) configureNicWithInternalPort(podName, podNamespace, provider, netns, containerID, ifName, mac string, mtu int, ip, gateway string, isDefaultRoute, detectIPConflict bool, routes []request.Route, _, _ []string, ingress, egress, _, nicType, latency, limit, loss, jitter string, gwCheckMode int, u2oInterconnectionIP string) (string, error) { _, containerNicName := generateNicName(containerID, ifName) - ipStr := util.GetIpWithoutMask(ip) + ipStr := util.GetIPWithoutMask(ip) ifaceID := ovs.PodNameToPortName(podName, podNamespace, provider) ovs.CleanDuplicatePort(ifaceID, containerNicName) diff --git a/pkg/daemon/ovs_windows.go b/pkg/daemon/ovs_windows.go index b4e2f24607c..d740159ccde 100644 --- a/pkg/daemon/ovs_windows.go +++ b/pkg/daemon/ovs_windows.go @@ -47,7 +47,7 @@ func (csh cniServerHandler) configureNic(podName, podNamespace, provider, netns, return err } - ipAddr := util.GetIpWithoutMask(ip) + ipAddr := util.GetIPWithoutMask(ip) sandbox := hns.GetSandboxContainerID(containerID, netns) epName := sandbox[:12] _, err = hns.AddHnsEndpoint(epName, hnsNetwork.Id, containerID, netns, func() (*hcsshim.HNSEndpoint, error) { @@ -253,7 +253,7 @@ func waitNetworkReady(nic, ipAddr, gateway string, underlayGateway, verbose bool } func configureNodeNic(portName, ip, gw string, macAddr net.HardwareAddr, mtu int) error { - ipStr := util.GetIpWithoutMask(ip) + ipStr := util.GetIPWithoutMask(ip) raw, err := ovs.Exec(ovs.MayExist, "add-port", "br-int", util.NodeNic, "--", "set", "interface", util.NodeNic, "type=internal", "--", "set", "interface", util.NodeNic, fmt.Sprintf("external_ids:iface-id=%s", portName), diff --git a/pkg/daemon/server.go b/pkg/daemon/server.go index f3d5d79d7b6..0976939a8f0 100644 --- a/pkg/daemon/server.go +++ b/pkg/daemon/server.go @@ -60,7 +60,8 @@ func createHandler(csh *cniServerHandler) http.Handler { // web-service filter function used for request and response logging. func requestAndResponseLogger(request *restful.Request, response *restful.Response, - chain *restful.FilterChain) { + chain *restful.FilterChain, +) { klog.Infof(formatRequestLog(request)) start := time.Now() chain.ProcessFilter(request, response) diff --git a/pkg/daemon/tproxy_linux.go b/pkg/daemon/tproxy_linux.go index d392bf1391b..ef9736b1f67 100644 --- a/pkg/daemon/tproxy_linux.go +++ b/pkg/daemon/tproxy_linux.go @@ -11,6 +11,7 @@ import ( "syscall" "github.com/containernetworking/plugins/pkg/ns" + "github.com/scylladb/go-set/strset" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" "k8s.io/klog/v2" @@ -19,7 +20,6 @@ import ( "github.com/kubeovn/kube-ovn/pkg/ovs" goTProxy "github.com/kubeovn/kube-ovn/pkg/tproxy" "github.com/kubeovn/kube-ovn/pkg/util" - "github.com/scylladb/go-set/strset" ) var ( @@ -62,7 +62,6 @@ func (c *Controller) StartTProxyForwarding() { } func (c *Controller) StartTProxyTCPPortProbe() { - probePorts := strset.New() pods, err := c.getTProxyConditionPod(false) @@ -270,7 +269,6 @@ func delRouteIfExist(family, table int, dst *net.IPNet) error { } func handleRedirectFlow(conn net.Conn) { - klog.V(5).Infof("Accepting TCP connection from %v with destination of %v", conn.RemoteAddr().String(), conn.LocalAddr().String()) defer func() { if err := conn.Close(); err != nil { @@ -308,10 +306,10 @@ func probePortInNs(podIP, probePort string, isTProxyProbe bool, conn net.Conn) { _ = ns.WithNetNSPath(podNS.Path(), func(_ ns.NetNS) error { // Packet's src and dst IP are both PodIP in netns - localpodTcpAddr := net.TCPAddr{IP: net.ParseIP(podIP)} - remotepodTcpAddr := net.TCPAddr{IP: net.ParseIP(podIP), Port: iprobePort} + localpodTCPAddr := net.TCPAddr{IP: net.ParseIP(podIP)} + remotepodTCPAddr := net.TCPAddr{IP: net.ParseIP(podIP), Port: iprobePort} - remoteConn, err := goTProxy.DialTCP(&localpodTcpAddr, &remotepodTcpAddr, !isTProxyProbe) + remoteConn, err := goTProxy.DialTCP(&localpodTCPAddr, &remotepodTCPAddr, !isTProxyProbe) if err != nil { if isTProxyProbe { customVPCPodTCPProbeIPPort.Store(getIPPortString(podIP, probePort), false) diff --git a/pkg/ipam/ip_range_list.go b/pkg/ipam/ip_range_list.go index 2c6362688ea..17f8195f1c3 100644 --- a/pkg/ipam/ip_range_list.go +++ b/pkg/ipam/ip_range_list.go @@ -33,7 +33,9 @@ func NewIPRangeListFrom(x ...string) (*IPRangeList, error) { ret := &IPRangeList{} for _, s := range x { var r *IPRange - if strings.Contains(s, "..") { + + switch { + case strings.Contains(s, ".."): ips := strings.Split(s, "..") start, err := NewIP(ips[0]) if err != nil { @@ -47,13 +49,13 @@ func NewIPRangeListFrom(x ...string) (*IPRangeList, error) { return nil, fmt.Errorf("invalid ip range %q: %s is greater than %s", s, start, end) } r = NewIPRange(start, end) - } else if strings.ContainsRune(s, '/') { + case strings.ContainsRune(s, '/'): _, cidr, err := net.ParseCIDR(s) if err != nil { return nil, err } r = NewIPRangeFromCIDR(*cidr) - } else { + default: start, err := NewIP(s) if err != nil { return nil, err diff --git a/pkg/ipam/ipam.go b/pkg/ipam/ipam.go index 5e0f17cbc57..1658c638ca1 100644 --- a/pkg/ipam/ipam.go +++ b/pkg/ipam/ipam.go @@ -29,7 +29,7 @@ type IPAM struct { type SubnetAddress struct { Subnet *Subnet - Ip string + IP string Mac string } @@ -61,44 +61,46 @@ func (ipam *IPAM) GetRandomAddress(podName, nicName string, mac *string, subnetN func (ipam *IPAM) GetStaticAddress(podName, nicName, ip string, mac *string, subnetName string, checkConflict bool) (string, string, string, error) { ipam.mutex.RLock() defer ipam.mutex.RUnlock() + var subnet *Subnet + var ok bool klog.Infof("allocating static ip %s from subnet %s", ip, subnetName) - if subnet, ok := ipam.Subnets[subnetName]; !ok { + if subnet, ok = ipam.Subnets[subnetName]; !ok { return "", "", "", ErrNoAvailable - } else { - var ips []IP - var err error - var ipAddr IP - var macStr string - for _, ipStr := range strings.Split(ip, ",") { - ip, err := NewIP(ipStr) - if err != nil { - klog.Errorf("failed to parse ip %s", ipStr) - return "", "", "", err - } - ipAddr, macStr, err = subnet.GetStaticAddress(podName, nicName, ip, mac, false, checkConflict) - if err != nil { - klog.Errorf("failed to allocate static ip %s for %s", ipStr, podName) - return "", "", "", err - } - ips = append(ips, ipAddr) + } + + var ips []IP + var err error + var ipAddr IP + var macStr string + for _, ipStr := range strings.Split(ip, ",") { + ip, err := NewIP(ipStr) + if err != nil { + klog.Errorf("failed to parse ip %s", ipStr) + return "", "", "", err } - ips, err = checkAndAppendIpsForDual(ips, macStr, podName, nicName, subnet, checkConflict) + ipAddr, macStr, err = subnet.GetStaticAddress(podName, nicName, ip, mac, false, checkConflict) if err != nil { - klog.Errorf("failed to append allocate ip %v mac %s for %s", ips, mac, podName) + klog.Errorf("failed to allocate static ip %s for %s", ipStr, podName) return "", "", "", err } + ips = append(ips, ipAddr) + } + ips, err = checkAndAppendIpsForDual(ips, macStr, podName, nicName, subnet, checkConflict) + if err != nil { + klog.Errorf("failed to append allocate ip %v mac %s for %s", ips, mac, podName) + return "", "", "", err + } - switch subnet.Protocol { - case kubeovnv1.ProtocolIPv4: - klog.Infof("allocate v4 %s mac %s for %s from subnet %s", ip, macStr, podName, subnetName) - return ip, "", macStr, err - case kubeovnv1.ProtocolIPv6: - klog.Infof("allocate v6 %s mac %s for %s from subnet %s", ip, macStr, podName, subnetName) - return "", ip, macStr, err - case kubeovnv1.ProtocolDual: - klog.Infof("allocate v4 %s v6 %s mac %s for %s from subnet %s", ips[0].String(), ips[1].String(), macStr, podName, subnetName) - return ips[0].String(), ips[1].String(), macStr, err - } + switch subnet.Protocol { + case kubeovnv1.ProtocolIPv4: + klog.Infof("allocate v4 %s mac %s for %s from subnet %s", ip, macStr, podName, subnetName) + return ip, "", macStr, err + case kubeovnv1.ProtocolIPv6: + klog.Infof("allocate v6 %s mac %s for %s from subnet %s", ip, macStr, podName, subnetName) + return "", ip, macStr, err + case kubeovnv1.ProtocolDual: + klog.Infof("allocate v4 %s v6 %s mac %s for %s from subnet %s", ips[0].String(), ips[1].String(), macStr, podName, subnetName) + return ips[0].String(), ips[1].String(), macStr, err } return "", "", "", ErrNoAvailable } @@ -142,11 +144,11 @@ func (ipam *IPAM) AddOrUpdateSubnet(name, cidrStr, gw string, excludeIps []strin var v4cidrStr, v6cidrStr, v4Gw, v6Gw string var cidrs []*net.IPNet for _, cidrBlock := range strings.Split(cidrStr, ",") { - if _, cidr, err := net.ParseCIDR(cidrBlock); err != nil { + _, cidr, err := net.ParseCIDR(cidrBlock) + if err != nil { return ErrInvalidCIDR - } else { - cidrs = append(cidrs, cidr) } + cidrs = append(cidrs, cidr) } protocol := util.CheckProtocol(cidrStr) switch protocol { @@ -304,12 +306,12 @@ func (ipam *IPAM) GetPodAddress(podName string) []*SubnetAddress { v4IP, v6IP, mac, protocol := subnet.GetPodAddress(podName, nicName) switch protocol { case kubeovnv1.ProtocolIPv4: - addresses = append(addresses, &SubnetAddress{Subnet: subnet, Ip: v4IP.String(), Mac: mac}) + addresses = append(addresses, &SubnetAddress{Subnet: subnet, IP: v4IP.String(), Mac: mac}) case kubeovnv1.ProtocolIPv6: - addresses = append(addresses, &SubnetAddress{Subnet: subnet, Ip: v6IP.String(), Mac: mac}) + addresses = append(addresses, &SubnetAddress{Subnet: subnet, IP: v6IP.String(), Mac: mac}) case kubeovnv1.ProtocolDual: - addresses = append(addresses, &SubnetAddress{Subnet: subnet, Ip: v4IP.String(), Mac: mac}) - addresses = append(addresses, &SubnetAddress{Subnet: subnet, Ip: v6IP.String(), Mac: mac}) + addresses = append(addresses, &SubnetAddress{Subnet: subnet, IP: v4IP.String(), Mac: mac}) + addresses = append(addresses, &SubnetAddress{Subnet: subnet, IP: v6IP.String(), Mac: mac}) } } subnet.mutex.RUnlock() @@ -338,20 +340,20 @@ func (ipam *IPAM) IsIPAssignedToOtherPod(ip, subnetName, podName string) (string ipam.mutex.RLock() defer ipam.mutex.RUnlock() - if subnet, ok := ipam.Subnets[subnetName]; !ok { + subnet, ok := ipam.Subnets[subnetName] + if !ok { return "", false - } else { - return subnet.isIPAssignedToOtherPod(ip, podName) } + return subnet.isIPAssignedToOtherPod(ip, podName) } func (ipam *IPAM) GetSubnetV4Mask(subnetName string) (string, error) { - if subnet, ok := ipam.Subnets[subnetName]; ok { + subnet, ok := ipam.Subnets[subnetName] + if ok { mask, _ := subnet.V4CIDR.Mask.Size() return strconv.Itoa(mask), nil - } else { - return "", ErrNoAvailable } + return "", ErrNoAvailable } func (ipam *IPAM) GetSubnetIPRangeString(subnetName string) (string, string, string, string) { diff --git a/pkg/ipam/subnet.go b/pkg/ipam/subnet.go index 6d379355490..c072f391d68 100644 --- a/pkg/ipam/subnet.go +++ b/pkg/ipam/subnet.go @@ -44,11 +44,11 @@ type Subnet struct { func NewSubnet(name, cidrStr string, excludeIps []string) (*Subnet, error) { var cidrs []*net.IPNet for _, cidrBlock := range strings.Split(cidrStr, ",") { - if _, cidr, err := net.ParseCIDR(cidrBlock); err != nil { + _, cidr, err := net.ParseCIDR(cidrBlock) + if err != nil { return nil, ErrInvalidCIDR - } else { - cidrs = append(cidrs, cidr) } + cidrs = append(cidrs, cidr) } // subnet.Spec.ExcludeIps contains both v4 and v6 addresses @@ -83,17 +83,18 @@ func NewSubnet(name, cidrStr string, excludeIps []string) (*Subnet, error) { PodToNicList: map[string][]string{}, IPPools: make(map[string]*IPPool, 0), } - if protocol == kubeovnv1.ProtocolIPv4 { + switch protocol { + case kubeovnv1.ProtocolIPv4: firstIP, _ := util.FirstIP(cidrStr) lastIP, _ := util.LastIP(cidrStr) subnet.V4CIDR = cidrs[0] subnet.V4Free, _ = NewIPRangeListFrom(fmt.Sprintf("%s..%s", firstIP, lastIP)) - } else if protocol == kubeovnv1.ProtocolIPv6 { + case kubeovnv1.ProtocolIPv6: firstIP, _ := util.FirstIP(cidrStr) lastIP, _ := util.LastIP(cidrStr) subnet.V6CIDR = cidrs[0] subnet.V6Free, _ = NewIPRangeListFrom(fmt.Sprintf("%s..%s", firstIP, lastIP)) - } else { + default: subnet.V4CIDR = cidrs[0] subnet.V6CIDR = cidrs[1] cidrBlocks := strings.Split(cidrStr, ",") @@ -128,93 +129,94 @@ func NewSubnet(name, cidrStr string, excludeIps []string) (*Subnet, error) { return subnet, nil } -func (subnet *Subnet) GetRandomMac(podName, nicName string) string { - if mac, ok := subnet.NicToMac[nicName]; ok { +func (s *Subnet) GetRandomMac(podName, nicName string) string { + if mac, ok := s.NicToMac[nicName]; ok { return mac } for { mac := util.GenerateMac() - if _, ok := subnet.MacToPod[mac]; !ok { - subnet.MacToPod[mac] = podName - subnet.NicToMac[nicName] = mac + if _, ok := s.MacToPod[mac]; !ok { + s.MacToPod[mac] = podName + s.NicToMac[nicName] = mac return mac } } } -func (subnet *Subnet) GetStaticMac(podName, nicName, mac string, checkConflict bool) error { +func (s *Subnet) GetStaticMac(podName, nicName, mac string, checkConflict bool) error { if mac == "" { return nil } if checkConflict { - if p, ok := subnet.MacToPod[mac]; ok && p != podName { + if p, ok := s.MacToPod[mac]; ok && p != podName { return ErrConflict } } - subnet.MacToPod[mac] = podName - subnet.NicToMac[nicName] = mac + s.MacToPod[mac] = podName + s.NicToMac[nicName] = mac return nil } -func (subnet *Subnet) pushPodNic(podName, nicName string) { - if subnet.V4NicToIP[nicName] != nil || subnet.V6NicToIP[nicName] != nil || subnet.NicToMac[nicName] != "" { - subnet.PodToNicList[podName] = util.UniqString(append(subnet.PodToNicList[podName], nicName)) +func (s *Subnet) pushPodNic(podName, nicName string) { + if s.V4NicToIP[nicName] != nil || s.V6NicToIP[nicName] != nil || s.NicToMac[nicName] != "" { + s.PodToNicList[podName] = util.UniqString(append(s.PodToNicList[podName], nicName)) } } -func (subnet *Subnet) popPodNic(podName, nicName string) { - subnet.PodToNicList[podName] = util.RemoveString(subnet.PodToNicList[podName], nicName) - if subnet.PodToNicList[podName] == nil { - delete(subnet.PodToNicList, podName) +func (s *Subnet) popPodNic(podName, nicName string) { + s.PodToNicList[podName] = util.RemoveString(s.PodToNicList[podName], nicName) + if s.PodToNicList[podName] == nil { + delete(s.PodToNicList, podName) } } -func (subnet *Subnet) GetRandomAddress(poolName, podName, nicName string, mac *string, skippedAddrs []string, checkConflict bool) (IP, IP, string, error) { - subnet.mutex.Lock() +func (s *Subnet) GetRandomAddress(poolName, podName, nicName string, mac *string, skippedAddrs []string, checkConflict bool) (IP, IP, string, error) { + s.mutex.Lock() defer func() { - subnet.pushPodNic(podName, nicName) - subnet.mutex.Unlock() + s.pushPodNic(podName, nicName) + s.mutex.Unlock() }() - if subnet.Protocol == kubeovnv1.ProtocolDual { - return subnet.getDualRandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) - } else if subnet.Protocol == kubeovnv1.ProtocolIPv4 { - return subnet.getV4RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) - } else { - return subnet.getV6RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) + switch s.Protocol { + case kubeovnv1.ProtocolDual: + return s.getDualRandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) + case kubeovnv1.ProtocolIPv4: + return s.getV4RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) + default: + return s.getV6RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) } } -func (subnet *Subnet) getDualRandomAddress(poolName, podName, nicName string, mac *string, skippedAddrs []string, checkConflict bool) (IP, IP, string, error) { - v4IP, _, _, err := subnet.getV4RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) +func (s *Subnet) getDualRandomAddress(poolName, podName, nicName string, mac *string, skippedAddrs []string, checkConflict bool) (IP, IP, string, error) { + v4IP, _, _, err := s.getV4RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) if err != nil { return nil, nil, "", err } - _, v6IP, macStr, err := subnet.getV6RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) + _, v6IP, macStr, err := s.getV6RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) if err != nil { return nil, nil, "", err } // allocated IPv4 address may be released in getV6RandomAddress() - if !subnet.V4NicToIP[nicName].Equal(v4IP) { - v4IP, _, _, _ = subnet.getV4RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) + if !s.V4NicToIP[nicName].Equal(v4IP) { + v4IP, _, _, _ = s.getV4RandomAddress(poolName, podName, nicName, mac, skippedAddrs, checkConflict) } return v4IP, v6IP, macStr, nil } -func (subnet *Subnet) getV4RandomAddress(ippoolName, podName, nicName string, mac *string, skippedAddrs []string, checkConflict bool) (IP, IP, string, error) { +func (s *Subnet) getV4RandomAddress(ippoolName, podName, nicName string, mac *string, skippedAddrs []string, checkConflict bool) (IP, IP, string, error) { // After 'macAdd' introduced to support only static mac address, pod restart will run into error mac AddressConflict // controller will re-enqueue the new pod then wait for old pod deleted and address released. // here will return only if both ip and mac exist, otherwise only ip without mac returned will trigger CreatePort error. - if subnet.V4NicToIP[nicName] != nil && subnet.NicToMac[nicName] != "" { - if !util.ContainsString(skippedAddrs, subnet.V4NicToIP[nicName].String()) { - return subnet.V4NicToIP[nicName], nil, subnet.NicToMac[nicName], nil + if s.V4NicToIP[nicName] != nil && s.NicToMac[nicName] != "" { + if !util.ContainsString(skippedAddrs, s.V4NicToIP[nicName].String()) { + return s.V4NicToIP[nicName], nil, s.NicToMac[nicName], nil } - subnet.releaseAddr(podName, nicName) + s.releaseAddr(podName, nicName) } - pool := subnet.IPPools[ippoolName] + pool := s.IPPools[ippoolName] if pool == nil { return nil, nil, "", ErrNoAvailable } @@ -240,35 +242,34 @@ func (subnet *Subnet) getV4RandomAddress(ippoolName, podName, nicName string, ma pool.V4Available.Remove(ip) pool.V4Using.Add(ip) - subnet.V4Free.Remove(ip) - subnet.V4Available.Remove(ip) - subnet.V4Using.Add(ip) + s.V4Free.Remove(ip) + s.V4Available.Remove(ip) + s.V4Using.Add(ip) - subnet.V4NicToIP[nicName] = ip - subnet.V4IPToPod[ip.String()] = podName - subnet.pushPodNic(podName, nicName) + s.V4NicToIP[nicName] = ip + s.V4IPToPod[ip.String()] = podName + s.pushPodNic(podName, nicName) if mac == nil { - return ip, nil, subnet.GetRandomMac(podName, nicName), nil - } else { - if err := subnet.GetStaticMac(podName, nicName, *mac, checkConflict); err != nil { - return nil, nil, "", err - } - return ip, nil, *mac, nil + return ip, nil, s.GetRandomMac(podName, nicName), nil + } + if err := s.GetStaticMac(podName, nicName, *mac, checkConflict); err != nil { + return nil, nil, "", err } + return ip, nil, *mac, nil } -func (subnet *Subnet) getV6RandomAddress(ippoolName, podName, nicName string, mac *string, skippedAddrs []string, checkConflict bool) (IP, IP, string, error) { +func (s *Subnet) getV6RandomAddress(ippoolName, podName, nicName string, mac *string, skippedAddrs []string, checkConflict bool) (IP, IP, string, error) { // After 'macAdd' introduced to support only static mac address, pod restart will run into error mac AddressConflict // controller will re-enqueue the new pod then wait for old pod deleted and address released. // here will return only if both ip and mac exist, otherwise only ip without mac returned will trigger CreatePort error. - if subnet.V6NicToIP[nicName] != nil && subnet.NicToMac[nicName] != "" { - if !util.ContainsString(skippedAddrs, subnet.V6NicToIP[nicName].String()) { - return nil, subnet.V6NicToIP[nicName], subnet.NicToMac[nicName], nil + if s.V6NicToIP[nicName] != nil && s.NicToMac[nicName] != "" { + if !util.ContainsString(skippedAddrs, s.V6NicToIP[nicName].String()) { + return nil, s.V6NicToIP[nicName], s.NicToMac[nicName], nil } - subnet.releaseAddr(podName, nicName) + s.releaseAddr(podName, nicName) } - pool := subnet.IPPools[ippoolName] + pool := s.IPPools[ippoolName] if pool == nil { return nil, nil, "", ErrNoAvailable } @@ -294,43 +295,42 @@ func (subnet *Subnet) getV6RandomAddress(ippoolName, podName, nicName string, ma pool.V6Available.Remove(ip) pool.V6Using.Add(ip) - subnet.V6Free.Remove(ip) - subnet.V6Available.Remove(ip) - subnet.V6Using.Add(ip) + s.V6Free.Remove(ip) + s.V6Available.Remove(ip) + s.V6Using.Add(ip) - subnet.V6NicToIP[nicName] = ip - subnet.V6IPToPod[ip.String()] = podName - subnet.pushPodNic(podName, nicName) + s.V6NicToIP[nicName] = ip + s.V6IPToPod[ip.String()] = podName + s.pushPodNic(podName, nicName) if mac == nil { - return nil, ip, subnet.GetRandomMac(podName, nicName), nil - } else { - if err := subnet.GetStaticMac(podName, nicName, *mac, checkConflict); err != nil { - return nil, nil, "", err - } - return nil, ip, *mac, nil + return nil, ip, s.GetRandomMac(podName, nicName), nil } + if err := s.GetStaticMac(podName, nicName, *mac, checkConflict); err != nil { + return nil, nil, "", err + } + return nil, ip, *mac, nil } -func (subnet *Subnet) GetStaticAddress(podName, nicName string, ip IP, mac *string, force bool, checkConflict bool) (IP, string, error) { +func (s *Subnet) GetStaticAddress(podName, nicName string, ip IP, mac *string, force, checkConflict bool) (IP, string, error) { var v4, v6 bool isAllocated := false - subnet.mutex.Lock() - defer subnet.mutex.Unlock() + s.mutex.Lock() + defer s.mutex.Unlock() if ip.To4() != nil { - v4 = subnet.V4CIDR != nil + v4 = s.V4CIDR != nil } else { - v6 = subnet.V6CIDR != nil + v6 = s.V6CIDR != nil } - if v4 && !subnet.V4CIDR.Contains(net.IP(ip)) { + if v4 && !s.V4CIDR.Contains(net.IP(ip)) { return ip, "", ErrOutOfRange } - if v6 && !subnet.V6CIDR.Contains(net.IP(ip)) { + if v6 && !s.V6CIDR.Contains(net.IP(ip)) { return ip, "", ErrOutOfRange } var pool *IPPool - for _, p := range subnet.IPPools { + for _, p := range s.IPPools { if v4 && p.V4IPs.Contains(ip) { pool = p break @@ -342,17 +342,17 @@ func (subnet *Subnet) GetStaticAddress(podName, nicName string, ip IP, mac *stri } defer func() { - subnet.pushPodNic(podName, nicName) + s.pushPodNic(podName, nicName) if isAllocated { if v4 { - subnet.V4Available.Remove(ip) - subnet.V4Using.Add(ip) + s.V4Available.Remove(ip) + s.V4Using.Add(ip) pool.V4Available.Remove(ip) pool.V4Using.Add(ip) } if v6 { - subnet.V6Available.Remove(ip) - subnet.V6Using.Add(ip) + s.V6Available.Remove(ip) + s.V6Using.Add(ip) pool.V6Available.Remove(ip) pool.V6Using.Add(ip) } @@ -361,25 +361,25 @@ func (subnet *Subnet) GetStaticAddress(podName, nicName string, ip IP, mac *stri var macStr string if mac == nil { - if m, ok := subnet.NicToMac[nicName]; ok { + if m, ok := s.NicToMac[nicName]; ok { macStr = m } else { - macStr = subnet.GetRandomMac(podName, nicName) + macStr = s.GetRandomMac(podName, nicName) } } else { - if err := subnet.GetStaticMac(podName, nicName, *mac, checkConflict); err != nil { + if err := s.GetStaticMac(podName, nicName, *mac, checkConflict); err != nil { return ip, macStr, err } macStr = *mac } if v4 { - if existPod, ok := subnet.V4IPToPod[ip.String()]; ok { + if existPod, ok := s.V4IPToPod[ip.String()]; ok { pods := strings.Split(existPod, ",") if !util.ContainsString(pods, podName) { if !checkConflict { - subnet.V4NicToIP[nicName] = ip - subnet.V4IPToPod[ip.String()] = fmt.Sprintf("%s,%s", subnet.V4IPToPod[ip.String()], podName) + s.V4NicToIP[nicName] = ip + s.V4IPToPod[ip.String()] = fmt.Sprintf("%s,%s", s.V4IPToPod[ip.String()], podName) return ip, macStr, nil } klog.Errorf("ip %s has been allocated to %v", ip.String(), pods) @@ -391,30 +391,30 @@ func (subnet *Subnet) GetStaticAddress(podName, nicName string, ip IP, mac *stri } if pool.V4Reserved.Contains(ip) { - subnet.V4NicToIP[nicName] = ip - subnet.V4IPToPod[ip.String()] = podName + s.V4NicToIP[nicName] = ip + s.V4IPToPod[ip.String()] = podName return ip, macStr, nil } if pool.V4Free.Remove(ip) { - subnet.V4Free.Remove(ip) - subnet.V4NicToIP[nicName] = ip - subnet.V4IPToPod[ip.String()] = podName + s.V4Free.Remove(ip) + s.V4NicToIP[nicName] = ip + s.V4IPToPod[ip.String()] = podName isAllocated = true return ip, macStr, nil } else if pool.V4Released.Remove(ip) { - subnet.V4NicToIP[nicName] = ip - subnet.V4IPToPod[ip.String()] = podName + s.V4NicToIP[nicName] = ip + s.V4IPToPod[ip.String()] = podName isAllocated = true return ip, macStr, nil } } else if v6 { - if existPod, ok := subnet.V6IPToPod[ip.String()]; ok { + if existPod, ok := s.V6IPToPod[ip.String()]; ok { pods := strings.Split(existPod, ",") if !util.ContainsString(pods, podName) { if !checkConflict { - subnet.V6NicToIP[nicName] = ip - subnet.V6IPToPod[ip.String()] = fmt.Sprintf("%s,%s", subnet.V6IPToPod[ip.String()], podName) + s.V6NicToIP[nicName] = ip + s.V6IPToPod[ip.String()] = fmt.Sprintf("%s,%s", s.V6IPToPod[ip.String()], podName) return ip, macStr, nil } klog.Errorf("ip %s has been allocated to %v", ip.String(), pods) @@ -426,20 +426,20 @@ func (subnet *Subnet) GetStaticAddress(podName, nicName string, ip IP, mac *stri } if pool.V6Reserved.Contains(ip) { - subnet.V6NicToIP[nicName] = ip - subnet.V6IPToPod[ip.String()] = podName + s.V6NicToIP[nicName] = ip + s.V6IPToPod[ip.String()] = podName return ip, macStr, nil } if pool.V6Free.Remove(ip) { - subnet.V6Free.Remove(ip) - subnet.V6NicToIP[nicName] = ip - subnet.V6IPToPod[ip.String()] = podName + s.V6Free.Remove(ip) + s.V6NicToIP[nicName] = ip + s.V6IPToPod[ip.String()] = podName isAllocated = true return ip, macStr, nil } else if pool.V6Released.Remove(ip) { - subnet.V6NicToIP[nicName] = ip - subnet.V6IPToPod[ip.String()] = podName + s.V6NicToIP[nicName] = ip + s.V6IPToPod[ip.String()] = podName isAllocated = true return ip, macStr, nil } @@ -447,43 +447,43 @@ func (subnet *Subnet) GetStaticAddress(podName, nicName string, ip IP, mac *stri return ip, macStr, ErrNoAvailable } -func (subnet *Subnet) releaseAddr(podName, nicName string) { +func (s *Subnet) releaseAddr(podName, nicName string) { var ip IP var mac string var ok, changed bool - if ip, ok = subnet.V4NicToIP[nicName]; ok { - oldPods := strings.Split(subnet.V4IPToPod[ip.String()], ",") + if ip, ok = s.V4NicToIP[nicName]; ok { + oldPods := strings.Split(s.V4IPToPod[ip.String()], ",") if len(oldPods) > 1 { newPods := util.RemoveString(oldPods, podName) - subnet.V4IPToPod[ip.String()] = strings.Join(newPods, ",") + s.V4IPToPod[ip.String()] = strings.Join(newPods, ",") } else { - delete(subnet.V4NicToIP, nicName) - delete(subnet.V4IPToPod, ip.String()) - if mac, ok = subnet.NicToMac[nicName]; ok { - delete(subnet.NicToMac, nicName) - delete(subnet.MacToPod, mac) + delete(s.V4NicToIP, nicName) + delete(s.V4IPToPod, ip.String()) + if mac, ok = s.NicToMac[nicName]; ok { + delete(s.NicToMac, nicName) + delete(s.MacToPod, mac) } // When CIDR changed, do not relocate ip to CIDR list - if !subnet.V4CIDR.Contains(net.IP(ip)) { + if !s.V4CIDR.Contains(net.IP(ip)) { // Continue to release IPv6 address - klog.Infof("release v4 %s mac %s from subnet %s for %s, ignore ip", ip, mac, subnet.Name, podName) + klog.Infof("release v4 %s mac %s from subnet %s for %s, ignore ip", ip, mac, s.Name, podName) changed = true } - if subnet.V4Reserved.Contains(ip) { - klog.Infof("release v4 %s mac %s from subnet %s for %s, ip is in reserved list", ip, mac, subnet.Name, podName) + if s.V4Reserved.Contains(ip) { + klog.Infof("release v4 %s mac %s from subnet %s for %s, ip is in reserved list", ip, mac, s.Name, podName) changed = true } - subnet.V4Available.Add(ip) - subnet.V4Using.Remove(ip) - for _, pool := range subnet.IPPools { + s.V4Available.Add(ip) + s.V4Using.Remove(ip) + for _, pool := range s.IPPools { if pool.V4Using.Remove(ip) { pool.V4Available.Add(ip) if !changed { if pool.V4Released.Add(ip) { - klog.Infof("release v4 %s mac %s from subnet %s for %s, add ip to released list", ip, mac, subnet.Name, podName) + klog.Infof("release v4 %s mac %s from subnet %s for %s, add ip to released list", ip, mac, s.Name, podName) } } break @@ -491,38 +491,38 @@ func (subnet *Subnet) releaseAddr(podName, nicName string) { } } } - if ip, ok = subnet.V6NicToIP[nicName]; ok { - oldPods := strings.Split(subnet.V6IPToPod[ip.String()], ",") + if ip, ok = s.V6NicToIP[nicName]; ok { + oldPods := strings.Split(s.V6IPToPod[ip.String()], ",") if len(oldPods) > 1 { newPods := util.RemoveString(oldPods, podName) - subnet.V6IPToPod[ip.String()] = strings.Join(newPods, ",") + s.V6IPToPod[ip.String()] = strings.Join(newPods, ",") } else { - delete(subnet.V6NicToIP, nicName) - delete(subnet.V6IPToPod, ip.String()) - if mac, ok = subnet.NicToMac[nicName]; ok { - delete(subnet.NicToMac, nicName) - delete(subnet.MacToPod, mac) + delete(s.V6NicToIP, nicName) + delete(s.V6IPToPod, ip.String()) + if mac, ok = s.NicToMac[nicName]; ok { + delete(s.NicToMac, nicName) + delete(s.MacToPod, mac) } changed = false // When CIDR changed, do not relocate ip to CIDR list - if !subnet.V6CIDR.Contains(net.IP(ip)) { - klog.Infof("release v6 %s mac %s from subnet %s for %s, ignore ip", ip, mac, subnet.Name, podName) + if !s.V6CIDR.Contains(net.IP(ip)) { + klog.Infof("release v6 %s mac %s from subnet %s for %s, ignore ip", ip, mac, s.Name, podName) changed = true } - if subnet.V6Reserved.Contains(ip) { - klog.Infof("release v6 %s mac %s from subnet %s for %s, ip is in reserved list", ip, mac, subnet.Name, podName) + if s.V6Reserved.Contains(ip) { + klog.Infof("release v6 %s mac %s from subnet %s for %s, ip is in reserved list", ip, mac, s.Name, podName) changed = true } - subnet.V6Available.Add(ip) - subnet.V6Using.Remove(ip) - for _, pool := range subnet.IPPools { + s.V6Available.Add(ip) + s.V6Using.Remove(ip) + for _, pool := range s.IPPools { if pool.V6Using.Remove(ip) { pool.V6Available.Add(ip) if !changed { if pool.V6Released.Add(ip) { - klog.Infof("release v6 %s mac %s from subnet %s for %s, add ip to released list", ip, mac, subnet.Name, podName) + klog.Infof("release v6 %s mac %s from subnet %s for %s, add ip to released list", ip, mac, s.Name, podName) } } break @@ -532,58 +532,59 @@ func (subnet *Subnet) releaseAddr(podName, nicName string) { } } -func (subnet *Subnet) ReleaseAddress(podName string) { - subnet.mutex.Lock() - defer subnet.mutex.Unlock() - for _, nicName := range subnet.PodToNicList[podName] { - subnet.releaseAddr(podName, nicName) - subnet.popPodNic(podName, nicName) +func (s *Subnet) ReleaseAddress(podName string) { + s.mutex.Lock() + defer s.mutex.Unlock() + for _, nicName := range s.PodToNicList[podName] { + s.releaseAddr(podName, nicName) + s.popPodNic(podName, nicName) } } -func (subnet *Subnet) ReleaseAddressWithNicName(podName, nicName string) { - subnet.mutex.Lock() - defer subnet.mutex.Unlock() +func (s *Subnet) ReleaseAddressWithNicName(podName, nicName string) { + s.mutex.Lock() + defer s.mutex.Unlock() - subnet.releaseAddr(podName, nicName) - subnet.popPodNic(podName, nicName) + s.releaseAddr(podName, nicName) + s.popPodNic(podName, nicName) } -func (subnet *Subnet) ContainAddress(address IP) bool { - subnet.mutex.RLock() - defer subnet.mutex.RUnlock() +func (s *Subnet) ContainAddress(address IP) bool { + s.mutex.RLock() + defer s.mutex.RUnlock() - if _, ok := subnet.V4IPToPod[address.String()]; ok { + if _, ok := s.V4IPToPod[address.String()]; ok { return true - } else if _, ok := subnet.V6IPToPod[address.String()]; ok { + } else if _, ok := s.V6IPToPod[address.String()]; ok { return true } return false } // This func is only called in ipam.GetPodAddress, move mutex to caller -func (subnet *Subnet) GetPodAddress(podName, nicName string) (IP, IP, string, string) { - if subnet.Protocol == kubeovnv1.ProtocolIPv4 { - ip, mac := subnet.V4NicToIP[nicName], subnet.NicToMac[nicName] +func (s *Subnet) GetPodAddress(_, nicName string) (IP, IP, string, string) { + switch s.Protocol { + case kubeovnv1.ProtocolIPv4: + ip, mac := s.V4NicToIP[nicName], s.NicToMac[nicName] return ip, nil, mac, kubeovnv1.ProtocolIPv4 - } else if subnet.Protocol == kubeovnv1.ProtocolIPv6 { - ip, mac := subnet.V6NicToIP[nicName], subnet.NicToMac[nicName] + case kubeovnv1.ProtocolIPv6: + ip, mac := s.V6NicToIP[nicName], s.NicToMac[nicName] return nil, ip, mac, kubeovnv1.ProtocolIPv6 - } else { - v4IP, v6IP, mac := subnet.V4NicToIP[nicName], subnet.V6NicToIP[nicName], subnet.NicToMac[nicName] + default: + v4IP, v6IP, mac := s.V4NicToIP[nicName], s.V6NicToIP[nicName], s.NicToMac[nicName] return v4IP, v6IP, mac, kubeovnv1.ProtocolDual } } -func (subnet *Subnet) isIPAssignedToOtherPod(ip, podName string) (string, bool) { - if existPod, ok := subnet.V4IPToPod[ip]; ok { +func (s *Subnet) isIPAssignedToOtherPod(ip, podName string) (string, bool) { + if existPod, ok := s.V4IPToPod[ip]; ok { klog.V(4).Infof("v4 check ip assigned, existPod %s, podName %s", existPod, podName) pods := strings.Split(existPod, ",") if !util.ContainsString(pods, podName) { return existPod, true } } - if existPod, ok := subnet.V6IPToPod[ip]; ok { + if existPod, ok := s.V6IPToPod[ip]; ok { klog.V(4).Infof("v6 check ip assigned, existPod %s, podName %s", existPod, podName) pods := strings.Split(existPod, ",") if !util.ContainsString(pods, podName) { diff --git a/pkg/ovn_leader_checker/ovn.go b/pkg/ovn_leader_checker/ovn.go index b9697ec1b43..66362a9a921 100755 --- a/pkg/ovn_leader_checker/ovn.go +++ b/pkg/ovn_leader_checker/ovn.go @@ -176,7 +176,7 @@ func isDBLeader(dbName string, port int) bool { func checkNorthdActive() bool { var command []string - file, err := os.OpenFile(OvnNorthdPid, os.O_RDWR, 0600) + file, err := os.OpenFile(OvnNorthdPid, os.O_RDWR, 0o600) if err != nil { klog.Errorf("failed to open %s err = %v", OvnNorthdPid, err) return false @@ -322,7 +322,7 @@ func updatePodLabels(labels map[string]string, key string, isLeader bool) { } func compactOvnDatabase(db string) { - var command = []string{ + command := []string{ "-t", fmt.Sprintf("/var/run/ovn/ovn%s_db.ctl", db), "ovsdb-server/compact", @@ -341,7 +341,7 @@ func compactOvnDatabase(db string) { } } -func doOvnLeaderCheck(cfg *Configuration, podName string, podNamespace string) { +func doOvnLeaderCheck(cfg *Configuration, podName, podNamespace string) { if podName == "" || podNamespace == "" { util.LogFatalAndExit(nil, "env variables POD_NAME and POD_NAMESPACE must be set") } diff --git a/pkg/ovn_leader_checker/ovn_test.go b/pkg/ovn_leader_checker/ovn_test.go index 63b999e3e12..75c90c1d583 100644 --- a/pkg/ovn_leader_checker/ovn_test.go +++ b/pkg/ovn_leader_checker/ovn_test.go @@ -30,7 +30,8 @@ func Test_patchPodLabels(t *testing.T) { podName := "ovn-central-123" podNamespace := "default" pod := mockPod(podName, podNamespace, map[string]string{ - "app": "nginx"}) + "app": "nginx", + }) clientset := fake.NewSimpleClientset(pod) cfg := &Configuration{ diff --git a/pkg/ovnmonitor/exporter.go b/pkg/ovnmonitor/exporter.go index eeb17a717bb..77ecdc49785 100644 --- a/pkg/ovnmonitor/exporter.go +++ b/pkg/ovnmonitor/exporter.go @@ -287,19 +287,17 @@ func (e *Exporter) exportOvnDBStatusGauge() { if checkNbDbCnt < 6 { klog.Warningf("Failed to get OVN NB DB status for %v times", checkNbDbCnt) return - } else { - klog.Warningf("Failed to get OVN NB DB status for %v times, ready to restore OVN DB", checkNbDbCnt) - checkNbDbCnt = 0 } + klog.Warningf("Failed to get OVN NB DB status for %v times, ready to restore OVN DB", checkNbDbCnt) + checkNbDbCnt = 0 case "OVN_Southbound": checkSbDbCnt++ if checkSbDbCnt < 6 { klog.Warningf("Failed to get OVN SB DB status for %v times", checkSbDbCnt) return - } else { - klog.Warningf("Failed to get OVN SB DB status for %v times, ready to restore OVN DB", checkSbDbCnt) - checkSbDbCnt = 0 } + klog.Warningf("Failed to get OVN SB DB status for %v times, ready to restore OVN DB", checkSbDbCnt) + checkSbDbCnt = 0 } output, err := exec.Command("/bin/bash", "/kube-ovn/restore-ovn-nb-db.sh").CombinedOutput() diff --git a/pkg/ovnmonitor/util.go b/pkg/ovnmonitor/util.go index a39d6b370e5..f6dbad4bd0b 100644 --- a/pkg/ovnmonitor/util.go +++ b/pkg/ovnmonitor/util.go @@ -207,13 +207,14 @@ func getClusterInfo(direction, dbName string) (*OVNDBClusterStatus, error) { // the value is of the format `->0000 (->56d7) <-46ac <-56d7` var connIn, connOut, connInErr, connOutErr float64 for _, conn := range strings.Fields(line[idx+2:]) { - if strings.HasPrefix(conn, "->") { + switch { + case strings.HasPrefix(conn, "->"): connOut++ - } else if strings.HasPrefix(conn, "<-") { + case strings.HasPrefix(conn, "<-"): connIn++ - } else if strings.HasPrefix(conn, "(->") { + case strings.HasPrefix(conn, "(->"): connOutErr++ - } else if strings.HasPrefix(conn, "(<-") { + case strings.HasPrefix(conn, "(<-"): connInErr++ } } diff --git a/pkg/ovs/adapter.go b/pkg/ovs/adapter.go index b070654be40..a2315b68194 100644 --- a/pkg/ovs/adapter.go +++ b/pkg/ovs/adapter.go @@ -2,15 +2,13 @@ package ovs import "github.com/prometheus/client_golang/prometheus" -var ( - // OVN NB metrics - ovsClientRequestLatency = prometheus.NewHistogramVec( - prometheus.HistogramOpts{ - Name: "ovs_client_request_latency_milliseconds", - Buckets: prometheus.ExponentialBuckets(1, 2, 10), - }, - []string{"db", "method", "code"}, - ) +// OVN NB metrics +var ovsClientRequestLatency = prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "ovs_client_request_latency_milliseconds", + Buckets: prometheus.ExponentialBuckets(1, 2, 10), + }, + []string{"db", "method", "code"}, ) func init() { diff --git a/pkg/ovs/interface.go b/pkg/ovs/interface.go index 0d8e28f4401..78b6c37931c 100644 --- a/pkg/ovs/interface.go +++ b/pkg/ovs/interface.go @@ -31,7 +31,7 @@ type LogicalRouter interface { type LogicalRouterPort interface { CreatePeerRouterPort(localRouter, remoteRouter, localRouterPortIP string) error - CreateLogicalRouterPort(lrName string, lrpName, mac string, networks []string) error + CreateLogicalRouterPort(lrName, lrpName, mac string, networks []string) error UpdateLogicalRouterPortRA(lrpName, ipv6RAConfigsStr string, enableIPv6RA bool) error UpdateLogicalRouterPortOptions(lrpName string, options map[string]string) error DeleteLogicalRouterPort(lrpName string) error @@ -58,7 +58,7 @@ type LogicalSwitch interface { } type LogicalSwitchPort interface { - CreateLogicalSwitchPort(lsName, lspName, ip, mac, podName, namespace string, portSecurity bool, securityGroups string, vips string, enableDHCP bool, dhcpOptions *DHCPOptionsUUIDs, vpc string) error + CreateLogicalSwitchPort(lsName, lspName, ip, mac, podName, namespace string, portSecurity bool, securityGroups, vips string, enableDHCP bool, dhcpOptions *DHCPOptionsUUIDs, vpc string) error CreateBareLogicalSwitchPort(lsName, lspName, ip, mac string) error CreateLocalnetLogicalSwitchPort(lsName, lspName, provider string, vlanID int) error CreateVirtualLogicalSwitchPorts(lsName string, ips ...string) error @@ -67,7 +67,7 @@ type LogicalSwitchPort interface { SetLogicalSwitchPortArpProxy(lspName string, enableArpProxy bool) error SetLogicalSwitchPortExternalIds(lspName string, externalIds map[string]string) error SetLogicalSwitchPortVlanTag(lspName string, vlanID int) error - SetLogicalSwitchPortsSecurityGroup(sgName string, op string) error + SetLogicalSwitchPortsSecurityGroup(sgName, op string) error EnablePortLayer2forward(lspName string) error DeleteLogicalSwitchPort(lspName string) error ListLogicalSwitchPorts(needVendorFilter bool, externalIDs map[string]string, filter func(lsp *ovnnb.LogicalSwitchPort) bool) ([]ovnnb.LogicalSwitchPort, error) @@ -100,18 +100,18 @@ type PortGroup interface { } type ACL interface { - UpdateIngressAclOps(pgName, asIngressName, asExceptName, protocol string, npp []netv1.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) - UpdateEgressAclOps(pgName, asEgressName, asExceptName, protocol string, npp []netv1.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) - CreateGatewayAcl(lsName, pgName, gateway string) error - CreateNodeAcl(pgName, nodeIpStr, joinIpStr string) error - CreateSgDenyAllAcl(sgName string) error - CreateSgBaseACL(sgName string, direction string) error - UpdateSgAcl(sg *kubeovnv1.SecurityGroup, direction string) error - UpdateLogicalSwitchAcl(lsName string, subnetAcls []kubeovnv1.Acl) error - SetAclLog(pgName, protocol string, logEnable, isIngress bool) error + UpdateIngressACLOps(pgName, asIngressName, asExceptName, protocol string, npp []netv1.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) + UpdateEgressACLOps(pgName, asEgressName, asExceptName, protocol string, npp []netv1.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) + CreateGatewayACL(lsName, pgName, gateway string) error + CreateNodeACL(pgName, nodeIPStr, joinIPStr string) error + CreateSgDenyAllACL(sgName string) error + CreateSgBaseACL(sgName, direction string) error + UpdateSgACL(sg *kubeovnv1.SecurityGroup, direction string) error + UpdateLogicalSwitchACL(lsName string, subnetAcls []kubeovnv1.ACL) error + SetACLLog(pgName, protocol string, logEnable, isIngress bool) error SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR string, allowSubnets []string) error - DeleteAcls(parentName, parentType string, direction string, externalIDs map[string]string) error - DeleteAclsOps(parentName, parentType string, direction string, externalIDs map[string]string) ([]ovsdb.Operation, error) + DeleteAcls(parentName, parentType, direction string, externalIDs map[string]string) error + DeleteAclsOps(parentName, parentType, direction string, externalIDs map[string]string) ([]ovsdb.Operation, error) } type AddressSet interface { @@ -123,7 +123,7 @@ type AddressSet interface { } type LogicalRouterStaticRoute interface { - AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix string, bfdId *string, nexthops ...string) error + AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix string, bfdID *string, nexthops ...string) error ClearLogicalRouterStaticRoute(lrName string) error DeleteLogicalRouterStaticRoute(lrName string, routeTable, policy *string, ipPrefix, nextHop string) error ListLogicalRouterStaticRoutesByOption(lrName, routeTable, key, value string) ([]*ovnnb.LogicalRouterStaticRoute, error) @@ -135,7 +135,7 @@ type LogicalRouterPolicy interface { AddLogicalRouterPolicy(lrName string, priority int, match, action string, nextHops []string, externalIDs map[string]string) error DeleteLogicalRouterPolicy(lrName string, priority int, match string) error DeleteLogicalRouterPolicies(lrName string, priority int, externalIDs map[string]string) error - DeleteLogicalRouterPolicyByUUID(lrName string, uuid string) error + DeleteLogicalRouterPolicyByUUID(lrName, uuid string) error DeleteLogicalRouterPolicyByNexthop(lrName string, priority int, nexthop string) error ClearLogicalRouterPolicy(lrName string) error ListLogicalRouterPolicies(lrName string, priority int, externalIDs map[string]string) ([]*ovnnb.LogicalRouterPolicy, error) @@ -155,7 +155,7 @@ type NAT interface { type DHCPOptions interface { UpdateDHCPOptions(subnet *kubeovnv1.Subnet, mtu int) (*DHCPOptionsUUIDs, error) - DeleteDHCPOptions(lsName string, protocol string) error + DeleteDHCPOptions(lsName, protocol string) error DeleteDHCPOptionsByUUIDs(uuidList ...string) error ListDHCPOptions(needVendorFilter bool, externalIDs map[string]string) ([]ovnnb.DHCPOptions, error) } @@ -200,7 +200,7 @@ type Chassis interface { GetChassisByHost(nodeName string) (*ovnsb.Chassis, error) GetChassis(chassisName string, ignoreNotFound bool) (*ovnsb.Chassis, error) GetKubeOvnChassisses() (*[]ovnsb.Chassis, error) - UpdateChassisTag(chassisName string, nodeName string) error + UpdateChassisTag(chassisName, nodeName string) error UpdateChassis(chassis *ovnsb.Chassis, fields ...interface{}) error ListChassis() (*[]ovnsb.Chassis, error) } diff --git a/pkg/ovs/ovn-nb-acl.go b/pkg/ovs/ovn-nb-acl.go index 77f8b359829..4521b587af3 100644 --- a/pkg/ovs/ovn-nb-acl.go +++ b/pkg/ovs/ovn-nb-acl.go @@ -18,8 +18,8 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -// UpdateIngressAclOps return operation that creates an ingress ACL -func (c *ovnNbClient) UpdateIngressAclOps(pgName, asIngressName, asExceptName, protocol string, npp []netv1.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { +// UpdateIngressACLOps return operation that creates an ingress ACL +func (c *OVNNbClient) UpdateIngressACLOps(pgName, asIngressName, asExceptName, protocol string, npp []netv1.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { acls := make([]*ovnnb.ACL, 0) ipSuffix := "ip4" @@ -28,9 +28,9 @@ func (c *ovnNbClient) UpdateIngressAclOps(pgName, asIngressName, asExceptName, p } /* default drop acl */ - allIpMatch := NewAndAclMatch( - NewAclMatch("outport", "==", "@"+pgName, ""), - NewAclMatch(ipSuffix, "", "", ""), + allIPMatch := NewAndACLMatch( + NewACLMatch("outport", "==", "@"+pgName, ""), + NewACLMatch(ipSuffix, "", "", ""), ) options := func(acl *ovnnb.ACL) { if logEnable { @@ -39,22 +39,22 @@ func (c *ovnNbClient) UpdateIngressAclOps(pgName, asIngressName, asExceptName, p } } - defaultDropAcl, err := c.newAclWithoutCheck(pgName, ovnnb.ACLDirectionToLport, util.IngressDefaultDrop, allIpMatch.String(), ovnnb.ACLActionDrop, options) + defaultDropACL, err := c.newACLWithoutCheck(pgName, ovnnb.ACLDirectionToLport, util.IngressDefaultDrop, allIPMatch.String(), ovnnb.ACLActionDrop, options) if err != nil { return nil, fmt.Errorf("new default drop ingress acl for port group %s: %v", pgName, err) } - acls = append(acls, defaultDropAcl) + acls = append(acls, defaultDropACL) /* allow acl */ - matches := newNetworkPolicyAclMatch(pgName, asIngressName, asExceptName, protocol, ovnnb.ACLDirectionToLport, npp, namedPortMap) + matches := newNetworkPolicyACLMatch(pgName, asIngressName, asExceptName, protocol, ovnnb.ACLDirectionToLport, npp, namedPortMap) for _, m := range matches { - allowAcl, err := c.newAclWithoutCheck(pgName, ovnnb.ACLDirectionToLport, util.IngressAllowPriority, m, ovnnb.ACLActionAllowRelated) + allowACL, err := c.newACLWithoutCheck(pgName, ovnnb.ACLDirectionToLport, util.IngressAllowPriority, m, ovnnb.ACLActionAllowRelated) if err != nil { return nil, fmt.Errorf("new allow ingress acl for port group %s: %v", pgName, err) } - acls = append(acls, allowAcl) + acls = append(acls, allowACL) } ops, err := c.CreateAclsOps(pgName, portGroupKey, acls...) @@ -65,8 +65,8 @@ func (c *ovnNbClient) UpdateIngressAclOps(pgName, asIngressName, asExceptName, p return ops, nil } -// UpdateEgressAclOps return operation that creates an egress ACL -func (c *ovnNbClient) UpdateEgressAclOps(pgName, asEgressName, asExceptName, protocol string, npp []netv1.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { +// UpdateEgressACLOps return operation that creates an egress ACL +func (c *OVNNbClient) UpdateEgressACLOps(pgName, asEgressName, asExceptName, protocol string, npp []netv1.NetworkPolicyPort, logEnable bool, namedPortMap map[string]*util.NamedPortInfo) ([]ovsdb.Operation, error) { acls := make([]*ovnnb.ACL, 0) ipSuffix := "ip4" @@ -75,9 +75,9 @@ func (c *ovnNbClient) UpdateEgressAclOps(pgName, asEgressName, asExceptName, pro } /* default drop acl */ - allIpMatch := NewAndAclMatch( - NewAclMatch("inport", "==", "@"+pgName, ""), - NewAclMatch(ipSuffix, "", "", ""), + allIPMatch := NewAndACLMatch( + NewACLMatch("inport", "==", "@"+pgName, ""), + NewACLMatch(ipSuffix, "", "", ""), ) options := func(acl *ovnnb.ACL) { if logEnable { @@ -91,18 +91,18 @@ func (c *ovnNbClient) UpdateEgressAclOps(pgName, asEgressName, asExceptName, pro acl.Options["apply-after-lb"] = "true" } - defaultDropAcl, err := c.newAclWithoutCheck(pgName, ovnnb.ACLDirectionFromLport, util.EgressDefaultDrop, allIpMatch.String(), ovnnb.ACLActionDrop, options) + defaultDropACL, err := c.newACLWithoutCheck(pgName, ovnnb.ACLDirectionFromLport, util.EgressDefaultDrop, allIPMatch.String(), ovnnb.ACLActionDrop, options) if err != nil { klog.Error(err) return nil, fmt.Errorf("new default drop egress acl for port group %s: %v", pgName, err) } - acls = append(acls, defaultDropAcl) + acls = append(acls, defaultDropACL) /* allow acl */ - matches := newNetworkPolicyAclMatch(pgName, asEgressName, asExceptName, protocol, ovnnb.ACLDirectionFromLport, npp, namedPortMap) + matches := newNetworkPolicyACLMatch(pgName, asEgressName, asExceptName, protocol, ovnnb.ACLDirectionFromLport, npp, namedPortMap) for _, m := range matches { - allowAcl, err := c.newAclWithoutCheck(pgName, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, m, ovnnb.ACLActionAllowRelated, func(acl *ovnnb.ACL) { + allowACL, err := c.newACLWithoutCheck(pgName, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, m, ovnnb.ACLActionAllowRelated, func(acl *ovnnb.ACL) { if acl.Options == nil { acl.Options = make(map[string]string) } @@ -113,7 +113,7 @@ func (c *ovnNbClient) UpdateEgressAclOps(pgName, asEgressName, asExceptName, pro return nil, fmt.Errorf("new allow egress acl for port group %s: %v", pgName, err) } - acls = append(acls, allowAcl) + acls = append(acls, allowACL) } ops, err := c.CreateAclsOps(pgName, portGroupKey, acls...) @@ -126,15 +126,16 @@ func (c *ovnNbClient) UpdateEgressAclOps(pgName, asEgressName, asExceptName, pro } // CreateGatewayACL create allow acl for subnet gateway -func (c *ovnNbClient) CreateGatewayAcl(lsName, pgName, gateway string) error { +func (c *OVNNbClient) CreateGatewayACL(lsName, pgName, gateway string) error { acls := make([]*ovnnb.ACL, 0) var parentName, parentType string - if len(pgName) != 0 { + switch { + case len(pgName) != 0: parentName, parentType = pgName, portGroupKey - } else if len(lsName) != 0 { + case len(lsName) != 0: parentName, parentType = lsName, logicalSwitchKey - } else { + default: return fmt.Errorf("one of port group name and logical switch name must be specified") } @@ -145,7 +146,7 @@ func (c *ovnNbClient) CreateGatewayAcl(lsName, pgName, gateway string) error { ipSuffix = "ip6" } - allowIngressAcl, err := c.newAcl(parentName, ovnnb.ACLDirectionToLport, util.IngressAllowPriority, fmt.Sprintf("%s.src == %s", ipSuffix, gw), ovnnb.ACLActionAllowStateless) + allowIngressACL, err := c.newACL(parentName, ovnnb.ACLDirectionToLport, util.IngressAllowPriority, fmt.Sprintf("%s.src == %s", ipSuffix, gw), ovnnb.ACLActionAllowStateless) if err != nil { klog.Error(err) return fmt.Errorf("new allow ingress acl for %s: %v", parentName, err) @@ -158,22 +159,22 @@ func (c *ovnNbClient) CreateGatewayAcl(lsName, pgName, gateway string) error { acl.Options["apply-after-lb"] = "true" } - allowEgressAcl, err := c.newAcl(parentName, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, fmt.Sprintf("%s.dst == %s", ipSuffix, gw), ovnnb.ACLActionAllowStateless, options) + allowEgressACL, err := c.newACL(parentName, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, fmt.Sprintf("%s.dst == %s", ipSuffix, gw), ovnnb.ACLActionAllowStateless, options) if err != nil { klog.Error(err) return fmt.Errorf("new allow egress acl for %s: %v", parentName, err) } - acls = append(acls, allowIngressAcl, allowEgressAcl) + acls = append(acls, allowIngressACL, allowEgressACL) if ipSuffix == "ip6" { - ndAcl, err := c.newAcl(parentName, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, "nd || nd_ra || nd_rs", ovnnb.ACLActionAllowStateless, options) + ndACL, err := c.newACL(parentName, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, "nd || nd_ra || nd_rs", ovnnb.ACLActionAllowStateless, options) if err != nil { klog.Error(err) return fmt.Errorf("new nd acl for %s: %v", parentName, err) } - acls = append(acls, ndAcl) + acls = append(acls, ndACL) } } @@ -185,10 +186,10 @@ func (c *ovnNbClient) CreateGatewayAcl(lsName, pgName, gateway string) error { return nil } -// CreateNodeAcl create allow acl for node join ip -func (c *ovnNbClient) CreateNodeAcl(pgName, nodeIpStr, joinIpStr string) error { +// CreateNodeACL create allow acl for node join ip +func (c *OVNNbClient) CreateNodeACL(pgName, nodeIPStr, joinIPStr string) error { acls := make([]*ovnnb.ACL, 0) - nodeIPs := strings.Split(nodeIpStr, ",") + nodeIPs := strings.Split(nodeIPStr, ",") for _, nodeIP := range nodeIPs { protocol := util.CheckProtocol(nodeIP) ipSuffix := "ip4" @@ -197,7 +198,7 @@ func (c *ovnNbClient) CreateNodeAcl(pgName, nodeIpStr, joinIpStr string) error { } pgAs := fmt.Sprintf("%s_%s", pgName, ipSuffix) - allowIngressAcl, err := c.newAcl(pgName, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, fmt.Sprintf("%s.src == %s && %s.dst == $%s", ipSuffix, nodeIP, ipSuffix, pgAs), ovnnb.ACLActionAllowStateless) + allowIngressACL, err := c.newACL(pgName, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, fmt.Sprintf("%s.src == %s && %s.dst == $%s", ipSuffix, nodeIP, ipSuffix, pgAs), ovnnb.ACLActionAllowStateless) if err != nil { klog.Error(err) return fmt.Errorf("new allow ingress acl for port group %s: %v", pgName, err) @@ -210,21 +211,21 @@ func (c *ovnNbClient) CreateNodeAcl(pgName, nodeIpStr, joinIpStr string) error { acl.Options["apply-after-lb"] = "true" } - allowEgressAcl, err := c.newAcl(pgName, ovnnb.ACLDirectionFromLport, util.NodeAllowPriority, fmt.Sprintf("%s.dst == %s && %s.src == $%s", ipSuffix, nodeIP, ipSuffix, pgAs), ovnnb.ACLActionAllowStateless, options) + allowEgressACL, err := c.newACL(pgName, ovnnb.ACLDirectionFromLport, util.NodeAllowPriority, fmt.Sprintf("%s.dst == %s && %s.src == $%s", ipSuffix, nodeIP, ipSuffix, pgAs), ovnnb.ACLActionAllowStateless, options) if err != nil { klog.Error(err) return fmt.Errorf("new allow egress acl for port group %s: %v", pgName, err) } - acls = append(acls, allowIngressAcl, allowEgressAcl) + acls = append(acls, allowIngressACL, allowEgressACL) } - for _, joinIp := range strings.Split(joinIpStr, ",") { - if util.ContainsString(nodeIPs, joinIp) { + for _, joinIP := range strings.Split(joinIPStr, ",") { + if util.ContainsString(nodeIPs, joinIP) { continue } - protocol := util.CheckProtocol(joinIp) + protocol := util.CheckProtocol(joinIP) ipSuffix := "ip4" if protocol == kubeovnv1.ProtocolIPv6 { ipSuffix = "ip6" @@ -232,12 +233,12 @@ func (c *ovnNbClient) CreateNodeAcl(pgName, nodeIpStr, joinIpStr string) error { pgAs := fmt.Sprintf("%s_%s", pgName, ipSuffix) - if err := c.DeleteAcl(pgName, portGroupKey, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, fmt.Sprintf("%s.src == %s && %s.dst == $%s", ipSuffix, joinIp, ipSuffix, pgAs)); err != nil { + if err := c.DeleteACL(pgName, portGroupKey, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, fmt.Sprintf("%s.src == %s && %s.dst == $%s", ipSuffix, joinIP, ipSuffix, pgAs)); err != nil { klog.Errorf("delete ingress acl from port group %s: %v", pgName, err) return err } - if err := c.DeleteAcl(pgName, portGroupKey, ovnnb.ACLDirectionFromLport, util.NodeAllowPriority, fmt.Sprintf("%s.dst == %s && %s.src == $%s", ipSuffix, joinIp, ipSuffix, pgAs)); err != nil { + if err := c.DeleteACL(pgName, portGroupKey, ovnnb.ACLDirectionFromLport, util.NodeAllowPriority, fmt.Sprintf("%s.dst == %s && %s.src == $%s", ipSuffix, joinIP, ipSuffix, pgAs)); err != nil { klog.Errorf("delete egress acl from port group %s: %v", pgName, err) return err } @@ -250,29 +251,29 @@ func (c *ovnNbClient) CreateNodeAcl(pgName, nodeIpStr, joinIpStr string) error { return nil } -func (c *ovnNbClient) CreateSgDenyAllAcl(sgName string) error { +func (c *OVNNbClient) CreateSgDenyAllACL(sgName string) error { pgName := GetSgPortGroupName(sgName) - ingressAcl, err := c.newAcl(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupDropPriority, fmt.Sprintf("outport == @%s && ip", pgName), ovnnb.ACLActionDrop) + ingressACL, err := c.newACL(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupDropPriority, fmt.Sprintf("outport == @%s && ip", pgName), ovnnb.ACLActionDrop) if err != nil { klog.Error(err) return fmt.Errorf("new deny all ingress acl for security group %s: %v", sgName, err) } - egressAcl, err := c.newAcl(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupDropPriority, fmt.Sprintf("inport == @%s && ip", pgName), ovnnb.ACLActionDrop) + egressACL, err := c.newACL(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupDropPriority, fmt.Sprintf("inport == @%s && ip", pgName), ovnnb.ACLActionDrop) if err != nil { klog.Error(err) return fmt.Errorf("new deny all egress acl for security group %s: %v", sgName, err) } - if err := c.CreateAcls(pgName, portGroupKey, ingressAcl, egressAcl); err != nil { + if err := c.CreateAcls(pgName, portGroupKey, ingressACL, egressACL); err != nil { return fmt.Errorf("add deny all acl to port group %s: %v", pgName, err) } return nil } -func (c *ovnNbClient) CreateSgBaseACL(sgName string, direction string) error { +func (c *OVNNbClient) CreateSgBaseACL(sgName, direction string) error { pgName := GetSgPortGroupName(sgName) // ingress rule @@ -287,8 +288,8 @@ func (c *ovnNbClient) CreateSgBaseACL(sgName string, direction string) error { acls := make([]*ovnnb.ACL, 0) - newAcl := func(match string) { - acl, err := c.newAcl(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupBasePriority, match, ovnnb.ACLActionAllowRelated) + newACL := func(match string) { + acl, err := c.newACL(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupBasePriority, match, ovnnb.ACLActionAllowRelated) if err != nil { klog.Error(err) klog.Errorf("new base ingress acl for security group %s: %v", sgName, err) @@ -298,39 +299,39 @@ func (c *ovnNbClient) CreateSgBaseACL(sgName string, direction string) error { } // allow arp - AllArpMatch := NewAndAclMatch( - NewAclMatch(portDirection, "==", "@"+pgName, ""), - NewAclMatch("arp", "", "", ""), + AllArpMatch := NewAndACLMatch( + NewACLMatch(portDirection, "==", "@"+pgName, ""), + NewACLMatch("arp", "", "", ""), ) - newAcl(AllArpMatch.String()) + newACL(AllArpMatch.String()) // icmpv6 - icmpv6Match := NewAndAclMatch( - NewAclMatch(portDirection, "==", "@"+pgName, ""), - NewAclMatch("icmp6.type", "==", "{130, 134, 135, 136}", ""), - NewAclMatch("icmp6.code", "==", "0", ""), - NewAclMatch("ip.ttl", "==", "255", ""), + icmpv6Match := NewAndACLMatch( + NewACLMatch(portDirection, "==", "@"+pgName, ""), + NewACLMatch("icmp6.type", "==", "{130, 134, 135, 136}", ""), + NewACLMatch("icmp6.code", "==", "0", ""), + NewACLMatch("ip.ttl", "==", "255", ""), ) - newAcl(icmpv6Match.String()) + newACL(icmpv6Match.String()) // dhcpv4 offer - dhcpv4Match := NewAndAclMatch( - NewAclMatch(portDirection, "==", "@"+pgName, ""), - NewAclMatch("udp.src", "==", dhcpv4UdpSrc, ""), - NewAclMatch("udp.dst", "==", dhcpv4UdpDst, ""), - NewAclMatch("ip4", "", "", ""), + dhcpv4Match := NewAndACLMatch( + NewACLMatch(portDirection, "==", "@"+pgName, ""), + NewACLMatch("udp.src", "==", dhcpv4UdpSrc, ""), + NewACLMatch("udp.dst", "==", dhcpv4UdpDst, ""), + NewACLMatch("ip4", "", "", ""), ) - newAcl(dhcpv4Match.String()) + newACL(dhcpv4Match.String()) // dhcpv6 offer - dhcpv6Match := NewAndAclMatch( - NewAclMatch(portDirection, "==", "@"+pgName, ""), - NewAclMatch("udp.src", "==", dhcpv6UdpSrc, ""), - NewAclMatch("udp.dst", "==", dhcpv6UdpDst, ""), - NewAclMatch("ip6", "", "", ""), + dhcpv6Match := NewAndACLMatch( + NewACLMatch(portDirection, "==", "@"+pgName, ""), + NewACLMatch("udp.src", "==", dhcpv6UdpSrc, ""), + NewACLMatch("udp.dst", "==", dhcpv6UdpDst, ""), + NewACLMatch("ip6", "", "", ""), ) - newAcl(dhcpv6Match.String()) + newACL(dhcpv6Match.String()) if err := c.CreateAcls(pgName, portGroupKey, acls...); err != nil { return fmt.Errorf("add ingress acls to port group %s: %v", pgName, err) @@ -338,7 +339,7 @@ func (c *ovnNbClient) CreateSgBaseACL(sgName string, direction string) error { return nil } -func (c *ovnNbClient) UpdateSgAcl(sg *kubeovnv1.SecurityGroup, direction string) error { +func (c *OVNNbClient) UpdateSgACL(sg *kubeovnv1.SecurityGroup, direction string) error { pgName := GetSgPortGroupName(sg.Name) // clear acl @@ -364,12 +365,12 @@ func (c *ovnNbClient) UpdateSgAcl(sg *kubeovnv1.SecurityGroup, direction string) asName = GetSgV6AssociatedName(sg.Name) } - match := NewAndAclMatch( - NewAclMatch(portDirection, "==", "@"+pgName, ""), - NewAclMatch(ipSuffix, "", "", ""), - NewAclMatch(ipSuffix+"."+srcOrDst, "==", "$"+asName, ""), + match := NewAndACLMatch( + NewACLMatch(portDirection, "==", "@"+pgName, ""), + NewACLMatch(ipSuffix, "", "", ""), + NewACLMatch(ipSuffix+"."+srcOrDst, "==", "$"+asName, ""), ) - acl, err := c.newAcl(pgName, direction, util.SecurityGroupAllowPriority, match.String(), ovnnb.ACLActionAllowRelated) + acl, err := c.newACL(pgName, direction, util.SecurityGroupAllowPriority, match.String(), ovnnb.ACLActionAllowRelated) if err != nil { klog.Error(err) return fmt.Errorf("new allow acl for security group %s: %v", sg.Name, err) @@ -396,7 +397,7 @@ func (c *ovnNbClient) UpdateSgAcl(sg *kubeovnv1.SecurityGroup, direction string) return nil } -func (c *ovnNbClient) UpdateLogicalSwitchAcl(lsName string, subnetAcls []kubeovnv1.Acl) error { +func (c *OVNNbClient) UpdateLogicalSwitchACL(lsName string, subnetAcls []kubeovnv1.ACL) error { if err := c.DeleteAcls(lsName, logicalSwitchKey, "", map[string]string{"subnet": lsName}); err != nil { return fmt.Errorf("delete subnet acls from %s: %v", lsName, err) } @@ -414,8 +415,8 @@ func (c *ovnNbClient) UpdateLogicalSwitchAcl(lsName string, subnetAcls []kubeovn } /* recreate logical switch acl */ - for _, subnetAcl := range subnetAcls { - acl, err := c.newAcl(lsName, subnetAcl.Direction, strconv.Itoa(subnetAcl.Priority), subnetAcl.Match, subnetAcl.Action, options) + for _, subnetACL := range subnetAcls { + acl, err := c.newACL(lsName, subnetACL.Direction, strconv.Itoa(subnetACL.Priority), subnetACL.Match, subnetACL.Action, options) if err != nil { klog.Error(err) return fmt.Errorf("new acl for logical switch %s: %v", lsName, err) @@ -430,8 +431,8 @@ func (c *ovnNbClient) UpdateLogicalSwitchAcl(lsName string, subnetAcls []kubeovn return nil } -// UpdateAcl update acl -func (c *ovnNbClient) UpdateAcl(acl *ovnnb.ACL, fields ...interface{}) error { +// UpdateACL update acl +func (c *OVNNbClient) UpdateACL(acl *ovnnb.ACL, fields ...interface{}) error { if acl == nil { return fmt.Errorf("address_set is nil") } @@ -450,7 +451,7 @@ func (c *ovnNbClient) UpdateAcl(acl *ovnnb.ACL, fields ...interface{}) error { } // SetLogicalSwitchPrivate will drop all ingress traffic except allow subnets, same subnet and node subnet -func (c *ovnNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR string, allowSubnets []string) error { +func (c *OVNNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR string, allowSubnets []string) error { // clear acls if err := c.DeleteAcls(lsName, logicalSwitchKey, "", nil); err != nil { return fmt.Errorf("clear logical switch %s acls: %v", lsName, err) @@ -459,7 +460,7 @@ func (c *ovnNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR acls := make([]*ovnnb.ACL, 0) /* default drop acl */ - allIpMatch := NewAclMatch("ip", "", "", "") + allIPMatch := NewACLMatch("ip", "", "", "") options := func(acl *ovnnb.ACL) { acl.Name = &lsName @@ -467,24 +468,24 @@ func (c *ovnNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR acl.Severity = &ovnnb.ACLSeverityWarning } - defaultDropAcl, err := c.newAcl(lsName, ovnnb.ACLDirectionToLport, util.DefaultDropPriority, allIpMatch.String(), ovnnb.ACLActionDrop, options) + defaultDropACL, err := c.newACL(lsName, ovnnb.ACLDirectionToLport, util.DefaultDropPriority, allIPMatch.String(), ovnnb.ACLActionDrop, options) if err != nil { klog.Error(err) return fmt.Errorf("new default drop ingress acl for logical switch %s: %v", lsName, err) } - acls = append(acls, defaultDropAcl) + acls = append(acls, defaultDropACL) - nodeSubnetAclFunc := func(protocol, ipSuffix string) error { + nodeSubnetACLFunc := func(protocol, ipSuffix string) error { for _, nodeCidr := range strings.Split(nodeSwitchCIDR, ",") { // skip different address family if protocol != util.CheckProtocol(nodeCidr) { continue } - match := NewAclMatch(ipSuffix+".src", "==", nodeCidr, "") + match := NewACLMatch(ipSuffix+".src", "==", nodeCidr, "") - acl, err := c.newAcl(lsName, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, match.String(), ovnnb.ACLActionAllowRelated) + acl, err := c.newACL(lsName, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, match.String(), ovnnb.ACLActionAllowRelated) if err != nil { klog.Error(err) return fmt.Errorf("new node subnet ingress acl for logical switch %s: %v", lsName, err) @@ -496,7 +497,7 @@ func (c *ovnNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR return nil } - allowSubnetAclFunc := func(protocol, ipSuffix, cidr string) error { + allowSubnetACLFunc := func(protocol, ipSuffix, cidr string) error { for _, allowSubnet := range allowSubnets { subnet := strings.TrimSpace(allowSubnet) // skip empty subnet @@ -509,18 +510,18 @@ func (c *ovnNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR continue } - match := NewOrAclMatch( - NewAndAclMatch( - NewAclMatch(ipSuffix+".src", "==", cidr, ""), - NewAclMatch(ipSuffix+".dst", "==", subnet, ""), + match := NewOrACLMatch( + NewAndACLMatch( + NewACLMatch(ipSuffix+".src", "==", cidr, ""), + NewACLMatch(ipSuffix+".dst", "==", subnet, ""), ), - NewAndAclMatch( - NewAclMatch(ipSuffix+".src", "==", subnet, ""), - NewAclMatch(ipSuffix+".dst", "==", cidr, ""), + NewAndACLMatch( + NewACLMatch(ipSuffix+".src", "==", subnet, ""), + NewACLMatch(ipSuffix+".dst", "==", cidr, ""), ), ) - acl, err := c.newAcl(lsName, ovnnb.ACLDirectionToLport, util.SubnetAllowPriority, match.String(), ovnnb.ACLActionAllowRelated) + acl, err := c.newACL(lsName, ovnnb.ACLDirectionToLport, util.SubnetAllowPriority, match.String(), ovnnb.ACLActionAllowRelated) if err != nil { klog.Error(err) return fmt.Errorf("new allow subnet ingress acl for logical switch %s: %v", lsName, err) @@ -540,27 +541,27 @@ func (c *ovnNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR } /* same subnet acl */ - sameSubnetMatch := NewAndAclMatch( - NewAclMatch(ipSuffix+".src", "==", cidr, ""), - NewAclMatch(ipSuffix+".dst", "==", cidr, ""), + sameSubnetMatch := NewAndACLMatch( + NewACLMatch(ipSuffix+".src", "==", cidr, ""), + NewACLMatch(ipSuffix+".dst", "==", cidr, ""), ) - sameSubnetAcl, err := c.newAcl(lsName, ovnnb.ACLDirectionToLport, util.SubnetAllowPriority, sameSubnetMatch.String(), ovnnb.ACLActionAllowRelated) + sameSubnetACL, err := c.newACL(lsName, ovnnb.ACLDirectionToLport, util.SubnetAllowPriority, sameSubnetMatch.String(), ovnnb.ACLActionAllowRelated) if err != nil { klog.Error(err) return fmt.Errorf("new same subnet ingress acl for logical switch %s: %v", lsName, err) } - acls = append(acls, sameSubnetAcl) + acls = append(acls, sameSubnetACL) // node subnet acl - if err := nodeSubnetAclFunc(protocol, ipSuffix); err != nil { + if err := nodeSubnetACLFunc(protocol, ipSuffix); err != nil { klog.Error(err) return err } // allow subnet acl - if err := allowSubnetAclFunc(protocol, ipSuffix, cidr); err != nil { + if err := allowSubnetACLFunc(protocol, ipSuffix, cidr); err != nil { klog.Error(err) return err } @@ -574,7 +575,7 @@ func (c *ovnNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR return nil } -func (c *ovnNbClient) SetAclLog(pgName, protocol string, logEnable, isIngress bool) error { +func (c *OVNNbClient) SetACLLog(pgName, protocol string, logEnable, isIngress bool) error { direction := ovnnb.ACLDirectionToLport portDirection := "outport" if !isIngress { @@ -588,24 +589,24 @@ func (c *ovnNbClient) SetAclLog(pgName, protocol string, logEnable, isIngress bo } // match all traffic to or from pgName - allIpMatch := NewAndAclMatch( - NewAclMatch(portDirection, "==", "@"+pgName, ""), - NewAclMatch(ipSuffix, "", "", ""), + allIPMatch := NewAndACLMatch( + NewACLMatch(portDirection, "==", "@"+pgName, ""), + NewACLMatch(ipSuffix, "", "", ""), ) - acl, err := c.GetAcl(pgName, direction, util.IngressDefaultDrop, allIpMatch.String(), true) + acl, err := c.GetACL(pgName, direction, util.IngressDefaultDrop, allIPMatch.String(), true) if err != nil { klog.Error(err) return err } if acl == nil { - return nil //skip if acl not found + return nil // skip if acl not found } acl.Log = logEnable - err = c.UpdateAcl(acl, &acl.Log) + err = c.UpdateACL(acl, &acl.Log) if err != nil { klog.Error(err) return fmt.Errorf("update acl: %v", err) @@ -616,7 +617,7 @@ func (c *ovnNbClient) SetAclLog(pgName, protocol string, logEnable, isIngress bo // CreateAcls create several acl once // parentType is 'ls' or 'pg' -func (c *ovnNbClient) CreateAcls(parentName, parentType string, acls ...*ovnnb.ACL) error { +func (c *OVNNbClient) CreateAcls(parentName, parentType string, acls ...*ovnnb.ACL) error { ops, err := c.CreateAclsOps(parentName, parentType, acls...) if err != nil { klog.Error(err) @@ -630,8 +631,8 @@ func (c *ovnNbClient) CreateAcls(parentName, parentType string, acls ...*ovnnb.A return nil } -func (c *ovnNbClient) CreateBareAcl(parentName, direction, priority, match, action string) error { - acl, err := c.newAcl(parentName, direction, priority, match, action) +func (c *OVNNbClient) CreateBareACL(parentName, direction, priority, match, action string) error { + acl, err := c.newACL(parentName, direction, priority, match, action) if err != nil { klog.Error(err) return fmt.Errorf("new acl direction %s priority %s match %s action %s: %v", direction, priority, match, action, err) @@ -653,7 +654,7 @@ func (c *ovnNbClient) CreateBareAcl(parentName, direction, priority, match, acti // DeleteAcls delete several acl once, // delete to-lport and from-lport direction acl when direction is empty, otherwise one-way // parentType is 'ls' or 'pg' -func (c *ovnNbClient) DeleteAcls(parentName, parentType string, direction string, externalIDs map[string]string) error { +func (c *OVNNbClient) DeleteAcls(parentName, parentType, direction string, externalIDs map[string]string) error { ops, err := c.DeleteAclsOps(parentName, parentType, direction, externalIDs) if err != nil { klog.Error(err) @@ -667,8 +668,8 @@ func (c *ovnNbClient) DeleteAcls(parentName, parentType string, direction string return nil } -func (c *ovnNbClient) DeleteAcl(parentName, parentType, direction, priority, match string) error { - acl, err := c.GetAcl(parentName, direction, priority, match, true) +func (c *OVNNbClient) DeleteACL(parentName, parentType, direction, priority, match string) error { + acl, err := c.GetACL(parentName, direction, priority, match, true) if err != nil { klog.Error(err) return err @@ -679,22 +680,22 @@ func (c *ovnNbClient) DeleteAcl(parentName, parentType, direction, priority, mat } // the acls column has a strong reference to the ACL table, so there is no need to delete the ACL - var removeAclOp []ovsdb.Operation + var removeACLOp []ovsdb.Operation if parentType == portGroupKey { // remove acl from port group - removeAclOp, err = c.portGroupUpdateAclOp(parentName, []string{acl.UUID}, ovsdb.MutateOperationDelete) + removeACLOp, err = c.portGroupUpdateACLOp(parentName, []string{acl.UUID}, ovsdb.MutateOperationDelete) if err != nil { klog.Error(err) return fmt.Errorf("generate operations for deleting acl from port group %s: %v", parentName, err) } } else { // remove acl from logical switch - removeAclOp, err = c.logicalSwitchUpdateAclOp(parentName, []string{acl.UUID}, ovsdb.MutateOperationDelete) + removeACLOp, err = c.logicalSwitchUpdateACLOp(parentName, []string{acl.UUID}, ovsdb.MutateOperationDelete) if err != nil { klog.Error(err) return fmt.Errorf("generate operations for deleting acl from logical switch %s: %v", parentName, err) } } - if err = c.Transact("acls-del", removeAclOp); err != nil { + if err = c.Transact("acls-del", removeACLOp); err != nil { klog.Error(err) return fmt.Errorf("del acls from type %s %s: %v", parentType, parentName, err) } @@ -702,9 +703,9 @@ func (c *ovnNbClient) DeleteAcl(parentName, parentType, direction, priority, mat return nil } -// GetAcl get acl by direction, priority and match, +// GetACL get acl by direction, priority and match, // be consistent with ovn-nbctl which direction, priority and match determine one acl in port group or logical switch -func (c *ovnNbClient) GetAcl(parent, direction, priority, match string, ignoreNotFound bool) (*ovnnb.ACL, error) { +func (c *OVNNbClient) GetACL(parent, direction, priority, match string, ignoreNotFound bool) (*ovnnb.ACL, error) { // this is necessary because may exist same direction, priority and match acl in different port group or logical switch if len(parent) == 0 { return nil, fmt.Errorf("the parent name is required") @@ -743,7 +744,7 @@ func (c *ovnNbClient) GetAcl(parent, direction, priority, match string, ignoreNo // result should include all acls when externalIDs is empty, // result should include all acls which externalIDs[key] is not empty when externalIDs[key] is "" // TODO: maybe add other filter conditions(priority or match) -func (c *ovnNbClient) ListAcls(direction string, externalIDs map[string]string) ([]ovnnb.ACL, error) { +func (c *OVNNbClient) ListAcls(direction string, externalIDs map[string]string) ([]ovnnb.ACL, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -757,13 +758,13 @@ func (c *ovnNbClient) ListAcls(direction string, externalIDs map[string]string) return aclList, nil } -func (c *ovnNbClient) AclExists(parent, direction, priority, match string) (bool, error) { - acl, err := c.GetAcl(parent, direction, priority, match, true) +func (c *OVNNbClient) ACLExists(parent, direction, priority, match string) (bool, error) { + acl, err := c.GetACL(parent, direction, priority, match, true) return acl != nil, err } -// newAcl return acl with basic information -func (c *ovnNbClient) newAcl(parent, direction, priority, match, action string, options ...func(acl *ovnnb.ACL)) (*ovnnb.ACL, error) { +// newACL return acl with basic information +func (c *OVNNbClient) newACL(parent, direction, priority, match, action string, options ...func(acl *ovnnb.ACL)) (*ovnnb.ACL, error) { if len(parent) == 0 { return nil, fmt.Errorf("the parent name is required") } @@ -772,7 +773,7 @@ func (c *ovnNbClient) newAcl(parent, direction, priority, match, action string, return nil, fmt.Errorf("acl 'direction %s' and 'priority %s' and 'match %s' and 'action %s' is required", direction, priority, match, action) } - exists, err := c.AclExists(parent, direction, priority, match) + exists, err := c.ACLExists(parent, direction, priority, match) if err != nil { klog.Error(err) return nil, fmt.Errorf("get parent %s acl: %v", parent, err) @@ -803,10 +804,10 @@ func (c *ovnNbClient) newAcl(parent, direction, priority, match, action string, return acl, nil } -// newAclWithoutCheck return acl with basic information without check acl exists, +// newACLWithoutCheck return acl with basic information without check acl exists, // this would cause duplicated acl, so don't use this function to create acl normally, // but maybe used for updating network policy acl -func (c *ovnNbClient) newAclWithoutCheck(parent, direction, priority, match, action string, options ...func(acl *ovnnb.ACL)) (*ovnnb.ACL, error) { +func (c *OVNNbClient) newACLWithoutCheck(parent, direction, priority, match, action string, options ...func(acl *ovnnb.ACL)) (*ovnnb.ACL, error) { if len(parent) == 0 { return nil, fmt.Errorf("the parent name is required") } @@ -836,7 +837,7 @@ func (c *ovnNbClient) newAclWithoutCheck(parent, direction, priority, match, act } // createSgRuleACL create security group rule acl -func (c *ovnNbClient) newSgRuleACL(sgName string, direction string, rule *kubeovnv1.SgRule) (*ovnnb.ACL, error) { +func (c *OVNNbClient) newSgRuleACL(sgName, direction string, rule *kubeovnv1.SgRule) (*ovnnb.ACL, error) { ipSuffix := "ip4" if rule.IPVersion == "ipv6" { ipSuffix = "ip6" @@ -854,16 +855,16 @@ func (c *ovnNbClient) newSgRuleACL(sgName string, direction string, rule *kubeov ipKey := ipSuffix + "." + srcOrDst /* match all traffic to or from pgName */ - allIpMatch := NewAndAclMatch( - NewAclMatch(portDirection, "==", "@"+pgName, ""), - NewAclMatch(ipSuffix, "", "", ""), + allIPMatch := NewAndACLMatch( + NewACLMatch(portDirection, "==", "@"+pgName, ""), + NewACLMatch(ipSuffix, "", "", ""), ) /* allow allowed ip traffic */ // type address - allowedIpMatch := NewAndAclMatch( - allIpMatch, - NewAclMatch(ipKey, "==", rule.RemoteAddress, ""), + allowedIPMatch := NewAndACLMatch( + allIPMatch, + NewACLMatch(ipKey, "==", rule.RemoteAddress, ""), ) // type securityGroup @@ -872,32 +873,32 @@ func (c *ovnNbClient) newSgRuleACL(sgName string, direction string, rule *kubeov remotePgName = GetSgV6AssociatedName(rule.RemoteSecurityGroup) } if rule.RemoteType == kubeovnv1.SgRemoteTypeSg { - allowedIpMatch = NewAndAclMatch( - allIpMatch, - NewAclMatch(ipKey, "==", "$"+remotePgName, ""), + allowedIPMatch = NewAndACLMatch( + allIPMatch, + NewACLMatch(ipKey, "==", "$"+remotePgName, ""), ) } /* allow layer 4 traffic */ // allow all layer 4 traffic - match := allowedIpMatch + match := allowedIPMatch switch rule.Protocol { case kubeovnv1.ProtocolICMP: - match = NewAndAclMatch( - allowedIpMatch, - NewAclMatch("icmp4", "", "", ""), + match = NewAndACLMatch( + allowedIPMatch, + NewACLMatch("icmp4", "", "", ""), ) if ipSuffix == "ip6" { - match = NewAndAclMatch( - allowedIpMatch, - NewAclMatch("icmp6", "", "", ""), + match = NewAndACLMatch( + allowedIPMatch, + NewACLMatch("icmp6", "", "", ""), ) } case kubeovnv1.ProtocolTCP, kubeovnv1.ProtocolUDP: - match = NewAndAclMatch( - allowedIpMatch, - NewAclMatch(string(rule.Protocol)+".dst", "<=", strconv.Itoa(rule.PortRangeMin), strconv.Itoa(rule.PortRangeMax)), + match = NewAndACLMatch( + allowedIPMatch, + NewACLMatch(string(rule.Protocol)+".dst", "<=", strconv.Itoa(rule.PortRangeMin), strconv.Itoa(rule.PortRangeMax)), ) } @@ -908,7 +909,7 @@ func (c *ovnNbClient) newSgRuleACL(sgName string, direction string, rule *kubeov highestPriority, _ := strconv.Atoi(util.SecurityGroupHighestPriority) - acl, err := c.newAcl(pgName, direction, strconv.Itoa(highestPriority-rule.Priority), match.String(), action) + acl, err := c.newACL(pgName, direction, strconv.Itoa(highestPriority-rule.Priority), match.String(), action) if err != nil { klog.Error(err) return nil, fmt.Errorf("new security group acl for port group %s: %v", pgName, err) @@ -917,7 +918,7 @@ func (c *ovnNbClient) newSgRuleACL(sgName string, direction string, rule *kubeov return acl, nil } -func newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, protocol, direction string, npp []netv1.NetworkPolicyPort, namedPortMap map[string]*util.NamedPortInfo) []string { +func newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, protocol, direction string, npp []netv1.NetworkPolicyPort, namedPortMap map[string]*util.NamedPortInfo) []string { ipSuffix := "ip4" if protocol == kubeovnv1.ProtocolIPv6 { ipSuffix = "ip6" @@ -933,22 +934,22 @@ func newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, protocol, direc ipKey := ipSuffix + "." + srcOrDst // match all traffic to or from pgName - allIpMatch := NewAndAclMatch( - NewAclMatch(portDirection, "==", "@"+pgName, ""), - NewAclMatch("ip", "", "", ""), + allIPMatch := NewAndACLMatch( + NewACLMatch(portDirection, "==", "@"+pgName, ""), + NewACLMatch("ip", "", "", ""), ) - allowedIpMatch := NewAndAclMatch( - allIpMatch, - NewAclMatch(ipKey, "==", "$"+asAllowName, ""), - NewAclMatch(ipKey, "!=", "$"+asExceptName, ""), + allowedIPMatch := NewAndACLMatch( + allIPMatch, + NewACLMatch(ipKey, "==", "$"+asAllowName, ""), + NewACLMatch(ipKey, "!=", "$"+asExceptName, ""), ) matches := make([]string, 0) // allow allowed ip traffic but except if len(npp) == 0 { - return []string{allowedIpMatch.String()} + return []string{allowedIPMatch.String()} } for _, port := range npp { @@ -956,9 +957,9 @@ func newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, protocol, direc // allow all tcp or udp traffic if port.Port == nil { - allLayer4Match := NewAndAclMatch( - allowedIpMatch, - NewAclMatch(protocol, "", "", ""), + allLayer4Match := NewAndACLMatch( + allowedIPMatch, + NewACLMatch(protocol, "", "", ""), ) matches = append(matches, allLayer4Match.String()) @@ -969,40 +970,37 @@ func newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, protocol, direc if port.EndPort == nil { tcpKey := protocol + ".dst" - var portId int32 = 0 - + var portID int32 if port.Port.Type == intstr.Int { - portId = port.Port.IntVal - } else { - if namedPortMap != nil { - _, ok := namedPortMap[port.Port.StrVal] - if !ok { - // for cyclonus network policy test case 'should allow ingress access on one named port' - // this case expect all-deny if no named port defined - klog.Errorf("no named port with name %s found ", port.Port.StrVal) - } else { - portId = namedPortMap[port.Port.StrVal].PortId - } + portID = port.Port.IntVal + } else if namedPortMap != nil { + _, ok := namedPortMap[port.Port.StrVal] + if !ok { + // for cyclonus network policy test case 'should allow ingress access on one named port' + // this case expect all-deny if no named port defined + klog.Errorf("no named port with name %s found ", port.Port.StrVal) + } else { + portID = namedPortMap[port.Port.StrVal].PortID } } - oneTcpMatch := NewAndAclMatch( - allowedIpMatch, - NewAclMatch(tcpKey, "==", fmt.Sprintf("%d", portId), ""), + oneTCPMatch := NewAndACLMatch( + allowedIPMatch, + NewACLMatch(tcpKey, "==", fmt.Sprintf("%d", portID), ""), ) - matches = append(matches, oneTcpMatch.String()) + matches = append(matches, oneTCPMatch.String()) continue } // allow several tcp or udp port traffic tcpKey := protocol + ".dst" - severalTcpMatch := NewAndAclMatch( - allowedIpMatch, - NewAclMatch(tcpKey, "<=", fmt.Sprintf("%d", port.Port.IntVal), fmt.Sprintf("%d", *port.EndPort)), + severalTCPMatch := NewAndACLMatch( + allowedIPMatch, + NewACLMatch(tcpKey, "<=", fmt.Sprintf("%d", port.Port.IntVal), fmt.Sprintf("%d", *port.EndPort)), ) - matches = append(matches, severalTcpMatch.String()) + matches = append(matches, severalTCPMatch.String()) } return matches @@ -1045,7 +1043,7 @@ func aclFilter(direction string, externalIDs map[string]string) func(acl *ovnnb. // CreateAcls return operations which create several acl once // parentType is 'ls' or 'pg' -func (c *ovnNbClient) CreateAclsOps(parentName, parentType string, acls ...*ovnnb.ACL) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) CreateAclsOps(parentName, parentType string, acls ...*ovnnb.ACL) ([]ovsdb.Operation, error) { if parentType != portGroupKey && parentType != logicalSwitchKey { return nil, fmt.Errorf("acl parent type must be '%s' or '%s'", portGroupKey, logicalSwitchKey) } @@ -1071,13 +1069,13 @@ func (c *ovnNbClient) CreateAclsOps(parentName, parentType string, acls ...*ovnn var aclAddOp []ovsdb.Operation if parentType == portGroupKey { // acl attach to port group - aclAddOp, err = c.portGroupUpdateAclOp(parentName, aclUUIDs, ovsdb.MutateOperationInsert) + aclAddOp, err = c.portGroupUpdateACLOp(parentName, aclUUIDs, ovsdb.MutateOperationInsert) if err != nil { klog.Error(err) return nil, fmt.Errorf("generate operations for adding acls to port group %s: %v", parentName, err) } } else { // acl attach to logical switch - aclAddOp, err = c.logicalSwitchUpdateAclOp(parentName, aclUUIDs, ovsdb.MutateOperationInsert) + aclAddOp, err = c.logicalSwitchUpdateACLOp(parentName, aclUUIDs, ovsdb.MutateOperationInsert) if err != nil { klog.Error(err) return nil, fmt.Errorf("generate operations for adding acls to logical switch %s: %v", parentName, err) @@ -1094,7 +1092,7 @@ func (c *ovnNbClient) CreateAclsOps(parentName, parentType string, acls ...*ovnn // DeleteAcls return operation which delete several acl once, // delete to-lport and from-lport direction acl when direction is empty, otherwise one-way // parentType is 'ls' or 'pg' -func (c *ovnNbClient) DeleteAclsOps(parentName, parentType string, direction string, externalIDs map[string]string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) DeleteAclsOps(parentName, parentType, direction string, externalIDs map[string]string) ([]ovsdb.Operation, error) { if externalIDs == nil { externalIDs = make(map[string]string) } @@ -1114,20 +1112,20 @@ func (c *ovnNbClient) DeleteAclsOps(parentName, parentType string, direction str } // the acls column has a strong reference to the ACL table, so there is no need to delete the ACL - var removeAclOp []ovsdb.Operation + var removeACLOp []ovsdb.Operation if parentType == portGroupKey { // remove acl from port group - removeAclOp, err = c.portGroupUpdateAclOp(parentName, aclUUIDs, ovsdb.MutateOperationDelete) + removeACLOp, err = c.portGroupUpdateACLOp(parentName, aclUUIDs, ovsdb.MutateOperationDelete) if err != nil { klog.Error(err) return nil, fmt.Errorf("generate operations for deleting acls from port group %s: %v", parentName, err) } } else { // remove acl from logical switch - removeAclOp, err = c.logicalSwitchUpdateAclOp(parentName, aclUUIDs, ovsdb.MutateOperationDelete) + removeACLOp, err = c.logicalSwitchUpdateACLOp(parentName, aclUUIDs, ovsdb.MutateOperationDelete) if err != nil { klog.Error(err) return nil, fmt.Errorf("generate operations for deleting acls from logical switch %s: %v", parentName, err) } } - return removeAclOp, nil + return removeACLOp, nil } diff --git a/pkg/ovs/ovn-nb-acl_test.go b/pkg/ovs/ovn-nb-acl_test.go index 069e43e4bc7..2f98d2378a6 100644 --- a/pkg/ovs/ovn-nb-acl_test.go +++ b/pkg/ovs/ovn-nb-acl_test.go @@ -20,7 +20,7 @@ import ( ) func mockNetworkPolicyPort() []netv1.NetworkPolicyPort { - protocolTcp := v1.ProtocolTCP + protocolTCP := v1.ProtocolTCP var endPort int32 = 20000 return []netv1.NetworkPolicyPort{ { @@ -28,7 +28,7 @@ func mockNetworkPolicyPort() []netv1.NetworkPolicyPort { Type: intstr.Int, IntVal: 12345, }, - Protocol: &protocolTcp, + Protocol: &protocolTCP, }, { Port: &intstr.IntOrString{ @@ -36,12 +36,12 @@ func mockNetworkPolicyPort() []netv1.NetworkPolicyPort { IntVal: 12346, }, EndPort: &endPort, - Protocol: &protocolTcp, + Protocol: &protocolTCP, }, } } -func newAcl(parentName, direction, priority, match, action string, options ...func(acl *ovnnb.ACL)) *ovnnb.ACL { +func newACL(parentName, direction, priority, match, action string, options ...func(acl *ovnnb.ACL)) *ovnnb.ACL { intPriority, _ := strconv.Atoi(priority) acl := &ovnnb.ACL{ @@ -62,7 +62,7 @@ func newAcl(parentName, direction, priority, match, action string, options ...fu return acl } -func (suite *OvnClientTestSuite) testUpdateIngressAclOps() { +func (suite *OvnClientTestSuite) testUpdateIngressACLOps() { t := suite.T() t.Parallel() @@ -90,13 +90,13 @@ func (suite *OvnClientTestSuite) testUpdateIngressAclOps() { npp := mockNetworkPolicyPort() - ops, err := ovnClient.UpdateIngressAclOps(pgName, asIngressName, asExceptName, protocol, npp, true, nil) + ops, err := ovnClient.UpdateIngressACLOps(pgName, asIngressName, asExceptName, protocol, npp, true, nil) require.NoError(t, err) require.Len(t, ops, 4) expect(ops[0].Row, "drop", ovnnb.ACLDirectionToLport, fmt.Sprintf("outport == @%s && ip4", pgName), util.IngressDefaultDrop) - matches := newNetworkPolicyAclMatch(pgName, asIngressName, asExceptName, protocol, ovnnb.ACLDirectionToLport, npp, nil) + matches := newNetworkPolicyACLMatch(pgName, asIngressName, asExceptName, protocol, ovnnb.ACLDirectionToLport, npp, nil) i := 1 for _, m := range matches { require.Equal(t, m, ops[i].Row["match"]) @@ -116,13 +116,13 @@ func (suite *OvnClientTestSuite) testUpdateIngressAclOps() { err := ovnClient.CreatePortGroup(pgName, nil) require.NoError(t, err) - ops, err := ovnClient.UpdateIngressAclOps(pgName, asIngressName, asExceptName, protocol, nil, true, nil) + ops, err := ovnClient.UpdateIngressACLOps(pgName, asIngressName, asExceptName, protocol, nil, true, nil) require.NoError(t, err) require.Len(t, ops, 3) expect(ops[0].Row, "drop", ovnnb.ACLDirectionToLport, fmt.Sprintf("outport == @%s && ip6", pgName), util.IngressDefaultDrop) - matches := newNetworkPolicyAclMatch(pgName, asIngressName, asExceptName, protocol, ovnnb.ACLDirectionToLport, nil, nil) + matches := newNetworkPolicyACLMatch(pgName, asIngressName, asExceptName, protocol, ovnnb.ACLDirectionToLport, nil, nil) i := 1 for _, m := range matches { require.Equal(t, m, ops[i].Row["match"]) @@ -132,7 +132,7 @@ func (suite *OvnClientTestSuite) testUpdateIngressAclOps() { }) } -func (suite *OvnClientTestSuite) testUpdateEgressAclOps() { +func (suite *OvnClientTestSuite) testUpdateEgressACLOps() { t := suite.T() t.Parallel() @@ -160,13 +160,13 @@ func (suite *OvnClientTestSuite) testUpdateEgressAclOps() { npp := mockNetworkPolicyPort() - ops, err := ovnClient.UpdateEgressAclOps(pgName, asEgressName, asExceptName, protocol, npp, true, nil) + ops, err := ovnClient.UpdateEgressACLOps(pgName, asEgressName, asExceptName, protocol, npp, true, nil) require.NoError(t, err) require.Len(t, ops, 4) expect(ops[0].Row, "drop", ovnnb.ACLDirectionFromLport, fmt.Sprintf("inport == @%s && ip4", pgName), util.EgressDefaultDrop) - matches := newNetworkPolicyAclMatch(pgName, asEgressName, asExceptName, protocol, ovnnb.ACLDirectionFromLport, npp, nil) + matches := newNetworkPolicyACLMatch(pgName, asEgressName, asExceptName, protocol, ovnnb.ACLDirectionFromLport, npp, nil) i := 1 for _, m := range matches { require.Equal(t, m, ops[i].Row["match"]) @@ -186,13 +186,13 @@ func (suite *OvnClientTestSuite) testUpdateEgressAclOps() { err := ovnClient.CreatePortGroup(pgName, nil) require.NoError(t, err) - ops, err := ovnClient.UpdateEgressAclOps(pgName, asEgressName, asExceptName, protocol, nil, true, nil) + ops, err := ovnClient.UpdateEgressACLOps(pgName, asEgressName, asExceptName, protocol, nil, true, nil) require.NoError(t, err) require.Len(t, ops, 3) expect(ops[0].Row, "drop", ovnnb.ACLDirectionFromLport, fmt.Sprintf("inport == @%s && ip6", pgName), util.EgressDefaultDrop) - matches := newNetworkPolicyAclMatch(pgName, asEgressName, asExceptName, protocol, ovnnb.ACLDirectionFromLport, nil, nil) + matches := newNetworkPolicyACLMatch(pgName, asEgressName, asExceptName, protocol, ovnnb.ACLDirectionFromLport, nil, nil) i := 1 for _, m := range matches { require.Equal(t, m, ops[i].Row["match"]) @@ -202,13 +202,13 @@ func (suite *OvnClientTestSuite) testUpdateEgressAclOps() { }) } -func (suite *OvnClientTestSuite) testCreateGatewayAcl() { +func (suite *OvnClientTestSuite) testCreateGatewayACL() { t := suite.T() t.Parallel() ovnClient := suite.ovnClient - checkAcl := func(parent interface{}, direction, priority, match string, options map[string]string) { + checkACL := func(parent interface{}, direction, priority, match string, options map[string]string) { pg, isPg := parent.(*ovnnb.PortGroup) var name string var acls []string @@ -222,16 +222,15 @@ func (suite *OvnClientTestSuite) testCreateGatewayAcl() { acls = ls.ACLs } - acl, err := ovnClient.GetAcl(name, direction, priority, match, false) + acl, err := ovnClient.GetACL(name, direction, priority, match, false) require.NoError(t, err) - expect := newAcl(name, direction, priority, match, ovnnb.ACLActionAllowStateless) + expect := newACL(name, direction, priority, match, ovnnb.ACLActionAllowStateless) expect.UUID = acl.UUID if len(options) != 0 { expect.Options = options } require.Equal(t, expect, acl) require.Contains(t, acls, acl.UUID) - } expect := func(parent interface{}, gateway string) { @@ -243,16 +242,16 @@ func (suite *OvnClientTestSuite) testCreateGatewayAcl() { } match := fmt.Sprintf("%s.src == %s", ipSuffix, gw) - checkAcl(parent, ovnnb.ACLDirectionToLport, util.IngressAllowPriority, match, nil) + checkACL(parent, ovnnb.ACLDirectionToLport, util.IngressAllowPriority, match, nil) match = fmt.Sprintf("%s.dst == %s", ipSuffix, gw) - checkAcl(parent, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, match, map[string]string{ + checkACL(parent, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, match, map[string]string{ "apply-after-lb": "true", }) if ipSuffix == "ip6" { match = "nd || nd_ra || nd_rs" - checkAcl(parent, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, match, map[string]string{ + checkACL(parent, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, match, map[string]string{ "apply-after-lb": "true", }) } @@ -271,7 +270,7 @@ func (suite *OvnClientTestSuite) testCreateGatewayAcl() { err := ovnClient.CreatePortGroup(pgName, nil) require.NoError(t, err) - err = ovnClient.CreateGatewayAcl("", pgName, gateway) + err = ovnClient.CreateGatewayACL("", pgName, gateway) require.NoError(t, err) pg, err := ovnClient.GetPortGroup(pgName, false) @@ -290,7 +289,7 @@ func (suite *OvnClientTestSuite) testCreateGatewayAcl() { err := ovnClient.CreatePortGroup(pgName, nil) require.NoError(t, err) - err = ovnClient.CreateGatewayAcl("", pgName, gateway) + err = ovnClient.CreateGatewayACL("", pgName, gateway) require.NoError(t, err) pg, err := ovnClient.GetPortGroup(pgName, false) @@ -309,7 +308,7 @@ func (suite *OvnClientTestSuite) testCreateGatewayAcl() { err := ovnClient.CreatePortGroup(pgName, nil) require.NoError(t, err) - err = ovnClient.CreateGatewayAcl("", pgName, gateway) + err = ovnClient.CreateGatewayACL("", pgName, gateway) require.NoError(t, err) pg, err := ovnClient.GetPortGroup(pgName, false) @@ -332,7 +331,7 @@ func (suite *OvnClientTestSuite) testCreateGatewayAcl() { err := ovnClient.CreateBareLogicalSwitch(lsName) require.NoError(t, err) - err = ovnClient.CreateGatewayAcl(lsName, "", gateway) + err = ovnClient.CreateGatewayACL(lsName, "", gateway) require.NoError(t, err) ls, err := ovnClient.GetLogicalSwitch(lsName, false) @@ -345,24 +344,24 @@ func (suite *OvnClientTestSuite) testCreateGatewayAcl() { t.Run("has no pg name and ls name", func(t *testing.T) { t.Parallel() - err := ovnClient.CreateGatewayAcl("", "", "") + err := ovnClient.CreateGatewayACL("", "", "") require.EqualError(t, err, "one of port group name and logical switch name must be specified") }) } -func (suite *OvnClientTestSuite) testCreateNodeAcl() { +func (suite *OvnClientTestSuite) testCreateNodeACL() { t := suite.T() t.Parallel() ovnClient := suite.ovnClient pgName := "test_create_node_acl_pg" - nodeIp := "192.168.20.3" - joinIp := "100.64.0.2,fd00:100:64::2" + nodeIP := "192.168.20.3" + joinIP := "100.64.0.2,fd00:100:64::2" - checkAcl := func(pg *ovnnb.PortGroup, direction, priority, match string, options map[string]string) { - acl, err := ovnClient.GetAcl(pg.Name, direction, priority, match, false) + checkACL := func(pg *ovnnb.PortGroup, direction, priority, match string, options map[string]string) { + acl, err := ovnClient.GetACL(pg.Name, direction, priority, match, false) require.NoError(t, err) - expect := newAcl(pg.Name, direction, priority, match, ovnnb.ACLActionAllowStateless) + expect := newACL(pg.Name, direction, priority, match, ovnnb.ACLActionAllowStateless) expect.UUID = acl.UUID if len(options) != 0 { expect.Options = options @@ -372,7 +371,7 @@ func (suite *OvnClientTestSuite) testCreateNodeAcl() { } expect := func(pg *ovnnb.PortGroup, gateway string) { - for _, ip := range strings.Split(nodeIp, ",") { + for _, ip := range strings.Split(nodeIP, ",") { protocol := util.CheckProtocol(ip) ipSuffix := "ip4" if protocol == kubeovnv1.ProtocolIPv6 { @@ -382,10 +381,10 @@ func (suite *OvnClientTestSuite) testCreateNodeAcl() { pgAs := fmt.Sprintf("%s_%s", pgName, ipSuffix) match := fmt.Sprintf("%s.src == %s && %s.dst == $%s", ipSuffix, ip, ipSuffix, pgAs) - checkAcl(pg, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, match, nil) + checkACL(pg, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, match, nil) match = fmt.Sprintf("%s.dst == %s && %s.src == $%s", ipSuffix, ip, ipSuffix, pgAs) - checkAcl(pg, ovnnb.ACLDirectionFromLport, util.NodeAllowPriority, match, map[string]string{ + checkACL(pg, ovnnb.ACLDirectionFromLport, util.NodeAllowPriority, match, map[string]string{ "apply-after-lb": "true", }) } @@ -394,17 +393,17 @@ func (suite *OvnClientTestSuite) testCreateNodeAcl() { err := ovnClient.CreatePortGroup(pgName, nil) require.NoError(t, err) - err = ovnClient.CreateNodeAcl(pgName, nodeIp, joinIp) + err = ovnClient.CreateNodeACL(pgName, nodeIP, joinIP) require.NoError(t, err) pg, err := ovnClient.GetPortGroup(pgName, false) require.NoError(t, err) require.Len(t, pg.ACLs, 2) - expect(pg, nodeIp) + expect(pg, nodeIP) } -func (suite *OvnClientTestSuite) testCreateSgDenyAllAcl() { +func (suite *OvnClientTestSuite) testCreateSgDenyAllACL() { t := suite.T() t.Parallel() @@ -415,7 +414,7 @@ func (suite *OvnClientTestSuite) testCreateSgDenyAllAcl() { err := ovnClient.CreatePortGroup(pgName, nil) require.NoError(t, err) - err = ovnClient.CreateSgDenyAllAcl(sgName) + err = ovnClient.CreateSgDenyAllACL(sgName) require.NoError(t, err) pg, err := ovnClient.GetPortGroup(pgName, false) @@ -423,21 +422,21 @@ func (suite *OvnClientTestSuite) testCreateSgDenyAllAcl() { // ingress acl match := fmt.Sprintf("outport == @%s && ip", pgName) - ingressAcl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupDropPriority, match, false) + ingressACL, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupDropPriority, match, false) require.NoError(t, err) - expect := newAcl(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupDropPriority, match, ovnnb.ACLActionDrop) - expect.UUID = ingressAcl.UUID - require.Equal(t, expect, ingressAcl) - require.Contains(t, pg.ACLs, ingressAcl.UUID) + expect := newACL(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupDropPriority, match, ovnnb.ACLActionDrop) + expect.UUID = ingressACL.UUID + require.Equal(t, expect, ingressACL) + require.Contains(t, pg.ACLs, ingressACL.UUID) // egress acl match = fmt.Sprintf("inport == @%s && ip", pgName) - egressAcl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupDropPriority, match, false) + egressACL, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupDropPriority, match, false) require.NoError(t, err) - expect = newAcl(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupDropPriority, match, ovnnb.ACLActionDrop) - expect.UUID = egressAcl.UUID - require.Equal(t, expect, egressAcl) - require.Contains(t, pg.ACLs, egressAcl.UUID) + expect = newACL(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupDropPriority, match, ovnnb.ACLActionDrop) + expect.UUID = egressACL.UUID + require.Equal(t, expect, egressACL) + require.Contains(t, pg.ACLs, egressACL.UUID) } func (suite *OvnClientTestSuite) testCreateSgBaseACL() { @@ -447,15 +446,15 @@ func (suite *OvnClientTestSuite) testCreateSgBaseACL() { ovnClient := suite.ovnClient expect := func(pg *ovnnb.PortGroup, match string) { - arpAcl, err := ovnClient.GetAcl(pg.Name, ovnnb.ACLDirectionToLport, util.SecurityGroupBasePriority, match, false) + arpACL, err := ovnClient.GetACL(pg.Name, ovnnb.ACLDirectionToLport, util.SecurityGroupBasePriority, match, false) require.NoError(t, err) - expect := newAcl(pg.Name, ovnnb.ACLDirectionToLport, util.SecurityGroupBasePriority, match, ovnnb.ACLActionAllowRelated, func(acl *ovnnb.ACL) { - acl.UUID = arpAcl.UUID + expect := newACL(pg.Name, ovnnb.ACLDirectionToLport, util.SecurityGroupBasePriority, match, ovnnb.ACLActionAllowRelated, func(acl *ovnnb.ACL) { + acl.UUID = arpACL.UUID }) - require.Equal(t, expect, arpAcl) - require.Contains(t, pg.ACLs, arpAcl.UUID) + require.Equal(t, expect, arpACL) + require.Contains(t, pg.ACLs, arpACL.UUID) } t.Run("create sg base ingress acl", func(t *testing.T) { @@ -527,10 +526,9 @@ func (suite *OvnClientTestSuite) testCreateSgBaseACL() { match = fmt.Sprintf("%s == @%s && udp.src == 546 && udp.dst == 547 && ip6", portDirection, pgName) expect(pg, match) }) - } -func (suite *OvnClientTestSuite) testUpdateSgAcl() { +func (suite *OvnClientTestSuite) testUpdateSgACL() { t := suite.T() t.Parallel() @@ -573,7 +571,7 @@ func (suite *OvnClientTestSuite) testUpdateSgAcl() { require.NoError(t, err) t.Run("update securityGroup ingress acl", func(t *testing.T) { - err = ovnClient.UpdateSgAcl(sg, ovnnb.ACLDirectionToLport) + err = ovnClient.UpdateSgACL(sg, ovnnb.ACLDirectionToLport) require.NoError(t, err) pg, err := ovnClient.GetPortGroup(pgName, false) @@ -581,34 +579,34 @@ func (suite *OvnClientTestSuite) testUpdateSgAcl() { // ipv4 acl match := fmt.Sprintf("outport == @%s && ip4 && ip4.src == $%s", pgName, v4AsName) - v4Acl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupAllowPriority, match, false) + v4Acl, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupAllowPriority, match, false) require.NoError(t, err) - expect := newAcl(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupAllowPriority, match, ovnnb.ACLActionAllowRelated) + expect := newACL(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupAllowPriority, match, ovnnb.ACLActionAllowRelated) expect.UUID = v4Acl.UUID require.Equal(t, expect, v4Acl) require.Contains(t, pg.ACLs, v4Acl.UUID) // ipv6 acl match = fmt.Sprintf("outport == @%s && ip6 && ip6.src == $%s", pgName, v6AsName) - v6Acl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupAllowPriority, match, false) + v6Acl, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupAllowPriority, match, false) require.NoError(t, err) - expect = newAcl(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupAllowPriority, match, ovnnb.ACLActionAllowRelated) + expect = newACL(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupAllowPriority, match, ovnnb.ACLActionAllowRelated) expect.UUID = v6Acl.UUID require.Equal(t, expect, v6Acl) require.Contains(t, pg.ACLs, v6Acl.UUID) // rule acl match = fmt.Sprintf("outport == @%s && ip4 && ip4.src == 0.0.0.0/0 && icmp4", pgName) - rulAcl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionToLport, "2288", match, false) + rulACL, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionToLport, "2288", match, false) require.NoError(t, err) - expect = newAcl(pgName, ovnnb.ACLDirectionToLport, "2288", match, ovnnb.ACLActionAllowRelated) - expect.UUID = rulAcl.UUID - require.Equal(t, expect, rulAcl) - require.Contains(t, pg.ACLs, rulAcl.UUID) + expect = newACL(pgName, ovnnb.ACLDirectionToLport, "2288", match, ovnnb.ACLActionAllowRelated) + expect.UUID = rulACL.UUID + require.Equal(t, expect, rulACL) + require.Contains(t, pg.ACLs, rulACL.UUID) }) t.Run("update securityGroup egress acl", func(t *testing.T) { - err = ovnClient.UpdateSgAcl(sg, ovnnb.ACLDirectionFromLport) + err = ovnClient.UpdateSgACL(sg, ovnnb.ACLDirectionFromLport) require.NoError(t, err) pg, err := ovnClient.GetPortGroup(pgName, false) @@ -616,41 +614,41 @@ func (suite *OvnClientTestSuite) testUpdateSgAcl() { // ipv4 acl match := fmt.Sprintf("inport == @%s && ip4 && ip4.dst == $%s", pgName, v4AsName) - v4Acl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupAllowPriority, match, false) + v4Acl, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupAllowPriority, match, false) require.NoError(t, err) - expect := newAcl(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupAllowPriority, match, ovnnb.ACLActionAllowRelated) + expect := newACL(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupAllowPriority, match, ovnnb.ACLActionAllowRelated) expect.UUID = v4Acl.UUID require.Equal(t, expect, v4Acl) require.Contains(t, pg.ACLs, v4Acl.UUID) // ipv6 acl match = fmt.Sprintf("inport == @%s && ip6 && ip6.dst == $%s", pgName, v6AsName) - v6Acl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupAllowPriority, match, false) + v6Acl, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupAllowPriority, match, false) require.NoError(t, err) - expect = newAcl(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupAllowPriority, match, ovnnb.ACLActionAllowRelated) + expect = newACL(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupAllowPriority, match, ovnnb.ACLActionAllowRelated) expect.UUID = v6Acl.UUID require.Equal(t, expect, v6Acl) require.Contains(t, pg.ACLs, v6Acl.UUID) // rule acl match = fmt.Sprintf("inport == @%s && ip4 && ip4.dst == 0.0.0.0/0", pgName) - rulAcl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionFromLport, "2290", match, false) + rulACL, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionFromLport, "2290", match, false) require.NoError(t, err) - expect = newAcl(pgName, ovnnb.ACLDirectionFromLport, "2290", match, ovnnb.ACLActionAllowRelated) - expect.UUID = rulAcl.UUID - require.Equal(t, expect, rulAcl) - require.Contains(t, pg.ACLs, rulAcl.UUID) + expect = newACL(pgName, ovnnb.ACLDirectionFromLport, "2290", match, ovnnb.ACLActionAllowRelated) + expect.UUID = rulACL.UUID + require.Equal(t, expect, rulACL) + require.Contains(t, pg.ACLs, rulACL.UUID) }) } -func (suite *OvnClientTestSuite) testUpdateLogicalSwitchAcl() { +func (suite *OvnClientTestSuite) testUpdateLogicalSwitchACL() { t := suite.T() t.Parallel() ovnClient := suite.ovnClient lsName := "test_update_acl_ls" - subnetAcls := []kubeovnv1.Acl{ + subnetAcls := []kubeovnv1.ACL{ { Direction: ovnnb.ACLDirectionToLport, Priority: 1111, @@ -668,16 +666,16 @@ func (suite *OvnClientTestSuite) testUpdateLogicalSwitchAcl() { err := ovnClient.CreateBareLogicalSwitch(lsName) require.NoError(t, err) - err = ovnClient.UpdateLogicalSwitchAcl(lsName, subnetAcls) + err = ovnClient.UpdateLogicalSwitchACL(lsName, subnetAcls) require.NoError(t, err) ls, err := ovnClient.GetLogicalSwitch(lsName, false) require.NoError(t, err) - for _, subnetAcl := range subnetAcls { - acl, err := ovnClient.GetAcl(lsName, subnetAcl.Direction, strconv.Itoa(subnetAcl.Priority), subnetAcl.Match, false) + for _, subnetACL := range subnetAcls { + acl, err := ovnClient.GetACL(lsName, subnetACL.Direction, strconv.Itoa(subnetACL.Priority), subnetACL.Match, false) require.NoError(t, err) - expect := newAcl(lsName, subnetAcl.Direction, strconv.Itoa(subnetAcl.Priority), subnetAcl.Match, subnetAcl.Action) + expect := newACL(lsName, subnetACL.Direction, strconv.Itoa(subnetACL.Priority), subnetACL.Match, subnetACL.Action) expect.UUID = acl.UUID expect.ExternalIDs["subnet"] = lsName require.Equal(t, expect, acl) @@ -685,7 +683,7 @@ func (suite *OvnClientTestSuite) testUpdateLogicalSwitchAcl() { } } -func (suite *OvnClientTestSuite) testSetAclLog() { +func (suite *OvnClientTestSuite) testSetACLLog() { t := suite.T() t.Parallel() @@ -697,7 +695,7 @@ func (suite *OvnClientTestSuite) testSetAclLog() { t.Run("set ingress acl log to false", func(t *testing.T) { match := fmt.Sprintf("outport == @%s && ip4", pgName) - acl := newAcl(pgName, ovnnb.ACLDirectionToLport, util.IngressDefaultDrop, match, ovnnb.ACLActionDrop, func(acl *ovnnb.ACL) { + acl := newACL(pgName, ovnnb.ACLDirectionToLport, util.IngressDefaultDrop, match, ovnnb.ACLActionDrop, func(acl *ovnnb.ACL) { acl.Name = &pgName acl.Log = true acl.Severity = &ovnnb.ACLSeverityWarning @@ -706,17 +704,17 @@ func (suite *OvnClientTestSuite) testSetAclLog() { err = ovnClient.CreateAcls(pgName, portGroupKey, acl) require.NoError(t, err) - err = ovnClient.SetAclLog(pgName, kubeovnv1.ProtocolIPv4, false, true) + err = ovnClient.SetACLLog(pgName, kubeovnv1.ProtocolIPv4, false, true) require.NoError(t, err) - acl, err = ovnClient.GetAcl(pgName, ovnnb.ACLDirectionToLport, util.IngressDefaultDrop, match, false) + acl, err = ovnClient.GetACL(pgName, ovnnb.ACLDirectionToLport, util.IngressDefaultDrop, match, false) require.NoError(t, err) require.False(t, acl.Log) }) t.Run("set egress acl log to false", func(t *testing.T) { match := fmt.Sprintf("inport == @%s && ip4", pgName) - acl := newAcl(pgName, ovnnb.ACLDirectionFromLport, util.IngressDefaultDrop, match, ovnnb.ACLActionDrop, func(acl *ovnnb.ACL) { + acl := newACL(pgName, ovnnb.ACLDirectionFromLport, util.IngressDefaultDrop, match, ovnnb.ACLActionDrop, func(acl *ovnnb.ACL) { acl.Name = &pgName acl.Log = false acl.Severity = &ovnnb.ACLSeverityWarning @@ -725,14 +723,13 @@ func (suite *OvnClientTestSuite) testSetAclLog() { err = ovnClient.CreateAcls(pgName, portGroupKey, acl) require.NoError(t, err) - err = ovnClient.SetAclLog(pgName, kubeovnv1.ProtocolIPv4, true, false) + err = ovnClient.SetACLLog(pgName, kubeovnv1.ProtocolIPv4, true, false) require.NoError(t, err) - acl, err = ovnClient.GetAcl(pgName, ovnnb.ACLDirectionFromLport, util.IngressDefaultDrop, match, false) + acl, err = ovnClient.GetACL(pgName, ovnnb.ACLDirectionFromLport, util.IngressDefaultDrop, match, false) require.NoError(t, err) require.True(t, acl.Log) }) - } func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { @@ -767,7 +764,7 @@ func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { // default drop acl match := "ip" - acl, err := ovnClient.GetAcl(lsName, direction, util.DefaultDropPriority, match, false) + acl, err := ovnClient.GetACL(lsName, direction, util.DefaultDropPriority, match, false) require.NoError(t, err) require.Contains(t, ls.ACLs, acl.UUID) @@ -780,7 +777,7 @@ func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { match = fmt.Sprintf(`ip6.src == %s && ip6.dst == %s`, cidr, cidr) } - acl, err = ovnClient.GetAcl(lsName, direction, util.SubnetAllowPriority, match, false) + acl, err = ovnClient.GetACL(lsName, direction, util.SubnetAllowPriority, match, false) require.NoError(t, err) require.Contains(t, ls.ACLs, acl.UUID) @@ -798,7 +795,7 @@ func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { match = fmt.Sprintf("(ip6.src == %s && ip6.dst == %s) || (ip6.src == %s && ip6.dst == %s)", cidr, subnet, subnet, cidr) } - acl, err = ovnClient.GetAcl(lsName, direction, util.SubnetAllowPriority, match, false) + acl, err = ovnClient.GetACL(lsName, direction, util.SubnetAllowPriority, match, false) require.NoError(t, err) require.Contains(t, ls.ACLs, acl.UUID) } @@ -813,7 +810,7 @@ func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { match = fmt.Sprintf(`ip6.src == %s`, cidr) } - acl, err = ovnClient.GetAcl(lsName, direction, util.NodeAllowPriority, match, false) + acl, err = ovnClient.GetACL(lsName, direction, util.NodeAllowPriority, match, false) require.NoError(t, err) require.Contains(t, ls.ACLs, acl.UUID) } @@ -836,7 +833,7 @@ func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { // default drop acl match := "ip" - acl, err := ovnClient.GetAcl(lsName, direction, util.DefaultDropPriority, match, false) + acl, err := ovnClient.GetACL(lsName, direction, util.DefaultDropPriority, match, false) require.NoError(t, err) require.Contains(t, ls.ACLs, acl.UUID) @@ -849,7 +846,7 @@ func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { match = fmt.Sprintf(`ip6.src == %s && ip6.dst == %s`, cidr, cidr) } - acl, err = ovnClient.GetAcl(lsName, direction, util.SubnetAllowPriority, match, false) + acl, err = ovnClient.GetACL(lsName, direction, util.SubnetAllowPriority, match, false) require.NoError(t, err) require.Contains(t, ls.ACLs, acl.UUID) @@ -867,7 +864,7 @@ func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { match = fmt.Sprintf("(ip6.src == %s && ip6.dst == %s) || (ip6.src == %s && ip6.dst == %s)", cidr, subnet, subnet, cidr) } - acl, err = ovnClient.GetAcl(lsName, direction, util.SubnetAllowPriority, match, false) + acl, err = ovnClient.GetACL(lsName, direction, util.SubnetAllowPriority, match, false) require.NoError(t, err) require.Contains(t, ls.ACLs, acl.UUID) } @@ -882,7 +879,7 @@ func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { match = fmt.Sprintf(`ip6.src == %s`, cidr) } - acl, err = ovnClient.GetAcl(lsName, direction, util.NodeAllowPriority, match, false) + acl, err = ovnClient.GetACL(lsName, direction, util.NodeAllowPriority, match, false) if protocol == kubeovnv1.ProtocolIPv4 { require.NoError(t, err) require.Contains(t, ls.ACLs, acl.UUID) @@ -893,7 +890,7 @@ func (suite *OvnClientTestSuite) testSetLogicalSwitchPrivate() { }) } -func (suite *OvnClientTestSuite) test_newSgRuleACL() { +func (suite *OvnClientTestSuite) testNewSgRuleACL() { t := suite.T() t.Parallel() @@ -919,7 +916,7 @@ func (suite *OvnClientTestSuite) test_newSgRuleACL() { require.NoError(t, err) match := fmt.Sprintf("outport == @%s && ip4 && ip4.src == $%s && icmp4", pgName, GetSgV4AssociatedName(sgRule.RemoteSecurityGroup)) - expect := newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + expect := newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) expect.UUID = acl.UUID require.Equal(t, expect, acl) }) @@ -941,7 +938,7 @@ func (suite *OvnClientTestSuite) test_newSgRuleACL() { require.NoError(t, err) match := fmt.Sprintf("outport == @%s && ip4 && ip4.src == %s && icmp4", pgName, sgRule.RemoteAddress) - expect := newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + expect := newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) expect.UUID = acl.UUID require.Equal(t, expect, acl) }) @@ -963,7 +960,7 @@ func (suite *OvnClientTestSuite) test_newSgRuleACL() { require.NoError(t, err) match := fmt.Sprintf("outport == @%s && ip6 && ip6.src == %s && icmp6", pgName, sgRule.RemoteAddress) - expect := newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + expect := newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) expect.UUID = acl.UUID require.Equal(t, expect, acl) }) @@ -985,7 +982,7 @@ func (suite *OvnClientTestSuite) test_newSgRuleACL() { require.NoError(t, err) match := fmt.Sprintf("inport == @%s && ip4 && ip4.dst == %s && icmp4", pgName, sgRule.RemoteAddress) - expect := newAcl(pgName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) + expect := newACL(pgName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) expect.UUID = acl.UUID require.Equal(t, expect, acl) }) @@ -1007,7 +1004,7 @@ func (suite *OvnClientTestSuite) test_newSgRuleACL() { require.NoError(t, err) match := fmt.Sprintf("outport == @%s && ip4 && ip4.src == %s && icmp4", pgName, sgRule.RemoteAddress) - expect := newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionDrop) + expect := newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionDrop) expect.UUID = acl.UUID require.Equal(t, expect, acl) }) @@ -1031,7 +1028,7 @@ func (suite *OvnClientTestSuite) test_newSgRuleACL() { require.NoError(t, err) match := fmt.Sprintf("outport == @%s && ip4 && ip4.src == %s && %d <= tcp.dst <= %d", pgName, sgRule.RemoteAddress, sgRule.PortRangeMin, sgRule.PortRangeMax) - expect := newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + expect := newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) expect.UUID = acl.UUID require.Equal(t, expect, acl) }) @@ -1054,7 +1051,7 @@ func (suite *OvnClientTestSuite) testCreateAcls() { for i := 0; i < 3; i++ { match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1067,7 +1064,7 @@ func (suite *OvnClientTestSuite) testCreateAcls() { for i := 0; i < 3; i++ { match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, false) + acl, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionToLport, priority, match, false) require.NoError(t, err) require.Equal(t, match, acl.Match) @@ -1082,7 +1079,7 @@ func (suite *OvnClientTestSuite) testCreateAcls() { for i := 0; i < 3; i++ { match := fmt.Sprintf("%s && udp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1095,7 +1092,7 @@ func (suite *OvnClientTestSuite) testCreateAcls() { for i := 0; i < 3; i++ { match := fmt.Sprintf("%s && udp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.GetAcl(lsName, ovnnb.ACLDirectionToLport, priority, match, false) + acl, err := ovnClient.GetACL(lsName, ovnnb.ACLDirectionToLport, priority, match, false) require.NoError(t, err) require.Equal(t, match, acl.Match) @@ -1135,7 +1132,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { // to-lport for i := 0; i < 2; i++ { match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1143,7 +1140,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { // from-lport for i := 0; i < 3; i++ { match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(pgName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(pgName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1171,7 +1168,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { // to-lport for i := 0; i < 2; i++ { match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1179,7 +1176,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { // from-lport for i := 0; i < 3; i++ { match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(pgName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(pgName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1216,7 +1213,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { // to-lport for i := 0; i < 2; i++ { match := fmt.Sprintf("%s && udp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1224,7 +1221,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { // from-lport for i := 0; i < 3; i++ { match := fmt.Sprintf("%s && udp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(lsName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(lsName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1252,7 +1249,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { // to-lport for i := 0; i < 2; i++ { match := fmt.Sprintf("%s && udp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1260,7 +1257,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { // from-lport for i := 0; i < 3; i++ { match := fmt.Sprintf("%s && udp.dst == %d", matchPrefix, basePort+i) - acl, err := ovnClient.newAcl(lsName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(lsName, ovnnb.ACLDirectionFromLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) acls = append(acls, acl) } @@ -1297,7 +1294,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { // to-lport match := fmt.Sprintf("%s && udp.dst == %d", matchPrefix, basePort) - acl, err := ovnClient.newAcl(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated, func(acl *ovnnb.ACL) { + acl, err := ovnClient.newACL(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated, func(acl *ovnnb.ACL) { if acl.ExternalIDs == nil { acl.ExternalIDs = make(map[string]string) } @@ -1313,8 +1310,8 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { require.NoError(t, err) require.Len(t, ls.ACLs, 1) - newAcl := &ovnnb.ACL{UUID: ls.ACLs[0]} - err = ovnClient.GetEntityInfo(newAcl) + newACL := &ovnnb.ACL{UUID: ls.ACLs[0]} + err = ovnClient.GetEntityInfo(newACL) require.NoError(t, err) /* delete to-lport direction acl */ @@ -1327,7 +1324,7 @@ func (suite *OvnClientTestSuite) testDeleteAcls() { }) } -func (suite *OvnClientTestSuite) testDeleteAcl() { +func (suite *OvnClientTestSuite) testDeleteACL() { t := suite.T() t.Parallel() @@ -1347,7 +1344,7 @@ func (suite *OvnClientTestSuite) testDeleteAcl() { basePort := 5601 match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort) - acl, err := ovnClient.newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) err = ovnClient.CreateAcls(pgName, portGroupKey, acl) @@ -1357,7 +1354,7 @@ func (suite *OvnClientTestSuite) testDeleteAcl() { require.NoError(t, err) require.Len(t, pg.ACLs, 1) - err = ovnClient.DeleteAcl(pgName, portGroupKey, ovnnb.ACLDirectionToLport, priority, match) + err = ovnClient.DeleteACL(pgName, portGroupKey, ovnnb.ACLDirectionToLport, priority, match) require.NoError(t, err) pg, err = ovnClient.GetPortGroup(pgName, false) @@ -1370,7 +1367,7 @@ func (suite *OvnClientTestSuite) testDeleteAcl() { basePort := 5601 match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort) - acl, err := ovnClient.newAcl(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(lsName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) err = ovnClient.CreateAcls(lsName, logicalSwitchKey, acl) @@ -1380,7 +1377,7 @@ func (suite *OvnClientTestSuite) testDeleteAcl() { require.NoError(t, err) require.Len(t, ls.ACLs, 1) - err = ovnClient.DeleteAcl(lsName, logicalSwitchKey, ovnnb.ACLDirectionToLport, priority, match) + err = ovnClient.DeleteACL(lsName, logicalSwitchKey, ovnnb.ACLDirectionToLport, priority, match) require.NoError(t, err) ls, err = ovnClient.GetLogicalSwitch(lsName, false) @@ -1389,7 +1386,7 @@ func (suite *OvnClientTestSuite) testDeleteAcl() { }) } -func (suite *OvnClientTestSuite) testGetAcl() { +func (suite *OvnClientTestSuite) testGetACL() { t := suite.T() t.Parallel() @@ -1398,12 +1395,12 @@ func (suite *OvnClientTestSuite) testGetAcl() { priority := "2000" match := "ip4.dst == 100.64.0.0/16" - err := ovnClient.CreateBareAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + err := ovnClient.CreateBareACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) t.Run("direction, priority and match are same", func(t *testing.T) { t.Parallel() - acl, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, false) + acl, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionToLport, priority, match, false) require.NoError(t, err) require.Equal(t, ovnnb.ACLDirectionToLport, acl.Direction) require.Equal(t, 2000, acl.Priority) @@ -1414,27 +1411,27 @@ func (suite *OvnClientTestSuite) testGetAcl() { t.Run("direction, priority and match are not all same", func(t *testing.T) { t.Parallel() - _, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionFromLport, priority, match, false) + _, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionFromLport, priority, match, false) require.ErrorContains(t, err, "not found acl") - _, err = ovnClient.GetAcl(pgName, ovnnb.ACLDirectionToLport, "1010", match, false) + _, err = ovnClient.GetACL(pgName, ovnnb.ACLDirectionToLport, "1010", match, false) require.ErrorContains(t, err, "not found acl") - _, err = ovnClient.GetAcl(pgName, ovnnb.ACLDirectionToLport, priority, match+" && tcp", false) + _, err = ovnClient.GetACL(pgName, ovnnb.ACLDirectionToLport, priority, match+" && tcp", false) require.ErrorContains(t, err, "not found acl") }) t.Run("should no err when direction, priority and match are not all same but ignoreNotFound=true", func(t *testing.T) { t.Parallel() - _, err := ovnClient.GetAcl(pgName, ovnnb.ACLDirectionFromLport, priority, match, true) + _, err := ovnClient.GetACL(pgName, ovnnb.ACLDirectionFromLport, priority, match, true) require.NoError(t, err) }) t.Run("no acl belongs to parent exist", func(t *testing.T) { t.Parallel() - _, err := ovnClient.GetAcl(pgName+"_1", ovnnb.ACLDirectionFromLport, priority, match, false) + _, err := ovnClient.GetACL(pgName+"_1", ovnnb.ACLDirectionFromLport, priority, match, false) require.ErrorContains(t, err, "not found acl") }) } @@ -1451,14 +1448,14 @@ func (suite *OvnClientTestSuite) testListAcls() { // create two to-lport acl for i := 0; i < 2; i++ { match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort+i) - err := ovnClient.CreateBareAcl(pgName, ovnnb.ACLDirectionToLport, "9999", match, ovnnb.ACLActionAllowRelated) + err := ovnClient.CreateBareACL(pgName, ovnnb.ACLDirectionToLport, "9999", match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) } // create two from-lport acl for i := 0; i < 3; i++ { match := fmt.Sprintf("%s && tcp.dst == %d", matchPrefix, basePort+i) - err := ovnClient.CreateBareAcl(pgName, ovnnb.ACLDirectionFromLport, "9999", match, ovnnb.ACLActionAllowRelated) + err := ovnClient.CreateBareACL(pgName, ovnnb.ACLDirectionFromLport, "9999", match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) } @@ -1474,7 +1471,7 @@ func (suite *OvnClientTestSuite) testListAcls() { require.Equal(t, count, 5) } -func (suite *OvnClientTestSuite) test_newAcl() { +func (suite *OvnClientTestSuite) testNewACL() { t := suite.T() t.Parallel() @@ -1501,13 +1498,13 @@ func (suite *OvnClientTestSuite) test_newAcl() { Severity: &ovnnb.ACLSeverityWarning, } - acl, err := ovnClient.newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated, options) + acl, err := ovnClient.newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated, options) require.NoError(t, err) expect.UUID = acl.UUID require.Equal(t, expect, acl) } -func (suite *OvnClientTestSuite) testnewNetworkPolicyAclMatch() { +func (suite *OvnClientTestSuite) testnewNetworkPolicyACLMatch() { t := suite.T() t.Parallel() @@ -1519,7 +1516,7 @@ func (suite *OvnClientTestSuite) testnewNetworkPolicyAclMatch() { t.Parallel() npp := mockNetworkPolicyPort() - matches := newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, nil) + matches := newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, nil) require.ElementsMatch(t, []string{ fmt.Sprintf("outport == @%s && ip && ip4.src == $%s && ip4.src != $%s && tcp.dst == %d", pgName, asAllowName, asExceptName, npp[0].Port.IntVal), fmt.Sprintf("outport == @%s && ip && ip4.src == $%s && ip4.src != $%s && %d <= tcp.dst <= %d", pgName, asAllowName, asExceptName, npp[1].Port.IntVal, *npp[1].EndPort), @@ -1531,7 +1528,7 @@ func (suite *OvnClientTestSuite) testnewNetworkPolicyAclMatch() { npp := mockNetworkPolicyPort() - matches := newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionFromLport, npp, nil) + matches := newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionFromLport, npp, nil) require.ElementsMatch(t, []string{ fmt.Sprintf("inport == @%s && ip && ip4.dst == $%s && ip4.dst != $%s && tcp.dst == %d", pgName, asAllowName, asExceptName, npp[0].Port.IntVal), fmt.Sprintf("inport == @%s && ip && ip4.dst == $%s && ip4.dst != $%s && %d <= tcp.dst <= %d", pgName, asAllowName, asExceptName, npp[1].Port.IntVal, *npp[1].EndPort), @@ -1541,7 +1538,7 @@ func (suite *OvnClientTestSuite) testnewNetworkPolicyAclMatch() { t.Run("network policy port is nil", func(t *testing.T) { t.Parallel() - matches := newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, nil, nil) + matches := newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, nil, nil) require.ElementsMatch(t, []string{ fmt.Sprintf("outport == @%s && ip && ip4.src == $%s && ip4.src != $%s", pgName, asAllowName, asExceptName), }, matches) @@ -1553,7 +1550,7 @@ func (suite *OvnClientTestSuite) testnewNetworkPolicyAclMatch() { npp := mockNetworkPolicyPort() npp[1].Port = nil - matches := newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, nil) + matches := newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, nil) require.ElementsMatch(t, []string{ fmt.Sprintf("outport == @%s && ip && ip4.src == $%s && ip4.src != $%s && tcp.dst == %d", pgName, asAllowName, asExceptName, npp[0].Port.IntVal), fmt.Sprintf("outport == @%s && ip && ip4.src == $%s && ip4.src != $%s && tcp", pgName, asAllowName, asExceptName), @@ -1568,7 +1565,7 @@ func (suite *OvnClientTestSuite) testnewNetworkPolicyAclMatch() { npp := mockNetworkPolicyPort() npp[1].EndPort = nil - matches := newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, nil) + matches := newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, nil) require.ElementsMatch(t, []string{ fmt.Sprintf("outport == @%s && ip && ip4.src == $%s && ip4.src != $%s && tcp.dst == %d", pgName, asAllowName, asExceptName, npp[0].Port.IntVal), fmt.Sprintf("outport == @%s && ip && ip4.src == $%s && ip4.src != $%s && tcp.dst == %d", pgName, asAllowName, asExceptName, npp[1].Port.IntVal), @@ -1577,23 +1574,23 @@ func (suite *OvnClientTestSuite) testnewNetworkPolicyAclMatch() { t.Run("port type is String", func(t *testing.T) { t.Parallel() - protocolTcp := v1.ProtocolTCP + protocolTCP := v1.ProtocolTCP npp := []netv1.NetworkPolicyPort{ { Port: &intstr.IntOrString{ Type: intstr.String, StrVal: "test-pod-port", }, - Protocol: &protocolTcp, + Protocol: &protocolTCP, }, } namedPortMap := map[string]*util.NamedPortInfo{ "test-pod-port": { - PortId: 13455, + PortID: 13455, }, } - matches := newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, namedPortMap) + matches := newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, namedPortMap) require.ElementsMatch(t, []string{ fmt.Sprintf("outport == @%s && ip && ip4.src == $%s && ip4.src != $%s && tcp.dst == %d", pgName, asAllowName, asExceptName, 13455), }, matches) @@ -1601,23 +1598,23 @@ func (suite *OvnClientTestSuite) testnewNetworkPolicyAclMatch() { t.Run("port type is String and not find named port", func(t *testing.T) { t.Parallel() - protocolTcp := v1.ProtocolTCP + protocolTCP := v1.ProtocolTCP npp := []netv1.NetworkPolicyPort{ { Port: &intstr.IntOrString{ Type: intstr.String, StrVal: "test-pod-port-x", }, - Protocol: &protocolTcp, + Protocol: &protocolTCP, }, } namedPortMap := map[string]*util.NamedPortInfo{ "test-pod-port": { - PortId: 13455, + PortID: 13455, }, } - matches := newNetworkPolicyAclMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, namedPortMap) + matches := newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, kubeovnv1.ProtocolIPv4, ovnnb.ACLDirectionToLport, npp, namedPortMap) require.ElementsMatch(t, []string{ fmt.Sprintf("outport == @%s && ip && ip4.src == $%s && ip4.src != $%s && tcp.dst == %d", pgName, asAllowName, asExceptName, 0), }, matches) @@ -1625,7 +1622,7 @@ func (suite *OvnClientTestSuite) testnewNetworkPolicyAclMatch() { }) } -func (suite *OvnClientTestSuite) test_aclFilter() { +func (suite *OvnClientTestSuite) testACLFilter() { t := suite.T() t.Parallel() @@ -1639,26 +1636,26 @@ func (suite *OvnClientTestSuite) test_aclFilter() { match := "outport == @ovn.sg.test_list_acl_pg && ip" // create two to-lport acl for i := 0; i < 2; i++ { - acl := newAcl(pgName, ovnnb.ACLDirectionToLport, "9999", match, ovnnb.ACLActionAllowRelated) + acl := newACL(pgName, ovnnb.ACLDirectionToLport, "9999", match, ovnnb.ACLActionAllowRelated) acls = append(acls, acl) } // create two to-lport acl without acl parent key for i := 0; i < 2; i++ { - acl := newAcl(pgName, ovnnb.ACLDirectionToLport, "9999", match, ovnnb.ACLActionAllowRelated) + acl := newACL(pgName, ovnnb.ACLDirectionToLport, "9999", match, ovnnb.ACLActionAllowRelated) acl.ExternalIDs = nil acls = append(acls, acl) } // create two from-lport acl for i := 0; i < 3; i++ { - acl := newAcl(pgName, ovnnb.ACLDirectionFromLport, "9999", match, ovnnb.ACLActionAllowRelated) + acl := newACL(pgName, ovnnb.ACLDirectionFromLport, "9999", match, ovnnb.ACLActionAllowRelated) acls = append(acls, acl) } // create four from-lport acl with other acl parent key for i := 0; i < 4; i++ { - acl := newAcl(pgName, ovnnb.ACLDirectionFromLport, "9999", match, ovnnb.ACLActionAllowRelated) + acl := newACL(pgName, ovnnb.ACLDirectionFromLport, "9999", match, ovnnb.ACLActionAllowRelated) acl.ExternalIDs[aclParentKey] = pgName + "-test" acls = append(acls, acl) } @@ -1728,7 +1725,7 @@ func (suite *OvnClientTestSuite) test_aclFilter() { t.Parallel() match := "outport == @ovn.sg.test_filter_acl_pg && ip" - acl := newAcl(pgName, ovnnb.ACLDirectionToLport, "9999", match, ovnnb.ACLActionAllowRelated) + acl := newACL(pgName, ovnnb.ACLDirectionToLport, "9999", match, ovnnb.ACLActionAllowRelated) filterFunc := aclFilter("", map[string]string{ aclParentKey: pgName, diff --git a/pkg/ovs/ovn-nb-address_set.go b/pkg/ovs/ovn-nb-address_set.go index afbf3076f3a..941fab810a5 100644 --- a/pkg/ovs/ovn-nb-address_set.go +++ b/pkg/ovs/ovn-nb-address_set.go @@ -14,7 +14,7 @@ import ( ) // CreateAddressSet create address set with external ids -func (c *ovnNbClient) CreateAddressSet(asName string, externalIDs map[string]string) error { +func (c *OVNNbClient) CreateAddressSet(asName string, externalIDs map[string]string) error { // ovn acl doesn't support address_set name with '-' if matched := matchAddressSetName(asName); !matched { return fmt.Errorf("address set %s must match `[a-zA-Z_.][a-zA-Z_.0-9]*`", asName) @@ -51,7 +51,7 @@ func (c *ovnNbClient) CreateAddressSet(asName string, externalIDs map[string]str // AddressSetUpdateAddress update addresses, // clear addresses when addresses is empty -func (c *ovnNbClient) AddressSetUpdateAddress(asName string, addresses ...string) error { +func (c *OVNNbClient) AddressSetUpdateAddress(asName string, addresses ...string) error { as, err := c.GetAddressSet(asName, false) if err != nil { klog.Error(err) @@ -84,7 +84,7 @@ func (c *ovnNbClient) AddressSetUpdateAddress(asName string, addresses ...string } // UpdateAddressSet update address set -func (c *ovnNbClient) UpdateAddressSet(as *ovnnb.AddressSet, fields ...interface{}) error { +func (c *OVNNbClient) UpdateAddressSet(as *ovnnb.AddressSet, fields ...interface{}) error { if as == nil { return fmt.Errorf("address_set is nil") } @@ -103,7 +103,7 @@ func (c *ovnNbClient) UpdateAddressSet(as *ovnnb.AddressSet, fields ...interface return nil } -func (c *ovnNbClient) DeleteAddressSet(asName string) error { +func (c *OVNNbClient) DeleteAddressSet(asName string) error { as, err := c.GetAddressSet(asName, true) if err != nil { klog.Error(err) @@ -129,7 +129,7 @@ func (c *ovnNbClient) DeleteAddressSet(asName string) error { } // DeleteAddressSets delete several address set once -func (c *ovnNbClient) DeleteAddressSets(externalIDs map[string]string) error { +func (c *OVNNbClient) DeleteAddressSets(externalIDs map[string]string) error { // it's dangerous when externalIDs is empty, it will delete all address set if len(externalIDs) == 0 { return nil @@ -149,7 +149,7 @@ func (c *ovnNbClient) DeleteAddressSets(externalIDs map[string]string) error { } // GetAddressSet get address set by name -func (c *ovnNbClient) GetAddressSet(asName string, ignoreNotFound bool) (*ovnnb.AddressSet, error) { +func (c *OVNNbClient) GetAddressSet(asName string, ignoreNotFound bool) (*ovnnb.AddressSet, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -165,13 +165,13 @@ func (c *ovnNbClient) GetAddressSet(asName string, ignoreNotFound bool) (*ovnnb. return as, nil } -func (c *ovnNbClient) AddressSetExists(name string) (bool, error) { +func (c *OVNNbClient) AddressSetExists(name string) (bool, error) { as, err := c.GetAddressSet(name, true) return as != nil, err } // ListAddressSets list address set by external_ids -func (c *ovnNbClient) ListAddressSets(externalIDs map[string]string) ([]ovnnb.AddressSet, error) { +func (c *OVNNbClient) ListAddressSets(externalIDs map[string]string) ([]ovnnb.AddressSet, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() diff --git a/pkg/ovs/ovn-nb-address_set_test.go b/pkg/ovs/ovn-nb-address_set_test.go index 393ec82218b..eb29d06fc25 100644 --- a/pkg/ovs/ovn-nb-address_set_test.go +++ b/pkg/ovs/ovn-nb-address_set_test.go @@ -163,10 +163,9 @@ func (suite *OvnClientTestSuite) testListAddressSets() { require.NoError(t, err) require.Len(t, ass, 1) require.Equal(t, asName, ass[0].Name) - } -func (suite *OvnClientTestSuite) test_addressSetFilter() { +func (suite *OvnClientTestSuite) testAddressSetFilter() { t := suite.T() t.Parallel() diff --git a/pkg/ovs/ovn-nb-bfd.go b/pkg/ovs/ovn-nb-bfd.go index d5160690ae3..3e897af27fa 100644 --- a/pkg/ovs/ovn-nb-bfd.go +++ b/pkg/ovs/ovn-nb-bfd.go @@ -4,11 +4,12 @@ import ( "context" "fmt" - "github.com/kubeovn/kube-ovn/pkg/ovsdb/ovnnb" "k8s.io/klog/v2" + + "github.com/kubeovn/kube-ovn/pkg/ovsdb/ovnnb" ) -func (c *ovnNbClient) ListBFD(lrpName, dstIP string) ([]ovnnb.BFD, error) { +func (c *OVNNbClient) ListBFD(lrpName, dstIP string) ([]ovnnb.BFD, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -25,7 +26,7 @@ func (c *ovnNbClient) ListBFD(lrpName, dstIP string) ([]ovnnb.BFD, error) { return bfdList, nil } -func (c *ovnNbClient) CreateBFD(lrpName, dstIP string, minRx, minTx, detectMult int) (*ovnnb.BFD, error) { +func (c *OVNNbClient) CreateBFD(lrpName, dstIP string, minRx, minTx, detectMult int) (*ovnnb.BFD, error) { bfdList, err := c.ListBFD(lrpName, dstIP) if err != nil { klog.Error(err) @@ -59,7 +60,7 @@ func (c *ovnNbClient) CreateBFD(lrpName, dstIP string, minRx, minTx, detectMult return &bfdList[0], nil } -func (c *ovnNbClient) DeleteBFD(lrpName, dstIP string) error { +func (c *OVNNbClient) DeleteBFD(lrpName, dstIP string) error { bfdList, err := c.ListBFD(lrpName, dstIP) if err != nil { klog.Error(err) diff --git a/pkg/ovs/ovn-nb-dhcp_options.go b/pkg/ovs/ovn-nb-dhcp_options.go index e344ddbe42b..d5fb27a5ea5 100644 --- a/pkg/ovs/ovn-nb-dhcp_options.go +++ b/pkg/ovs/ovn-nb-dhcp_options.go @@ -18,7 +18,7 @@ type DHCPOptionsUUIDs struct { DHCPv6OptionsUUID string } -func (c *ovnNbClient) CreateDHCPOptions(lsName, cidr, options string) error { +func (c *OVNNbClient) CreateDHCPOptions(lsName, cidr, options string) error { dhcpOpt, err := newDHCPOptions(lsName, cidr, options) if err != nil { klog.Error(err) @@ -39,7 +39,7 @@ func (c *ovnNbClient) CreateDHCPOptions(lsName, cidr, options string) error { return nil } -func (c *ovnNbClient) UpdateDHCPOptions(subnet *kubeovnv1.Subnet, mtu int) (*DHCPOptionsUUIDs, error) { +func (c *OVNNbClient) UpdateDHCPOptions(subnet *kubeovnv1.Subnet, mtu int) (*DHCPOptionsUUIDs, error) { lsName := subnet.Name cidrBlock := subnet.Spec.CIDRBlock gateway := subnet.Spec.Gateway @@ -87,7 +87,7 @@ func (c *ovnNbClient) UpdateDHCPOptions(subnet *kubeovnv1.Subnet, mtu int) (*DHC }, nil } -func (c *ovnNbClient) updateDHCPv4Options(lsName, cidr, gateway, options string, mtu int) (uuid string, err error) { +func (c *OVNNbClient) updateDHCPv4Options(lsName, cidr, gateway, options string, mtu int) (uuid string, err error) { protocol := util.CheckProtocol(cidr) if protocol != kubeovnv1.ProtocolIPv4 { return "", fmt.Errorf("cidr %s must be a valid ipv4 address", cidr) @@ -129,7 +129,7 @@ func (c *ovnNbClient) updateDHCPv4Options(lsName, cidr, gateway, options string, return dhcpOpt.UUID, nil } -func (c *ovnNbClient) updateDHCPv6Options(lsName, cidr, options string) (uuid string, err error) { +func (c *OVNNbClient) updateDHCPv6Options(lsName, cidr, options string) (uuid string, err error) { protocol := util.CheckProtocol(cidr) if protocol != kubeovnv1.ProtocolIPv6 { return "", fmt.Errorf("cidr %s must be a valid ipv4 address", cidr) @@ -172,7 +172,7 @@ func (c *ovnNbClient) updateDHCPv6Options(lsName, cidr, options string) (uuid st } // updateDHCPOptions update dhcp options -func (c *ovnNbClient) updateDHCPOptions(dhcpOpt *ovnnb.DHCPOptions, fields ...interface{}) error { +func (c *OVNNbClient) updateDHCPOptions(dhcpOpt *ovnnb.DHCPOptions, fields ...interface{}) error { if dhcpOpt == nil { return fmt.Errorf("dhcp_options is nil") } @@ -191,7 +191,7 @@ func (c *ovnNbClient) updateDHCPOptions(dhcpOpt *ovnnb.DHCPOptions, fields ...in } // DeleteDHCPOptionsByUUIDs delete dhcp options by uuid -func (c *ovnNbClient) DeleteDHCPOptionsByUUIDs(uuidList ...string) error { +func (c *OVNNbClient) DeleteDHCPOptionsByUUIDs(uuidList ...string) error { ops := make([]ovsdb.Operation, 0, len(uuidList)) for _, uuid := range uuidList { dhcpOptions := &ovnnb.DHCPOptions{ @@ -214,7 +214,7 @@ func (c *ovnNbClient) DeleteDHCPOptionsByUUIDs(uuidList ...string) error { } // DeleteDHCPOptions delete dhcp options which belongs to logical switch -func (c *ovnNbClient) DeleteDHCPOptions(lsName string, protocol string) error { +func (c *OVNNbClient) DeleteDHCPOptions(lsName, protocol string) error { if protocol == kubeovnv1.ProtocolDual { protocol = "" } @@ -239,7 +239,7 @@ func (c *ovnNbClient) DeleteDHCPOptions(lsName string, protocol string) error { // GetDHCPOptions get dhcp options, // a dhcp options is uniquely identified by switch(lsName) and protocol -func (c *ovnNbClient) GetDHCPOptions(lsName, protocol string, ignoreNotFound bool) (*ovnnb.DHCPOptions, error) { +func (c *OVNNbClient) GetDHCPOptions(lsName, protocol string, ignoreNotFound bool) (*ovnnb.DHCPOptions, error) { if len(lsName) == 0 { return nil, fmt.Errorf("the logical router name is required") } @@ -252,7 +252,6 @@ func (c *ovnNbClient) GetDHCPOptions(lsName, protocol string, ignoreNotFound boo logicalSwitchKey: lsName, "protocol": protocol, }) - if err != nil { klog.Error(err) return nil, fmt.Errorf("get logical switch %s %s dhcp options: %v", lsName, protocol, err) @@ -275,7 +274,7 @@ func (c *ovnNbClient) GetDHCPOptions(lsName, protocol string, ignoreNotFound boo } // ListDHCPOptions list dhcp options which match the given externalIDs -func (c *ovnNbClient) ListDHCPOptions(needVendorFilter bool, externalIDs map[string]string) ([]ovnnb.DHCPOptions, error) { +func (c *OVNNbClient) ListDHCPOptions(needVendorFilter bool, externalIDs map[string]string) ([]ovnnb.DHCPOptions, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -288,7 +287,7 @@ func (c *ovnNbClient) ListDHCPOptions(needVendorFilter bool, externalIDs map[str return dhcpOptList, nil } -func (c *ovnNbClient) DHCPOptionsExists(lsName, cidr string) (bool, error) { +func (c *OVNNbClient) DHCPOptionsExists(lsName, cidr string) (bool, error) { dhcpOpt, err := c.GetDHCPOptions(lsName, cidr, true) return dhcpOpt != nil, err } diff --git a/pkg/ovs/ovn-nb-dhcp_options_test.go b/pkg/ovs/ovn-nb-dhcp_options_test.go index a0d7ff4c551..624f71ba29d 100644 --- a/pkg/ovs/ovn-nb-dhcp_options_test.go +++ b/pkg/ovs/ovn-nb-dhcp_options_test.go @@ -64,7 +64,7 @@ func (suite *OvnClientTestSuite) testUpdateDHCPOptions() { }) } -func (suite *OvnClientTestSuite) test_updateDHCPv4Options() { +func (suite *OvnClientTestSuite) testUpdateDHCPv4Options() { t := suite.T() t.Parallel() @@ -134,7 +134,7 @@ func (suite *OvnClientTestSuite) test_updateDHCPv4Options() { }) } -func (suite *OvnClientTestSuite) test_updateDHCPv6Options() { +func (suite *OvnClientTestSuite) testUpdateDHCPv6Options() { t := suite.T() t.Parallel() @@ -358,7 +358,7 @@ func (suite *OvnClientTestSuite) testListDHCPOptions() { require.Len(t, out, 3) } -func (suite *OvnClientTestSuite) test_dhcpOptionsFilter() { +func (suite *OvnClientTestSuite) testDhcpOptionsFilter() { t := suite.T() t.Parallel() diff --git a/pkg/ovs/ovn-nb-gateway_chassis.go b/pkg/ovs/ovn-nb-gateway_chassis.go index 3cf8d20647e..7ef57b82011 100644 --- a/pkg/ovs/ovn-nb-gateway_chassis.go +++ b/pkg/ovs/ovn-nb-gateway_chassis.go @@ -14,7 +14,7 @@ import ( ) // CreateGatewayChassises create multiple gateway chassis once -func (c *ovnNbClient) CreateGatewayChassises(lrpName string, chassises ...string) error { +func (c *OVNNbClient) CreateGatewayChassises(lrpName string, chassises ...string) error { op, err := c.CreateGatewayChassisesOp(lrpName, chassises) if err != nil { return fmt.Errorf("generate operations for creating gateway chassis %v", err) @@ -28,7 +28,7 @@ func (c *ovnNbClient) CreateGatewayChassises(lrpName string, chassises ...string } // DeleteGatewayChassises delete multiple gateway chassis once -func (c *ovnNbClient) DeleteGatewayChassises(lrpName string, chassises []string) error { +func (c *OVNNbClient) DeleteGatewayChassises(lrpName string, chassises []string) error { if len(chassises) == 0 { return nil } @@ -59,7 +59,7 @@ func (c *ovnNbClient) DeleteGatewayChassises(lrpName string, chassises []string) } // GetGatewayChassis get gateway chassis by name -func (c *ovnNbClient) GetGatewayChassis(name string, ignoreNotFound bool) (*ovnnb.GatewayChassis, error) { +func (c *OVNNbClient) GetGatewayChassis(name string, ignoreNotFound bool) (*ovnnb.GatewayChassis, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -75,13 +75,13 @@ func (c *ovnNbClient) GetGatewayChassis(name string, ignoreNotFound bool) (*ovnn return gwChassis, nil } -func (c *ovnNbClient) GatewayChassisExist(name string) (bool, error) { +func (c *OVNNbClient) GatewayChassisExist(name string) (bool, error) { gwChassis, err := c.GetGatewayChassis(name, true) return gwChassis != nil, err } // newGatewayChassis return gateway chassis with basic information -func (c *ovnNbClient) newGatewayChassis(gwChassisName, chassisName string, priority int) (*ovnnb.GatewayChassis, error) { +func (c *OVNNbClient) newGatewayChassis(gwChassisName, chassisName string, priority int) (*ovnnb.GatewayChassis, error) { exists, err := c.GatewayChassisExist(gwChassisName) if err != nil { klog.Error(err) @@ -104,7 +104,7 @@ func (c *ovnNbClient) newGatewayChassis(gwChassisName, chassisName string, prior } // DeleteGatewayChassisOp create operation which create gateway chassis -func (c *ovnNbClient) CreateGatewayChassisesOp(lrpName string, chassises []string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) CreateGatewayChassisesOp(lrpName string, chassises []string) ([]ovsdb.Operation, error) { if len(chassises) == 0 { return nil, nil } @@ -148,9 +148,8 @@ func (c *ovnNbClient) CreateGatewayChassisesOp(lrpName string, chassises []strin } // DeleteGatewayChassisOp create operation which delete gateway chassis -func (c *ovnNbClient) DeleteGatewayChassisOp(chassisName string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) DeleteGatewayChassisOp(chassisName string) ([]ovsdb.Operation, error) { gwChassis, err := c.GetGatewayChassis(chassisName, true) - if err != nil { klog.Error(err) return nil, err diff --git a/pkg/ovs/ovn-nb-load_balancer.go b/pkg/ovs/ovn-nb-load_balancer.go index 00a184bb5bf..120a98146ee 100644 --- a/pkg/ovs/ovn-nb-load_balancer.go +++ b/pkg/ovs/ovn-nb-load_balancer.go @@ -16,7 +16,7 @@ import ( ) // CreateLoadBalancer create loadbalancer -func (c *ovnNbClient) CreateLoadBalancer(lbName, protocol, selectFields string) error { +func (c *OVNNbClient) CreateLoadBalancer(lbName, protocol, selectFields string) error { exist, err := c.LoadBalancerExists(lbName) if err != nil { klog.Error(err) @@ -51,7 +51,7 @@ func (c *ovnNbClient) CreateLoadBalancer(lbName, protocol, selectFields string) } // UpdateLoadBalancer update load balancer -func (c *ovnNbClient) UpdateLoadBalancer(lb *ovnnb.LoadBalancer, fields ...interface{}) error { +func (c *OVNNbClient) UpdateLoadBalancer(lb *ovnnb.LoadBalancer, fields ...interface{}) error { op, err := c.ovsDbClient.Where(lb).Update(lb, fields...) if err != nil { return fmt.Errorf("generate operations for updating load balancer %s: %v", lb.Name, err) @@ -65,7 +65,7 @@ func (c *ovnNbClient) UpdateLoadBalancer(lb *ovnnb.LoadBalancer, fields ...inter } // LoadBalancerAddVips adds or updates a vip -func (c *ovnNbClient) LoadBalancerAddVip(lbName, vip string, backends ...string) error { +func (c *OVNNbClient) LoadBalancerAddVip(lbName, vip string, backends ...string) error { sort.Strings(backends) ops, err := c.LoadBalancerOp(lbName, func(lb *ovnnb.LoadBalancer) []model.Mutation { mutations := make([]model.Mutation, 0, 2) @@ -97,7 +97,7 @@ func (c *ovnNbClient) LoadBalancerAddVip(lbName, vip string, backends ...string) } // LoadBalancerDeleteVip deletes load balancer vip -func (c *ovnNbClient) LoadBalancerDeleteVip(lbName string, vip string) error { +func (c *OVNNbClient) LoadBalancerDeleteVip(lbName, vip string) error { ops, err := c.LoadBalancerOp(lbName, func(lb *ovnnb.LoadBalancer) []model.Mutation { if len(lb.Vips) == 0 { return nil @@ -125,7 +125,7 @@ func (c *ovnNbClient) LoadBalancerDeleteVip(lbName string, vip string) error { } // SetLoadBalancerAffinityTimeout sets the LB's affinity timeout in seconds -func (c *ovnNbClient) SetLoadBalancerAffinityTimeout(lbName string, timeout int) error { +func (c *OVNNbClient) SetLoadBalancerAffinityTimeout(lbName string, timeout int) error { lb, err := c.GetLoadBalancer(lbName, false) if err != nil { klog.Error(err) @@ -150,7 +150,7 @@ func (c *ovnNbClient) SetLoadBalancerAffinityTimeout(lbName string, timeout int) } // DeleteLoadBalancers delete several loadbalancer once -func (c *ovnNbClient) DeleteLoadBalancers(filter func(lb *ovnnb.LoadBalancer) bool) error { +func (c *OVNNbClient) DeleteLoadBalancers(filter func(lb *ovnnb.LoadBalancer) bool) error { op, err := c.ovsDbClient.WhereCache(func(lb *ovnnb.LoadBalancer) bool { if filter != nil { return filter(lb) @@ -158,7 +158,6 @@ func (c *ovnNbClient) DeleteLoadBalancers(filter func(lb *ovnnb.LoadBalancer) bo return true }).Delete() - if err != nil { return fmt.Errorf("generate operations for delete load balancers: %v", err) } @@ -171,7 +170,7 @@ func (c *ovnNbClient) DeleteLoadBalancers(filter func(lb *ovnnb.LoadBalancer) bo } // DeleteLoadBalancer delete loadbalancer -func (c *ovnNbClient) DeleteLoadBalancer(lbName string) error { +func (c *OVNNbClient) DeleteLoadBalancer(lbName string) error { op, err := c.DeleteLoadBalancerOp(lbName) if err != nil { klog.Error(err) @@ -187,8 +186,8 @@ func (c *ovnNbClient) DeleteLoadBalancer(lbName string) error { } // GetLoadBalancer get load balancer by name, -// it is because of lack name index that does't use ovnNbClient.Get -func (c *ovnNbClient) GetLoadBalancer(lbName string, ignoreNotFound bool) (*ovnnb.LoadBalancer, error) { +// it is because of lack name index that does't use OVNNbClient.Get +func (c *OVNNbClient) GetLoadBalancer(lbName string, ignoreNotFound bool) (*ovnnb.LoadBalancer, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -215,13 +214,13 @@ func (c *ovnNbClient) GetLoadBalancer(lbName string, ignoreNotFound bool) (*ovnn return &lbList[0], nil } -func (c *ovnNbClient) LoadBalancerExists(lbName string) (bool, error) { +func (c *OVNNbClient) LoadBalancerExists(lbName string) (bool, error) { lrp, err := c.GetLoadBalancer(lbName, true) return lrp != nil, err } // ListLoadBalancers list all load balancers -func (c *ovnNbClient) ListLoadBalancers(filter func(lb *ovnnb.LoadBalancer) bool) ([]ovnnb.LoadBalancer, error) { +func (c *OVNNbClient) ListLoadBalancers(filter func(lb *ovnnb.LoadBalancer) bool) ([]ovnnb.LoadBalancer, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -239,7 +238,7 @@ func (c *ovnNbClient) ListLoadBalancers(filter func(lb *ovnnb.LoadBalancer) bool return lbList, nil } -func (c *ovnNbClient) LoadBalancerOp(lbName string, mutationsFunc ...func(lb *ovnnb.LoadBalancer) []model.Mutation) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LoadBalancerOp(lbName string, mutationsFunc ...func(lb *ovnnb.LoadBalancer) []model.Mutation) ([]ovsdb.Operation, error) { lb, err := c.GetLoadBalancer(lbName, false) if err != nil { klog.Error(err) @@ -270,9 +269,8 @@ func (c *ovnNbClient) LoadBalancerOp(lbName string, mutationsFunc ...func(lb *ov } // DeleteLoadBalancerOp create operation which delete load balancer -func (c *ovnNbClient) DeleteLoadBalancerOp(lbName string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) DeleteLoadBalancerOp(lbName string) ([]ovsdb.Operation, error) { lb, err := c.GetLoadBalancer(lbName, true) - if err != nil { klog.Error(err) return nil, err diff --git a/pkg/ovs/ovn-nb-logical_router.go b/pkg/ovs/ovn-nb-logical_router.go index f092431e2be..958e2014ab4 100644 --- a/pkg/ovs/ovn-nb-logical_router.go +++ b/pkg/ovs/ovn-nb-logical_router.go @@ -14,7 +14,7 @@ import ( ) // CreateLogicalRouter create logical router in ovn -func (c *ovnNbClient) CreateLogicalRouter(lrName string) error { +func (c *OVNNbClient) CreateLogicalRouter(lrName string) error { exist, err := c.LogicalRouterExists(lrName) if err != nil { return err @@ -44,7 +44,7 @@ func (c *ovnNbClient) CreateLogicalRouter(lrName string) error { } // UpdateLogicalRouter update logical router -func (c *ovnNbClient) UpdateLogicalRouter(lr *ovnnb.LogicalRouter, fields ...interface{}) error { +func (c *OVNNbClient) UpdateLogicalRouter(lr *ovnnb.LogicalRouter, fields ...interface{}) error { op, err := c.UpdateLogicalRouterOp(lr, fields...) if err != nil { klog.Error(err) @@ -59,7 +59,7 @@ func (c *ovnNbClient) UpdateLogicalRouter(lr *ovnnb.LogicalRouter, fields ...int } // DeleteLogicalRouter delete logical router in ovn -func (c *ovnNbClient) DeleteLogicalRouter(lrName string) error { +func (c *OVNNbClient) DeleteLogicalRouter(lrName string) error { lr, err := c.GetLogicalRouter(lrName, true) if err != nil { klog.Error(err) @@ -85,8 +85,8 @@ func (c *ovnNbClient) DeleteLogicalRouter(lrName string) error { } // GetLogicalRouter get logical router by name, -// it is because of lack name index that does't use ovnNbClient.Get -func (c *ovnNbClient) GetLogicalRouter(lrName string, ignoreNotFound bool) (*ovnnb.LogicalRouter, error) { +// it is because of lack name index that does't use OVNNbClient.Get +func (c *OVNNbClient) GetLogicalRouter(lrName string, ignoreNotFound bool) (*ovnnb.LogicalRouter, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -113,13 +113,13 @@ func (c *ovnNbClient) GetLogicalRouter(lrName string, ignoreNotFound bool) (*ovn return &lrList[0], nil } -func (c *ovnNbClient) LogicalRouterExists(name string) (bool, error) { +func (c *OVNNbClient) LogicalRouterExists(name string) (bool, error) { lrp, err := c.GetLogicalRouter(name, true) return lrp != nil, err } // ListLogicalRouter list logical router -func (c *ovnNbClient) ListLogicalRouter(needVendorFilter bool, filter func(lr *ovnnb.LogicalRouter) bool) ([]ovnnb.LogicalRouter, error) { +func (c *OVNNbClient) ListLogicalRouter(needVendorFilter bool, filter func(lr *ovnnb.LogicalRouter) bool) ([]ovnnb.LogicalRouter, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -143,7 +143,7 @@ func (c *ovnNbClient) ListLogicalRouter(needVendorFilter bool, filter func(lr *o } // LogicalRouterUpdateLoadBalancers add several lb to or from logical router once -func (c *ovnNbClient) LogicalRouterUpdateLoadBalancers(lrName string, op ovsdb.Mutator, lbNames ...string) error { +func (c *OVNNbClient) LogicalRouterUpdateLoadBalancers(lrName string, op ovsdb.Mutator, lbNames ...string) error { if len(lbNames) == 0 { return nil } @@ -181,14 +181,13 @@ func (c *ovnNbClient) LogicalRouterUpdateLoadBalancers(lrName string, op ovsdb.M if err := c.Transact("lr-lb-update", ops); err != nil { return fmt.Errorf("logical router %s update lbs %v: %v", lrName, lbNames, err) - } return nil } // UpdateLogicalRouterOp generate operations which update logical router -func (c *ovnNbClient) UpdateLogicalRouterOp(lr *ovnnb.LogicalRouter, fields ...interface{}) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) UpdateLogicalRouterOp(lr *ovnnb.LogicalRouter, fields ...interface{}) ([]ovsdb.Operation, error) { if lr == nil { return nil, fmt.Errorf("logical_router is nil") } @@ -203,7 +202,7 @@ func (c *ovnNbClient) UpdateLogicalRouterOp(lr *ovnnb.LogicalRouter, fields ...i } // LogicalRouterUpdatePortOp create operations add to or delete port from logical router -func (c *ovnNbClient) LogicalRouterUpdatePortOp(lrName, lrpUUID string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalRouterUpdatePortOp(lrName, lrpUUID string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(lrpUUID) == 0 { return nil, nil } @@ -247,7 +246,7 @@ func (c *ovnNbClient) LogicalRouterUpdatePortOp(lrName, lrpUUID string, op ovsdb } // LogicalRouterUpdatePolicyOp create operations add to or delete policy from logical router -func (c *ovnNbClient) LogicalRouterUpdatePolicyOp(lrName string, policyUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalRouterUpdatePolicyOp(lrName string, policyUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(policyUUIDs) == 0 { return nil, nil } @@ -266,7 +265,7 @@ func (c *ovnNbClient) LogicalRouterUpdatePolicyOp(lrName string, policyUUIDs []s } // LogicalRouterUpdateNatOp create operations add to or delete nat rule from logical router -func (c *ovnNbClient) LogicalRouterUpdateNatOp(lrName string, natUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalRouterUpdateNatOp(lrName string, natUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(natUUIDs) == 0 { return nil, nil } @@ -285,7 +284,7 @@ func (c *ovnNbClient) LogicalRouterUpdateNatOp(lrName string, natUUIDs []string, } // LogicalRouterUpdateStaticRouteOp create operations add to or delete static route from logical router -func (c *ovnNbClient) LogicalRouterUpdateStaticRouteOp(lrName string, routeUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalRouterUpdateStaticRouteOp(lrName string, routeUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(routeUUIDs) == 0 { return nil, nil } @@ -304,7 +303,7 @@ func (c *ovnNbClient) LogicalRouterUpdateStaticRouteOp(lrName string, routeUUIDs } // LogicalRouterOp create operations about logical router -func (c *ovnNbClient) LogicalRouterOp(lrName string, mutationsFunc ...func(lr *ovnnb.LogicalRouter) *model.Mutation) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalRouterOp(lrName string, mutationsFunc ...func(lr *ovnnb.LogicalRouter) *model.Mutation) ([]ovsdb.Operation, error) { lr, err := c.GetLogicalRouter(lrName, false) if err != nil { klog.Error(err) diff --git a/pkg/ovs/ovn-nb-logical_router_policy.go b/pkg/ovs/ovn-nb-logical_router_policy.go index 64834b1a469..db95486c338 100644 --- a/pkg/ovs/ovn-nb-logical_router_policy.go +++ b/pkg/ovs/ovn-nb-logical_router_policy.go @@ -17,7 +17,7 @@ import ( ) // AddLogicalRouterPolicy add a policy route to logical router -func (c *ovnNbClient) AddLogicalRouterPolicy(lrName string, priority int, match, action string, nextHops []string, externalIDs map[string]string) error { +func (c *OVNNbClient) AddLogicalRouterPolicy(lrName string, priority int, match, action string, nextHops []string, externalIDs map[string]string) error { fnFilter := func(policy *ovnnb.LogicalRouterPolicy) bool { return policy.Priority == priority && policy.Match == match } @@ -51,7 +51,7 @@ func (c *ovnNbClient) AddLogicalRouterPolicy(lrName string, priority int, match, } // CreateLogicalRouterPolicies create several logical router policy once -func (c *ovnNbClient) CreateLogicalRouterPolicies(lrName string, policies ...*ovnnb.LogicalRouterPolicy) error { +func (c *OVNNbClient) CreateLogicalRouterPolicies(lrName string, policies ...*ovnnb.LogicalRouterPolicy) error { if len(policies) == 0 { return nil } @@ -89,7 +89,7 @@ func (c *ovnNbClient) CreateLogicalRouterPolicies(lrName string, policies ...*ov } // DeleteLogicalRouterPolicy delete policy from logical router -func (c *ovnNbClient) DeleteLogicalRouterPolicy(lrName string, priority int, match string) error { +func (c *OVNNbClient) DeleteLogicalRouterPolicy(lrName string, priority int, match string) error { policyList, err := c.GetLogicalRouterPolicy(lrName, priority, match, true) if err != nil { klog.Error(err) @@ -107,7 +107,7 @@ func (c *ovnNbClient) DeleteLogicalRouterPolicy(lrName string, priority int, mat } // DeleteLogicalRouterPolicy delete some policies from logical router once -func (c *ovnNbClient) DeleteLogicalRouterPolicies(lrName string, priority int, externalIDs map[string]string) error { +func (c *OVNNbClient) DeleteLogicalRouterPolicies(lrName string, priority int, externalIDs map[string]string) error { // remove policies from logical router policies, err := c.ListLogicalRouterPolicies(lrName, priority, externalIDs) if err != nil { @@ -133,7 +133,7 @@ func (c *ovnNbClient) DeleteLogicalRouterPolicies(lrName string, priority int, e return nil } -func (c *ovnNbClient) DeleteLogicalRouterPolicyByUUID(lrName, uuid string) error { +func (c *OVNNbClient) DeleteLogicalRouterPolicyByUUID(lrName, uuid string) error { // remove policy from logical router ops, err := c.LogicalRouterUpdatePolicyOp(lrName, []string{uuid}, ovsdb.MutateOperationDelete) if err != nil { @@ -145,7 +145,7 @@ func (c *ovnNbClient) DeleteLogicalRouterPolicyByUUID(lrName, uuid string) error return nil } -func (c *ovnNbClient) DeleteLogicalRouterPolicyByNexthop(lrName string, priority int, nexthop string) error { +func (c *OVNNbClient) DeleteLogicalRouterPolicyByNexthop(lrName string, priority int, nexthop string) error { policyList, err := c.listLogicalRouterPoliciesByFilter(lrName, func(route *ovnnb.LogicalRouterPolicy) bool { if route.Priority != priority { return false @@ -165,7 +165,7 @@ func (c *ovnNbClient) DeleteLogicalRouterPolicyByNexthop(lrName string, priority } // ClearLogicalRouterPolicy clear policy from logical router once -func (c *ovnNbClient) ClearLogicalRouterPolicy(lrName string) error { +func (c *OVNNbClient) ClearLogicalRouterPolicy(lrName string) error { lr, err := c.GetLogicalRouter(lrName, false) if err != nil { return fmt.Errorf("get logical router %s: %v", lrName, err) @@ -186,7 +186,7 @@ func (c *ovnNbClient) ClearLogicalRouterPolicy(lrName string) error { // GetLogicalRouterPolicy get logical router policy by priority and match, // be consistent with ovn-nbctl which priority and match determine one policy in logical router -func (c *ovnNbClient) GetLogicalRouterPolicy(lrName string, priority int, match string, ignoreNotFound bool) ([]*ovnnb.LogicalRouterPolicy, error) { +func (c *OVNNbClient) GetLogicalRouterPolicy(lrName string, priority int, match string, ignoreNotFound bool) ([]*ovnnb.LogicalRouterPolicy, error) { // this is necessary because may exist same priority and match policy in different logical router if len(lrName) == 0 { return nil, fmt.Errorf("the logical router name is required") @@ -212,7 +212,7 @@ func (c *ovnNbClient) GetLogicalRouterPolicy(lrName string, priority int, match } // GetLogicalRouterPolicyByUUID get logical router policy by UUID -func (c *ovnNbClient) GetLogicalRouterPolicyByUUID(uuid string) (*ovnnb.LogicalRouterPolicy, error) { +func (c *OVNNbClient) GetLogicalRouterPolicyByUUID(uuid string) (*ovnnb.LogicalRouterPolicy, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -224,7 +224,7 @@ func (c *ovnNbClient) GetLogicalRouterPolicyByUUID(uuid string) (*ovnnb.LogicalR return policy, nil } -func (c *ovnNbClient) GetLogicalRouterPoliciesByExtID(lrName, key, value string) ([]*ovnnb.LogicalRouterPolicy, error) { +func (c *OVNNbClient) GetLogicalRouterPoliciesByExtID(lrName, key, value string) ([]*ovnnb.LogicalRouterPolicy, error) { fnFilter := func(policy *ovnnb.LogicalRouterPolicy) bool { return len(policy.ExternalIDs) != 0 && policy.ExternalIDs[key] == value } @@ -232,12 +232,12 @@ func (c *ovnNbClient) GetLogicalRouterPoliciesByExtID(lrName, key, value string) } // ListLogicalRouterPolicies list route policy which match the given externalIDs -func (c *ovnNbClient) ListLogicalRouterPolicies(lrName string, priority int, externalIDs map[string]string) ([]*ovnnb.LogicalRouterPolicy, error) { +func (c *OVNNbClient) ListLogicalRouterPolicies(lrName string, priority int, externalIDs map[string]string) ([]*ovnnb.LogicalRouterPolicy, error) { return c.listLogicalRouterPoliciesByFilter(lrName, policyFilter(priority, externalIDs)) } // newLogicalRouterPolicy return logical router policy with basic information -func (c *ovnNbClient) newLogicalRouterPolicy(priority int, match, action string, nextHops []string, externalIDs map[string]string) *ovnnb.LogicalRouterPolicy { +func (c *OVNNbClient) newLogicalRouterPolicy(priority int, match, action string, nextHops []string, externalIDs map[string]string) *ovnnb.LogicalRouterPolicy { return &ovnnb.LogicalRouterPolicy{ UUID: ovsclient.NamedUUID(), Priority: priority, @@ -279,7 +279,7 @@ func policyFilter(priority int, externalIDs map[string]string) func(policy *ovnn } } -func (c *ovnNbClient) DeleteRouterPolicy(lr *ovnnb.LogicalRouter, uuid string) error { +func (c *OVNNbClient) DeleteRouterPolicy(lr *ovnnb.LogicalRouter, uuid string) error { ops, err := c.ovsDbClient.Where(lr).Mutate(lr, model.Mutation{ Field: &lr.Policies, Mutator: ovsdb.MutateOperationDelete, @@ -294,7 +294,7 @@ func (c *ovnNbClient) DeleteRouterPolicy(lr *ovnnb.LogicalRouter, uuid string) e return nil } -func (c *ovnNbClient) listLogicalRouterPoliciesByFilter(lrName string, filter func(route *ovnnb.LogicalRouterPolicy) bool) ([]*ovnnb.LogicalRouterPolicy, error) { +func (c *OVNNbClient) listLogicalRouterPoliciesByFilter(lrName string, filter func(route *ovnnb.LogicalRouterPolicy) bool) ([]*ovnnb.LogicalRouterPolicy, error) { lr, err := c.GetLogicalRouter(lrName, false) if err != nil { klog.Error(err) diff --git a/pkg/ovs/ovn-nb-logical_router_policy_test.go b/pkg/ovs/ovn-nb-logical_router_policy_test.go index c0c77da23ec..c03cc90d70a 100644 --- a/pkg/ovs/ovn-nb-logical_router_policy_test.go +++ b/pkg/ovs/ovn-nb-logical_router_policy_test.go @@ -290,7 +290,7 @@ func (suite *OvnClientTestSuite) testGetLogicalRouterPolicy() { }) } -func (suite *OvnClientTestSuite) test_newLogicalRouterPolicy() { +func (suite *OvnClientTestSuite) testNewLogicalRouterPolicy() { t := suite.T() t.Parallel() @@ -317,7 +317,7 @@ func (suite *OvnClientTestSuite) test_newLogicalRouterPolicy() { require.Equal(t, expect, policy) } -func (suite *OvnClientTestSuite) test_policyFilter() { +func (suite *OvnClientTestSuite) testPolicyFilter() { t := suite.T() t.Parallel() diff --git a/pkg/ovs/ovn-nb-logical_router_port.go b/pkg/ovs/ovn-nb-logical_router_port.go index 7c310427485..25027c45a09 100644 --- a/pkg/ovs/ovn-nb-logical_router_port.go +++ b/pkg/ovs/ovn-nb-logical_router_port.go @@ -15,7 +15,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -func (c *ovnNbClient) CreatePeerRouterPort(localRouter, remoteRouter, localRouterPortIP string) error { +func (c *OVNNbClient) CreatePeerRouterPort(localRouter, remoteRouter, localRouterPortIP string) error { localRouterPort := fmt.Sprintf("%s-%s", localRouter, remoteRouter) remoteRouterPort := fmt.Sprintf("%s-%s", remoteRouter, localRouter) @@ -56,7 +56,7 @@ func (c *ovnNbClient) CreatePeerRouterPort(localRouter, remoteRouter, localRoute return nil } -func (c *ovnNbClient) UpdateLogicalRouterPortRA(lrpName, ipv6RAConfigsStr string, enableIPv6RA bool) error { +func (c *OVNNbClient) UpdateLogicalRouterPortRA(lrpName, ipv6RAConfigsStr string, enableIPv6RA bool) error { lrp, err := c.GetLogicalRouterPort(lrpName, false) if err != nil { klog.Error(err) @@ -80,7 +80,7 @@ func (c *ovnNbClient) UpdateLogicalRouterPortRA(lrpName, ipv6RAConfigsStr string return c.UpdateLogicalRouterPort(lrp, &lrp.Ipv6Prefix, &lrp.Ipv6RaConfigs) } -func (c *ovnNbClient) UpdateLogicalRouterPortOptions(lrpName string, options map[string]string) error { +func (c *OVNNbClient) UpdateLogicalRouterPortOptions(lrpName string, options map[string]string) error { if len(options) == 0 { return nil } @@ -106,7 +106,7 @@ func (c *ovnNbClient) UpdateLogicalRouterPortOptions(lrpName string, options map } // UpdateLogicalRouterPort update logical router port -func (c *ovnNbClient) UpdateLogicalRouterPort(lrp *ovnnb.LogicalRouterPort, fields ...interface{}) error { +func (c *OVNNbClient) UpdateLogicalRouterPort(lrp *ovnnb.LogicalRouterPort, fields ...interface{}) error { if lrp == nil { return fmt.Errorf("logical_router_port is nil") } @@ -125,7 +125,7 @@ func (c *ovnNbClient) UpdateLogicalRouterPort(lrp *ovnnb.LogicalRouterPort, fiel } // CreateLogicalRouterPort create logical router port with basic configuration -func (c *ovnNbClient) CreateLogicalRouterPort(lrName string, lrpName, mac string, networks []string) error { +func (c *OVNNbClient) CreateLogicalRouterPort(lrName, lrpName, mac string, networks []string) error { exists, err := c.LogicalRouterPortExists(lrpName) if err != nil { klog.Error(err) @@ -162,7 +162,7 @@ func (c *ovnNbClient) CreateLogicalRouterPort(lrName string, lrpName, mac string } // DeleteLogicalRouterPort delete logical router port from logical router -func (c *ovnNbClient) DeleteLogicalRouterPorts(externalIDs map[string]string, filter func(lrp *ovnnb.LogicalRouterPort) bool) error { +func (c *OVNNbClient) DeleteLogicalRouterPorts(externalIDs map[string]string, filter func(lrp *ovnnb.LogicalRouterPort) bool) error { lrpList, err := c.ListLogicalRouterPorts(externalIDs, filter) if err != nil { klog.Error(err) @@ -187,7 +187,7 @@ func (c *ovnNbClient) DeleteLogicalRouterPorts(externalIDs map[string]string, fi } // DeleteLogicalRouterPort delete logical router port from logical router -func (c *ovnNbClient) DeleteLogicalRouterPort(lrpName string) error { +func (c *OVNNbClient) DeleteLogicalRouterPort(lrpName string) error { ops, err := c.DeleteLogicalRouterPortOp(lrpName) if err != nil { klog.Error(err) @@ -202,7 +202,7 @@ func (c *ovnNbClient) DeleteLogicalRouterPort(lrpName string) error { } // GetLogicalRouterPort get logical router port by name -func (c *ovnNbClient) GetLogicalRouterPort(lrpName string, ignoreNotFound bool) (*ovnnb.LogicalRouterPort, error) { +func (c *OVNNbClient) GetLogicalRouterPort(lrpName string, ignoreNotFound bool) (*ovnnb.LogicalRouterPort, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -219,7 +219,7 @@ func (c *ovnNbClient) GetLogicalRouterPort(lrpName string, ignoreNotFound bool) } // GetLogicalRouterPortByUUID get logical router port by UUID -func (c *ovnNbClient) GetLogicalRouterPortByUUID(uuid string) (*ovnnb.LogicalRouterPort, error) { +func (c *OVNNbClient) GetLogicalRouterPortByUUID(uuid string) (*ovnnb.LogicalRouterPort, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -232,7 +232,7 @@ func (c *ovnNbClient) GetLogicalRouterPortByUUID(uuid string) (*ovnnb.LogicalRou } // ListLogicalRouterPorts list logical router ports -func (c *ovnNbClient) ListLogicalRouterPorts(externalIDs map[string]string, filter func(lrp *ovnnb.LogicalRouterPort) bool) ([]ovnnb.LogicalRouterPort, error) { +func (c *OVNNbClient) ListLogicalRouterPorts(externalIDs map[string]string, filter func(lrp *ovnnb.LogicalRouterPort) bool) ([]ovnnb.LogicalRouterPort, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -245,13 +245,13 @@ func (c *ovnNbClient) ListLogicalRouterPorts(externalIDs map[string]string, filt return lrpList, nil } -func (c *ovnNbClient) LogicalRouterPortExists(lrpName string) (bool, error) { +func (c *OVNNbClient) LogicalRouterPortExists(lrpName string) (bool, error) { lrp, err := c.GetLogicalRouterPort(lrpName, true) return lrp != nil, err } // LogicalRouterPortUpdateGatewayChassisOp create operations add to or delete gateway chassis from logical router port -func (c *ovnNbClient) LogicalRouterPortUpdateGatewayChassisOp(lrpName string, uuids []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalRouterPortUpdateGatewayChassisOp(lrpName string, uuids []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(uuids) == 0 { return nil, nil } @@ -270,7 +270,7 @@ func (c *ovnNbClient) LogicalRouterPortUpdateGatewayChassisOp(lrpName string, uu } // CreateLogicalRouterPortOp create operation which create logical router port -func (c *ovnNbClient) CreateLogicalRouterPortOp(lrp *ovnnb.LogicalRouterPort, lrName string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) CreateLogicalRouterPortOp(lrp *ovnnb.LogicalRouterPort, lrName string) ([]ovsdb.Operation, error) { if lrp == nil { return nil, fmt.Errorf("logical_router_port is nil") } @@ -305,7 +305,7 @@ func (c *ovnNbClient) CreateLogicalRouterPortOp(lrp *ovnnb.LogicalRouterPort, lr } // DeleteLogicalRouterPortOp create operation which delete logical router port -func (c *ovnNbClient) DeleteLogicalRouterPortOp(lrpName string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) DeleteLogicalRouterPortOp(lrpName string) ([]ovsdb.Operation, error) { lrp, err := c.GetLogicalRouterPort(lrpName, true) if err != nil { klog.Error(err) @@ -323,7 +323,7 @@ func (c *ovnNbClient) DeleteLogicalRouterPortOp(lrpName string) ([]ovsdb.Operati } // LogicalRouterPortOp create operations about logical router port -func (c *ovnNbClient) LogicalRouterPortOp(lrpName string, mutationsFunc ...func(lrp *ovnnb.LogicalRouterPort) *model.Mutation) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalRouterPortOp(lrpName string, mutationsFunc ...func(lrp *ovnnb.LogicalRouterPort) *model.Mutation) ([]ovsdb.Operation, error) { lrp, err := c.GetLogicalRouterPort(lrpName, false) if err != nil { klog.Error(err) @@ -385,7 +385,7 @@ func logicalRouterPortFilter(externalIDs map[string]string, filter func(lrp *ovn } } -func (c *ovnNbClient) AddLogicalRouterPort(lr, name, mac, networks string) error { +func (c *OVNNbClient) AddLogicalRouterPort(lr, name, mac, networks string) error { router, err := c.GetLogicalRouter(lr, false) if err != nil { klog.Error(err) diff --git a/pkg/ovs/ovn-nb-logical_router_port_test.go b/pkg/ovs/ovn-nb-logical_router_port_test.go index b83c563526b..9ca56eac130 100644 --- a/pkg/ovs/ovn-nb-logical_router_port_test.go +++ b/pkg/ovs/ovn-nb-logical_router_port_test.go @@ -25,7 +25,7 @@ func newLogicalRouterPort(lrName, lrpName, mac string, networks []string) *ovnnb } } -func createLogicalRouterPort(c *ovnNbClient, lrp *ovnnb.LogicalRouterPort) error { +func createLogicalRouterPort(c *OVNNbClient, lrp *ovnnb.LogicalRouterPort) error { op, err := c.Create(lrp) if err != nil { return fmt.Errorf("generate operations for creating logical router port %s: %v", lrp.Name, err) @@ -125,7 +125,6 @@ func (suite *OvnClientTestSuite) testUpdateLogicalRouterPortRA() { require.NoError(t, err) require.Empty(t, out.Ipv6Prefix) require.Empty(t, out.Ipv6RaConfigs) - }) t.Run("do nothing when enableIPv6RA is true and ipv6RAConfigsStr is invalid", func(t *testing.T) { diff --git a/pkg/ovs/ovn-nb-logical_router_route.go b/pkg/ovs/ovn-nb-logical_router_route.go index 2e220a0eef5..a1b559cdfc0 100644 --- a/pkg/ovs/ovn-nb-logical_router_route.go +++ b/pkg/ovs/ovn-nb-logical_router_route.go @@ -16,7 +16,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -func (c *ovnNbClient) ListLogicalRouterStaticRoutesByOption(lrName, routeTable, key, value string) ([]*ovnnb.LogicalRouterStaticRoute, error) { +func (c *OVNNbClient) ListLogicalRouterStaticRoutesByOption(lrName, _, key, value string) ([]*ovnnb.LogicalRouterStaticRoute, error) { fnFilter := func(route *ovnnb.LogicalRouterStaticRoute) bool { return len(route.Options) != 0 && route.Options[key] == value } @@ -24,7 +24,7 @@ func (c *ovnNbClient) ListLogicalRouterStaticRoutesByOption(lrName, routeTable, } // CreateLogicalRouterStaticRoutes create several logical router static route once -func (c *ovnNbClient) CreateLogicalRouterStaticRoutes(lrName string, routes ...*ovnnb.LogicalRouterStaticRoute) error { +func (c *OVNNbClient) CreateLogicalRouterStaticRoutes(lrName string, routes ...*ovnnb.LogicalRouterStaticRoute) error { if len(routes) == 0 { return nil } @@ -60,7 +60,7 @@ func (c *ovnNbClient) CreateLogicalRouterStaticRoutes(lrName string, routes ...* } // AddLogicalRouterStaticRoute add a logical router static route -func (c *ovnNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix string, bfdId *string, nexthops ...string) error { +func (c *OVNNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix string, bfdID *string, nexthops ...string) error { if len(policy) == 0 { policy = ovnnb.LogicalRouterStaticRoutePolicyDstIP } @@ -77,7 +77,7 @@ func (c *ovnNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ip if util.ContainsString(nexthops, route.Nexthop) { existing.Add(route.Nexthop) } else { - if route.BFD != nil && bfdId != nil && *route.BFD != *bfdId { + if route.BFD != nil && bfdID != nil && *route.BFD != *bfdID { continue } toDel = append(toDel, route.UUID) @@ -86,7 +86,7 @@ func (c *ovnNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ip var toAdd []*ovnnb.LogicalRouterStaticRoute for _, nexthop := range nexthops { if !existing.Has(nexthop) { - route, err := c.newLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, nexthop, bfdId) + route, err := c.newLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, nexthop, bfdID) if err != nil { klog.Error(err) return err @@ -111,7 +111,7 @@ func (c *ovnNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ip } // UpdateLogicalRouterStaticRoute update logical router static route -func (c *ovnNbClient) UpdateLogicalRouterStaticRoute(route *ovnnb.LogicalRouterStaticRoute, fields ...interface{}) error { +func (c *OVNNbClient) UpdateLogicalRouterStaticRoute(route *ovnnb.LogicalRouterStaticRoute, fields ...interface{}) error { if route == nil { return fmt.Errorf("route is nil") } @@ -130,7 +130,7 @@ func (c *ovnNbClient) UpdateLogicalRouterStaticRoute(route *ovnnb.LogicalRouterS } // DeleteLogicalRouterStaticRoute add a logical router static route -func (c *ovnNbClient) DeleteLogicalRouterStaticRoute(lrName string, routeTable, policy *string, ipPrefix, nexthop string) error { +func (c *OVNNbClient) DeleteLogicalRouterStaticRoute(lrName string, routeTable, policy *string, ipPrefix, nexthop string) error { if policy == nil || len(*policy) == 0 { policy = &ovnnb.LogicalRouterStaticRoutePolicyDstIP } @@ -168,7 +168,7 @@ func (c *ovnNbClient) DeleteLogicalRouterStaticRoute(lrName string, routeTable, } // ClearLogicalRouterStaticRoute clear static route from logical router once -func (c *ovnNbClient) ClearLogicalRouterStaticRoute(lrName string) error { +func (c *OVNNbClient) ClearLogicalRouterStaticRoute(lrName string) error { lr, err := c.GetLogicalRouter(lrName, false) if err != nil { klog.Error(err) @@ -191,7 +191,7 @@ func (c *ovnNbClient) ClearLogicalRouterStaticRoute(lrName string) error { } // GetLogicalRouterStaticRouteByUUID get logical router static route by UUID -func (c *ovnNbClient) GetLogicalRouterStaticRouteByUUID(uuid string) (*ovnnb.LogicalRouterStaticRoute, error) { +func (c *OVNNbClient) GetLogicalRouterStaticRouteByUUID(uuid string) (*ovnnb.LogicalRouterStaticRoute, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -207,7 +207,7 @@ func (c *ovnNbClient) GetLogicalRouterStaticRouteByUUID(uuid string) (*ovnnb.Log // GetLogicalRouterStaticRoute get logical router static route by some attribute, // a static route is uniquely identified by router(lrName), policy and ipPrefix when route is not ecmp // a static route is uniquely identified by router(lrName), policy, ipPrefix and nexthop when route is ecmp -func (c *ovnNbClient) GetLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, nexthop string, ignoreNotFound bool) (*ovnnb.LogicalRouterStaticRoute, error) { +func (c *OVNNbClient) GetLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, nexthop string, ignoreNotFound bool) (*ovnnb.LogicalRouterStaticRoute, error) { // this is necessary because may exist same static route in different logical router if len(lrName) == 0 { return nil, fmt.Errorf("the logical router name is required") @@ -238,7 +238,7 @@ func (c *ovnNbClient) GetLogicalRouterStaticRoute(lrName, routeTable, policy, ip } // ListLogicalRouterStaticRoutes list route which match the given externalIDs -func (c *ovnNbClient) ListLogicalRouterStaticRoutes(lrName string, routeTable, policy *string, ipPrefix string, externalIDs map[string]string) ([]*ovnnb.LogicalRouterStaticRoute, error) { +func (c *OVNNbClient) ListLogicalRouterStaticRoutes(lrName string, routeTable, policy *string, ipPrefix string, externalIDs map[string]string) ([]*ovnnb.LogicalRouterStaticRoute, error) { fnFilter := func(route *ovnnb.LogicalRouterStaticRoute) bool { if len(route.ExternalIDs) < len(externalIDs) { return false @@ -282,13 +282,13 @@ func (c *ovnNbClient) ListLogicalRouterStaticRoutes(lrName string, routeTable, p return c.listLogicalRouterStaticRoutesByFilter(lrName, fnFilter) } -func (c *ovnNbClient) LogicalRouterStaticRouteExists(lrName, routeTable, policy, ipPrefix, nexthop string) (bool, error) { +func (c *OVNNbClient) LogicalRouterStaticRouteExists(lrName, routeTable, policy, ipPrefix, nexthop string) (bool, error) { route, err := c.GetLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, nexthop, true) return route != nil, err } // newLogicalRouterStaticRoute return logical router static route with basic information -func (c *ovnNbClient) newLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, nexthop string, bfdId *string, options ...func(route *ovnnb.LogicalRouterStaticRoute)) (*ovnnb.LogicalRouterStaticRoute, error) { +func (c *OVNNbClient) newLogicalRouterStaticRoute(lrName, routeTable, policy, ipPrefix, nexthop string, bfdID *string, options ...func(route *ovnnb.LogicalRouterStaticRoute)) (*ovnnb.LogicalRouterStaticRoute, error) { if len(lrName) == 0 { return nil, fmt.Errorf("the logical router name is required") } @@ -318,8 +318,8 @@ func (c *ovnNbClient) newLogicalRouterStaticRoute(lrName, routeTable, policy, ip option(route) } - if bfdId != nil { - route.BFD = bfdId + if bfdID != nil { + route.BFD = bfdID if route.Options == nil { route.Options = make(map[string]string) } @@ -328,7 +328,7 @@ func (c *ovnNbClient) newLogicalRouterStaticRoute(lrName, routeTable, policy, ip return route, nil } -func (c *ovnNbClient) listLogicalRouterStaticRoutesByFilter(lrName string, filter func(route *ovnnb.LogicalRouterStaticRoute) bool) ([]*ovnnb.LogicalRouterStaticRoute, error) { +func (c *OVNNbClient) listLogicalRouterStaticRoutesByFilter(lrName string, filter func(route *ovnnb.LogicalRouterStaticRoute) bool) ([]*ovnnb.LogicalRouterStaticRoute, error) { lr, err := c.GetLogicalRouter(lrName, false) if err != nil { klog.Error(err) diff --git a/pkg/ovs/ovn-nb-logical_router_route_test.go b/pkg/ovs/ovn-nb-logical_router_route_test.go index e3dc6ba0f2d..4138bdc3ecd 100644 --- a/pkg/ovs/ovn-nb-logical_router_route_test.go +++ b/pkg/ovs/ovn-nb-logical_router_route_test.go @@ -348,7 +348,7 @@ func (suite *OvnClientTestSuite) testListLogicalRouterStaticRoutes() { }) } -func (suite *OvnClientTestSuite) test_newLogicalRouterStaticRoute() { +func (suite *OvnClientTestSuite) testNewLogicalRouterStaticRoute() { t := suite.T() t.Parallel() diff --git a/pkg/ovs/ovn-nb-logical_router_test.go b/pkg/ovs/ovn-nb-logical_router_test.go index 7a3e4215127..4d49dbb44f6 100644 --- a/pkg/ovs/ovn-nb-logical_router_test.go +++ b/pkg/ovs/ovn-nb-logical_router_test.go @@ -15,17 +15,13 @@ import ( ) // createLogicalRouter delete logical router in ovn -func createLogicalRouter(c *ovnNbClient, lr *ovnnb.LogicalRouter) error { +func createLogicalRouter(c *OVNNbClient, lr *ovnnb.LogicalRouter) error { op, err := c.ovsDbClient.Create(lr) if err != nil { return err } - if err := c.Transact("lr-add", op); err != nil { - return err - } - - return nil + return c.Transact("lr-add", op) } func (suite *OvnClientTestSuite) testCreateLogicalRouter() { diff --git a/pkg/ovs/ovn-nb-logical_switch.go b/pkg/ovs/ovn-nb-logical_switch.go index 68b1acdd821..163d089a346 100644 --- a/pkg/ovs/ovn-nb-logical_switch.go +++ b/pkg/ovs/ovn-nb-logical_switch.go @@ -14,11 +14,11 @@ import ( ) // CreateLogicalSwitch create logical switch -func (c *ovnNbClient) CreateLogicalSwitch(lsName, lrName, cidrBlock, gateway string, needRouter, randomAllocateGW bool) error { +func (c *OVNNbClient) CreateLogicalSwitch(lsName, lrName, cidrBlock, gateway string, needRouter, randomAllocateGW bool) error { lspName := fmt.Sprintf("%s-%s", lsName, lrName) lrpName := fmt.Sprintf("%s-%s", lrName, lsName) - networks := util.GetIpAddrWithMask(gateway, cidrBlock) + networks := util.GetIPAddrWithMask(gateway, cidrBlock) exist, err := c.LogicalSwitchExists(lsName) if err != nil { @@ -62,7 +62,7 @@ func (c *ovnNbClient) CreateLogicalSwitch(lsName, lrName, cidrBlock, gateway str } // CreateBareLogicalSwitch create logical switch with basic configuration -func (c *ovnNbClient) CreateBareLogicalSwitch(lsName string) error { +func (c *OVNNbClient) CreateBareLogicalSwitch(lsName string) error { exist, err := c.LogicalSwitchExists(lsName) if err != nil { klog.Error(err) @@ -93,7 +93,7 @@ func (c *ovnNbClient) CreateBareLogicalSwitch(lsName string) error { } // LogicalSwitchAddPort add port to logical switch -func (c *ovnNbClient) LogicalSwitchAddPort(lsName, lspName string) error { +func (c *OVNNbClient) LogicalSwitchAddPort(lsName, lspName string) error { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) @@ -115,7 +115,7 @@ func (c *ovnNbClient) LogicalSwitchAddPort(lsName, lspName string) error { } // LogicalSwitchDelPort del port from logical switch -func (c *ovnNbClient) LogicalSwitchDelPort(lsName, lspName string) error { +func (c *OVNNbClient) LogicalSwitchDelPort(lsName, lspName string) error { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) @@ -136,7 +136,7 @@ func (c *ovnNbClient) LogicalSwitchDelPort(lsName, lspName string) error { } // LogicalSwitchUpdateLoadBalancers add several lb to or from logical switch once -func (c *ovnNbClient) LogicalSwitchUpdateLoadBalancers(lsName string, op ovsdb.Mutator, lbNames ...string) error { +func (c *OVNNbClient) LogicalSwitchUpdateLoadBalancers(lsName string, op ovsdb.Mutator, lbNames ...string) error { if len(lbNames) == 0 { return nil } @@ -164,14 +164,13 @@ func (c *ovnNbClient) LogicalSwitchUpdateLoadBalancers(lsName string, op ovsdb.M if err := c.Transact("ls-lb-update", ops); err != nil { return fmt.Errorf("logical switch %s update lbs %v: %v", lsName, lbNames, err) - } return nil } // LogicalSwitchUpdateOtherConfig add other config to or from logical switch once -func (c *ovnNbClient) LogicalSwitchUpdateOtherConfig(lsName string, op ovsdb.Mutator, otherConfig map[string]string) error { +func (c *OVNNbClient) LogicalSwitchUpdateOtherConfig(lsName string, op ovsdb.Mutator, otherConfig map[string]string) error { if len(otherConfig) == 0 { return nil } @@ -190,7 +189,7 @@ func (c *ovnNbClient) LogicalSwitchUpdateOtherConfig(lsName string, op ovsdb.Mut } // DeleteLogicalSwitch delete logical switch -func (c *ovnNbClient) DeleteLogicalSwitch(lsName string) error { +func (c *OVNNbClient) DeleteLogicalSwitch(lsName string) error { op, err := c.DeleteLogicalSwitchOp(lsName) if err != nil { klog.Error(err) @@ -205,8 +204,8 @@ func (c *ovnNbClient) DeleteLogicalSwitch(lsName string) error { } // GetLogicalSwitch get logical switch by name, -// it is because of lack name index that does't use ovnNbClient.Get -func (c *ovnNbClient) GetLogicalSwitch(lsName string, ignoreNotFound bool) (*ovnnb.LogicalSwitch, error) { +// it is because of lack name index that does't use OVNNbClient.Get +func (c *OVNNbClient) GetLogicalSwitch(lsName string, ignoreNotFound bool) (*ovnnb.LogicalSwitch, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -233,13 +232,13 @@ func (c *ovnNbClient) GetLogicalSwitch(lsName string, ignoreNotFound bool) (*ovn return &lsList[0], nil } -func (c *ovnNbClient) LogicalSwitchExists(lsName string) (bool, error) { +func (c *OVNNbClient) LogicalSwitchExists(lsName string) (bool, error) { ls, err := c.GetLogicalSwitch(lsName, true) return ls != nil, err } // ListLogicalSwitch list logical switch -func (c *ovnNbClient) ListLogicalSwitch(needVendorFilter bool, filter func(ls *ovnnb.LogicalSwitch) bool) ([]ovnnb.LogicalSwitch, error) { +func (c *OVNNbClient) ListLogicalSwitch(needVendorFilter bool, filter func(ls *ovnnb.LogicalSwitch) bool) ([]ovnnb.LogicalSwitch, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -263,7 +262,7 @@ func (c *ovnNbClient) ListLogicalSwitch(needVendorFilter bool, filter func(ls *o } // LogicalSwitchUpdatePortOp create operations add port to or delete port from logical switch -func (c *ovnNbClient) LogicalSwitchUpdatePortOp(lsName string, lspUUID string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalSwitchUpdatePortOp(lsName, lspUUID string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(lspUUID) == 0 { return nil, nil } @@ -307,7 +306,7 @@ func (c *ovnNbClient) LogicalSwitchUpdatePortOp(lsName string, lspUUID string, o } // LogicalSwitchUpdateOtherConfigOp create operations add otherConfig to or delete otherConfig from logical switch -func (c *ovnNbClient) LogicalSwitchUpdateOtherConfigOp(lsName string, otherConfig map[string]string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalSwitchUpdateOtherConfigOp(lsName string, otherConfig map[string]string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(otherConfig) == 0 { return nil, nil } @@ -326,7 +325,7 @@ func (c *ovnNbClient) LogicalSwitchUpdateOtherConfigOp(lsName string, otherConfi } // LogicalSwitchUpdateLoadBalancerOp create operations add lb to or delete lb from logical switch -func (c *ovnNbClient) LogicalSwitchUpdateLoadBalancerOp(lsName string, lbUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalSwitchUpdateLoadBalancerOp(lsName string, lbUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(lbUUIDs) == 0 { return nil, nil } @@ -344,8 +343,8 @@ func (c *ovnNbClient) LogicalSwitchUpdateLoadBalancerOp(lsName string, lbUUIDs [ return c.LogicalSwitchOp(lsName, mutation) } -// logicalSwitchUpdateAclOp create operations add acl to or delete acl from logical switch -func (c *ovnNbClient) logicalSwitchUpdateAclOp(lsName string, aclUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +// logicalSwitchUpdateACLOp create operations add acl to or delete acl from logical switch +func (c *OVNNbClient) logicalSwitchUpdateACLOp(lsName string, aclUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(aclUUIDs) == 0 { return nil, nil } @@ -364,7 +363,7 @@ func (c *ovnNbClient) logicalSwitchUpdateAclOp(lsName string, aclUUIDs []string, } // LogicalSwitchOp create operations about logical switch -func (c *ovnNbClient) LogicalSwitchOp(lsName string, mutationsFunc ...func(ls *ovnnb.LogicalSwitch) *model.Mutation) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) LogicalSwitchOp(lsName string, mutationsFunc ...func(ls *ovnnb.LogicalSwitch) *model.Mutation) ([]ovsdb.Operation, error) { ls, err := c.GetLogicalSwitch(lsName, false) if err != nil { klog.Error(err) @@ -395,7 +394,7 @@ func (c *ovnNbClient) LogicalSwitchOp(lsName string, mutationsFunc ...func(ls *o } // DeleteLogicalSwitchOp create operations that delete logical switch -func (c *ovnNbClient) DeleteLogicalSwitchOp(lsName string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) DeleteLogicalSwitchOp(lsName string) ([]ovsdb.Operation, error) { ls, err := c.GetLogicalSwitch(lsName, true) if err != nil { klog.Error(err) diff --git a/pkg/ovs/ovn-nb-logical_switch_port.go b/pkg/ovs/ovn-nb-logical_switch_port.go index f2db2d481b9..b964eb44697 100644 --- a/pkg/ovs/ovn-nb-logical_switch_port.go +++ b/pkg/ovs/ovn-nb-logical_switch_port.go @@ -16,7 +16,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -func (c *ovnNbClient) CreateLogicalSwitchPort(lsName, lspName, ip, mac, podName, namespace string, portSecurity bool, securityGroups, vips string, enableDHCP bool, dhcpOptions *DHCPOptionsUUIDs, vpc string) error { +func (c *OVNNbClient) CreateLogicalSwitchPort(lsName, lspName, ip, mac, podName, namespace string, portSecurity bool, securityGroups, vips string, enableDHCP bool, dhcpOptions *DHCPOptionsUUIDs, vpc string) error { exist, err := c.LogicalSwitchPortExists(lspName) if err != nil { klog.Error(err) @@ -102,7 +102,7 @@ func (c *ovnNbClient) CreateLogicalSwitchPort(lsName, lspName, ip, mac, podName, } // CreateLocalnetLogicalSwitchPort create localnet type logical switch port -func (c *ovnNbClient) CreateLocalnetLogicalSwitchPort(lsName, lspName, provider string, vlanID int) error { +func (c *OVNNbClient) CreateLocalnetLogicalSwitchPort(lsName, lspName, provider string, vlanID int) error { exist, err := c.LogicalSwitchPortExists(lspName) if err != nil { klog.Error(err) @@ -143,7 +143,7 @@ func (c *ovnNbClient) CreateLocalnetLogicalSwitchPort(lsName, lspName, provider } // CreateVirtualLogicalSwitchPorts create several virtual type logical switch port once -func (c *ovnNbClient) CreateVirtualLogicalSwitchPorts(lsName string, ips ...string) error { +func (c *OVNNbClient) CreateVirtualLogicalSwitchPorts(lsName string, ips ...string) error { ops := make([]ovsdb.Operation, 0, len(ips)) for _, ip := range ips { @@ -186,7 +186,7 @@ func (c *ovnNbClient) CreateVirtualLogicalSwitchPorts(lsName string, ips ...stri } // CreateBareLogicalSwitchPort create logical switch port with basic configuration -func (c *ovnNbClient) CreateBareLogicalSwitchPort(lsName, lspName, ip, mac string) error { +func (c *OVNNbClient) CreateBareLogicalSwitchPort(lsName, lspName, ip, mac string) error { exist, err := c.LogicalSwitchPortExists(lspName) if err != nil { klog.Error(err) @@ -224,7 +224,7 @@ func (c *ovnNbClient) CreateBareLogicalSwitchPort(lsName, lspName, ip, mac strin } // CreateVirtualLogicalSwitchPorts update several virtual type logical switch port virtual-parents once -func (c *ovnNbClient) SetLogicalSwitchPortVirtualParents(lsName, parents string, ips ...string) error { +func (c *OVNNbClient) SetLogicalSwitchPortVirtualParents(lsName, parents string, ips ...string) error { ops := make([]ovsdb.Operation, 0, len(ips)) for _, ip := range ips { lspName := fmt.Sprintf("%s-vip-%s", lsName, ip) @@ -255,7 +255,7 @@ func (c *ovnNbClient) SetLogicalSwitchPortVirtualParents(lsName, parents string, return nil } -func (c *ovnNbClient) SetLogicalSwitchPortArpProxy(lspName string, enableArpProxy bool) error { +func (c *OVNNbClient) SetLogicalSwitchPortArpProxy(lspName string, enableArpProxy bool) error { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { return fmt.Errorf("get logical switch port %s: %v", lspName, err) @@ -280,7 +280,7 @@ func (c *ovnNbClient) SetLogicalSwitchPortArpProxy(lspName string, enableArpProx } // SetLogicalSwitchPortSecurity set logical switch port port_security -func (c *ovnNbClient) SetLogicalSwitchPortSecurity(portSecurity bool, lspName, mac, ips, vips string) error { +func (c *OVNNbClient) SetLogicalSwitchPortSecurity(portSecurity bool, lspName, mac, ips, vips string) error { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) @@ -325,7 +325,7 @@ func (c *ovnNbClient) SetLogicalSwitchPortSecurity(portSecurity bool, lspName, m } // SetLogicalSwitchPortExternalIds set logical switch port external ids -func (c *ovnNbClient) SetLogicalSwitchPortExternalIds(lspName string, externalIds map[string]string) error { +func (c *OVNNbClient) SetLogicalSwitchPortExternalIds(lspName string, externalIds map[string]string) error { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) @@ -349,7 +349,7 @@ func (c *ovnNbClient) SetLogicalSwitchPortExternalIds(lspName string, externalId // SetLogicalSwitchPortSecurityGroup set logical switch port security group, // op is 'add' or 'remove' -func (c *ovnNbClient) SetLogicalSwitchPortSecurityGroup(lsp *ovnnb.LogicalSwitchPort, op string, sgs ...string) ([]string, error) { +func (c *OVNNbClient) SetLogicalSwitchPortSecurityGroup(lsp *ovnnb.LogicalSwitchPort, op string, sgs ...string) ([]string, error) { if len(sgs) == 0 { return nil, nil } @@ -395,7 +395,7 @@ func (c *ovnNbClient) SetLogicalSwitchPortSecurityGroup(lsp *ovnnb.LogicalSwitch // SetLogicalSwitchPortsSecurityGroup set logical switch port security group, // op is 'add' or 'remove' -func (c *ovnNbClient) SetLogicalSwitchPortsSecurityGroup(sgName string, op string) error { +func (c *OVNNbClient) SetLogicalSwitchPortsSecurityGroup(sgName, op string) error { if op != "add" && op != "remove" { return fmt.Errorf("op must be 'add' or 'remove'") } @@ -425,7 +425,7 @@ func (c *ovnNbClient) SetLogicalSwitchPortsSecurityGroup(sgName string, op strin } // EnablePortLayer2forward set logical switch port addresses as 'unknown' -func (c *ovnNbClient) EnablePortLayer2forward(lspName string) error { +func (c *OVNNbClient) EnablePortLayer2forward(lspName string) error { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) @@ -441,7 +441,7 @@ func (c *ovnNbClient) EnablePortLayer2forward(lspName string) error { return nil } -func (c *ovnNbClient) SetLogicalSwitchPortVlanTag(lspName string, vlanID int) error { +func (c *OVNNbClient) SetLogicalSwitchPortVlanTag(lspName string, vlanID int) error { // valid vlan id is 0~4095 if vlanID < 0 || vlanID > 4095 { return fmt.Errorf("invalid vlan id %d", vlanID) @@ -471,7 +471,7 @@ func (c *ovnNbClient) SetLogicalSwitchPortVlanTag(lspName string, vlanID int) er } // UpdateLogicalSwitchPort update logical switch port -func (c *ovnNbClient) UpdateLogicalSwitchPort(lsp *ovnnb.LogicalSwitchPort, fields ...interface{}) error { +func (c *OVNNbClient) UpdateLogicalSwitchPort(lsp *ovnnb.LogicalSwitchPort, fields ...interface{}) error { if lsp == nil { return fmt.Errorf("logical_switch_port is nil") } @@ -490,7 +490,7 @@ func (c *ovnNbClient) UpdateLogicalSwitchPort(lsp *ovnnb.LogicalSwitchPort, fiel } // DeleteLogicalSwitchPort delete logical switch port in ovn -func (c *ovnNbClient) DeleteLogicalSwitchPort(lspName string) error { +func (c *OVNNbClient) DeleteLogicalSwitchPort(lspName string) error { ops, err := c.DeleteLogicalSwitchPortOp(lspName) if err != nil { klog.Error(err) @@ -505,7 +505,7 @@ func (c *ovnNbClient) DeleteLogicalSwitchPort(lspName string) error { } // GetLogicalSwitchPort get logical switch port by name -func (c *ovnNbClient) GetLogicalSwitchPort(lspName string, ignoreNotFound bool) (*ovnnb.LogicalSwitchPort, error) { +func (c *OVNNbClient) GetLogicalSwitchPort(lspName string, ignoreNotFound bool) (*ovnnb.LogicalSwitchPort, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() lsp := &ovnnb.LogicalSwitchPort{Name: lspName} @@ -520,7 +520,7 @@ func (c *ovnNbClient) GetLogicalSwitchPort(lspName string, ignoreNotFound bool) } // ListNormalLogicalSwitchPorts list logical switch ports which type is "" -func (c *ovnNbClient) ListNormalLogicalSwitchPorts(needVendorFilter bool, externalIDs map[string]string) ([]ovnnb.LogicalSwitchPort, error) { +func (c *OVNNbClient) ListNormalLogicalSwitchPorts(needVendorFilter bool, externalIDs map[string]string) ([]ovnnb.LogicalSwitchPort, error) { lsps, err := c.ListLogicalSwitchPorts(needVendorFilter, externalIDs, func(lsp *ovnnb.LogicalSwitchPort) bool { return lsp.Type == "" }) @@ -533,7 +533,7 @@ func (c *ovnNbClient) ListNormalLogicalSwitchPorts(needVendorFilter bool, extern } // ListLogicalSwitchPortsWithLegacyExternalIDs list logical switch ports with legacy external-ids -func (c *ovnNbClient) ListLogicalSwitchPortsWithLegacyExternalIDs() ([]ovnnb.LogicalSwitchPort, error) { +func (c *OVNNbClient) ListLogicalSwitchPortsWithLegacyExternalIDs() ([]ovnnb.LogicalSwitchPort, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -548,7 +548,7 @@ func (c *ovnNbClient) ListLogicalSwitchPortsWithLegacyExternalIDs() ([]ovnnb.Log } // ListLogicalSwitchPorts list logical switch ports -func (c *ovnNbClient) ListLogicalSwitchPorts(needVendorFilter bool, externalIDs map[string]string, filter func(lsp *ovnnb.LogicalSwitchPort) bool) ([]ovnnb.LogicalSwitchPort, error) { +func (c *OVNNbClient) ListLogicalSwitchPorts(needVendorFilter bool, externalIDs map[string]string, filter func(lsp *ovnnb.LogicalSwitchPort) bool) ([]ovnnb.LogicalSwitchPort, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -561,13 +561,13 @@ func (c *ovnNbClient) ListLogicalSwitchPorts(needVendorFilter bool, externalIDs return lspList, nil } -func (c *ovnNbClient) LogicalSwitchPortExists(name string) (bool, error) { +func (c *OVNNbClient) LogicalSwitchPortExists(name string) (bool, error) { lsp, err := c.GetLogicalSwitchPort(name, true) return lsp != nil, err } // CreateLogicalSwitchPortOp create operations which create logical switch port -func (c *ovnNbClient) CreateLogicalSwitchPortOp(lsp *ovnnb.LogicalSwitchPort, lsName string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) CreateLogicalSwitchPortOp(lsp *ovnnb.LogicalSwitchPort, lsName string) ([]ovsdb.Operation, error) { if lsp == nil { return nil, fmt.Errorf("logical_switch_port is nil") } @@ -602,7 +602,7 @@ func (c *ovnNbClient) CreateLogicalSwitchPortOp(lsp *ovnnb.LogicalSwitchPort, ls } // DeleteLogicalSwitchPortOp create operations which delete logical switch port -func (c *ovnNbClient) DeleteLogicalSwitchPortOp(lspName string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) DeleteLogicalSwitchPortOp(lspName string) ([]ovsdb.Operation, error) { lsp, err := c.GetLogicalSwitchPort(lspName, true) if err != nil { klog.Error(err) @@ -624,7 +624,7 @@ func (c *ovnNbClient) DeleteLogicalSwitchPortOp(lspName string) ([]ovsdb.Operati } // UpdateLogicalSwitchPortOp create operations which update logical switch port -func (c *ovnNbClient) UpdateLogicalSwitchPortOp(lsp *ovnnb.LogicalSwitchPort, fields ...interface{}) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) UpdateLogicalSwitchPortOp(lsp *ovnnb.LogicalSwitchPort, fields ...interface{}) ([]ovsdb.Operation, error) { // not found, skip if lsp == nil { return nil, nil diff --git a/pkg/ovs/ovn-nb-logical_switch_port_test.go b/pkg/ovs/ovn-nb-logical_switch_port_test.go index a0d843b6c2b..de0cb56db6b 100644 --- a/pkg/ovs/ovn-nb-logical_switch_port_test.go +++ b/pkg/ovs/ovn-nb-logical_switch_port_test.go @@ -14,7 +14,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -func createLogicalSwitchPort(c *ovnNbClient, lsp *ovnnb.LogicalSwitchPort) error { +func createLogicalSwitchPort(c *OVNNbClient, lsp *ovnnb.LogicalSwitchPort) error { if lsp == nil { return fmt.Errorf("logical_switch_port is nil") } diff --git a/pkg/ovs/ovn-nb-logical_switch_test.go b/pkg/ovs/ovn-nb-logical_switch_test.go index 8fd391e86a7..25fbe246b06 100644 --- a/pkg/ovs/ovn-nb-logical_switch_test.go +++ b/pkg/ovs/ovn-nb-logical_switch_test.go @@ -14,17 +14,13 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -func createLogicalSwitch(c *ovnNbClient, ls *ovnnb.LogicalSwitch) error { +func createLogicalSwitch(c *OVNNbClient, ls *ovnnb.LogicalSwitch) error { op, err := c.Create(ls) if err != nil { return err } - if err := c.Transact("ls-add", op); err != nil { - return err - } - - return nil + return c.Transact("ls-add", op) } func (suite *OvnClientTestSuite) testCreateLogicalSwitch() { @@ -468,7 +464,7 @@ func (suite *OvnClientTestSuite) testLogicalSwitchUpdateLoadBalancerOp() { }) } -func (suite *OvnClientTestSuite) test_logicalSwitchUpdateAclOp() { +func (suite *OvnClientTestSuite) testLogicalSwitchUpdateACLOp() { t := suite.T() t.Parallel() @@ -482,7 +478,7 @@ func (suite *OvnClientTestSuite) test_logicalSwitchUpdateAclOp() { t.Run("add new acl to logical switch ", func(t *testing.T) { t.Parallel() - ops, err := ovnClient.logicalSwitchUpdateAclOp(lsName, aclUUIDs, ovsdb.MutateOperationInsert) + ops, err := ovnClient.logicalSwitchUpdateACLOp(lsName, aclUUIDs, ovsdb.MutateOperationInsert) require.NoError(t, err) require.Equal(t, []ovsdb.Mutation{ { @@ -505,7 +501,7 @@ func (suite *OvnClientTestSuite) test_logicalSwitchUpdateAclOp() { t.Run("del acl from logical switch", func(t *testing.T) { t.Parallel() - ops, err := ovnClient.logicalSwitchUpdateAclOp(lsName, aclUUIDs, ovsdb.MutateOperationDelete) + ops, err := ovnClient.logicalSwitchUpdateACLOp(lsName, aclUUIDs, ovsdb.MutateOperationDelete) require.NoError(t, err) require.Equal(t, []ovsdb.Mutation{ { @@ -528,7 +524,7 @@ func (suite *OvnClientTestSuite) test_logicalSwitchUpdateAclOp() { t.Run("should return err when logical switch does not exist", func(t *testing.T) { t.Parallel() - _, err := ovnClient.logicalSwitchUpdateAclOp("test-acl-op-ls-non-existent", aclUUIDs, ovsdb.MutateOperationInsert) + _, err := ovnClient.logicalSwitchUpdateACLOp("test-acl-op-ls-non-existent", aclUUIDs, ovsdb.MutateOperationInsert) require.ErrorContains(t, err, "not found logical switch") }) } diff --git a/pkg/ovs/ovn-nb-nat.go b/pkg/ovs/ovn-nb-nat.go index 4e9514912d7..902fbf1ea1b 100644 --- a/pkg/ovs/ovn-nb-nat.go +++ b/pkg/ovs/ovn-nb-nat.go @@ -15,7 +15,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/ovsdb/ovnnb" ) -func (c *ovnNbClient) AddNat(lrName, natType, externalIP, logicalIP, logicalMac, port string, options map[string]string) error { +func (c *OVNNbClient) AddNat(lrName, natType, externalIP, logicalIP, logicalMac, port string, options map[string]string) error { nat, err := c.newNat(lrName, natType, externalIP, logicalIP, logicalMac, port, func(nat *ovnnb.NAT) { if len(options) == 0 { return @@ -35,7 +35,7 @@ func (c *ovnNbClient) AddNat(lrName, natType, externalIP, logicalIP, logicalMac, } // CreateNats create several logical router nat rule once -func (c *ovnNbClient) CreateNats(lrName string, nats ...*ovnnb.NAT) error { +func (c *OVNNbClient) CreateNats(lrName string, nats ...*ovnnb.NAT) error { if len(nats) == 0 { return nil } @@ -73,7 +73,7 @@ func (c *ovnNbClient) CreateNats(lrName string, nats ...*ovnnb.NAT) error { } // UpdateSnat update snat rule -func (c *ovnNbClient) UpdateSnat(lrName, externalIP, logicalIP string) error { +func (c *OVNNbClient) UpdateSnat(lrName, externalIP, logicalIP string) error { natType := ovnnb.NATTypeSNAT nat, err := c.GetNat(lrName, natType, "", logicalIP, true) @@ -103,7 +103,7 @@ func (c *ovnNbClient) UpdateSnat(lrName, externalIP, logicalIP string) error { } // UpdateDnatAndSnat update dnat_and_snat rule -func (c *ovnNbClient) UpdateDnatAndSnat(lrName, externalIP, logicalIP, lspName, externalMac, gatewayType string) error { +func (c *OVNNbClient) UpdateDnatAndSnat(lrName, externalIP, logicalIP, lspName, externalMac, gatewayType string) error { natType := ovnnb.NATTypeDNATAndSNAT nat, err := c.GetNat(lrName, natType, externalIP, "", true) @@ -150,7 +150,7 @@ func (c *ovnNbClient) UpdateDnatAndSnat(lrName, externalIP, logicalIP, lspName, } // UpdateNat update nat -func (c *ovnNbClient) UpdateNat(nat *ovnnb.NAT, fields ...interface{}) error { +func (c *OVNNbClient) UpdateNat(nat *ovnnb.NAT, fields ...interface{}) error { if nat == nil { return fmt.Errorf("nat is nil") } @@ -170,7 +170,7 @@ func (c *ovnNbClient) UpdateNat(nat *ovnnb.NAT, fields ...interface{}) error { } // DeleteNat delete several nat rule once -func (c *ovnNbClient) DeleteNats(lrName, natType, logicalIP string) error { +func (c *OVNNbClient) DeleteNats(lrName, natType, logicalIP string) error { /* delete nats from logical router */ nats, err := c.ListNats(lrName, natType, logicalIP, nil) if err != nil { @@ -196,7 +196,7 @@ func (c *ovnNbClient) DeleteNats(lrName, natType, logicalIP string) error { } // DeleteNat delete nat rule -func (c *ovnNbClient) DeleteNat(lrName, natType, externalIP, logicalIP string) error { +func (c *OVNNbClient) DeleteNat(lrName, natType, externalIP, logicalIP string) error { nat, err := c.GetNat(lrName, natType, externalIP, logicalIP, false) if err != nil { klog.Error(err) @@ -217,7 +217,7 @@ func (c *ovnNbClient) DeleteNat(lrName, natType, externalIP, logicalIP string) e } // GetNATByUUID get NAT by UUID -func (c *ovnNbClient) GetNATByUUID(uuid string) (*ovnnb.NAT, error) { +func (c *OVNNbClient) GetNATByUUID(uuid string) (*ovnnb.NAT, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -232,7 +232,7 @@ func (c *ovnNbClient) GetNATByUUID(uuid string) (*ovnnb.NAT, error) { // GetNat get nat by some attribute, // a nat rule is uniquely identified by router(lrName), type(natType) and logical_ip when snat // a nat rule is uniquely identified by router(lrName), type(natType) and external_ip when dnat_and_snat -func (c *ovnNbClient) GetNat(lrName, natType, externalIP, logicalIP string, ignoreNotFound bool) (*ovnnb.NAT, error) { +func (c *OVNNbClient) GetNat(lrName, natType, externalIP, logicalIP string, ignoreNotFound bool) (*ovnnb.NAT, error) { // this is necessary because may exist same nat rule in different logical router if len(lrName) == 0 { return nil, fmt.Errorf("the logical router name is required") @@ -273,17 +273,17 @@ func (c *ovnNbClient) GetNat(lrName, natType, externalIP, logicalIP string, igno } // ListNats list acls which match the given externalIDs -func (c *ovnNbClient) ListNats(lrName, natType, logicalIP string, externalIDs map[string]string) ([]*ovnnb.NAT, error) { +func (c *OVNNbClient) ListNats(lrName, natType, logicalIP string, externalIDs map[string]string) ([]*ovnnb.NAT, error) { return c.listLogicalRouterNatByFilter(lrName, natFilter(natType, logicalIP, externalIDs)) } -func (c *ovnNbClient) NatExists(lrName, natType, externalIP, logicalIP string) (bool, error) { +func (c *OVNNbClient) NatExists(lrName, natType, externalIP, logicalIP string) (bool, error) { nat, err := c.GetNat(lrName, natType, externalIP, logicalIP, true) return nat != nil, err } // newNat return net with basic information -func (c *ovnNbClient) newNat(lrName, natType, externalIP, logicalIP, logicalMac, port string, options ...func(nat *ovnnb.NAT)) (*ovnnb.NAT, error) { +func (c *OVNNbClient) newNat(lrName, natType, externalIP, logicalIP, logicalMac, port string, options ...func(nat *ovnnb.NAT)) (*ovnnb.NAT, error) { if len(lrName) == 0 { return nil, fmt.Errorf("the logical router name is required") } @@ -365,7 +365,7 @@ func natFilter(natType, logicalIP string, externalIDs map[string]string) func(na } } -func (c *ovnNbClient) listLogicalRouterNatByFilter(lrName string, filter func(route *ovnnb.NAT) bool) ([]*ovnnb.NAT, error) { +func (c *OVNNbClient) listLogicalRouterNatByFilter(lrName string, filter func(route *ovnnb.NAT) bool) ([]*ovnnb.NAT, error) { lr, err := c.GetLogicalRouter(lrName, false) if err != nil { klog.Error(err) diff --git a/pkg/ovs/ovn-nb-nat_test.go b/pkg/ovs/ovn-nb-nat_test.go index e4562e80759..17f15b45d2d 100644 --- a/pkg/ovs/ovn-nb-nat_test.go +++ b/pkg/ovs/ovn-nb-nat_test.go @@ -427,7 +427,7 @@ func (suite *OvnClientTestSuite) testGetNat() { }) } -func (suite *OvnClientTestSuite) test_newNat() { +func (suite *OvnClientTestSuite) testNewNat() { t := suite.T() t.Parallel() @@ -482,7 +482,7 @@ func (suite *OvnClientTestSuite) test_newNat() { }) } -func (suite *OvnClientTestSuite) test_natFilter() { +func (suite *OvnClientTestSuite) testNatFilter() { t := suite.T() t.Parallel() diff --git a/pkg/ovs/ovn-nb-port_group.go b/pkg/ovs/ovn-nb-port_group.go index 705a061df66..ce14104c75a 100644 --- a/pkg/ovs/ovn-nb-port_group.go +++ b/pkg/ovs/ovn-nb-port_group.go @@ -13,7 +13,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/ovsdb/ovnnb" ) -func (c *ovnNbClient) CreatePortGroup(pgName string, externalIDs map[string]string) error { +func (c *OVNNbClient) CreatePortGroup(pgName string, externalIDs map[string]string) error { exist, err := c.PortGroupExists(pgName) if err != nil { klog.Error(err) @@ -43,16 +43,16 @@ func (c *ovnNbClient) CreatePortGroup(pgName string, externalIDs map[string]stri } // PortGroupAddPorts add ports to port group -func (c *ovnNbClient) PortGroupAddPorts(pgName string, lspNames ...string) error { +func (c *OVNNbClient) PortGroupAddPorts(pgName string, lspNames ...string) error { return c.PortGroupUpdatePorts(pgName, ovsdb.MutateOperationInsert, lspNames...) } // PortGroupRemovePorts remove ports from port group -func (c *ovnNbClient) PortGroupRemovePorts(pgName string, lspNames ...string) error { +func (c *OVNNbClient) PortGroupRemovePorts(pgName string, lspNames ...string) error { return c.PortGroupUpdatePorts(pgName, ovsdb.MutateOperationDelete, lspNames...) } -func (c *ovnNbClient) PortGroupSetPorts(pgName string, ports []string) error { +func (c *OVNNbClient) PortGroupSetPorts(pgName string, ports []string) error { pg, err := c.GetPortGroup(pgName, false) if err != nil { return fmt.Errorf("get port group %s: %v", pgName, err) @@ -91,7 +91,7 @@ func (c *ovnNbClient) PortGroupSetPorts(pgName string, ports []string) error { } // UpdatePortGroup update port group -func (c *ovnNbClient) UpdatePortGroup(pg *ovnnb.PortGroup, fields ...interface{}) error { +func (c *OVNNbClient) UpdatePortGroup(pg *ovnnb.PortGroup, fields ...interface{}) error { op, err := c.Where(pg).Update(pg, fields...) if err != nil { return fmt.Errorf("generate operations for updating port group %s: %v", pg.Name, err) @@ -105,7 +105,7 @@ func (c *ovnNbClient) UpdatePortGroup(pg *ovnnb.PortGroup, fields ...interface{} } // PortGroupUpdatePorts add several ports to or from port group once -func (c *ovnNbClient) PortGroupUpdatePorts(pgName string, op ovsdb.Mutator, lspNames ...string) error { +func (c *OVNNbClient) PortGroupUpdatePorts(pgName string, op ovsdb.Mutator, lspNames ...string) error { if len(lspNames) == 0 { return nil } @@ -137,7 +137,7 @@ func (c *ovnNbClient) PortGroupUpdatePorts(pgName string, op ovsdb.Mutator, lspN return nil } -func (c *ovnNbClient) DeletePortGroup(pgName string) error { +func (c *OVNNbClient) DeletePortGroup(pgName string) error { pg, err := c.GetPortGroup(pgName, true) if err != nil { return fmt.Errorf("get port group %s when delete: %v", pgName, err) @@ -162,7 +162,7 @@ func (c *ovnNbClient) DeletePortGroup(pgName string) error { } // GetPortGroup get port group by name -func (c *ovnNbClient) GetPortGroup(pgName string, ignoreNotFound bool) (*ovnnb.PortGroup, error) { +func (c *OVNNbClient) GetPortGroup(pgName string, ignoreNotFound bool) (*ovnnb.PortGroup, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -180,7 +180,7 @@ func (c *ovnNbClient) GetPortGroup(pgName string, ignoreNotFound bool) (*ovnnb.P // ListPortGroups list port groups which match the given externalIDs, // result should include all port groups when externalIDs is empty, // result should include all port groups which externalIDs[key] is not empty when externalIDs[key] is "" -func (c *ovnNbClient) ListPortGroups(externalIDs map[string]string) ([]ovnnb.PortGroup, error) { +func (c *OVNNbClient) ListPortGroups(externalIDs map[string]string) ([]ovnnb.PortGroup, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -204,7 +204,6 @@ func (c *ovnNbClient) ListPortGroups(externalIDs map[string]string) ([]ovnnb.Por return false } } - } } @@ -217,13 +216,13 @@ func (c *ovnNbClient) ListPortGroups(externalIDs map[string]string) ([]ovnnb.Por return pgs, nil } -func (c *ovnNbClient) PortGroupExists(pgName string) (bool, error) { +func (c *OVNNbClient) PortGroupExists(pgName string) (bool, error) { lsp, err := c.GetPortGroup(pgName, true) return lsp != nil, err } // portGroupUpdatePortOp create operations add port to or delete port from port group -func (c *ovnNbClient) portGroupUpdatePortOp(pgName string, lspUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) portGroupUpdatePortOp(pgName string, lspUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(lspUUIDs) == 0 { return nil, nil } @@ -241,8 +240,8 @@ func (c *ovnNbClient) portGroupUpdatePortOp(pgName string, lspUUIDs []string, op return c.portGroupOp(pgName, mutation) } -// portGroupUpdateAclOp create operations add acl to or delete acl from port group -func (c *ovnNbClient) portGroupUpdateAclOp(pgName string, aclUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { +// portGroupUpdateACLOp create operations add acl to or delete acl from port group +func (c *OVNNbClient) portGroupUpdateACLOp(pgName string, aclUUIDs []string, op ovsdb.Mutator) ([]ovsdb.Operation, error) { if len(aclUUIDs) == 0 { return nil, nil } @@ -261,7 +260,7 @@ func (c *ovnNbClient) portGroupUpdateAclOp(pgName string, aclUUIDs []string, op } // portGroupOp create operations about port group -func (c *ovnNbClient) portGroupOp(pgName string, mutationsFunc ...func(pg *ovnnb.PortGroup) *model.Mutation) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) portGroupOp(pgName string, mutationsFunc ...func(pg *ovnnb.PortGroup) *model.Mutation) ([]ovsdb.Operation, error) { pg, err := c.GetPortGroup(pgName, false) if err != nil { return nil, fmt.Errorf("get port group %s: %v", pgName, err) diff --git a/pkg/ovs/ovn-nb-port_group_test.go b/pkg/ovs/ovn-nb-port_group_test.go index a4ea9fc9d5c..af82ec3875c 100644 --- a/pkg/ovs/ovn-nb-port_group_test.go +++ b/pkg/ovs/ovn-nb-port_group_test.go @@ -299,7 +299,7 @@ func (suite *OvnClientTestSuite) testListPortGroups() { }) } -func (suite *OvnClientTestSuite) test_portGroupUpdatePortOp() { +func (suite *OvnClientTestSuite) testPortGroupUpdatePortOp() { t := suite.T() t.Parallel() @@ -367,7 +367,7 @@ func (suite *OvnClientTestSuite) test_portGroupUpdatePortOp() { }) } -func (suite *OvnClientTestSuite) test_portGroupUpdateAclOp() { +func (suite *OvnClientTestSuite) testPortGroupUpdateACLOp() { t := suite.T() t.Parallel() @@ -384,7 +384,7 @@ func (suite *OvnClientTestSuite) test_portGroupUpdateAclOp() { t.Run("add new acl to port group", func(t *testing.T) { t.Parallel() - ops, err := ovnClient.portGroupUpdateAclOp(pgName, aclUUIDs, ovsdb.MutateOperationInsert) + ops, err := ovnClient.portGroupUpdateACLOp(pgName, aclUUIDs, ovsdb.MutateOperationInsert) require.NoError(t, err) require.Equal(t, []ovsdb.Mutation{ { @@ -407,7 +407,7 @@ func (suite *OvnClientTestSuite) test_portGroupUpdateAclOp() { t.Run("del acl from port group", func(t *testing.T) { t.Parallel() - ops, err := ovnClient.portGroupUpdateAclOp(pgName, aclUUIDs, ovsdb.MutateOperationDelete) + ops, err := ovnClient.portGroupUpdateACLOp(pgName, aclUUIDs, ovsdb.MutateOperationDelete) require.NoError(t, err) require.Equal(t, []ovsdb.Mutation{ { @@ -430,12 +430,12 @@ func (suite *OvnClientTestSuite) test_portGroupUpdateAclOp() { t.Run("should return err when port group does not exist", func(t *testing.T) { t.Parallel() - _, err := ovnClient.portGroupUpdateAclOp("test-acl-op-pg-non-existent", aclUUIDs, ovsdb.MutateOperationInsert) + _, err := ovnClient.portGroupUpdateACLOp("test-acl-op-pg-non-existent", aclUUIDs, ovsdb.MutateOperationInsert) require.ErrorContains(t, err, "object not found") }) } -func (suite *OvnClientTestSuite) test_portGroupOp() { +func (suite *OvnClientTestSuite) testPortGroupOp() { t := suite.T() t.Parallel() diff --git a/pkg/ovs/ovn-nb-suite_test.go b/pkg/ovs/ovn-nb-suite_test.go index 16824262397..eb55cd5998b 100644 --- a/pkg/ovs/ovn-nb-suite_test.go +++ b/pkg/ovs/ovn-nb-suite_test.go @@ -26,7 +26,7 @@ import ( type OvnClientTestSuite struct { suite.Suite - ovnClient *ovnNbClient + ovnClient *OVNNbClient } func (suite *OvnClientTestSuite) SetupSuite() { @@ -114,7 +114,7 @@ func (suite *OvnClientTestSuite) Test_LogicalSwitchUpdateLoadBalancerOp() { } func (suite *OvnClientTestSuite) Test_logicalSwitchUpdateAclOp() { - suite.test_logicalSwitchUpdateAclOp() + suite.testLogicalSwitchUpdateACLOp() } func (suite *OvnClientTestSuite) Test_LogicalSwitchOp() { @@ -380,15 +380,15 @@ func (suite *OvnClientTestSuite) Test_ListPortGroups() { } func (suite *OvnClientTestSuite) Test_portGroupUpdatePortOp() { - suite.test_portGroupUpdatePortOp() + suite.testPortGroupUpdatePortOp() } func (suite *OvnClientTestSuite) Test_portGroupUpdateAclOp() { - suite.test_portGroupUpdateAclOp() + suite.testPortGroupUpdateACLOp() } func (suite *OvnClientTestSuite) Test_portGroupOp() { - suite.test_portGroupOp() + suite.testPortGroupOp() } /* address_set unit test */ @@ -413,28 +413,28 @@ func (suite *OvnClientTestSuite) Test_ListAddressSets() { } func (suite *OvnClientTestSuite) Test_addressSetFilter() { - suite.test_addressSetFilter() + suite.testAddressSetFilter() } /* acl unit test */ func (suite *OvnClientTestSuite) Test_testUpdateIngressAclOps() { - suite.testUpdateIngressAclOps() + suite.testUpdateIngressACLOps() } func (suite *OvnClientTestSuite) Test_UpdateEgressAclOps() { - suite.testUpdateEgressAclOps() + suite.testUpdateEgressACLOps() } func (suite *OvnClientTestSuite) Test_CreateGatewayAcl() { - suite.testCreateGatewayAcl() + suite.testCreateGatewayACL() } func (suite *OvnClientTestSuite) Test_CreateNodeAcl() { - suite.testCreateNodeAcl() + suite.testCreateNodeACL() } func (suite *OvnClientTestSuite) Test_CreateSgDenyAllAcl() { - suite.testCreateSgDenyAllAcl() + suite.testCreateSgDenyAllACL() } func (suite *OvnClientTestSuite) Test_CreateSgBaseACL() { @@ -442,15 +442,15 @@ func (suite *OvnClientTestSuite) Test_CreateSgBaseACL() { } func (suite *OvnClientTestSuite) Test_UpdateSgAcl() { - suite.testUpdateSgAcl() + suite.testUpdateSgACL() } func (suite *OvnClientTestSuite) Test_UpdateLogicalSwitchAcl() { - suite.testUpdateLogicalSwitchAcl() + suite.testUpdateLogicalSwitchACL() } func (suite *OvnClientTestSuite) Test_SetAclLog() { - suite.testSetAclLog() + suite.testSetACLLog() } func (suite *OvnClientTestSuite) Test_SetLogicalSwitchPrivate() { @@ -458,7 +458,7 @@ func (suite *OvnClientTestSuite) Test_SetLogicalSwitchPrivate() { } func (suite *OvnClientTestSuite) Test_newSgRuleACL() { - suite.test_newSgRuleACL() + suite.testNewSgRuleACL() } func (suite *OvnClientTestSuite) Test_CreateAcls() { @@ -470,11 +470,11 @@ func (suite *OvnClientTestSuite) Test_DeleteAcls() { } func (suite *OvnClientTestSuite) Test_DeleteAcl() { - suite.testDeleteAcl() + suite.testDeleteACL() } func (suite *OvnClientTestSuite) Test_GetAcl() { - suite.testGetAcl() + suite.testGetACL() } func (suite *OvnClientTestSuite) Test_ListAcls() { @@ -482,15 +482,15 @@ func (suite *OvnClientTestSuite) Test_ListAcls() { } func (suite *OvnClientTestSuite) Test_newAcl() { - suite.test_newAcl() + suite.testNewACL() } func (suite *OvnClientTestSuite) Test_newNetworkPolicyAclMatch() { - suite.testnewNetworkPolicyAclMatch() + suite.testnewNetworkPolicyACLMatch() } func (suite *OvnClientTestSuite) Test_aclFilter() { - suite.test_aclFilter() + suite.testACLFilter() } /* logical_router_policy unit test */ @@ -519,11 +519,11 @@ func (suite *OvnClientTestSuite) Test_GetLogicalRouterPolicy() { } func (suite *OvnClientTestSuite) Test_newLogicalRouterPolicy() { - suite.test_newLogicalRouterPolicy() + suite.testNewLogicalRouterPolicy() } func (suite *OvnClientTestSuite) Test_policyFilter() { - suite.test_policyFilter() + suite.testPolicyFilter() } /* nat unit test */ @@ -552,11 +552,11 @@ func (suite *OvnClientTestSuite) Test_GetNat() { } func (suite *OvnClientTestSuite) Test_newNat() { - suite.test_newNat() + suite.testNewNat() } func (suite *OvnClientTestSuite) Test_natFilter() { - suite.test_natFilter() + suite.testNatFilter() } /* logical_router_static_route unit test */ @@ -585,7 +585,7 @@ func (suite *OvnClientTestSuite) Test_ListLogicalRouterStaticRoutes() { } func (suite *OvnClientTestSuite) Test_newLogicalRouterStaticRoute() { - suite.test_newLogicalRouterStaticRoute() + suite.testNewLogicalRouterStaticRoute() } /* dhcp options unit test */ @@ -594,11 +594,11 @@ func (suite *OvnClientTestSuite) Test_UpdateDHCPOptions() { } func (suite *OvnClientTestSuite) Test_updateDHCPv4Options() { - suite.test_updateDHCPv4Options() + suite.testUpdateDHCPv4Options() } func (suite *OvnClientTestSuite) Test_updateDHCPv6Options() { - suite.test_updateDHCPv6Options() + suite.testUpdateDHCPv6Options() } func (suite *OvnClientTestSuite) Test_DeleteDHCPOptionsByUUIDs() { @@ -618,7 +618,7 @@ func (suite *OvnClientTestSuite) Test_ListDHCPOptions() { } func (suite *OvnClientTestSuite) Test_dhcpOptionsFilter() { - suite.test_dhcpOptionsFilter() + suite.testDhcpOptionsFilter() } /* mixed operations unit test */ @@ -692,11 +692,11 @@ func newOVSDBServer(t *testing.T, dbModel model.ClientDBModel, schema ovsdb.Data return server, tmpfile } -func newOvnNbClient(t *testing.T, ovnNbAddr string, ovnNbTimeout int) (*ovnNbClient, error) { +func newOvnNbClient(t *testing.T, ovnNbAddr string, ovnNbTimeout int) (*OVNNbClient, error) { nbClient, err := newNbClient(ovnNbAddr, ovnNbTimeout) require.NoError(t, err) - return &ovnNbClient{ + return &OVNNbClient{ ovsDbClient: ovsDbClient{ Client: nbClient, Timeout: time.Duration(ovnNbTimeout) * time.Second, diff --git a/pkg/ovs/ovn-nb.go b/pkg/ovs/ovn-nb.go index 69963bdf549..e29c0c6990c 100644 --- a/pkg/ovs/ovn-nb.go +++ b/pkg/ovs/ovn-nb.go @@ -22,7 +22,7 @@ const ( ) // CreateGatewayLogicalSwitch create gateway switch connect external networks -func (c *ovnNbClient) CreateGatewayLogicalSwitch(lsName, lrName, provider, ip, mac string, vlanID int, chassises ...string) error { +func (c *OVNNbClient) CreateGatewayLogicalSwitch(lsName, lrName, provider, ip, mac string, vlanID int, chassises ...string) error { lspName := fmt.Sprintf("%s-%s", lsName, lrName) lrpName := fmt.Sprintf("%s-%s", lrName, lsName) @@ -41,15 +41,11 @@ func (c *ovnNbClient) CreateGatewayLogicalSwitch(lsName, lrName, provider, ip, m return fmt.Errorf("create localnet logical switch port %s: %v", localnetLspName, err) } - if err := c.CreateLogicalPatchPort(lsName, lrName, lspName, lrpName, ip, mac, chassises...); err != nil { - return err - } - - return nil + return c.CreateLogicalPatchPort(lsName, lrName, lspName, lrpName, ip, mac, chassises...) } // CreateLogicalPatchPort create logical router port and associated logical switch port which type is router -func (c *ovnNbClient) CreateLogicalPatchPort(lsName, lrName, lspName, lrpName, ip, mac string, chassises ...string) error { +func (c *OVNNbClient) CreateLogicalPatchPort(lsName, lrName, lspName, lrpName, ip, mac string, chassises ...string) error { if len(ip) != 0 { // check ip format: 192.168.231.1/24,fc00::0af4:01/112 if err := util.CheckCidrs(ip); err != nil { @@ -68,15 +64,11 @@ func (c *ovnNbClient) CreateLogicalPatchPort(lsName, lrName, lspName, lrpName, i } /* create gateway chassises for logical router port */ - if err = c.CreateGatewayChassises(lrpName, chassises...); err != nil { - return err - } - - return nil + return c.CreateGatewayChassises(lrpName, chassises...) } // DeleteLogicalGatewaySwitch delete gateway switch and corresponding port -func (c *ovnNbClient) DeleteLogicalGatewaySwitch(lsName, lrName string) error { +func (c *OVNNbClient) DeleteLogicalGatewaySwitch(lsName, lrName string) error { lrpName := fmt.Sprintf("%s-%s", lrName, lsName) // all corresponding logical switch port(e.g. localnet port and normal port) will be deleted when delete logical switch @@ -101,7 +93,7 @@ func (c *ovnNbClient) DeleteLogicalGatewaySwitch(lsName, lrName string) error { return nil } -func (c *ovnNbClient) DeleteSecurityGroup(sgName string) error { +func (c *OVNNbClient) DeleteSecurityGroup(sgName string) error { pgName := GetSgPortGroupName(sgName) // clear acl @@ -121,14 +113,10 @@ func (c *ovnNbClient) DeleteSecurityGroup(sgName string) error { } // delete pg - if err := c.DeletePortGroup(pgName); err != nil { - return err - } - - return nil + return c.DeletePortGroup(pgName) } -func (c *ovnNbClient) CreateRouterPortOp(lsName, lrName, lspName, lrpName, ip, mac string) ([]ovsdb.Operation, error) { +func (c *OVNNbClient) CreateRouterPortOp(lsName, lrName, lspName, lrpName, ip, mac string) ([]ovsdb.Operation, error) { /* do nothing if logical switch port exist */ lspExist, err := c.LogicalSwitchPortExists(lspName) if err != nil { @@ -177,7 +165,7 @@ func (c *ovnNbClient) CreateRouterPortOp(lsName, lrName, lspName, lrpName, ip, m } // RemoveLogicalPatchPort delete logical router port and associated logical switch port which type is router -func (c *ovnNbClient) RemoveLogicalPatchPort(lspName, lrpName string) error { +func (c *OVNNbClient) RemoveLogicalPatchPort(lspName, lrpName string) error { /* delete logical switch port*/ lspDelOp, err := c.DeleteLogicalSwitchPortOp(lspName) if err != nil { diff --git a/pkg/ovs/ovn-nb_global.go b/pkg/ovs/ovn-nb_global.go index 96df1836d43..c0944210e1c 100644 --- a/pkg/ovs/ovn-nb_global.go +++ b/pkg/ovs/ovn-nb_global.go @@ -6,11 +6,12 @@ import ( "reflect" "strings" - "github.com/kubeovn/kube-ovn/pkg/ovsdb/ovnnb" "k8s.io/klog/v2" + + "github.com/kubeovn/kube-ovn/pkg/ovsdb/ovnnb" ) -func (c *ovnNbClient) CreateNbGlobal(nbGlobal *ovnnb.NBGlobal) error { +func (c *OVNNbClient) CreateNbGlobal(nbGlobal *ovnnb.NBGlobal) error { op, err := c.ovsDbClient.Create(nbGlobal) if err != nil { return fmt.Errorf("generate operations for creating nb global: %v", err) @@ -19,7 +20,7 @@ func (c *ovnNbClient) CreateNbGlobal(nbGlobal *ovnnb.NBGlobal) error { return c.Transact("nb-global-create", op) } -func (c *ovnNbClient) DeleteNbGlobal() error { +func (c *OVNNbClient) DeleteNbGlobal() error { nbGlobal, err := c.GetNbGlobal() if err != nil { klog.Error(err) @@ -35,7 +36,7 @@ func (c *ovnNbClient) DeleteNbGlobal() error { return c.Transact("nb-global-delete", op) } -func (c *ovnNbClient) GetNbGlobal() (*ovnnb.NBGlobal, error) { +func (c *OVNNbClient) GetNbGlobal() (*ovnnb.NBGlobal, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -45,7 +46,6 @@ func (c *ovnNbClient) GetNbGlobal() (*ovnnb.NBGlobal, error) { err := c.WhereCache(func(config *ovnnb.NBGlobal) bool { return true }).List(ctx, &nbGlobalList) - if err != nil { klog.Error(err) return nil, fmt.Errorf("list nbGlobal: %v", err) @@ -58,7 +58,7 @@ func (c *ovnNbClient) GetNbGlobal() (*ovnnb.NBGlobal, error) { return &nbGlobalList[0], nil } -func (c *ovnNbClient) UpdateNbGlobal(nbGlobal *ovnnb.NBGlobal, fields ...interface{}) error { +func (c *OVNNbClient) UpdateNbGlobal(nbGlobal *ovnnb.NBGlobal, fields ...interface{}) error { op, err := c.Where(nbGlobal).Update(nbGlobal, fields...) if err != nil { return fmt.Errorf("generate operations for updating nb global: %v", err) @@ -71,7 +71,7 @@ func (c *ovnNbClient) UpdateNbGlobal(nbGlobal *ovnnb.NBGlobal, fields ...interfa return nil } -func (c *ovnNbClient) SetAzName(azName string) error { +func (c *OVNNbClient) SetAzName(azName string) error { nbGlobal, err := c.GetNbGlobal() if err != nil { return fmt.Errorf("get nb global: %v", err) @@ -88,7 +88,7 @@ func (c *ovnNbClient) SetAzName(azName string) error { return nil } -func (c *ovnNbClient) SetNbGlobalOptions(key string, value interface{}) error { +func (c *OVNNbClient) SetNbGlobalOptions(key string, value interface{}) error { nbGlobal, err := c.GetNbGlobal() if err != nil { return fmt.Errorf("failed to get nb global: %v", err) @@ -111,11 +111,11 @@ func (c *ovnNbClient) SetNbGlobalOptions(key string, value interface{}) error { return nil } -func (c *ovnNbClient) SetUseCtInvMatch() error { +func (c *OVNNbClient) SetUseCtInvMatch() error { return c.SetNbGlobalOptions("use_ct_inv_match", false) } -func (c *ovnNbClient) SetICAutoRoute(enable bool, blackList []string) error { +func (c *OVNNbClient) SetICAutoRoute(enable bool, blackList []string) error { nbGlobal, err := c.GetNbGlobal() if err != nil { return fmt.Errorf("get nb global: %v", err) @@ -146,10 +146,10 @@ func (c *ovnNbClient) SetICAutoRoute(enable bool, blackList []string) error { return nil } -func (c *ovnNbClient) SetLBCIDR(serviceCIDR string) error { +func (c *OVNNbClient) SetLBCIDR(serviceCIDR string) error { return c.SetNbGlobalOptions("svc_ipv4_cidr", serviceCIDR) } -func (c *ovnNbClient) SetLsDnatModDlDst(enabled bool) error { +func (c *OVNNbClient) SetLsDnatModDlDst(enabled bool) error { return c.SetNbGlobalOptions("ls_dnat_mod_dl_dst", enabled) } diff --git a/pkg/ovs/ovn-nb_test.go b/pkg/ovs/ovn-nb_test.go index 4bfd03d60c0..6f55aafdb35 100644 --- a/pkg/ovs/ovn-nb_test.go +++ b/pkg/ovs/ovn-nb_test.go @@ -175,7 +175,7 @@ func (suite *OvnClientTestSuite) testDeleteSecurityGroup() { }) require.NoError(t, err) - acl, err := ovnClient.newAcl(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) + acl, err := ovnClient.newACL(pgName, ovnnb.ACLDirectionToLport, priority, match, ovnnb.ACLActionAllowRelated) require.NoError(t, err) err = ovnClient.CreateAcls(pgName, portGroupKey, acl) diff --git a/pkg/ovs/ovn-sb-chassis.go b/pkg/ovs/ovn-sb-chassis.go index 55f9ed1e592..599f86a7ed2 100644 --- a/pkg/ovs/ovn-sb-chassis.go +++ b/pkg/ovs/ovn-sb-chassis.go @@ -11,7 +11,7 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -func (c *ovnSbClient) UpdateChassis(chassis *ovnsb.Chassis, fields ...interface{}) error { +func (c *OVNSbClient) UpdateChassis(chassis *ovnsb.Chassis, fields ...interface{}) error { op, err := c.ovsDbClient.Where(chassis).Update(chassis, fields...) if err != nil { err := fmt.Errorf("failed to generate update operations for chassis: %v", err) @@ -27,7 +27,7 @@ func (c *ovnSbClient) UpdateChassis(chassis *ovnsb.Chassis, fields ...interface{ } // DeleteChassis delete one chassis by name -func (c *ovnSbClient) DeleteChassis(chassisName string) error { +func (c *OVNSbClient) DeleteChassis(chassisName string) error { chassis, err := c.GetChassis(chassisName, true) if err != nil { klog.Error(err) @@ -47,7 +47,7 @@ func (c *ovnSbClient) DeleteChassis(chassisName string) error { } // GetChassis return south bound db chassis from cache -func (c *ovnSbClient) GetChassis(chassisName string, ignoreNotFound bool) (*ovnsb.Chassis, error) { +func (c *OVNSbClient) GetChassis(chassisName string, ignoreNotFound bool) (*ovnsb.Chassis, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() if chassisName == "" { @@ -67,7 +67,7 @@ func (c *ovnSbClient) GetChassis(chassisName string, ignoreNotFound bool) (*ovns } // ListChassis return south bound db chassis from cache -func (c *ovnSbClient) ListChassis() (*[]ovnsb.Chassis, error) { +func (c *OVNSbClient) ListChassis() (*[]ovnsb.Chassis, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -78,7 +78,7 @@ func (c *ovnSbClient) ListChassis() (*[]ovnsb.Chassis, error) { return &css, nil } -func (c *ovnSbClient) GetAllChassisByHost(nodeName string) (*[]ovnsb.Chassis, error) { +func (c *OVNSbClient) GetAllChassisByHost(nodeName string) (*[]ovnsb.Chassis, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -101,7 +101,7 @@ func (c *ovnSbClient) GetAllChassisByHost(nodeName string) (*[]ovnsb.Chassis, er return &chassisList, nil } -func (c *ovnSbClient) GetChassisByHost(nodeName string) (*ovnsb.Chassis, error) { +func (c *OVNSbClient) GetChassisByHost(nodeName string) (*ovnsb.Chassis, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -127,7 +127,7 @@ func (c *ovnSbClient) GetChassisByHost(nodeName string) (*ovnsb.Chassis, error) } // DeleteChassisByHost delete all chassis by node name -func (c *ovnSbClient) DeleteChassisByHost(nodeName string) error { +func (c *OVNSbClient) DeleteChassisByHost(nodeName string) error { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() @@ -149,7 +149,7 @@ func (c *ovnSbClient) DeleteChassisByHost(nodeName string) error { return nil } -func (c *ovnSbClient) UpdateChassisTag(chassisName string, nodeName string) error { +func (c *OVNSbClient) UpdateChassisTag(chassisName, nodeName string) error { chassis, err := c.GetChassis(chassisName, true) if err != nil { klog.Error(err) @@ -178,7 +178,7 @@ func (c *ovnSbClient) UpdateChassisTag(chassisName string, nodeName string) erro } // GetKubeOvnChassisses return all chassis which vendor is kube-ovn -func (c *ovnSbClient) GetKubeOvnChassisses() (*[]ovnsb.Chassis, error) { +func (c *OVNSbClient) GetKubeOvnChassisses() (*[]ovnsb.Chassis, error) { ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() diff --git a/pkg/ovs/ovn.go b/pkg/ovs/ovn.go index 84afd459a1c..ce9ed276959 100644 --- a/pkg/ovs/ovn.go +++ b/pkg/ovs/ovn.go @@ -22,12 +22,12 @@ type LegacyClient struct { OvnICSbAddress string } -type ovnNbClient struct { +type OVNNbClient struct { ovsDbClient ClusterRouter string } -type ovnSbClient struct { +type OVNSbClient struct { ovsDbClient } @@ -53,7 +53,7 @@ func NewLegacyClient(timeout int) *LegacyClient { } } -func NewOvnNbClient(ovnNbAddr string, ovnNbTimeout int) (*ovnNbClient, error) { +func NewOvnNbClient(ovnNbAddr string, ovnNbTimeout int) (*OVNNbClient, error) { dbModel, err := ovnnb.FullDatabaseModel() if err != nil { klog.Error(err) @@ -83,7 +83,7 @@ func NewOvnNbClient(ovnNbAddr string, ovnNbTimeout int) (*ovnNbClient, error) { return nil, err } - c := &ovnNbClient{ + c := &OVNNbClient{ ovsDbClient: ovsDbClient{ Client: nbClient, Timeout: time.Duration(ovnNbTimeout) * time.Second, @@ -92,7 +92,7 @@ func NewOvnNbClient(ovnNbAddr string, ovnNbTimeout int) (*ovnNbClient, error) { return c, nil } -func NewOvnSbClient(ovnSbAddr string, ovnSbTimeout int) (*ovnSbClient, error) { +func NewOvnSbClient(ovnSbAddr string, ovnSbTimeout int) (*OVNSbClient, error) { dbModel, err := ovnsb.FullDatabaseModel() if err != nil { klog.Error(err) @@ -101,7 +101,7 @@ func NewOvnSbClient(ovnSbAddr string, ovnSbTimeout int) (*ovnSbClient, error) { monitors := []client.MonitorOption{ client.WithTable(&ovnsb.Chassis{}), - // TODO:// monitor other neccessary tables in ovsdb/ovnsb/model.go + // TODO:// monitor other necessary tables in ovsdb/ovnsb/model.go } sbClient, err := ovsclient.NewOvsDbClient(ovsclient.SBDB, ovnSbAddr, dbModel, monitors) if err != nil { @@ -109,7 +109,7 @@ func NewOvnSbClient(ovnSbAddr string, ovnSbTimeout int) (*ovnSbClient, error) { return nil, err } - c := &ovnSbClient{ + c := &OVNSbClient{ ovsDbClient: ovsDbClient{ Client: sbClient, Timeout: time.Duration(ovnSbTimeout) * time.Second, @@ -120,11 +120,11 @@ func NewOvnSbClient(ovnSbAddr string, ovnSbTimeout int) (*ovnSbClient, error) { // TODO: support ic-nb ic-sb client -func ConstructWaitForNameNotExistsOperation(name string, table string) ovsdb.Operation { +func ConstructWaitForNameNotExistsOperation(name, table string) ovsdb.Operation { return ConstructWaitForUniqueOperation(table, "name", name) } -func ConstructWaitForUniqueOperation(table string, column string, value interface{}) ovsdb.Operation { +func ConstructWaitForUniqueOperation(table, column string, value interface{}) ovsdb.Operation { timeout := OVSDBWaitTimeout return ovsdb.Operation{ Op: ovsdb.OperationWait, diff --git a/pkg/ovs/ovs-vsctl.go b/pkg/ovs/ovs-vsctl.go index 3c0afc15ab5..681e312c0f5 100644 --- a/pkg/ovs/ovs-vsctl.go +++ b/pkg/ovs/ovs-vsctl.go @@ -62,7 +62,7 @@ func ovsSet(table, record string, values ...string) error { return err } -func ovsAdd(table, record string, column string, values ...string) error { +func ovsAdd(table, record, column string, values ...string) error { args := append([]string{"add", table, record, column}, values...) _, err := Exec(args...) return err @@ -174,10 +174,10 @@ func ClearPodBandwidth(podName, podNamespace, ifaceID string) error { return err } - for _, qosId := range qosList { + for _, qosID := range qosList { found := false - for _, usedQosId := range usedQosList { - if qosId == usedQosId { + for _, usedQosID := range usedQosList { + if qosID == usedQosID { found = true break } @@ -186,7 +186,7 @@ func ClearPodBandwidth(podName, podNamespace, ifaceID string) error { continue } - if err := ovsDestroy("qos", qosId); err != nil { + if err := ovsDestroy("qos", qosID); err != nil { return err } } @@ -279,7 +279,7 @@ func GetInterfacePodNs(iface string) (string, error) { } // config mirror for interface by pod annotations and install param -func ConfigInterfaceMirror(globalMirror bool, open string, iface string) error { +func ConfigInterfaceMirror(globalMirror bool, open, iface string) error { if globalMirror { return nil } @@ -300,10 +300,10 @@ func ConfigInterfaceMirror(globalMirror bool, open string, iface string) error { if len(portUUIDs) != 1 { return fmt.Errorf(fmt.Sprintf("find port failed, portName=%s", ifName)) } - portId := portUUIDs[0] + portID := portUUIDs[0] if open == "true" { // add port to mirror - err = ovsAdd("mirror", util.MirrorDefaultName, "select_dst_port", portId) + err = ovsAdd("mirror", util.MirrorDefaultName, "select_dst_port", portID) if err != nil { klog.Error(err) return err @@ -321,9 +321,9 @@ func ConfigInterfaceMirror(globalMirror bool, open string, iface string) error { return fmt.Errorf("repeated mirror data, mirror name=" + util.MirrorDefaultName) } for _, mirrorPortIds := range mirrorPorts { - if strings.Contains(mirrorPortIds, portId) { + if strings.Contains(mirrorPortIds, portID) { // remove port from mirror - _, err := Exec("remove", "mirror", util.MirrorDefaultName, "select_dst_port", portId) + _, err := Exec("remove", "mirror", util.MirrorDefaultName, "select_dst_port", portID) if err != nil { klog.Error(err) return err @@ -393,11 +393,11 @@ func ListExternalIds(table string) (map[string]string, error) { } uuid := strings.TrimSpace(parts[0]) externalIds := strings.Fields(parts[1]) - for _, externalId := range externalIds { - if !strings.Contains(externalId, "iface-id=") { + for _, externalID := range externalIds { + if !strings.Contains(externalID, "iface-id=") { continue } - iface := strings.TrimPrefix(strings.TrimSpace(externalId), "iface-id=") + iface := strings.TrimPrefix(strings.TrimSpace(externalID), "iface-id=") result[iface] = uuid break } @@ -422,12 +422,12 @@ func ListQosQueueIds() (map[string]string, error) { if len(parts) != 2 { continue } - qosId := strings.TrimSpace(parts[0]) + qosID := strings.TrimSpace(parts[0]) if !strings.Contains(strings.TrimSpace(parts[1]), "0=") { continue } - queueId := strings.TrimPrefix(strings.TrimSpace(parts[1]), "0=") - result[qosId] = queueId + queueID := strings.TrimPrefix(strings.TrimSpace(parts[1]), "0=") + result[qosID] = queueID } return result, nil } diff --git a/pkg/ovs/ovs-vsctl_linux.go b/pkg/ovs/ovs-vsctl_linux.go index 89a57d4695e..a6a44f1316c 100644 --- a/pkg/ovs/ovs-vsctl_linux.go +++ b/pkg/ovs/ovs-vsctl_linux.go @@ -21,13 +21,13 @@ func SetInterfaceBandwidth(podName, podNamespace, iface, ingress, egress string) return err } - qosIfaceUidMap, err := ListExternalIds("qos") + qosIfaceUIDMap, err := ListExternalIds("qos") if err != nil { klog.Error(err) return err } - queueIfaceUidMap, err := ListExternalIds("queue") + queueIfaceUIDMap, err := ListExternalIds("queue") if err != nil { klog.Error(err) return err @@ -45,18 +45,18 @@ func SetInterfaceBandwidth(podName, podNamespace, iface, ingress, egress string) egressBPS := egressMPS * 1000 * 1000 if egressBPS > 0 { - queueUid, err := SetHtbQosQueueRecord(podName, podNamespace, iface, egressBPS, queueIfaceUidMap) + queueUID, err := SetHtbQosQueueRecord(podName, podNamespace, iface, egressBPS, queueIfaceUIDMap) if err != nil { klog.Error(err) return err } - if err = SetQosQueueBinding(podName, podNamespace, ifName, iface, queueUid, qosIfaceUidMap); err != nil { + if err = SetQosQueueBinding(podName, podNamespace, ifName, iface, queueUID, qosIfaceUIDMap); err != nil { return err } } else { - if qosUid, ok := qosIfaceUidMap[iface]; ok { - qosType, err := ovsGet("qos", qosUid, "type", "") + if qosUID, ok := qosIfaceUIDMap[iface]; ok { + qosType, err := ovsGet("qos", qosUID, "type", "") if err != nil { klog.Error(err) return err @@ -64,20 +64,20 @@ func SetInterfaceBandwidth(podName, podNamespace, iface, ingress, egress string) if qosType != util.HtbQos { continue } - queueId, err := ovsGet("qos", qosUid, "queues", "0") + queueID, err := ovsGet("qos", qosUID, "queues", "0") if err != nil { klog.Error(err) return err } - if _, err := Exec("remove", "queue", queueId, "other_config", "max-rate"); err != nil { + if _, err := Exec("remove", "queue", queueID, "other_config", "max-rate"); err != nil { return fmt.Errorf("failed to remove rate limit for queue in pod %v/%v, %v", podNamespace, podName, err) } } } // Delete Qos and Queue record if both bandwidth and priority do not exist - if err = CheckAndUpdateHtbQos(podName, podNamespace, iface, queueIfaceUidMap); err != nil { + if err = CheckAndUpdateHtbQos(podName, podNamespace, iface, queueIfaceUIDMap); err != nil { klog.Errorf("failed to check htb qos: %v", err) return err } @@ -109,10 +109,10 @@ func ClearHtbQosQueue(podName, podNamespace, iface string) error { return err } - for _, queueId := range queueList { + for _, queueID := range queueList { found := false - for _, usedQueueId := range qosQueueMap { - if queueId == usedQueueId { + for _, usedQueueID := range qosQueueMap { + if queueID == usedQueueID { found = true break } @@ -121,7 +121,7 @@ func ClearHtbQosQueue(podName, podNamespace, iface string) error { continue } - if err := ovsDestroy("queue", queueId); err != nil { + if err := ovsDestroy("queue", queueID); err != nil { return err } } @@ -141,16 +141,16 @@ func IsHtbQos(iface string) (bool, error) { return false, nil } -func SetHtbQosQueueRecord(podName, podNamespace, iface string, maxRateBPS int, queueIfaceUidMap map[string]string) (string, error) { +func SetHtbQosQueueRecord(podName, podNamespace, iface string, maxRateBPS int, queueIfaceUIDMap map[string]string) (string, error) { var queueCommandValues []string var err error if maxRateBPS > 0 { queueCommandValues = append(queueCommandValues, fmt.Sprintf("other_config:max-rate=%d", maxRateBPS)) } - if queueUid, ok := queueIfaceUidMap[iface]; ok { - if err := ovsSet("queue", queueUid, queueCommandValues...); err != nil { - return queueUid, err + if queueUID, ok := queueIfaceUIDMap[iface]; ok { + if err := ovsSet("queue", queueUID, queueCommandValues...); err != nil { + return queueUID, err } } else { queueCommandValues = append(queueCommandValues, fmt.Sprintf("external-ids:iface-id=%s", iface)) @@ -158,22 +158,22 @@ func SetHtbQosQueueRecord(podName, podNamespace, iface string, maxRateBPS int, q queueCommandValues = append(queueCommandValues, fmt.Sprintf("external-ids:pod=%s/%s", podNamespace, podName)) } - var queueId string - if queueId, err = ovsCreate("queue", queueCommandValues...); err != nil { - return queueUid, err + var queueID string + if queueID, err = ovsCreate("queue", queueCommandValues...); err != nil { + return queueUID, err } - queueIfaceUidMap[iface] = queueId + queueIfaceUIDMap[iface] = queueID } - return queueIfaceUidMap[iface], nil + return queueIfaceUIDMap[iface], nil } // SetQosQueueBinding set qos related to queue record. -func SetQosQueueBinding(podName, podNamespace, ifName, iface, queueUid string, qosIfaceUidMap map[string]string) error { +func SetQosQueueBinding(podName, podNamespace, ifName, iface, queueUID string, qosIfaceUIDMap map[string]string) error { var qosCommandValues []string - qosCommandValues = append(qosCommandValues, fmt.Sprintf("queues:0=%s", queueUid)) + qosCommandValues = append(qosCommandValues, fmt.Sprintf("queues:0=%s", queueUID)) - if qosUid, ok := qosIfaceUidMap[iface]; !ok { + if qosUID, ok := qosIfaceUIDMap[iface]; !ok { qosCommandValues = append(qosCommandValues, "type=linux-htb", fmt.Sprintf(`external-ids:iface-id="%s"`, iface)) if podNamespace != "" && podName != "" { qosCommandValues = append(qosCommandValues, fmt.Sprintf("external-ids:pod=%s/%s", podNamespace, podName)) @@ -188,9 +188,9 @@ func SetQosQueueBinding(podName, podNamespace, ifName, iface, queueUid string, q klog.Error(err) return err } - qosIfaceUidMap[iface] = qos + qosIfaceUIDMap[iface] = qos } else { - qosType, err := ovsGet("qos", qosUid, "type", "") + qosType, err := ovsGet("qos", qosUID, "type", "") if err != nil { klog.Error(err) return err @@ -201,17 +201,17 @@ func SetQosQueueBinding(podName, podNamespace, ifName, iface, queueUid string, q } if qosType == util.HtbQos { - queueId, err := ovsGet("qos", qosUid, "queues", "0") + queueID, err := ovsGet("qos", qosUID, "queues", "0") if err != nil { klog.Error(err) return err } - if queueId == queueUid { + if queueID == queueUID { return nil } } - if err := ovsSet("qos", qosUid, qosCommandValues...); err != nil { + if err := ovsSet("qos", qosUID, qosCommandValues...); err != nil { return err } } @@ -294,7 +294,7 @@ func SetNetemQos(podName, podNamespace, iface, latency, limit, loss, jitter stri continue } - if err = deleteNetemQosById(qos, iface, podName, podNamespace); err != nil { + if err = deleteNetemQosByID(qos, iface, podName, podNamespace); err != nil { klog.Errorf("failed to delete netem qos: %v", err) return err } @@ -318,7 +318,7 @@ func SetNetemQos(podName, podNamespace, iface, latency, limit, loss, jitter stri } } else { for _, qos := range qosList { - if err := deleteNetemQosById(qos, iface, podName, podNamespace); err != nil { + if err := deleteNetemQosByID(qos, iface, podName, podNamespace); err != nil { klog.Errorf("failed to delete netem qos: %v", err) return err } @@ -328,12 +328,12 @@ func SetNetemQos(podName, podNamespace, iface, latency, limit, loss, jitter stri return nil } -func getNetemQosConfig(qosId string) (string, string, string, string, error) { +func getNetemQosConfig(qosID string) (string, string, string, string, error) { var latency, loss, limit, jitter string - config, err := ovsGet("qos", qosId, "other_config", "") + config, err := ovsGet("qos", qosID, "other_config", "") if err != nil { - klog.Errorf("failed to get other_config for qos %s: %v", qosId, err) + klog.Errorf("failed to get other_config for qos %s: %v", qosID, err) return latency, loss, limit, jitter, err } if len(config) == 0 { @@ -357,8 +357,8 @@ func getNetemQosConfig(qosId string) (string, string, string, string, error) { return latency, loss, limit, jitter, nil } -func deleteNetemQosById(qosId, iface, podName, podNamespace string) error { - qosType, _ := ovsGet("qos", qosId, "type", "") +func deleteNetemQosByID(qosID, iface, podName, podNamespace string) error { + qosType, _ := ovsGet("qos", qosID, "type", "") if qosType != util.NetemQos { return nil } @@ -385,16 +385,16 @@ func IsUserspaceDataPath() (is bool, err error) { return len(dp) > 0 && dp[0] == "netdev", nil } -func CheckAndUpdateHtbQos(podName, podNamespace, ifaceID string, queueIfaceUidMap map[string]string) error { - var queueUid string +func CheckAndUpdateHtbQos(podName, podNamespace, ifaceID string, queueIfaceUIDMap map[string]string) error { + var queueUID string var ok bool - if queueUid, ok = queueIfaceUidMap[ifaceID]; !ok { + if queueUID, ok = queueIfaceUIDMap[ifaceID]; !ok { return nil } - config, err := ovsGet("queue", queueUid, "other_config", "") + config, err := ovsGet("queue", queueUID, "other_config", "") if err != nil { - klog.Errorf("failed to get other_config for queueId %s: %v", queueUid, err) + klog.Errorf("failed to get other_config for queueID %s: %v", queueUID, err) return err } // bandwidth or priority exists, can not delete qos diff --git a/pkg/ovs/ovs-vsctl_windows.go b/pkg/ovs/ovs-vsctl_windows.go index 501c6007c66..22d738bb208 100644 --- a/pkg/ovs/ovs-vsctl_windows.go +++ b/pkg/ovs/ovs-vsctl_windows.go @@ -8,7 +8,7 @@ func SetInterfaceBandwidth(podName, podNamespace, iface, ingress, egress string) } func ClearHtbQosQueue(podName, podNamespace, iface string) error { - //TODO + // TODO return nil } @@ -17,13 +17,13 @@ func IsHtbQos(iface string) (bool, error) { return false, nil } -func SetHtbQosQueueRecord(podName, podNamespace, iface, priority string, maxRateBPS int, queueIfaceUidMap map[string]string) (string, error) { - //TODO +func SetHtbQosQueueRecord(podName, podNamespace, iface, priority string, maxRateBPS int, queueIfaceUIDMap map[string]string) (string, error) { + // TODO return "", nil } // SetQosQueueBinding set qos related to queue record. -func SetQosQueueBinding(podName, podNamespace, ifName, iface, queueUid string, qosIfaceUidMap map[string]string) error { +func SetQosQueueBinding(podName, podNamespace, ifName, iface, queueUID string, qosIfaceUIDMap map[string]string) error { // TODO return nil } diff --git a/pkg/ovs/util.go b/pkg/ovs/util.go index 1fc90b8011e..43cd59a920e 100644 --- a/pkg/ovs/util.go +++ b/pkg/ovs/util.go @@ -37,15 +37,15 @@ func LogicalSwitchPortName(lr, ls string) string { } func GetSgPortGroupName(sgName string) string { - return strings.Replace(fmt.Sprintf("ovn.sg.%s", sgName), "-", ".", -1) + return strings.ReplaceAll(fmt.Sprintf("ovn.sg.%s", sgName), "-", ".") } func GetSgV4AssociatedName(sgName string) string { - return strings.Replace(fmt.Sprintf("ovn.sg.%s.associated.v4", sgName), "-", ".", -1) + return strings.ReplaceAll(fmt.Sprintf("ovn.sg.%s.associated.v4", sgName), "-", ".") } func GetSgV6AssociatedName(sgName string) string { - return strings.Replace(fmt.Sprintf("ovn.sg.%s.associated.v6", sgName), "-", ".", -1) + return strings.ReplaceAll(fmt.Sprintf("ovn.sg.%s.associated.v6", sgName), "-", ".") } // parseIpv6RaConfigs parses the ipv6 ra config, @@ -120,23 +120,23 @@ func matchAddressSetName(asName string) bool { return addressSetNameRegex.MatchString(asName) } -type AclMatch interface { +type ACLMatch interface { Match() (string, error) String() string } -type AndAclMatch struct { - matches []AclMatch +type AndACLMatch struct { + matches []ACLMatch } -func NewAndAclMatch(matches ...AclMatch) AclMatch { - return AndAclMatch{ +func NewAndACLMatch(matches ...ACLMatch) ACLMatch { + return AndACLMatch{ matches: matches, } } // Rule generate acl match like 'ip4.src == $test.allow.as && ip4.src != $test.except.as && 12345 <= tcp.dst <= 12500 && outport == @ovn.sg.test_sg && ip' -func (m AndAclMatch) Match() (string, error) { +func (m AndACLMatch) Match() (string, error) { var matches []string for _, r := range m.matches { match, err := r.Match() @@ -149,23 +149,23 @@ func (m AndAclMatch) Match() (string, error) { return strings.Join(matches, " && "), nil } -func (m AndAclMatch) String() string { +func (m AndACLMatch) String() string { match, _ := m.Match() return match } -type OrAclMatch struct { - matches []AclMatch +type OrACLMatch struct { + matches []ACLMatch } -func NewOrAclMatch(matches ...AclMatch) AclMatch { - return OrAclMatch{ +func NewOrACLMatch(matches ...ACLMatch) ACLMatch { + return OrACLMatch{ matches: matches, } } // Match generate acl match like '(ip4.src==10.250.0.0/16 && ip4.dst==10.244.0.0/16) || (ip4.src==10.244.0.0/16 && ip4.dst==10.250.0.0/16)' -func (m OrAclMatch) Match() (string, error) { +func (m OrACLMatch) Match() (string, error) { var matches []string for _, specification := range m.matches { match, err := specification.Match() @@ -184,7 +184,7 @@ func (m OrAclMatch) Match() (string, error) { return strings.Join(matches, " || "), nil } -func (m OrAclMatch) String() string { +func (m OrACLMatch) String() string { match, _ := m.Match() return match } @@ -196,7 +196,7 @@ type aclMatch struct { effect string } -func NewAclMatch(key, effect, value, maxValue string) AclMatch { +func NewACLMatch(key, effect, value, maxValue string) ACLMatch { return aclMatch{ key: key, effect: effect, diff --git a/pkg/ovs/util_test.go b/pkg/ovs/util_test.go index 1fdbd123e3f..0fd0c57e9e2 100644 --- a/pkg/ovs/util_test.go +++ b/pkg/ovs/util_test.go @@ -102,12 +102,12 @@ func Test_aclMatch_Match(t *testing.T) { t.Run("generate rule like 'ip4.src == $test.allow.as'", func(t *testing.T) { t.Parallel() - match := NewAclMatch("ip4.dst", "==", "$test.allow.as", "") + match := NewACLMatch("ip4.dst", "==", "$test.allow.as", "") rule, err := match.Match() require.NoError(t, err) require.Equal(t, "ip4.dst == $test.allow.as", rule) - match = NewAclMatch("ip4.dst", "!=", "$test.allow.as", "") + match = NewACLMatch("ip4.dst", "!=", "$test.allow.as", "") rule, err = match.Match() require.NoError(t, err) require.Equal(t, "ip4.dst != $test.allow.as", rule) @@ -116,7 +116,7 @@ func Test_aclMatch_Match(t *testing.T) { t.Run("generate acl match rule like 'ip'", func(t *testing.T) { t.Parallel() - match := NewAclMatch("ip", "==", "", "") + match := NewACLMatch("ip", "==", "", "") rule, err := match.Match() require.NoError(t, err) @@ -126,7 +126,7 @@ func Test_aclMatch_Match(t *testing.T) { t.Run("generate rule like '12345 <= tcp.dst <= 12500'", func(t *testing.T) { t.Parallel() - match := NewAclMatch("tcp.dst", "<=", "12345", "12500") + match := NewACLMatch("tcp.dst", "<=", "12345", "12500") rule, err := match.Match() require.NoError(t, err) require.Equal(t, "12345 <= tcp.dst <= 12500", rule) @@ -135,8 +135,8 @@ func Test_aclMatch_Match(t *testing.T) { t.Run("err occurred when key is empty", func(t *testing.T) { t.Parallel() - match := NewAndAclMatch( - NewAclMatch("", "", "", ""), + match := NewAndACLMatch( + NewACLMatch("", "", "", ""), ) _, err := match.Match() @@ -151,12 +151,12 @@ func Test_AndAclMatch_Match(t *testing.T) { t.Parallel() /* match several tcp port traffic */ - match := NewAndAclMatch( - NewAclMatch("inport", "==", "@ovn.sg.test_sg", ""), - NewAclMatch("ip", "", "", ""), - NewAclMatch("ip4.dst", "==", "$test.allow.as", ""), - NewAclMatch("ip4.dst", "!=", "$test.except.as", ""), - NewAclMatch("tcp.dst", "<=", "12345", "12500"), + match := NewAndACLMatch( + NewACLMatch("inport", "==", "@ovn.sg.test_sg", ""), + NewACLMatch("ip", "", "", ""), + NewACLMatch("ip4.dst", "==", "$test.allow.as", ""), + NewACLMatch("ip4.dst", "!=", "$test.except.as", ""), + NewACLMatch("tcp.dst", "<=", "12345", "12500"), ) rule, err := match.Match() @@ -167,8 +167,8 @@ func Test_AndAclMatch_Match(t *testing.T) { t.Run("err occurred when key is empty", func(t *testing.T) { t.Parallel() - match := NewAndAclMatch( - NewAclMatch("", "", "", ""), + match := NewAndACLMatch( + NewACLMatch("", "", "", ""), ) _, err := match.Match() @@ -183,14 +183,14 @@ func Test_OrAclMatch_Match(t *testing.T) { t.Parallel() /* match several tcp port traffic */ - match := NewOrAclMatch( - NewAndAclMatch( - NewAclMatch("ip4.src", "==", "10.250.0.0/16", ""), + match := NewOrACLMatch( + NewAndACLMatch( + NewACLMatch("ip4.src", "==", "10.250.0.0/16", ""), ), - NewAndAclMatch( - NewAclMatch("ip4.src", "==", "10.244.0.0/16", ""), + NewAndACLMatch( + NewACLMatch("ip4.src", "==", "10.244.0.0/16", ""), ), - NewAclMatch("ip4.src", "==", "10.260.0.0/16", ""), + NewACLMatch("ip4.src", "==", "10.260.0.0/16", ""), ) rule, err := match.Match() @@ -202,14 +202,14 @@ func Test_OrAclMatch_Match(t *testing.T) { t.Parallel() /* match several tcp port traffic */ - match := NewOrAclMatch( - NewAndAclMatch( - NewAclMatch("ip4.src", "==", "10.250.0.0/16", ""), - NewAclMatch("ip4.dst", "==", "10.244.0.0/16", ""), + match := NewOrACLMatch( + NewAndACLMatch( + NewACLMatch("ip4.src", "==", "10.250.0.0/16", ""), + NewACLMatch("ip4.dst", "==", "10.244.0.0/16", ""), ), - NewAndAclMatch( - NewAclMatch("ip4.src", "==", "10.244.0.0/16", ""), - NewAclMatch("ip4.dst", "==", "10.250.0.0/16", ""), + NewAndACLMatch( + NewACLMatch("ip4.src", "==", "10.244.0.0/16", ""), + NewACLMatch("ip4.dst", "==", "10.250.0.0/16", ""), ), ) @@ -221,8 +221,8 @@ func Test_OrAclMatch_Match(t *testing.T) { t.Run("err occurred when key is empty", func(t *testing.T) { t.Parallel() - match := NewAndAclMatch( - NewAclMatch("", "", "", ""), + match := NewAndACLMatch( + NewACLMatch("", "", "", ""), ) _, err := match.Match() diff --git a/pkg/ovsdb/ovnnb/meter_band.go b/pkg/ovsdb/ovnnb/meter_band.go index 19f8b0d3ba8..a687046072f 100644 --- a/pkg/ovsdb/ovnnb/meter_band.go +++ b/pkg/ovsdb/ovnnb/meter_band.go @@ -9,9 +9,7 @@ type ( MeterBandAction = string ) -var ( - MeterBandActionDrop MeterBandAction = "drop" -) +var MeterBandActionDrop MeterBandAction = "drop" // MeterBand defines an object in Meter_Band table type MeterBand struct { diff --git a/pkg/ovsdb/ovnsb/controller_event.go b/pkg/ovsdb/ovnsb/controller_event.go index d358d0a3055..f369b162b51 100644 --- a/pkg/ovsdb/ovnsb/controller_event.go +++ b/pkg/ovsdb/ovnsb/controller_event.go @@ -9,9 +9,7 @@ type ( ControllerEventEventType = string ) -var ( - ControllerEventEventTypeEmptyLbBackends ControllerEventEventType = "empty_lb_backends" -) +var ControllerEventEventTypeEmptyLbBackends ControllerEventEventType = "empty_lb_backends" // ControllerEvent defines an object in Controller_Event table type ControllerEvent struct { diff --git a/pkg/ovsdb/ovnsb/meter_band.go b/pkg/ovsdb/ovnsb/meter_band.go index 58d1426a1aa..b0ea8d96ccb 100644 --- a/pkg/ovsdb/ovnsb/meter_band.go +++ b/pkg/ovsdb/ovnsb/meter_band.go @@ -9,9 +9,7 @@ type ( MeterBandAction = string ) -var ( - MeterBandActionDrop MeterBandAction = "drop" -) +var MeterBandActionDrop MeterBandAction = "drop" // MeterBand defines an object in Meter_Band table type MeterBand struct { diff --git a/pkg/pinger/config.go b/pkg/pinger/config.go index e1d3b1d3b2f..f876f56e36e 100644 --- a/pkg/pinger/config.go +++ b/pkg/pinger/config.go @@ -70,8 +70,8 @@ func ParseFlags() (*Configuration, error) { argInterval = pflag.Int("interval", 5, "interval seconds between consecutive pings") argMode = pflag.String("mode", "server", "server or job Mode") argExitCode = pflag.Int("exit-code", 0, "exit code when failure happens") - argInternalDns = pflag.String("internal-dns", "kubernetes.default", "check dns from pod") - argExternalDns = pflag.String("external-dns", "", "check external dns resolve from pod") + argInternalDNS = pflag.String("internal-dns", "kubernetes.default", "check dns from pod") + argExternalDNS = pflag.String("external-dns", "", "check external dns resolve from pod") argExternalAddress = pflag.String("external-address", "", "check ping connection to an external address, default: 114.114.114.114") argTargetIPPorts = pflag.String("target-ip-ports", "", "target protocol ip and port, eg: 'tcp-169.254.1.1-8080,udp-169.254.2.2-8081'") argNetworkMode = pflag.String("network-mode", "kube-ovn", "The cni plugin current cluster used, default: kube-ovn") @@ -119,8 +119,8 @@ func ParseFlags() (*Configuration, error) { Interval: *argInterval, Mode: *argMode, ExitCode: *argExitCode, - InternalDNS: *argInternalDns, - ExternalDNS: *argExternalDns, + InternalDNS: *argInternalDNS, + ExternalDNS: *argExternalDNS, PodIP: os.Getenv("POD_IP"), HostIP: os.Getenv("HOST_IP"), NodeName: os.Getenv("NODE_NAME"), diff --git a/pkg/pinger/metrics.go b/pkg/pinger/metrics.go index 52192784439..eef0fe1be6f 100644 --- a/pkg/pinger/metrics.go +++ b/pkg/pinger/metrics.go @@ -68,7 +68,7 @@ var ( []string{ "nodeName", }) - internalDnsHealthyGauge = prometheus.NewGaugeVec( + internalDNSHealthyGauge = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Name: "pinger_internal_dns_healthy", Help: "If the internal dns request is healthy on this node", @@ -76,7 +76,7 @@ var ( []string{ "nodeName", }) - internalDnsUnhealthyGauge = prometheus.NewGaugeVec( + internalDNSUnhealthyGauge = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Name: "pinger_internal_dns_unhealthy", Help: "If the internal dns request is unhealthy on this node", @@ -84,7 +84,7 @@ var ( []string{ "nodeName", }) - internalDnsRequestLatencyHistogram = prometheus.NewHistogramVec( + internalDNSRequestLatencyHistogram = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "pinger_internal_dns_latency_ms", Help: "The latency ms histogram the node request internal dns", @@ -93,7 +93,7 @@ var ( []string{ "nodeName", }) - externalDnsHealthyGauge = prometheus.NewGaugeVec( + externalDNSHealthyGauge = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Name: "pinger_external_dns_healthy", Help: "If the external dns request is healthy on this node", @@ -101,7 +101,7 @@ var ( []string{ "nodeName", }) - externalDnsUnhealthyGauge = prometheus.NewGaugeVec( + externalDNSUnhealthyGauge = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Name: "pinger_external_dns_unhealthy", Help: "If the external dns request is unhealthy on this node", @@ -109,7 +109,7 @@ var ( []string{ "nodeName", }) - externalDnsRequestLatencyHistogram = prometheus.NewHistogramVec( + externalDNSRequestLatencyHistogram = prometheus.NewHistogramVec( prometheus.HistogramOpts{ Name: "pinger_external_dns_latency_ms", Help: "The latency ms histogram the node request external dns", @@ -647,12 +647,12 @@ func InitPingerMetrics() { prometheus.MustRegister(apiserverHealthyGauge) prometheus.MustRegister(apiserverUnhealthyGauge) prometheus.MustRegister(apiserverRequestLatencyHistogram) - prometheus.MustRegister(internalDnsHealthyGauge) - prometheus.MustRegister(internalDnsUnhealthyGauge) - prometheus.MustRegister(internalDnsRequestLatencyHistogram) - prometheus.MustRegister(externalDnsHealthyGauge) - prometheus.MustRegister(externalDnsUnhealthyGauge) - prometheus.MustRegister(externalDnsRequestLatencyHistogram) + prometheus.MustRegister(internalDNSHealthyGauge) + prometheus.MustRegister(internalDNSUnhealthyGauge) + prometheus.MustRegister(internalDNSRequestLatencyHistogram) + prometheus.MustRegister(externalDNSHealthyGauge) + prometheus.MustRegister(externalDNSUnhealthyGauge) + prometheus.MustRegister(externalDNSRequestLatencyHistogram) prometheus.MustRegister(podPingLatencyHistogram) prometheus.MustRegister(podPingLostCounter) prometheus.MustRegister(podPingTotalCounter) @@ -739,26 +739,26 @@ func SetApiserverUnhealthyMetrics(nodeName string) { apiserverUnhealthyGauge.WithLabelValues(nodeName).Set(1) } -func SetInternalDnsHealthyMetrics(nodeName string, latency float64) { - internalDnsHealthyGauge.WithLabelValues(nodeName).Set(1) - internalDnsRequestLatencyHistogram.WithLabelValues(nodeName).Observe(latency) - internalDnsUnhealthyGauge.WithLabelValues(nodeName).Set(0) +func SetInternalDNSHealthyMetrics(nodeName string, latency float64) { + internalDNSHealthyGauge.WithLabelValues(nodeName).Set(1) + internalDNSRequestLatencyHistogram.WithLabelValues(nodeName).Observe(latency) + internalDNSUnhealthyGauge.WithLabelValues(nodeName).Set(0) } -func SetInternalDnsUnhealthyMetrics(nodeName string) { - internalDnsHealthyGauge.WithLabelValues(nodeName).Set(0) - internalDnsUnhealthyGauge.WithLabelValues(nodeName).Set(1) +func SetInternalDNSUnhealthyMetrics(nodeName string) { + internalDNSHealthyGauge.WithLabelValues(nodeName).Set(0) + internalDNSUnhealthyGauge.WithLabelValues(nodeName).Set(1) } -func SetExternalDnsHealthyMetrics(nodeName string, latency float64) { - externalDnsHealthyGauge.WithLabelValues(nodeName).Set(1) - externalDnsRequestLatencyHistogram.WithLabelValues(nodeName).Observe(latency) - externalDnsUnhealthyGauge.WithLabelValues(nodeName).Set(0) +func SetExternalDNSHealthyMetrics(nodeName string, latency float64) { + externalDNSHealthyGauge.WithLabelValues(nodeName).Set(1) + externalDNSRequestLatencyHistogram.WithLabelValues(nodeName).Observe(latency) + externalDNSUnhealthyGauge.WithLabelValues(nodeName).Set(0) } -func SetExternalDnsUnhealthyMetrics(nodeName string) { - externalDnsHealthyGauge.WithLabelValues(nodeName).Set(0) - externalDnsUnhealthyGauge.WithLabelValues(nodeName).Set(1) +func SetExternalDNSUnhealthyMetrics(nodeName string) { + externalDNSHealthyGauge.WithLabelValues(nodeName).Set(0) + externalDNSUnhealthyGauge.WithLabelValues(nodeName).Set(1) } func SetPodPingMetrics(srcNodeName, srcNodeIP, srcPodIP, targetNodeName, targetNodeIP, targetPodIP string, latency float64, lost, total int) { diff --git a/pkg/pinger/ovn.go b/pkg/pinger/ovn.go index 3c3f50dec25..23255da627d 100644 --- a/pkg/pinger/ovn.go +++ b/pkg/pinger/ovn.go @@ -59,10 +59,10 @@ func checkPortBindings(config *Configuration) error { klog.Errorf("%d port %v not exist in sb-bindings", len(misMatch), misMatch) inconsistentPortBindingGauge.WithLabelValues(config.NodeName).Set(float64(len(misMatch))) return fmt.Errorf("%d port %v not exist in sb-bindings", len(misMatch), misMatch) - } else { - klog.Infof("ovs and ovn-sb binding check passed") - inconsistentPortBindingGauge.WithLabelValues(config.NodeName).Set(0) } + + klog.Infof("ovs and ovn-sb binding check passed") + inconsistentPortBindingGauge.WithLabelValues(config.NodeName).Set(0) return nil } @@ -144,7 +144,8 @@ func checkSBBindings(config *Configuration) ([]string, error) { "--timeout=10", "find", "port_binding", - fmt.Sprintf("chassis=%s", chassis)} + fmt.Sprintf("chassis=%s", chassis), + } if os.Getenv("ENABLE_SSL") == "true" { command = []string{ "-p", "/var/run/tls/key", diff --git a/pkg/pinger/ping.go b/pkg/pinger/ping.go index 64452e3a0a4..9a211056ef2 100644 --- a/pkg/pinger/ping.go +++ b/pkg/pinger/ping.go @@ -50,7 +50,7 @@ func StartPinger(config *Configuration, e *Exporter) { func ping(config *Configuration) error { errHappens := false - if checkApiServer(config) != nil { + if checkAPIServer(config) != nil { errHappens = true } if pingPods(config) != nil { @@ -169,24 +169,24 @@ func pingPods(config *Configuration) error { for _, pod := range pods.Items { for _, podIP := range pod.Status.PodIPs { if util.ContainsString(config.PodProtocols, util.CheckProtocol(podIP.IP)) { - func(podIp, podName, nodeIP, nodeName string) { + func(podIP, podName, nodeIP, nodeName string) { if config.EnableVerboseConnCheck { - if err := util.TCPConnectivityCheck(fmt.Sprintf("%s:%d", podIp, config.TCPConnCheckPort)); err != nil { - klog.Infof("TCP connectivity to pod %s %s failed", podName, podIp) + if err := util.TCPConnectivityCheck(fmt.Sprintf("%s:%d", podIP, config.TCPConnCheckPort)); err != nil { + klog.Infof("TCP connectivity to pod %s %s failed", podName, podIP) pingErr = err } else { - klog.Infof("TCP connectivity to pod %s %s success", podName, podIp) + klog.Infof("TCP connectivity to pod %s %s success", podName, podIP) } - if err := util.UDPConnectivityCheck(fmt.Sprintf("%s:%d", podIp, config.UDPConnCheckPort)); err != nil { - klog.Infof("UDP connectivity to pod %s %s failed", podName, podIp) + if err := util.UDPConnectivityCheck(fmt.Sprintf("%s:%d", podIP, config.UDPConnCheckPort)); err != nil { + klog.Infof("UDP connectivity to pod %s %s failed", podName, podIP) pingErr = err } else { - klog.Infof("UDP connectivity to pod %s %s success", podName, podIp) + klog.Infof("UDP connectivity to pod %s %s success", podName, podIP) } } - pinger, err := goping.NewPinger(podIp) + pinger, err := goping.NewPinger(podIP) if err != nil { klog.Errorf("failed to init pinger, %v", err) pingErr = err @@ -198,14 +198,14 @@ func pingPods(config *Configuration) error { pinger.Count = 3 pinger.Interval = 1 * time.Millisecond if err = pinger.Run(); err != nil { - klog.Errorf("failed to run pinger for destination %s: %v", podIp, err) + klog.Errorf("failed to run pinger for destination %s: %v", podIP, err) pingErr = err return } stats := pinger.Statistics() klog.Infof("ping pod: %s %s, count: %d, loss count %d, average rtt %.2fms", - podName, podIp, pinger.Count, int(math.Abs(float64(stats.PacketsSent-stats.PacketsRecv))), float64(stats.AvgRtt)/float64(time.Millisecond)) + podName, podIP, pinger.Count, int(math.Abs(float64(stats.PacketsSent-stats.PacketsRecv))), float64(stats.AvgRtt)/float64(time.Millisecond)) if int(math.Abs(float64(stats.PacketsSent-stats.PacketsRecv))) != 0 { pingErr = fmt.Errorf("ping failed") } @@ -215,7 +215,7 @@ func pingPods(config *Configuration) error { config.PodName, nodeName, nodeIP, - podIp, + podIP, float64(stats.AvgRtt)/float64(time.Millisecond), int(math.Abs(float64(stats.PacketsSent-stats.PacketsRecv))), int(float64(stats.PacketsSent))) @@ -295,27 +295,27 @@ func checkAccessTargetIPPorts(config *Configuration) error { addr = fmt.Sprintf("[%s]", addr) } - if proto == util.ProtocolTCP { + switch proto { + case util.ProtocolTCP: if err := util.TCPConnectivityCheck(fmt.Sprintf("%s:%s", addr, port)); err != nil { klog.Infof("TCP connectivity to targetIPPort %s:%s failed", addr, port) checkErr = err } else { klog.Infof("TCP connectivity to targetIPPort %s:%s success", addr, port) } - } else if proto == util.ProtocolUDP { + case util.ProtocolUDP: if err := util.UDPConnectivityCheck(fmt.Sprintf("%s:%s", addr, port)); err != nil { klog.Infof("UDP connectivity to target %s:%s failed", addr, port) checkErr = err } else { klog.Infof("UDP connectivity to target %s:%s success", addr, port) } - } else { + default: klog.Infof("unrecognized protocol %s", proto) continue } } return checkErr - } func internalNslookup(config *Configuration) error { @@ -328,10 +328,10 @@ func internalNslookup(config *Configuration) error { elapsed := time.Since(t1) if err != nil { klog.Errorf("failed to resolve dns %s, %v", config.InternalDNS, err) - SetInternalDnsUnhealthyMetrics(config.NodeName) + SetInternalDNSUnhealthyMetrics(config.NodeName) return err } - SetInternalDnsHealthyMetrics(config.NodeName, float64(elapsed)/float64(time.Millisecond)) + SetInternalDNSHealthyMetrics(config.NodeName, float64(elapsed)/float64(time.Millisecond)) klog.Infof("resolve dns %s to %v in %.2fms", config.InternalDNS, addrs, float64(elapsed)/float64(time.Millisecond)) return nil } @@ -346,15 +346,15 @@ func externalNslookup(config *Configuration) error { elapsed := time.Since(t1) if err != nil { klog.Errorf("failed to resolve dns %s, %v", config.ExternalDNS, err) - SetExternalDnsUnhealthyMetrics(config.NodeName) + SetExternalDNSUnhealthyMetrics(config.NodeName) return err } - SetExternalDnsHealthyMetrics(config.NodeName, float64(elapsed)/float64(time.Millisecond)) + SetExternalDNSHealthyMetrics(config.NodeName, float64(elapsed)/float64(time.Millisecond)) klog.Infof("resolve dns %s to %v in %.2fms", config.ExternalDNS, addrs, float64(elapsed)/float64(time.Millisecond)) return nil } -func checkApiServer(config *Configuration) error { +func checkAPIServer(config *Configuration) error { klog.Infof("start to check apiserver connectivity") t1 := time.Now() _, err := config.KubeClient.Discovery().ServerVersion() diff --git a/pkg/pinger/util.go b/pkg/pinger/util.go index 2d6ecdf287b..60ccb59bca2 100644 --- a/pkg/pinger/util.go +++ b/pkg/pinger/util.go @@ -76,14 +76,15 @@ func (e *Exporter) setOvsDpIfMetric(datapathName string) error { var datapathPortCount float64 for _, kvPair := range strings.Split(string(output), "\n") { line := strings.TrimSpace(kvPair) - if strings.HasPrefix(line, "lookups:") { + switch { + case strings.HasPrefix(line, "lookups:"): e.ovsDatapathLookupsMetrics(line, datapathName) - } else if strings.HasPrefix(line, "masks:") { + case strings.HasPrefix(line, "masks:"): e.ovsDatapathMasksMetrics(line, datapathName) - } else if strings.HasPrefix(line, "port ") { + case strings.HasPrefix(line, "port "): e.ovsDatapathPortMetrics(line, datapathName) datapathPortCount++ - } else if strings.HasPrefix(line, "flows:") { + case strings.HasPrefix(line, "flows:"): flowFields := strings.Fields(line) value, _ := strconv.ParseFloat(flowFields[1], 64) metricOvsDpFlowsTotal.WithLabelValues(e.Client.System.Hostname, datapathName).Set(value) diff --git a/pkg/request/cniserver.go b/pkg/request/cniserver.go index f1baeabf76c..20ce903a66d 100644 --- a/pkg/request/cniserver.go +++ b/pkg/request/cniserver.go @@ -41,7 +41,7 @@ type CniRequest struct { // CniResponse is the cniserver response format type CniResponse struct { Protocol string `json:"protocol"` - IpAddress string `json:"address"` + IPAddress string `json:"address"` MacAddress string `json:"mac_address"` CIDR string `json:"cidr"` Gateway string `json:"gateway"` diff --git a/pkg/speaker/config.go b/pkg/speaker/config.go index 354f1fa6fd0..48f90cedb52 100644 --- a/pkg/speaker/config.go +++ b/pkg/speaker/config.go @@ -38,7 +38,7 @@ type Configuration struct { GrpcHost string GrpcPort uint32 ClusterAs uint32 - RouterId string + RouterID string NeighborAddress string NeighborIPv6Address string NeighborAs uint32 @@ -50,7 +50,7 @@ type Configuration struct { GracefulRestartDeferralTime time.Duration GracefulRestartTime time.Duration PassiveMode bool - EbgpMultihopTtl uint8 + EbgpMultihopTTL uint8 KubeConfigFile string KubeClient kubernetes.Interface @@ -68,7 +68,7 @@ func ParseFlags() (*Configuration, error) { argGrpcHost = pflag.String("grpc-host", "127.0.0.1", "The host address for grpc to listen, default: 127.0.0.1") argGrpcPort = pflag.Uint32("grpc-port", DefaultBGPGrpcPort, "The port for grpc to listen, default:50051") argClusterAs = pflag.Uint32("cluster-as", DefaultBGPClusterAs, "The as number of container network, default 65000") - argRouterId = pflag.String("router-id", "", "The address for the speaker to use as router id, default the node ip") + argRouterID = pflag.String("router-id", "", "The address for the speaker to use as router id, default the node ip") argNeighborAddress = pflag.String("neighbor-address", "", "The router address the speaker connects to.") argNeighborIPv6Address = pflag.String("neighbor-ipv6-address", "", "The router address the speaker connects to.") argNeighborAs = pflag.Uint32("neighbor-as", DefaultBGPNeighborAs, "The router as number, default 65001") @@ -77,7 +77,7 @@ func ParseFlags() (*Configuration, error) { argPprofPort = pflag.Uint32("pprof-port", DefaultPprofPort, "The port to get profiling data, default: 10667") argKubeConfigFile = pflag.String("kubeconfig", "", "Path to kubeconfig file with authorization and master location information. If not set use the inCluster token.") argPassiveMode = pflag.BoolP("passivemode", "", false, "Set BGP Speaker to passive model,do not actively initiate connections to peers ") - argEbgpMultihopTtl = pflag.Uint8("ebgp-multihop", DefaultEbgpMultiHop, "The TTL value of EBGP peer, default: 1") + argEbgpMultihopTTL = pflag.Uint8("ebgp-multihop", DefaultEbgpMultiHop, "The TTL value of EBGP peer, default: 1") ) klogFlags := flag.NewFlagSet("klog", flag.ExitOnError) klog.InitFlags(klogFlags) @@ -101,8 +101,8 @@ func ParseFlags() (*Configuration, error) { if ht > 65536 || ht < 3 { return nil, errors.New("the bgp holdtime must be in the range 3s to 65536s") } - if *argRouterId != "" && net.ParseIP(*argRouterId) == nil { - return nil, fmt.Errorf("invalid router-id format: %s", *argRouterId) + if *argRouterID != "" && net.ParseIP(*argRouterID) == nil { + return nil, fmt.Errorf("invalid router-id format: %s", *argRouterID) } if *argNeighborAddress != "" && net.ParseIP(*argNeighborAddress).To4() == nil { return nil, fmt.Errorf("invalid neighbor-address format: %s", *argNeighborAddress) @@ -110,7 +110,7 @@ func ParseFlags() (*Configuration, error) { if *argNeighborIPv6Address != "" && net.ParseIP(*argNeighborIPv6Address).To16() == nil { return nil, fmt.Errorf("invalid neighbor-ipv6-address format: %s", *argNeighborIPv6Address) } - if *argEbgpMultihopTtl < 1 || *argEbgpMultihopTtl > 255 { + if *argEbgpMultihopTTL < 1 || *argEbgpMultihopTTL > 255 { return nil, errors.New("the bgp MultihopTtl must be in the range 1 to 255") } @@ -119,7 +119,7 @@ func ParseFlags() (*Configuration, error) { GrpcHost: *argGrpcHost, GrpcPort: *argGrpcPort, ClusterAs: *argClusterAs, - RouterId: *argRouterId, + RouterID: *argRouterID, NeighborAddress: *argNeighborAddress, NeighborIPv6Address: *argNeighborIPv6Address, NeighborAs: *argNeighborAs, @@ -131,12 +131,12 @@ func ParseFlags() (*Configuration, error) { GracefulRestartDeferralTime: *argGracefulRestartDeferralTime, GracefulRestartTime: *argDefaultGracefulTime, PassiveMode: *argPassiveMode, - EbgpMultihopTtl: *argEbgpMultihopTtl, + EbgpMultihopTTL: *argEbgpMultihopTTL, } - if config.RouterId == "" { - config.RouterId = os.Getenv("POD_IP") - if config.RouterId == "" { + if config.RouterID == "" { + config.RouterID = os.Getenv("POD_IP") + if config.RouterID == "" { return nil, errors.New("no router id or POD_IP") } } @@ -224,7 +224,7 @@ func (config *Configuration) initBgpServer() error { if err := s.StartBgp(context.Background(), &api.StartBgpRequest{ Global: &api.Global{ Asn: config.ClusterAs, - RouterId: config.RouterId, + RouterId: config.RouterID, ListenPort: listenPort, UseMultiplePaths: true, }, @@ -242,10 +242,10 @@ func (config *Configuration) initBgpServer() error { PassiveMode: config.PassiveMode, }, } - if config.EbgpMultihopTtl != DefaultEbgpMultiHop { + if config.EbgpMultihopTTL != DefaultEbgpMultiHop { peer.EbgpMultihop = &api.EbgpMultihop{ Enabled: true, - MultihopTtl: uint32(config.EbgpMultihopTtl), + MultihopTtl: uint32(config.EbgpMultihopTTL), } } if config.AuthPassword != "" { diff --git a/pkg/speaker/subnet.go b/pkg/speaker/subnet.go index d37516d5048..33c2e8b96a9 100644 --- a/pkg/speaker/subnet.go +++ b/pkg/speaker/subnet.go @@ -4,7 +4,6 @@ package speaker import ( "context" "fmt" - "net" "strconv" "strings" @@ -67,11 +66,10 @@ func (c *Controller) syncSubnetRoutes() { } for _, svc := range services { if svc.Annotations != nil && svc.Annotations[util.BgpAnnotation] == "true" && isClusterIPService(svc) { - for _, clusterIp := range svc.Spec.ClusterIPs { - ipFamily := util.CheckProtocol(clusterIp) - bgpExpected[ipFamily] = append(bgpExpected[ipFamily], fmt.Sprintf("%s/%d", clusterIp, maskMap[ipFamily])) + for _, clusterIP := range svc.Spec.ClusterIPs { + ipFamily := util.CheckProtocol(clusterIP) + bgpExpected[ipFamily] = append(bgpExpected[ipFamily], fmt.Sprintf("%s/%d", clusterIP, maskMap[ipFamily])) } - //bgpExpected = append(bgpExpected, fmt.Sprintf("%s/32", svc.Spec.ClusterIP)) } } } @@ -89,9 +87,9 @@ func (c *Controller) syncSubnetRoutes() { for _, pod := range pods { if isPodAlive(pod) && !pod.Spec.HostNetwork && pod.Annotations[util.BgpAnnotation] == "true" && pod.Status.PodIP != "" { podIps := pod.Status.PodIPs - for _, podIp := range podIps { - ipFamily := util.CheckProtocol(podIp.IP) - bgpExpected[ipFamily] = append(bgpExpected[ipFamily], fmt.Sprintf("%s/%d", podIp.IP, maskMap[ipFamily])) + for _, podIP := range podIps { + ipFamily := util.CheckProtocol(podIP.IP) + bgpExpected[ipFamily] = append(bgpExpected[ipFamily], fmt.Sprintf("%s/%d", podIP.IP, maskMap[ipFamily])) } } } @@ -102,10 +100,10 @@ func (c *Controller) syncSubnetRoutes() { for _, path := range d.Paths { attrInterfaces, _ := bgpapiutil.UnmarshalPathAttributes(path.Pattrs) nextHop := getNextHopFromPathAttributes(attrInterfaces) - klog.V(5).Infof("nexthop is %s, routerID is %s", nextHop.String(), c.config.RouterId) + klog.V(5).Infof("nexthop is %s, routerID is %s", nextHop.String(), c.config.RouterID) ipFamily := util.CheckProtocol(nextHop.String()) route, _ := netlink.RouteGet(nextHop) - if len(route) == 1 && route[0].Type == unix.RTN_LOCAL || nextHop.String() == c.config.RouterId { + if len(route) == 1 && route[0].Type == unix.RTN_LOCAL || nextHop.String() == c.config.RouterID { bgpExists[ipFamily] = append(bgpExists[ipFamily], d.Prefix) return } @@ -170,7 +168,7 @@ func (c *Controller) syncSubnetRoutes() { } } -func routeDiff(expected, exists []string) (toAdd []string, toDel []string) { +func routeDiff(expected, exists []string) (toAdd, toDel []string) { expectedMap, existsMap := map[string]bool{}, map[string]bool{} for _, e := range expected { expectedMap[e] = true @@ -250,7 +248,7 @@ func (c *Controller) getNlriAndAttrs(route string) (*anypb.Any, []*anypb.Any, er Origin: 0, }) a2, _ := anypb.New(&bgpapi.NextHopAttribute{ - NextHop: getNextHopAttribute(neighborAddr, c.config.RouterId), + NextHop: getNextHopAttribute(neighborAddr, c.config.RouterID), }) attrs := []*anypb.Any{a1, a2} return nlri, attrs, err @@ -291,9 +289,10 @@ func getNextHopFromPathAttributes(attrs []bgp.PathAttributeInterface) net.IP { } return nil } -func getNextHopAttribute(NeighborAddress string, RouteId string) string { - nextHop := RouteId - routes, err := netlink.RouteGet(net.ParseIP(NeighborAddress)) + +func getNextHopAttribute(neighborAddress, routeID string) string { + nextHop := routeID + routes, err := netlink.RouteGet(net.ParseIP(neighborAddress)) if err == nil && len(routes) == 1 && routes[0].Src != nil { nextHop = routes[0].Src.String() } diff --git a/pkg/tproxy/tproxy_tcp_linux.go b/pkg/tproxy/tproxy_tcp_linux.go index 35230e71d95..756b7bf66a5 100644 --- a/pkg/tproxy/tproxy_tcp_linux.go +++ b/pkg/tproxy/tproxy_tcp_linux.go @@ -148,7 +148,7 @@ func DialTCP(laddr, raddr *net.TCPAddr, isnonblocking bool) (*net.TCPConn, error return dialTCP("", laddr, raddr, false, isnonblocking) } -func dialTCP(device string, laddr, raddr *net.TCPAddr, dontAssumeRemote bool, isnonblocking bool) (*net.TCPConn, error) { +func dialTCP(device string, laddr, raddr *net.TCPAddr, dontAssumeRemote, isnonblocking bool) (*net.TCPConn, error) { if laddr == nil || raddr == nil { return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("empty local address or remote address")} } @@ -172,7 +172,7 @@ func dialTCP(device string, laddr, raddr *net.TCPAddr, dontAssumeRemote bool, is } if device != "" { - if err = syscall.BindToDevice(int(fileDescriptor), device); err != nil { + if err = syscall.BindToDevice(fileDescriptor, device); err != nil { klog.Error(err) return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: SO_BINDTODEVICE(%s): %s", device, err)} } diff --git a/pkg/util/arp.go b/pkg/util/arp.go index f59b8c3227c..b3baa2a57f2 100644 --- a/pkg/util/arp.go +++ b/pkg/util/arp.go @@ -15,7 +15,7 @@ import ( "k8s.io/klog/v2" ) -func ArpResolve(nic, srcIP, dstIP string, timeout time.Duration, maxRetry int) (net.HardwareAddr, int, error) { +func ArpResolve(nic, _, dstIP string, timeout time.Duration, maxRetry int) (net.HardwareAddr, int, error) { target, err := netip.ParseAddr(dstIP) if err != nil { return nil, 0, fmt.Errorf("failed to parse target address %s: %v", dstIP, err) @@ -76,8 +76,8 @@ func ArpDetectIPConflict(nic, ip string, mac net.HardwareAddr) (net.HardwareAddr const ( probeWait = 1 * time.Second // initial random delay probeNum = 3 // number of probe packets - probeMin = 1 * time.Second // minimum delay until repeated probe - probeMax = 2 * time.Second // maximum delay until repeated probe + probeMinmum = 1 * time.Second // minimum delay until repeated probe + probeMaxmum = 2 * time.Second // maximum delay until repeated probe announceWait = 2 * time.Second // delay before announcing announceNum = 2 // number of Announcement packets announceInterval = 2 * time.Second // time between Announcement packets @@ -119,7 +119,7 @@ func ArpDetectIPConflict(nic, ip string, mac net.HardwareAddr) (net.HardwareAddr for i := 1; i < probeNum; i++ { // send PROBE_NUM probe packets, each of these probe packets spaced // randomly and uniformly, PROBE_MIN to PROBE_MAX seconds apart - durations[i] = probeMin + time.Duration(rand.Int63n(int64(probeMax-probeMin))) + durations[i] = probeMinmum + time.Duration(rand.Int63n(int64(probeMaxmum-probeMinmum))) deadline = deadline.Add(durations[i]) } diff --git a/pkg/util/const.go b/pkg/util/const.go index 1885ef1c94b..2f5caad537e 100644 --- a/pkg/util/const.go +++ b/pkg/util/const.go @@ -9,10 +9,10 @@ const ( RoutedAnnotation = "ovn.kubernetes.io/routed" RoutesAnnotation = "ovn.kubernetes.io/routes" MacAddressAnnotation = "ovn.kubernetes.io/mac_address" - IpAddressAnnotation = "ovn.kubernetes.io/ip_address" + IPAddressAnnotation = "ovn.kubernetes.io/ip_address" CidrAnnotation = "ovn.kubernetes.io/cidr" GatewayAnnotation = "ovn.kubernetes.io/gateway" - IpPoolAnnotation = "ovn.kubernetes.io/ip_pool" + IPPoolAnnotation = "ovn.kubernetes.io/ip_pool" BgpAnnotation = "ovn.kubernetes.io/bgp" SnatAnnotation = "ovn.kubernetes.io/snat" EipAnnotation = "ovn.kubernetes.io/eip" @@ -23,7 +23,7 @@ const ( VipAnnotation = "ovn.kubernetes.io/vip" ChassisAnnotation = "ovn.kubernetes.io/chassis" - ExternalIpAnnotation = "ovn.kubernetes.io/external_ip" + ExternalIPAnnotation = "ovn.kubernetes.io/external_ip" ExternalMacAnnotation = "ovn.kubernetes.io/external_mac" ExternalCidrAnnotation = "ovn.kubernetes.io/external_cidr" ExternalSwitchAnnotation = "ovn.kubernetes.io/external_switch" @@ -33,7 +33,7 @@ const ( VpcNatGatewayAnnotation = "ovn.kubernetes.io/vpc_nat_gw" VpcNatGatewayInitAnnotation = "ovn.kubernetes.io/vpc_nat_gw_init" VpcEipsAnnotation = "ovn.kubernetes.io/vpc_eips" - VpcFloatingIpMd5Annotation = "ovn.kubernetes.io/vpc_floating_ips" + VpcFloatingIPMd5Annotation = "ovn.kubernetes.io/vpc_floating_ips" VpcDnatMd5Annotation = "ovn.kubernetes.io/vpc_dnat_md5" VpcSnatMd5Annotation = "ovn.kubernetes.io/vpc_snat_md5" VpcCIDRsAnnotation = "ovn.kubernetes.io/vpc_cidrs" @@ -62,13 +62,13 @@ const ( RoutedAnnotationTemplate = "%s.kubernetes.io/routed" RoutesAnnotationTemplate = "%s.kubernetes.io/routes" MacAddressAnnotationTemplate = "%s.kubernetes.io/mac_address" - IpAddressAnnotationTemplate = "%s.kubernetes.io/ip_address" + IPAddressAnnotationTemplate = "%s.kubernetes.io/ip_address" CidrAnnotationTemplate = "%s.kubernetes.io/cidr" GatewayAnnotationTemplate = "%s.kubernetes.io/gateway" - IpPoolAnnotationTemplate = "%s.kubernetes.io/ip_pool" + IPPoolAnnotationTemplate = "%s.kubernetes.io/ip_pool" LogicalSwitchAnnotationTemplate = "%s.kubernetes.io/logical_switch" LogicalRouterAnnotationTemplate = "%s.kubernetes.io/logical_router" - VlanIdAnnotationTemplate = "%s.kubernetes.io/vlan_id" + VlanIDAnnotationTemplate = "%s.kubernetes.io/vlan_id" IngressRateAnnotationTemplate = "%s.kubernetes.io/ingress_rate" EgressRateAnnotationTemplate = "%s.kubernetes.io/egress_rate" SecurityGroupAnnotationTemplate = "%s.kubernetes.io/security_groups" @@ -83,7 +83,7 @@ const ( ProviderNetworkMtuTemplate = "%s.provider-network.kubernetes.io/mtu" MirrorControlAnnotationTemplate = "%s.kubernetes.io/mirror" PodNicAnnotationTemplate = "%s.kubernetes.io/pod_nic_type" - VmTemplate = "%s.kubernetes.io/virtualmachine" + VMTemplate = "%s.kubernetes.io/virtualmachine" ExcludeIpsAnnotation = "ovn.kubernetes.io/exclude_ips" @@ -103,10 +103,10 @@ const ( ExGatewayLabel = "ovn.kubernetes.io/external-gw" NodeExtGwLabel = "ovn.kubernetes.io/node-ext-gw" VpcNatGatewayLabel = "ovn.kubernetes.io/vpc-nat-gw" - IpReservedLabel = "ovn.kubernetes.io/ip_reserved" + IPReservedLabel = "ovn.kubernetes.io/ip_reserved" VpcNatGatewayNameLabel = "ovn.kubernetes.io/vpc-nat-gw-name" VpcLbLabel = "ovn.kubernetes.io/vpc_lb" - VpcDnsNameLabel = "ovn.kubernetes.io/vpc-dns" + VpcDNSNameLabel = "ovn.kubernetes.io/vpc-dns" QoSLabel = "ovn.kubernetes.io/qos" NodeNameLabel = "ovn.kubernetes.io/node-name" NetworkPolicyLogAnnotation = "ovn.kubernetes.io/enable_log" @@ -148,7 +148,7 @@ const ( GeneveHeaderLength = 100 VxlanHeaderLength = 50 SttHeaderLength = 72 - TcpIpHeaderLength = 40 + TCPIPHeaderLength = 40 OvnProvider = "ovn" AttachmentNetworkAnnotation = "k8s.v1.cni.cncf.io/networks" @@ -162,8 +162,8 @@ const ( ExternalGatewaySwitch = "ovn-external" VpcNatGatewayConfig = "ovn-vpc-nat-gw-config" VpcLbNetworkAttachment = "ovn-vpc-lb" - VpcDnsConfig = "vpc-dns-config" - VpcDnsDepTemplate = "vpc-dns-dep" + VpcDNSConfig = "vpc-dns-config" + VpcDNSDepTemplate = "vpc-dns-dep" VpcNatConfig = "ovn-vpc-nat-config" DefaultSecurityGroupName = "default-securitygroup" @@ -191,7 +191,7 @@ const ( GatewayRouterPolicyPriority = 29000 OvnICPolicyPriority = 29500 NodeRouterPolicyPriority = 30000 - NodeLocalDnsPolicyPriority = 30100 + NodeLocalDNSPolicyPriority = 30100 SubnetRouterPolicyPriority = 31000 OffloadType = "offload-port" @@ -201,8 +201,8 @@ const ( HostnameEnv = "KUBE_NODE_NAME" ChasRetryTime = 5 ChasRetryIntev = 1 - Vm = "VirtualMachine" - VmInstance = "VirtualMachineInstance" + VM = "VirtualMachine" + VMInstance = "VirtualMachineInstance" MirrorControlAnnotation = "ovn.kubernetes.io/mirror" MirrorDefaultName = "m0" @@ -219,7 +219,7 @@ const ( NetemQosLossAnnotationTemplate = "%s.kubernetes.io/loss" NetemQosJitterAnnotationTemplate = "%s.kubernetes.io/jitter" - POD_IP = "POD_IP" + PodIP = "POD_IP" ContentType = "application/vnd.kubernetes.protobuf" AcceptContentTypes = "application/vnd.kubernetes.protobuf,application/json" diff --git a/pkg/util/k8s.go b/pkg/util/k8s.go index a88c09d8e39..e7d32986b8e 100644 --- a/pkg/util/k8s.go +++ b/pkg/util/k8s.go @@ -13,7 +13,7 @@ import ( "k8s.io/klog/v2" ) -func DialApiServer(host string) error { +func DialAPIServer(host string) error { u, err := url.Parse(host) if err != nil { return fmt.Errorf("failed to parse host %q: %v", host, err) diff --git a/pkg/util/named_port.go b/pkg/util/named_port.go index 8bee17be139..8314783cef3 100644 --- a/pkg/util/named_port.go +++ b/pkg/util/named_port.go @@ -3,6 +3,6 @@ package util import "github.com/scylladb/go-set/strset" type NamedPortInfo struct { - PortId int32 + PortID int32 Pods *strset.Set } diff --git a/pkg/util/net.go b/pkg/util/net.go index 7503aba45b6..800acea7d78 100644 --- a/pkg/util/net.go +++ b/pkg/util/net.go @@ -46,7 +46,7 @@ func GenerateMac() string { return mac } -func Ip2BigInt(ipStr string) *big.Int { +func IP2BigInt(ipStr string) *big.Int { ipBigInt := big.NewInt(0) if CheckProtocol(ipStr) == kubeovnv1.ProtocolIPv4 { ipBigInt.SetBytes(net.ParseIP(ipStr).To4()) @@ -79,7 +79,7 @@ func SubnetBroadcast(subnet string) string { length = 128 } maskLength, _ := cidr.Mask.Size() - ipInt := Ip2BigInt(cidr.IP.String()) + ipInt := IP2BigInt(cidr.IP.String()) size := big.NewInt(0).Lsh(big.NewInt(1), length-uint(maskLength)) size = big.NewInt(0).Sub(size, big.NewInt(1)) return BigInt2Ip(ipInt.Add(ipInt, size)) @@ -90,7 +90,7 @@ func FirstIP(subnet string) (string, error) { if err != nil { return "", fmt.Errorf("%s is not a valid cidr", subnet) } - ipInt := Ip2BigInt(cidr.IP.String()) + ipInt := IP2BigInt(cidr.IP.String()) return BigInt2Ip(ipInt.Add(ipInt, big.NewInt(1))), nil } @@ -106,7 +106,7 @@ func LastIP(subnet string) (string, error) { length = 128 } maskLength, _ := cidr.Mask.Size() - ipInt := Ip2BigInt(cidr.IP.String()) + ipInt := IP2BigInt(cidr.IP.String()) size := big.NewInt(0).Lsh(big.NewInt(1), length-uint(maskLength)) size = big.NewInt(0).Sub(size, big.NewInt(2)) return BigInt2Ip(ipInt.Add(ipInt, size)), nil @@ -204,7 +204,7 @@ func genRandomIP(cidr string, isIPv6 bool) string { if err != nil { LogFatalAndExit(err, "failed to generate random ip") } - t := big.NewInt(0).Add(Ip2BigInt(ip), add) + t := big.NewInt(0).Add(IP2BigInt(ip), add) return fmt.Sprintf("%s/%d", BigInt2Ip(t), netMask) } @@ -252,21 +252,20 @@ func AppendGwByCidr(gateway, cidrStr string) (string, error) { if CheckProtocol(gateway) == CheckProtocol(cidr) { gws = append(gws, gateway) continue + } + gw, err := FirstIP(cidr) + if err != nil { + return "", err + } + var gwArray [2]string + if CheckProtocol(gateway) == kubeovnv1.ProtocolIPv4 { + gwArray[0] = gateway + gwArray[1] = gw } else { - gw, err := FirstIP(cidr) - if err != nil { - return "", err - } - var gwArray [2]string - if CheckProtocol(gateway) == kubeovnv1.ProtocolIPv4 { - gwArray[0] = gateway - gwArray[1] = gw - } else { - gwArray[0] = gw - gwArray[1] = gateway - } - gws = gwArray[:] + gwArray[0] = gw + gwArray[1] = gateway } + gws = gwArray[:] } return strings.Join(gws, ","), nil @@ -288,17 +287,18 @@ func SplitIpsByProtocol(excludeIps []string) ([]string, []string) { func GetStringIP(v4IP, v6IP string) string { var ipStr string - if IsValidIP(v4IP) && IsValidIP(v6IP) { + switch { + case IsValidIP(v4IP) && IsValidIP(v6IP): ipStr = v4IP + "," + v6IP - } else if IsValidIP(v4IP) { + case IsValidIP(v4IP): ipStr = v4IP - } else if IsValidIP(v6IP) { + case IsValidIP(v6IP): ipStr = v6IP } return ipStr } -func GetIpAddrWithMask(ip, cidr string) string { +func GetIPAddrWithMask(ip, cidr string) string { var ipAddr string if CheckProtocol(cidr) == kubeovnv1.ProtocolDual { cidrBlocks := strings.Split(cidr, ",") @@ -314,7 +314,7 @@ func GetIpAddrWithMask(ip, cidr string) string { return ipAddr } -func GetIpWithoutMask(ipStr string) string { +func GetIPWithoutMask(ipStr string) string { var ips []string for _, ip := range strings.Split(ipStr, ",") { ips = append(ips, strings.Split(ip, "/")[0]) @@ -353,8 +353,8 @@ func ExpandExcludeIPs(excludeIPs []string, cidr string) []string { klog.Errorf("invalid exclude IP: %s", excludeIP) continue } - s := Ip2BigInt(parts[0]) - e := Ip2BigInt(parts[1]) + s := IP2BigInt(parts[0]) + e := IP2BigInt(parts[1]) if s.Cmp(e) > 0 { continue } @@ -375,11 +375,11 @@ func ExpandExcludeIPs(excludeIPs []string, cidr string) []string { } lastIP, _ := LastIP(cidrBlock) s1, e1 := s, e - if s1.Cmp(Ip2BigInt(firstIP)) < 0 { - s1 = Ip2BigInt(firstIP) + if s1.Cmp(IP2BigInt(firstIP)) < 0 { + s1 = IP2BigInt(firstIP) } - if e1.Cmp(Ip2BigInt(lastIP)) > 0 { - e1 = Ip2BigInt(lastIP) + if e1.Cmp(IP2BigInt(lastIP)) > 0 { + e1 = IP2BigInt(lastIP) } if c := s1.Cmp(e1); c == 0 { rv = append(rv, BigInt2Ip(s1)) @@ -400,31 +400,29 @@ func ExpandExcludeIPs(excludeIPs []string, cidr string) []string { return rv } -func ContainsIPs(excludeIP string, ip string) bool { +func ContainsIPs(excludeIP, ip string) bool { if strings.Contains(excludeIP, "..") { parts := strings.Split(excludeIP, "..") - s := Ip2BigInt(parts[0]) - e := Ip2BigInt(parts[1]) - ipv := Ip2BigInt(ip) + s := IP2BigInt(parts[0]) + e := IP2BigInt(parts[1]) + ipv := IP2BigInt(ip) if s.Cmp(ipv) <= 0 && e.Cmp(ipv) >= 0 { return true } - } else { - if excludeIP == ip { - return true - } + } else if excludeIP == ip { + return true } return false } -func CountIpNums(excludeIPs []string) float64 { +func CountIPNums(excludeIPs []string) float64 { var count float64 for _, excludeIP := range excludeIPs { if strings.Contains(excludeIP, "..") { var val big.Int parts := strings.Split(excludeIP, "..") - s := Ip2BigInt(parts[0]) - e := Ip2BigInt(parts[1]) + s := IP2BigInt(parts[0]) + e := IP2BigInt(parts[1]) v, _ := new(big.Float).SetInt(val.Add(val.Sub(e, s), big.NewInt(1))).Float64() count += v } else { @@ -459,12 +457,12 @@ func CIDROverlap(a, b string) bool { if CheckProtocol(cidrA) != CheckProtocol(cidrB) { continue } - aIp, aIpNet, aErr := net.ParseCIDR(cidrA) - bIp, bIpNet, bErr := net.ParseCIDR(cidrB) + aIP, aIPNet, aErr := net.ParseCIDR(cidrA) + bIP, bIPNet, bErr := net.ParseCIDR(cidrB) if aErr != nil || bErr != nil { return false } - if aIpNet.Contains(bIp) || bIpNet.Contains(aIp) { + if aIPNet.Contains(bIP) || bIPNet.Contains(aIP) { return true } } @@ -567,7 +565,6 @@ func TCPConnectivityListen(address string) error { } func UDPConnectivityCheck(address string) error { - udpAddr, err := net.ResolveUDPAddr("udp", address) if err != nil { return fmt.Errorf("resolve udp addr failed with err %v", err) diff --git a/pkg/util/net_test.go b/pkg/util/net_test.go index 456c857215c..bccc995aac0 100644 --- a/pkg/util/net_test.go +++ b/pkg/util/net_test.go @@ -6,8 +6,9 @@ import ( "reflect" "testing" - kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1" "github.com/stretchr/testify/require" + + kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1" ) func TestCheckSystemCIDR(t *testing.T) { @@ -136,7 +137,7 @@ func TestIp2BigInt(t *testing.T) { } for _, c := range tests { t.Run(c.name, func(t *testing.T) { - if ans := Ip2BigInt(c.ip); !reflect.DeepEqual(ans, c.expect) { + if ans := IP2BigInt(c.ip); !reflect.DeepEqual(ans, c.expect) { t.Errorf("%v expected %v, but %v got", c.ip, c.expect, ans) } @@ -700,7 +701,7 @@ func TestGetStringIP(t *testing.T) { } } -func TestGetIpAddrWithMask(t *testing.T) { +func TestGetIPAddrWithMask(t *testing.T) { tests := []struct { name string ip string @@ -728,7 +729,7 @@ func TestGetIpAddrWithMask(t *testing.T) { } for _, c := range tests { t.Run(c.name, func(t *testing.T) { - ans := GetIpAddrWithMask(c.ip, c.cidr) + ans := GetIPAddrWithMask(c.ip, c.cidr) if c.want != ans { t.Errorf("%v, %v expected %v, but %v got", c.ip, c.cidr, c.want, ans) @@ -737,7 +738,7 @@ func TestGetIpAddrWithMask(t *testing.T) { } } -func TestGetIpWithoutMask(t *testing.T) { +func TestGetIPWithoutMask(t *testing.T) { tests := []struct { name string cidr string @@ -756,7 +757,7 @@ func TestGetIpWithoutMask(t *testing.T) { } for _, c := range tests { t.Run(c.name, func(t *testing.T) { - ans := GetIpWithoutMask(c.cidr) + ans := GetIPWithoutMask(c.cidr) if c.want != ans { t.Errorf("%v expected %v, but %v got", c.cidr, c.want, ans) @@ -919,7 +920,7 @@ func TestCountIpNums(t *testing.T) { } for _, c := range tests { t.Run(c.name, func(t *testing.T) { - ans := CountIpNums(c.excl) + ans := CountIPNums(c.excl) if ans != c.want { t.Errorf("%v expected %v but %v got", c.excl, c.want, ans) diff --git a/pkg/util/network_attachment.go b/pkg/util/network_attachment.go index d107c7888f8..c3dacfe9a45 100644 --- a/pkg/util/network_attachment.go +++ b/pkg/util/network_attachment.go @@ -20,12 +20,13 @@ func parsePodNetworkObjectName(podNetwork string) (string, string, string, error klog.V(3).Infof("parsePodNetworkObjectName: %s", podNetwork) slashItems := strings.Split(podNetwork, "/") - if len(slashItems) == 2 { + switch len(slashItems) { + case 2: netNsName = strings.TrimSpace(slashItems[0]) networkName = slashItems[1] - } else if len(slashItems) == 1 { + case 1: networkName = slashItems[0] - } else { + default: klog.Errorf("parsePodNetworkObjectName: Invalid network object (failed at '/')") return "", "", "", fmt.Errorf("parsePodNetworkObjectName: Invalid network object (failed at '/')") } diff --git a/pkg/util/network_attachment_test.go b/pkg/util/network_attachment_test.go index 2d2e25ece92..cb4b5383dc3 100644 --- a/pkg/util/network_attachment_test.go +++ b/pkg/util/network_attachment_test.go @@ -87,8 +87,7 @@ func TestParsePodNetworkObjectName(t *testing.T) { } func TestParsePodNetworkAnnotation(t *testing.T) { - - correctJson0, _ := json.Marshal([]types.NetworkSelectionElement{ + correctJSON0, _ := json.Marshal([]types.NetworkSelectionElement{ { Name: "lb-svc-attachment", Namespace: "kube-system", @@ -98,7 +97,7 @@ func TestParsePodNetworkAnnotation(t *testing.T) { IPRequest: []string{"192.168.50.6"}, }, }) - correctJson0IP, _ := json.Marshal([]types.NetworkSelectionElement{ + correctJSON0IP, _ := json.Marshal([]types.NetworkSelectionElement{ { Name: "lb-svc-attachment", Namespace: "kube-system", @@ -108,7 +107,7 @@ func TestParsePodNetworkAnnotation(t *testing.T) { IPRequest: []string{"192.168.50.6/20"}, }, }) - errJson0, _ := json.Marshal(types.NetworkSelectionElement{ + errJSON0, _ := json.Marshal(types.NetworkSelectionElement{ Name: "lb-svc-attachment", Namespace: "kube-system", InterfaceRequest: "eth0", @@ -116,7 +115,7 @@ func TestParsePodNetworkAnnotation(t *testing.T) { DeprecatedInterfaceRequest: "eth0", IPRequest: []string{"192.168.50.6"}, }) - errJsonMac, _ := json.Marshal([]types.NetworkSelectionElement{ + errJSONMac, _ := json.Marshal([]types.NetworkSelectionElement{ { Name: "lb-svc-attachment", Namespace: "kube-system", @@ -126,7 +125,7 @@ func TestParsePodNetworkAnnotation(t *testing.T) { IPRequest: []string{"192.168.50.6"}, }, }) - errJson0IP1, _ := json.Marshal([]types.NetworkSelectionElement{ + errJSON0IP1, _ := json.Marshal([]types.NetworkSelectionElement{ { Name: "lb-svc-attachment", Namespace: "kube-system", @@ -136,7 +135,7 @@ func TestParsePodNetworkAnnotation(t *testing.T) { IPRequest: []string{"192.168.6"}, }, }) - errJson0IP2, _ := json.Marshal([]types.NetworkSelectionElement{ + errJSON0IP2, _ := json.Marshal([]types.NetworkSelectionElement{ { Name: "lb-svc-attachment", Namespace: "kube-system", @@ -146,7 +145,7 @@ func TestParsePodNetworkAnnotation(t *testing.T) { IPRequest: []string{"192.168.6/20"}, }, }) - correctJson0IfReq, _ := json.Marshal([]types.NetworkSelectionElement{ + correctJSON0IfReq, _ := json.Marshal([]types.NetworkSelectionElement{ { Name: "lb-svc-attachment", Namespace: "kube-system", @@ -231,7 +230,7 @@ func TestParsePodNetworkAnnotation(t *testing.T) { }, { name: "correctJson", - podNetworks: string(correctJson0), + podNetworks: string(correctJSON0), defaultNamespace: "kube-system", exp: []*types.NetworkSelectionElement{ { @@ -247,7 +246,7 @@ func TestParsePodNetworkAnnotation(t *testing.T) { }, { name: "correctJsonIP", - podNetworks: string(correctJson0IP), + podNetworks: string(correctJSON0IP), defaultNamespace: "kube-system", exp: []*types.NetworkSelectionElement{ { @@ -263,7 +262,7 @@ func TestParsePodNetworkAnnotation(t *testing.T) { }, { name: "correctJsonIfReq", - podNetworks: string(correctJson0IfReq), + podNetworks: string(correctJSON0IfReq), defaultNamespace: "kube-system", exp: []*types.NetworkSelectionElement{ { @@ -279,28 +278,28 @@ func TestParsePodNetworkAnnotation(t *testing.T) { }, { name: "errJson", - podNetworks: string(errJson0), + podNetworks: string(errJSON0), defaultNamespace: "kube-system", exp: nil, err: "json: cannot unmarshal object into Go value", }, { - name: "errJsonMac", - podNetworks: string(errJsonMac), + name: "errJSONMac", + podNetworks: string(errJSONMac), defaultNamespace: "kube-system", exp: nil, err: "invalid MAC address", }, { name: "errJsonIP1", - podNetworks: string(errJson0IP1), + podNetworks: string(errJSON0IP1), defaultNamespace: "kube-system", exp: nil, err: "failed to parse IP address", }, { name: "errJsonIP2", - podNetworks: string(errJson0IP2), + podNetworks: string(errJSON0IP2), defaultNamespace: "kube-system", exp: nil, err: "invalid CIDR address", diff --git a/pkg/util/pod_exec.go b/pkg/util/pod_exec.go index 7f362131c72..fa159775af6 100644 --- a/pkg/util/pod_exec.go +++ b/pkg/util/pod_exec.go @@ -26,8 +26,9 @@ type ExecOptions struct { PreserveWhitespace bool } -func ExecuteCommandInContainer(client kubernetes.Interface, cfg *rest.Config, namespace string, podName string, containerName string, cmd ...string) ( - string, string, error) { +func ExecuteCommandInContainer(client kubernetes.Interface, cfg *rest.Config, namespace, podName, containerName string, cmd ...string) ( + string, string, error, +) { return ExecuteWithOptions(client, cfg, ExecOptions{ Command: cmd, Namespace: namespace, @@ -66,7 +67,8 @@ func ExecuteWithOptions(client kubernetes.Interface, cfg *rest.Config, options E } func execute(method string, url *url.URL, cfg *rest.Config, stdin io.Reader, stdout, stderr io.Writer, - tty bool) error { + tty bool, +) error { exec, err := remotecommand.NewSPDYExecutor(cfg, method, url) if err != nil { klog.Errorf("remotecommand.NewSPDYExecutor error: %v", err) diff --git a/pkg/util/slice_test.go b/pkg/util/slice_test.go index 387ac769c91..a9d2cbf8438 100644 --- a/pkg/util/slice_test.go +++ b/pkg/util/slice_test.go @@ -184,6 +184,7 @@ func TestRemoveString(t *testing.T) { }) } } + func Test_DiffStringSlice(t *testing.T) { t.Parallel() tests := []struct { diff --git a/pkg/util/strings.go b/pkg/util/strings.go index 7e9454bfd5e..81b10c50ee6 100644 --- a/pkg/util/strings.go +++ b/pkg/util/strings.go @@ -11,12 +11,13 @@ func DoubleQuotedFields(s string) []string { var fields []string sb := &strings.Builder{} for _, r := range s { - if r == '"' { + switch { + case r == '"': quoted = !quoted - } else if !quoted && r == ' ' { + case !quoted && r == ' ': fields = append(fields, sb.String()) sb.Reset() - } else { + default: sb.WriteRune(r) } } diff --git a/pkg/util/validator.go b/pkg/util/validator.go index 6af7a22495b..a73bf824752 100644 --- a/pkg/util/validator.go +++ b/pkg/util/validator.go @@ -41,7 +41,7 @@ func ValidateSubnet(subnet kubeovnv1.Subnet) error { return fmt.Errorf("ip %s in exclude_ips is not a valid address", ip) } } - if Ip2BigInt(ips[0]).Cmp(Ip2BigInt(ips[1])) == 1 { + if IP2BigInt(ips[0]).Cmp(IP2BigInt(ips[1])) == 1 { return fmt.Errorf("%s in excludeIps is not a valid ip range", ipr) } } @@ -73,9 +73,9 @@ func ValidateSubnet(subnet kubeovnv1.Subnet) error { } if subnet.Spec.Vpc == DefaultVpc { - k8sApiServer := os.Getenv("KUBERNETES_SERVICE_HOST") - if k8sApiServer != "" && CIDRContainIP(subnet.Spec.CIDRBlock, k8sApiServer) { - return fmt.Errorf("subnet %s cidr %s conflicts with k8s apiserver svc ip %s", subnet.Name, subnet.Spec.CIDRBlock, k8sApiServer) + k8sAPIServer := os.Getenv("KUBERNETES_SERVICE_HOST") + if k8sAPIServer != "" && CIDRContainIP(subnet.Spec.CIDRBlock, k8sAPIServer) { + return fmt.Errorf("subnet %s cidr %s conflicts with k8s apiserver svc ip %s", subnet.Name, subnet.Spec.CIDRBlock, k8sAPIServer) } } @@ -189,17 +189,17 @@ func validateNatOutGoingPolicyRuleIPs(matchIPStr string) (string, error) { func ValidatePodNetwork(annotations map[string]string) error { errors := []error{} - if ipAddress := annotations[IpAddressAnnotation]; ipAddress != "" { + if ipAddress := annotations[IPAddressAnnotation]; ipAddress != "" { // The format of IP Annotation in dual-stack is 10.244.0.0/16,fd00:10:244:0:2::/80 for _, ip := range strings.Split(ipAddress, ",") { if strings.Contains(ip, "/") { if _, _, err := net.ParseCIDR(ip); err != nil { - errors = append(errors, fmt.Errorf("%s is not a valid %s", ip, IpAddressAnnotation)) + errors = append(errors, fmt.Errorf("%s is not a valid %s", ip, IPAddressAnnotation)) continue } } else { if net.ParseIP(ip) == nil { - errors = append(errors, fmt.Errorf("%s is not a valid %s", ip, IpAddressAnnotation)) + errors = append(errors, fmt.Errorf("%s is not a valid %s", ip, IPAddressAnnotation)) continue } } @@ -225,7 +225,7 @@ func ValidatePodNetwork(annotations map[string]string) error { } } - ipPool := annotations[IpPoolAnnotation] + ipPool := annotations[IPPoolAnnotation] if ipPool != "" { if strings.ContainsRune(ipPool, ';') || strings.ContainsRune(ipPool, ',') || net.ParseIP(ipPool) != nil { for _, ips := range strings.Split(ipPool, ";") { @@ -238,7 +238,7 @@ func ValidatePodNetwork(annotations map[string]string) error { for _, ip := range strings.Split(ips, ",") { if net.ParseIP(strings.TrimSpace(ip)) == nil { - errors = append(errors, fmt.Errorf("%s in %s is not a valid address", ip, IpPoolAnnotation)) + errors = append(errors, fmt.Errorf("%s in %s is not a valid address", ip, IPPoolAnnotation)) } } } diff --git a/pkg/util/validator_test.go b/pkg/util/validator_test.go index b395c86303c..89fa6b8f178 100644 --- a/pkg/util/validator_test.go +++ b/pkg/util/validator_test.go @@ -10,7 +10,6 @@ import ( ) func TestValidateSubnet(t *testing.T) { - os.Setenv("KUBERNETES_SERVICE_HOST", "10.20.0.1") tests := []struct { name string diff --git a/pkg/util/version.go b/pkg/util/version.go index 7d10ca31195..0e3f32f5f60 100644 --- a/pkg/util/version.go +++ b/pkg/util/version.go @@ -6,7 +6,7 @@ import ( ) // CompareVersion compare two version -func CompareVersion(version1 string, version2 string) int { +func CompareVersion(version1, version2 string) int { versionA := strings.Split(version1, ".") versionB := strings.Split(version2, ".") @@ -19,11 +19,13 @@ func CompareVersion(version1 string, version2 string) int { for i := 0; i < 4; i++ { version1, _ := strconv.Atoi(versionA[i]) version2, _ := strconv.Atoi(versionB[i]) - if version1 == version2 { + + switch { + case version1 == version2: continue - } else if version1 > version2 { + case version1 > version2: return 1 - } else { + default: return -1 } } diff --git a/pkg/webhook/ovn_nat_gateway.go b/pkg/webhook/ovn_nat_gateway.go index ea54138448f..756880d7792 100644 --- a/pkg/webhook/ovn_nat_gateway.go +++ b/pkg/webhook/ovn_nat_gateway.go @@ -54,10 +54,9 @@ func (v *ValidatingHook) ovnEipUpdateHook(ctx context.Context, req admission.Req if eipOld.Status.Ready { err := fmt.Errorf("ovnEip \"%s\" is ready, not support change", eipNew.Name) return ctrlwebhook.Errored(http.StatusBadRequest, err) - } else { - if err := v.ValidateOvnEip(ctx, &eipNew); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + } + if err := v.ValidateOvnEip(ctx, &eipNew); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) } } return ctrlwebhook.Allowed("by pass") @@ -145,10 +144,9 @@ func (v *ValidatingHook) ovnDnatUpdateHook(ctx context.Context, req admission.Re if dnatOld.Status.Ready { err := fmt.Errorf("OvnDnatRule \"%s\" is ready, not support change", dnatNew.Name) return ctrlwebhook.Errored(http.StatusBadRequest, err) - } else { - if err := v.ValidateOvnDnat(ctx, &dnatNew); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + } + if err := v.ValidateOvnDnat(ctx, &dnatNew); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) } } @@ -183,10 +181,9 @@ func (v *ValidatingHook) ovnSnatUpdateHook(ctx context.Context, req admission.Re if snatOld.Status.Ready { err := fmt.Errorf("OvnSnatRule \"%s\" is ready, not support change", snatNew.Name) return ctrlwebhook.Errored(http.StatusBadRequest, err) - } else { - if err := v.ValidateOvnSnat(ctx, &snatNew); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + } + if err := v.ValidateOvnSnat(ctx, &snatNew); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) } } @@ -221,10 +218,9 @@ func (v *ValidatingHook) ovnFipUpdateHook(ctx context.Context, req admission.Req if fipOld.Status.Ready { err := fmt.Errorf("OvnFIPRule \"%s\" is ready, not support change", fipNew.Name) return ctrlwebhook.Errored(http.StatusBadRequest, err) - } else { - if err := v.ValidateOvnFip(ctx, &fipNew); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + } + if err := v.ValidateOvnFip(ctx, &fipNew); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) } } return ctrlwebhook.Allowed("by pass") @@ -272,8 +268,8 @@ func (v *ValidatingHook) ValidateOvnDnat(ctx context.Context, dnat *ovnv1.OvnDna err := fmt.Errorf("parameter \"OvnEip\" cannot be empty") return err } - if dnat.Spec.IpName == "" { - err := fmt.Errorf("parameter \"IpName\" cannot be empty") + if dnat.Spec.IPName == "" { + err := fmt.Errorf("parameter \"IPName\" cannot be empty") return err } eip := &ovnv1.OvnEip{} @@ -301,10 +297,10 @@ func (v *ValidatingHook) ValidateOvnDnat(ctx context.Context, dnat *ovnv1.OvnDna } if port, err := strconv.Atoi(dnat.Spec.InternalPort); err != nil { - errMsg := fmt.Errorf("failed to parse internalIp %s: %v", dnat.Spec.InternalPort, err) + errMsg := fmt.Errorf("failed to parse internalIP %s: %v", dnat.Spec.InternalPort, err) return errMsg } else if port < 0 || port > 65535 { - err := fmt.Errorf("internalIp %s is not a valid port", dnat.Spec.InternalPort) + err := fmt.Errorf("internalIP %s is not a valid port", dnat.Spec.InternalPort) return err } @@ -322,17 +318,13 @@ func (v *ValidatingHook) ValidateOvnSnat(ctx context.Context, snat *ovnv1.OvnSna err := fmt.Errorf("parameter \"eip\" cannot be empty") return err } - if snat.Spec.VpcSubnet == "" && snat.Spec.IpName == "" { - err := fmt.Errorf("should set parameter \"VpcSubnet\" or \"IpName\" at least") + if snat.Spec.VpcSubnet == "" && snat.Spec.IPName == "" { + err := fmt.Errorf("should set parameter \"VpcSubnet\" or \"IPName\" at least") return err } eip := &ovnv1.OvnEip{} key := types.NamespacedName{Name: snat.Spec.OvnEip} - if err := v.cache.Get(ctx, key, eip); err != nil { - return err - } - - return nil + return v.cache.Get(ctx, key, eip) } func (v *ValidatingHook) ValidateOvnFip(ctx context.Context, fip *ovnv1.OvnFip) error { @@ -340,15 +332,11 @@ func (v *ValidatingHook) ValidateOvnFip(ctx context.Context, fip *ovnv1.OvnFip) err := fmt.Errorf("parameter \"OvnEip\" cannot be empty") return err } - if fip.Spec.IpName == "" { - err := fmt.Errorf("parameter \"IpName\" cannot be empty") + if fip.Spec.IPName == "" { + err := fmt.Errorf("parameter \"IPName\" cannot be empty") return err } eip := &ovnv1.OvnEip{} key := types.NamespacedName{Name: fip.Spec.OvnEip} - if err := v.cache.Get(ctx, key, eip); err != nil { - return err - } - - return nil + return v.cache.Get(ctx, key, eip) } diff --git a/pkg/webhook/static_ip.go b/pkg/webhook/static_ip.go index 64bb0afa587..f12ef899fc5 100644 --- a/pkg/webhook/static_ip.go +++ b/pkg/webhook/static_ip.go @@ -37,12 +37,12 @@ func (v *ValidatingHook) DeploymentCreateHook(ctx context.Context, req admission return ctrlwebhook.Errored(http.StatusBadRequest, err) } // Get pod template static ips - staticIPSAnno := o.Spec.Template.GetAnnotations()[util.IpPoolAnnotation] + staticIPSAnno := o.Spec.Template.GetAnnotations()[util.IPPoolAnnotation] klog.V(3).Infof("%s %s@%s, ip_pool: %s", o.Kind, o.GetName(), o.GetNamespace(), staticIPSAnno) if staticIPSAnno == "" { return ctrlwebhook.Allowed("by pass") } - return v.validateIp(ctx, o.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) + return v.validateIP(ctx, o.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) } func (v *ValidatingHook) StatefulSetCreateHook(ctx context.Context, req admission.Request) admission.Response { @@ -51,12 +51,12 @@ func (v *ValidatingHook) StatefulSetCreateHook(ctx context.Context, req admissio return ctrlwebhook.Errored(http.StatusBadRequest, err) } // Get pod template static ips - staticIPSAnno := o.Spec.Template.GetAnnotations()[util.IpPoolAnnotation] + staticIPSAnno := o.Spec.Template.GetAnnotations()[util.IPPoolAnnotation] klog.V(3).Infof("%s %s@%s, ip_pool: %s", o.Kind, o.GetName(), o.GetNamespace(), staticIPSAnno) if staticIPSAnno == "" { return ctrlwebhook.Allowed("by pass") } - return v.validateIp(ctx, o.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) + return v.validateIP(ctx, o.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) } func (v *ValidatingHook) DaemonSetCreateHook(ctx context.Context, req admission.Request) admission.Response { @@ -65,12 +65,12 @@ func (v *ValidatingHook) DaemonSetCreateHook(ctx context.Context, req admission. return ctrlwebhook.Errored(http.StatusBadRequest, err) } // Get pod template static ips - staticIPSAnno := o.Spec.Template.GetAnnotations()[util.IpPoolAnnotation] + staticIPSAnno := o.Spec.Template.GetAnnotations()[util.IPPoolAnnotation] klog.V(3).Infof("%s %s@%s, ip_pool: %s", o.Kind, o.GetName(), o.GetNamespace(), staticIPSAnno) if staticIPSAnno == "" { return ctrlwebhook.Allowed("by pass") } - return v.validateIp(ctx, o.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) + return v.validateIP(ctx, o.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) } func (v *ValidatingHook) JobSetCreateHook(ctx context.Context, req admission.Request) admission.Response { @@ -79,12 +79,12 @@ func (v *ValidatingHook) JobSetCreateHook(ctx context.Context, req admission.Req return ctrlwebhook.Errored(http.StatusBadRequest, err) } // Get pod template static ips - staticIPSAnno := o.Spec.Template.GetAnnotations()[util.IpPoolAnnotation] + staticIPSAnno := o.Spec.Template.GetAnnotations()[util.IPPoolAnnotation] klog.V(3).Infof("%s %s@%s, ip_pool: %s", o.Kind, o.GetName(), o.GetNamespace(), staticIPSAnno) if staticIPSAnno == "" { return ctrlwebhook.Allowed("by pass") } - return v.validateIp(ctx, o.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) + return v.validateIP(ctx, o.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) } func (v *ValidatingHook) CornJobSetCreateHook(ctx context.Context, req admission.Request) admission.Response { @@ -93,12 +93,12 @@ func (v *ValidatingHook) CornJobSetCreateHook(ctx context.Context, req admission return ctrlwebhook.Errored(http.StatusBadRequest, err) } // Get pod template static ips - staticIPSAnno := o.Spec.JobTemplate.Spec.Template.GetAnnotations()[util.IpPoolAnnotation] + staticIPSAnno := o.Spec.JobTemplate.Spec.Template.GetAnnotations()[util.IPPoolAnnotation] klog.V(3).Infof("%s %s@%s, ip_pool: %s", o.Kind, o.GetName(), o.GetNamespace(), staticIPSAnno) if staticIPSAnno == "" { return ctrlwebhook.Allowed("by pass") } - return v.validateIp(ctx, o.Spec.JobTemplate.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) + return v.validateIP(ctx, o.Spec.JobTemplate.Spec.Template.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) } func (v *ValidatingHook) PodCreateHook(ctx context.Context, req admission.Request) admission.Response { @@ -106,10 +106,10 @@ func (v *ValidatingHook) PodCreateHook(ctx context.Context, req admission.Reques if err := v.decoder.Decode(req, &o); err != nil { return ctrlwebhook.Errored(http.StatusBadRequest, err) } - poolAnno := o.GetAnnotations()[util.IpPoolAnnotation] + poolAnno := o.GetAnnotations()[util.IPPoolAnnotation] klog.V(3).Infof("%s %s@%s, ip_pool: %s", o.Kind, o.GetName(), o.GetNamespace(), poolAnno) - staticIP := o.GetAnnotations()[util.IpAddressAnnotation] + staticIP := o.GetAnnotations()[util.IPAddressAnnotation] klog.V(3).Infof("%s %s@%s, ip_address: %s", o.Kind, o.GetName(), o.GetNamespace(), staticIP) if staticIP == "" && poolAnno == "" { return ctrlwebhook.Allowed("by pass") @@ -117,10 +117,10 @@ func (v *ValidatingHook) PodCreateHook(ctx context.Context, req admission.Reques if v.allowLiveMigration(ctx, o.GetAnnotations(), o.GetName(), o.GetNamespace()) { return ctrlwebhook.Allowed("by pass") } - return v.validateIp(ctx, o.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) + return v.validateIP(ctx, o.GetAnnotations(), o.Kind, o.GetName(), o.GetNamespace()) } -func (v *ValidatingHook) allowLiveMigration(ctx context.Context, annotations map[string]string, name, namespace string) bool { +func (v *ValidatingHook) allowLiveMigration(_ context.Context, annotations map[string]string, name, namespace string) bool { var multusNets []*multustypes.NetworkSelectionElement defaultAttachNetworks := annotations[util.DefaultNetworkAnnotation] if defaultAttachNetworks != "" { @@ -152,7 +152,7 @@ func (v *ValidatingHook) allowLiveMigration(ctx context.Context, annotations map return false } -func (v *ValidatingHook) validateIp(ctx context.Context, annotations map[string]string, kind, name, namespace string) admission.Response { +func (v *ValidatingHook) validateIP(ctx context.Context, annotations map[string]string, kind, name, namespace string) admission.Response { if err := util.ValidatePodNetwork(annotations); err != nil { klog.Errorf("validate %s %s/%s failed: %v", kind, namespace, name, err) return ctrlwebhook.Errored(http.StatusBadRequest, err) @@ -175,13 +175,13 @@ func (v *ValidatingHook) validateIPConflict(annotations map[string]string, name annoSubnet = util.DefaultSubnet } - if ipAddress := annotations[util.IpAddressAnnotation]; ipAddress != "" { + if ipAddress := annotations[util.IPAddressAnnotation]; ipAddress != "" { if err := v.checkIPConflict(ipAddress, annoSubnet, name, ipList); err != nil { return err } } - ipPool := annotations[util.IpPoolAnnotation] + ipPool := annotations[util.IPPoolAnnotation] if ipPool != "" { if err := v.checkIPConflict(ipPool, annoSubnet, name, ipList); err != nil { return err diff --git a/pkg/webhook/subnet.go b/pkg/webhook/subnet.go index 65b859f8188..1f571d7aa62 100644 --- a/pkg/webhook/subnet.go +++ b/pkg/webhook/subnet.go @@ -83,7 +83,7 @@ func (v *ValidatingHook) SubnetUpdateHook(ctx context.Context, req admission.Req return ctrlwebhook.Allowed("by pass") } -func (v *ValidatingHook) SubnetDeleteHook(ctx context.Context, req admission.Request) admission.Response { +func (v *ValidatingHook) SubnetDeleteHook(_ context.Context, req admission.Request) admission.Response { subnet := ovnv1.Subnet{} if err := v.decoder.DecodeRaw(req.OldObject, &subnet); err != nil { return ctrlwebhook.Errored(http.StatusBadRequest, err) diff --git a/pkg/webhook/vpc.go b/pkg/webhook/vpc.go index acdc4414605..f58a0d46783 100644 --- a/pkg/webhook/vpc.go +++ b/pkg/webhook/vpc.go @@ -36,7 +36,7 @@ func (v *ValidatingHook) VpcCreateHook(ctx context.Context, req admission.Reques return ctrlwebhook.Allowed("by pass") } -func (v *ValidatingHook) VpcUpdateHook(ctx context.Context, req admission.Request) admission.Response { +func (v *ValidatingHook) VpcUpdateHook(_ context.Context, req admission.Request) admission.Response { vpc := ovnv1.Vpc{} if err := v.decoder.DecodeRaw(req.Object, &vpc); err != nil { return ctrlwebhook.Errored(http.StatusBadRequest, err) @@ -49,7 +49,7 @@ func (v *ValidatingHook) VpcUpdateHook(ctx context.Context, req admission.Reques return ctrlwebhook.Allowed("by pass") } -func (v *ValidatingHook) VpcDeleteHook(ctx context.Context, req admission.Request) admission.Response { +func (v *ValidatingHook) VpcDeleteHook(_ context.Context, req admission.Request) admission.Response { vpc := ovnv1.Vpc{} if err := v.decoder.DecodeRaw(req.OldObject, &vpc); err != nil { return ctrlwebhook.Errored(http.StatusBadRequest, err) diff --git a/pkg/webhook/vpc_nat_gateway.go b/pkg/webhook/vpc_nat_gateway.go index cc7e8d673b2..91c8042ef76 100644 --- a/pkg/webhook/vpc_nat_gateway.go +++ b/pkg/webhook/vpc_nat_gateway.go @@ -98,18 +98,17 @@ func (v *ValidatingHook) iptablesEIPUpdateHook(ctx context.Context, req admissio if eipOld.Status.Ready && eipNew.Status.Redo == eipOld.Status.Redo { err := fmt.Errorf("IptablesEIP \"%s\" is ready,not support change", eipNew.Name) return ctrlwebhook.Errored(http.StatusBadRequest, err) - } else { - if err := v.ValidateVpcNatConfig(ctx); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + } + if err := v.ValidateVpcNatConfig(ctx); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) + } - if err := v.ValidateVpcNatGatewayConfig(ctx); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + if err := v.ValidateVpcNatGatewayConfig(ctx); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) + } - if err := v.ValidateIptablesEIP(ctx, &eipNew); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + if err := v.ValidateIptablesEIP(ctx, &eipNew); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) } } return ctrlwebhook.Allowed("by pass") @@ -197,18 +196,17 @@ func (v *ValidatingHook) iptablesDnatUpdateHook(ctx context.Context, req admissi if dnatOld.Status.Ready && dnatOld.Status.Redo == dnatNew.Status.Redo { err := fmt.Errorf("IptablesDnatRule \"%s\" is ready,not support change", dnatNew.Name) return ctrlwebhook.Errored(http.StatusBadRequest, err) - } else { - if err := v.ValidateVpcNatConfig(ctx); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + } + if err := v.ValidateVpcNatConfig(ctx); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) + } - if err := v.ValidateVpcNatGatewayConfig(ctx); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + if err := v.ValidateVpcNatGatewayConfig(ctx); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) + } - if err := v.ValidateIptablesDnat(ctx, &dnatNew); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + if err := v.ValidateIptablesDnat(ctx, &dnatNew); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) } } @@ -251,18 +249,17 @@ func (v *ValidatingHook) iptablesSnatUpdateHook(ctx context.Context, req admissi if snatOld.Status.Ready && snatOld.Status.Redo == snatNew.Status.Redo { err := fmt.Errorf("IptablesSnatRule \"%s\" is ready,not support change", snatNew.Name) return ctrlwebhook.Errored(http.StatusBadRequest, err) - } else { - if err := v.ValidateVpcNatConfig(ctx); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + } + if err := v.ValidateVpcNatConfig(ctx); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) + } - if err := v.ValidateVpcNatGatewayConfig(ctx); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + if err := v.ValidateVpcNatGatewayConfig(ctx); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) + } - if err := v.ValidateIptablesSnat(ctx, &snatNew); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + if err := v.ValidateIptablesSnat(ctx, &snatNew); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) } } @@ -305,18 +302,17 @@ func (v *ValidatingHook) iptablesFipUpdateHook(ctx context.Context, req admissio if fipOld.Status.Ready && fipNew.Status.Redo == fipOld.Status.Redo { err := fmt.Errorf("IptablesFIPRule \"%s\" is ready,not support change", fipNew.Name) return ctrlwebhook.Errored(http.StatusBadRequest, err) - } else { - if err := v.ValidateVpcNatConfig(ctx); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + } + if err := v.ValidateVpcNatConfig(ctx); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) + } - if err := v.ValidateVpcNatGatewayConfig(ctx); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + if err := v.ValidateVpcNatGatewayConfig(ctx); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) + } - if err := v.ValidateIptablesFip(ctx, &fipNew); err != nil { - return ctrlwebhook.Errored(http.StatusBadRequest, err) - } + if err := v.ValidateIptablesFip(ctx, &fipNew); err != nil { + return ctrlwebhook.Errored(http.StatusBadRequest, err) } } return ctrlwebhook.Allowed("by pass") @@ -344,27 +340,27 @@ func (v *ValidatingHook) ValidateVpcNatGW(ctx context.Context, gw *ovnv1.VpcNatG return err } - if net.ParseIP(gw.Spec.LanIp) == nil { - err := fmt.Errorf("lanIp %s is not a valid", gw.Spec.LanIp) + if net.ParseIP(gw.Spec.LanIP) == nil { + err := fmt.Errorf("lanIP %s is not a valid", gw.Spec.LanIP) return err } - if !util.CIDRContainIP(subnet.Spec.CIDRBlock, gw.Spec.LanIp) { - err := fmt.Errorf("lanIp %s is not in the range of subnet %s, cidr %v", - gw.Spec.LanIp, subnet.Name, subnet.Spec.CIDRBlock) + if !util.CIDRContainIP(subnet.Spec.CIDRBlock, gw.Spec.LanIP) { + err := fmt.Errorf("lanIP %s is not in the range of subnet %s, cidr %v", + gw.Spec.LanIP, subnet.Name, subnet.Spec.CIDRBlock) return err } for _, t := range gw.Spec.Tolerations { - if corev1.TolerationOperator(t.Operator) != corev1.TolerationOpExists && - corev1.TolerationOperator(t.Operator) != corev1.TolerationOpEqual { + if t.Operator != corev1.TolerationOpExists && + t.Operator != corev1.TolerationOpEqual { err := fmt.Errorf("invaild taint operator: %s, supported params: \"Equal\", \"Exists\"", t.Operator) return err } - if corev1.TaintEffect(t.Effect) != corev1.TaintEffectNoSchedule && - corev1.TaintEffect(t.Effect) != corev1.TaintEffectNoExecute && - corev1.TaintEffect(t.Effect) != corev1.TaintEffectPreferNoSchedule { + if t.Effect != corev1.TaintEffectNoSchedule && + t.Effect != corev1.TaintEffectNoExecute && + t.Effect != corev1.TaintEffectPreferNoSchedule { err := fmt.Errorf("invaild taint effect: %s, supported params: \"NoSchedule\", \"PreferNoSchedule\", \"NoExecute\"", t.Effect) return err } @@ -471,15 +467,15 @@ func (v *ValidatingHook) ValidateIptablesDnat(ctx context.Context, dnat *ovnv1.I } if port, err := strconv.Atoi(dnat.Spec.InternalPort); err != nil { - errMsg := fmt.Errorf("failed to parse internalIp %s: %v", dnat.Spec.InternalPort, err) + errMsg := fmt.Errorf("failed to parse internalIP %s: %v", dnat.Spec.InternalPort, err) return errMsg } else if port < 0 || port > 65535 { - err := fmt.Errorf("internalIp %s is not a valid port", dnat.Spec.InternalPort) + err := fmt.Errorf("internalIP %s is not a valid port", dnat.Spec.InternalPort) return err } - if net.ParseIP(dnat.Spec.InternalIp) == nil { - err := fmt.Errorf("internalIp %s is not a valid ip", dnat.Spec.InternalIp) + if net.ParseIP(dnat.Spec.InternalIP) == nil { + err := fmt.Errorf("internalIP %s is not a valid ip", dnat.Spec.InternalIP) return err } @@ -521,8 +517,8 @@ func (v *ValidatingHook) ValidateIptablesFip(ctx context.Context, fip *ovnv1.Ipt return err } - if net.ParseIP(fip.Spec.InternalIp) == nil { - err := fmt.Errorf("internalIp %s is not a valid", fip.Spec.InternalIp) + if net.ParseIP(fip.Spec.InternalIP) == nil { + err := fmt.Errorf("internalIP %s is not a valid", fip.Spec.InternalIP) return err } diff --git a/test/e2e/framework/deployment.go b/test/e2e/framework/deployment.go index e044c2db6e7..a783e79a6ec 100644 --- a/test/e2e/framework/deployment.go +++ b/test/e2e/framework/deployment.go @@ -193,7 +193,7 @@ func (c *DeploymentClient) WaitToComplete(deploy *appsv1.Deployment) error { } // WaitToDisappear waits the given timeout duration for the specified deployment to disappear. -func (c *DeploymentClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *DeploymentClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*appsv1.Deployment, error) { deploy, err := c.DeploymentInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/docker/network.go b/test/e2e/framework/docker/network.go index ccac1a1685a..12360becb25 100644 --- a/test/e2e/framework/docker/network.go +++ b/test/e2e/framework/docker/network.go @@ -12,6 +12,7 @@ import ( "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" + "github.com/kubeovn/kube-ovn/pkg/util" ) diff --git a/test/e2e/framework/endpoints.go b/test/e2e/framework/endpoints.go index ae9685b1e56..bb90fec8819 100644 --- a/test/e2e/framework/endpoints.go +++ b/test/e2e/framework/endpoints.go @@ -6,7 +6,6 @@ import ( "fmt" "time" - "github.com/kubeovn/kube-ovn/pkg/util" "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -15,6 +14,8 @@ import ( "k8s.io/apimachinery/pkg/util/wait" v1core "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/kubernetes/test/e2e/framework" + + "github.com/kubeovn/kube-ovn/pkg/util" ) // EndpointsClient is a struct for endpoint client. @@ -103,7 +104,7 @@ func (c *EndpointsClient) DeleteSync(name string) { } // WaitUntil waits the given timeout duration for the specified condition to be met. -func (c *EndpointsClient) WaitUntil(name string, cond func(s *corev1.Endpoints) (bool, error), condDesc string, interval, timeout time.Duration) *corev1.Endpoints { +func (c *EndpointsClient) WaitUntil(name string, cond func(s *corev1.Endpoints) (bool, error), condDesc string, _, timeout time.Duration) *corev1.Endpoints { var endpoints *corev1.Endpoints err := wait.PollUntilContextTimeout(context.Background(), 2*time.Second, timeout, true, func(ctx context.Context) (bool, error) { Logf("Waiting for endpoints %s to meet condition %q", name, condDesc) @@ -132,7 +133,7 @@ func (c *EndpointsClient) WaitUntil(name string, cond func(s *corev1.Endpoints) } // WaitToDisappear waits the given timeout duration for the specified endpoints to disappear. -func (c *EndpointsClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *EndpointsClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*corev1.Endpoints, error) { svc, err := c.EndpointsInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/expect.go b/test/e2e/framework/expect.go index 7e72c60b5f4..1f826f44722 100644 --- a/test/e2e/framework/expect.go +++ b/test/e2e/framework/expect.go @@ -30,12 +30,12 @@ var ( ) // ExpectEqual expects the specified two are the same, otherwise an exception raises -func ExpectEqual(actual interface{}, extra interface{}, explain ...interface{}) { +func ExpectEqual(actual, extra interface{}, explain ...interface{}) { gomega.ExpectWithOffset(1, actual).To(gomega.Equal(extra), explain...) } // ExpectNotEqual expects the specified two are not the same, otherwise an exception raises -func ExpectNotEqual(actual interface{}, extra interface{}, explain ...interface{}) { +func ExpectNotEqual(actual, extra interface{}, explain ...interface{}) { gomega.ExpectWithOffset(1, actual).NotTo(gomega.Equal(extra), explain...) } @@ -84,17 +84,17 @@ func ExpectNoErrorWithOffset(offset int, err error, explain ...interface{}) { // ExpectConsistOf expects actual contains precisely the extra elements. // The ordering of the elements does not matter. -func ExpectConsistOf(actual interface{}, extra interface{}, explain ...interface{}) { +func ExpectConsistOf(actual, extra interface{}, explain ...interface{}) { gomega.ExpectWithOffset(1, actual).To(gomega.ConsistOf(extra), explain...) } // ExpectContainElement expects actual contains the extra elements. -func ExpectContainElement(actual interface{}, extra interface{}, explain ...interface{}) { +func ExpectContainElement(actual, extra interface{}, explain ...interface{}) { gomega.ExpectWithOffset(1, actual).To(gomega.ContainElement(extra), explain...) } // ExpectNotContainElement expects actual does not contain the extra elements. -func ExpectNotContainElement(actual interface{}, extra interface{}, explain ...interface{}) { +func ExpectNotContainElement(actual, extra interface{}, explain ...interface{}) { gomega.ExpectWithOffset(1, actual).NotTo(gomega.ContainElement(extra), explain...) } @@ -109,17 +109,17 @@ func ExpectNotContainSubstring(actual, substr string, explain ...interface{}) { } // ExpectHaveKey expects the actual map has the key in the keyset -func ExpectHaveKey(actual interface{}, key interface{}, explain ...interface{}) { +func ExpectHaveKey(actual, key interface{}, explain ...interface{}) { gomega.ExpectWithOffset(1, actual).To(gomega.HaveKey(key), explain...) } // ExpectHaveKeyWithValue expects the actual map has the passed in key/value pair. -func ExpectHaveKeyWithValue(actual interface{}, key, value interface{}, explain ...interface{}) { +func ExpectHaveKeyWithValue(actual, key, value interface{}, explain ...interface{}) { gomega.ExpectWithOffset(1, actual).To(gomega.HaveKeyWithValue(key, value), explain...) } // ExpectNotHaveKey expects the actual map does not have the key in the keyset -func ExpectNotHaveKey(actual interface{}, key interface{}, explain ...interface{}) { +func ExpectNotHaveKey(actual, key interface{}, explain ...interface{}) { gomega.ExpectWithOffset(1, actual).NotTo(gomega.HaveKey(key), explain...) } diff --git a/test/e2e/framework/framework.go b/test/e2e/framework/framework.go index b23bbb017ff..97c9df16426 100644 --- a/test/e2e/framework/framework.go +++ b/test/e2e/framework/framework.go @@ -40,7 +40,7 @@ type Framework struct { ClusterVersionMajor uint ClusterVersionMinor uint // ipv4/ipv6/dual - ClusterIpFamily string + ClusterIPFamily string // overlay/underlay/underlay-hairpin ClusterNetworkMode string } @@ -50,7 +50,7 @@ func NewDefaultFramework(baseName string) *Framework { Framework: framework.NewDefaultFramework(baseName), } f.NamespacePodSecurityEnforceLevel = admissionapi.LevelPrivileged - f.ClusterIpFamily = os.Getenv("E2E_IP_FAMILY") + f.ClusterIPFamily = os.Getenv("E2E_IP_FAMILY") f.ClusterVersion = os.Getenv("E2E_BRANCH") f.ClusterNetworkMode = os.Getenv("E2E_NETWORK_MODE") @@ -98,7 +98,7 @@ func NewFrameworkWithContext(baseName, kubeContext string) *Framework { f.Framework = framework.NewDefaultFramework(baseName) f.NamespacePodSecurityEnforceLevel = admissionapi.LevelPrivileged - f.ClusterIpFamily = os.Getenv("E2E_IP_FAMILY") + f.ClusterIPFamily = os.Getenv("E2E_IP_FAMILY") f.ClusterVersion = os.Getenv("E2E_BRANCH") f.ClusterNetworkMode = os.Getenv("E2E_NETWORK_MODE") @@ -110,15 +110,15 @@ func NewFrameworkWithContext(baseName, kubeContext string) *Framework { } func (f *Framework) IsIPv4() bool { - return f.ClusterIpFamily == IPv4 + return f.ClusterIPFamily == IPv4 } func (f *Framework) IsIPv6() bool { - return f.ClusterIpFamily == IPv6 + return f.ClusterIPFamily == IPv6 } func (f *Framework) IsDual() bool { - return f.ClusterIpFamily == Dual + return f.ClusterIPFamily == Dual } func (f *Framework) HasIPv4() bool { diff --git a/test/e2e/framework/ip.go b/test/e2e/framework/ip.go index abff67f602c..5088a5a86eb 100644 --- a/test/e2e/framework/ip.go +++ b/test/e2e/framework/ip.go @@ -19,42 +19,42 @@ import ( "github.com/kubeovn/kube-ovn/pkg/util" ) -// IpClient is a struct for Ip client. -type IpClient struct { +// IPClient is a struct for IP client. +type IPClient struct { f *Framework v1.IPInterface } -func (f *Framework) IpClient() *IpClient { - return &IpClient{ +func (f *Framework) IPClient() *IPClient { + return &IPClient{ f: f, IPInterface: f.KubeOVNClientSet.KubeovnV1().IPs(), } } -func (c *IpClient) Get(name string) *apiv1.IP { - Ip, err := c.IPInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *IPClient) Get(name string) *apiv1.IP { + IP, err := c.IPInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) - return Ip.DeepCopy() + return IP.DeepCopy() } -// Create creates a new Ip according to the framework specifications -func (c *IpClient) Create(Ip *apiv1.IP) *apiv1.IP { - Ip, err := c.IPInterface.Create(context.TODO(), Ip, metav1.CreateOptions{}) - ExpectNoError(err, "Error creating Ip") - return Ip.DeepCopy() +// Create creates a new IP according to the framework specifications +func (c *IPClient) Create(iP *apiv1.IP) *apiv1.IP { + iP, err := c.IPInterface.Create(context.TODO(), iP, metav1.CreateOptions{}) + ExpectNoError(err, "Error creating IP") + return iP.DeepCopy() } // CreateSync creates a new IP according to the framework specifications, and waits for it to be ready. -func (c *IpClient) CreateSync(Ip *apiv1.IP) *apiv1.IP { - Ip = c.Create(Ip) - ExpectTrue(c.WaitToBeReady(Ip.Name, timeout)) +func (c *IPClient) CreateSync(iP *apiv1.IP) *apiv1.IP { + iP = c.Create(iP) + ExpectTrue(c.WaitToBeReady(iP.Name, timeout)) // Get the newest IP after it becomes ready - return c.Get(Ip.Name).DeepCopy() + return c.Get(iP.Name).DeepCopy() } // WaitToBeReady returns whether the IP is ready within timeout. -func (c *IpClient) WaitToBeReady(name string, timeout time.Duration) bool { +func (c *IPClient) WaitToBeReady(name string, timeout time.Duration) bool { Logf("Waiting up to %v for IP %s to be ready", timeout, name) for start := time.Now(); time.Since(start) < timeout; time.Sleep(poll) { ip := c.Get(name) @@ -68,22 +68,22 @@ func (c *IpClient) WaitToBeReady(name string, timeout time.Duration) bool { return false } -// Patch patches the Ip -func (c *IpClient) Patch(original, modified *apiv1.IP, timeout time.Duration) *apiv1.IP { +// Patch patches the IP +func (c *IPClient) Patch(original, modified *apiv1.IP, timeout time.Duration) *apiv1.IP { patch, err := util.GenerateMergePatchPayload(original, modified) ExpectNoError(err) - var patchedIp *apiv1.IP + var patchedIP *apiv1.IP err = wait.PollUntilContextTimeout(context.Background(), 2*time.Second, timeout, true, func(ctx context.Context) (bool, error) { p, err := c.IPInterface.Patch(ctx, original.Name, types.MergePatchType, patch, metav1.PatchOptions{}, "") if err != nil { - return handleWaitingAPIError(err, false, "patch Ip %q", original.Name) + return handleWaitingAPIError(err, false, "patch IP %q", original.Name) } - patchedIp = p + patchedIP = p return true, nil }) if err == nil { - return patchedIp.DeepCopy() + return patchedIP.DeepCopy() } if errors.Is(err, context.DeadlineExceeded) { @@ -94,23 +94,23 @@ func (c *IpClient) Patch(original, modified *apiv1.IP, timeout time.Duration) *a return nil } -// Delete deletes a Ip if the Ip exists -func (c *IpClient) Delete(name string) { +// Delete deletes a IP if the IP exists +func (c *IPClient) Delete(name string) { err := c.IPInterface.Delete(context.TODO(), name, metav1.DeleteOptions{}) if err != nil && !apierrors.IsNotFound(err) { - Failf("Failed to delete Ip %q: %v", name, err) + Failf("Failed to delete IP %q: %v", name, err) } } // DeleteSync deletes the IP and waits for the IP to disappear for `timeout`. // If the IP doesn't disappear before the timeout, it will fail the test. -func (c *IpClient) DeleteSync(name string) { +func (c *IPClient) DeleteSync(name string) { c.Delete(name) gomega.Expect(c.WaitToDisappear(name, 2*time.Second, timeout)).To(gomega.Succeed(), "wait for ovn eip %q to disappear", name) } // WaitToDisappear waits the given timeout duration for the specified IP to disappear. -func (c *IpClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *IPClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.IP, error) { ip, err := c.IPInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { @@ -124,10 +124,10 @@ func (c *IpClient) WaitToDisappear(name string, interval, timeout time.Duration) return nil } -func MakeIp(name, ns, subnet string) *apiv1.IP { +func MakeIP(name, ns, subnet string) *apiv1.IP { // pod ip name should including: pod name and namespace // node ip name: only node name - Ip := &apiv1.IP{ + IP := &apiv1.IP{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, @@ -136,5 +136,5 @@ func MakeIp(name, ns, subnet string) *apiv1.IP { Subnet: subnet, }, } - return Ip + return IP } diff --git a/test/e2e/framework/ippool.go b/test/e2e/framework/ippool.go index 3ef92bcdf08..a6cc5e1c265 100644 --- a/test/e2e/framework/ippool.go +++ b/test/e2e/framework/ippool.go @@ -34,8 +34,8 @@ func (f *Framework) IPPoolClient() *IPPoolClient { } } -func (s *IPPoolClient) Get(name string) *apiv1.IPPool { - ippool, err := s.IPPoolInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *IPPoolClient) Get(name string) *apiv1.IPPool { + ippool, err := c.IPPoolInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return ippool } @@ -228,7 +228,7 @@ func (c *IPPoolClient) WaitUntil(name string, cond func(s *apiv1.IPPool) (bool, } // WaitToDisappear waits the given timeout duration for the specified ippool to disappear. -func (c *IPPoolClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *IPPoolClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.IPPool, error) { ippool, err := c.IPPoolInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/iptables-dnat.go b/test/e2e/framework/iptables-dnat.go index 2e3d42acd36..a7384f87dff 100644 --- a/test/e2e/framework/iptables-dnat.go +++ b/test/e2e/framework/iptables-dnat.go @@ -33,8 +33,8 @@ func (f *Framework) IptablesDnatClient() *IptablesDnatClient { } } -func (s *IptablesDnatClient) Get(name string) *apiv1.IptablesDnatRule { - dnat, err := s.IptablesDnatRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *IptablesDnatClient) Get(name string) *apiv1.IptablesDnatRule { + dnat, err := c.IptablesDnatRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return dnat } @@ -82,7 +82,7 @@ func (c *IptablesDnatClient) Patch(original, modified *apiv1.IptablesDnatRule) * // PatchSync patches the iptables dnat and waits for the iptables dnat to be ready for `timeout`. // If the iptables dnat doesn't become ready before the timeout, it will fail the test. -func (c *IptablesDnatClient) PatchSync(original, modified *apiv1.IptablesDnatRule, requiredNodes []string, timeout time.Duration) *apiv1.IptablesDnatRule { +func (c *IptablesDnatClient) PatchSync(original, modified *apiv1.IptablesDnatRule, _ []string, timeout time.Duration) *apiv1.IptablesDnatRule { dnat := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(dnat, timeout)) ExpectTrue(c.WaitToBeReady(dnat.Name, timeout)) @@ -132,7 +132,7 @@ func (c *IptablesDnatClient) WaitToBeUpdated(dnat *apiv1.IptablesDnatRule, timeo } // WaitToDisappear waits the given timeout duration for the specified iptables DNAT rule to disappear. -func (c *IptablesDnatClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *IptablesDnatClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.IptablesDnatRule, error) { rule, err := c.IptablesDnatRuleInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { @@ -155,7 +155,7 @@ func MakeIptablesDnatRule(name, eip, externalPort, protocol, internalIP, interna EIP: eip, ExternalPort: externalPort, Protocol: protocol, - InternalIp: internalIP, + InternalIP: internalIP, InternalPort: internalPort, }, } diff --git a/test/e2e/framework/iptables-eip.go b/test/e2e/framework/iptables-eip.go index b8a43dc8461..29801bef60b 100644 --- a/test/e2e/framework/iptables-eip.go +++ b/test/e2e/framework/iptables-eip.go @@ -33,8 +33,8 @@ func (f *Framework) IptablesEIPClient() *IptablesEIPClient { } } -func (s *IptablesEIPClient) Get(name string) *apiv1.IptablesEIP { - eip, err := s.IptablesEIPInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *IptablesEIPClient) Get(name string) *apiv1.IptablesEIP { + eip, err := c.IptablesEIPInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return eip } @@ -82,7 +82,7 @@ func (c *IptablesEIPClient) Patch(original, modified *apiv1.IptablesEIP) *apiv1. // PatchSync patches the iptables eip and waits for the iptables eip to be ready for `timeout`. // If the iptables eip doesn't become ready before the timeout, it will fail the test. -func (c *IptablesEIPClient) PatchSync(original, modified *apiv1.IptablesEIP, requiredNodes []string, timeout time.Duration) *apiv1.IptablesEIP { +func (c *IptablesEIPClient) PatchSync(original, modified *apiv1.IptablesEIP, _ []string, timeout time.Duration) *apiv1.IptablesEIP { eip := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(eip, timeout)) ExpectTrue(c.WaitToBeReady(eip.Name, timeout)) @@ -92,7 +92,7 @@ func (c *IptablesEIPClient) PatchSync(original, modified *apiv1.IptablesEIP, req // PatchQoS patches the vpc nat gw and waits for the qos to be ready for `timeout`. // If the qos doesn't become ready before the timeout, it will fail the test. -func (c *IptablesEIPClient) PatchQoSPolicySync(eipName string, qosPolicyName string) *apiv1.IptablesEIP { +func (c *IptablesEIPClient) PatchQoSPolicySync(eipName, qosPolicyName string) *apiv1.IptablesEIP { eip := c.Get(eipName) modifiedEIP := eip.DeepCopy() modifiedEIP.Spec.QoSPolicy = qosPolicyName @@ -157,7 +157,7 @@ func (c *IptablesEIPClient) WaitToBeUpdated(eip *apiv1.IptablesEIP, timeout time } // WaitToDisappear waits the given timeout duration for the specified iptables eip to disappear. -func (c *IptablesEIPClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *IptablesEIPClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.IptablesEIP, error) { eip, err := c.IptablesEIPInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/iptables-fip.go b/test/e2e/framework/iptables-fip.go index e6812eaf936..0ecf28f3547 100644 --- a/test/e2e/framework/iptables-fip.go +++ b/test/e2e/framework/iptables-fip.go @@ -33,8 +33,8 @@ func (f *Framework) IptablesFIPClient() *IptablesFIPClient { } } -func (s *IptablesFIPClient) Get(name string) *apiv1.IptablesFIPRule { - fip, err := s.IptablesFIPRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *IptablesFIPClient) Get(name string) *apiv1.IptablesFIPRule { + fip, err := c.IptablesFIPRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return fip } @@ -82,7 +82,7 @@ func (c *IptablesFIPClient) Patch(original, modified *apiv1.IptablesFIPRule) *ap // PatchSync patches the iptables fip and waits for the iptables fip to be ready for `timeout`. // If the iptables fip doesn't become ready before the timeout, it will fail the test. -func (c *IptablesFIPClient) PatchSync(original, modified *apiv1.IptablesFIPRule, requiredNodes []string, timeout time.Duration) *apiv1.IptablesFIPRule { +func (c *IptablesFIPClient) PatchSync(original, modified *apiv1.IptablesFIPRule, _ []string, timeout time.Duration) *apiv1.IptablesFIPRule { fip := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(fip, timeout)) ExpectTrue(c.WaitToBeReady(fip.Name, timeout)) @@ -132,7 +132,7 @@ func (c *IptablesFIPClient) WaitToBeUpdated(fip *apiv1.IptablesFIPRule, timeout } // WaitToDisappear waits the given timeout duration for the specified iptables FIP rule to disappear. -func (c *IptablesFIPClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *IptablesFIPClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.IptablesFIPRule, error) { rule, err := c.IptablesFIPRuleInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { @@ -146,14 +146,14 @@ func (c *IptablesFIPClient) WaitToDisappear(name string, interval, timeout time. return nil } -func MakeIptablesFIPRule(name, eip, internalIp string) *apiv1.IptablesFIPRule { +func MakeIptablesFIPRule(name, eip, internalIP string) *apiv1.IptablesFIPRule { fip := &apiv1.IptablesFIPRule{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: apiv1.IptablesFIPRuleSpec{ EIP: eip, - InternalIp: internalIp, + InternalIP: internalIP, }, } return fip diff --git a/test/e2e/framework/iptables-snat.go b/test/e2e/framework/iptables-snat.go index 87a11709053..7249d0868cc 100644 --- a/test/e2e/framework/iptables-snat.go +++ b/test/e2e/framework/iptables-snat.go @@ -33,8 +33,8 @@ func (f *Framework) IptablesSnatClient() *IptablesSnatClient { } } -func (s *IptablesSnatClient) Get(name string) *apiv1.IptablesSnatRule { - snat, err := s.IptablesSnatRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *IptablesSnatClient) Get(name string) *apiv1.IptablesSnatRule { + snat, err := c.IptablesSnatRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return snat } @@ -82,7 +82,7 @@ func (c *IptablesSnatClient) Patch(original, modified *apiv1.IptablesSnatRule) * // PatchSync patches the iptables snat and waits for the iptables snat to be ready for `timeout`. // If the iptables snat doesn't become ready before the timeout, it will fail the test. -func (c *IptablesSnatClient) PatchSync(original, modified *apiv1.IptablesSnatRule, requiredNodes []string, timeout time.Duration) *apiv1.IptablesSnatRule { +func (c *IptablesSnatClient) PatchSync(original, modified *apiv1.IptablesSnatRule, _ []string, timeout time.Duration) *apiv1.IptablesSnatRule { snat := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(snat, timeout)) ExpectTrue(c.WaitToBeReady(snat.Name, timeout)) @@ -132,7 +132,7 @@ func (c *IptablesSnatClient) WaitToBeUpdated(snat *apiv1.IptablesSnatRule, timeo } // WaitToDisappear waits the given timeout duration for the specified iptables SNAT rule to disappear. -func (c *IptablesSnatClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *IptablesSnatClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.IptablesSnatRule, error) { rule, err := c.IptablesSnatRuleInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/iptables/iptables.go b/test/e2e/framework/iptables/iptables.go index 911115c03e9..e4581668169 100644 --- a/test/e2e/framework/iptables/iptables.go +++ b/test/e2e/framework/iptables/iptables.go @@ -7,15 +7,14 @@ import ( "time" "github.com/onsi/gomega" + corev1 "k8s.io/api/core/v1" + e2epodoutput "k8s.io/kubernetes/test/e2e/framework/pod/output" apiv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1" "github.com/kubeovn/kube-ovn/test/e2e/framework" - corev1 "k8s.io/api/core/v1" - e2epodoutput "k8s.io/kubernetes/test/e2e/framework/pod/output" ) func CheckIptablesRulesOnNode(f *framework.Framework, node, table, chain, protocol string, expectedRules []string, shouldExist bool) { - ovsPod := getOvsPodOnNode(f, node) iptBin := "iptables" diff --git a/test/e2e/framework/log.go b/test/e2e/framework/log.go index 51b4260cc7e..4c8e9ddaa49 100644 --- a/test/e2e/framework/log.go +++ b/test/e2e/framework/log.go @@ -27,7 +27,7 @@ func nowStamp() string { return time.Now().Format(time.StampMilli) } -func log(level string, format string, args ...interface{}) { +func log(level, format string, args ...interface{}) { fmt.Fprintf(ginkgo.GinkgoWriter, nowStamp()+": "+level+": "+format+"\n", args...) } @@ -89,7 +89,7 @@ func PrunedStack(skip int) []byte { n := 0 for i := 0; i < len(stack)/2; i++ { // We filter out based on the source code file name. - if !codeFilterRE.Match([]byte(stack[i*2+1])) { + if !codeFilterRE.Match(stack[i*2+1]) { stack[n] = stack[i*2] stack[n+1] = stack[i*2+1] n += 2 diff --git a/test/e2e/framework/namespace.go b/test/e2e/framework/namespace.go index 54886813e1c..796fab9a2c6 100644 --- a/test/e2e/framework/namespace.go +++ b/test/e2e/framework/namespace.go @@ -32,8 +32,8 @@ func (f *Framework) NamespaceClient() *NamespaceClient { } } -func (s *NamespaceClient) Get(name string) *corev1.Namespace { - np, err := s.NamespaceInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *NamespaceClient) Get(name string) *corev1.Namespace { + np, err := c.NamespaceInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return np } @@ -86,7 +86,7 @@ func (c *NamespaceClient) DeleteSync(name string) { } // WaitToDisappear waits the given timeout duration for the specified namespace to disappear. -func (c *NamespaceClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *NamespaceClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*corev1.Namespace, error) { policy, err := c.NamespaceInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/network-attachment-definition.go b/test/e2e/framework/network-attachment-definition.go index f8f71a7ec1e..28b54aa1338 100644 --- a/test/e2e/framework/network-attachment-definition.go +++ b/test/e2e/framework/network-attachment-definition.go @@ -22,8 +22,8 @@ func (f *Framework) NetworkAttachmentDefinitionClient(namespace string) *Network } } -func (s *NetworkAttachmentDefinitionClient) Get(name string) *apiv1.NetworkAttachmentDefinition { - nad, err := s.NetworkAttachmentDefinitionInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *NetworkAttachmentDefinitionClient) Get(name string) *apiv1.NetworkAttachmentDefinition { + nad, err := c.NetworkAttachmentDefinitionInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return nad } diff --git a/test/e2e/framework/network-policy.go b/test/e2e/framework/network-policy.go index 6c08df8651f..f368aa4188a 100644 --- a/test/e2e/framework/network-policy.go +++ b/test/e2e/framework/network-policy.go @@ -33,8 +33,8 @@ func (f *Framework) NetworkPolicyClientNS(namespace string) *NetworkPolicyClient } } -func (s *NetworkPolicyClient) Get(name string) *netv1.NetworkPolicy { - np, err := s.NetworkPolicyInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *NetworkPolicyClient) Get(name string) *netv1.NetworkPolicy { + np, err := c.NetworkPolicyInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return np } @@ -62,7 +62,7 @@ func (c *NetworkPolicyClient) DeleteSync(name string) { } // WaitToDisappear waits the given timeout duration for the specified network policy to disappear. -func (c *NetworkPolicyClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *NetworkPolicyClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*netv1.NetworkPolicy, error) { policy, err := c.NetworkPolicyInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/ovn-dnat.go b/test/e2e/framework/ovn-dnat.go index 27460a8bcf0..35692c0a0ea 100644 --- a/test/e2e/framework/ovn-dnat.go +++ b/test/e2e/framework/ovn-dnat.go @@ -33,8 +33,8 @@ func (f *Framework) OvnDnatRuleClient() *OvnDnatRuleClient { } } -func (s *OvnDnatRuleClient) Get(name string) *apiv1.OvnDnatRule { - dnat, err := s.OvnDnatRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *OvnDnatRuleClient) Get(name string) *apiv1.OvnDnatRule { + dnat, err := c.OvnDnatRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return dnat } @@ -82,7 +82,7 @@ func (c *OvnDnatRuleClient) Patch(original, modified *apiv1.OvnDnatRule) *apiv1. // PatchSync patches the ovn dnat and waits for the ovn dnat to be ready for `timeout`. // If the ovn dnat doesn't become ready before the timeout, it will fail the test. -func (c *OvnDnatRuleClient) PatchSync(original, modified *apiv1.OvnDnatRule, requiredNodes []string, timeout time.Duration) *apiv1.OvnDnatRule { +func (c *OvnDnatRuleClient) PatchSync(original, modified *apiv1.OvnDnatRule, _ []string, timeout time.Duration) *apiv1.OvnDnatRule { dnat := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(dnat, timeout)) ExpectTrue(c.WaitToBeReady(dnat.Name, timeout)) @@ -134,7 +134,7 @@ func (c *OvnDnatRuleClient) WaitToBeUpdated(dnat *apiv1.OvnDnatRule, timeout tim } // WaitToDisappear waits the given timeout duration for the specified ovn dnat to disappear. -func (c *OvnDnatRuleClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *OvnDnatRuleClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.OvnDnatRule, error) { rule, err := c.OvnDnatRuleInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { @@ -155,8 +155,8 @@ func MakeOvnDnatRule(name, ovnEip, ipType, ipName, internalPort, externalPort, p }, Spec: apiv1.OvnDnatRuleSpec{ OvnEip: ovnEip, - IpType: ipType, - IpName: ipName, + IPType: ipType, + IPName: ipName, InternalPort: internalPort, ExternalPort: externalPort, Protocol: protocol, diff --git a/test/e2e/framework/ovn-eip.go b/test/e2e/framework/ovn-eip.go index b2812d9691b..3c285b554c9 100644 --- a/test/e2e/framework/ovn-eip.go +++ b/test/e2e/framework/ovn-eip.go @@ -33,8 +33,8 @@ func (f *Framework) OvnEipClient() *OvnEipClient { } } -func (s *OvnEipClient) Get(name string) *apiv1.OvnEip { - eip, err := s.OvnEipInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *OvnEipClient) Get(name string) *apiv1.OvnEip { + eip, err := c.OvnEipInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return eip } @@ -82,7 +82,7 @@ func (c *OvnEipClient) Patch(original, modified *apiv1.OvnEip) *apiv1.OvnEip { // PatchSync patches the ovn eip and waits for the ovn eip to be ready for `timeout`. // If the ovn eip doesn't become ready before the timeout, it will fail the test. -func (c *OvnEipClient) PatchSync(original, modified *apiv1.OvnEip, requiredNodes []string, timeout time.Duration) *apiv1.OvnEip { +func (c *OvnEipClient) PatchSync(original, modified *apiv1.OvnEip, _ []string, timeout time.Duration) *apiv1.OvnEip { eip := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(eip, timeout)) ExpectTrue(c.WaitToBeReady(eip.Name, timeout)) @@ -134,7 +134,7 @@ func (c *OvnEipClient) WaitToBeUpdated(eip *apiv1.OvnEip, timeout time.Duration) } // WaitToDisappear waits the given timeout duration for the specified OVN EIP to disappear. -func (c *OvnEipClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *OvnEipClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.OvnEip, error) { eip, err := c.OvnEipInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/ovn-fip.go b/test/e2e/framework/ovn-fip.go index f16e000b94d..f21883edfc6 100644 --- a/test/e2e/framework/ovn-fip.go +++ b/test/e2e/framework/ovn-fip.go @@ -33,8 +33,8 @@ func (f *Framework) OvnFipClient() *OvnFipClient { } } -func (s *OvnFipClient) Get(name string) *apiv1.OvnFip { - fip, err := s.OvnFipInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *OvnFipClient) Get(name string) *apiv1.OvnFip { + fip, err := c.OvnFipInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return fip } @@ -82,7 +82,7 @@ func (c *OvnFipClient) Patch(original, modified *apiv1.OvnFip) *apiv1.OvnFip { // PatchSync patches the ovn fip and waits for the ovn fip to be ready for `timeout`. // If the ovn fip doesn't become ready before the timeout, it will fail the test. -func (c *OvnFipClient) PatchSync(original, modified *apiv1.OvnFip, requiredNodes []string, timeout time.Duration) *apiv1.OvnFip { +func (c *OvnFipClient) PatchSync(original, modified *apiv1.OvnFip, _ []string, timeout time.Duration) *apiv1.OvnFip { fip := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(fip, timeout)) ExpectTrue(c.WaitToBeReady(fip.Name, timeout)) @@ -134,7 +134,7 @@ func (c *OvnFipClient) WaitToBeUpdated(fip *apiv1.OvnFip, timeout time.Duration) } // WaitToDisappear waits the given timeout duration for the specified ovn fip to disappear. -func (c *OvnFipClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *OvnFipClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.OvnFip, error) { fip, err := c.OvnFipInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { @@ -155,8 +155,8 @@ func MakeOvnFip(name, ovnEip, ipType, ipName string) *apiv1.OvnFip { }, Spec: apiv1.OvnFipSpec{ OvnEip: ovnEip, - IpType: ipType, - IpName: ipName, + IPType: ipType, + IPName: ipName, }, } return fip diff --git a/test/e2e/framework/ovn-snat.go b/test/e2e/framework/ovn-snat.go index c54f3680300..9aea1ae2ef1 100644 --- a/test/e2e/framework/ovn-snat.go +++ b/test/e2e/framework/ovn-snat.go @@ -33,8 +33,8 @@ func (f *Framework) OvnSnatRuleClient() *OvnSnatRuleClient { } } -func (s *OvnSnatRuleClient) Get(name string) *apiv1.OvnSnatRule { - snat, err := s.OvnSnatRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *OvnSnatRuleClient) Get(name string) *apiv1.OvnSnatRule { + snat, err := c.OvnSnatRuleInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return snat } @@ -82,7 +82,7 @@ func (c *OvnSnatRuleClient) Patch(original, modified *apiv1.OvnSnatRule) *apiv1. // PatchSync patches the ovn snat and waits for the ovn snat to be ready for `timeout`. // If the ovn snat doesn't become ready before the timeout, it will fail the test. -func (c *OvnSnatRuleClient) PatchSync(original, modified *apiv1.OvnSnatRule, requiredNodes []string, timeout time.Duration) *apiv1.OvnSnatRule { +func (c *OvnSnatRuleClient) PatchSync(original, modified *apiv1.OvnSnatRule, _ []string, timeout time.Duration) *apiv1.OvnSnatRule { snat := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(snat, timeout)) ExpectTrue(c.WaitToBeReady(snat.Name, timeout)) @@ -134,7 +134,7 @@ func (c *OvnSnatRuleClient) WaitToBeUpdated(snat *apiv1.OvnSnatRule, timeout tim } // WaitToDisappear waits the given timeout duration for the specified OVN SNAT rule to disappear. -func (c *OvnSnatRuleClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *OvnSnatRuleClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.OvnSnatRule, error) { rule, err := c.OvnSnatRuleInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { @@ -156,7 +156,7 @@ func MakeOvnSnatRule(name, ovnEip, vpcSubnet, ipName string) *apiv1.OvnSnatRule Spec: apiv1.OvnSnatRuleSpec{ OvnEip: ovnEip, VpcSubnet: vpcSubnet, - IpName: ipName, + IPName: ipName, }, } return snat diff --git a/test/e2e/framework/provider-network.go b/test/e2e/framework/provider-network.go index 2e64c1b1f5b..f381d73938b 100644 --- a/test/e2e/framework/provider-network.go +++ b/test/e2e/framework/provider-network.go @@ -34,8 +34,8 @@ func (f *Framework) ProviderNetworkClient() *ProviderNetworkClient { } } -func (s *ProviderNetworkClient) Get(name string) *apiv1.ProviderNetwork { - pn, err := s.ProviderNetworkInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *ProviderNetworkClient) Get(name string) *apiv1.ProviderNetwork { + pn, err := c.ProviderNetworkInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return pn } @@ -83,7 +83,7 @@ func (c *ProviderNetworkClient) Patch(original, modified *apiv1.ProviderNetwork) // PatchSync patches the provider network and waits for the provider network to be ready for `timeout`. // If the provider network doesn't become ready before the timeout, it will fail the test. -func (c *ProviderNetworkClient) PatchSync(original, modified *apiv1.ProviderNetwork, requiredNodes []string, timeout time.Duration) *apiv1.ProviderNetwork { +func (c *ProviderNetworkClient) PatchSync(original, modified *apiv1.ProviderNetwork, _ []string, timeout time.Duration) *apiv1.ProviderNetwork { pn := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(pn, timeout)) ExpectTrue(c.WaitToBeReady(pn.Name, timeout)) @@ -172,7 +172,7 @@ func (c *ProviderNetworkClient) WaitToBeUpdated(pn *apiv1.ProviderNetwork, timeo } // WaitToDisappear waits the given timeout duration for the specified provider network to disappear. -func (c *ProviderNetworkClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *ProviderNetworkClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.ProviderNetwork, error) { pn, err := c.ProviderNetworkInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/qos-policy.go b/test/e2e/framework/qos-policy.go index 6414c1378be..17b6b982608 100644 --- a/test/e2e/framework/qos-policy.go +++ b/test/e2e/framework/qos-policy.go @@ -36,8 +36,8 @@ func (f *Framework) QoSPolicyClient() *QoSPolicyClient { } } -func (s *QoSPolicyClient) Get(name string) *apiv1.QoSPolicy { - qosPolicy, err := s.QoSPolicyInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *QoSPolicyClient) Get(name string) *apiv1.QoSPolicy { + qosPolicy, err := c.QoSPolicyInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return qosPolicy } @@ -230,7 +230,7 @@ func (c *QoSPolicyClient) WaitUntil(name string, cond func(s *apiv1.QoSPolicy) ( } // WaitToDisappear waits the given timeout duration for the specified qosPolicy to disappear. -func (c *QoSPolicyClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *QoSPolicyClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.QoSPolicy, error) { qosPolicy, err := c.QoSPolicyInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { @@ -262,7 +262,7 @@ func (c *QoSPolicyClient) WaitToQoSReady(name string) bool { for index, specRule := range qos.Spec.BandwidthLimitRules { statusRule := qos.Status.BandwidthLimitRules[index] if reflect.DeepEqual(specRule, statusRule) { - equalCount += 1 + equalCount++ } } diff --git a/test/e2e/framework/service.go b/test/e2e/framework/service.go index 78083d11e97..0535d203fa7 100644 --- a/test/e2e/framework/service.go +++ b/test/e2e/framework/service.go @@ -134,7 +134,7 @@ func (c *ServiceClient) WaitUntil(name string, cond func(s *corev1.Service) (boo } // WaitToDisappear waits the given timeout duration for the specified service to disappear. -func (c *ServiceClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *ServiceClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*corev1.Service, error) { svc, err := c.ServiceInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/statefulset.go b/test/e2e/framework/statefulset.go index f98bc70d705..9adfb85872e 100644 --- a/test/e2e/framework/statefulset.go +++ b/test/e2e/framework/statefulset.go @@ -82,7 +82,7 @@ func (c *StatefulSetClient) WaitForRunningAndReady(sts *appsv1.StatefulSet) { } // WaitToDisappear waits the given timeout duration for the specified statefulset to disappear. -func (c *StatefulSetClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *StatefulSetClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*appsv1.StatefulSet, error) { sts, err := c.StatefulSetInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/subnet.go b/test/e2e/framework/subnet.go index f449c2a0980..ff3b4b2be65 100644 --- a/test/e2e/framework/subnet.go +++ b/test/e2e/framework/subnet.go @@ -35,8 +35,8 @@ func (f *Framework) SubnetClient() *SubnetClient { } } -func (s *SubnetClient) Get(name string) *apiv1.Subnet { - subnet, err := s.SubnetInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *SubnetClient) Get(name string) *apiv1.Subnet { + subnet, err := c.SubnetInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return subnet } @@ -229,7 +229,7 @@ func (c *SubnetClient) WaitUntil(name string, cond func(s *apiv1.Subnet) (bool, } // WaitToDisappear waits the given timeout duration for the specified subnet to disappear. -func (c *SubnetClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *SubnetClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.Subnet, error) { subnet, err := c.SubnetInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/switch-lb-rule.go b/test/e2e/framework/switch-lb-rule.go index b5038c0039a..ff3d0cf5663 100644 --- a/test/e2e/framework/switch-lb-rule.go +++ b/test/e2e/framework/switch-lb-rule.go @@ -6,6 +6,7 @@ import ( "fmt" "time" + "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -16,7 +17,6 @@ import ( apiv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1" v1 "github.com/kubeovn/kube-ovn/pkg/client/clientset/versioned/typed/kubeovn/v1" "github.com/kubeovn/kube-ovn/pkg/util" - "github.com/onsi/gomega" ) // SwitchLBRuleClient is a struct for switch-lb-rule client. @@ -105,7 +105,7 @@ func (c *SwitchLBRuleClient) DeleteSync(name string) { } // WaitUntil waits the given timeout duration for the specified condition to be met. -func (c *SwitchLBRuleClient) WaitUntil(name string, cond func(s *apiv1.SwitchLBRule) (bool, error), condDesc string, interval, timeout time.Duration) *apiv1.SwitchLBRule { +func (c *SwitchLBRuleClient) WaitUntil(name string, cond func(s *apiv1.SwitchLBRule) (bool, error), condDesc string, _, timeout time.Duration) *apiv1.SwitchLBRule { var rules *apiv1.SwitchLBRule err := wait.PollUntilContextTimeout(context.Background(), 2*time.Second, timeout, true, func(ctx context.Context) (bool, error) { Logf("Waiting for switch-lb-rule %s to meet condition %q", name, condDesc) @@ -134,7 +134,7 @@ func (c *SwitchLBRuleClient) WaitUntil(name string, cond func(s *apiv1.SwitchLBR } // WaitToDisappear waits the given timeout duration for the specified switch-lb-rule to disappear. -func (c *SwitchLBRuleClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *SwitchLBRuleClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.SwitchLBRule, error) { svc, err := c.SwitchLBRuleInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/vip.go b/test/e2e/framework/vip.go index 8c4816d271e..bdd37ad5c2e 100644 --- a/test/e2e/framework/vip.go +++ b/test/e2e/framework/vip.go @@ -109,7 +109,7 @@ func (c *VipClient) DeleteSync(name string) { } // WaitToDisappear waits the given timeout duration for the specified OVN VIP to disappear. -func (c *VipClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *VipClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.Vip, error) { vip, err := c.VipInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/vlan.go b/test/e2e/framework/vlan.go index 77c63024811..955ce0d3824 100644 --- a/test/e2e/framework/vlan.go +++ b/test/e2e/framework/vlan.go @@ -28,8 +28,8 @@ func (f *Framework) VlanClient() *VlanClient { } } -func (s *VlanClient) Get(name string) *apiv1.Vlan { - vlan, err := s.VlanInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *VlanClient) Get(name string) *apiv1.Vlan { + vlan, err := c.VlanInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return vlan } diff --git a/test/e2e/framework/vpc-nat-gw.go b/test/e2e/framework/vpc-nat-gw.go index 7aafa05071b..7243a5b09e1 100644 --- a/test/e2e/framework/vpc-nat-gw.go +++ b/test/e2e/framework/vpc-nat-gw.go @@ -34,8 +34,8 @@ func (f *Framework) VpcNatGatewayClient() *VpcNatGatewayClient { } } -func (s *VpcNatGatewayClient) Get(name string) *apiv1.VpcNatGateway { - vpcNatGw, err := s.VpcNatGatewayInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *VpcNatGatewayClient) Get(name string) *apiv1.VpcNatGateway { + vpcNatGw, err := c.VpcNatGatewayInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return vpcNatGw } @@ -95,7 +95,7 @@ func (c *VpcNatGatewayClient) PatchSync(original, modified *apiv1.VpcNatGateway, // PatchQoS patches the vpc nat gw and waits for the qos to be ready for `timeout`. // If the qos doesn't become ready before the timeout, it will fail the test. -func (c *VpcNatGatewayClient) PatchQoSPolicySync(natgwName string, qosPolicyName string) *apiv1.VpcNatGateway { +func (c *VpcNatGatewayClient) PatchQoSPolicySync(natgwName, qosPolicyName string) *apiv1.VpcNatGateway { natgw := c.Get(natgwName) modifiedNATGW := natgw.DeepCopy() modifiedNATGW.Spec.QoSPolicy = qosPolicyName @@ -122,7 +122,7 @@ func (c *VpcNatGatewayClient) DeleteSync(name string) { // WaitToBeReady returns whether the vpc nat gw is ready within timeout. func (c *VpcNatGatewayClient) WaitToBeReady(name string, timeout time.Duration) bool { for start := time.Now(); time.Since(start) < timeout; time.Sleep(poll) { - if c.Get(name).Spec.LanIp != "" { + if c.Get(name).Spec.LanIP != "" { return true } } @@ -165,7 +165,7 @@ func (c *VpcNatGatewayClient) WaitToBeUpdated(vpcNatGw *apiv1.VpcNatGateway, tim } // WaitToDisappear waits the given timeout duration for the specified VPC NAT gateway to disappear. -func (c *VpcNatGatewayClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *VpcNatGatewayClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*apiv1.VpcNatGateway, error) { gw, err := c.VpcNatGatewayInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { @@ -192,7 +192,7 @@ func (c *VpcNatGatewayClient) WaitToQoSReady(name string) bool { return false } -func MakeVpcNatGateway(name, vpc, subnet, lanIp, externalSubnet, qosPolicyName string) *apiv1.VpcNatGateway { +func MakeVpcNatGateway(name, vpc, subnet, lanIP, externalSubnet, qosPolicyName string) *apiv1.VpcNatGateway { vpcNatGw := &apiv1.VpcNatGateway{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -200,7 +200,7 @@ func MakeVpcNatGateway(name, vpc, subnet, lanIp, externalSubnet, qosPolicyName s Spec: apiv1.VpcNatSpec{ Vpc: vpc, Subnet: subnet, - LanIp: lanIp, + LanIP: lanIP, }, } if externalSubnet != "" { diff --git a/test/e2e/framework/vpc.go b/test/e2e/framework/vpc.go index 39325a88250..9f49fba502a 100644 --- a/test/e2e/framework/vpc.go +++ b/test/e2e/framework/vpc.go @@ -33,8 +33,8 @@ func (f *Framework) VpcClient() *VpcClient { } } -func (s *VpcClient) Get(name string) *kubeovnv1.Vpc { - vpc, err := s.VpcInterface.Get(context.TODO(), name, metav1.GetOptions{}) +func (c *VpcClient) Get(name string) *kubeovnv1.Vpc { + vpc, err := c.VpcInterface.Get(context.TODO(), name, metav1.GetOptions{}) ExpectNoError(err) return vpc } @@ -82,7 +82,7 @@ func (c *VpcClient) Patch(original, modified *kubeovnv1.Vpc) *kubeovnv1.Vpc { // PatchSync patches the vpc and waits for the vpc to be ready for `timeout`. // If the vpc doesn't become ready before the timeout, it will fail the test. -func (c *VpcClient) PatchSync(original, modified *kubeovnv1.Vpc, requiredNodes []string, timeout time.Duration) *kubeovnv1.Vpc { +func (c *VpcClient) PatchSync(original, modified *kubeovnv1.Vpc, _ []string, timeout time.Duration) *kubeovnv1.Vpc { vpc := c.Patch(original, modified) ExpectTrue(c.WaitToBeUpdated(vpc, timeout)) ExpectTrue(c.WaitToBeReady(vpc.Name, timeout)) @@ -131,7 +131,7 @@ func (c *VpcClient) WaitToBeUpdated(vpc *kubeovnv1.Vpc, timeout time.Duration) b } // WaitToDisappear waits the given timeout duration for the specified VPC to disappear. -func (c *VpcClient) WaitToDisappear(name string, interval, timeout time.Duration) error { +func (c *VpcClient) WaitToDisappear(name string, _, timeout time.Duration) error { err := framework.Gomega().Eventually(context.Background(), framework.HandleRetry(func(ctx context.Context) (*kubeovnv1.Vpc, error) { vpc, err := c.VpcInterface.Get(ctx, name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { diff --git a/test/e2e/framework/wait.go b/test/e2e/framework/wait.go index 4d0cb7d7a74..6ae2e79b4ff 100644 --- a/test/e2e/framework/wait.go +++ b/test/e2e/framework/wait.go @@ -62,7 +62,7 @@ func shouldRetry(err error) (retry bool, retryAfter time.Duration) { } // WaitUntil waits the condition to be met -func WaitUntil(interval, timeout time.Duration, cond func(context.Context) (bool, error), condDesc string) { +func WaitUntil(_, timeout time.Duration, cond func(context.Context) (bool, error), condDesc string) { if err := wait.PollUntilContextTimeout(context.Background(), 2*time.Second, timeout, false, cond); err != nil { if errors.Is(err, context.DeadlineExceeded) { Failf("timed out while waiting for the condition to be met: %s", condDesc) diff --git a/test/e2e/iptables-vpc-nat-gw/e2e_test.go b/test/e2e/iptables-vpc-nat-gw/e2e_test.go index 4c625b39bef..994665f84c9 100644 --- a/test/e2e/iptables-vpc-nat-gw/e2e_test.go +++ b/test/e2e/iptables-vpc-nat-gw/e2e_test.go @@ -32,14 +32,18 @@ import ( "github.com/kubeovn/kube-ovn/test/e2e/framework/kind" ) -const dockerExtNet1Name = "kube-ovn-ext-net1" -const dockerExtNet2Name = "kube-ovn-ext-net2" -const vpcNatGWConfigMapName = "ovn-vpc-nat-gw-config" -const networkAttachDefName = "ovn-vpc-external-network" -const externalSubnetProvider = "ovn-vpc-external-network.kube-system" +const ( + dockerExtNet1Name = "kube-ovn-ext-net1" + dockerExtNet2Name = "kube-ovn-ext-net2" + vpcNatGWConfigMapName = "ovn-vpc-nat-gw-config" + networkAttachDefName = "ovn-vpc-external-network" + externalSubnetProvider = "ovn-vpc-external-network.kube-system" +) -const iperf2Port = "20288" -const skipIperf = false +const ( + iperf2Port = "20288" + skipIperf = false +) const ( eipLimit = iota*5 + 10 @@ -140,14 +144,13 @@ func setupVpcNatGwTestEnvironment( natGwQosPolicy string, overlaySubnetV4Cidr string, overlaySubnetV4Gw string, - lanIp string, + lanIP string, dockerExtNetName string, externalNetworkName string, nicName string, provider string, skipNADSetup bool, ) { - if !skipNADSetup { setupNetworkAttachmentDefinition( f, dockerExtNetNetwork, attachNetClient, @@ -159,7 +162,7 @@ func setupVpcNatGwTestEnvironment( framework.ExpectNoError(err, "failed to get ConfigMap") ginkgo.By("Creating custom vpc " + vpcName) - vpc := framework.MakeVpc(vpcName, lanIp, false, false, nil) + vpc := framework.MakeVpc(vpcName, lanIP, false, false, nil) _ = vpcClient.CreateSync(vpc) ginkgo.By("Creating custom overlay subnet " + overlaySubnetName) @@ -167,7 +170,7 @@ func setupVpcNatGwTestEnvironment( _ = subnetClient.CreateSync(overlaySubnet) ginkgo.By("Creating custom vpc nat gw " + vpcNatGwName) - vpcNatGw := framework.MakeVpcNatGateway(vpcNatGwName, vpcName, overlaySubnetName, lanIp, externalNetworkName, natGwQosPolicy) + vpcNatGw := framework.MakeVpcNatGateway(vpcNatGwName, vpcName, overlaySubnetName, lanIP, externalNetworkName, natGwQosPolicy) _ = vpcNatGwClient.CreateSync(vpcNatGw, f.ClientSet) } @@ -185,7 +188,7 @@ var _ = framework.Describe("[group:iptables-vpc-nat-gw]", func() { // sharing case var sharedVipName, sharedEipName, sharedEipDnatName, sharedEipSnatName, sharedEipFipShoudOkName, sharedEipFipShoudFailName string var vipClient *framework.VipClient - var ipClient *framework.IpClient + var ipClient *framework.IPClient var iptablesEIPClient *framework.IptablesEIPClient var iptablesFIPClient *framework.IptablesFIPClient var iptablesSnatRuleClient *framework.IptablesSnatClient @@ -245,7 +248,7 @@ var _ = framework.Describe("[group:iptables-vpc-nat-gw]", func() { vpcNatGwClient = f.VpcNatGatewayClient() iptablesEIPClient = f.IptablesEIPClient() vipClient = f.VipClient() - ipClient = f.IpClient() + ipClient = f.IPClient() iptablesFIPClient = f.IptablesFIPClient() iptablesSnatRuleClient = f.IptablesSnatClient() iptablesDnatRuleClient = f.IptablesDnatClient() @@ -369,13 +372,13 @@ var _ = framework.Describe("[group:iptables-vpc-nat-gw]", func() { framework.ConformanceIt("iptables eip fip snat dnat", func() { overlaySubnetV4Cidr := "10.0.0.0/24" overlaySubnetV4Gw := "10.0.0.1" - lanIp := "10.0.0.254" + lanIP := "10.0.0.254" natgwQoS := "" setupVpcNatGwTestEnvironment( f, dockerExtNet1Network, attachNetClient, subnetClient, vpcClient, vpcNatGwClient, vpcName, overlaySubnetName, vpcNatGwName, natgwQoS, - overlaySubnetV4Cidr, overlaySubnetV4Gw, lanIp, + overlaySubnetV4Cidr, overlaySubnetV4Gw, lanIP, dockerExtNet1Name, networkAttachDefName, net1NicName, externalSubnetProvider, false, @@ -514,13 +517,13 @@ var _ = framework.Describe("[group:iptables-vpc-nat-gw]", func() { // multiple external network case net2OverlaySubnetV4Cidr := "10.0.1.0/24" net2OoverlaySubnetV4Gw := "10.0.1.1" - net2LanIp := "10.0.1.254" + net2LanIP := "10.0.1.254" natgwQoS = "" setupVpcNatGwTestEnvironment( f, dockerExtNet2Network, attachNetClient, subnetClient, vpcClient, vpcNatGwClient, net2VpcName, net2OverlaySubnetName, net2VpcNatGwName, natgwQoS, - net2OverlaySubnetV4Cidr, net2OoverlaySubnetV4Gw, net2LanIp, + net2OverlaySubnetV4Cidr, net2OoverlaySubnetV4Gw, net2LanIP, dockerExtNet2Name, net2AttachDefName, net2NicName, net2SubnetProvider, false, @@ -577,8 +580,9 @@ func iperf(f *framework.Framework, iperfClientPod *corev1.Pod, iperfServerEIP *a } func checkQos(f *framework.Framework, - vpc1Pod *corev1.Pod, vpc2Pod *corev1.Pod, vpc1EIP *apiv1.IptablesEIP, vpc2EIP *apiv1.IptablesEIP, - limit int, expect bool) { + vpc1Pod, vpc2Pod *corev1.Pod, vpc1EIP, vpc2EIP *apiv1.IptablesEIP, + limit int, expect bool, +) { if !skipIperf { if expect { output := iperf(f, vpc1Pod, vpc2EIP) @@ -909,7 +913,7 @@ func priorityQoSCases(f *framework.Framework, func createNatGwAndSetQosCases(f *framework.Framework, vpcNatGwClient *framework.VpcNatGatewayClient, - ipClient *framework.IpClient, + ipClient *framework.IPClient, eipClient *framework.IptablesEIPClient, fipClient *framework.IptablesFIPClient, subnetClient *framework.SubnetClient, @@ -922,7 +926,7 @@ func createNatGwAndSetQosCases(f *framework.Framework, fipName string, vpcName string, overlaySubnetName string, - lanIp string, + lanIP string, attachDefName string, ) { // delete fip @@ -956,7 +960,7 @@ func createNatGwAndSetQosCases(f *framework.Framework, _ = qosPolicyClient.CreateSync(qosPolicy) ginkgo.By("Creating custom vpc nat gw") - vpcNatGw := framework.MakeVpcNatGateway(natgwName, vpcName, overlaySubnetName, lanIp, attachDefName, natgwQoSPolicyName) + vpcNatGw := framework.MakeVpcNatGateway(natgwName, vpcName, overlaySubnetName, lanIP, attachDefName, natgwQoSPolicyName) _ = vpcNatGwClient.CreateSync(vpcNatGw, f.ClientSet) eipQoSPolicyName := "eip-qos-policy-" + framework.RandomSuffix() @@ -1028,7 +1032,7 @@ var _ = framework.Describe("[group:qos-policy]", func() { var vpcNatGwClient *framework.VpcNatGatewayClient var subnetClient *framework.SubnetClient var podClient *framework.PodClient - var ipClient *framework.IpClient + var ipClient *framework.IPClient var iptablesEIPClient *framework.IptablesEIPClient var iptablesFIPClient *framework.IptablesFIPClient var qosPolicyClient *framework.QoSPolicyClient @@ -1049,7 +1053,7 @@ var _ = framework.Describe("[group:qos-policy]", func() { var vpc1FIP *apiv1.IptablesFIPRule var vpc2FIP *apiv1.IptablesFIPRule - var lanIp string + var lanIP string var overlaySubnetV4Cidr string var overlaySubnetV4Gw string var eth0Exist, net1Exist bool @@ -1088,7 +1092,7 @@ var _ = framework.Describe("[group:qos-policy]", func() { vpcClient = f.VpcClient() vpcNatGwClient = f.VpcNatGatewayClient() iptablesEIPClient = f.IptablesEIPClient() - ipClient = f.IpClient() + ipClient = f.IPClient() iptablesFIPClient = f.IptablesFIPClient() qosPolicyClient = f.QoSPolicyClient() if image == "" { @@ -1183,18 +1187,18 @@ var _ = framework.Describe("[group:qos-policy]", func() { } }) - var _ = framework.Describe("vpc qos", func() { + _ = framework.Describe("vpc qos", func() { ginkgo.BeforeEach(func() { iperfServerCmd = []string{"iperf", "-s", "-i", "1", "-p", iperf2Port} overlaySubnetV4Cidr = "10.0.0.0/24" overlaySubnetV4Gw = "10.0.0.1" - lanIp = "10.0.0.254" + lanIP = "10.0.0.254" natgwQoS := "" setupVpcNatGwTestEnvironment( f, dockerExtNetNetwork, attachNetClient, subnetClient, vpcClient, vpcNatGwClient, vpcQosParams.vpc1Name, vpcQosParams.vpc1SubnetName, vpcQosParams.vpcNat1GwName, - natgwQoS, overlaySubnetV4Cidr, overlaySubnetV4Gw, lanIp, + natgwQoS, overlaySubnetV4Cidr, overlaySubnetV4Gw, lanIP, dockerExtNetName, vpcQosParams.attachDefName, net1NicName, vpcQosParams.subnetProvider, true, @@ -1218,7 +1222,7 @@ var _ = framework.Describe("[group:qos-policy]", func() { f, dockerExtNetNetwork, attachNetClient, subnetClient, vpcClient, vpcNatGwClient, vpcQosParams.vpc2Name, vpcQosParams.vpc2SubnetName, vpcQosParams.vpcNat2GwName, - natgwQoS, overlaySubnetV4Cidr, overlaySubnetV4Gw, lanIp, + natgwQoS, overlaySubnetV4Cidr, overlaySubnetV4Gw, lanIP, dockerExtNetName, vpcQosParams.attachDefName, net1NicName, vpcQosParams.subnetProvider, true, @@ -1298,7 +1302,6 @@ var _ = framework.Describe("[group:qos-policy]", func() { ipClient.DeleteSync(net1IpName) ginkgo.By("Deleting overlay subnet " + vpcQosParams.vpc2SubnetName) subnetClient.DeleteSync(vpcQosParams.vpc2SubnetName) - }) framework.ConformanceIt("default nic qos", func() { // case 1: set qos policy for natgw @@ -1316,7 +1319,7 @@ var _ = framework.Describe("[group:qos-policy]", func() { // case 1: set specific ip qos policy for natgw specifyingIPQoSCases(f, vpcNatGwClient, qosPolicyClient, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, vpcQosParams.vpcNat1GwName) }) - framework.ConformanceIt("qos priority maching", func() { + framework.ConformanceIt("qos priority matching ", func() { // case 1: test qos match priority // case 2: change qos policy of natgw priorityQoSCases(f, vpcNatGwClient, iptablesEIPClient, qosPolicyClient, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, vpcQosParams.vpcNat1GwName, vpcQosParams.vpc1EIPName) @@ -1328,7 +1331,7 @@ var _ = framework.Describe("[group:qos-policy]", func() { vpcNatGwClient, ipClient, iptablesEIPClient, iptablesFIPClient, subnetClient, qosPolicyClient, vpc1Pod, vpc2Pod, vpc2EIP, vpcQosParams.vpcNat1GwName, vpcQosParams.vpc1EIPName, vpcQosParams.vpc1FIPName, vpcQosParams.vpc1Name, - vpcQosParams.vpc1SubnetName, lanIp, vpcQosParams.attachDefName) + vpcQosParams.vpc1SubnetName, lanIP, vpcQosParams.attachDefName) }) }) }) diff --git a/test/e2e/kube-ovn/ipam/ipam.go b/test/e2e/kube-ovn/ipam/ipam.go index 6466265dc1b..6137d5ad480 100644 --- a/test/e2e/kube-ovn/ipam/ipam.go +++ b/test/e2e/kube-ovn/ipam/ipam.go @@ -45,7 +45,7 @@ var _ = framework.Describe("[group:ipam]", func() { podName = "pod-" + framework.RandomSuffix() deployName = "deploy-" + framework.RandomSuffix() stsName = "sts-" + framework.RandomSuffix() - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) ginkgo.By("Creating subnet " + subnetName) subnet = framework.MakeSubnet(subnetName, "", cidr, "", "", "", nil, nil, []string{namespaceName}) @@ -74,7 +74,7 @@ var _ = framework.Describe("[group:ipam]", func() { ginkgo.By("Creating pod " + podName + " with ip " + ip + " and mac " + mac) annotations := map[string]string{ - util.IpAddressAnnotation: ip, + util.IPAddressAnnotation: ip, util.MacAddressAnnotation: mac, } pod := framework.MakePod(namespaceName, podName, nil, annotations, "", nil, nil) @@ -83,7 +83,7 @@ var _ = framework.Describe("[group:ipam]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.CidrAnnotation, subnet.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(pod.Annotations, util.GatewayAnnotation, subnet.Spec.Gateway) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpAddressAnnotation, ip) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPAddressAnnotation, ip) framework.ExpectHaveKeyWithValue(pod.Annotations, util.LogicalSwitchAnnotation, subnet.Name) framework.ExpectHaveKeyWithValue(pod.Annotations, util.MacAddressAnnotation, mac) framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") @@ -102,15 +102,15 @@ var _ = framework.Describe("[group:ipam]", func() { pool := framework.RandomIPs(cidr, ",", 3) ginkgo.By("Creating pod " + podName + " with ippool " + pool) - annotations := map[string]string{util.IpPoolAnnotation: pool} + annotations := map[string]string{util.IPPoolAnnotation: pool} pod := framework.MakePod(namespaceName, podName, nil, annotations, "", nil, nil) pod = podClient.CreateSync(pod) framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.CidrAnnotation, subnet.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(pod.Annotations, util.GatewayAnnotation, subnet.Spec.Gateway) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpPoolAnnotation, pool) - framework.ExpectEqual(pod.Annotations[util.IpAddressAnnotation], pod.Status.PodIP) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPPoolAnnotation, pool) + framework.ExpectEqual(pod.Annotations[util.IPAddressAnnotation], pod.Status.PodIP) framework.ExpectHaveKeyWithValue(pod.Annotations, util.LogicalSwitchAnnotation, subnet.Name) framework.ExpectMAC(pod.Annotations[util.MacAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") @@ -131,7 +131,7 @@ var _ = framework.Describe("[group:ipam]", func() { ginkgo.By("Creating deployment " + deployName + " with ippool " + ippool) labels := map[string]string{"app": deployName} - annotations := map[string]string{util.IpPoolAnnotation: ippool} + annotations := map[string]string{util.IPPoolAnnotation: ippool} deploy := framework.MakeDeployment(deployName, int32(replicas), labels, annotations, "pause", framework.PauseImage, "") deploy = deployClient.CreateSync(deploy) @@ -145,8 +145,8 @@ var _ = framework.Describe("[group:ipam]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.CidrAnnotation, subnet.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(pod.Annotations, util.GatewayAnnotation, subnet.Spec.Gateway) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpPoolAnnotation, ippool) - framework.ExpectContainElement(ips, pod.Annotations[util.IpAddressAnnotation]) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPPoolAnnotation, ippool) + framework.ExpectContainElement(ips, pod.Annotations[util.IPAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.LogicalSwitchAnnotation, subnet.Name) framework.ExpectMAC(pod.Annotations[util.MacAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") @@ -155,7 +155,7 @@ var _ = framework.Describe("[group:ipam]", func() { for _, podIP := range pod.Status.PodIPs { podIPs = append(podIPs, podIP.IP) } - framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IpAddressAnnotation], ",")) + framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IPAddressAnnotation], ",")) } ginkgo.By("Deleting pods for deployment " + deployName) @@ -178,8 +178,8 @@ var _ = framework.Describe("[group:ipam]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.CidrAnnotation, subnet.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(pod.Annotations, util.GatewayAnnotation, subnet.Spec.Gateway) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpPoolAnnotation, ippool) - framework.ExpectContainElement(ips, pod.Annotations[util.IpAddressAnnotation]) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPPoolAnnotation, ippool) + framework.ExpectContainElement(ips, pod.Annotations[util.IPAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.LogicalSwitchAnnotation, subnet.Name) framework.ExpectMAC(pod.Annotations[util.MacAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") @@ -188,7 +188,7 @@ var _ = framework.Describe("[group:ipam]", func() { for _, podIP := range pod.Status.PodIPs { podIPs = append(podIPs, podIP.IP) } - framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IpAddressAnnotation], ",")) + framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IPAddressAnnotation], ",")) } }) @@ -217,8 +217,8 @@ var _ = framework.Describe("[group:ipam]", func() { for _, podIP := range pod.Status.PodIPs { podIPs = append(podIPs, podIP.IP) } - framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IpAddressAnnotation], ",")) - ips = append(ips, pod.Annotations[util.IpAddressAnnotation]) + framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IPAddressAnnotation], ",")) + ips = append(ips, pod.Annotations[util.IPAddressAnnotation]) } ginkgo.By("Deleting pods for statefulset " + stsName) @@ -236,7 +236,7 @@ var _ = framework.Describe("[group:ipam]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.CidrAnnotation, subnet.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(pod.Annotations, util.GatewayAnnotation, subnet.Spec.Gateway) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpAddressAnnotation, ips[i]) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPAddressAnnotation, ips[i]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.LogicalSwitchAnnotation, subnet.Name) framework.ExpectMAC(pod.Annotations[util.MacAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") @@ -259,7 +259,7 @@ var _ = framework.Describe("[group:ipam]", func() { ginkgo.By("Creating statefulset " + stsName + " with ippool " + ippool) sts := framework.MakeStatefulSet(stsName, stsName, int32(replicas), labels, framework.PauseImage) - sts.Spec.Template.Annotations = map[string]string{util.IpPoolAnnotation: ippool} + sts.Spec.Template.Annotations = map[string]string{util.IPPoolAnnotation: ippool} sts = stsClient.CreateSync(sts) ginkgo.By("Getting pods for statefulset " + stsName) @@ -271,7 +271,7 @@ var _ = framework.Describe("[group:ipam]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.CidrAnnotation, subnet.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(pod.Annotations, util.GatewayAnnotation, subnet.Spec.Gateway) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpPoolAnnotation, ippool) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPPoolAnnotation, ippool) framework.ExpectHaveKeyWithValue(pod.Annotations, util.LogicalSwitchAnnotation, subnet.Name) framework.ExpectMAC(pod.Annotations[util.MacAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") @@ -280,8 +280,8 @@ var _ = framework.Describe("[group:ipam]", func() { for _, podIP := range pod.Status.PodIPs { podIPs = append(podIPs, podIP.IP) } - framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IpAddressAnnotation], ",")) - ips = append(ips, pod.Annotations[util.IpAddressAnnotation]) + framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IPAddressAnnotation], ",")) + ips = append(ips, pod.Annotations[util.IPAddressAnnotation]) } framework.ExpectConsistOf(ips, strings.Split(ippool, ippoolSep)) @@ -300,8 +300,8 @@ var _ = framework.Describe("[group:ipam]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.CidrAnnotation, subnet.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(pod.Annotations, util.GatewayAnnotation, subnet.Spec.Gateway) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpPoolAnnotation, ippool) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpAddressAnnotation, ips[i]) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPPoolAnnotation, ippool) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPAddressAnnotation, ips[i]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.LogicalSwitchAnnotation, subnet.Name) framework.ExpectMAC(pod.Annotations[util.MacAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") @@ -310,7 +310,7 @@ var _ = framework.Describe("[group:ipam]", func() { for _, podIP := range pod.Status.PodIPs { podIPs = append(podIPs, podIP.IP) } - framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IpAddressAnnotation], ",")) + framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IPAddressAnnotation], ",")) } ginkgo.By("Deleting statefulset " + stsName) @@ -331,7 +331,7 @@ var _ = framework.Describe("[group:ipam]", func() { ginkgo.By("Creating statefulset " + stsName + " with ippool " + ippool) sts := framework.MakeStatefulSet(stsName, stsName, int32(replicas), labels, framework.PauseImage) - sts.Spec.Template.Annotations = map[string]string{util.IpPoolAnnotation: ippool} + sts.Spec.Template.Annotations = map[string]string{util.IPPoolAnnotation: ippool} sts = stsClient.CreateSync(sts) ginkgo.By("Getting pods for statefulset " + stsName) @@ -343,7 +343,7 @@ var _ = framework.Describe("[group:ipam]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.CidrAnnotation, subnet.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(pod.Annotations, util.GatewayAnnotation, subnet.Spec.Gateway) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpPoolAnnotation, ippool) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPPoolAnnotation, ippool) framework.ExpectHaveKeyWithValue(pod.Annotations, util.LogicalSwitchAnnotation, subnet.Name) framework.ExpectMAC(pod.Annotations[util.MacAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") @@ -352,8 +352,8 @@ var _ = framework.Describe("[group:ipam]", func() { for _, podIP := range pod.Status.PodIPs { podIPs = append(podIPs, podIP.IP) } - framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IpAddressAnnotation], ",")) - ips = append(ips, pod.Annotations[util.IpAddressAnnotation]) + framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IPAddressAnnotation], ",")) + ips = append(ips, pod.Annotations[util.IPAddressAnnotation]) } framework.ExpectConsistOf(ips, strings.Split(ippool, ippoolSep)) @@ -372,8 +372,8 @@ var _ = framework.Describe("[group:ipam]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.CidrAnnotation, subnet.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(pod.Annotations, util.GatewayAnnotation, subnet.Spec.Gateway) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpPoolAnnotation, ippool) - framework.ExpectHaveKeyWithValue(pod.Annotations, util.IpAddressAnnotation, ips[i]) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPPoolAnnotation, ippool) + framework.ExpectHaveKeyWithValue(pod.Annotations, util.IPAddressAnnotation, ips[i]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.LogicalSwitchAnnotation, subnet.Name) framework.ExpectMAC(pod.Annotations[util.MacAddressAnnotation]) framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") @@ -382,7 +382,7 @@ var _ = framework.Describe("[group:ipam]", func() { for _, podIP := range pod.Status.PodIPs { podIPs = append(podIPs, podIP.IP) } - framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IpAddressAnnotation], ",")) + framework.ExpectConsistOf(podIPs, strings.Split(pod.Annotations[util.IPAddressAnnotation], ",")) } }) @@ -457,7 +457,7 @@ var _ = framework.Describe("[group:ipam]", func() { ginkgo.By("Creating deployment " + deployName + " within ippool " + ippoolName) replicas := 3 labels := map[string]string{"app": deployName} - annotations := map[string]string{util.IpPoolAnnotation: ippoolName} + annotations := map[string]string{util.IPPoolAnnotation: ippoolName} deploy := framework.MakeDeployment(deployName, int32(replicas), labels, annotations, "pause", framework.PauseImage, "") deploy = deployClient.CreateSync(deploy) @@ -535,7 +535,7 @@ var _ = framework.Describe("[group:ipam]", func() { ginkgo.By("Validating namespace annotations") framework.WaitUntil(2*time.Second, 30*time.Second, func(_ context.Context) (bool, error) { ns := nsClient.Get(namespaceName) - return len(ns.Annotations) != 0 && ns.Annotations[util.IpPoolAnnotation] == ippoolName, nil + return len(ns.Annotations) != 0 && ns.Annotations[util.IPPoolAnnotation] == ippoolName, nil }, "") ginkgo.By("Patching deployment " + deployName) diff --git a/test/e2e/kube-ovn/network-policy/network-policy.go b/test/e2e/kube-ovn/network-policy/network-policy.go index bb3eb406921..6953848f62f 100644 --- a/test/e2e/kube-ovn/network-policy/network-policy.go +++ b/test/e2e/kube-ovn/network-policy/network-policy.go @@ -45,7 +45,7 @@ var _ = framework.SerialDescribe("[group:network-policy]", func() { netpolName = "netpol-" + framework.RandomSuffix() podName = "pod-" + framework.RandomSuffix() subnetName = "subnet-" + framework.RandomSuffix() - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) if image == "" { image = framework.GetKubeOvnImage(cs) diff --git a/test/e2e/kube-ovn/node/node.go b/test/e2e/kube-ovn/node/node.go index 92f791683d6..34dce3b1803 100644 --- a/test/e2e/kube-ovn/node/node.go +++ b/test/e2e/kube-ovn/node/node.go @@ -42,7 +42,7 @@ var _ = framework.OrderedDescribe("[group:node]", func() { hostPodName = "pod-" + framework.RandomSuffix() serviceName = "service-" + framework.RandomSuffix() subnetName = "subnet-" + framework.RandomSuffix() - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) if image == "" { image = framework.GetKubeOvnImage(cs) @@ -76,7 +76,7 @@ var _ = framework.OrderedDescribe("[group:node]", func() { framework.ExpectUUID(node.Annotations[util.ChassisAnnotation]) framework.ExpectHaveKeyWithValue(node.Annotations, util.CidrAnnotation, join.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(node.Annotations, util.GatewayAnnotation, join.Spec.Gateway) - framework.ExpectIPInCIDR(node.Annotations[util.IpAddressAnnotation], join.Spec.CIDRBlock) + framework.ExpectIPInCIDR(node.Annotations[util.IPAddressAnnotation], join.Spec.CIDRBlock) framework.ExpectHaveKeyWithValue(node.Annotations, util.LogicalSwitchAnnotation, join.Name) framework.ExpectMAC(node.Annotations[util.MacAddressAnnotation]) framework.ExpectHaveKeyWithValue(node.Annotations, util.PortNameAnnotation, "node-"+node.Name) @@ -95,8 +95,8 @@ var _ = framework.OrderedDescribe("[group:node]", func() { }) framework.ExpectNoError(err) framework.ExpectHaveLen(links, 1) - framework.Logf(util.GetIpAddrWithMask(node.Annotations[util.IpAddressAnnotation], join.Spec.CIDRBlock)) - ips := strings.Split(util.GetIpAddrWithMask(node.Annotations[util.IpAddressAnnotation], join.Spec.CIDRBlock), ",") + framework.Logf(util.GetIPAddrWithMask(node.Annotations[util.IPAddressAnnotation], join.Spec.CIDRBlock)) + ips := strings.Split(util.GetIPAddrWithMask(node.Annotations[util.IPAddressAnnotation], join.Spec.CIDRBlock), ",") framework.ExpectConsistOf(links[0].NonLinkLocalAddresses(), ips) err = podClient.Delete(podName) diff --git a/test/e2e/kube-ovn/pod/pod.go b/test/e2e/kube-ovn/pod/pod.go index 61f3a2723f3..4edec39de8a 100644 --- a/test/e2e/kube-ovn/pod/pod.go +++ b/test/e2e/kube-ovn/pod/pod.go @@ -32,7 +32,7 @@ var _ = framework.Describe("[group:pod]", func() { namespaceName = f.Namespace.Name subnetName = "subnet-" + framework.RandomSuffix() podName = "pod-" + framework.RandomSuffix() - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) if image == "" { image = framework.GetKubeOvnImage(cs) } diff --git a/test/e2e/kube-ovn/pod/vpc_pod_probe.go b/test/e2e/kube-ovn/pod/vpc_pod_probe.go index d875453dd82..20ad5ed2182 100644 --- a/test/e2e/kube-ovn/pod/vpc_pod_probe.go +++ b/test/e2e/kube-ovn/pod/vpc_pod_probe.go @@ -39,7 +39,7 @@ var _ = framework.SerialDescribe("[group:pod]", func() { namespaceName = f.Namespace.Name subnetName = "subnet-" + framework.RandomSuffix() podName = "pod-" + framework.RandomSuffix() - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) vpcClient = f.VpcClient() if image == "" { image = framework.GetKubeOvnImage(cs) @@ -94,7 +94,7 @@ var _ = framework.SerialDescribe("[group:pod]", func() { vpcClient.CreateSync(customVPC) ginkgo.By("Creating subnet " + custVPCSubnetName) - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) subnet := framework.MakeSubnet(custVPCSubnetName, "", cidr, "", vpcName, "", nil, nil, nil) _ = subnetClient.CreateSync(subnet) @@ -190,7 +190,6 @@ var _ = framework.SerialDescribe("[group:pod]", func() { }) func checkTProxyRules(f *framework.Framework, pod *corev1.Pod, probePort int, exist bool) { - nodeName := pod.Spec.NodeName tProxyOutputMarkMask := fmt.Sprintf("%#x/%#x", util.TProxyOutputMark, util.TProxyOutputMask) tProxyPreRoutingMarkMask := fmt.Sprintf("%#x/%#x", util.TProxyPreroutingMark, util.TProxyPreroutingMask) diff --git a/test/e2e/kube-ovn/service/service.go b/test/e2e/kube-ovn/service/service.go index b2b7b93b826..be26ad10090 100644 --- a/test/e2e/kube-ovn/service/service.go +++ b/test/e2e/kube-ovn/service/service.go @@ -40,7 +40,7 @@ var _ = framework.Describe("[group:service]", func() { podName = "pod-" + framework.RandomSuffix() hostPodName = "pod-" + framework.RandomSuffix() subnetName = "subnet-" + framework.RandomSuffix() - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) if image == "" { image = framework.GetKubeOvnImage(cs) } @@ -140,22 +140,22 @@ var _ = framework.Describe("[group:service]", func() { service = serviceClient.CreateSync(service, func(s *corev1.Service) (bool, error) { return len(s.Spec.ClusterIPs) != 0, nil }, "cluster ips are not empty") - v6ClusterIp := service.Spec.ClusterIPs[1] + v6ClusterIP := service.Spec.ClusterIPs[1] originService := service.DeepCopy() ginkgo.By("Creating pod " + podName) podBackend := framework.MakePod(namespaceName, podName, selector, nil, framework.PauseImage, nil, nil) _ = podClient.CreateSync(podBackend) - checkContainsClusterIP := func(v6ClusterIp string, isContain bool) { + checkContainsClusterIP := func(v6ClusterIP string, isContain bool) { execCmd := "kubectl ko nbctl --format=csv --data=bare --no-heading --columns=vips find Load_Balancer name=cluster-tcp-loadbalancer" framework.WaitUntil(2*time.Second, 30*time.Second, func(_ context.Context) (bool, error) { output, err := exec.Command("bash", "-c", execCmd).CombinedOutput() framework.ExpectNoError(err) framework.Logf("output is %q", output) - framework.Logf("v6ClusterIp is %q", v6ClusterIp) + framework.Logf("v6ClusterIP is %q", v6ClusterIP) vips := strings.Fields(string(output)) - prefix := util.JoinHostPort(v6ClusterIp, port) + "=" + prefix := util.JoinHostPort(v6ClusterIP, port) + "=" var found bool for _, vip := range vips { if strings.HasPrefix(vip, prefix) { @@ -171,11 +171,11 @@ var _ = framework.Describe("[group:service]", func() { output, err := exec.Command("bash", "-c", execCmd).CombinedOutput() framework.ExpectNoError(err) - framework.ExpectEqual(strings.Contains(string(output), v6ClusterIp), isContain) + framework.ExpectEqual(strings.Contains(string(output), v6ClusterIP), isContain) } ginkgo.By("check service from dual stack should have cluster ip ") - checkContainsClusterIP(v6ClusterIp, true) + checkContainsClusterIP(v6ClusterIP, true) ginkgo.By("change service from dual stack to single stack ") modifyService := service.DeepCopy() @@ -183,7 +183,7 @@ var _ = framework.Describe("[group:service]", func() { modifyService.Spec.IPFamilies = []corev1.IPFamily{corev1.IPv4Protocol} modifyService.Spec.ClusterIPs = []string{service.Spec.ClusterIP} service = serviceClient.Patch(service, modifyService) - checkContainsClusterIP(v6ClusterIp, false) + checkContainsClusterIP(v6ClusterIP, false) ginkgo.By("recover service from single stack to dual stack ") recoverService := service.DeepCopy() @@ -191,6 +191,6 @@ var _ = framework.Describe("[group:service]", func() { recoverService.Spec.IPFamilies = originService.Spec.IPFamilies recoverService.Spec.ClusterIPs = originService.Spec.ClusterIPs _ = serviceClient.Patch(service, recoverService) - checkContainsClusterIP(v6ClusterIp, true) + checkContainsClusterIP(v6ClusterIP, true) }) }) diff --git a/test/e2e/kube-ovn/subnet/subnet.go b/test/e2e/kube-ovn/subnet/subnet.go index b4267aebe27..652c217e08e 100644 --- a/test/e2e/kube-ovn/subnet/subnet.go +++ b/test/e2e/kube-ovn/subnet/subnet.go @@ -98,7 +98,7 @@ var _ = framework.Describe("[group:subnet]", func() { deployName = "deploy-" + framework.RandomSuffix() podNamePrefix = "pod-" + framework.RandomSuffix() podName = "pod-" + framework.RandomSuffix() - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) cidrV4, cidrV6 = util.SplitStringIP(cidr) gateways = nil podCount = 0 @@ -273,14 +273,14 @@ var _ = framework.Describe("[group:subnet]", func() { framework.ExpectZero(subnet.Status.V4AvailableIPs) } else { _, ipnet, _ := net.ParseCIDR(cidrV4) - expected := util.AddressCount(ipnet) - util.CountIpNums(excludeIPv4) - 1 + expected := util.AddressCount(ipnet) - util.CountIPNums(excludeIPv4) - 1 framework.ExpectEqual(subnet.Status.V4AvailableIPs, expected) } if cidrV6 == "" { framework.ExpectZero(subnet.Status.V6AvailableIPs) } else { _, ipnet, _ := net.ParseCIDR(cidrV6) - expected := util.AddressCount(ipnet) - util.CountIpNums(excludeIPv6) - 1 + expected := util.AddressCount(ipnet) - util.CountIPNums(excludeIPv6) - 1 framework.ExpectEqual(subnet.Status.V6AvailableIPs, expected) } }) @@ -437,7 +437,7 @@ var _ = framework.Describe("[group:subnet]", func() { nodeIPs := make([]string, 0, len(nodes.Items)) for i := 0; i < 3 && i < len(nodes.Items); i++ { gatewayNodes = append(gatewayNodes, nodes.Items[i].Name) - nodeIPs = append(nodeIPs, nodes.Items[i].Annotations[util.IpAddressAnnotation]) + nodeIPs = append(nodeIPs, nodes.Items[i].Annotations[util.IPAddressAnnotation]) } subnet = framework.MakeSubnet(subnetName, "", cidr, "", "", "", nil, gatewayNodes, nil) subnet = subnetClient.CreateSync(subnet) @@ -680,10 +680,10 @@ var _ = framework.Describe("[group:subnet]", func() { podCount = 5 var startIPv4, startIPv6 string if firstIPv4 != "" { - startIPv4 = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(firstIPv4), big.NewInt(1))) + startIPv4 = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(firstIPv4), big.NewInt(1))) } if firstIPv6 != "" { - startIPv6 = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(firstIPv6), big.NewInt(1))) + startIPv6 = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(firstIPv6), big.NewInt(1))) } ginkgo.By("Creating subnet " + subnetName) @@ -709,8 +709,8 @@ var _ = framework.Describe("[group:subnet]", func() { framework.WaitUntil(2*time.Second, 30*time.Second, func(_ context.Context) (bool, error) { subnet = subnetClient.Get(subnetName) if cidrV4 != "" { - v4UsingIPEnd := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(startIPv4), big.NewInt(int64(podCount-1)))) - v4AvailableIPStart := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(v4UsingIPEnd), big.NewInt(1))) + v4UsingIPEnd := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(startIPv4), big.NewInt(int64(podCount-1)))) + v4AvailableIPStart := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(v4UsingIPEnd), big.NewInt(1))) framework.Logf("V4UsingIPRange: expected %q, current %q", fmt.Sprintf("%s-%s", startIPv4, v4UsingIPEnd), subnet.Status.V4UsingIPRange, @@ -725,8 +725,8 @@ var _ = framework.Describe("[group:subnet]", func() { } } if cidrV6 != "" { - v6UsingIPEnd := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(startIPv6), big.NewInt(int64(podCount-1)))) - v6AvailableIPStart := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(v6UsingIPEnd), big.NewInt(1))) + v6UsingIPEnd := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(startIPv6), big.NewInt(int64(podCount-1)))) + v6AvailableIPStart := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(v6UsingIPEnd), big.NewInt(1))) framework.Logf("V6UsingIPRange: expected %q, current %q", fmt.Sprintf("%s-%s", startIPv6, v6UsingIPEnd), subnet.Status.V6UsingIPRange, @@ -787,10 +787,10 @@ var _ = framework.Describe("[group:subnet]", func() { var startIPv4, startIPv6, usingIPv4Str, availableIPv4Str, usingIPv6Str, availableIPv6Str string if firstIPv4 != "" { - startIPv4 = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(firstIPv4), big.NewInt(1))) + startIPv4 = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(firstIPv4), big.NewInt(1))) } if firstIPv6 != "" { - startIPv6 = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(firstIPv6), big.NewInt(1))) + startIPv6 = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(firstIPv6), big.NewInt(1))) } ginkgo.By("Creating subnet " + subnetName) @@ -855,10 +855,10 @@ var _ = framework.Describe("[group:subnet]", func() { var startIPv4, startIPv6 string if firstIPv4 != "" { - startIPv4 = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(firstIPv4), big.NewInt(1))) + startIPv4 = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(firstIPv4), big.NewInt(1))) } if firstIPv6 != "" { - startIPv6 = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(firstIPv6), big.NewInt(1))) + startIPv6 = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(firstIPv6), big.NewInt(1))) } ginkgo.By("Creating subnet " + subnetName) @@ -878,8 +878,8 @@ var _ = framework.Describe("[group:subnet]", func() { return true } - usingIPEnd := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(startIP), big.NewInt(count-1))) - availableIPStart := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(usingIPEnd), big.NewInt(1))) + usingIPEnd := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(startIP), big.NewInt(count-1))) + availableIPStart := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(usingIPEnd), big.NewInt(1))) framework.Logf(`subnet status usingIPRange %q expect "%s-%s"`, usingIPRange, startIP, usingIPEnd) if usingIPRange != fmt.Sprintf("%s-%s", startIP, usingIPEnd) { @@ -908,13 +908,13 @@ var _ = framework.Describe("[group:subnet]", func() { expectAvailIPRangeStr := fmt.Sprintf("%s-%s,%s-%s", startIP, - util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(startIP), big.NewInt(count-1))), - util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(startIP), big.NewInt(2*count))), + util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(startIP), big.NewInt(count-1))), + util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(startIP), big.NewInt(2*count))), lastIP, ) expectUsingIPRangeStr := fmt.Sprintf("%s-%s", - util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(startIP), big.NewInt(count))), - util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(startIP), big.NewInt(2*count-1))), + util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(startIP), big.NewInt(count))), + util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(startIP), big.NewInt(2*count-1))), ) framework.Logf("subnet status usingIPRange %q expect %q", usingIPRange, expectUsingIPRangeStr) @@ -1153,7 +1153,7 @@ var _ = framework.Describe("[group:subnet]", func() { _ = subnetClient.PatchSync(subnet, modifiedSubnet) ginkgo.By("Creating another subnet with the same rules: " + fakeSubnetName) - fakeCidr := framework.RandomCIDR(f.ClusterIpFamily) + fakeCidr := framework.RandomCIDR(f.ClusterIPFamily) fakeCidrV4, fakeCidrV6 := util.SplitStringIP(fakeCidr) fakeSubnet := framework.MakeSubnet(fakeSubnetName, "", fakeCidr, "", "", "", nil, nil, nil) fakeSubnet.Spec.NatOutgoingPolicyRules = rules @@ -1405,21 +1405,22 @@ func createPodsByRandomIPs(podClient *framework.PodClient, subnetClient *framewo subnet := subnetClient.Get(subnetName) for i := 1; i <= podCount; i++ { step := rand.Int63()%10 + 2 - if subnet.Spec.Protocol == apiv1.ProtocolIPv4 { - podv4IP = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(podv4IP), big.NewInt(step))) + switch subnet.Spec.Protocol { + case apiv1.ProtocolIPv4: + podv4IP = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(podv4IP), big.NewInt(step))) allocIP = podv4IP - } else if subnet.Spec.Protocol == apiv1.ProtocolIPv6 { - podv6IP = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(podv6IP), big.NewInt(step))) + case apiv1.ProtocolIPv6: + podv6IP = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(podv6IP), big.NewInt(step))) allocIP = podv6IP - } else { - podv4IP = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(podv4IP), big.NewInt(step))) - podv6IP = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(podv6IP), big.NewInt(step))) + default: + podv4IP = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(podv4IP), big.NewInt(step))) + podv6IP = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(podv6IP), big.NewInt(step))) allocIP = fmt.Sprintf("%s,%s", podv4IP, podv6IP) } annotations := map[string]string{ util.LogicalSwitchAnnotation: subnetName, - fmt.Sprintf(util.IpAddressAnnotationTemplate, subnet.Spec.Provider): allocIP, + fmt.Sprintf(util.IPAddressAnnotationTemplate, subnet.Spec.Provider): allocIP, } podName := fmt.Sprintf("%s-%d", podNamePrefix, i) @@ -1444,11 +1445,11 @@ func calcuIPRangeListStr(podIPs []string, startIP, lastIP string) (string, strin for index, podIP := range podIPs { usingIPs = append(usingIPs, podIP) if index == 0 { - availableIPs = append(availableIPs, fmt.Sprintf("%s-%s", startIP, util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(podIP), big.NewInt(-1))))) + availableIPs = append(availableIPs, fmt.Sprintf("%s-%s", startIP, util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(podIP), big.NewInt(-1))))) } else { preIP := prePodIP - start := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(preIP), big.NewInt(1))) - end := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(podIP), big.NewInt(-1))) + start := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(preIP), big.NewInt(1))) + end := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(podIP), big.NewInt(-1))) if start == end { availableIPs = append(availableIPs, start) @@ -1460,7 +1461,7 @@ func calcuIPRangeListStr(podIPs []string, startIP, lastIP string) (string, strin } if prePodIP != "" { - availableIPs = append(availableIPs, fmt.Sprintf("%s-%s", util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(prePodIP), big.NewInt(1))), lastIP)) + availableIPs = append(availableIPs, fmt.Sprintf("%s-%s", util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(prePodIP), big.NewInt(1))), lastIP)) } usingIPStr = strings.Join(usingIPs, ",") diff --git a/test/e2e/kube-ovn/switch_lb_rule/switch_lb_rule.go b/test/e2e/kube-ovn/switch_lb_rule/switch_lb_rule.go index 66b61d6043d..ea8a75721b4 100644 --- a/test/e2e/kube-ovn/switch_lb_rule/switch_lb_rule.go +++ b/test/e2e/kube-ovn/switch_lb_rule/switch_lb_rule.go @@ -6,15 +6,16 @@ import ( "strconv" "time" - kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1" - "github.com/kubeovn/kube-ovn/pkg/util" - "github.com/kubeovn/kube-ovn/test/e2e/framework" "github.com/onsi/ginkgo/v2" corev1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" e2epodoutput "k8s.io/kubernetes/test/e2e/framework/pod/output" + + kubeovnv1 "github.com/kubeovn/kube-ovn/pkg/apis/kubeovn/v1" + "github.com/kubeovn/kube-ovn/pkg/util" + "github.com/kubeovn/kube-ovn/test/e2e/framework" ) func generateSwitchLBRuleName(ruleName string) string { @@ -88,7 +89,7 @@ var _ = framework.Describe("[group:slr]", func() { epSlrFrontPort = 8092 backendPort = 80 vip = "" - overlaySubnetCidr = framework.RandomCIDR(f.ClusterIpFamily) + overlaySubnetCidr = framework.RandomCIDR(f.ClusterIPFamily) ginkgo.By("Creating custom vpc") vpc := framework.MakeVpc(vpcName, "", false, false, []string{namespaceName}) _ = vpcClient.CreateSync(vpc) diff --git a/test/e2e/kube-ovn/underlay/underlay.go b/test/e2e/kube-ovn/underlay/underlay.go index 1808147cb7a..a42313fda09 100644 --- a/test/e2e/kube-ovn/underlay/underlay.go +++ b/test/e2e/kube-ovn/underlay/underlay.go @@ -26,8 +26,10 @@ import ( "github.com/kubeovn/kube-ovn/test/e2e/framework/kind" ) -const dockerNetworkName = "kube-ovn-vlan" -const curlListenPort = 8081 +const ( + dockerNetworkName = "kube-ovn-vlan" + curlListenPort = 8081 +) func makeProviderNetwork(providerNetworkName string, exchangeLinkName bool, linkMap map[string]*iproute.Link) *apiv1.ProviderNetwork { var defaultInterface string @@ -459,7 +461,7 @@ var _ = framework.SerialDescribe("[group:underlay]", func() { ip := containerInfo.NetworkSettings.Networks[dockerNetworkName].IPAddress mac := containerInfo.NetworkSettings.Networks[dockerNetworkName].MacAddress ginkgo.By("Creating pod " + podName + " with IP address " + ip) - annotations := map[string]string{util.IpAddressAnnotation: ip} + annotations := map[string]string{util.IPAddressAnnotation: ip} pod := framework.MakePod(namespaceName, podName, nil, annotations, image, cmd, nil) pod.Spec.TerminationGracePeriodSeconds = nil _ = podClient.Create(pod) @@ -536,7 +538,7 @@ var _ = framework.SerialDescribe("[group:underlay]", func() { waitSubnetStatusUpdate(subnetName, subnetClient, 2) ginkgo.By("Creating overlay subnet " + u2oOverlaySubnetName) - cidr := framework.RandomCIDR(f.ClusterIpFamily) + cidr := framework.RandomCIDR(f.ClusterIPFamily) overlaySubnet := framework.MakeSubnet(u2oOverlaySubnetName, "", cidr, "", "", "", nil, nil, nil) overlaySubnet = subnetClient.CreateSync(overlaySubnet) @@ -691,7 +693,7 @@ var _ = framework.SerialDescribe("[group:underlay]", func() { vpcClient.CreateSync(customVPC) ginkgo.By("Creating subnet " + u2oOverlaySubnetNameCustomVPC) - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) overlaySubnetCustomVpc := framework.MakeSubnet(u2oOverlaySubnetNameCustomVPC, "", cidr, "", vpcName, "", nil, nil, []string{namespaceName}) _ = subnetClient.CreateSync(overlaySubnetCustomVpc) @@ -803,7 +805,7 @@ func checkU2OItems(f *framework.Framework, subnet *apiv1.Subnet, underlayPod, ov } } - asName := strings.Replace(fmt.Sprintf("%s.u2o_exclude_ip.%s", subnet.Name, protocolStr), "-", ".", -1) + asName := strings.ReplaceAll(fmt.Sprintf("%s.u2o_exclude_ip.%s", subnet.Name, protocolStr), "-", ".") if !isU2OCustomVpc { ginkgo.By(fmt.Sprintf("checking underlay subnet's policy1 route %s", protocolStr)) hitPolicyStr := fmt.Sprintf("%d %s.dst == %s allow", util.U2OSubnetPolicyPriority, protocolStr, cidr) @@ -826,7 +828,7 @@ func checkU2OItems(f *framework.Framework, subnet *apiv1.Subnet, underlayPod, ov framework.ExpectNoError(err) framework.ExpectNotEmpty(routes) - v4InterconnIp, v6InterconnIp := util.SplitStringIP(subnet.Status.U2OInterconnectionIP) + v4InterconnIP, v6InterconnIP := util.SplitStringIP(subnet.Status.U2OInterconnectionIP) isV4DefaultRouteExist := false isV6DefaultRouteExist := false @@ -834,14 +836,14 @@ func checkU2OItems(f *framework.Framework, subnet *apiv1.Subnet, underlayPod, ov if route.Dst == "default" { if util.CheckProtocol(route.Gateway) == apiv1.ProtocolIPv4 { if subnet.Spec.U2OInterconnection { - framework.ExpectEqual(route.Gateway, v4InterconnIp) + framework.ExpectEqual(route.Gateway, v4InterconnIP) } else { framework.ExpectEqual(route.Gateway, v4gw) } isV4DefaultRouteExist = true } else { if subnet.Spec.U2OInterconnection { - framework.ExpectEqual(route.Gateway, v6InterconnIp) + framework.ExpectEqual(route.Gateway, v6InterconnIP) } else { framework.ExpectEqual(route.Gateway, v6gw) } @@ -850,11 +852,12 @@ func checkU2OItems(f *framework.Framework, subnet *apiv1.Subnet, underlayPod, ov } } - if subnet.Spec.Protocol == apiv1.ProtocolIPv4 { + switch { + case subnet.Spec.Protocol == apiv1.ProtocolIPv4: framework.ExpectTrue(isV4DefaultRouteExist) - } else if subnet.Spec.Protocol == apiv1.ProtocolIPv6 { + case subnet.Spec.Protocol == apiv1.ProtocolIPv6: framework.ExpectTrue(isV6DefaultRouteExist) - } else if subnet.Spec.Protocol == apiv1.ProtocolDual { + case subnet.Spec.Protocol == apiv1.ProtocolDual: framework.ExpectTrue(isV4DefaultRouteExist) framework.ExpectTrue(isV6DefaultRouteExist) } diff --git a/test/e2e/kubevirt/e2e_test.go b/test/e2e/kubevirt/e2e_test.go index af42d27daf6..615d7a9c315 100644 --- a/test/e2e/kubevirt/e2e_test.go +++ b/test/e2e/kubevirt/e2e_test.go @@ -60,7 +60,7 @@ var _ = framework.Describe("[group:kubevirt]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, util.AllocatedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, util.RoutedAnnotation, "true") framework.ExpectHaveKeyWithValue(pod.Annotations, "ovn.kubernetes.io/virtualmachine", "testvm") - ipAddr := pod.Annotations[util.IpAddressAnnotation] + ipAddr := pod.Annotations[util.IPAddressAnnotation] ginkgo.By("Deleting pod " + pod.Name) podClient.DeleteSync(pod.Name) @@ -80,7 +80,7 @@ var _ = framework.Describe("[group:kubevirt]", func() { framework.ExpectHaveKeyWithValue(pod.Annotations, "ovn.kubernetes.io/virtualmachine", "testvm") ginkgo.By("Check vm pod ip unchanged" + pod.Name) - ipNewAddr := pod.Annotations[util.IpAddressAnnotation] + ipNewAddr := pod.Annotations[util.IPAddressAnnotation] framework.ExpectEqual(ipAddr, ipNewAddr) }) }) diff --git a/test/e2e/lb-svc/e2e_test.go b/test/e2e/lb-svc/e2e_test.go index 951d57f8f08..bab782674eb 100644 --- a/test/e2e/lb-svc/e2e_test.go +++ b/test/e2e/lb-svc/e2e_test.go @@ -174,7 +174,7 @@ var _ = framework.SerialDescribe("[group:lb-svc]", func() { key := fmt.Sprintf(util.AllocatedAnnotationTemplate, subnetProvider) framework.ExpectHaveKeyWithValue(pods.Items[0].Annotations, key, "true") cidrKey := fmt.Sprintf(util.CidrAnnotationTemplate, subnetProvider) - ipKey := fmt.Sprintf(util.IpAddressAnnotationTemplate, subnetProvider) + ipKey := fmt.Sprintf(util.IPAddressAnnotationTemplate, subnetProvider) framework.ExpectHaveKey(pods.Items[0].Annotations, cidrKey) framework.ExpectHaveKey(pods.Items[0].Annotations, ipKey) cidr := pods.Items[0].Annotations[cidrKey] @@ -191,7 +191,7 @@ var _ = framework.SerialDescribe("[group:lb-svc]", func() { framework.ConformanceIt("should allocate static external IP for service", func() { ginkgo.By("Creating service " + serviceName) - base := util.Ip2BigInt(gateway) + base := util.IP2BigInt(gateway) lbIP := util.BigInt2Ip(base.Add(base, big.NewInt(50+rand.Int63n(50)))) ports := []corev1.ServicePort{{ Name: "tcp", @@ -230,7 +230,7 @@ var _ = framework.SerialDescribe("[group:lb-svc]", func() { ginkgo.By("Checking pod annotations") key := fmt.Sprintf(util.AllocatedAnnotationTemplate, subnetProvider) framework.ExpectHaveKeyWithValue(pods.Items[0].Annotations, key, "true") - ipKey := fmt.Sprintf(util.IpAddressAnnotationTemplate, subnetProvider) + ipKey := fmt.Sprintf(util.IPAddressAnnotationTemplate, subnetProvider) framework.ExpectHaveKeyWithValue(pods.Items[0].Annotations, ipKey, lbIP) cidr := pods.Items[0].Annotations[fmt.Sprintf(util.CidrAnnotationTemplate, subnetProvider)] framework.ExpectTrue(util.CIDRContainIP(cidr, lbIP)) diff --git a/test/e2e/ovn-ic/e2e_test.go b/test/e2e/ovn-ic/e2e_test.go index 30dd674235d..dd15ae9f02e 100644 --- a/test/e2e/ovn-ic/e2e_test.go +++ b/test/e2e/ovn-ic/e2e_test.go @@ -188,7 +188,7 @@ var _ = framework.OrderedDescribe("[group:ovn-ic]", func() { framework.ExpectNoError(err, "failed to marshal patch data") ginkgo.By("patching the ConfigMap in cluster " + clusters[0]) - _, err = clientSets[0].CoreV1().ConfigMaps(framework.KubeOvnNamespace).Patch(context.TODO(), util.InterconnectionConfig, k8stypes.StrategicMergePatchType, []byte(configMapPatchPayload), metav1.PatchOptions{}) + _, err = clientSets[0].CoreV1().ConfigMaps(framework.KubeOvnNamespace).Patch(context.TODO(), util.InterconnectionConfig, k8stypes.StrategicMergePatchType, configMapPatchPayload, metav1.PatchOptions{}) framework.ExpectNoError(err, "failed to patch ConfigMap") ginkgo.By("Waiting for new az names to be applied") diff --git a/test/e2e/ovn-vpc-nat-gw/e2e_test.go b/test/e2e/ovn-vpc-nat-gw/e2e_test.go index c5584e2a856..568665f8aa4 100644 --- a/test/e2e/ovn-vpc-nat-gw/e2e_test.go +++ b/test/e2e/ovn-vpc-nat-gw/e2e_test.go @@ -87,7 +87,7 @@ var _ = framework.Describe("[group:ovn-vpc-nat-gw]", func() { var subnetClient *framework.SubnetClient var ovnEipClient *framework.OvnEipClient var fipVipName, fipEipName, fipName, dnatVipName, dnatEipName, dnatName, snatEipName, snatName, namespaceName string - var ipClient *framework.IpClient + var ipClient *framework.IPClient var vipClient *framework.VipClient var ovnFipClient *framework.OvnFipClient var ovnSnatRuleClient *framework.OvnSnatRuleClient @@ -109,7 +109,7 @@ var _ = framework.Describe("[group:ovn-vpc-nat-gw]", func() { vpcClient = f.VpcClient() providerNetworkClient = f.ProviderNetworkClient() ovnEipClient = f.OvnEipClient() - ipClient = f.IpClient() + ipClient = f.IPClient() vipClient = f.VipClient() ovnFipClient = f.OvnFipClient() ovnSnatRuleClient = f.OvnSnatRuleClient() diff --git a/test/e2e/webhook/pod/pod.go b/test/e2e/webhook/pod/pod.go index 9f0afdaf5e5..051c41e7285 100644 --- a/test/e2e/webhook/pod/pod.go +++ b/test/e2e/webhook/pod/pod.go @@ -32,7 +32,7 @@ var _ = framework.Describe("[group:webhook-pod]", func() { subnetName = "subnet-" + framework.RandomSuffix() podName = "pod-" + framework.RandomSuffix() conflictName = podName + "-conflict" - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) if image == "" { image = framework.GetKubeOvnImage(cs) } @@ -66,17 +66,17 @@ var _ = framework.Describe("[group:webhook-pod]", func() { ginkgo.By("validate ip validation") annotations := map[string]string{ - util.IpAddressAnnotation: "10.10.10.10.10", + util.IPAddressAnnotation: "10.10.10.10.10", } pod := framework.MakePod(namespaceName, podName, nil, annotations, image, cmd, nil) _, err := podClient.PodInterface.Create(context.TODO(), pod, metav1.CreateOptions{}) - framework.ExpectError(err, "ip %s is not a valid %s", annotations[util.IpAddressAnnotation], util.IpAddressAnnotation) + framework.ExpectError(err, "ip %s is not a valid %s", annotations[util.IPAddressAnnotation], util.IPAddressAnnotation) ginkgo.By("validate pod ip not in subnet cidr") - staticIP := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(lastIPv4), big.NewInt(10))) + staticIP := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(lastIPv4), big.NewInt(10))) annotations = map[string]string{ util.CidrAnnotation: cidr, - util.IpAddressAnnotation: staticIP, + util.IPAddressAnnotation: staticIP, } framework.Logf("validate ip not in subnet range, cidr %s, staticip %s", cidr, staticIP) pod.Annotations = annotations @@ -85,12 +85,12 @@ var _ = framework.Describe("[group:webhook-pod]", func() { framework.ExpectError(err, "%s not in cidr %s", staticIP, cidr) ginkgo.By("validate pod ippool not in subnet cidr") - startIP := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(lastIPv4), big.NewInt(10))) - endIP := util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(lastIPv4), big.NewInt(20))) + startIP := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(lastIPv4), big.NewInt(10))) + endIP := util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(lastIPv4), big.NewInt(20))) ipPool := startIP + "," + endIP annotations = map[string]string{ util.CidrAnnotation: cidr, - util.IpPoolAnnotation: ipPool, + util.IPPoolAnnotation: ipPool, } framework.Logf("validate ippool not in subnet range, cidr %s, ippool %s", cidr, ipPool) pod.Annotations = annotations @@ -98,11 +98,11 @@ var _ = framework.Describe("[group:webhook-pod]", func() { framework.ExpectError(err, "%s not in cidr %s", ipPool, cidr) ginkgo.By("validate pod static ip success") - staticIP = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(firstIPv4), big.NewInt(10))) + staticIP = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(firstIPv4), big.NewInt(10))) annotations = map[string]string{ util.LogicalSwitchAnnotation: subnetName, util.CidrAnnotation: cidr, - util.IpAddressAnnotation: staticIP, + util.IPAddressAnnotation: staticIP, } pod.Annotations = annotations _ = podClient.CreateSync(pod) diff --git a/test/e2e/webhook/subnet/subnet.go b/test/e2e/webhook/subnet/subnet.go index d171cc42f06..e56dcc70032 100644 --- a/test/e2e/webhook/subnet/subnet.go +++ b/test/e2e/webhook/subnet/subnet.go @@ -22,7 +22,7 @@ var _ = framework.Describe("[group:webhook-subnet]", func() { ginkgo.BeforeEach(func() { subnetClient = f.SubnetClient() subnetName = "subnet-" + framework.RandomSuffix() - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) cidrV4, cidrV6 = util.SplitStringIP(cidr) gateways = nil diff --git a/test/e2e/webhook/vip/vip.go b/test/e2e/webhook/vip/vip.go index 13d98fbd132..a93e3e74b95 100644 --- a/test/e2e/webhook/vip/vip.go +++ b/test/e2e/webhook/vip/vip.go @@ -25,7 +25,7 @@ var _ = framework.Describe("[group:webhook-vip]", func() { ginkgo.BeforeEach(func() { subnetClient = f.SubnetClient() subnetName = "subnet-" + framework.RandomSuffix() - cidr = framework.RandomCIDR(f.ClusterIpFamily) + cidr = framework.RandomCIDR(f.ClusterIPFamily) cidrV4, _ := util.SplitStringIP(cidr) if cidrV4 == "" { lastIPv4 = "" @@ -79,7 +79,7 @@ var _ = framework.Describe("[group:webhook-vip]", func() { ginkgo.By("validate ip not in subnet cidr") vip.Spec.V6ip = "" - vip.Spec.V4ip = util.BigInt2Ip(big.NewInt(0).Add(util.Ip2BigInt(lastIPv4), big.NewInt(10))) + vip.Spec.V4ip = util.BigInt2Ip(big.NewInt(0).Add(util.IP2BigInt(lastIPv4), big.NewInt(10))) _, err = vipClient.VipInterface.Create(context.TODO(), vip, metav1.CreateOptions{}) framework.ExpectError(err, "%s is not in the range of subnet %s", vip.Spec.V4ip, vip.Spec.Subnet) }) diff --git a/test/server/server.go b/test/server/server.go index 571934cbf98..0aa15fd4d62 100644 --- a/test/server/server.go +++ b/test/server/server.go @@ -26,10 +26,10 @@ type Result struct { RemotePort uint32 TotalIcmpEcho int IcmpLost int - TotalTcpOutSegments int - TcpRetransSegment int - TotalTcpConnection int - FailedTcpConnection int + TotalTCPOutSegments int + TCPRetransSegment int + TotalTCPConnection int + FailedTCPConnection int } func parseFlag() *Configuration { @@ -112,10 +112,10 @@ func main() { break } time.Sleep(100 * time.Millisecond) - totalConnection += 1 + totalConnection++ _, err := exec.Command("curl", "-m", "1", fmt.Sprintf("%s:%d", config.RemoteAddress, config.RemotePort)).CombinedOutput() if err != nil { - failedConnection += 1 + failedConnection++ } } tcpConnDone <- "" @@ -151,17 +151,17 @@ func main() { RemotePort: config.RemotePort, TotalIcmpEcho: curIcmpEcho - preIcmpEcho, IcmpLost: curDiff - preDiff, - TotalTcpOutSegments: curOutSegs - preOutSegs, - TcpRetransSegment: curRetrans - preRetrans, - TotalTcpConnection: totalConnection, - FailedTcpConnection: failedConnection, + TotalTCPOutSegments: curOutSegs - preOutSegs, + TCPRetransSegment: curRetrans - preRetrans, + TotalTCPConnection: totalConnection, + FailedTCPConnection: failedConnection, } if config.Output == "text" { klog.Infof("remote address = %s, remote port = %d", result.RemoteAddress, result.RemotePort) klog.Infof("total icmp echo %d, lost %d icmp response", result.TotalIcmpEcho, result.IcmpLost) - klog.Infof("total out %d tcp segments, retrans %d tcp segments", result.TotalTcpOutSegments, result.TcpRetransSegment) - klog.Infof("%d failed connection, %d total connection", result.TotalTcpConnection, result.FailedTcpConnection) + klog.Infof("total out %d tcp segments, retrans %d tcp segments", result.TotalTCPOutSegments, result.TCPRetransSegment) + klog.Infof("%d failed connection, %d total connection", result.TotalTCPConnection, result.FailedTCPConnection) } else { output, _ := json.MarshalIndent(result, "", " ") fmt.Println(string(output)) diff --git a/test/unittest/ipam/ip.go b/test/unittest/ipam/ip.go index 44c9d6c8bfd..d2b828431cd 100644 --- a/test/unittest/ipam/ip.go +++ b/test/unittest/ipam/ip.go @@ -34,7 +34,7 @@ var _ = ginkgo.Context("[group:IPAM]", func() { ginkgo.It("IPv4", func() { n1 := rand.Uint32() if n1 == 0xffffffff { - n1 -= 1 + n1-- } n2 := n1 + 1 @@ -48,10 +48,6 @@ var _ = ginkgo.Context("[group:IPAM]", func() { gomega.Expect(err).NotTo(gomega.HaveOccurred()) gomega.Expect(ip2.String()).To(gomega.Equal(ip2Str)) - gomega.Expect(ip1.Equal(ip1)).To(gomega.BeTrue()) - gomega.Expect(ip1.GreaterThan(ip1)).To(gomega.BeFalse()) - gomega.Expect(ip1.LessThan(ip1)).To(gomega.BeFalse()) - gomega.Expect(ip1.Equal(ip2)).To(gomega.BeFalse()) gomega.Expect(ip1.GreaterThan(ip2)).To(gomega.BeFalse()) gomega.Expect(ip1.LessThan(ip2)).To(gomega.BeTrue()) @@ -65,7 +61,7 @@ var _ = ginkgo.Context("[group:IPAM]", func() { ginkgo.It("IPv6", func() { n1 := [4]uint32{rand.Uint32(), rand.Uint32(), rand.Uint32(), rand.Uint32()} if n1[0] == 0xffffffff && n1[1] == 0xffffffff && n1[2] == 0xffffffff && n1[3] == 0xffffffff { - n1[3] -= 1 + n1[3]-- } n2 := [4]uint32{n1[0], n1[1], n1[2], n1[3] + 1} @@ -89,10 +85,6 @@ var _ = ginkgo.Context("[group:IPAM]", func() { gomega.Expect(err).NotTo(gomega.HaveOccurred()) gomega.Expect(ip2.String()).To(gomega.Equal(net.ParseIP(ip2Str).String())) - gomega.Expect(ip1.Equal(ip1)).To(gomega.BeTrue()) - gomega.Expect(ip1.GreaterThan(ip1)).To(gomega.BeFalse()) - gomega.Expect(ip1.LessThan(ip1)).To(gomega.BeFalse()) - gomega.Expect(ip1.Equal(ip2)).To(gomega.BeFalse()) gomega.Expect(ip1.GreaterThan(ip2)).To(gomega.BeFalse()) gomega.Expect(ip1.LessThan(ip2)).To(gomega.BeTrue()) diff --git a/test/unittest/ipam/ip_range_list.go b/test/unittest/ipam/ip_range_list.go index 19f721391c7..a24ce1e328b 100644 --- a/test/unittest/ipam/ip_range_list.go +++ b/test/unittest/ipam/ip_range_list.go @@ -198,7 +198,6 @@ var _ = ginkgo.Context("[group:IPAM]", func() { merged := v1.Merge(v2) gomega.Expect(merged.Equal(expected)).To(gomega.BeTrue()) }) - }) ginkgo.It("NewIPRangeListFrom", func() { diff --git a/test/unittest/ipam/ipam.go b/test/unittest/ipam/ipam.go index 7a75b5335c2..83dc4d51ea1 100644 --- a/test/unittest/ipam/ipam.go +++ b/test/unittest/ipam/ipam.go @@ -63,65 +63,65 @@ var _ = Describe("[IPAM]", func() { pod1 := "pod1.ns" pod1Nic1 := "pod1nic1.ns" - freeIp1 := im.Subnets[subnetName].V4Free.At(0).Start().String() - ip, _, _, err := im.GetStaticAddress(pod1, pod1Nic1, freeIp1, nil, subnetName, true) + freeIP1 := im.Subnets[subnetName].V4Free.At(0).Start().String() + ip, _, _, err := im.GetStaticAddress(pod1, pod1Nic1, freeIP1, nil, subnetName, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip).To(Equal(freeIp1)) + Expect(ip).To(Equal(freeIP1)) ip, _, _, err = im.GetRandomAddress(pod1, pod1Nic1, nil, subnetName, "", nil, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip).To(Equal(freeIp1)) + Expect(ip).To(Equal(freeIP1)) By("create multiple ips on one pod ") pod2 := "pod2.ns" pod2Nic1 := "pod2Nic1.ns" pod2Nic2 := "pod2Nic2.ns" - freeIp2 := im.Subnets[subnetName].V4Free.At(0).Start().String() + freeIP2 := im.Subnets[subnetName].V4Free.At(0).Start().String() ip, _, _, err = im.GetRandomAddress(pod2, pod2Nic1, nil, subnetName, "", nil, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip).To(Equal(freeIp2)) + Expect(ip).To(Equal(freeIP2)) - freeIp3 := im.Subnets[subnetName].V4Free.At(0).Start().String() + freeIP3 := im.Subnets[subnetName].V4Free.At(0).Start().String() ip, _, _, err = im.GetRandomAddress(pod2, pod2Nic2, nil, subnetName, "", nil, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip).To(Equal(freeIp3)) + Expect(ip).To(Equal(freeIP3)) addresses := im.GetPodAddress(pod2) Expect(addresses).To(HaveLen(2)) - Expect([]string{addresses[0].Ip, addresses[1].Ip}).To(Equal([]string{freeIp2, freeIp3})) - Expect(im.ContainAddress(freeIp2)).Should(BeTrue()) - Expect(im.ContainAddress(freeIp3)).Should(BeTrue()) + Expect([]string{addresses[0].IP, addresses[1].IP}).To(Equal([]string{freeIP2, freeIP3})) + Expect(im.ContainAddress(freeIP2)).Should(BeTrue()) + Expect(im.ContainAddress(freeIP3)).Should(BeTrue()) - _, isIPAssigned := im.IsIPAssignedToOtherPod(freeIp2, subnetName, pod2) + _, isIPAssigned := im.IsIPAssignedToOtherPod(freeIP2, subnetName, pod2) Expect(isIPAssigned).Should(BeFalse()) - _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIp3, subnetName, pod2) + _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIP3, subnetName, pod2) Expect(isIPAssigned).Should(BeFalse()) - assignedPod, isIPAssigned := im.IsIPAssignedToOtherPod(freeIp1, subnetName, pod2) + assignedPod, isIPAssigned := im.IsIPAssignedToOtherPod(freeIP1, subnetName, pod2) Expect(isIPAssigned).Should(BeTrue()) Expect(assignedPod).To(Equal(pod1)) By("get static ip conflict with ip in use ") pod3 := "pod3.ns" pod3Nic1 := "pod3Nic1.ns" - _, _, _, err = im.GetStaticAddress(pod3, pod3Nic1, freeIp3, nil, subnetName, true) + _, _, _, err = im.GetStaticAddress(pod3, pod3Nic1, freeIP3, nil, subnetName, true) Expect(err).Should(MatchError(ipam.ErrConflict)) By("release pod with multiple nics") im.ReleaseAddressByPod(pod2) - ip2, err := ipam.NewIP(freeIp2) + ip2, err := ipam.NewIP(freeIP2) Expect(err).ShouldNot(HaveOccurred()) - ip3, err := ipam.NewIP(freeIp3) + ip3, err := ipam.NewIP(freeIP3) Expect(err).ShouldNot(HaveOccurred()) Expect(im.Subnets[subnetName].IPPools[""].V4Released.Contains(ip2)).Should(BeTrue()) Expect(im.Subnets[subnetName].IPPools[""].V4Released.Contains(ip3)).Should(BeTrue()) By("release pod with single nic") im.ReleaseAddressByPod(pod1) - ip1, err := ipam.NewIP(freeIp1) + ip1, err := ipam.NewIP(freeIP1) Expect(err).ShouldNot(HaveOccurred()) Expect(im.Subnets[subnetName].IPPools[""].V4Released.Contains(ip1)).To(BeTrue()) @@ -129,7 +129,7 @@ var _ = Describe("[IPAM]", func() { pod4 := "pod4.ns" pod4Nic1 := "pod4Nic1.ns" - _, _, _, err = im.GetStaticAddress(pod4, pod4Nic1, freeIp1, nil, subnetName, true) + _, _, _, err = im.GetStaticAddress(pod4, pod4Nic1, freeIP1, nil, subnetName, true) Expect(err).ShouldNot(HaveOccurred()) By("create pod with no initialized subnet") @@ -218,65 +218,65 @@ var _ = Describe("[IPAM]", func() { pod1 := "pod1.ns" pod1Nic1 := "pod1nic1.ns" - freeIp1 := im.Subnets[subnetName].V6Free.At(0).Start().String() - _, ip, _, err := im.GetStaticAddress(pod1, pod1Nic1, freeIp1, nil, subnetName, true) + freeIP1 := im.Subnets[subnetName].V6Free.At(0).Start().String() + _, ip, _, err := im.GetStaticAddress(pod1, pod1Nic1, freeIP1, nil, subnetName, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip).To(Equal(freeIp1)) + Expect(ip).To(Equal(freeIP1)) _, ip, _, err = im.GetRandomAddress(pod1, pod1Nic1, nil, subnetName, "", nil, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip).To(Equal(freeIp1)) + Expect(ip).To(Equal(freeIP1)) By("create multiple ips on one pod ") pod2 := "pod2.ns" pod2Nic1 := "pod2Nic1.ns" pod2Nic2 := "pod2Nic2.ns" - freeIp2 := im.Subnets[subnetName].V6Free.At(0).Start().String() + freeIP2 := im.Subnets[subnetName].V6Free.At(0).Start().String() _, ip, _, err = im.GetRandomAddress(pod2, pod2Nic1, nil, subnetName, "", nil, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip).To(Equal(freeIp2)) + Expect(ip).To(Equal(freeIP2)) - freeIp3 := im.Subnets[subnetName].V6Free.At(0).Start().String() + freeIP3 := im.Subnets[subnetName].V6Free.At(0).Start().String() _, ip, _, err = im.GetRandomAddress(pod2, pod2Nic2, nil, subnetName, "", nil, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip).To(Equal(freeIp3)) + Expect(ip).To(Equal(freeIP3)) addresses := im.GetPodAddress(pod2) Expect(addresses).To(HaveLen(2)) - Expect([]string{addresses[0].Ip, addresses[1].Ip}).To(Equal([]string{freeIp2, freeIp3})) - Expect(im.ContainAddress(freeIp2)).Should(BeTrue()) - Expect(im.ContainAddress(freeIp3)).Should(BeTrue()) + Expect([]string{addresses[0].IP, addresses[1].IP}).To(Equal([]string{freeIP2, freeIP3})) + Expect(im.ContainAddress(freeIP2)).Should(BeTrue()) + Expect(im.ContainAddress(freeIP3)).Should(BeTrue()) - _, isIPAssigned := im.IsIPAssignedToOtherPod(freeIp2, subnetName, pod2) + _, isIPAssigned := im.IsIPAssignedToOtherPod(freeIP2, subnetName, pod2) Expect(isIPAssigned).Should(BeFalse()) - _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIp3, subnetName, pod2) + _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIP3, subnetName, pod2) Expect(isIPAssigned).Should(BeFalse()) - assignedPod, isIPAssigned := im.IsIPAssignedToOtherPod(freeIp1, subnetName, pod2) + assignedPod, isIPAssigned := im.IsIPAssignedToOtherPod(freeIP1, subnetName, pod2) Expect(isIPAssigned).Should(BeTrue()) Expect(assignedPod).To(Equal(pod1)) By("get static ip conflict with ip in use ") pod3 := "pod3.ns" pod3Nic1 := "pod3Nic1.ns" - _, _, _, err = im.GetStaticAddress(pod3, pod3Nic1, freeIp3, nil, subnetName, true) + _, _, _, err = im.GetStaticAddress(pod3, pod3Nic1, freeIP3, nil, subnetName, true) Expect(err).Should(MatchError(ipam.ErrConflict)) By("release pod with multiple nics") im.ReleaseAddressByPod(pod2) - ip2, err := ipam.NewIP(freeIp2) + ip2, err := ipam.NewIP(freeIP2) Expect(err).ShouldNot(HaveOccurred()) - ip3, err := ipam.NewIP(freeIp3) + ip3, err := ipam.NewIP(freeIP3) Expect(err).ShouldNot(HaveOccurred()) Expect(im.Subnets[subnetName].IPPools[""].V6Released.Contains(ip2)).Should(BeTrue()) Expect(im.Subnets[subnetName].IPPools[""].V6Released.Contains(ip3)).Should(BeTrue()) By("release pod with single nic") im.ReleaseAddressByPod(pod1) - ip1, err := ipam.NewIP(freeIp1) + ip1, err := ipam.NewIP(freeIP1) Expect(err).ShouldNot(HaveOccurred()) Expect(im.Subnets[subnetName].IPPools[""].V6Released.Contains(ip1)).Should(BeTrue()) @@ -284,7 +284,7 @@ var _ = Describe("[IPAM]", func() { pod4 := "pod4.ns" pod4Nic1 := "pod4Nic1.ns" - _, _, _, err = im.GetStaticAddress(pod4, pod4Nic1, freeIp1, nil, subnetName, true) + _, _, _, err = im.GetStaticAddress(pod4, pod4Nic1, freeIP1, nil, subnetName, true) Expect(err).ShouldNot(HaveOccurred()) By("create pod with no initialized subnet") @@ -373,81 +373,81 @@ var _ = Describe("[IPAM]", func() { pod1 := "pod1.ns" pod1Nic1 := "pod1nic1.ns" - freeIp41 := im.Subnets[subnetName].V4Free.At(0).Start().String() - freeIp61 := im.Subnets[subnetName].V6Free.At(0).Start().String() - dualIp := fmt.Sprintf("%s,%s", freeIp41, freeIp61) - ip4, ip6, _, err := im.GetStaticAddress(pod1, pod1Nic1, dualIp, nil, subnetName, true) + freeIP41 := im.Subnets[subnetName].V4Free.At(0).Start().String() + freeIP61 := im.Subnets[subnetName].V6Free.At(0).Start().String() + dualIP := fmt.Sprintf("%s,%s", freeIP41, freeIP61) + ip4, ip6, _, err := im.GetStaticAddress(pod1, pod1Nic1, dualIP, nil, subnetName, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip4).To(Equal(freeIp41)) - Expect(ip6).To(Equal(freeIp61)) + Expect(ip4).To(Equal(freeIP41)) + Expect(ip6).To(Equal(freeIP61)) ip4, ip6, _, err = im.GetRandomAddress(pod1, pod1Nic1, nil, subnetName, "", nil, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip4).To(Equal(freeIp41)) - Expect(ip6).To(Equal(freeIp61)) + Expect(ip4).To(Equal(freeIP41)) + Expect(ip6).To(Equal(freeIP61)) By("create multiple ips on one pod ") pod2 := "pod2.ns" pod2Nic1 := "pod2Nic1.ns" pod2Nic2 := "pod2Nic2.ns" - freeIp42 := im.Subnets[subnetName].V4Free.At(0).Start().String() - freeIp62 := im.Subnets[subnetName].V6Free.At(0).Start().String() + freeIP42 := im.Subnets[subnetName].V4Free.At(0).Start().String() + freeIP62 := im.Subnets[subnetName].V6Free.At(0).Start().String() ip4, ip6, _, err = im.GetRandomAddress(pod2, pod2Nic1, nil, subnetName, "", nil, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip4).To(Equal(freeIp42)) - Expect(ip6).To(Equal(freeIp62)) + Expect(ip4).To(Equal(freeIP42)) + Expect(ip6).To(Equal(freeIP62)) - freeIp43 := im.Subnets[subnetName].V4Free.At(0).Start().String() - freeIp63 := im.Subnets[subnetName].V6Free.At(0).Start().String() + freeIP43 := im.Subnets[subnetName].V4Free.At(0).Start().String() + freeIP63 := im.Subnets[subnetName].V6Free.At(0).Start().String() ip4, ip6, _, err = im.GetRandomAddress(pod2, pod2Nic2, nil, subnetName, "", nil, true) Expect(err).ShouldNot(HaveOccurred()) - Expect(ip4).To(Equal(freeIp43)) - Expect(ip6).To(Equal(freeIp63)) + Expect(ip4).To(Equal(freeIP43)) + Expect(ip6).To(Equal(freeIP63)) addresses := im.GetPodAddress(pod2) Expect(addresses).To(HaveLen(4)) - Expect([]string{addresses[0].Ip, addresses[1].Ip, addresses[2].Ip, addresses[3].Ip}). - To(Equal([]string{freeIp42, freeIp62, freeIp43, freeIp63})) - Expect(im.ContainAddress(freeIp42)).Should(BeTrue()) - Expect(im.ContainAddress(freeIp43)).Should(BeTrue()) - Expect(im.ContainAddress(freeIp62)).Should(BeTrue()) - Expect(im.ContainAddress(freeIp63)).Should(BeTrue()) - - _, isIPAssigned := im.IsIPAssignedToOtherPod(freeIp42, subnetName, pod2) + Expect([]string{addresses[0].IP, addresses[1].IP, addresses[2].IP, addresses[3].IP}). + To(Equal([]string{freeIP42, freeIP62, freeIP43, freeIP63})) + Expect(im.ContainAddress(freeIP42)).Should(BeTrue()) + Expect(im.ContainAddress(freeIP43)).Should(BeTrue()) + Expect(im.ContainAddress(freeIP62)).Should(BeTrue()) + Expect(im.ContainAddress(freeIP63)).Should(BeTrue()) + + _, isIPAssigned := im.IsIPAssignedToOtherPod(freeIP42, subnetName, pod2) Expect(isIPAssigned).Should(BeFalse()) - _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIp62, subnetName, pod2) + _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIP62, subnetName, pod2) Expect(isIPAssigned).Should(BeFalse()) - _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIp43, subnetName, pod2) + _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIP43, subnetName, pod2) Expect(isIPAssigned).Should(BeFalse()) - _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIp63, subnetName, pod2) + _, isIPAssigned = im.IsIPAssignedToOtherPod(freeIP63, subnetName, pod2) Expect(isIPAssigned).Should(BeFalse()) - assignedPod, isIPAssigned := im.IsIPAssignedToOtherPod(freeIp41, subnetName, pod2) + assignedPod, isIPAssigned := im.IsIPAssignedToOtherPod(freeIP41, subnetName, pod2) Expect(isIPAssigned).Should(BeTrue()) Expect(assignedPod).To(Equal(pod1)) By("get static ip conflict with ip in use ") pod3 := "pod3.ns" pod3Nic1 := "pod3Nic1.ns" - _, _, _, err = im.GetStaticAddress(pod3, pod3Nic1, freeIp43, nil, subnetName, true) + _, _, _, err = im.GetStaticAddress(pod3, pod3Nic1, freeIP43, nil, subnetName, true) Expect(err).Should(MatchError(ipam.ErrConflict)) - _, _, _, err = im.GetStaticAddress(pod3, pod3Nic1, freeIp63, nil, subnetName, true) + _, _, _, err = im.GetStaticAddress(pod3, pod3Nic1, freeIP63, nil, subnetName, true) Expect(err).Should(MatchError(ipam.ErrConflict)) By("release pod with multiple nics") im.ReleaseAddressByPod(pod2) - ip42, err := ipam.NewIP(freeIp42) + ip42, err := ipam.NewIP(freeIP42) Expect(err).ShouldNot(HaveOccurred()) - ip43, err := ipam.NewIP(freeIp43) + ip43, err := ipam.NewIP(freeIP43) Expect(err).ShouldNot(HaveOccurred()) - ip62, err := ipam.NewIP(freeIp62) + ip62, err := ipam.NewIP(freeIP62) Expect(err).ShouldNot(HaveOccurred()) - ip63, err := ipam.NewIP(freeIp63) + ip63, err := ipam.NewIP(freeIP63) Expect(err).ShouldNot(HaveOccurred()) Expect(im.Subnets[subnetName].IPPools[""].V4Released.Contains(ip42)).Should(BeTrue()) Expect(im.Subnets[subnetName].IPPools[""].V4Released.Contains(ip43)).Should(BeTrue()) @@ -456,9 +456,9 @@ var _ = Describe("[IPAM]", func() { By("release pod with single nic") im.ReleaseAddressByPod(pod1) - ip41, err := ipam.NewIP(freeIp41) + ip41, err := ipam.NewIP(freeIP41) Expect(err).ShouldNot(HaveOccurred()) - ip61, err := ipam.NewIP(freeIp61) + ip61, err := ipam.NewIP(freeIP61) Expect(err).ShouldNot(HaveOccurred()) Expect(im.Subnets[subnetName].IPPools[""].V4Released.Contains(ip41)).Should(BeTrue()) Expect(im.Subnets[subnetName].IPPools[""].V6Released.Contains(ip61)).Should(BeTrue()) @@ -467,10 +467,10 @@ var _ = Describe("[IPAM]", func() { pod4 := "pod4.ns" pod4Nic1 := "pod4Nic1.ns" - _, _, _, err = im.GetStaticAddress(pod4, pod4Nic1, freeIp41, nil, subnetName, true) + _, _, _, err = im.GetStaticAddress(pod4, pod4Nic1, freeIP41, nil, subnetName, true) Expect(err).ShouldNot(HaveOccurred()) - _, _, _, err = im.GetStaticAddress(pod4, pod4Nic1, freeIp61, nil, subnetName, true) + _, _, _, err = im.GetStaticAddress(pod4, pod4Nic1, freeIP61, nil, subnetName, true) Expect(err).ShouldNot(HaveOccurred()) By("create pod with no initialized subnet") @@ -479,7 +479,6 @@ var _ = Describe("[IPAM]", func() { _, _, _, err = im.GetRandomAddress(pod5, pod5Nic1, nil, "invalid_subnet", "", nil, true) Expect(err).Should(MatchError(ipam.ErrNoAvailable)) - }) It("change cidr", func() { diff --git a/test/unittest/ipam_bench/ipam_test.go b/test/unittest/ipam_bench/ipam_test.go index b15329194b5..d5489adbca0 100644 --- a/test/unittest/ipam_bench/ipam_test.go +++ b/test/unittest/ipam_bench/ipam_test.go @@ -364,7 +364,7 @@ func getDefaultSubnetParam(protocol string) (string, string, string, []string) { } func getDefaultSubnetRandomIps(b *testing.B, protocol string, ipCount int) *stringSet { - var newIp string + var newIP string ipSet := newStringSet() for n := 0; ipSet.Len() < ipCount; n++ { bytes := make([]byte, 3) @@ -373,14 +373,14 @@ func getDefaultSubnetRandomIps(b *testing.B, protocol string, ipCount int) *stri } switch protocol { case kubeovnv1.ProtocolIPv4: - newIp = fmt.Sprintf("10.%d.%d.%d", bytes[0], bytes[1], bytes[2]) + newIP = fmt.Sprintf("10.%d.%d.%d", bytes[0], bytes[1], bytes[2]) case kubeovnv1.ProtocolIPv6: - newIp = fmt.Sprintf("fd00::00%02x:%02x%02x", bytes[0], bytes[1], bytes[2]) + newIP = fmt.Sprintf("fd00::00%02x:%02x%02x", bytes[0], bytes[1], bytes[2]) case kubeovnv1.ProtocolDual: - newIp = fmt.Sprintf("10.%d.%d.%d,fd00::00%02x:%02x%02x", + newIP = fmt.Sprintf("10.%d.%d.%d,fd00::00%02x:%02x%02x", bytes[0], bytes[1], bytes[2], bytes[0], bytes[1], bytes[2]) } - ipSet.Add(newIp) + ipSet.Add(newIP) } return ipSet } diff --git a/test/unittest/util/net.go b/test/unittest/util/net.go index 78f412b3e8b..ba6d53d11cb 100644 --- a/test/unittest/util/net.go +++ b/test/unittest/util/net.go @@ -31,7 +31,7 @@ var _ = Describe("[Net]", func() { } }) - It("CountIpNums", func() { + It("CountIPNums", func() { args := [][]string{ {"10.0.0.101"}, {"10.0.0.101..10.0.0.105"}, @@ -45,7 +45,7 @@ var _ = Describe("[Net]", func() { Expect(args).To(HaveLen(len(wants))) for i := range args { - Expect(util.CountIpNums(args[i])).To(Equal(wants[i])) + Expect(util.CountIPNums(args[i])).To(Equal(wants[i])) } })