diff --git a/.github/workflows/build-x86-image.yaml b/.github/workflows/build-x86-image.yaml index 3536afe89fb..9314c96544e 100644 --- a/.github/workflows/build-x86-image.yaml +++ b/.github/workflows/build-x86-image.yaml @@ -23,7 +23,7 @@ concurrency: env: GO_VERSION: '' KIND_VERSION: v0.23.0 - GOSEC_VERSION: '2.20.0' + GOLANGCI_LINT_VERSION: 'v1.59.1' HELM_VERSION: v3.15.3 SUBMARINER_VERSION: '0.18.0' @@ -167,14 +167,9 @@ jobs: go install -mod=mod github.com/onsi/ginkgo/v2/ginkgo make ut - - name: Install gosec + - name: Install golangci-lint run: | - tmp=$(mktemp -d) - archive="gosec_${{ env.GOSEC_VERSION }}_$(go env GOHOSTOS)_$(go env GOHOSTARCH).tar.gz" - wget -q -O "$tmp/$archive" https://github.com/securego/gosec/releases/download/v${{ env.GOSEC_VERSION }}/$archive - tar --no-same-owner -C "$tmp" -xzf "$tmp/$archive" - install "$tmp/gosec" /usr/local/bin - rm -rf $tmp + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin $GOLANGCI_LINT_VERSION - name: Download base images if: needs.build-kube-ovn-base.outputs.build-base == 1 diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml deleted file mode 100644 index 15713d815b7..00000000000 --- a/.github/workflows/lint.yaml +++ /dev/null @@ -1,43 +0,0 @@ -name: golangci-lint -on: - push: - tags: - - v* - branches: - - master - - main - pull_request: - -concurrency: - group: "${{ github.workflow }}-${{ github.ref }}" - cancel-in-progress: true - -env: - GO_VERSION: '' - -jobs: - golangci: - name: lint - runs-on: ubuntu-24.04 - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-go@v5 - with: - go-version: ${{ env.GO_VERSION || '' }} - go-version-file: go.mod - check-latest: true - cache: false - - - name: golangci-lint - uses: golangci/golangci-lint-action@v6 - with: - # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. - version: latest - - # Optional: working directory, useful for monorepos - # working-directory: somedir - - # Optional: golangci-lint command line arguments. - 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 index 10ba84a7e65..4e4ddf5afdc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -15,6 +15,13 @@ linters: - unconvert - unused - errcheck + - gosec + - govet + - perfsprint + - usestdlibvars + - loggercheck + - whitespace + - errorlint issues: max-same-issues: 0 @@ -31,10 +38,20 @@ issues: - linters: - revive text: "VpcDnsList should be VpcDNSList" # api param not change + - linters: + - gosec + path: _test\.go + - linters: + - gosec + path: test/ linters-settings: goimports: local-prefixes: github.com/kubeovn/kube-ovn gofumpt: extra-rules: true + perfsprint: + strconcat: false + errorlint: + asserts: false diff --git a/Makefile b/Makefile index a86afe63182..45ad280f5a4 100644 --- a/Makefile +++ b/Makefile @@ -972,16 +972,7 @@ uninstall: .PHONY: lint lint: - @gofmt -d . - @if [ $$(gofmt -l . | wc -l) -ne 0 ]; then \ - echo "Code differs from gofmt's style" 1>&2 && exit 1; \ - fi - @GOOS=linux go vet ./... - @GOOS=linux gosec -exclude-dir=test -exclude-dir=pkg/client ./... - -.PHONY: gofumpt -gofumpt: - gofumpt -w -extra . + golangci-lint run -v .PHONY: lint-windows lint-windows: diff --git a/cmd/daemon/cniserver.go b/cmd/daemon/cniserver.go index 1138a781d57..00d0b0e164a 100644 --- a/cmd/daemon/cniserver.go +++ b/cmd/daemon/cniserver.go @@ -1,6 +1,7 @@ package daemon import ( + "errors" "fmt" "net" "net/http" @@ -175,7 +176,7 @@ func initChassisAnno(cfg *daemon.Configuration) error { chassesName := strings.TrimSpace(string(chassisID)) if chassesName == "" { // not ready yet - err = fmt.Errorf("chassis id is empty") + err = errors.New("chassis id is empty") klog.Error(err) return err } diff --git a/cmd/daemon/init.go b/cmd/daemon/init.go index bf094065afd..333a95c407e 100644 --- a/cmd/daemon/init.go +++ b/cmd/daemon/init.go @@ -14,7 +14,7 @@ func initForOS() error { // disable checksum for genev_sys_6081 as default cmd := exec.Command("sh", "-c", "ethtool -K genev_sys_6081 tx off") if err := cmd.Run(); err != nil { - err := fmt.Errorf("failed to set checksum off for genev_sys_6081, %v", err) + err := fmt.Errorf("failed to set checksum off for genev_sys_6081, %w", err) // should not affect cni pod running if failed, just record err log klog.Error(err) } diff --git a/go.mod b/go.mod index d7c6f2e58fc..168659fcc11 100644 --- a/go.mod +++ b/go.mod @@ -44,6 +44,7 @@ require ( gopkg.in/k8snetworkplumbingwg/multus-cni.v4 v4.0.2 k8s.io/api v0.30.3 k8s.io/apimachinery v0.30.3 + k8s.io/apiserver v0.30.3 k8s.io/client-go v12.0.0+incompatible k8s.io/klog/v2 v2.130.1 k8s.io/kubectl v0.30.3 @@ -242,7 +243,6 @@ require ( gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/apiextensions-apiserver v0.30.3 // indirect - k8s.io/apiserver v0.30.3 // indirect k8s.io/cli-runtime v0.30.3 // indirect k8s.io/cloud-provider v0.30.3 // indirect k8s.io/cluster-bootstrap v0.30.3 // indirect diff --git a/pkg/controller/admin_network_policy.go b/pkg/controller/admin_network_policy.go index 076c48fb03f..f8feb9682af 100644 --- a/pkg/controller/admin_network_policy.go +++ b/pkg/controller/admin_network_policy.go @@ -1,6 +1,7 @@ package controller import ( + "errors" "fmt" "reflect" "strings" @@ -200,7 +201,7 @@ func (c *Controller) processNextUpdateAnpWorkItem() bool { } if err := c.handleUpdateAnp(key); err != nil { c.updateAnpQueue.AddRateLimited(key) - return fmt.Errorf("error syncing admin network policy %s: %v, requeuing", key.key, err) + return fmt.Errorf("error syncing admin network policy %s: %w, requeuing", key.key, err) } c.updateAnpQueue.Forget(obj) return nil @@ -358,10 +359,10 @@ func (c *Controller) handleAddAnp(key string) (err error) { } if err := c.OVNNbClient.Transact("add-ingress-acls", ingressACLOps); err != nil { - return fmt.Errorf("failed to add ingress acls for anp %s: %v", key, err) + return fmt.Errorf("failed to add ingress acls for anp %s: %w", key, err) } if err := c.deleteUnusedAddrSetForAnp(curIngressAddrSet, desiredIngressAddrSet); err != nil { - return fmt.Errorf("failed to delete unused ingress address set for anp %s: %v", key, err) + return fmt.Errorf("failed to delete unused ingress address set for anp %s: %w", key, err) } egressACLOps, err := c.OVNNbClient.DeleteAclsOps(pgName, portGroupKey, "from-lport", nil) @@ -423,10 +424,10 @@ func (c *Controller) handleAddAnp(key string) (err error) { } if err := c.OVNNbClient.Transact("add-egress-acls", egressACLOps); err != nil { - return fmt.Errorf("failed to add egress acls for anp %s: %v", key, err) + return fmt.Errorf("failed to add egress acls for anp %s: %w", key, err) } if err := c.deleteUnusedAddrSetForAnp(curEgressAddrSet, desiredEgressAddrSet); err != nil { - return fmt.Errorf("failed to delete unused egress address set for anp %s: %v", key, err) + return fmt.Errorf("failed to delete unused egress address set for anp %s: %w", key, err) } return nil @@ -600,26 +601,26 @@ func (c *Controller) fetchSelectedPods(anpSubject *v1alpha1.AdminNetworkPolicySu if anpSubject.Namespaces != nil { nsSelector, err := metav1.LabelSelectorAsSelector(anpSubject.Namespaces) if err != nil { - return nil, fmt.Errorf("error creating ns label selector, %v", err) + return nil, fmt.Errorf("error creating ns label selector, %w", err) } ports, _, _, err = c.fetchPods(nsSelector, labels.Everything()) if err != nil { - return nil, fmt.Errorf("failed to fetch pods, %v", err) + return nil, fmt.Errorf("failed to fetch pods, %w", err) } } else { nsSelector, err := metav1.LabelSelectorAsSelector(&anpSubject.Pods.NamespaceSelector) if err != nil { - return nil, fmt.Errorf("error creating ns label selector, %v", err) + return nil, fmt.Errorf("error creating ns label selector, %w", err) } podSelector, err := metav1.LabelSelectorAsSelector(&anpSubject.Pods.PodSelector) if err != nil { - return nil, fmt.Errorf("error creating pod label selector, %v", err) + return nil, fmt.Errorf("error creating pod label selector, %w", err) } ports, _, _, err = c.fetchPods(nsSelector, podSelector) if err != nil { - return nil, fmt.Errorf("failed to fetch pods, %v", err) + return nil, fmt.Errorf("failed to fetch pods, %w", err) } } klog.Infof("get selected ports for subject, %v", ports) @@ -641,7 +642,7 @@ func (c *Controller) fetchPods(nsSelector, podSelector labels.Selector) ([]strin for _, namespace := range namespaces { pods, err := c.podsLister.Pods(namespace.Name).List(podSelector) if err != nil { - return nil, nil, nil, fmt.Errorf("failed to list pods, %v", err) + return nil, nil, nil, fmt.Errorf("failed to list pods, %w", err) } for _, pod := range pods { @@ -652,7 +653,7 @@ func (c *Controller) fetchPods(nsSelector, podSelector labels.Selector) ([]strin podNets, err := c.getPodKubeovnNets(pod) if err != nil { - return nil, nil, nil, fmt.Errorf("failed to get pod networks, %v", err) + return nil, nil, nil, fmt.Errorf("failed to get pod networks, %w", err) } for _, podNet := range podNets { @@ -688,26 +689,26 @@ func (c *Controller) fetchIngressSelectedAddresses(ingressPeer *v1alpha1.AdminNe if ingressPeer.Namespaces != nil { nsSelector, err := metav1.LabelSelectorAsSelector(ingressPeer.Namespaces) if err != nil { - return nil, nil, fmt.Errorf("error creating ns label selector, %v", err) + return nil, nil, fmt.Errorf("error creating ns label selector, %w", err) } _, v4Addresses, v6Addresses, err = c.fetchPods(nsSelector, labels.Everything()) if err != nil { - return nil, nil, fmt.Errorf("failed to fetch ingress peer addresses, %v", err) + return nil, nil, fmt.Errorf("failed to fetch ingress peer addresses, %w", err) } } else if ingressPeer.Pods != nil { nsSelector, err := metav1.LabelSelectorAsSelector(&ingressPeer.Pods.NamespaceSelector) if err != nil { - return nil, nil, fmt.Errorf("error creating ns label selector, %v", err) + return nil, nil, fmt.Errorf("error creating ns label selector, %w", err) } podSelector, err := metav1.LabelSelectorAsSelector(&ingressPeer.Pods.PodSelector) if err != nil { - return nil, nil, fmt.Errorf("error creating pod label selector, %v", err) + return nil, nil, fmt.Errorf("error creating pod label selector, %w", err) } _, v4Addresses, v6Addresses, err = c.fetchPods(nsSelector, podSelector) if err != nil { - return nil, nil, fmt.Errorf("failed to fetch ingress peer addresses, %v", err) + return nil, nil, fmt.Errorf("failed to fetch ingress peer addresses, %w", err) } } @@ -723,29 +724,29 @@ func (c *Controller) fetchEgressSelectedAddresses(egressPeer *v1alpha1.AdminNetw case egressPeer.Namespaces != nil: nsSelector, err := metav1.LabelSelectorAsSelector(egressPeer.Namespaces) if err != nil { - return nil, nil, fmt.Errorf("error creating ns label selector, %v", err) + return nil, nil, fmt.Errorf("error creating ns label selector, %w", err) } _, v4Addresses, v6Addresses, err = c.fetchPods(nsSelector, labels.Everything()) if err != nil { - return nil, nil, fmt.Errorf("failed to fetch egress peer addresses, %v", err) + return nil, nil, fmt.Errorf("failed to fetch egress peer addresses, %w", err) } case egressPeer.Pods != nil: nsSelector, err := metav1.LabelSelectorAsSelector(&egressPeer.Pods.NamespaceSelector) if err != nil { - return nil, nil, fmt.Errorf("error creating ns label selector, %v", err) + return nil, nil, fmt.Errorf("error creating ns label selector, %w", err) } podSelector, err := metav1.LabelSelectorAsSelector(&egressPeer.Pods.PodSelector) if err != nil { - return nil, nil, fmt.Errorf("error creating pod label selector, %v", err) + return nil, nil, fmt.Errorf("error creating pod label selector, %w", err) } _, v4Addresses, v6Addresses, err = c.fetchPods(nsSelector, podSelector) if err != nil { - return nil, nil, fmt.Errorf("failed to fetch egress peer addresses, %v", err) + return nil, nil, fmt.Errorf("failed to fetch egress peer addresses, %w", err) } default: - return nil, nil, fmt.Errorf("either Namespaces or Pods must be specified in egressPeer") + return nil, nil, errors.New("either Namespaces or Pods must be specified in egressPeer") } return v4Addresses, v6Addresses, nil diff --git a/pkg/controller/baseline_admin_network_policy.go b/pkg/controller/baseline_admin_network_policy.go index f04475955ad..6dc630bac68 100644 --- a/pkg/controller/baseline_admin_network_policy.go +++ b/pkg/controller/baseline_admin_network_policy.go @@ -173,7 +173,7 @@ func (c *Controller) processNextUpdateBanpWorkItem() bool { } if err := c.handleUpdateBanp(key); err != nil { c.updateBanpQueue.AddRateLimited(key) - return fmt.Errorf("error syncing banp %s: %v, requeuing", key.key, err) + return fmt.Errorf("error syncing banp %s: %w, requeuing", key.key, err) } c.updateBanpQueue.Forget(obj) return nil @@ -319,10 +319,10 @@ func (c *Controller) handleAddBanp(key string) (err error) { } if err := c.OVNNbClient.Transact("add-ingress-acls", ingressACLOps); err != nil { - return fmt.Errorf("failed to add ingress acls for banp %s: %v", key, err) + return fmt.Errorf("failed to add ingress acls for banp %s: %w", key, err) } if err := c.deleteUnusedAddrSetForAnp(curIngressAddrSet, desiredIngressAddrSet); err != nil { - return fmt.Errorf("failed to delete unused ingress address set for banp %s: %v", key, err) + return fmt.Errorf("failed to delete unused ingress address set for banp %s: %w", key, err) } egressACLOps, err := c.OVNNbClient.DeleteAclsOps(pgName, portGroupKey, "from-lport", nil) @@ -384,10 +384,10 @@ func (c *Controller) handleAddBanp(key string) (err error) { } if err := c.OVNNbClient.Transact("add-egress-acls", egressACLOps); err != nil { - return fmt.Errorf("failed to add egress acls for banp %s: %v", key, err) + return fmt.Errorf("failed to add egress acls for banp %s: %w", key, err) } if err := c.deleteUnusedAddrSetForAnp(curEgressAddrSet, desiredEgressAddrSet); err != nil { - return fmt.Errorf("failed to delete unused egress address set for banp %s: %v", key, err) + return fmt.Errorf("failed to delete unused egress address set for banp %s: %w", key, err) } return nil diff --git a/pkg/controller/config.go b/pkg/controller/config.go index af4a8b72bd8..1c625d55b24 100644 --- a/pkg/controller/config.go +++ b/pkg/controller/config.go @@ -1,6 +1,7 @@ package controller import ( + "errors" "flag" "fmt" "os" @@ -265,7 +266,7 @@ func ParseFlags() (*Configuration, error) { } if config.NetworkType == util.NetworkTypeVlan && config.DefaultHostInterface == "" { - return nil, fmt.Errorf("no host nic for vlan") + return nil, errors.New("no host nic for vlan") } if config.DefaultGateway == "" { @@ -302,7 +303,7 @@ func ParseFlags() (*Configuration, error) { if err := util.CheckSystemCIDR([]string{config.NodeSwitchCIDR, config.DefaultCIDR, config.ServiceClusterIPRange}); err != nil { klog.Error(err) - return nil, fmt.Errorf("check system cidr failed, %v", err) + return nil, fmt.Errorf("check system cidr failed, %w", err) } for _, ip := range strings.Split(*argNodeLocalDNSIP, ",") { diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go index dc4ec484840..ab81820b617 100644 --- a/pkg/controller/controller.go +++ b/pkg/controller/controller.go @@ -1204,7 +1204,7 @@ func (c *Controller) allSubnetReady(subnets ...string) (bool, error) { exist, err := c.OVNNbClient.LogicalSwitchExists(lsName) if err != nil { klog.Error(err) - return false, fmt.Errorf("check logical switch %s exist: %v", lsName, err) + return false, fmt.Errorf("check logical switch %s exist: %w", lsName, err) } if !exist { diff --git a/pkg/controller/external_gw.go b/pkg/controller/external_gw.go index 32667597d6f..e09d9cdd2bd 100644 --- a/pkg/controller/external_gw.go +++ b/pkg/controller/external_gw.go @@ -2,6 +2,7 @@ package controller import ( "context" + "errors" "fmt" "reflect" "slices" @@ -254,7 +255,7 @@ func (c *Controller) getGatewayChassis(config map[string]string) ([]string, erro chassises = append(chassises, chassis.Name) } if len(chassises) == 0 { - err := fmt.Errorf("no available external gw chassis") + err := errors.New("no available external gw chassis") klog.Error(err) return nil, err } @@ -271,7 +272,7 @@ func (c *Controller) updateDefaultVpcExternal(enableExternal bool) error { if vpc.Spec.EnableExternal != enableExternal { vpc.Spec.EnableExternal = enableExternal if _, err := c.config.KubeOvnClient.KubeovnV1().Vpcs().Update(context.Background(), vpc, metav1.UpdateOptions{}); err != nil { - err := fmt.Errorf("failed to update vpc enable external %s, %v", vpc.Name, err) + err := fmt.Errorf("failed to update vpc enable external %s, %w", vpc.Name, err) klog.Error(err) return err } diff --git a/pkg/controller/init.go b/pkg/controller/init.go index 3142471a20b..4a85e6b22b2 100644 --- a/pkg/controller/init.go +++ b/pkg/controller/init.go @@ -141,7 +141,7 @@ func (c *Controller) initDefaultLogicalSwitch() error { if c.config.NetworkType == util.NetworkTypeVlan { defaultSubnet.Spec.Vlan = c.config.DefaultVlanName if c.config.DefaultLogicalGateway && c.config.DefaultU2OInterconnection { - err = fmt.Errorf("logicalGateway and u2oInterconnection can't be opened at the same time") + err = errors.New("logicalGateway and u2oInterconnection can't be opened at the same time") klog.Error(err) return err } @@ -571,7 +571,7 @@ func (c *Controller) initDefaultVlan() error { } if c.config.DefaultVlanID < 0 || c.config.DefaultVlanID > 4095 { - return fmt.Errorf("the default vlan id is not between 1-4095") + return errors.New("the default vlan id is not between 1-4095") } defaultVlan := kubeovnv1.Vlan{ diff --git a/pkg/controller/ip.go b/pkg/controller/ip.go index e689823cca3..d55171c7eb8 100644 --- a/pkg/controller/ip.go +++ b/pkg/controller/ip.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "net" "reflect" @@ -217,7 +218,7 @@ func (c *Controller) handleAddReservedIP(key string) error { } klog.V(3).Infof("handle add reserved ip %s", ip.Name) if ip.Spec.Subnet == "" { - err := fmt.Errorf("subnet parameter cannot be empty") + err := errors.New("subnet parameter cannot be empty") klog.Error(err) return err } @@ -229,7 +230,7 @@ func (c *Controller) handleAddReservedIP(key string) error { subnet, err := c.subnetsLister.Get(ip.Spec.Subnet) if err != nil { - err = fmt.Errorf("failed to get subnet %s: %v", ip.Spec.Subnet, err) + err = fmt.Errorf("failed to get subnet %s: %w", ip.Spec.Subnet, err) klog.Error(err) return err } @@ -255,13 +256,13 @@ func (c *Controller) handleAddReservedIP(key string) error { v4IP, v6IP, mac, err := c.ipAcquireAddress(ip, subnet) if err != nil { - err = fmt.Errorf("failed to acquire ip address %v", err) + err = fmt.Errorf("failed to acquire ip address %w", err) klog.Error(err) return err } ipStr := util.GetStringIP(v4IP, v6IP) if err := c.createOrUpdateIPCR(ip.Name, ip.Spec.PodName, ipStr, mac, subnet.Name, ip.Spec.Namespace, ip.Spec.NodeName, ip.Spec.PodType); err != nil { - err = fmt.Errorf("failed to create ips CR %s.%s: %v", ip.Spec.PodName, ip.Spec.Namespace, err) + err = fmt.Errorf("failed to create ips CR %s.%s: %w", ip.Spec.PodName, ip.Spec.Namespace, err) klog.Error(err) return err } @@ -485,7 +486,7 @@ func (c *Controller) createOrUpdateIPCR(ipCRName, podName, ip, mac, subnetName, ipCR, err = c.ipsLister.Get(ipName) if err != nil { if !k8serrors.IsNotFound(err) { - err := fmt.Errorf("failed to get ip CR %s: %v", ipName, err) + err := fmt.Errorf("failed to get ip CR %s: %w", ipName, err) klog.Error(err) return err } @@ -521,7 +522,7 @@ func (c *Controller) createOrUpdateIPCR(ipCRName, podName, ip, mac, subnetName, }, }, metav1.CreateOptions{}) if err != nil { - errMsg := fmt.Errorf("failed to create ip CR %s: %v", ipName, err) + errMsg := fmt.Errorf("failed to create ip CR %s: %w", ipName, err) klog.Error(errMsg) return errMsg } @@ -555,11 +556,10 @@ func (c *Controller) createOrUpdateIPCR(ipCRName, podName, ip, mac, subnetName, ipCR, err = c.config.KubeOvnClient.KubeovnV1().IPs().Update(context.Background(), newIPCR, metav1.UpdateOptions{}) if err != nil { - err := fmt.Errorf("failed to update ip CR %s: %v", ipCRName, err) + err := fmt.Errorf("failed to update ip CR %s: %w", ipCRName, err) klog.Error(err) return err } - } if err := c.handleAddIPFinalizer(ipCR); err != nil { klog.Errorf("failed to handle add ip finalizer %v", err) @@ -590,14 +590,14 @@ func (c *Controller) ipAcquireAddress(ip *kubeovnv1.IP, subnet *kubeovnv1.Subnet if err == nil { return v4IP, v6IP, mac, err } - err = fmt.Errorf("failed to get random address for ip %s, %v", ip.Name, err) + err = fmt.Errorf("failed to get random address for ip %s, %w", ip.Name, err) } else { // static address v4IP, v6IP, mac, err = c.acquireStaticAddress(key, portName, ipStr, macPtr, subnet.Name, true) if err == nil { return v4IP, v6IP, mac, nil } - err = fmt.Errorf("failed to get static address for ip %s, %v", ip.Name, err) + err = fmt.Errorf("failed to get static address for ip %s, %w", ip.Name, err) } klog.Error(err) return "", "", "", err diff --git a/pkg/controller/network_policy.go b/pkg/controller/network_policy.go index e1c53c8662b..b1e6628e622 100644 --- a/pkg/controller/network_policy.go +++ b/pkg/controller/network_policy.go @@ -88,7 +88,7 @@ func (c *Controller) processNextUpdateNpWorkItem() bool { } if err := c.handleUpdateNp(key); err != nil { c.updateNpQueue.AddRateLimited(key) - return fmt.Errorf("error syncing network policy %s: %v, requeuing", key, err) + return fmt.Errorf("error syncing network policy %s: %w, requeuing", key, err) } c.updateNpQueue.Forget(obj) return nil @@ -301,7 +301,7 @@ func (c *Controller) handleUpdateNp(key string) error { } } if err := c.OVNNbClient.Transact("add-ingress-acls", ingressACLOps); err != nil { - return fmt.Errorf("add ingress acls to %s: %v", pgName, err) + return fmt.Errorf("add ingress acls to %s: %w", pgName, err) } if err := c.OVNNbClient.SetACLLog(pgName, logEnable, true); err != nil { @@ -425,11 +425,10 @@ func (c *Controller) handleUpdateNp(key string) error { egressACLOps = append(egressACLOps, ops...) } - } } if err := c.OVNNbClient.Transact("add-egress-acls", egressACLOps); err != nil { - return fmt.Errorf("add egress acls to %s: %v", pgName, err) + return fmt.Errorf("add egress acls to %s: %w", pgName, err) } if err := c.OVNNbClient.SetACLLog(pgName, logEnable, false); err != nil { @@ -537,11 +536,11 @@ func (c *Controller) fetchSelectedPorts(namespace string, selector *metav1.Label var subnets []string sel, err := metav1.LabelSelectorAsSelector(selector) if err != nil { - return nil, nil, fmt.Errorf("error creating label selector, %v", err) + return nil, nil, fmt.Errorf("error creating label selector, %w", err) } pods, err := c.podsLister.Pods(namespace).List(sel) if err != nil { - return nil, nil, fmt.Errorf("failed to list pods, %v", err) + return nil, nil, fmt.Errorf("failed to list pods, %w", err) } ports := make([]string, 0, len(pods)) @@ -552,7 +551,7 @@ func (c *Controller) fetchSelectedPorts(namespace string, selector *metav1.Label podName := c.getNameByPod(pod) podNets, err := c.getPodKubeovnNets(pod) if err != nil { - return nil, nil, fmt.Errorf("failed to get pod networks, %v", err) + return nil, nil, fmt.Errorf("failed to get pod networks, %w", err) } for _, podNet := range podNets { @@ -610,11 +609,11 @@ func (c *Controller) fetchPolicySelectedAddresses(namespace, protocol string, np } else { sel, err := metav1.LabelSelectorAsSelector(npp.NamespaceSelector) if err != nil { - return nil, nil, fmt.Errorf("error creating label selector, %v", err) + return nil, nil, fmt.Errorf("error creating label selector, %w", err) } nss, err := c.namespacesLister.List(sel) if err != nil { - return nil, nil, fmt.Errorf("failed to list ns, %v", err) + return nil, nil, fmt.Errorf("failed to list ns, %w", err) } for _, ns := range nss { selectedNs = append(selectedNs, ns.Name) @@ -631,12 +630,12 @@ func (c *Controller) fetchPolicySelectedAddresses(namespace, protocol string, np for _, ns := range selectedNs { pods, err := c.podsLister.Pods(ns).List(sel) if err != nil { - return nil, nil, fmt.Errorf("failed to list pod, %v", err) + return nil, nil, fmt.Errorf("failed to list pod, %w", err) } svcs, err := c.servicesLister.Services(ns).List(labels.Everything()) if err != nil { klog.Errorf("failed to list svc, %v", err) - return nil, nil, fmt.Errorf("failed to list svc, %v", err) + return nil, nil, fmt.Errorf("failed to list svc, %w", err) } for _, pod := range pods { @@ -701,7 +700,7 @@ func isSvcMatchPod(svc *corev1.Service, pod *corev1.Pod) (bool, error) { ss := metav1.SetAsLabelSelector(svc.Spec.Selector) sel, err := metav1.LabelSelectorAsSelector(ss) if err != nil { - return false, fmt.Errorf("error fetch label selector, %v", err) + return false, fmt.Errorf("error fetch label selector, %w", err) } if pod.Labels == nil { return false, nil @@ -740,13 +739,13 @@ func (c *Controller) svcMatchNetworkPolicies(svc *corev1.Service) ([]string, err // find all match pod pods, err := c.podsLister.Pods(svc.Namespace).List(labels.Everything()) if err != nil { - return nil, fmt.Errorf("failed to list pods, %v", err) + return nil, fmt.Errorf("failed to list pods, %w", err) } // find all match netpol nps, err := c.npsLister.NetworkPolicies(corev1.NamespaceAll).List(labels.Everything()) if err != nil { - return nil, fmt.Errorf("failed to list netpols, %v", err) + return nil, fmt.Errorf("failed to list netpols, %w", err) } match := []string{} for _, pod := range pods { diff --git a/pkg/controller/node.go b/pkg/controller/node.go index 450a17254b6..c65731783d9 100644 --- a/pkg/controller/node.go +++ b/pkg/controller/node.go @@ -2,6 +2,7 @@ package controller import ( "context" + "errors" "fmt" "reflect" "slices" @@ -695,7 +696,7 @@ func (c *Controller) checkGatewayReady() error { if util.GatewayContains(subnet.Spec.GatewayNode, node.Name) { pinger, err := goping.NewPinger(ip) if err != nil { - return fmt.Errorf("failed to init pinger, %v", err) + return fmt.Errorf("failed to init pinger, %w", err) } pinger.SetPrivileged(true) @@ -793,7 +794,7 @@ func (c *Controller) retryDelDupChassis(attempts, sleep int, f func(node *v1.Nod time.Sleep(time.Duration(sleep) * time.Second) } if i >= (attempts - 1) { - errMsg := fmt.Errorf("exhausting all attempts") + errMsg := errors.New("exhausting all attempts") klog.Error(errMsg) return errMsg } @@ -917,7 +918,7 @@ func (c *Controller) UpdateChassisTag(node *v1.Node) error { if chassis.ExternalIDs == nil || chassis.ExternalIDs["vendor"] != util.CniTypeName { klog.Infof("init tag %s for node %s chassis %s", util.CniTypeName, node.Name, chassis.Name) if err = c.OVNSbClient.UpdateChassisTag(chassis.Name, node.Name); err != nil { - return fmt.Errorf("failed to init chassis tag, %v", err) + return fmt.Errorf("failed to init chassis tag, %w", err) } } return nil diff --git a/pkg/controller/ovn_eip.go b/pkg/controller/ovn_eip.go index 20f88dabdea..3767eb35d3e 100644 --- a/pkg/controller/ovn_eip.go +++ b/pkg/controller/ovn_eip.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "strings" "time" @@ -391,7 +392,7 @@ func (c *Controller) createOrUpdateOvnEipCR(key, subnet, v4ip, v6ip, mac, usageT }, }, metav1.CreateOptions{}) if err != nil { - err := fmt.Errorf("failed to create crd ovn eip '%s', %v", key, err) + err := fmt.Errorf("failed to create crd ovn eip '%s', %w", key, err) klog.Error(err) return err } @@ -423,7 +424,7 @@ func (c *Controller) createOrUpdateOvnEipCR(key, subnet, v4ip, v6ip, mac, usageT } if needUpdate { if _, err := c.config.KubeOvnClient.KubeovnV1().OvnEips().Update(context.Background(), ovnEip, metav1.UpdateOptions{}); err != nil { - errMsg := fmt.Errorf("failed to update ovn eip '%s', %v", key, err) + errMsg := fmt.Errorf("failed to update ovn eip '%s', %w", key, err) klog.Error(errMsg) return errMsg } @@ -520,7 +521,7 @@ func (c *Controller) patchOvnEipStatus(key string, ready bool) error { } nat, err := c.getOvnEipNat(ovnEip.Spec.V4Ip) if err != nil { - err := fmt.Errorf("failed to get ovn eip nat") + err := errors.New("failed to get ovn eip nat") klog.Error(err) return err } @@ -646,7 +647,7 @@ func (c *Controller) handleDelOvnEipFinalizer(cachedEip *kubeovnv1.OvnEip) error var err error nat, err := c.getOvnEipNat(cachedEip.Spec.V4Ip) if err != nil { - err := fmt.Errorf("failed to get ovn eip nat") + err := errors.New("failed to get ovn eip nat") klog.Error(err) return err } diff --git a/pkg/controller/ovn_fip.go b/pkg/controller/ovn_fip.go index 1ef9e40ce6a..04c816ab3fd 100644 --- a/pkg/controller/ovn_fip.go +++ b/pkg/controller/ovn_fip.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "strconv" @@ -209,7 +210,7 @@ func (c *Controller) handleAddOvnFip(key string) error { // check eip eipName := cachedFip.Spec.OvnEip if eipName == "" { - err := fmt.Errorf("failed to create fip rule, should set eip") + err := errors.New("failed to create fip rule, should set eip") klog.Error(err) return err } @@ -228,7 +229,7 @@ func (c *Controller) handleAddOvnFip(key string) error { v4Eip = cachedEip.Status.V4Ip v6Eip = cachedEip.Status.V6Ip if err = c.isOvnFipDuplicated(key, cachedEip.Spec.V4Ip); err != nil { - err = fmt.Errorf("failed to add fip %s, %v", key, err) + err = fmt.Errorf("failed to add fip %s, %w", key, err) klog.Error(err) return err } @@ -271,7 +272,7 @@ func (c *Controller) handleAddOvnFip(key string) error { } vpcName = subnet.Spec.Vpc if err = c.isOvnFipDuplicated(key, cachedEip.Spec.V4Ip); err != nil { - err = fmt.Errorf("failed to update fip %s, %v", key, err) + err = fmt.Errorf("failed to update fip %s, %w", key, err) klog.Error(err) return err } @@ -349,7 +350,7 @@ func (c *Controller) handleUpdateOvnFip(key string) error { // check eip eipName := cachedFip.Spec.OvnEip if eipName == "" { - err := fmt.Errorf("failed to create fip rule, should set eip") + err := errors.New("failed to create fip rule, should set eip") klog.Error(err) return err } @@ -368,7 +369,7 @@ func (c *Controller) handleUpdateOvnFip(key string) error { v4Eip = cachedEip.Status.V4Ip v6Eip = cachedEip.Status.V6Ip if err = c.isOvnFipDuplicated(key, cachedEip.Spec.V4Ip); err != nil { - err = fmt.Errorf("failed to add fip %s, %v", key, err) + err = fmt.Errorf("failed to add fip %s, %w", key, err) klog.Error(err) return err } @@ -408,7 +409,7 @@ func (c *Controller) handleUpdateOvnFip(key string) error { } vpcName = subnet.Spec.Vpc if err = c.isOvnFipDuplicated(key, cachedEip.Spec.V4Ip); err != nil { - err = fmt.Errorf("failed to update fip %s, %v", key, err) + err = fmt.Errorf("failed to update fip %s, %w", key, err) klog.Error(err) return err } diff --git a/pkg/controller/ovn_snat.go b/pkg/controller/ovn_snat.go index 4d7b1383235..db3c01cf0df 100644 --- a/pkg/controller/ovn_snat.go +++ b/pkg/controller/ovn_snat.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" k8serrors "k8s.io/apimachinery/pkg/api/errors" @@ -190,7 +191,7 @@ func (c *Controller) handleAddOvnSnatRule(key string) error { // check eip eipName := cachedSnat.Spec.OvnEip if eipName == "" { - err := fmt.Errorf("failed to create ovn snat rule, should set eip") + err := errors.New("failed to create ovn snat rule, should set eip") klog.Error(err) return err } @@ -305,7 +306,7 @@ func (c *Controller) handleUpdateOvnSnatRule(key string) error { // check eip eipName := cachedSnat.Spec.OvnEip if eipName == "" { - err := fmt.Errorf("failed to create ovn snat rule, should set eip") + err := errors.New("failed to create ovn snat rule, should set eip") klog.Error(err) return err } diff --git a/pkg/controller/pod.go b/pkg/controller/pod.go index da533cd39db..568200097a2 100644 --- a/pkg/controller/pod.go +++ b/pkg/controller/pod.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "net" "reflect" @@ -726,14 +727,14 @@ func (c *Controller) reconcileAllocateSubnets(cachedPod, pod *v1.Pod, needAlloca if migrated { klog.Infof("migrate end reset options for lsp %s from %s to %s, migrated fail: %t", portName, srcNodeName, targetNodeName, migratedFail) if err := c.OVNNbClient.ResetLogicalSwitchPortMigrateOptions(portName, srcNodeName, targetNodeName, migratedFail); err != nil { - err = fmt.Errorf("failed to clean migrate options for lsp %s, %v", portName, err) + err = fmt.Errorf("failed to clean migrate options for lsp %s, %w", portName, err) klog.Error(err) return nil, err } } else { klog.Infof("migrate start set options for lsp %s from %s to %s", portName, srcNodeName, targetNodeName) if err := c.OVNNbClient.SetLogicalSwitchPortMigrateOptions(portName, srcNodeName, targetNodeName); err != nil { - err = fmt.Errorf("failed to set migrate options for lsp %s, %v", portName, err) + err = fmt.Errorf("failed to set migrate options for lsp %s, %w", portName, err) klog.Error(err) return nil, err } @@ -764,7 +765,7 @@ func (c *Controller) reconcileAllocateSubnets(cachedPod, pod *v1.Pod, needAlloca // CreatePort may fail, so put ip CR creation after CreatePort ipCRName := ovs.PodNameToPortName(podName, pod.Namespace, podNet.ProviderName) if err := c.createOrUpdateIPCR(ipCRName, podName, ipStr, mac, subnet.Name, pod.Namespace, pod.Spec.NodeName, podType); err != nil { - err = fmt.Errorf("failed to create ips CR %s.%s: %v", podName, pod.Namespace, err) + err = fmt.Errorf("failed to create ips CR %s.%s: %w", podName, pod.Namespace, err) klog.Error(err) return nil, err } @@ -866,7 +867,7 @@ func (c *Controller) reconcileRouteSubnets(cachedPod, pod *v1.Pod, needRoutePodN nextHop = externalSubnet.Spec.Gateway if nextHop == "" { klog.Errorf("no available gateway address") - return fmt.Errorf("no available gateway address") + return errors.New("no available gateway address") } } if strings.Contains(nextHop, "/") { @@ -891,7 +892,6 @@ func (c *Controller) reconcileRouteSubnets(cachedPod, pod *v1.Pod, needRoutePodN klog.Error(err) return err } - } else { if subnet.Spec.GatewayType == kubeovnv1.GWDistributedType && pod.Annotations[util.NorthGatewayAnnotation] == "" { nodeTunlIPAddr, err := getNodeTunlIP(node) @@ -1080,7 +1080,7 @@ func (c *Controller) handleDeletePod(key string) error { } for _, port := range ports { if err := c.OVNNbClient.CleanLogicalSwitchPortMigrateOptions(port.Name); err != nil { - err = fmt.Errorf("failed to clean migrate options for vm lsp %s, %v", port.Name, err) + err = fmt.Errorf("failed to clean migrate options for vm lsp %s, %w", port.Name, err) klog.Error(err) return err } @@ -1408,7 +1408,7 @@ func getNodeTunlIP(node *v1.Node) ([]net.IP, error) { var nodeTunlIPAddr []net.IP nodeTunlIP := node.Annotations[util.IPAddressAnnotation] if nodeTunlIP == "" { - return nil, fmt.Errorf("node has no tunnel ip annotation") + return nil, errors.New("node has no tunnel ip annotation") } for _, ip := range strings.Split(nodeTunlIP, ",") { @@ -1474,7 +1474,7 @@ func (c *Controller) podNeedSync(pod *v1.Pod) (bool, error) { } ipName := ovs.PodNameToPortName(pod.Name, pod.Namespace, n.ProviderName) if _, err = c.ipsLister.Get(ipName); err != nil { - err = fmt.Errorf("pod has no ip %s: %v", ipName, err) + err = fmt.Errorf("pod has no ip %s: %w", ipName, err) // need to sync to create ip klog.Error(err) return true, nil @@ -2246,7 +2246,7 @@ func setPodRoutesAnnotation(annotations map[string]string, provider string, rout buf, err := json.Marshal(routes) if err != nil { - err = fmt.Errorf("failed to marshal routes %+v: %v", routes, err) + err = fmt.Errorf("failed to marshal routes %+v: %w", routes, err) klog.Error(err) return err } diff --git a/pkg/controller/qos_policy.go b/pkg/controller/qos_policy.go index cfe640c7c01..7a2e31d7539 100644 --- a/pkg/controller/qos_policy.go +++ b/pkg/controller/qos_policy.go @@ -340,13 +340,13 @@ func (c *Controller) reconcileEIPBandtithLimitRules( } } if len(added) > 0 { - if err = c.addOrUpdateEIPBandtithLimitRules(eip, eip.Status.IP, added); err != nil { + if err = c.addOrUpdateEIPBandwidthLimitRules(eip, eip.Status.IP, added); err != nil { klog.Errorf("failed to add eip %s bandwidth limit rules, %v", eip.Name, err) return err } } if len(updated) > 0 { - if err = c.addOrUpdateEIPBandtithLimitRules(eip, eip.Status.IP, updated); err != nil { + if err = c.addOrUpdateEIPBandwidthLimitRules(eip, eip.Status.IP, updated); err != nil { klog.Errorf("failed to update eip %s bandwidth limit rules, %v", eip.Name, err) return err } diff --git a/pkg/controller/security_group.go b/pkg/controller/security_group.go index 9330368f206..5713bed27ee 100644 --- a/pkg/controller/security_group.go +++ b/pkg/controller/security_group.go @@ -2,6 +2,8 @@ package controller import ( "context" + "encoding/hex" + "errors" "fmt" "net" "reflect" @@ -192,7 +194,7 @@ func (c *Controller) syncSecurityGroup() error { for _, sg := range sgs { lost, err := c.OVNNbClient.SGLostACL(sg) if err != nil { - err = fmt.Errorf("failed to check if security group %s lost acl: %v", sg.Name, err) + err = fmt.Errorf("failed to check if security group %s lost acl: %w", sg.Name, err) klog.Error(err) return err } @@ -303,12 +305,12 @@ func (c *Controller) handleAddOrUpdateSg(key string, force bool) error { egressNeedUpdate = true } else { // check md5 - newIngressMd5 = fmt.Sprintf("%x", structhash.Md5(sg.Spec.IngressRules, 1)) + newIngressMd5 = hex.EncodeToString(structhash.Md5(sg.Spec.IngressRules, 1)) if !sg.Status.IngressLastSyncSuccess || newIngressMd5 != sg.Status.IngressMd5 { klog.Infof("ingress need update, sg:%s", sg.Name) ingressNeedUpdate = true } - newEgressMd5 = fmt.Sprintf("%x", structhash.Md5(sg.Spec.EgressRules, 1)) + newEgressMd5 = hex.EncodeToString(structhash.Md5(sg.Spec.EgressRules, 1)) if !sg.Status.EgressLastSyncSuccess || newEgressMd5 != sg.Status.EgressMd5 { klog.Infof("egress need update, sg:%s", sg.Name) egressNeedUpdate = true @@ -370,7 +372,7 @@ func (c *Controller) validateSgRule(sg *kubeovnv1.SecurityGroup) error { allRules := append(sg.Spec.IngressRules, sg.Spec.EgressRules...) for _, rule := range allRules { if rule.IPVersion != "ipv4" && rule.IPVersion != "ipv6" { - return fmt.Errorf("IPVersion should be 'ipv4' or 'ipv6'") + return errors.New("IPVersion should be 'ipv4' or 'ipv6'") } if rule.Priority < 1 || rule.Priority > 200 { @@ -391,7 +393,7 @@ func (c *Controller) validateSgRule(sg *kubeovnv1.SecurityGroup) error { case kubeovnv1.SgRemoteTypeSg: _, err := c.sgsLister.Get(rule.RemoteSecurityGroup) if err != nil { - return fmt.Errorf("failed to get remote sg '%s', %v", rule.RemoteSecurityGroup, err) + return fmt.Errorf("failed to get remote sg '%s', %w", rule.RemoteSecurityGroup, err) } default: return fmt.Errorf("not support sgRemoteType '%s'", rule.RemoteType) @@ -399,10 +401,10 @@ func (c *Controller) validateSgRule(sg *kubeovnv1.SecurityGroup) error { if rule.Protocol == kubeovnv1.ProtocolTCP || rule.Protocol == kubeovnv1.ProtocolUDP { if rule.PortRangeMin < 1 || rule.PortRangeMin > 65535 || rule.PortRangeMax < 1 || rule.PortRangeMax > 65535 { - return fmt.Errorf("portRange is out of range") + return errors.New("portRange is out of range") } if rule.PortRangeMin > rule.PortRangeMax { - return fmt.Errorf("portRange err, range Minimum value greater than maximum value") + return errors.New("portRange err, range Minimum value greater than maximum value") } } } diff --git a/pkg/controller/service.go b/pkg/controller/service.go index 180eac4e772..262f7e881a4 100644 --- a/pkg/controller/service.go +++ b/pkg/controller/service.go @@ -60,7 +60,6 @@ func (c *Controller) enqueueDeleteService(obj interface{}) { vip, ok := svc.Annotations[util.SwitchLBRuleVipsAnnotation] if ok || svc.Spec.ClusterIP != v1.ClusterIPNone && svc.Spec.ClusterIP != "" { - if c.config.EnableNP { var netpols []string var err error @@ -234,7 +233,7 @@ func (c *Controller) handleDeleteService(service *vpcService) error { key, err := cache.MetaNamespaceKeyFunc(service.Svc) if err != nil { klog.Error(err) - utilruntime.HandleError(fmt.Errorf("failed to get meta namespace key of %#v: %v", service.Svc, err)) + utilruntime.HandleError(fmt.Errorf("failed to get meta namespace key of %#v: %w", service.Svc, err)) return nil } diff --git a/pkg/controller/service_lb.go b/pkg/controller/service_lb.go index 9b3a276118d..cd3bc756bb5 100644 --- a/pkg/controller/service_lb.go +++ b/pkg/controller/service_lb.go @@ -57,7 +57,7 @@ func parseAttachNetworkProvider(svc *corev1.Service) (string, string) { func (c *Controller) checkAttachNetwork(svc *corev1.Service) error { attachmentName, attachmentNs := parseAttachNetworkProvider(svc) if attachmentName == "" && attachmentNs == "" { - return fmt.Errorf("the provider name should be consisted of name and namespace") + return errors.New("the provider name should be consisted of name and namespace") } _, err := c.config.AttachNetClient.K8sCniCncfIoV1().NetworkAttachmentDefinitions(attachmentNs).Get(context.Background(), attachmentName, metav1.GetOptions{}) @@ -197,7 +197,7 @@ func (c *Controller) getLbSvcPod(svcName, svcNamespace string) (*corev1.Pod, err return nil, fmt.Errorf("pod of deployment %s/%s not found", svcNamespace, genLbSvcDpName(svcName)) case len(pods) != 1: time.Sleep(2 * time.Second) - return nil, fmt.Errorf("too many pods") + return nil, errors.New("too many pods") case pods[0].Status.Phase != corev1.PodRunning: time.Sleep(2 * time.Second) return nil, fmt.Errorf("pod %s/%s is not running", pods[0].Namespace, pods[0].Name) @@ -240,7 +240,7 @@ func (c *Controller) getPodAttachIP(pod *corev1.Pod, svc *corev1.Service) (strin if pod.Annotations[attachIPAnnotation] != "" { loadBalancerIP = pod.Annotations[attachIPAnnotation] } else { - err = fmt.Errorf("failed to get attachment ip from pod's annotation") + err = errors.New("failed to get attachment ip from pod's annotation") } return loadBalancerIP, err diff --git a/pkg/controller/subnet.go b/pkg/controller/subnet.go index 035fb6f3836..e68c9dbb06c 100644 --- a/pkg/controller/subnet.go +++ b/pkg/controller/subnet.go @@ -3,11 +3,13 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "net" "reflect" "slices" "sort" + "strconv" "strings" "time" @@ -87,7 +89,6 @@ func (c *Controller) enqueueUpdateSubnet(oldObj, newObj interface{}) { if oldSubnet.Spec.Vpc != newSubnet.Spec.Vpc && !(oldSubnet.Spec.Vpc == "" && newSubnet.Spec.Vpc == c.config.ClusterRouter || oldSubnet.Spec.Vpc == c.config.ClusterRouter && newSubnet.Spec.Vpc == "") { - if newSubnet.Annotations == nil { newSubnet.Annotations = make(map[string]string) } @@ -130,7 +131,6 @@ func (c *Controller) enqueueUpdateSubnet(oldObj, newObj interface{}) { oldSubnet.Spec.EnableMulticastSnoop != newSubnet.Spec.EnableMulticastSnoop || !reflect.DeepEqual(oldSubnet.Spec.NatOutgoingPolicyRules, newSubnet.Spec.NatOutgoingPolicyRules) || (newSubnet.Spec.U2OInterconnection && newSubnet.Spec.U2OInterconnectionIP != "" && oldSubnet.Spec.U2OInterconnectionIP != newSubnet.Spec.U2OInterconnectionIP) { - klog.V(3).Infof("enqueue update subnet %s", key) if oldSubnet.Spec.GatewayType != newSubnet.Spec.GatewayType { @@ -317,7 +317,7 @@ func (c *Controller) formatSubnet(subnet *kubeovnv1.Subnet) (*kubeovnv1.Subnet, if subnet.Spec.Vlan != "" { if _, err := c.vlansLister.Get(subnet.Spec.Vlan); err != nil { - err = fmt.Errorf("failed to get vlan %s: %s", subnet.Spec.Vlan, err) + err = fmt.Errorf("failed to get vlan %s: %w", subnet.Spec.Vlan, err) klog.Error(err) return nil, err } @@ -359,7 +359,7 @@ func (c *Controller) updateNatOutgoingPolicyRulesStatus(subnet *kubeovnv1.Subnet klog.Error(err) return err } - priority := fmt.Sprintf("%d", index) + priority := strconv.Itoa(index) // hash code generate by subnetName, rule and priority var retBytes []byte retBytes = append(retBytes, []byte(subnet.Name)...) @@ -1369,7 +1369,7 @@ func (c *Controller) reconcileCustomVpcBfdStaticRoute(vpcName, subnetName string lrpEipName = fmt.Sprintf("%s-%s", vpcName, c.config.ExternalGatewaySwitch) lrpEip, err := c.ovnEipsLister.Get(lrpEipName) if err != nil { - err := fmt.Errorf("failed to get lrp eip %s, %v", lrpEipName, err) + err := fmt.Errorf("failed to get lrp eip %s, %w", lrpEipName, err) klog.Error(err) return err } @@ -1792,7 +1792,6 @@ func (c *Controller) reconcileOvnDefaultVpcRoute(subnet *kubeovnv1.Subnet) error return err } } - } else { // It's difficult to update policy route when subnet cidr is changed, add check for cidr changed situation if err := c.reconcilePolicyRouteForCidrChangedSubnet(subnet, true); err != nil { @@ -1827,7 +1826,7 @@ func (c *Controller) reconcileOvnDefaultVpcRoute(subnet *kubeovnv1.Subnet) error gwNodeExists := c.checkGwNodeExists(subnet.Spec.GatewayNode) if !gwNodeExists { klog.Errorf("failed to init centralized gateway for subnet %s, no gateway node exists", subnet.Name) - return fmt.Errorf("failed to add ecmp policy route, no gateway node exists") + return errors.New("failed to add ecmp policy route, no gateway node exists") } if err := c.reconcilePolicyRouteForCidrChangedSubnet(subnet, false); err != nil { diff --git a/pkg/controller/switch_lb_rule.go b/pkg/controller/switch_lb_rule.go index 61fc3af6934..d9d9ded8b70 100644 --- a/pkg/controller/switch_lb_rule.go +++ b/pkg/controller/switch_lb_rule.go @@ -131,7 +131,7 @@ func (c *Controller) processSwitchLBRuleWorkItem(processName string, queue workq queue.Forget(obj) return nil }(obj); err != nil { - utilruntime.HandleError(fmt.Errorf("process: %s. err: %v", processName, err)) + utilruntime.HandleError(fmt.Errorf("process: %s. err: %w", processName, err)) queue.AddRateLimited(obj) return true } @@ -203,13 +203,13 @@ func (c *Controller) handleAddOrUpdateSwitchLBRule(key string) error { eps = generateEndpoints(slr, oldEps) if needToCreateEps { if _, err = c.config.KubeClient.CoreV1().Endpoints(slr.Spec.Namespace).Create(context.Background(), eps, metav1.CreateOptions{}); err != nil { - err = fmt.Errorf("failed to create endpoints '%s', err: %v", eps, err) + err = fmt.Errorf("failed to create endpoints '%s', err: %w", eps, err) klog.Error(err) return err } } else { if _, err = c.config.KubeClient.CoreV1().Endpoints(slr.Spec.Namespace).Update(context.Background(), eps, metav1.UpdateOptions{}); err != nil { - err = fmt.Errorf("failed to update endpoints '%s', err: %v", eps, err) + err = fmt.Errorf("failed to update endpoints '%s', err: %w", eps, err) klog.Error(err) return err } @@ -221,13 +221,13 @@ func (c *Controller) handleAddOrUpdateSwitchLBRule(key string) error { svc = generateHeadlessService(slr, oldSvc) if needToCreateSvc { if _, err = c.config.KubeClient.CoreV1().Services(slr.Spec.Namespace).Create(context.Background(), svc, metav1.CreateOptions{}); err != nil { - err = fmt.Errorf("failed to create service '%s', err: %v", svc, err) + err = fmt.Errorf("failed to create service '%s', err: %w", svc, err) klog.Error(err) return err } } else { if _, err = c.config.KubeClient.CoreV1().Services(slr.Spec.Namespace).Update(context.Background(), svc, metav1.UpdateOptions{}); err != nil { - err = fmt.Errorf("failed to update service '%s', err: %v", svc, err) + err = fmt.Errorf("failed to update service '%s', err: %w", svc, err) klog.Error(err) return err } @@ -249,7 +249,7 @@ func (c *Controller) handleAddOrUpdateSwitchLBRule(key string) error { newSlr.Status.Ports = strings.TrimPrefix(formatPorts, ",") if _, err = c.config.KubeOvnClient.KubeovnV1().SwitchLBRules().UpdateStatus(context.Background(), newSlr, metav1.UpdateOptions{}); err != nil { - err = fmt.Errorf("failed to update switch lb rule status, %v", err) + err = fmt.Errorf("failed to update switch lb rule status, %w", err) klog.Error(err) return err } diff --git a/pkg/controller/vip.go b/pkg/controller/vip.go index ca4cbe94a12..1e3a9fb7b56 100644 --- a/pkg/controller/vip.go +++ b/pkg/controller/vip.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "reflect" "slices" @@ -261,19 +262,19 @@ 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 { - err = fmt.Errorf("failed to create lsp %s: %v", portName, err) + err = fmt.Errorf("failed to create lsp %s: %w", portName, err) klog.Error(err) return err } if err := c.OVNNbClient.SetLogicalSwitchPortArpProxy(portName, true); err != nil { - err = fmt.Errorf("failed to enable lsp arp proxy for vip %s: %v", portName, err) + err = fmt.Errorf("failed to enable lsp arp proxy for vip %s: %w", portName, err) klog.Error(err) return err } } if vip.Spec.ParentMac != "" { if vip.Spec.Type == util.SwitchLBRuleVip { - err = fmt.Errorf("invalid usage of vip") + err = errors.New("invalid usage of vip") klog.Error(err) return err } @@ -314,17 +315,17 @@ func (c *Controller) handleUpdateVirtualIP(key string) error { } // not support change if vip.Status.Mac != "" && vip.Status.Mac != vip.Spec.MacAddress { - err = fmt.Errorf("not support change mac of vip") + err = errors.New("not support change mac of vip") klog.Errorf("%v", err) return err } if vip.Status.V4ip != "" && vip.Status.V4ip != vip.Spec.V4ip { - err = fmt.Errorf("not support change v4 ip of vip") + err = errors.New("not support change v4 ip of vip") klog.Errorf("%v", err) return err } if vip.Status.V6ip != "" && vip.Status.V6ip != vip.Spec.V6ip { - err = fmt.Errorf("not support change v6 ip of vip") + err = errors.New("not support change v6 ip of vip") klog.Errorf("%v", err) return err } @@ -362,7 +363,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 { - err = fmt.Errorf("failed to delete lsp %s: %v", vip.Name, err) + err = fmt.Errorf("failed to delete lsp %s: %w", vip.Name, err) klog.Error(err) return err } @@ -478,12 +479,12 @@ func (c *Controller) createOrUpdateVipCR(key, ns, subnet, v4ip, v6ip, mac, pV4ip ParentMac: pmac, }, }, metav1.CreateOptions{}); err != nil { - err := fmt.Errorf("failed to create crd vip '%s', %v", key, err) + err := fmt.Errorf("failed to create crd vip '%s', %w", key, err) klog.Error(err) return err } } else { - err := fmt.Errorf("failed to get crd vip '%s', %v", key, err) + err := fmt.Errorf("failed to get crd vip '%s', %w", key, err) klog.Error(err) return err } @@ -508,7 +509,7 @@ func (c *Controller) createOrUpdateVipCR(key, ns, subnet, v4ip, v6ip, mac, pV4ip vip.Status.Pmac = pmac vip.Status.Type = vip.Spec.Type if _, err := c.config.KubeOvnClient.KubeovnV1().Vips().Update(context.Background(), vip, metav1.UpdateOptions{}); err != nil { - err := fmt.Errorf("failed to update vip '%s', %v", key, err) + err := fmt.Errorf("failed to update vip '%s', %w", key, err) klog.Error(err) return err } diff --git a/pkg/controller/vpc.go b/pkg/controller/vpc.go index 30416fd85a1..493a45d1a21 100644 --- a/pkg/controller/vpc.go +++ b/pkg/controller/vpc.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "net" "reflect" @@ -386,7 +387,7 @@ func (c *Controller) handleAddOrUpdateVpc(key string) error { nextHop = externalSubnet.Spec.Gateway if nextHop == "" { klog.Errorf("no available gateway address") - return fmt.Errorf("no available gateway address") + return errors.New("no available gateway address") } } if strings.Contains(nextHop, "/") { @@ -1137,7 +1138,7 @@ func (c *Controller) handleAddVpcExternalSubnet(key, subnet string) error { } if len(chassises) == 0 { - err := fmt.Errorf("no external gw nodes") + err := errors.New("no external gw nodes") klog.Error(err) return err } @@ -1173,13 +1174,13 @@ func (c *Controller) handleAddVpcExternalSubnet(key, subnet string) error { } if _, err = c.config.KubeOvnClient.KubeovnV1().Vpcs().Patch(context.Background(), vpc.Name, types.MergePatchType, bytes, metav1.PatchOptions{}, "status"); err != nil { - err := fmt.Errorf("failed to patch vpc %s status, %v", vpc.Name, err) + err := fmt.Errorf("failed to patch vpc %s status, %w", vpc.Name, err) klog.Error(err) return err } } if _, err = c.ovnEipsLister.Get(lrpEipName); err != nil { - err := fmt.Errorf("failed to get ovn eip %s, %v", lrpEipName, err) + err := fmt.Errorf("failed to get ovn eip %s, %w", lrpEipName, err) klog.Error(err) return err } diff --git a/pkg/controller/vpc_dns.go b/pkg/controller/vpc_dns.go index 2541326f89c..0925a6755b9 100644 --- a/pkg/controller/vpc_dns.go +++ b/pkg/controller/vpc_dns.go @@ -142,7 +142,7 @@ func (c *Controller) handleAddOrUpdateVPCDNS(key string) error { if !enableCoredns { time.Sleep(10 * time.Second) if !enableCoredns { - return fmt.Errorf("failed to add or update vpc-dns, not enabled") + return errors.New("failed to add or update vpc-dns, not enabled") } } @@ -163,55 +163,55 @@ func (c *Controller) handleAddOrUpdateVPCDNS(key string) error { if _, err = c.config.KubeOvnClient.KubeovnV1().VpcDnses().UpdateStatus(context.Background(), newVPCDNS, metav1.UpdateOptions{}); err != nil { - err := fmt.Errorf("failed to update vpc dns status, %v", err) + err := fmt.Errorf("failed to update vpc dns status, %w", err) klog.Error(err) } }() if len(corednsImage) == 0 { - err := fmt.Errorf("vpc-dns coredns image should be set") + err := errors.New("vpc-dns coredns image should be set") klog.Error(err) return err } if len(corednsVip) == 0 { - err := fmt.Errorf("vpc-dns corednsVip should be set") + err := errors.New("vpc-dns corednsVip should be set") klog.Error(err) 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) + err := fmt.Errorf("failed to get vpc '%s', err: %w", 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) + err := fmt.Errorf("failed to get subnet '%s', err: %w", vpcDNS.Spec.Subnet, err) klog.Error(err) return err } if err := c.checkOvnNad(); err != nil { - err := fmt.Errorf("failed to check nad, %v", err) + err := fmt.Errorf("failed to check nad, %w", err) klog.Error(err) return err } if err := c.checkVpcDNSDuplicated(vpcDNS); err != nil { - err = fmt.Errorf("failed to deploy %s, %v", vpcDNS.Name, err) + err = fmt.Errorf("failed to deploy %s, %w", 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) + err = fmt.Errorf("failed to create or update vpc dns %s, %w", 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) + err = fmt.Errorf("failed to create or update slr for vpc dns %s, %w", vpcDNS.Name, err) klog.Error(err) return err } @@ -224,14 +224,14 @@ func (c *Controller) handleDelVpcDNS(key string) error { 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) + err := fmt.Errorf("failed to delete vpc dns deployment: %w", err) klog.Error(err) return err } err = c.config.KubeOvnClient.KubeovnV1().SwitchLBRules().Delete(context.Background(), name, metav1.DeleteOptions{}) if err != nil && !k8serrors.IsNotFound(err) { - err := fmt.Errorf("failed to delete switch lb rule: %v", err) + err := fmt.Errorf("failed to delete switch lb rule: %w", err) klog.Error(err) return err } @@ -251,7 +251,7 @@ func (c *Controller) checkVpcDNSDuplicated(vpcDNS *kubeovnv1.VpcDns) error { if item.Status.Active && item.Name != vpcDNS.Name && item.Spec.Vpc == vpcDNS.Spec.Vpc { - err = fmt.Errorf("only one vpc-dns can be deployed in a vpc") + err = errors.New("only one vpc-dns can be deployed in a vpc") return err } } @@ -582,7 +582,7 @@ func (c *Controller) getDefaultCoreDNSImage() (string, error) { } } - return "", fmt.Errorf("coredns container no found") + return "", errors.New("coredns container no found") } func (c *Controller) initVpcDNSConfig() error { diff --git a/pkg/controller/vpc_nat.go b/pkg/controller/vpc_nat.go index 1213524cc66..57b0eee160d 100644 --- a/pkg/controller/vpc_nat.go +++ b/pkg/controller/vpc_nat.go @@ -13,7 +13,7 @@ var vpcNatImage = "" func (c *Controller) resyncVpcNatImage() { cm, err := c.configMapsLister.ConfigMaps(c.config.PodNamespace).Get(util.VpcNatConfig) if err != nil { - err = fmt.Errorf("failed to get ovn-vpc-nat-config, %v", err) + err = fmt.Errorf("failed to get ovn-vpc-nat-config, %w", err) klog.Error(err) return } diff --git a/pkg/controller/vpc_nat_gateway.go b/pkg/controller/vpc_nat_gateway.go index d24118da2b7..fb13f8f3f61 100644 --- a/pkg/controller/vpc_nat_gateway.go +++ b/pkg/controller/vpc_nat_gateway.go @@ -189,7 +189,7 @@ func (c *Controller) processNextWorkItem(processName string, queue workqueue.Rat return nil }(obj) if err != nil { - utilruntime.HandleError(fmt.Errorf("process: %s. err: %v", processName, err)) + utilruntime.HandleError(fmt.Errorf("process: %s. err: %w", processName, err)) queue.AddRateLimited(obj) return true } @@ -249,16 +249,16 @@ func (c *Controller) handleAddOrUpdateVpcNatGw(key string) error { klog.Infof("handle add/update vpc nat gateway %s", key) if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } if _, err := c.vpcsLister.Get(gw.Spec.Vpc); err != nil { - err = fmt.Errorf("failed to get vpc '%s', err: %v", gw.Spec.Vpc, err) + err = fmt.Errorf("failed to get vpc '%s', err: %w", gw.Spec.Vpc, err) klog.Error(err) return err } if _, err := c.subnetsLister.Get(gw.Spec.Subnet); err != nil { - err = fmt.Errorf("failed to get subnet '%s', err: %v", gw.Spec.Subnet, err) + err = fmt.Errorf("failed to get subnet '%s', err: %w", gw.Spec.Subnet, err) klog.Error(err) return err } @@ -289,7 +289,7 @@ func (c *Controller) handleAddOrUpdateVpcNatGw(key string) error { // 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 { - err := fmt.Errorf("failed to create statefulset '%s', err: %v", newSts.Name, err) + err := fmt.Errorf("failed to create statefulset '%s', err: %w", newSts.Name, err) klog.Error(err) return err } @@ -301,7 +301,7 @@ func (c *Controller) handleAddOrUpdateVpcNatGw(key string) error { 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) + err := fmt.Errorf("failed to update statefulset '%s', err: %w", newSts.Name, err) klog.Error(err) return err } @@ -325,7 +325,7 @@ func (c *Controller) handleAddOrUpdateVpcNatGw(key string) error { } } if err := c.updateCrdNatGwLabels(key, gw.Spec.QoSPolicy); err != nil { - err := fmt.Errorf("failed to update nat gw %s: %v", gw.Name, err) + err := fmt.Errorf("failed to update nat gw %s: %w", gw.Name, err) klog.Error(err) return err } @@ -351,7 +351,7 @@ func (c *Controller) handleInitVpcNatGw(key string) error { } if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(key) @@ -362,7 +362,7 @@ func (c *Controller) handleInitVpcNatGw(key string) error { oriPod, err := c.getNatGwPod(key) if err != nil { - err := fmt.Errorf("failed to get nat gw %s pod: %v", gw.Name, err) + err := fmt.Errorf("failed to get nat gw %s pod: %w", gw.Name, err) klog.Error(err) return err } @@ -381,7 +381,7 @@ func (c *Controller) handleInitVpcNatGw(key string) error { 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, nil); err != nil { - err = fmt.Errorf("failed to init vpc nat gateway, %v", err) + err = fmt.Errorf("failed to init vpc nat gateway, %w", err) klog.Error(err) return err } @@ -401,7 +401,7 @@ func (c *Controller) handleInitVpcNatGw(key string) error { } if err := c.updateCrdNatGwLabels(gw.Name, gw.Spec.QoSPolicy); err != nil { - err := fmt.Errorf("failed to update nat gw %s: %v", gw.Name, err) + err := fmt.Errorf("failed to update nat gw %s: %w", gw.Name, err) klog.Error(err) return err } @@ -419,7 +419,7 @@ func (c *Controller) handleInitVpcNatGw(key string) error { } if _, err := c.config.KubeClient.CoreV1().Pods(pod.Namespace).Patch(context.Background(), pod.Name, types.StrategicMergePatchType, patch, metav1.PatchOptions{}, ""); err != nil { - err := fmt.Errorf("patch pod %s/%s failed %v", pod.Name, pod.Namespace, err) + err := fmt.Errorf("patch pod %s/%s failed %w", pod.Name, pod.Namespace, err) klog.Error(err) return err } @@ -428,7 +428,7 @@ func (c *Controller) handleInitVpcNatGw(key string) error { func (c *Controller) handleUpdateVpcFloatingIP(natGwKey string) error { if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(natGwKey) @@ -437,14 +437,14 @@ func (c *Controller) handleUpdateVpcFloatingIP(natGwKey string) error { // refresh exist fips if err := c.initCreateAt(natGwKey); err != nil { - err = fmt.Errorf("failed to init nat gw pod '%s' create at, %v", natGwKey, err) + err = fmt.Errorf("failed to init nat gw pod '%s' create at, %w", natGwKey, err) klog.Error(err) return err } fips, err := c.iptablesFipsLister.List(labels.SelectorFromSet(labels.Set{util.VpcNatGatewayNameLabel: natGwKey})) if err != nil { - err := fmt.Errorf("failed to get all fips, %v", err) + err := fmt.Errorf("failed to get all fips, %w", err) klog.Error(err) return err } @@ -463,7 +463,7 @@ func (c *Controller) handleUpdateVpcFloatingIP(natGwKey string) error { func (c *Controller) handleUpdateVpcEip(natGwKey string) error { if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(natGwKey) @@ -472,13 +472,13 @@ func (c *Controller) handleUpdateVpcEip(natGwKey string) error { // refresh exist fips if err := c.initCreateAt(natGwKey); err != nil { - err = fmt.Errorf("failed to init nat gw pod '%s' create at, %v", natGwKey, err) + err = fmt.Errorf("failed to init nat gw pod '%s' create at, %w", natGwKey, err) klog.Error(err) return err } eips, err := c.iptablesEipsLister.List(labels.Everything()) if err != nil { - err = fmt.Errorf("failed to get eip list, %v", err) + err = fmt.Errorf("failed to get eip list, %w", err) klog.Error(err) return err } @@ -496,7 +496,7 @@ func (c *Controller) handleUpdateVpcEip(natGwKey string) error { func (c *Controller) handleUpdateVpcSnat(natGwKey string) error { if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(natGwKey) @@ -505,13 +505,13 @@ func (c *Controller) handleUpdateVpcSnat(natGwKey string) error { // refresh exist snats if err := c.initCreateAt(natGwKey); err != nil { - err = fmt.Errorf("failed to init nat gw pod '%s' create at, %v", natGwKey, err) + err = fmt.Errorf("failed to init nat gw pod '%s' create at, %w", natGwKey, err) klog.Error(err) return err } snats, err := c.iptablesSnatRulesLister.List(labels.SelectorFromSet(labels.Set{util.VpcNatGatewayNameLabel: natGwKey})) if err != nil { - err = fmt.Errorf("failed to get all snats, %v", err) + err = fmt.Errorf("failed to get all snats, %w", err) klog.Error(err) return err } @@ -519,7 +519,7 @@ func (c *Controller) handleUpdateVpcSnat(natGwKey string) error { if snat.Status.Redo != natGwCreatedAT { klog.V(3).Infof("redo snat %s", snat.Name) 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) + err = fmt.Errorf("failed to update eip '%s' to re-apply, %w", snat.Spec.EIP, err) klog.Error(err) return err } @@ -530,7 +530,7 @@ func (c *Controller) handleUpdateVpcSnat(natGwKey string) error { func (c *Controller) handleUpdateVpcDnat(natGwKey string) error { if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(natGwKey) @@ -539,14 +539,14 @@ func (c *Controller) handleUpdateVpcDnat(natGwKey string) error { // refresh exist dnats if err := c.initCreateAt(natGwKey); err != nil { - err = fmt.Errorf("failed to init nat gw pod '%s' create at, %v", natGwKey, err) + err = fmt.Errorf("failed to init nat gw pod '%s' create at, %w", natGwKey, err) klog.Error(err) return err } dnats, err := c.iptablesDnatRulesLister.List(labels.SelectorFromSet(labels.Set{util.VpcNatGatewayNameLabel: natGwKey})) if err != nil { - err = fmt.Errorf("failed to get all dnats, %v", err) + err = fmt.Errorf("failed to get all dnats, %w", err) klog.Error(err) return err } @@ -554,7 +554,7 @@ func (c *Controller) handleUpdateVpcDnat(natGwKey string) error { if dnat.Status.Redo != natGwCreatedAT { klog.V(3).Infof("redo dnat %s", dnat.Name) if err = c.redoDnat(dnat.Name, natGwCreatedAT, false); err != nil { - err := fmt.Errorf("failed to update dnat '%s' to redo, %v", dnat.Name, err) + err := fmt.Errorf("failed to update dnat '%s' to redo, %w", dnat.Name, err) klog.Error(err) return err } @@ -607,7 +607,7 @@ func (c *Controller) handleUpdateNatGwSubnetRoute(natGwKey string) error { } if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(natGwKey) @@ -616,7 +616,7 @@ func (c *Controller) handleUpdateNatGwSubnetRoute(natGwKey string) error { cachedPod, err := c.getNatGwPod(natGwKey) if err != nil { - err = fmt.Errorf("failed to get nat gw '%s' pod, %v", natGwKey, err) + err = fmt.Errorf("failed to get nat gw '%s' pod, %w", natGwKey, err) klog.Error(err) return err } @@ -624,13 +624,13 @@ func (c *Controller) handleUpdateNatGwSubnetRoute(natGwKey string) error { v4InternalGw, _, err := c.GetGwBySubnet(gw.Spec.Subnet) if err != nil { - err = fmt.Errorf("failed to get gw, err: %v", err) + err = fmt.Errorf("failed to get gw, err: %w", err) klog.Error(err) return err } vpc, err := c.vpcsLister.Get(gw.Spec.Vpc) if err != nil { - err = fmt.Errorf("failed to get vpc, err: %v", err) + err = fmt.Errorf("failed to get vpc, err: %w", err) klog.Error(err) return err } @@ -641,7 +641,7 @@ func (c *Controller) handleUpdateNatGwSubnetRoute(natGwKey string) error { for _, s := range vpc.Status.Subnets { subnet, err := c.subnetsLister.Get(s) if err != nil { - err = fmt.Errorf("failed to get subnet, err: %v", err) + err = fmt.Errorf("failed to get subnet, err: %w", err) klog.Error(err) return err } @@ -671,7 +671,7 @@ func (c *Controller) handleUpdateNatGwSubnetRoute(natGwKey string) error { } if len(rules) > 0 { if err = c.execNatGwRules(pod, natGwSubnetRouteAdd, rules); err != nil { - err = fmt.Errorf("failed to exec nat gateway rule, err: %v", err) + err = fmt.Errorf("failed to exec nat gateway rule, err: %w", err) klog.Error(err) return err } @@ -681,7 +681,7 @@ func (c *Controller) handleUpdateNatGwSubnetRoute(natGwKey string) error { if len(toBeDelCIDRs) > 0 { for _, cidr := range toBeDelCIDRs { if err = c.execNatGwRules(pod, natGwSubnetRouteDel, []string{cidr}); err != nil { - err = fmt.Errorf("failed to exec nat gateway rule, err: %v", err) + err = fmt.Errorf("failed to exec nat gateway rule, err: %w", err) klog.Error(err) return err } @@ -701,7 +701,7 @@ func (c *Controller) handleUpdateNatGwSubnetRoute(natGwKey string) error { } if _, err := c.config.KubeClient.CoreV1().Pods(pod.Namespace).Patch(context.Background(), pod.Name, types.StrategicMergePatchType, patch, metav1.PatchOptions{}, ""); err != nil { - err = fmt.Errorf("patch pod %s/%s failed %v", pod.Name, pod.Namespace, err) + err = fmt.Errorf("patch pod %s/%s failed %w", pod.Name, pod.Namespace, err) klog.Error(err) return err } @@ -889,10 +889,10 @@ func (c *Controller) getNatGwPod(name string) (*corev1.Pod, error) { return nil, k8serrors.NewNotFound(v1.Resource("pod"), name) case len(pods) != 1: time.Sleep(5 * time.Second) - return nil, fmt.Errorf("too many pod") + return nil, errors.New("too many pod") case pods[0].Status.Phase != corev1.PodRunning: time.Sleep(5 * time.Second) - return nil, fmt.Errorf("pod is not active now") + return nil, errors.New("pod is not active now") } return pods[0], nil @@ -914,7 +914,7 @@ func (c *Controller) initCreateAt(key string) (err 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) + errMsg := fmt.Errorf("failed to get vpc nat gw '%s', %w", key, err) klog.Error(errMsg) return errMsg } @@ -1109,7 +1109,7 @@ func (c *Controller) execNatGwQoSInPod( addRules = append(addRules, rule) if err = c.execNatGwRules(gwPod, operation, addRules); err != nil { - err = fmt.Errorf("failed to exec nat gateway rule, err: %v", err) + err = fmt.Errorf("failed to exec nat gateway rule, err: %w", err) klog.Error(err) return err } @@ -1120,7 +1120,7 @@ func (c *Controller) initVpcNatGw() error { klog.Infof("init all vpc nat gateways") gws, err := c.vpcNatGatewayLister.List(labels.Everything()) if err != nil { - err = fmt.Errorf("failed to get vpc nat gw list, %v", err) + err = fmt.Errorf("failed to get vpc nat gw list, %w", err) klog.Error(err) return err } @@ -1129,7 +1129,7 @@ func (c *Controller) initVpcNatGw() error { } if vpcNatEnabled != "true" { - err := fmt.Errorf("iptables nat gw not enable") + err := errors.New("iptables nat gw not enable") klog.Warning(err) return nil } @@ -1138,7 +1138,7 @@ func (c *Controller) initVpcNatGw() error { pod, err := c.getNatGwPod(gw.Name) if err != nil { // the nat gw maybe deleted - err := fmt.Errorf("failed to get nat gw %s pod: %v", gw.Name, err) + err := fmt.Errorf("failed to get nat gw %s pod: %w", gw.Name, err) klog.Error(err) continue } diff --git a/pkg/controller/vpc_nat_gw_eip.go b/pkg/controller/vpc_nat_gw_eip.go index 9e406239f43..ef0661d7d96 100644 --- a/pkg/controller/vpc_nat_gw_eip.go +++ b/pkg/controller/vpc_nat_gw_eip.go @@ -2,6 +2,7 @@ package controller import ( "context" + "errors" "fmt" "net" "strings" @@ -211,7 +212,7 @@ func (c *Controller) handleAddIptablesEip(key string) error { } if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(key) @@ -258,7 +259,7 @@ func (c *Controller) handleAddIptablesEip(key string) error { } addrV4, err := util.GetIPAddrWithMask(v4ip, eipV4Cidr) if err != nil { - err = fmt.Errorf("failed to get eip %s with mask by cidr %s: %v", v4ip, eipV4Cidr, err) + err = fmt.Errorf("failed to get eip %s with mask by cidr %s: %w", v4ip, eipV4Cidr, err) klog.Error(err) return err } @@ -364,7 +365,7 @@ func (c *Controller) handleUpdateIptablesEip(key string) error { } // make sure vpc nat enabled if vpcNatEnabled != "true" { - err := fmt.Errorf("iptables nat gw not enable") + err := errors.New("iptables nat gw not enable") klog.Error(err) return err } @@ -414,7 +415,7 @@ func (c *Controller) handleUpdateIptablesEip(key string) error { } addrV4, err := util.GetIPAddrWithMask(cachedEip.Status.IP, v4Cidr) if err != nil { - err = fmt.Errorf("failed to get eip %s with mask by cidr %s: %v", cachedEip.Status.IP, v4Cidr, err) + err = fmt.Errorf("failed to get eip %s with mask by cidr %s: %w", cachedEip.Status.IP, v4Cidr, err) klog.Error(err) return err } @@ -488,7 +489,7 @@ func (c *Controller) deleteEipInPod(dp, v4Cidr string) error { return nil } -func (c *Controller) addOrUpdateEIPBandtithLimitRules(eip *kubeovnv1.IptablesEIP, v4ip string, rules kubeovnv1.QoSPolicyBandwidthLimitRules) error { +func (c *Controller) addOrUpdateEIPBandwidthLimitRules(eip *kubeovnv1.IptablesEIP, v4ip string, rules kubeovnv1.QoSPolicyBandwidthLimitRules) error { var err error for _, rule := range rules { if err = c.addEipQoSInPod(eip.Spec.NatGwDp, v4ip, rule.Direction, rule.Priority, rule.RateMax, rule.BurstMax); err != nil { @@ -525,7 +526,7 @@ func (c *Controller) addEipQoS(eip *kubeovnv1.IptablesEIP, v4ip string) error { } } } - return c.addOrUpdateEIPBandtithLimitRules(eip, v4ip, qosPolicy.Status.BandwidthLimitRules) + return c.addOrUpdateEIPBandwidthLimitRules(eip, v4ip, qosPolicy.Status.BandwidthLimitRules) } func (c *Controller) delEIPBandtithLimitRules(eip *kubeovnv1.IptablesEIP, v4ip string, rules kubeovnv1.QoSPolicyBandwidthLimitRules) error { @@ -656,7 +657,7 @@ func (c *Controller) eipChangeIP(eip *kubeovnv1.IptablesEIP) bool { func (c *Controller) GetGwBySubnet(name string) (string, string, error) { subnet, err := c.subnetsLister.Get(name) if err != nil { - err = fmt.Errorf("faile to get subnet %q: %v", name, err) + err = fmt.Errorf("faile to get subnet %q: %w", name, err) klog.Error(err) return "", "", err } @@ -695,7 +696,7 @@ func (c *Controller) createOrUpdateEipCR(key, v4ip, v6ip, mac, natGwDp, qos, ext }, }, metav1.CreateOptions{}) if err != nil { - errMsg := fmt.Errorf("failed to create eip crd %s, %v", key, err) + errMsg := fmt.Errorf("failed to create eip crd %s, %w", key, err) klog.Error(errMsg) return errMsg } @@ -708,7 +709,7 @@ func (c *Controller) createOrUpdateEipCR(key, v4ip, v6ip, mac, natGwDp, qos, ext eip.Spec.NatGwDp = natGwDp eip.Spec.MacAddress = mac if _, err := c.config.KubeOvnClient.KubeovnV1().IptablesEIPs().Update(context.Background(), eip, metav1.UpdateOptions{}); err != nil { - errMsg := fmt.Errorf("failed to update eip crd %s, %v", key, err) + errMsg := fmt.Errorf("failed to update eip crd %s, %w", key, err) klog.Error(errMsg) return errMsg } @@ -934,7 +935,7 @@ func (c *Controller) patchEipStatus(key, v4ip, redo, qos string, ready bool) err nat, err := c.getIptablesEipNat(oriEip.Spec.V4ip) if err != nil { - err := fmt.Errorf("failed to get eip nat") + err := errors.New("failed to get eip nat") klog.Error(err) return err } diff --git a/pkg/controller/vpc_nat_gw_nat.go b/pkg/controller/vpc_nat_gw_nat.go index 5d3d468c901..7adb1e1b894 100644 --- a/pkg/controller/vpc_nat_gw_nat.go +++ b/pkg/controller/vpc_nat_gw_nat.go @@ -3,6 +3,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "time" @@ -488,7 +489,7 @@ func (c *Controller) handleAddIptablesFip(key string) error { } if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(key) @@ -503,7 +504,7 @@ func (c *Controller) handleAddIptablesFip(key string) error { // get eip eipName := fip.Spec.EIP if eipName == "" { - return fmt.Errorf("failed to create fip rule, should set eip") + return errors.New("failed to create fip rule, should set eip") } eip, err := c.GetEip(eipName) if err != nil { @@ -512,7 +513,7 @@ func (c *Controller) handleAddIptablesFip(key string) error { } if err = c.fipTryUseEip(key, eip.Spec.V4ip); err != nil { - err = fmt.Errorf("failed to create fip %s, %v", key, err) + err = fmt.Errorf("failed to create fip %s, %w", key, err) klog.Error(err) return err } @@ -595,11 +596,11 @@ func (c *Controller) handleUpdateIptablesFip(key string) error { klog.V(3).Infof("handle update fip %s", key) // add or update should make sure vpc nat enabled if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } eipName := cachedFip.Spec.EIP if eipName == "" { - return fmt.Errorf("failed to update fip rule, should set eip") + return errors.New("failed to update fip rule, should set eip") } eip, err := c.GetEip(eipName) if err != nil { @@ -608,7 +609,7 @@ func (c *Controller) handleUpdateIptablesFip(key string) error { } if err = c.fipTryUseEip(key, eip.Spec.V4ip); err != nil { - err = fmt.Errorf("failed to update fip %s, %v", key, err) + err = fmt.Errorf("failed to update fip %s, %w", key, err) klog.Error(err) return err } @@ -690,7 +691,7 @@ func (c *Controller) handleAddIptablesDnatRule(key string) error { } if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(key) @@ -704,7 +705,7 @@ func (c *Controller) handleAddIptablesDnatRule(key string) error { klog.V(3).Infof("handle add iptables dnat %s", key) eipName := dnat.Spec.EIP if eipName == "" { - return fmt.Errorf("failed to create dnat rule, should set eip") + return errors.New("failed to create dnat rule, should set eip") } eip, err := c.GetEip(eipName) @@ -780,7 +781,7 @@ func (c *Controller) handleUpdateIptablesDnatRule(key string) error { klog.V(3).Infof("handle update dnat %s", key) eipName := cachedDnat.Spec.EIP if eipName == "" { - return fmt.Errorf("failed to update fip rule, should set eip") + return errors.New("failed to update fip rule, should set eip") } eip, err := c.GetEip(eipName) if err != nil { @@ -793,7 +794,7 @@ func (c *Controller) handleUpdateIptablesDnatRule(key string) error { } // add or update should make sure vpc nat enabled if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } if err = c.deleteDnatInPod(cachedDnat.Status.NatGwDp, cachedDnat.Status.Protocol, @@ -878,7 +879,7 @@ func (c *Controller) handleAddIptablesSnatRule(key string) error { } if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } c.vpcNatGwKeyMutex.LockKey(key) @@ -892,7 +893,7 @@ func (c *Controller) handleAddIptablesSnatRule(key string) error { klog.V(3).Infof("handle add iptables snat %s", key) eipName := snat.Spec.EIP if eipName == "" { - return fmt.Errorf("failed to create snat rule, should set eip") + return errors.New("failed to create snat rule, should set eip") } eip, err := c.GetEip(eipName) @@ -975,7 +976,7 @@ func (c *Controller) handleUpdateIptablesSnatRule(key string) error { klog.V(3).Infof("handle update snat %s", key) eipName := cachedSnat.Spec.EIP if eipName == "" { - return fmt.Errorf("failed to update fip rule, should set eip") + return errors.New("failed to update fip rule, should set eip") } eip, err := c.GetEip(eipName) if err != nil { @@ -985,7 +986,7 @@ func (c *Controller) handleUpdateIptablesSnatRule(key string) error { // add or update should make sure vpc nat enabled if vpcNatEnabled != "true" { - return fmt.Errorf("iptables nat gw not enable") + return errors.New("iptables nat gw not enable") } klog.V(3).Infof("snat change ip, old ip %s, new ip %s", cachedSnat.Status.V4ip, eip.Status.IP) @@ -1381,18 +1382,18 @@ func (c *Controller) redoFip(key, redo string, eipReady bool) error { if redo != "" && redo != fip.Status.Redo { if !eipReady { if err = c.patchEipLabel(fip.Spec.EIP); err != nil { - err = fmt.Errorf("failed to patch eip %s, %v", fip.Spec.EIP, err) + err = fmt.Errorf("failed to patch eip %s, %w", fip.Spec.EIP, err) klog.Error(err) return err } if err = c.patchEipStatus(fip.Spec.EIP, "", redo, "", false); err != nil { - err = fmt.Errorf("failed to patch eip %s, %v", fip.Spec.EIP, err) + err = fmt.Errorf("failed to patch eip %s, %w", fip.Spec.EIP, err) klog.Error(err) return err } } if err = c.patchFipStatus(key, "", "", "", redo, false); err != nil { - err = fmt.Errorf("failed to patch fip %s, %v", fip.Name, err) + err = fmt.Errorf("failed to patch fip %s, %w", fip.Name, err) klog.Error(err) return err } @@ -1527,13 +1528,13 @@ func (c *Controller) redoDnat(key, redo string, eipReady bool) error { if redo != "" && redo != dnat.Status.Redo { if !eipReady { if err = c.patchEipStatus(dnat.Spec.EIP, "", redo, "", false); err != nil { - err = fmt.Errorf("failed to patch eip %s, %v", dnat.Spec.EIP, err) + err = fmt.Errorf("failed to patch eip %s, %w", dnat.Spec.EIP, err) klog.Error(err) return err } } if err = c.patchDnatStatus(key, "", "", "", redo, false); err != nil { - err = fmt.Errorf("failed to patch dnat %s, %v", key, err) + err = fmt.Errorf("failed to patch dnat %s, %w", key, err) klog.Error(err) return err } @@ -1660,13 +1661,13 @@ func (c *Controller) redoSnat(key, redo string, eipReady bool) error { if redo != "" && redo != snat.Status.Redo { if !eipReady { if err = c.patchEipStatus(snat.Spec.EIP, "", redo, "", false); err != nil { - err = fmt.Errorf("failed to patch eip %s, %v", snat.Spec.EIP, err) + err = fmt.Errorf("failed to patch eip %s, %w", snat.Spec.EIP, err) klog.Error(err) return err } } if err = c.patchSnatStatus(key, "", "", "", redo, false); err != nil { - err = fmt.Errorf("failed to patch snat %s, %v", key, err) + err = fmt.Errorf("failed to patch snat %s, %w", key, err) klog.Error(err) return err } diff --git a/pkg/daemon/config.go b/pkg/daemon/config.go index 738743ca8c1..276ce85a2c3 100644 --- a/pkg/daemon/config.go +++ b/pkg/daemon/config.go @@ -175,7 +175,7 @@ func (config *Configuration) Init(nicBridgeMappings map[string]string) error { klog.Info("node name not specified in environment variables, fall back to the hostname") hostname, err := os.Hostname() if err != nil { - return fmt.Errorf("failed to get hostname: %v", err) + return fmt.Errorf("failed to get hostname: %w", err) } config.NodeName = strings.ToLower(hostname) } @@ -233,11 +233,11 @@ func (config *Configuration) initNicConfig(nicBridgeMappings map[string]string) } srcIPs, err := getSrcIPsByRoutes(iface) if err != nil { - return fmt.Errorf("failed to get src IPs by routes on interface %s: %v", iface.Name, err) + return fmt.Errorf("failed to get src IPs by routes on interface %s: %w", iface.Name, err) } addrs, err := iface.Addrs() if err != nil { - return fmt.Errorf("failed to get iface addr. %v", err) + return fmt.Errorf("failed to get iface addr. %w", err) } for _, addr := range addrs { _, ipCidr, err := net.ParseCIDR(addr.String()) diff --git a/pkg/daemon/config_linux.go b/pkg/daemon/config_linux.go index eeadc6cdb19..e53fe42f9a9 100644 --- a/pkg/daemon/config_linux.go +++ b/pkg/daemon/config_linux.go @@ -13,11 +13,11 @@ const defaultBindSocket = "/run/openvswitch/kube-ovn-daemon.sock" func getSrcIPsByRoutes(iface *net.Interface) ([]string, error) { link, err := netlink.LinkByName(iface.Name) if err != nil { - return nil, fmt.Errorf("failed to get link %s: %v", iface.Name, err) + return nil, fmt.Errorf("failed to get link %s: %w", iface.Name, err) } routes, err := netlink.RouteList(link, netlink.FAMILY_ALL) if err != nil { - return nil, fmt.Errorf("failed to get routes on link %s: %v", iface.Name, err) + return nil, fmt.Errorf("failed to get routes on link %s: %w", iface.Name, err) } srcIPs := make([]string, 0, 2) @@ -38,7 +38,7 @@ func getIfaceByIP(ip string) (string, int, error) { for _, link := range links { addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL) if err != nil { - return "", 0, fmt.Errorf("failed to get addresses of link %s: %v", link.Attrs().Name, err) + return "", 0, fmt.Errorf("failed to get addresses of link %s: %w", link.Attrs().Name, err) } for _, addr := range addrs { if addr.IPNet.Contains(net.ParseIP(ip)) && addr.IP.String() == ip { diff --git a/pkg/daemon/controller.go b/pkg/daemon/controller.go index c178c4e4067..a3c18db22cc 100644 --- a/pkg/daemon/controller.go +++ b/pkg/daemon/controller.go @@ -244,7 +244,7 @@ func (c *Controller) processNextDeleteProviderNetworkWorkItem() bool { return nil } if err := c.handleDeleteProviderNetwork(pn); err != nil { - return fmt.Errorf("error syncing '%s': %v, requeuing", pn.Name, err) + return fmt.Errorf("error syncing '%s': %w, requeuing", pn.Name, err) } c.deleteProviderNetworkQueue.Forget(obj) return nil @@ -590,7 +590,7 @@ func (c *Controller) markAndCleanInternalPort() error { // Remove ovs port output, err := ovs.Exec(ovs.IfExists, "--with-iface", "del-port", "br-int", portName) if err != nil { - return fmt.Errorf("failed to delete ovs port %v, %q", err, output) + return fmt.Errorf("failed to delete ovs port %w, %q", err, output) } } } diff --git a/pkg/daemon/controller_linux.go b/pkg/daemon/controller_linux.go index 7eb9ec7ca2d..938047c0d7b 100644 --- a/pkg/daemon/controller_linux.go +++ b/pkg/daemon/controller_linux.go @@ -45,11 +45,11 @@ type ControllerRuntime struct { func evalCommandSymlinks(cmd string) (string, error) { path, err := exec.LookPath(cmd) if err != nil { - return "", fmt.Errorf("failed to search for command %q: %v", cmd, err) + return "", fmt.Errorf("failed to search for command %q: %w", cmd, err) } file, err := filepath.EvalSymlinks(path) if err != nil { - return "", fmt.Errorf("failed to read evaluate symbolic links for file %q: %v", path, err) + return "", fmt.Errorf("failed to read evaluate symbolic links for file %q: %w", path, err) } return file, nil @@ -232,7 +232,7 @@ func (c *Controller) reconcileRouters(event *subnetEvent) error { gateway, ok := node.Annotations[util.GatewayAnnotation] if !ok { klog.Errorf("annotation for node %s ovn.kubernetes.io/gateway not exists", node.Name) - return fmt.Errorf("annotation for node ovn.kubernetes.io/gateway not exists") + return errors.New("annotation for node ovn.kubernetes.io/gateway not exists") } nic, err := netlink.LinkByName(util.NodeNic) if err != nil { diff --git a/pkg/daemon/gateway.go b/pkg/daemon/gateway.go index d13a15bee8d..5c3af620a49 100644 --- a/pkg/daemon/gateway.go +++ b/pkg/daemon/gateway.go @@ -64,20 +64,20 @@ func (c *Controller) setICGateway() error { if enable == "true" { icEnabled, err := ovs.Exec(ovs.IfExists, "get", "open", ".", "external_ids:ovn-is-interconn") if err != nil { - return fmt.Errorf("failed to get if ic enabled, %v", err) + return fmt.Errorf("failed to get if ic enabled, %w", err) } if strings.Trim(icEnabled, "\"") != "true" { if _, err := ovs.Exec("set", "open", ".", "external_ids:ovn-is-interconn=true"); err != nil { - return fmt.Errorf("failed to enable ic gateway, %v", err) + return fmt.Errorf("failed to enable ic gateway, %w", err) } output, err := exec.Command("/usr/share/ovn/scripts/ovn-ctl", "restart_controller").CombinedOutput() if err != nil { - return fmt.Errorf("failed to restart ovn-controller, %v, %q", err, output) + return fmt.Errorf("failed to restart ovn-controller, %w, %q", err, output) } } } else { if _, err := ovs.Exec("set", "open", ".", "external_ids:ovn-is-interconn=false"); err != nil { - return fmt.Errorf("failed to disable ic gateway, %v", err) + return fmt.Errorf("failed to disable ic gateway, %w", err) } } return nil @@ -271,8 +271,7 @@ func (c *Controller) getTProxyConditionPod(needSort bool) ([]*v1.Pod, error) { subnet, err := c.subnetsLister.Get(subnetName) if err != nil { - err = fmt.Errorf("failed to get subnet '%s', err: %v", subnetName, err) - return nil, err + return nil, fmt.Errorf("failed to get subnet '%s', err: %w", subnetName, err) } if subnet.Spec.Vpc == c.config.ClusterRouter { diff --git a/pkg/daemon/gateway_linux.go b/pkg/daemon/gateway_linux.go index a9427ade669..e8ae2adbf21 100644 --- a/pkg/daemon/gateway_linux.go +++ b/pkg/daemon/gateway_linux.go @@ -329,7 +329,7 @@ func (c *Controller) addPolicyRouting(family int, gateway string, priority, tabl Table: int(tableID), } if err := netlink.RouteReplace(route); err != nil && !errors.Is(err, syscall.EEXIST) { - err = fmt.Errorf("failed to replace route in table %d: %+v", tableID, err) + err = fmt.Errorf("failed to replace route in table %d: %w", tableID, err) klog.Error(err) return err } @@ -350,7 +350,7 @@ func (c *Controller) addPolicyRouting(family int, gateway string, priority, tabl var err error if rule.Src, err = netlink.ParseIPNet(ip); err != nil { klog.Errorf("unexpected CIDR: %s", ip) - err = fmt.Errorf("failed to add route in table %d: %+v", tableID, err) + err = fmt.Errorf("failed to add route in table %d: %w", tableID, err) klog.Error(err) return err } @@ -359,7 +359,7 @@ func (c *Controller) addPolicyRouting(family int, gateway string, priority, tabl } if err := netlink.RuleAdd(rule); err != nil && !errors.Is(err, syscall.EEXIST) { - err = fmt.Errorf("failed to add network rule: %+v", err) + err = fmt.Errorf("failed to add network rule: %w", err) klog.Error(err) return err } @@ -385,7 +385,7 @@ func (c *Controller) deletePolicyRouting(family int, _ string, priority, tableID var err error if rule.Src, err = netlink.ParseIPNet(ip); err != nil { klog.Errorf("unexpected CIDR: %s", ip) - err = fmt.Errorf("failed to delete route in table %d: %+v", tableID, err) + err = fmt.Errorf("failed to delete route in table %d: %w", tableID, err) klog.Error(err) return err } @@ -394,7 +394,7 @@ func (c *Controller) deletePolicyRouting(family int, _ string, priority, tableID } if err := netlink.RuleDel(rule); err != nil && !errors.Is(err, syscall.ENOENT) { - err = fmt.Errorf("failed to delete network rule: %+v", err) + err = fmt.Errorf("failed to delete network rule: %w", err) klog.Error(err) return err } @@ -1433,7 +1433,7 @@ func (c *Controller) setExGateway() error { linkName, exist := cm.Data["external-gw-nic"] if !exist || len(linkName) == 0 { - err = fmt.Errorf("external-gw-nic not configured in ovn-external-gw-config") + err = errors.New("external-gw-nic not configured in ovn-external-gw-config") klog.Error(err) return err } @@ -1454,7 +1454,7 @@ func (c *Controller) setExGateway() error { } else { klog.Infof("external bridge should change from %s to %s, delete external bridge %s", existBr, externalBridge, existBr) if _, err := ovs.Exec(ovs.IfExists, "del-br", existBr); err != nil { - err = fmt.Errorf("failed to del external br %s, %v", existBr, err) + err = fmt.Errorf("failed to del external br %s, %w", existBr, err) klog.Error(err) return err } @@ -1467,7 +1467,7 @@ func (c *Controller) setExGateway() error { ovs.MayExist, "add-br", externalBridge, "--", ovs.MayExist, "add-port", externalBridge, linkName, ); err != nil { - err = fmt.Errorf("failed to enable external gateway, %v", err) + err = fmt.Errorf("failed to enable external gateway, %w", err) klog.Error(err) } } @@ -1478,7 +1478,7 @@ func (c *Controller) setExGateway() error { } else { brExists, err := ovs.BridgeExists(externalBridge) if err != nil { - return fmt.Errorf("failed to check OVS bridge existence: %v", err) + return fmt.Errorf("failed to check OVS bridge existence: %w", err) } if !brExists { return nil @@ -1517,7 +1517,7 @@ func (c *Controller) setExGateway() error { klog.Infof("delete external bridge %s", externalBridge) if _, err := ovs.Exec( ovs.IfExists, "del-br", externalBridge); err != nil { - err = fmt.Errorf("failed to disable external gateway, %v", err) + err = fmt.Errorf("failed to disable external gateway, %w", err) klog.Error(err) return err } @@ -1667,7 +1667,7 @@ func (c *Controller) deleteObsoleteSnatRules(ipt *iptables.IPTables, table, chai func (c *Controller) ipsetExists(name string) (bool, error) { sets, err := c.k8sipsets.ListSets() if err != nil { - return false, fmt.Errorf("failed to list ipset names: %v", err) + return false, fmt.Errorf("failed to list ipset names: %w", err) } return slices.Contains(sets, name), nil diff --git a/pkg/daemon/handler.go b/pkg/daemon/handler.go index 1e3e399cc79..39333b95fd9 100644 --- a/pkg/daemon/handler.go +++ b/pkg/daemon/handler.go @@ -61,7 +61,7 @@ func (csh cniServerHandler) providerExists(provider string) (*kubeovnv1.Subnet, func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Response) { podRequest := request.CniRequest{} if err := req.ReadEntity(&podRequest); err != nil { - errMsg := fmt.Errorf("parse add request failed %v", err) + errMsg := fmt.Errorf("parse add request failed %w", err) klog.Error(errMsg) if err := resp.WriteHeaderAndEntity(http.StatusBadRequest, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response, %v", err) @@ -96,7 +96,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon var err error for i := 0; i < 20; i++ { if pod, err = csh.Controller.podsLister.Pods(podRequest.PodNamespace).Get(podRequest.PodName); err != nil { - errMsg := fmt.Errorf("get pod %s/%s failed %v", podRequest.PodNamespace, podRequest.PodName, err) + errMsg := fmt.Errorf("get pod %s/%s failed %w", podRequest.PodNamespace, podRequest.PodName, err) klog.Error(errMsg) if err := resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response, %v", err) @@ -132,7 +132,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon vmName = pod.Annotations[fmt.Sprintf(util.VMAnnotationTemplate, podRequest.Provider)] ipAddr, err = util.GetIPAddrWithMask(ip, cidr) if err != nil { - errMsg := fmt.Errorf("failed to get ip address with mask, %v", err) + errMsg := fmt.Errorf("failed to get ip address with mask, %w", err) klog.Error(errMsg) if err := resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response, %v", err) @@ -142,7 +142,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon oldPodName = podRequest.PodName 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) + errMsg := fmt.Errorf("invalid routes for pod %s/%s: %w", pod.Namespace, pod.Name, err) klog.Error(errMsg) if err = resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response: %v", err) @@ -231,7 +231,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon if strings.HasSuffix(podRequest.Provider, util.OvnProvider) && subnet != "" { podSubnet, err := csh.Controller.subnetsLister.Get(subnet) if err != nil { - errMsg := fmt.Errorf("failed to get subnet %s: %v", subnet, err) + errMsg := fmt.Errorf("failed to get subnet %s: %w", subnet, err) klog.Error(errMsg) if err = resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response: %v", err) @@ -280,7 +280,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon if providerNetwork != "" && !podSubnet.Spec.LogicalGateway && !podSubnet.Spec.U2OInterconnection { node, err := csh.Controller.nodesLister.Get(csh.Config.NodeName) if err != nil { - errMsg := fmt.Errorf("failed to get node %s: %v", csh.Config.NodeName, err) + errMsg := fmt.Errorf("failed to get node %s: %w", csh.Config.NodeName, err) klog.Error(errMsg) if err = resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response: %v", err) @@ -290,7 +290,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon mtuStr := node.Labels[fmt.Sprintf(util.ProviderNetworkMtuTemplate, providerNetwork)] if mtuStr != "" { if mtu, err = strconv.Atoi(mtuStr); err != nil || mtu <= 0 { - errMsg := fmt.Errorf("failed to parse provider network MTU %s: %v", mtuStr, err) + errMsg := fmt.Errorf("failed to parse provider network MTU %s: %w", mtuStr, err) klog.Error(errMsg) if err = resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response: %v", err) @@ -316,7 +316,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon routes, 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, oldPodName) } if err != nil { - errMsg := fmt.Errorf("configure nic %s for pod %s/%s failed: %v", ifName, podRequest.PodName, podRequest.PodNamespace, err) + errMsg := fmt.Errorf("configure nic %s for pod %s/%s failed: %w", ifName, podRequest.PodName, podRequest.PodNamespace, err) klog.Error(errMsg) if err := resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response, %v", err) @@ -331,7 +331,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon } if err = csh.Controller.addEgressConfig(podSubnet, ip); err != nil { - errMsg := fmt.Errorf("failed to add egress configuration: %v", err) + errMsg := fmt.Errorf("failed to add egress configuration: %w", err) klog.Error(errMsg) if err = resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response, %v", err) @@ -354,7 +354,7 @@ func (csh cniServerHandler) handleAdd(req *restful.Request, resp *restful.Respon if len(hasDefaultRoute) != 0 { // remove existing default route so other CNI plugins, such as macvlan, can add the new default route correctly if err = csh.removeDefaultRoute(podRequest.NetNs, hasDefaultRoute[kubeovnv1.ProtocolIPv4], hasDefaultRoute[kubeovnv1.ProtocolIPv6]); err != nil { - errMsg := fmt.Errorf("failed to remove existing default route for interface %s of pod %s/%s: %v", podRequest.IfName, podRequest.PodNamespace, podRequest.PodName, err) + errMsg := fmt.Errorf("failed to remove existing default route for interface %s of pod %s/%s: %w", podRequest.IfName, podRequest.PodNamespace, podRequest.PodName, err) klog.Error(errMsg) if err = resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response: %v", err) @@ -386,7 +386,7 @@ func (csh cniServerHandler) UpdateIPCR(podRequest request.CniRequest, subnet, ip for i := 0; i < 20; i++ { ipCR, 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) + err = fmt.Errorf("failed to get ip crd for %s, %w", ip, err) // maybe create a backup pod with previous annotations klog.Error(err) } else if ipCR.Spec.NodeName != csh.Config.NodeName { @@ -398,7 +398,7 @@ func (csh cniServerHandler) UpdateIPCR(podRequest request.CniRequest, subnet, ip 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) + err = fmt.Errorf("failed to update ip crd for %s, %w", ip, err) klog.Error(err) } else { return nil @@ -418,7 +418,7 @@ func (csh cniServerHandler) UpdateIPCR(podRequest request.CniRequest, subnet, ip func (csh cniServerHandler) handleDel(req *restful.Request, resp *restful.Response) { var podRequest request.CniRequest if err := req.ReadEntity(&podRequest); err != nil { - errMsg := fmt.Errorf("parse del request failed %v", err) + errMsg := fmt.Errorf("parse del request failed %w", err) klog.Error(errMsg) if err := resp.WriteHeaderAndEntity(http.StatusBadRequest, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response, %v", err) @@ -433,7 +433,7 @@ func (csh cniServerHandler) handleDel(req *restful.Request, resp *restful.Respon return } - errMsg := fmt.Errorf("parse del request failed %v", err) + errMsg := fmt.Errorf("parse del request failed %w", err) klog.Error(errMsg) if err := resp.WriteHeaderAndEntity(http.StatusBadRequest, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response, %v", err) @@ -461,7 +461,7 @@ func (csh cniServerHandler) handleDel(req *restful.Request, resp *restful.Respon if subnet != "" { 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) + errMsg := fmt.Errorf("failed to remove egress configuration: %w", err) klog.Error(errMsg) if err = resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response, %v", err) @@ -498,7 +498,7 @@ func (csh cniServerHandler) handleDel(req *restful.Request, resp *restful.Respon err = csh.deleteNic(podRequest.PodName, podRequest.PodNamespace, podRequest.ContainerID, podRequest.NetNs, podRequest.DeviceID, podRequest.IfName, nicType, podRequest.Provider) if err != nil { - errMsg := fmt.Errorf("del nic failed %v", err) + errMsg := fmt.Errorf("del nic failed %w", err) klog.Error(errMsg) if err := resp.WriteHeaderAndEntity(http.StatusInternalServerError, request.CniResponse{Err: errMsg.Error()}); err != nil { klog.Errorf("failed to write response, %v", err) diff --git a/pkg/daemon/handler_linux.go b/pkg/daemon/handler_linux.go index dc82c1aa41c..8d626a2f759 100644 --- a/pkg/daemon/handler_linux.go +++ b/pkg/daemon/handler_linux.go @@ -46,14 +46,14 @@ func createShortSharedDir(pod *v1.Pod, volumeName, socketConsumption, kubeletDir err = os.MkdirAll(newSharedDir, 0o777) // #nosec G301 if err != nil { klog.Error(err) - return fmt.Errorf("createSharedDir: Failed to create dir (%s): %v", newSharedDir, err) + return fmt.Errorf("createSharedDir: Failed to create dir (%s): %w", newSharedDir, err) } if strings.Contains(newSharedDir, util.DefaultHostVhostuserBaseDir) { klog.Infof("createSharedDir: Mount from %s to %s", originSharedDir, newSharedDir) err = unix.Mount(originSharedDir, newSharedDir, "", unix.MS_BIND, "") if err != nil { - return fmt.Errorf("createSharedDir: Failed to bind mount: %s", err) + return fmt.Errorf("createSharedDir: Failed to bind mount: %w", err) } } return nil @@ -76,11 +76,11 @@ func removeShortSharedDir(pod *v1.Pod, volumeName, socketConsumption string) (er return nil } - // keep mount util dpdk sock not used by kuebvirt + // keep mount util dpdk sock not used by kubevirt if socketConsumption == util.ConsumptionKubevirt { files, err := os.ReadDir(sharedDir) if err != nil { - return fmt.Errorf("read file from dpdk share dir error: %s", err) + return fmt.Errorf("read file from dpdk share dir error: %w", err) } if len(files) != 0 { return nil diff --git a/pkg/daemon/init.go b/pkg/daemon/init.go index bc43b657909..3d7095e2da8 100644 --- a/pkg/daemon/init.go +++ b/pkg/daemon/init.go @@ -31,14 +31,14 @@ func InitOVSBridges() (map[string]string, error) { output, err := ovs.Exec("list-ports", brName) if err != nil { - return nil, fmt.Errorf("failed to list ports of OVS bridge %s, %v: %q", brName, err, output) + return nil, fmt.Errorf("failed to list ports of OVS bridge %s, %w: %q", brName, err, output) } if output != "" { for _, port := range strings.Split(output, "\n") { ok, err := ovs.ValidatePortVendor(port) if err != nil { - return nil, fmt.Errorf("failed to check vendor of port %s: %v", port, err) + return nil, fmt.Errorf("failed to check vendor of port %s: %w", port, err) } if ok { mappings[port] = brName @@ -79,7 +79,7 @@ func InitNodeGateway(config *Configuration) error { } mac, err := net.ParseMAC(macAddr) if err != nil { - return fmt.Errorf("failed to parse mac %s %v", mac, err) + return fmt.Errorf("failed to parse mac %s %w", mac, err) } ipAddr, err = util.GetIPAddrWithMask(ip, cidr) @@ -113,14 +113,14 @@ func (c *Controller) ovsInitProviderNetwork(provider, nic string, trunks []strin klog.V(3).Infof("configure external bridge %s", brName) if err := c.configExternalBridge(provider, brName, nic, exchangeLinkName, macLearningFallback); err != nil { - errMsg := fmt.Errorf("failed to create and configure external bridge %s: %v", brName, err) + errMsg := fmt.Errorf("failed to create and configure external bridge %s: %w", brName, err) klog.Error(errMsg) return 0, errMsg } // init provider chassis mac if err := initProviderChassisMac(provider); err != nil { - errMsg := fmt.Errorf("failed to init chassis mac for provider %s, %v", provider, err) + errMsg := fmt.Errorf("failed to init chassis mac for provider %s, %w", provider, err) klog.Error(errMsg) return 0, errMsg } @@ -129,7 +129,7 @@ func (c *Controller) ovsInitProviderNetwork(provider, nic string, trunks []strin klog.Infof("config provider nic %s on bridge %s", nic, brName) mtu, err := c.configProviderNic(nic, brName, trunks) if err != nil { - errMsg := fmt.Errorf("failed to add nic %s to external bridge %s: %v", nic, brName, err) + errMsg := fmt.Errorf("failed to add nic %s to external bridge %s: %w", nic, brName, err) klog.Error(errMsg) return 0, errMsg } @@ -151,7 +151,7 @@ func (c *Controller) ovsCleanProviderNetwork(provider string) error { output, err := ovs.Exec("list-br") if err != nil { - return fmt.Errorf("failed to list OVS bridges: %v, %q", err, output) + return fmt.Errorf("failed to list OVS bridges: %w, %q", err, output) } if !slices.Contains(strings.Split(output, "\n"), brName) { @@ -161,7 +161,7 @@ func (c *Controller) ovsCleanProviderNetwork(provider string) error { // get host nic if output, err = ovs.Exec("list-ports", brName); err != nil { - return fmt.Errorf("failed to list ports of OVS bridge %s, %v: %q", brName, err, output) + return fmt.Errorf("failed to list ports of OVS bridge %s, %w: %q", brName, err, output) } // remove host nic from the external bridge @@ -169,14 +169,14 @@ func (c *Controller) ovsCleanProviderNetwork(provider string) error { for _, port := range strings.Split(output, "\n") { // patch port created by ovn-controller has an external ID ovn-localnet-port=localnet. if output, err = ovs.Exec("--data=bare", "--no-heading", "--columns=_uuid", "find", "port", "name="+port, `external-ids:ovn-localnet-port!=""`); err != nil { - return fmt.Errorf("failed to find ovs port %s, %v: %q", port, err, output) + return fmt.Errorf("failed to find ovs port %s, %w: %q", port, err, output) } if output != "" { continue } klog.V(3).Infof("removing ovs port %s from bridge %s", port, brName) if err = c.removeProviderNic(port, brName); err != nil { - errMsg := fmt.Errorf("failed to remove port %s from external bridge %s: %v", port, brName, err) + errMsg := fmt.Errorf("failed to remove port %s from external bridge %s: %w", port, brName, err) klog.Error(errMsg) return errMsg } @@ -187,7 +187,7 @@ func (c *Controller) ovsCleanProviderNetwork(provider string) error { // remove OVS bridge klog.Infof("delete external bridge %s", brName) if output, err = ovs.Exec(ovs.IfExists, "del-br", brName); err != nil { - return fmt.Errorf("failed to remove OVS bridge %s, %v: %q", brName, err, output) + return fmt.Errorf("failed to remove OVS bridge %s, %w: %q", brName, err, output) } klog.V(3).Infof("ovs bridge %s has been deleted", brName) diff --git a/pkg/daemon/ovs.go b/pkg/daemon/ovs.go index 06e6debc876..29b799f0dc8 100644 --- a/pkg/daemon/ovs.go +++ b/pkg/daemon/ovs.go @@ -1,6 +1,7 @@ package daemon import ( + "errors" "fmt" "strings" "time" @@ -17,7 +18,7 @@ const gatewayCheckMaxRetry = 200 func pingGateway(gw, src string, verbose bool, maxRetry int, done chan struct{}) (count int, err error) { pinger, err := goping.NewPinger(gw) if err != nil { - return 0, fmt.Errorf("failed to init pinger: %v", err) + return 0, fmt.Errorf("failed to init pinger: %w", err) } pinger.SetPrivileged(true) // CNITimeoutSec = 220, cannot exceed @@ -96,7 +97,7 @@ func configureGlobalMirror(portName string, mtu int) error { "add", "bridge", "br-int", "mirrors", "@m") if err != nil { klog.Errorf("failed to configure mirror nic %s, %q, %v", portName, raw, err) - return fmt.Errorf(raw) + return errors.New(raw) } } else { klog.Infof("nic %s exist, configure it", portName) @@ -107,7 +108,7 @@ func configureGlobalMirror(portName string, mtu int) error { "add", "bridge", "br-int", "mirrors", "@m") if err != nil { klog.Errorf("failed to configure mirror nic %s, %q, %v", portName, raw, err) - return fmt.Errorf(raw) + return errors.New(raw) } } @@ -131,7 +132,7 @@ func configureEmptyMirror(portName string, mtu int) error { "add", "bridge", "br-int", "mirrors", "@m") if err != nil { klog.Errorf("failed to configure mirror nic %s %q, %v", portName, raw, err) - return fmt.Errorf(raw) + return errors.New(raw) } } else { klog.Infof("nic %s exist, configure it", portName) @@ -142,7 +143,7 @@ func configureEmptyMirror(portName string, mtu int) error { "add", "bridge", "br-int", "mirrors", "@m") if err != nil { klog.Errorf("failed to configure mirror nic %s %q", portName, raw) - return fmt.Errorf(raw) + return errors.New(raw) } } return configureMirrorLink(portName, mtu) @@ -181,7 +182,7 @@ func encodeOvnMappings(mappings map[string]string) string { func getOvnMappings(name string) (map[string]string, error) { output, err := ovs.Exec(ovs.IfExists, "get", "open", ".", "external-ids:"+name) if err != nil { - return nil, fmt.Errorf("failed to get %s, %v: %q", name, err, output) + return nil, fmt.Errorf("failed to get %s, %w: %q", name, err, output) } return decodeOvnMappings(output), nil @@ -196,7 +197,7 @@ func setOvnMappings(name string, mappings map[string]string) error { output, err = ovs.Exec("set", "open", ".", fmt.Sprintf("external-ids:%s=%s", name, s)) } if err != nil { - return fmt.Errorf("failed to set %s, %v: %q", name, err, output) + return fmt.Errorf("failed to set %s, %w: %q", name, err, output) } return nil @@ -235,7 +236,7 @@ func removeOvnMapping(name, key string) error { func (c *Controller) configExternalBridge(provider, bridge, nic string, exchangeLinkName, macLearningFallback bool) error { brExists, err := ovs.BridgeExists(bridge) if err != nil { - return fmt.Errorf("failed to check OVS bridge existence: %v", err) + return fmt.Errorf("failed to check OVS bridge existence: %w", err) } cmd := []string{ ovs.MayExist, "add-br", bridge, @@ -249,21 +250,21 @@ func (c *Controller) configExternalBridge(provider, bridge, nic string, exchange } output, err := ovs.Exec(cmd...) if err != nil { - return fmt.Errorf("failed to create OVS bridge %s, %v: %q", bridge, err, output) + return fmt.Errorf("failed to create OVS bridge %s, %w: %q", bridge, err, output) } if output, err = ovs.Exec("list-ports", bridge); err != nil { - return fmt.Errorf("failed to list ports of OVS bridge %s, %v: %q", bridge, err, output) + return fmt.Errorf("failed to list ports of OVS bridge %s, %w: %q", bridge, err, output) } if output != "" { for _, port := range strings.Split(output, "\n") { if port != nic { ok, err := ovs.ValidatePortVendor(port) if err != nil { - return fmt.Errorf("failed to check vendor of port %s: %v", port, err) + return fmt.Errorf("failed to check vendor of port %s: %w", port, err) } if ok { if err = c.removeProviderNic(port, bridge); err != nil { - return fmt.Errorf("failed to remove port %s from OVS bridge %s: %v", port, bridge, err) + return fmt.Errorf("failed to remove port %s from OVS bridge %s: %w", port, bridge, err) } } } diff --git a/pkg/daemon/ovs_linux.go b/pkg/daemon/ovs_linux.go index d94b1e14218..96550013322 100644 --- a/pkg/daemon/ovs_linux.go +++ b/pkg/daemon/ovs_linux.go @@ -61,7 +61,7 @@ func (csh cniServerHandler) configureDpdkNic(podName, podNamespace, provider, ne fmt.Sprintf("external_ids:ip=%s", ipStr), fmt.Sprintf("external_ids:pod_netns=%s", netns)) if err != nil { - return fmt.Errorf("add nic to ovs failed %v: %q", err, output) + return fmt.Errorf("add nic to ovs failed %w: %q", err, output) } return ovs.SetInterfaceBandwidth(podName, podNamespace, ifaceID, egress, ingress) } @@ -83,7 +83,6 @@ func (csh cniServerHandler) configureNic(podName, podNamespace, provider, netns, } } }() - } else { hostNicName, containerNicName, err = setupSriovInterface(containerID, deviceID, vfDriver, ifName, mtu, mac) if err != nil { @@ -104,7 +103,7 @@ func (csh cniServerHandler) configureNic(podName, podNamespace, provider, netns, fmt.Sprintf("external_ids:ip=%s", ipStr), fmt.Sprintf("external_ids:pod_netns=%s", netns)) if err != nil { - return nil, fmt.Errorf("add nic to ovs failed %v: %q", err, output) + return nil, fmt.Errorf("add nic to ovs failed %w: %q", err, output) } defer func() { if err != nil { @@ -148,7 +147,7 @@ func (csh cniServerHandler) configureNic(podName, podNamespace, provider, netns, // lsp and container nic must use same mac address, otherwise ovn will reject these packets by default macAddr, err := net.ParseMAC(mac) if err != nil { - return nil, fmt.Errorf("failed to parse mac %s %v", macAddr, err) + return nil, fmt.Errorf("failed to parse mac %s %w", macAddr, err) } if err = configureHostNic(hostNicName); err != nil { klog.Error(err) @@ -182,7 +181,7 @@ func (csh cniServerHandler) configureNic(podName, podNamespace, provider, netns, podNS, err := ns.GetNS(netns) if err != nil { - err = fmt.Errorf("failed to open netns %q: %v", netns, err) + err = fmt.Errorf("failed to open netns %q: %w", netns, err) klog.Error(err) return nil, err } @@ -203,13 +202,13 @@ func (csh cniServerHandler) releaseVf(podName, podNamespace, podNetns, ifName, n klog.Infof("Tear down interface %s", podDesc) netns, err := ns.GetNS(podNetns) if err != nil { - return fmt.Errorf("failed to get container namespace %s: %v", podDesc, err) + return fmt.Errorf("failed to get container namespace %s: %w", podDesc, err) } defer netns.Close() hostNS, err := ns.GetCurrentNS() if err != nil { - return fmt.Errorf("failed to get host namespace %s: %v", podDesc, err) + return fmt.Errorf("failed to get host namespace %s: %w", podDesc, err) } defer hostNS.Close() @@ -217,10 +216,10 @@ func (csh cniServerHandler) releaseVf(podName, podNamespace, podNetns, ifName, n // container side interface deletion link, err := netlink.LinkByName(ifName) if err != nil { - return fmt.Errorf("failed to get container interface %s %s: %v", ifName, podDesc, err) + return fmt.Errorf("failed to get container interface %s %s: %w", ifName, podDesc, err) } if err = netlink.LinkSetDown(link); err != nil { - return fmt.Errorf("failed to bring down container interface %s %s: %v", ifName, podDesc, err) + return fmt.Errorf("failed to bring down container interface %s %s: %w", ifName, podDesc, err) } // rename VF device back to its original name in the host namespace: pod, err := csh.Controller.podsLister.Pods(podNamespace).Get(podName) @@ -230,12 +229,12 @@ func (csh cniServerHandler) releaseVf(podName, podNamespace, podNetns, ifName, n } vfName := pod.Annotations[fmt.Sprintf(util.VfNameTemplate, provider)] if err = netlink.LinkSetName(link, vfName); err != nil { - return fmt.Errorf("failed to rename container interface %s to %s %s: %v", + return fmt.Errorf("failed to rename container interface %s to %s %s: %w", ifName, vfName, podDesc, err) } // move VF device to host netns if err = netlink.LinkSetNsFd(link, int(hostNS.Fd())); err != nil { - return fmt.Errorf("failed to move container interface %s back to host namespace %s: %v", + return fmt.Errorf("failed to move container interface %s back to host namespace %s: %w", ifName, podDesc, err) } return nil @@ -250,7 +249,7 @@ func (csh cniServerHandler) releaseVf(podName, podNamespace, podNetns, ifName, n func (csh cniServerHandler) deleteNic(podName, podNamespace, containerID, netns, deviceID, ifName, nicType, provider string) error { if err := csh.releaseVf(podName, podNamespace, netns, ifName, nicType, provider, deviceID); err != nil { return fmt.Errorf("failed to release VF %s assigned to the Pod %s/%s back to the host network namespace: "+ - "%v", ifName, podName, podNamespace, err) + "%w", ifName, podName, podNamespace, err) } var nicName string @@ -265,7 +264,7 @@ func (csh cniServerHandler) deleteNic(podName, podNamespace, containerID, netns, // Remove ovs port output, err := ovs.Exec(ovs.IfExists, "--with-iface", "del-port", "br-int", nicName) if err != nil { - return fmt.Errorf("failed to delete ovs port %v, %q", err, output) + return fmt.Errorf("failed to delete ovs port %w, %q", err, output) } if err = ovs.ClearPodBandwidth(podName, podNamespace, ""); err != nil { @@ -285,14 +284,14 @@ func (csh cniServerHandler) deleteNic(podName, podNamespace, containerID, netns, if _, ok := err.(netlink.LinkNotFoundError); ok { return nil } - return fmt.Errorf("find host link %s failed %v", nicName, err) + return fmt.Errorf("find host link %s failed %w", nicName, err) } hostLinkType := hostLink.Type() // Sometimes no deviceID input for vf nic, avoid delete vf nic. if hostLinkType == "veth" { if err = netlink.LinkDel(hostLink); err != nil { - return fmt.Errorf("delete host link %s failed %v", hostLink, err) + return fmt.Errorf("delete host link %s failed %w", hostLink, err) } } } else if pciAddrRegexp.MatchString(deviceID) { @@ -340,16 +339,16 @@ func generateNicName(containerID, ifname string) (string, string) { func configureHostNic(nicName string) error { hostLink, err := netlink.LinkByName(nicName) if err != nil { - return fmt.Errorf("can not find host nic %s: %v", nicName, err) + return fmt.Errorf("can not find host nic %s: %w", nicName, err) } if hostLink.Attrs().OperState != netlink.OperUp { if err = netlink.LinkSetUp(hostLink); err != nil { - return fmt.Errorf("can not set host nic %s up: %v", nicName, err) + return fmt.Errorf("can not set host nic %s up: %w", nicName, err) } } if err = netlink.LinkSetTxQLen(hostLink, 1000); err != nil { - return fmt.Errorf("can not set host nic %s qlen: %v", nicName, err) + return fmt.Errorf("can not set host nic %s qlen: %w", nicName, err) } return nil @@ -358,7 +357,7 @@ func configureHostNic(nicName string) error { func (csh cniServerHandler) configureContainerNic(podName, podNamespace, 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) ([]request.Route, error) { containerLink, err := netlink.LinkByName(nicName) if err != nil { - return nil, fmt.Errorf("can not find container nic %s: %v", nicName, err) + return nil, fmt.Errorf("can not find container nic %s: %w", nicName, err) } // Set link alias to its origin link name for fastpath to recognize and bypass netfilter @@ -368,7 +367,7 @@ func (csh cniServerHandler) configureContainerNic(podName, podNamespace, nicName } if err = netlink.LinkSetNsFd(containerLink, int(netns.Fd())); err != nil { - return nil, fmt.Errorf("failed to move link to netns: %v", err) + return nil, fmt.Errorf("failed to move link to netns: %w", err) } var finalRoutes []request.Route @@ -413,7 +412,7 @@ func (csh cniServerHandler) configureContainerNic(podName, podNamespace, nicName Scope: netlink.SCOPE_UNIVERSE, Gw: net.ParseIP(gw), }); err != nil { - return fmt.Errorf("failed to configure default gateway %s: %v", gw, err) + return fmt.Errorf("failed to configure default gateway %s: %w", gw, err) } } } @@ -447,7 +446,7 @@ func (csh cniServerHandler) configureContainerNic(podName, podNamespace, nicName linkRoutes, err := netlink.RouteList(containerLink, netlink.FAMILY_ALL) if err != nil { - return fmt.Errorf("failed to get routes on interface %s: %v", ifName, err) + return fmt.Errorf("failed to get routes on interface %s: %w", ifName, err) } for _, r := range linkRoutes { @@ -548,7 +547,7 @@ func waitNetworkReady(nic, ipAddr, gateway string, underlayGateway, verbose bool mac, count, err := util.ArpResolve(nic, gw, time.Second, maxRetry, done) cniConnectivityResult.WithLabelValues(nodeName).Add(float64(count)) if err != nil { - err = fmt.Errorf("network %s with gateway %s is not ready for interface %s after %d checks: %v", ips[i], gw, nic, count, err) + err = fmt.Errorf("network %s with gateway %s is not ready for interface %s after %d checks: %w", ips[i], gw, nic, count, err) klog.Warning(err) return err } @@ -575,14 +574,14 @@ func configureNodeNic(portName, ip, gw, joinCIDR string, macAddr net.HardwareAdd fmt.Sprintf("external_ids:ip=%s", ipStr)) if err != nil { klog.Errorf("failed to configure node nic %s: %v, %q", portName, err, raw) - return fmt.Errorf(raw) + return errors.New(raw) } value, err := sysctl.Sysctl(fmt.Sprintf("net.ipv6.conf.%s.addr_gen_mode", util.NodeNic)) if err == nil { if value != "0" { if _, err = sysctl.Sysctl(fmt.Sprintf("net.ipv6.conf.%s.addr_gen_mode", util.NodeNic), "0"); err != nil { - return fmt.Errorf("failed to set ovn0 addr_gen_mode: %v", err) + return fmt.Errorf("failed to set ovn0 addr_gen_mode: %w", err) } } } @@ -594,11 +593,11 @@ func configureNodeNic(portName, ip, gw, joinCIDR string, macAddr net.HardwareAdd hostLink, err := netlink.LinkByName(util.NodeNic) if err != nil { - return fmt.Errorf("can not find nic %s: %v", util.NodeNic, err) + return fmt.Errorf("can not find nic %s: %w", util.NodeNic, err) } if err = netlink.LinkSetTxQLen(hostLink, 1000); err != nil { - return fmt.Errorf("can not set host nic %s qlen: %v", util.NodeNic, err) + return fmt.Errorf("can not set host nic %s qlen: %w", util.NodeNic, err) } // check and add default route for ovn0 in case of can not add automatically @@ -709,7 +708,7 @@ func (c *Controller) checkNodeGwNicInNs(nodeExtIP, ip, gw string, gwNS ns.NetNS) if err == nil { cmd := exec.Command("sh", "-c", "bfdd-control status") if err := cmd.Run(); err != nil { - err := fmt.Errorf("failed to get bfdd status, %v", err) + err := fmt.Errorf("failed to get bfdd status, %w", err) klog.Error(err) return err } @@ -726,7 +725,7 @@ func (c *Controller) checkNodeGwNicInNs(nodeExtIP, ip, gw string, gwNS ns.NetNS) // not exist cmd = exec.Command("sh", "-c", fmt.Sprintf("bfdd-control allow %s", eip.Spec.V4Ip)) // #nosec G204 if err := cmd.Run(); err != nil { - err := fmt.Errorf("failed to add lrp %s ip %s into bfd listening list, %v", eip.Name, eip.Status.V4Ip, err) + err := fmt.Errorf("failed to add lrp %s ip %s into bfd listening list, %w", eip.Name, eip.Status.V4Ip, err) klog.Error(err) return err } @@ -736,7 +735,6 @@ func (c *Controller) checkNodeGwNicInNs(nodeExtIP, ip, gw string, gwNS ns.NetNS) klog.Error(err) return err } - } } } @@ -744,7 +742,7 @@ func (c *Controller) checkNodeGwNicInNs(nodeExtIP, ip, gw string, gwNS ns.NetNS) }) } - err = fmt.Errorf("node external gw not ready") + err = errors.New("node external gw not ready") klog.Error(err) return err } @@ -758,7 +756,7 @@ func configureNodeGwNic(portName, ip, gw string, macAddr net.HardwareAddr, mtu i fmt.Sprintf("external_ids:pod_netns=%s", util.NodeGwNsPath)) if err != nil { klog.Errorf("failed to configure node external nic %s: %v, %q", portName, err, output) - return fmt.Errorf(output) + return errors.New(output) } gwLink, err := netlink.LinkByName(util.NodeGwNic) if err == nil { @@ -771,7 +769,7 @@ func configureNodeGwNic(portName, ip, gw string, macAddr net.HardwareAddr, mtu i } return ns.WithNetNSPath(gwNS.Path(), func(_ ns.NetNS) error { if err = configureNic(util.NodeGwNic, ip, macAddr, mtu, true); err != nil { - klog.Errorf("failed to congigure node gw nic %s, %v", util.NodeGwNic, err) + klog.Errorf("failed to configure node gw nic %s, %v", util.NodeGwNic, err) return err } @@ -811,7 +809,7 @@ func configureNodeGwNic(portName, ip, gw string, macAddr net.HardwareAddr, mtu i Gw: net.ParseIP(gws[0]), }) if err != nil { - return fmt.Errorf("config v4 gateway failed: %v", err) + return fmt.Errorf("config v4 gateway failed: %w", err) } _, defaultNet, _ = net.ParseCIDR("::/0") @@ -823,11 +821,11 @@ func configureNodeGwNic(portName, ip, gw string, macAddr net.HardwareAddr, mtu i }) } if err != nil { - return fmt.Errorf("failed to configure gateway: %v", err) + return fmt.Errorf("failed to configure gateway: %w", err) } cmd := exec.Command("sh", "-c", "/usr/local/bin/bfdd-beacon --listen=0.0.0.0") if err := cmd.Run(); err != nil { - err := fmt.Errorf("failed to get start bfd listen, %v", err) + err := fmt.Errorf("failed to get start bfd listen, %w", err) klog.Error(err) return err } @@ -837,7 +835,7 @@ func configureNodeGwNic(portName, ip, gw string, macAddr net.HardwareAddr, mtu i func removeNodeGwNic() error { if _, err := ovs.Exec(ovs.IfExists, "del-port", "br-int", util.NodeGwNic); err != nil { - return fmt.Errorf("failed to remove ecmp external port %s from OVS bridge %s: %v", "br-int", util.NodeGwNic, err) + return fmt.Errorf("failed to remove ecmp external port %s from OVS bridge %s: %w", "br-int", util.NodeGwNic, err) } klog.Infof("removed node external gw nic %q", util.NodeGwNic) return nil @@ -845,7 +843,7 @@ func removeNodeGwNic() error { func removeNodeGwNs() error { if err := DeleteNamedNs(util.NodeGwNs); err != nil { - return fmt.Errorf("failed to remove node external gw ns %s: %v", util.NodeGwNs, err) + return fmt.Errorf("failed to remove node external gw ns %s: %w", util.NodeGwNs, err) } klog.Infof("node external gw ns %s removed", util.NodeGwNs) return nil @@ -918,12 +916,12 @@ func (c *Controller) loopOvnExt0Check() { // ns not exist, create node external gw ns cmd := exec.Command("sh", "-c", fmt.Sprintf("/usr/sbin/ip netns add %s", util.NodeGwNs)) // #nosec G204 if err := cmd.Run(); err != nil { - err := fmt.Errorf("failed to get create gw ns %s, %v", util.NodeGwNs, err) + err := fmt.Errorf("failed to get create gw ns %s, %w", util.NodeGwNs, err) klog.Error(err) return } if gwNS, err = ns.GetNS(util.NodeGwNsPath); err != nil { - err := fmt.Errorf("failed to get node gw ns %s, %v", util.NodeGwNs, err) + err := fmt.Errorf("failed to get node gw ns %s, %w", util.NodeGwNs, err) klog.Error(err) return } @@ -1000,13 +998,13 @@ func configureMirrorLink(portName string, _ int) error { mirrorLink, err := netlink.LinkByName(portName) if err != nil { klog.Error(err) - return fmt.Errorf("can not find mirror nic %s: %v", portName, err) + return fmt.Errorf("can not find mirror nic %s: %w", portName, err) } if mirrorLink.Attrs().OperState != netlink.OperUp { if err = netlink.LinkSetUp(mirrorLink); err != nil { klog.Error(err) - return fmt.Errorf("can not set mirror nic %s up: %v", portName, err) + return fmt.Errorf("can not set mirror nic %s up: %w", portName, err) } } @@ -1017,12 +1015,12 @@ func configureNic(link, ip string, macAddr net.HardwareAddr, mtu int, detectIPCo nodeLink, err := netlink.LinkByName(link) if err != nil { klog.Error(err) - return fmt.Errorf("can not find nic %s: %v", link, err) + return fmt.Errorf("can not find nic %s: %w", link, err) } if err = netlink.LinkSetHardwareAddr(nodeLink, macAddr); err != nil { klog.Error(err) - return fmt.Errorf("can not set mac address to nic %s: %v", link, err) + return fmt.Errorf("can not set mac address to nic %s: %w", link, err) } if mtu > 0 { @@ -1032,14 +1030,14 @@ func configureNic(link, ip string, macAddr net.HardwareAddr, mtu int, detectIPCo err = netlink.LinkSetMTU(nodeLink, mtu) } if err != nil { - return fmt.Errorf("failed to set nic %s mtu: %v", link, err) + return fmt.Errorf("failed to set nic %s mtu: %w", link, err) } } if nodeLink.Attrs().OperState != netlink.OperUp { if err = netlink.LinkSetUp(nodeLink); err != nil { klog.Error(err) - return fmt.Errorf("can not set node nic %s up: %v", link, err) + return fmt.Errorf("can not set node nic %s up: %w", link, err) } } @@ -1048,7 +1046,7 @@ func configureNic(link, ip string, macAddr net.HardwareAddr, mtu int, detectIPCo ipAddrs, err := netlink.AddrList(nodeLink, unix.AF_UNSPEC) if err != nil { klog.Error(err) - return fmt.Errorf("can not get addr %s: %v", nodeLink, err) + return fmt.Errorf("can not get addr %s: %w", nodeLink, err) } for _, ipAddr := range ipAddrs { if ipAddr.IP.IsLinkLocalUnicast() { @@ -1067,7 +1065,7 @@ func configureNic(link, ip string, macAddr net.HardwareAddr, mtu int, detectIPCo ipAddr, err := netlink.ParseAddr(ipStr) if err != nil { - return fmt.Errorf("can not parse address %s: %v", ipStr, err) + return fmt.Errorf("can not parse address %s: %w", ipStr, err) } ipAddMap[ipStr] = *ipAddr } @@ -1076,7 +1074,7 @@ func configureNic(link, ip string, macAddr net.HardwareAddr, mtu int, detectIPCo klog.Infof("delete ip address %s on %s", ip, link) if err = netlink.AddrDel(nodeLink, &addr); err != nil { klog.Error(err) - return fmt.Errorf("delete address %s: %v", addr, err) + return fmt.Errorf("delete address %s: %w", addr, err) } } for ip, addr := range ipAddMap { @@ -1084,7 +1082,7 @@ func configureNic(link, ip string, macAddr net.HardwareAddr, mtu int, detectIPCo ip := addr.IP.String() mac, err := util.ArpDetectIPConflict(link, ip, macAddr) if err != nil { - err = fmt.Errorf("failed to detect address conflict for %s on link %s: %v", ip, link, err) + err = fmt.Errorf("failed to detect address conflict for %s on link %s: %w", ip, link, err) klog.Error(err) return err } @@ -1102,7 +1100,7 @@ func configureNic(link, ip string, macAddr net.HardwareAddr, mtu int, detectIPCo klog.Infof("add ip address %s to %s", ip, link) if err = netlink.AddrAdd(nodeLink, &addr); err != nil { klog.Error(err) - return fmt.Errorf("can not add address %v to nic %s: %v", addr, link, err) + return fmt.Errorf("can not add address %s to nic %s: %w", addr, link, err) } } @@ -1112,14 +1110,14 @@ func configureNic(link, ip string, macAddr net.HardwareAddr, mtu int, detectIPCo func configureLoNic() error { loLink, err := netlink.LinkByName(util.LoNic) if err != nil { - err := fmt.Errorf("can not find nic %s, %v", util.LoNic, err) + err := fmt.Errorf("can not find nic %s, %w", util.LoNic, err) klog.Error(err) return err } if loLink.Attrs().OperState != netlink.OperUp { if err = netlink.LinkSetUp(loLink); err != nil { - err := fmt.Errorf("failed to set up nic %s, %v", util.LoNic, err) + err := fmt.Errorf("failed to set up nic %s, %w", util.LoNic, err) klog.Error(err) return err } @@ -1131,25 +1129,25 @@ func configureLoNic() error { func (c *Controller) transferAddrsAndRoutes(nicName, brName string, delNonExistent bool) (int, error) { nic, err := netlink.LinkByName(nicName) if err != nil { - return 0, fmt.Errorf("failed to get nic by name %s: %v", nicName, err) + return 0, fmt.Errorf("failed to get nic by name %s: %w", nicName, err) } bridge, err := netlink.LinkByName(brName) if err != nil { - return 0, fmt.Errorf("failed to get bridge by name %s: %v", brName, err) + return 0, fmt.Errorf("failed to get bridge by name %s: %w", brName, err) } addrs, err := netlink.AddrList(nic, netlink.FAMILY_ALL) if err != nil { - return 0, fmt.Errorf("failed to get addresses on nic %s: %v", nicName, err) + return 0, fmt.Errorf("failed to get addresses on nic %s: %w", nicName, err) } routes, err := netlink.RouteList(nic, netlink.FAMILY_ALL) if err != nil { - return 0, fmt.Errorf("failed to get routes on nic %s: %v", nicName, err) + return 0, fmt.Errorf("failed to get routes on nic %s: %w", nicName, err) } brAddrs, err := netlink.AddrList(bridge, netlink.FAMILY_ALL) if err != nil { - return 0, fmt.Errorf("failed to get addresses on OVS bridge %s: %v", brName, err) + return 0, fmt.Errorf("failed to get addresses on OVS bridge %s: %w", brName, err) } var delAddrs []netlink.Addr @@ -1192,7 +1190,7 @@ func (c *Controller) transferAddrsAndRoutes(nicName, brName string, delNonExiste count++ if err = netlink.AddrDel(nic, &addr); err != nil { - errMsg := fmt.Errorf("failed to delete address %q on nic %s: %v", addr.String(), nicName, err) + errMsg := fmt.Errorf("failed to delete address %q on nic %s: %w", addr.String(), nicName, err) klog.Error(errMsg) return 0, errMsg } @@ -1201,7 +1199,7 @@ func (c *Controller) transferAddrsAndRoutes(nicName, brName string, delNonExiste addr.Label = "" addr.PreferedLft, addr.ValidLft = 0, 0 if err = netlink.AddrReplace(bridge, &addr); err != nil { - return 0, fmt.Errorf("failed to replace address %q on OVS bridge %s: %v", addr.String(), brName, err) + return 0, fmt.Errorf("failed to replace address %q on OVS bridge %s: %w", addr.String(), brName, err) } klog.Infof("address %q has been added/replaced to link %s", addr.String(), brName) } @@ -1209,7 +1207,7 @@ func (c *Controller) transferAddrsAndRoutes(nicName, brName string, delNonExiste if count != 0 { for _, addr := range delAddrs { if err = netlink.AddrDel(bridge, &addr); err != nil { - errMsg := fmt.Errorf("failed to delete address %q on OVS bridge %s: %v", addr.String(), brName, err) + errMsg := fmt.Errorf("failed to delete address %q on OVS bridge %s: %w", addr.String(), brName, err) klog.Error(errMsg) return 0, errMsg } @@ -1225,12 +1223,12 @@ func (c *Controller) transferAddrsAndRoutes(nicName, brName string, delNonExiste } if !albBond { if _, err = ovs.Exec("set", "bridge", brName, fmt.Sprintf(`other-config:hwaddr="%s"`, nic.Attrs().HardwareAddr.String())); err != nil { - return 0, fmt.Errorf("failed to set MAC address of OVS bridge %s: %v", brName, err) + return 0, fmt.Errorf("failed to set MAC address of OVS bridge %s: %w", brName, err) } } if err = netlink.LinkSetUp(bridge); err != nil { - return 0, fmt.Errorf("failed to set OVS bridge %s up: %v", brName, err) + return 0, fmt.Errorf("failed to set OVS bridge %s up: %w", brName, err) } for _, scope := range routeScopeOrders { @@ -1242,7 +1240,7 @@ func (c *Controller) transferAddrsAndRoutes(nicName, brName string, delNonExiste if route.Scope == scope { route.LinkIndex = bridge.Attrs().Index if err = netlink.RouteReplace(&route); err != nil { - return 0, fmt.Errorf("failed to add/replace route %s to OVS bridge %s: %v", route.String(), brName, err) + return 0, fmt.Errorf("failed to add/replace route %s to OVS bridge %s: %w", route.String(), brName, err) } klog.Infof("route %q has been added/replaced to OVS bridge %s", route.String(), brName) } @@ -1251,7 +1249,7 @@ func (c *Controller) transferAddrsAndRoutes(nicName, brName string, delNonExiste brRoutes, err := netlink.RouteList(bridge, netlink.FAMILY_ALL) if err != nil { - return 0, fmt.Errorf("failed to get routes on OVS bridge %s: %v", brName, err) + return 0, fmt.Errorf("failed to get routes on OVS bridge %s: %w", brName, err) } var delRoutes []netlink.Route @@ -1281,7 +1279,7 @@ func (c *Controller) transferAddrsAndRoutes(nicName, brName string, delNonExiste for _, route := range delRoutes { if route.Scope == routeScopeOrders[i] { if err = netlink.RouteDel(&route); err != nil { - return 0, fmt.Errorf("failed to delete route %s from OVS bridge %s: %v", route.String(), brName, err) + return 0, fmt.Errorf("failed to delete route %s from OVS bridge %s: %w", route.String(), brName, err) } klog.Infof("route %q has been deleted from OVS bridge %s", route.String(), brName) } @@ -1289,7 +1287,7 @@ func (c *Controller) transferAddrsAndRoutes(nicName, brName string, delNonExiste } if err = netlink.LinkSetUp(nic); err != nil { - return 0, fmt.Errorf("failed to set link %s up: %v", nicName, err) + return 0, fmt.Errorf("failed to set link %s up: %w", nicName, err) } return nic.Attrs().MTU, nil @@ -1301,22 +1299,22 @@ func (c *Controller) configProviderNic(nicName, brName string, trunks []string) sysctlDisableIPv6 := fmt.Sprintf("net.ipv6.conf.%s.disable_ipv6", brName) disableIPv6, err := sysctl.Sysctl(sysctlDisableIPv6) if err != nil { - return 0, fmt.Errorf("failed to get sysctl %s: %v", sysctlDisableIPv6, err) + return 0, fmt.Errorf("failed to get sysctl %s: %w", sysctlDisableIPv6, err) } if disableIPv6 != "0" { if _, err = sysctl.Sysctl(sysctlDisableIPv6, "0"); err != nil { - return 0, fmt.Errorf("failed to enable ipv6 on OVS bridge %s: %v", brName, err) + return 0, fmt.Errorf("failed to enable ipv6 on OVS bridge %s: %w", brName, err) } } mtu, err := c.transferAddrsAndRoutes(nicName, brName, false) if err != nil { - return 0, fmt.Errorf("failed to transfer addresess and routes from %s to %s: %v", nicName, brName, err) + return 0, fmt.Errorf("failed to transfer addresses and routes from %s to %s: %w", nicName, brName, err) } if _, err = ovs.Exec(ovs.MayExist, "add-port", brName, nicName, "--", "set", "port", nicName, "trunks="+strings.Join(trunks, ","), "external_ids:vendor="+util.CniTypeName); err != nil { - return 0, fmt.Errorf("failed to add %s to OVS bridge %s: %v", nicName, brName, err) + return 0, fmt.Errorf("failed to add %s to OVS bridge %s: %w", nicName, brName, err) } klog.V(3).Infof("ovs port %s has been added to bridge %s", nicName, brName) @@ -1357,24 +1355,24 @@ func (c *Controller) removeProviderNic(nicName, brName string) error { klog.Warningf("failed to get nic by name %s: %v", nicName, err) return nil } - return fmt.Errorf("failed to get nic by name %s: %v", nicName, err) + return fmt.Errorf("failed to get nic by name %s: %w", nicName, err) } bridge, err := netlink.LinkByName(brName) if err != nil { - return fmt.Errorf("failed to get bridge by name %s: %v", brName, err) + return fmt.Errorf("failed to get bridge by name %s: %w", brName, err) } addrs, err := netlink.AddrList(bridge, netlink.FAMILY_ALL) if err != nil { - return fmt.Errorf("failed to get addresses on bridge %s: %v", brName, err) + return fmt.Errorf("failed to get addresses on bridge %s: %w", brName, err) } routes, err := netlink.RouteList(bridge, netlink.FAMILY_ALL) if err != nil { - return fmt.Errorf("failed to get routes on bridge %s: %v", brName, err) + return fmt.Errorf("failed to get routes on bridge %s: %w", brName, err) } if _, err = ovs.Exec(ovs.IfExists, "del-port", brName, nicName); err != nil { - return fmt.Errorf("failed to remove %s from OVS bridge %s: %v", nicName, brName, err) + return fmt.Errorf("failed to remove %s from OVS bridge %s: %w", nicName, brName, err) } klog.V(3).Infof("ovs port %s has been removed from bridge %s", nicName, brName) @@ -1385,7 +1383,7 @@ func (c *Controller) removeProviderNic(nicName, brName string) error { } if err = netlink.AddrDel(bridge, &addr); err != nil { - errMsg := fmt.Errorf("failed to delete address %q on OVS bridge %s: %v", addr.String(), brName, err) + errMsg := fmt.Errorf("failed to delete address %q on OVS bridge %s: %w", addr.String(), brName, err) klog.Error(errMsg) return errMsg } @@ -1393,7 +1391,7 @@ func (c *Controller) removeProviderNic(nicName, brName string) error { addr.Label = "" if err = netlink.AddrReplace(nic, &addr); err != nil { - return fmt.Errorf("failed to replace address %q on nic %s: %v", addr.String(), nicName, err) + return fmt.Errorf("failed to replace address %q on nic %s: %w", addr.String(), nicName, err) } klog.Infof("address %q has been added/replaced to link %s", addr.String(), nicName) } @@ -1418,7 +1416,7 @@ func (c *Controller) removeProviderNic(nicName, brName string) error { if route.Scope == scope { route.LinkIndex = nic.Attrs().Index if err = netlink.RouteReplace(&route); err != nil { - return fmt.Errorf("failed to add/replace route %s: %v", route.String(), err) + return fmt.Errorf("failed to add/replace route %s: %w", route.String(), err) } klog.Infof("route %q has been added/replaced to link %s", route.String(), nicName) } @@ -1426,7 +1424,7 @@ func (c *Controller) removeProviderNic(nicName, brName string) error { } if err = netlink.LinkSetDown(bridge); err != nil { - return fmt.Errorf("failed to set OVS bridge %s down: %v", brName, err) + return fmt.Errorf("failed to set OVS bridge %s down: %w", brName, err) } klog.V(3).Infof("link %s has been set down", brName) @@ -1449,7 +1447,7 @@ func setupVethPair(containerID, ifName string, mtu int) (string, string, error) klog.Errorf("failed to delete veth %v", err) return "", "", err } - return "", "", fmt.Errorf("failed to create veth for %v", err) + return "", "", fmt.Errorf("failed to create veth for %w", err) } return hostNicName, containerNicName, nil } @@ -1461,7 +1459,7 @@ func setupSriovInterface(containerID, deviceID, vfDriver, ifName string, mtu int if vfDriver == "vfio-pci" { matches, err := filepath.Glob(filepath.Join(util.VfioSysDir, "*")) if err != nil { - return "", "", fmt.Errorf("failed to check %s 'vfio-pci' driver path, %v", deviceID, err) + return "", "", fmt.Errorf("failed to check %s 'vfio-pci' driver path, %w", deviceID, err) } for _, match := range matches { @@ -1521,7 +1519,7 @@ func setupSriovInterface(containerID, deviceID, vfDriver, ifName string, mtu int // 5. rename the host VF representor hostNicName, _ := generateNicName(containerID, ifName) if err = renameLink(oldHostRepName, hostNicName); err != nil { - return "", "", fmt.Errorf("failed to rename %s to %s: %v", oldHostRepName, hostNicName, err) + return "", "", fmt.Errorf("failed to rename %s to %s: %w", oldHostRepName, hostNicName, err) } link, err := netlink.LinkByName(hostNicName) @@ -1531,7 +1529,7 @@ func setupSriovInterface(containerID, deviceID, vfDriver, ifName string, mtu int // 6. set MTU on VF representor if err = netlink.LinkSetMTU(link, mtu); err != nil { - return "", "", fmt.Errorf("failed to set MTU on %s: %v", hostNicName, err) + return "", "", fmt.Errorf("failed to set MTU on %s: %w", hostNicName, err) } // 7. set MAC address to VF @@ -1576,7 +1574,7 @@ func (csh cniServerHandler) configureNicWithInternalPort(podName, podNamespace, fmt.Sprintf("external_ids:ip=%s", ipStr), fmt.Sprintf("external_ids:pod_netns=%s", netns)) if err != nil { - err := fmt.Errorf("add nic to ovs failed %v: %q", err, output) + err := fmt.Errorf("add nic to ovs failed %w: %q", err, output) klog.Error(err) return containerNicName, nil, err } @@ -1592,7 +1590,7 @@ func (csh cniServerHandler) configureNicWithInternalPort(podName, podNamespace, // container nic must use same mac address from pod annotation, otherwise ovn will reject these packets by default macAddr, err := net.ParseMAC(mac) if err != nil { - return containerNicName, nil, fmt.Errorf("failed to parse mac %s %v", macAddr, err) + return containerNicName, nil, fmt.Errorf("failed to parse mac %s %w", macAddr, err) } if err = ovs.SetInterfaceBandwidth(podName, podNamespace, ifaceID, egress, ingress); err != nil { @@ -1605,7 +1603,7 @@ func (csh cniServerHandler) configureNicWithInternalPort(podName, podNamespace, podNS, err := ns.GetNS(netns) if err != nil { - return containerNicName, nil, fmt.Errorf("failed to open netns %q: %v", netns, err) + return containerNicName, nil, fmt.Errorf("failed to open netns %q: %w", netns, err) } routes, err = csh.configureContainerNic(podName, podNamespace, containerNicName, ifName, ip, gateway, isDefaultRoute, detectIPConflict, routes, macAddr, podNS, mtu, nicType, gwCheckMode, u2oInterconnectionIP) return containerNicName, routes, err @@ -1614,13 +1612,13 @@ func (csh cniServerHandler) configureNicWithInternalPort(podName, podNamespace, func (csh cniServerHandler) removeDefaultRoute(netns string, ipv4, ipv6 bool) error { podNS, err := ns.GetNS(netns) if err != nil { - return fmt.Errorf("failed to open netns %q: %v", netns, err) + return fmt.Errorf("failed to open netns %q: %w", netns, err) } return ns.WithNetNSPath(podNS.Path(), func(_ ns.NetNS) error { routes, err := netlink.RouteList(nil, netlink.FAMILY_ALL) if err != nil { - return fmt.Errorf("failed to get all routes: %v", err) + return fmt.Errorf("failed to get all routes: %w", err) } for _, r := range routes { @@ -1632,14 +1630,14 @@ func (csh cniServerHandler) removeDefaultRoute(netns string, ipv4, ipv6 bool) er if ipv4 && r.Family == netlink.FAMILY_V4 { klog.Infof("deleting default ipv4 route %+v", r) if err = netlink.RouteDel(&r); err != nil { - return fmt.Errorf("failed to delete route %+v: %v", r, err) + return fmt.Errorf("failed to delete route %+v: %w", r, err) } continue } if ipv6 && r.Family == netlink.FAMILY_V6 { klog.Infof("deleting default ipv6 route %+v", r) if err = netlink.RouteDel(&r); err != nil { - return fmt.Errorf("failed to delete route %+v: %v", r, err) + return fmt.Errorf("failed to delete route %+v: %w", r, err) } } } @@ -1651,14 +1649,14 @@ func (csh cniServerHandler) removeDefaultRoute(netns string, ipv4, ipv6 bool) er func configureAdditionalNic(link, ip string) error { nodeLink, err := netlink.LinkByName(link) if err != nil { - return fmt.Errorf("can not find nic %s %v", link, err) + return fmt.Errorf("can not find nic %s %w", link, err) } ipDelMap := make(map[string]netlink.Addr) ipAddMap := make(map[string]netlink.Addr) ipAddrs, err := netlink.AddrList(nodeLink, 0x0) if err != nil { - return fmt.Errorf("can not get addr %s %v", nodeLink, err) + return fmt.Errorf("can not get addr %s %w", nodeLink, err) } for _, ipAddr := range ipAddrs { if ipAddr.IP.IsLinkLocalUnicast() { @@ -1677,19 +1675,19 @@ func configureAdditionalNic(link, ip string) error { ipAddr, err := netlink.ParseAddr(ipStr) if err != nil { - return fmt.Errorf("can not parse %s %v", ipStr, err) + return fmt.Errorf("can not parse %s %w", ipStr, err) } ipAddMap[ipStr] = *ipAddr } for _, addr := range ipDelMap { if err = netlink.AddrDel(nodeLink, &addr); err != nil { - return fmt.Errorf("delete address %s %v", addr, err) + return fmt.Errorf("delete address %s %w", addr, err) } } for _, addr := range ipAddMap { if err = netlink.AddrAdd(nodeLink, &addr); err != nil { - return fmt.Errorf("can not add address %v to nic %s, %v", addr, link, err) + return fmt.Errorf("can not add address %v to nic %s, %w", addr, link, err) } } @@ -1708,7 +1706,7 @@ func addAdditionalNic(ifName string) error { klog.Errorf("failed to delete static iface %v, err %v", ifName, err) return err } - return fmt.Errorf("failed to create static iface %v, err %v", ifName, err) + return fmt.Errorf("failed to create static iface %v, err %w", ifName, err) } return nil } @@ -1716,17 +1714,17 @@ func addAdditionalNic(ifName string) error { func setVfMac(deviceID string, vfIndex int, mac string) error { macAddr, err := net.ParseMAC(mac) if err != nil { - return fmt.Errorf("failed to parse mac %s %v", macAddr, err) + return fmt.Errorf("failed to parse mac %s %w", macAddr, err) } pfPci, err := sriovnet.GetPfPciFromVfPci(deviceID) if err != nil { - return fmt.Errorf("failed to get pf of device %s %v", deviceID, err) + return fmt.Errorf("failed to get pf of device %s %w", deviceID, err) } netDevs, err := sriovnet.GetNetDevicesFromPci(pfPci) if err != nil { - return fmt.Errorf("failed to get pf of device %s %v", deviceID, err) + return fmt.Errorf("failed to get pf of device %s %w", deviceID, err) } // get real pf @@ -1749,10 +1747,10 @@ func setVfMac(deviceID string, vfIndex int, mac string) error { pfLink, err := netlink.LinkByName(pfName) if err != nil { - return fmt.Errorf("failed to lookup pf %s: %v", pfName, err) + return fmt.Errorf("failed to lookup pf %s: %w", pfName, err) } if err := netlink.LinkSetVfHardwareAddr(pfLink, vfIndex, macAddr); err != nil { - return fmt.Errorf("can not set mac address to vf nic:%s vf:%d %v", pfName, vfIndex, err) + return fmt.Errorf("can not set mac address to vf nic:%s vf:%d %w", pfName, vfIndex, err) } return nil } @@ -1792,7 +1790,7 @@ func rollBackVethPair(nicName string) error { return nil } klog.Error(err) - return fmt.Errorf("find host link %s failed %v", nicName, err) + return fmt.Errorf("find host link %s failed %w", nicName, err) } hostLinkType := hostLink.Type() @@ -1800,7 +1798,7 @@ func rollBackVethPair(nicName string) error { if hostLinkType == "veth" { if err = netlink.LinkDel(hostLink); err != nil { klog.Error(err) - return fmt.Errorf("delete host link %s failed %v", hostLink, err) + return fmt.Errorf("delete host link %s failed %w", hostLink, err) } } klog.Infof("rollback veth success %s", nicName) diff --git a/pkg/daemon/server.go b/pkg/daemon/server.go index 0976939a8f0..01045d9ec68 100644 --- a/pkg/daemon/server.go +++ b/pkg/daemon/server.go @@ -3,6 +3,7 @@ package daemon import ( "fmt" "net/http" + "strconv" "time" "github.com/emicklei/go-restful/v3" @@ -69,7 +70,7 @@ func requestAndResponseLogger(request *restful.Request, response *restful.Respon cniOperationHistogram.WithLabelValues( nodeName, getRequestURI(request), - fmt.Sprintf("%d", response.StatusCode())).Observe(elapsed / 1000) + strconv.Itoa(response.StatusCode())).Observe(elapsed / 1000) klog.Infof(formatResponseLog(response, request, elapsed)) } diff --git a/pkg/daemon/tproxy_linux.go b/pkg/daemon/tproxy_linux.go index d2c63014a7e..79b7706f1d5 100644 --- a/pkg/daemon/tproxy_linux.go +++ b/pkg/daemon/tproxy_linux.go @@ -162,7 +162,7 @@ func (c *Controller) cleanTProxyRoutes(protocol string) { func addRuleIfNotExist(family, mark, mask, table int) error { curRules, err := netlink.RuleListFiltered(family, &netlink.Rule{Mark: mark}, netlink.RT_FILTER_MARK) if err != nil { - return fmt.Errorf("list rules with mark %x failed err: %v", mark, err) + return fmt.Errorf("list rules with mark %x failed err: %w", mark, err) } if len(curRules) != 0 { @@ -186,13 +186,13 @@ func addRuleIfNotExist(family, mark, mask, table int) error { func deleteRuleIfExists(family, mark int) error { curRules, err := netlink.RuleListFiltered(family, &netlink.Rule{Mark: mark}, netlink.RT_FILTER_MARK) if err != nil { - return fmt.Errorf("list rules with mark %x failed err: %v", mark, err) + return fmt.Errorf("list rules with mark %x failed err: %w", mark, err) } if len(curRules) != 0 { for _, r := range curRules { if err := netlink.RuleDel(&r); err != nil && !errors.Is(err, syscall.ENOENT) { - return fmt.Errorf("delete rule %v failed with err: %v", r, err) + return fmt.Errorf("delete rule %v failed with err: %w", r, err) } } } @@ -202,7 +202,7 @@ func deleteRuleIfExists(family, mark int) error { func addRouteIfNotExist(family, table int, dst *net.IPNet) error { curRoutes, err := netlink.RouteListFiltered(family, &netlink.Route{Table: table, Dst: dst}, netlink.RT_FILTER_TABLE|netlink.RT_FILTER_DST) if err != nil { - return fmt.Errorf("list routes with table %d failed with err: %v", table, err) + return fmt.Errorf("list routes with table %d failed with err: %w", table, err) } if len(curRoutes) != 0 { @@ -243,7 +243,7 @@ func delRouteIfExist(family, table int, dst *net.IPNet) error { link, err := netlink.LinkByName("lo") if err != nil { - return fmt.Errorf("can't find device lo") + return errors.New("can't find device lo") } route := netlink.Route{ diff --git a/pkg/metrics/server.go b/pkg/metrics/server.go index 5a16762df69..f389f398e39 100644 --- a/pkg/metrics/server.go +++ b/pkg/metrics/server.go @@ -18,7 +18,7 @@ func Run(ctx context.Context, config *rest.Config, addr string, secureServing bo client, err := rest.HTTPClientFor(config) if err != nil { klog.Error(err) - return fmt.Errorf("failed to create http client: %v", err) + return fmt.Errorf("failed to create http client: %w", err) } options := server.Options{ @@ -31,7 +31,7 @@ func Run(ctx context.Context, config *rest.Config, addr string, secureServing bo svr, err := server.NewServer(options, config, client) if err != nil { klog.Error(err) - return fmt.Errorf("failed to create metrics server: %v", err) + return fmt.Errorf("failed to create metrics server: %w", err) } return svr.Start(ctx) diff --git a/pkg/ovn_ic_controller/config.go b/pkg/ovn_ic_controller/config.go index a97fbbe29a5..29779e96786 100644 --- a/pkg/ovn_ic_controller/config.go +++ b/pkg/ovn_ic_controller/config.go @@ -88,7 +88,7 @@ func ParseFlags() (*Configuration, error) { } if err := config.initKubeClient(); err != nil { - return nil, fmt.Errorf("failed to init kube client, %v", err) + return nil, fmt.Errorf("failed to init kube client, %w", err) } return config, nil diff --git a/pkg/ovn_ic_controller/ovn_ic_controller.go b/pkg/ovn_ic_controller/ovn_ic_controller.go index cccc76e7044..9a86e65957b 100644 --- a/pkg/ovn_ic_controller/ovn_ic_controller.go +++ b/pkg/ovn_ic_controller/ovn_ic_controller.go @@ -393,7 +393,7 @@ func (c *Controller) startOVNIC(icHost, icNbPort, icSbPort string) error { } output, err := cmd.CombinedOutput() if err != nil { - return fmt.Errorf("output: %s, err: %v", output, err) + return fmt.Errorf("output: %s, err: %w", output, err) } return nil } @@ -402,7 +402,7 @@ func (c *Controller) stopOVNIC() error { cmd := exec.Command("/usr/share/ovn/scripts/ovn-ctl", "stop_ic") output, err := cmd.CombinedOutput() if err != nil { - return fmt.Errorf("output: %s, err: %v", output, err) + return fmt.Errorf("output: %s, err: %w", output, err) } return nil } @@ -435,7 +435,6 @@ func (c *Controller) delLearnedRoute() error { klog.Errorf("failed to delete learned static route %#v on logical router %s: %v", r, lr.Name, err) return err } - } } @@ -632,7 +631,7 @@ func (c *Controller) listRemoteLogicalSwitchPortAddress() (*strset.Set, error) { }) if err != nil { klog.Error(err) - return nil, fmt.Errorf("list remote logical switch ports: %v", err) + return nil, fmt.Errorf("list remote logical switch ports: %w", err) } existAddress := strset.NewWithSize(len(lsps)) diff --git a/pkg/ovn_leader_checker/ovn.go b/pkg/ovn_leader_checker/ovn.go index 06a9aa7ee30..60ffae15b38 100755 --- a/pkg/ovn_leader_checker/ovn.go +++ b/pkg/ovn_leader_checker/ovn.go @@ -2,6 +2,7 @@ package ovn_leader_checker import ( "context" + "errors" "flag" "fmt" "net" @@ -94,7 +95,7 @@ func ParseFlags() (*Configuration, error) { // KubeClientInit funcs to check apiserver alive func KubeClientInit(cfg *Configuration) error { if cfg == nil { - return fmt.Errorf("invalid cfg") + return errors.New("invalid cfg") } // init kubeconfig here @@ -453,7 +454,7 @@ func updateTS() error { cmd := exec.Command("ovn-ic-nbctl", "show") output, err := cmd.CombinedOutput() if err != nil { - return fmt.Errorf("ovn-ic-nbctl show output: %s, err: %v", output, err) + return fmt.Errorf("ovn-ic-nbctl show output: %s, err: %w", output, err) } var existTSCount int if lines := strings.TrimSpace(string(output)); lines != "" { @@ -461,7 +462,7 @@ func updateTS() error { } expectTSCount, err := strconv.Atoi(os.Getenv("TS_NUM")) if err != nil { - return fmt.Errorf("expectTSCount atoi failed output: %s, err: %v", output, err) + return fmt.Errorf("expectTSCount atoi failed output: %s, err: %w", output, err) } if expectTSCount == existTSCount { klog.V(3).Infof("expectTSCount %d no changes required.", expectTSCount) @@ -490,7 +491,7 @@ func updateTS() error { } output, err := cmd.CombinedOutput() if err != nil { - return fmt.Errorf("output: %s, err: %v", output, err) + return fmt.Errorf("output: %s, err: %w", output, err) } } } else { @@ -507,7 +508,7 @@ func updateTS() error { } output, err := cmd.CombinedOutput() if err != nil { - return fmt.Errorf("output: %s, err: %v", output, err) + return fmt.Errorf("output: %s, err: %w", output, err) } } } diff --git a/pkg/ovnmonitor/util.go b/pkg/ovnmonitor/util.go index 1a803a5da09..612eac48d29 100644 --- a/pkg/ovnmonitor/util.go +++ b/pkg/ovnmonitor/util.go @@ -184,7 +184,7 @@ func getClusterInfo(direction, dbName string) (*OVNDBClusterStatus, error) { cmd := exec.Command("sh", "-c", cmdstr) // #nosec G204 output, err := cmd.CombinedOutput() if err != nil { - return nil, fmt.Errorf("failed to retrieve cluster/status info for database %s: %v", dbName, err) + return nil, fmt.Errorf("failed to retrieve cluster/status info for database %s: %w", dbName, err) } for _, line := range strings.Split(string(output), "\n") { diff --git a/pkg/ovs/ovn-ic-nbctl.go b/pkg/ovs/ovn-ic-nbctl.go index 1ac9d90475d..4d6e070a8fa 100644 --- a/pkg/ovs/ovn-ic-nbctl.go +++ b/pkg/ovs/ovn-ic-nbctl.go @@ -30,7 +30,7 @@ func (c LegacyClient) ovnIcNbCommand(cmdArgs ...string) (string, error) { if err != nil { code = "1" klog.Warningf("ovn-ic-nbctl command error: %s %s in %vms", OVNIcNbCtl, strings.Join(cmdArgs, " "), elapsed) - return "", fmt.Errorf("%s, %q", raw, err) + return "", fmt.Errorf("%s, %w", raw, err) } else if elapsed > 500 { klog.Warningf("ovn-ic-nbctl command took too long: %s %s in %vms", OVNIcNbCtl, strings.Join(cmdArgs, " "), elapsed) } @@ -41,7 +41,7 @@ func (c LegacyClient) GetTsSubnet(ts string) (string, error) { subnet, err := c.ovnIcNbCommand("get", "Transit_Switch", ts, "external_ids:subnet") if err != nil { klog.Error(err) - return "", fmt.Errorf("failed to get ts subnet, %v", err) + return "", fmt.Errorf("failed to get ts subnet, %w", err) } return subnet, nil } diff --git a/pkg/ovs/ovn-ic-sbctl.go b/pkg/ovs/ovn-ic-sbctl.go index a864d57c391..a80ed60e8f4 100644 --- a/pkg/ovs/ovn-ic-sbctl.go +++ b/pkg/ovs/ovn-ic-sbctl.go @@ -1,6 +1,7 @@ package ovs import ( + "errors" "fmt" "os/exec" "strings" @@ -30,7 +31,7 @@ func (c LegacyClient) ovnIcSbCommand(cmdArgs ...string) (string, error) { if err != nil { code = "1" klog.Warningf("ovn-ic-sbctl command error: %s %s in %vms", OVNIcSbCtl, strings.Join(cmdArgs, " "), elapsed) - return "", fmt.Errorf("%s, %q", raw, err) + return "", fmt.Errorf("%s, %w", raw, err) } else if elapsed > 500 { klog.Warningf("ovn-ic-sbctl command took too long: %s %s in %vms", OVNIcSbCtl, strings.Join(cmdArgs, " "), elapsed) } @@ -41,7 +42,7 @@ func (c LegacyClient) FindUUIDWithAttrInTable(attribute, value, table string) ([ key := attribute + "=" + value output, err := c.ovnIcSbCommand("--format=csv", "--no-heading", "--data=bare", "--columns=_uuid", "find", table, key) if err != nil { - err := fmt.Errorf("failed to find ovn-ic-sb db, %v", err) + err := fmt.Errorf("failed to find ovn-ic-sb db, %w", err) klog.Error(err) return nil, err } @@ -60,7 +61,7 @@ func (c LegacyClient) DestroyTableWithUUID(uuid, table string) error { _, err := c.ovnIcSbCommand("destroy", table, uuid) if err != nil { klog.Error(err) - return fmt.Errorf("failed to destroy record %s in table %s: %v", uuid, table, err) + return fmt.Errorf("failed to destroy record %s in table %s: %w", uuid, table, err) } return nil } @@ -69,21 +70,21 @@ func (c LegacyClient) GetAzUUID(az string) (string, error) { uuids, err := c.FindUUIDWithAttrInTable("name", az, "availability_zone") if err != nil { klog.Error(err) - return "", fmt.Errorf("failed to get ovn-ic-sb availability_zone uuid: %v", err) + return "", fmt.Errorf("failed to get ovn-ic-sb availability_zone uuid: %w", err) } if len(uuids) == 1 { return uuids[0], nil } else if len(uuids) == 0 { return "", nil } - return "", fmt.Errorf("two same-name chassises in one db is insane") + return "", errors.New("two same-name chassises in one db is insane") } func (c LegacyClient) GetGatewayUUIDsInOneAZ(uuid string) ([]string, error) { gateways, err := c.FindUUIDWithAttrInTable("availability_zone", uuid, "gateway") if err != nil { klog.Error(err) - return nil, fmt.Errorf("failed to get ovn-ic-sb gateways with uuid %v: %v", uuid, err) + return nil, fmt.Errorf("failed to get ovn-ic-sb gateways with uuid %v: %w", uuid, err) } return gateways, nil } @@ -92,7 +93,7 @@ func (c LegacyClient) GetRouteUUIDsInOneAZ(uuid string) ([]string, error) { routes, err := c.FindUUIDWithAttrInTable("availability_zone", uuid, "route") if err != nil { klog.Error(err) - return nil, fmt.Errorf("failed to get ovn-ic-sb routes with uuid %v: %v", uuid, err) + return nil, fmt.Errorf("failed to get ovn-ic-sb routes with uuid %v: %w", uuid, err) } return routes, nil } @@ -100,7 +101,7 @@ func (c LegacyClient) GetRouteUUIDsInOneAZ(uuid string) ([]string, error) { func (c LegacyClient) GetPortBindingUUIDsInOneAZ(uuid string) ([]string, error) { portBindings, err := c.FindUUIDWithAttrInTable("availability_zone", uuid, "Port_Binding") if err != nil { - return nil, fmt.Errorf("failed to get ovn-ic-sb Port_Binding with uuid %v: %v", uuid, err) + return nil, fmt.Errorf("failed to get ovn-ic-sb Port_Binding with uuid %v: %w", uuid, err) } return portBindings, nil } @@ -108,7 +109,7 @@ func (c LegacyClient) GetPortBindingUUIDsInOneAZ(uuid string) ([]string, error) func (c LegacyClient) DestroyGateways(uuids []string) error { for _, uuid := range uuids { if err := c.DestroyTableWithUUID(uuid, "gateway"); err != nil { - return fmt.Errorf("failed to delete gateway %v: %v", uuid, err) + return fmt.Errorf("failed to delete gateway %v: %w", uuid, err) } } return nil @@ -117,7 +118,7 @@ func (c LegacyClient) DestroyGateways(uuids []string) error { func (c LegacyClient) DestroyRoutes(uuids []string) error { for _, uuid := range uuids { if err := c.DestroyTableWithUUID(uuid, "route"); err != nil { - return fmt.Errorf("failed to delete route %v: %v", uuid, err) + return fmt.Errorf("failed to delete route %v: %w", uuid, err) } } return nil @@ -126,7 +127,7 @@ func (c LegacyClient) DestroyRoutes(uuids []string) error { func (c LegacyClient) DestroyPortBindings(uuids []string) error { for _, uuid := range uuids { if err := c.DestroyTableWithUUID(uuid, "Port_Binding"); err != nil { - return fmt.Errorf("failed to delete Port_Binding %v: %v", uuid, err) + return fmt.Errorf("failed to delete Port_Binding %v: %w", uuid, err) } } return nil @@ -134,7 +135,7 @@ func (c LegacyClient) DestroyPortBindings(uuids []string) error { func (c LegacyClient) DestroyChassis(uuid string) error { if err := c.DestroyTableWithUUID(uuid, "availability_zone"); err != nil { - return fmt.Errorf("failed to delete chassis %v: %v", uuid, err) + return fmt.Errorf("failed to delete chassis %v: %w", uuid, err) } return nil } diff --git a/pkg/ovs/ovn-nb-acl.go b/pkg/ovs/ovn-nb-acl.go index 7266f60f009..095b2f3cb2e 100644 --- a/pkg/ovs/ovn-nb-acl.go +++ b/pkg/ovs/ovn-nb-acl.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "slices" "strconv" @@ -41,7 +42,7 @@ func (c *OVNNbClient) UpdateIngressACLOps(pgName, asIngressName, asExceptName, p defaultDropACL, err := c.newACLWithoutCheck(pgName, ovnnb.ACLDirectionToLport, util.IngressDefaultDrop, allIPMatch.String(), ovnnb.ACLActionDrop, util.NetpolACLTier, options) if err != nil { - return nil, fmt.Errorf("new default drop ingress acl for port group %s: %v", pgName, err) + return nil, fmt.Errorf("new default drop ingress acl for port group %s: %w", pgName, err) } acls = append(acls, defaultDropACL) @@ -52,7 +53,7 @@ func (c *OVNNbClient) UpdateIngressACLOps(pgName, asIngressName, asExceptName, p for _, m := range matches { allowACL, err := c.newACLWithoutCheck(pgName, ovnnb.ACLDirectionToLport, util.IngressAllowPriority, m, ovnnb.ACLActionAllowRelated, util.NetpolACLTier) if err != nil { - return nil, fmt.Errorf("new allow ingress acl for port group %s: %v", pgName, err) + return nil, fmt.Errorf("new allow ingress acl for port group %s: %w", pgName, err) } acls = append(acls, allowACL) @@ -92,7 +93,7 @@ func (c *OVNNbClient) UpdateEgressACLOps(pgName, asEgressName, asExceptName, pro defaultDropACL, err := c.newACLWithoutCheck(pgName, ovnnb.ACLDirectionFromLport, util.EgressDefaultDrop, allIPMatch.String(), ovnnb.ACLActionDrop, util.NetpolACLTier, options) if err != nil { klog.Error(err) - return nil, fmt.Errorf("new default drop egress acl for port group %s: %v", pgName, err) + return nil, fmt.Errorf("new default drop egress acl for port group %s: %w", pgName, err) } acls = append(acls, defaultDropACL) @@ -109,7 +110,7 @@ func (c *OVNNbClient) UpdateEgressACLOps(pgName, asEgressName, asExceptName, pro }) if err != nil { klog.Error(err) - return nil, fmt.Errorf("new allow egress acl for port group %s: %v", pgName, err) + return nil, fmt.Errorf("new allow egress acl for port group %s: %w", pgName, err) } acls = append(acls, allowACL) @@ -135,7 +136,7 @@ func (c *OVNNbClient) CreateGatewayACL(lsName, pgName, gateway string) error { case len(lsName) != 0: parentName, parentType = lsName, logicalSwitchKey default: - return fmt.Errorf("one of port group name and logical switch name must be specified") + return errors.New("one of port group name and logical switch name must be specified") } for _, gw := range strings.Split(gateway, ",") { @@ -148,7 +149,7 @@ func (c *OVNNbClient) CreateGatewayACL(lsName, pgName, gateway string) error { allowIngressACL, err := c.newACL(parentName, ovnnb.ACLDirectionToLport, util.IngressAllowPriority, fmt.Sprintf("%s.src == %s", ipSuffix, gw), ovnnb.ACLActionAllowStateless, util.NetpolACLTier) if err != nil { klog.Error(err) - return fmt.Errorf("new allow ingress acl for %s: %v", parentName, err) + return fmt.Errorf("new allow ingress acl for %s: %w", parentName, err) } options := func(acl *ovnnb.ACL) { @@ -161,7 +162,7 @@ func (c *OVNNbClient) CreateGatewayACL(lsName, pgName, gateway string) error { allowEgressACL, err := c.newACL(parentName, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, fmt.Sprintf("%s.dst == %s", ipSuffix, gw), ovnnb.ACLActionAllowStateless, util.NetpolACLTier, options) if err != nil { klog.Error(err) - return fmt.Errorf("new allow egress acl for %s: %v", parentName, err) + return fmt.Errorf("new allow egress acl for %s: %w", parentName, err) } acls = append(acls, allowIngressACL, allowEgressACL) @@ -170,16 +171,15 @@ func (c *OVNNbClient) CreateGatewayACL(lsName, pgName, gateway string) error { ndACL, err := c.newACL(parentName, ovnnb.ACLDirectionFromLport, util.EgressAllowPriority, "nd || nd_ra || nd_rs", ovnnb.ACLActionAllowStateless, util.NetpolACLTier, options) if err != nil { klog.Error(err) - return fmt.Errorf("new nd acl for %s: %v", parentName, err) + return fmt.Errorf("new nd acl for %s: %w", parentName, err) } acls = append(acls, ndACL) } - } if err := c.CreateAcls(parentName, parentType, acls...); err != nil { - return fmt.Errorf("add gateway acls to %s: %v", pgName, err) + return fmt.Errorf("add gateway acls to %s: %w", pgName, err) } return nil @@ -200,7 +200,7 @@ func (c *OVNNbClient) CreateNodeACL(pgName, nodeIPStr, joinIPStr string) error { allowIngressACL, err := c.newACL(pgName, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, fmt.Sprintf("%s.src == %s && %s.dst == $%s", ipSuffix, nodeIP, ipSuffix, pgAs), ovnnb.ACLActionAllowRelated, util.NetpolACLTier) if err != nil { klog.Error(err) - return fmt.Errorf("new allow ingress acl for port group %s: %v", pgName, err) + return fmt.Errorf("new allow ingress acl for port group %s: %w", pgName, err) } options := func(acl *ovnnb.ACL) { @@ -213,7 +213,7 @@ func (c *OVNNbClient) CreateNodeACL(pgName, nodeIPStr, joinIPStr string) error { allowEgressACL, err := c.newACL(pgName, ovnnb.ACLDirectionFromLport, util.NodeAllowPriority, fmt.Sprintf("%s.dst == %s && %s.src == $%s", ipSuffix, nodeIP, ipSuffix, pgAs), ovnnb.ACLActionAllowRelated, util.NetpolACLTier, options) if err != nil { klog.Error(err) - return fmt.Errorf("new allow egress acl for port group %s: %v", pgName, err) + return fmt.Errorf("new allow egress acl for port group %s: %w", pgName, err) } acls = append(acls, allowIngressACL, allowEgressACL) @@ -244,7 +244,7 @@ func (c *OVNNbClient) CreateNodeACL(pgName, nodeIPStr, joinIPStr string) error { } if err := c.CreateAcls(pgName, portGroupKey, acls...); err != nil { - return fmt.Errorf("add node acls to port group %s: %v", pgName, err) + return fmt.Errorf("add node acls to port group %s: %w", pgName, err) } return nil @@ -256,17 +256,17 @@ func (c *OVNNbClient) CreateSgDenyAllACL(sgName string) error { ingressACL, err := c.newACL(pgName, ovnnb.ACLDirectionToLport, util.SecurityGroupDropPriority, fmt.Sprintf("outport == @%s && ip", pgName), ovnnb.ACLActionDrop, util.NetpolACLTier) if err != nil { klog.Error(err) - return fmt.Errorf("new deny all ingress acl for security group %s: %v", sgName, err) + return fmt.Errorf("new deny all ingress acl for security group %s: %w", sgName, err) } egressACL, err := c.newACL(pgName, ovnnb.ACLDirectionFromLport, util.SecurityGroupDropPriority, fmt.Sprintf("inport == @%s && ip", pgName), ovnnb.ACLActionDrop, util.NetpolACLTier) if err != nil { klog.Error(err) - return fmt.Errorf("new deny all egress acl for security group %s: %v", sgName, err) + return fmt.Errorf("new deny all egress acl for security group %s: %w", sgName, err) } 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 fmt.Errorf("add deny all acl to port group %s: %w", pgName, err) } return nil @@ -347,7 +347,7 @@ func (c *OVNNbClient) CreateSgBaseACL(sgName, direction string) error { newACL(vrrpMatch.String()) if err := c.CreateAcls(pgName, portGroupKey, acls...); err != nil { - return fmt.Errorf("add ingress acls to port group %s: %v", pgName, err) + return fmt.Errorf("add ingress acls to port group %s: %w", pgName, err) } return nil } @@ -357,7 +357,7 @@ func (c *OVNNbClient) UpdateSgACL(sg *kubeovnv1.SecurityGroup, direction string) // clear acl if err := c.DeleteAcls(pgName, portGroupKey, direction, nil); err != nil { - return fmt.Errorf("delete direction '%s' acls from port group %s: %v", direction, pgName, err) + return fmt.Errorf("delete direction '%s' acls from port group %s: %w", direction, pgName, err) } acls := make([]*ovnnb.ACL, 0, 2) @@ -386,7 +386,7 @@ func (c *OVNNbClient) UpdateSgACL(sg *kubeovnv1.SecurityGroup, direction string) acl, err := c.newACL(pgName, direction, util.SecurityGroupAllowPriority, match.String(), ovnnb.ACLActionAllowRelated, util.NetpolACLTier) if err != nil { klog.Error(err) - return fmt.Errorf("new allow acl for security group %s: %v", sg.Name, err) + return fmt.Errorf("new allow acl for security group %s: %w", sg.Name, err) } acls = append(acls, acl) @@ -398,13 +398,13 @@ func (c *OVNNbClient) UpdateSgACL(sg *kubeovnv1.SecurityGroup, direction string) acl, err := c.newSgRuleACL(sg.Name, direction, rule) if err != nil { klog.Error(err) - return fmt.Errorf("new rule acl for security group %s: %v", sg.Name, err) + return fmt.Errorf("new rule acl for security group %s: %w", sg.Name, err) } acls = append(acls, acl) } if err := c.CreateAcls(pgName, portGroupKey, acls...); err != nil { - return fmt.Errorf("add acl to port group %s: %v", pgName, err) + return fmt.Errorf("add acl to port group %s: %w", pgName, err) } return nil @@ -412,7 +412,7 @@ func (c *OVNNbClient) UpdateSgACL(sg *kubeovnv1.SecurityGroup, direction string) func (c *OVNNbClient) UpdateLogicalSwitchACL(lsName, cidrBlock string, subnetAcls []kubeovnv1.ACL, allowEWTraffic bool) 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) + return fmt.Errorf("delete subnet acls from %s: %w", lsName, err) } if len(subnetAcls) == 0 { @@ -445,14 +445,14 @@ func (c *OVNNbClient) UpdateLogicalSwitchACL(lsName, cidrBlock string, subnetAcl ingressSameSubnetACL, err := c.newACL(lsName, ovnnb.ACLDirectionToLport, util.AllowEWTrafficPriority, sameSubnetMatch.String(), ovnnb.ACLActionAllow, util.NetpolACLTier, options) if err != nil { klog.Error(err) - return fmt.Errorf("new same subnet ingress acl for logical switch %s: %v", lsName, err) + return fmt.Errorf("new same subnet ingress acl for logical switch %s: %w", lsName, err) } acls = append(acls, ingressSameSubnetACL) egressSameSubnetACL, err := c.newACL(lsName, ovnnb.ACLDirectionFromLport, util.AllowEWTrafficPriority, sameSubnetMatch.String(), ovnnb.ACLActionAllow, util.NetpolACLTier, options) if err != nil { klog.Error(err) - return fmt.Errorf("new same subnet egress acl for logical switch %s: %v", lsName, err) + return fmt.Errorf("new same subnet egress acl for logical switch %s: %w", lsName, err) } acls = append(acls, egressSameSubnetACL) } @@ -463,13 +463,13 @@ func (c *OVNNbClient) UpdateLogicalSwitchACL(lsName, cidrBlock string, subnetAcl acl, err := c.newACL(lsName, subnetACL.Direction, strconv.Itoa(subnetACL.Priority), subnetACL.Match, subnetACL.Action, util.NetpolACLTier, options) if err != nil { klog.Error(err) - return fmt.Errorf("new acl for logical switch %s: %v", lsName, err) + return fmt.Errorf("new acl for logical switch %s: %w", lsName, err) } acls = append(acls, acl) } if err := c.CreateAcls(lsName, logicalSwitchKey, acls...); err != nil { - return fmt.Errorf("add acls to logical switch %s: %v", lsName, err) + return fmt.Errorf("add acls to logical switch %s: %w", lsName, err) } return nil @@ -478,17 +478,17 @@ func (c *OVNNbClient) UpdateLogicalSwitchACL(lsName, cidrBlock string, subnetAcl // UpdateACL update acl func (c *OVNNbClient) UpdateACL(acl *ovnnb.ACL, fields ...interface{}) error { if acl == nil { - return fmt.Errorf("address_set is nil") + return errors.New("address_set is nil") } op, err := c.Where(acl).Update(acl, fields...) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for updating acl with 'direction %s priority %d match %s': %v", acl.Direction, acl.Priority, acl.Match, err) + return fmt.Errorf("generate operations for updating acl with 'direction %s priority %d match %s': %w", acl.Direction, acl.Priority, acl.Match, err) } if err = c.Transact("acl-update", op); err != nil { - return fmt.Errorf("update acl with 'direction %s priority %d match %s': %v", acl.Direction, acl.Priority, acl.Match, err) + return fmt.Errorf("update acl with 'direction %s priority %d match %s': %w", acl.Direction, acl.Priority, acl.Match, err) } return nil @@ -498,7 +498,7 @@ func (c *OVNNbClient) UpdateACL(acl *ovnnb.ACL, fields ...interface{}) 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) + return fmt.Errorf("clear logical switch %s acls: %w", lsName, err) } acls := make([]*ovnnb.ACL, 0) @@ -515,7 +515,7 @@ func (c *OVNNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR defaultDropACL, err := c.newACL(lsName, ovnnb.ACLDirectionToLport, util.DefaultDropPriority, allIPMatch.String(), ovnnb.ACLActionDrop, util.NetpolACLTier, options) if err != nil { klog.Error(err) - return fmt.Errorf("new default drop ingress acl for logical switch %s: %v", lsName, err) + return fmt.Errorf("new default drop ingress acl for logical switch %s: %w", lsName, err) } acls = append(acls, defaultDropACL) @@ -532,7 +532,7 @@ func (c *OVNNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR acl, err := c.newACL(lsName, ovnnb.ACLDirectionToLport, util.NodeAllowPriority, match.String(), ovnnb.ACLActionAllowRelated, util.NetpolACLTier) if err != nil { klog.Error(err) - return fmt.Errorf("new node subnet ingress acl for logical switch %s: %v", lsName, err) + return fmt.Errorf("new node subnet ingress acl for logical switch %s: %w", lsName, err) } acls = append(acls, acl) @@ -568,7 +568,7 @@ func (c *OVNNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR acl, err := c.newACL(lsName, ovnnb.ACLDirectionToLport, util.SubnetAllowPriority, match.String(), ovnnb.ACLActionAllowRelated, util.NetpolACLTier) if err != nil { klog.Error(err) - return fmt.Errorf("new allow subnet ingress acl for logical switch %s: %v", lsName, err) + return fmt.Errorf("new allow subnet ingress acl for logical switch %s: %w", lsName, err) } acls = append(acls, acl) @@ -593,7 +593,7 @@ func (c *OVNNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR sameSubnetACL, err := c.newACL(lsName, ovnnb.ACLDirectionToLport, util.SubnetAllowPriority, sameSubnetMatch.String(), ovnnb.ACLActionAllowRelated, util.NetpolACLTier) if err != nil { klog.Error(err) - return fmt.Errorf("new same subnet ingress acl for logical switch %s: %v", lsName, err) + return fmt.Errorf("new same subnet ingress acl for logical switch %s: %w", lsName, err) } acls = append(acls, sameSubnetACL) @@ -613,7 +613,7 @@ func (c *OVNNbClient) SetLogicalSwitchPrivate(lsName, cidrBlock, nodeSwitchCIDR if err := c.CreateAcls(lsName, logicalSwitchKey, acls...); err != nil { klog.Error(err) - return fmt.Errorf("add ingress acls to logical switch %s: %v", lsName, err) + return fmt.Errorf("add ingress acls to logical switch %s: %w", lsName, err) } return nil @@ -651,7 +651,7 @@ func (c *OVNNbClient) SetACLLog(pgName string, logEnable, isIngress bool) error err = c.UpdateACL(acl, &acl.Log) if err != nil { klog.Error(err) - return fmt.Errorf("update acl: %v", err) + return fmt.Errorf("update acl: %w", err) } return nil @@ -667,7 +667,7 @@ func (c *OVNNbClient) CreateAcls(parentName, parentType string, acls ...*ovnnb.A } if err = c.Transact("acls-add", ops); err != nil { - return fmt.Errorf("add acls to type %s %s: %v", parentType, parentName, err) + return fmt.Errorf("add acls to type %s %s: %w", parentType, parentName, err) } return nil @@ -677,17 +677,17 @@ func (c *OVNNbClient) CreateBareACL(parentName, direction, priority, match, acti acl, err := c.newACL(parentName, direction, priority, match, action, util.NetpolACLTier) 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) + return fmt.Errorf("new acl direction %s priority %s match %s action %s: %w", direction, priority, match, action, err) } op, err := c.ovsDbClient.Create(acl) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for creating acl direction %s priority %s match %s action %s: %v", direction, priority, match, action, err) + return fmt.Errorf("generate operations for creating acl direction %s priority %s match %s action %s: %w", direction, priority, match, action, err) } if err = c.Transact("acl-create", op); err != nil { - return fmt.Errorf("create acl direction %s priority %s match %s action %s: %v", direction, priority, match, action, err) + return fmt.Errorf("create acl direction %s priority %s match %s action %s: %w", direction, priority, match, action, err) } return nil @@ -704,7 +704,7 @@ func (c *OVNNbClient) DeleteAcls(parentName, parentType, direction string, exter } if err = c.Transact("acls-del", ops); err != nil { - return fmt.Errorf("del acls from type %s %s: %v", parentType, parentName, err) + return fmt.Errorf("del acls from type %s %s: %w", parentType, parentName, err) } return nil @@ -727,19 +727,19 @@ func (c *OVNNbClient) DeleteACL(parentName, parentType, direction, priority, mat 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) + return fmt.Errorf("generate operations for deleting acl from port group %s: %w", parentName, err) } } else { // remove acl from logical switch 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) + return fmt.Errorf("generate operations for deleting acl from logical switch %s: %w", parentName, err) } } 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) + return fmt.Errorf("del acls from type %s %s: %w", parentType, parentName, err) } return nil @@ -750,7 +750,7 @@ func (c *OVNNbClient) DeleteACL(parentName, parentType, direction, priority, mat 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") + return nil, errors.New("the parent name is required") } ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) @@ -762,7 +762,7 @@ func (c *OVNNbClient) GetACL(parent, direction, priority, match string, ignoreNo if err := c.ovsDbClient.WhereCache(func(acl *ovnnb.ACL) bool { return len(acl.ExternalIDs) != 0 && acl.ExternalIDs[aclParentKey] == parent && acl.Direction == direction && acl.Priority == intPriority && acl.Match == match }).List(ctx, &aclList); err != nil { - return nil, fmt.Errorf("get acl with 'parent %s direction %s priority %s match %s': %v", parent, direction, priority, match, err) + return nil, fmt.Errorf("get acl with 'parent %s direction %s priority %s match %s': %w", parent, direction, priority, match, err) } // not found @@ -794,7 +794,7 @@ func (c *OVNNbClient) ListAcls(direction string, externalIDs map[string]string) if err := c.WhereCache(aclFilter(direction, externalIDs)).List(ctx, &aclList); err != nil { klog.Error(err) - return nil, fmt.Errorf("list acls: %v", err) + return nil, fmt.Errorf("list acls: %w", err) } return aclList, nil @@ -808,7 +808,7 @@ func (c *OVNNbClient) ACLExists(parent, direction, priority, match string) (bool // newACL return acl with basic information func (c *OVNNbClient) newACL(parent, direction, priority, match, action string, tier int, options ...func(acl *ovnnb.ACL)) (*ovnnb.ACL, error) { if len(parent) == 0 { - return nil, fmt.Errorf("the parent name is required") + return nil, errors.New("the parent name is required") } if len(direction) == 0 || len(priority) == 0 || len(match) == 0 || len(action) == 0 { @@ -818,7 +818,7 @@ func (c *OVNNbClient) newACL(parent, direction, priority, match, action string, 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) + return nil, fmt.Errorf("get parent %s acl: %w", parent, err) } // found, ignore @@ -852,7 +852,7 @@ func (c *OVNNbClient) newACL(parent, direction, priority, match, action string, // but maybe used for updating network policy acl func (c *OVNNbClient) newACLWithoutCheck(parent, direction, priority, match, action string, tier int, options ...func(acl *ovnnb.ACL)) (*ovnnb.ACL, error) { if len(parent) == 0 { - return nil, fmt.Errorf("the parent name is required") + return nil, errors.New("the parent name is required") } if len(direction) == 0 || len(priority) == 0 || len(match) == 0 || len(action) == 0 { @@ -956,7 +956,7 @@ func (c *OVNNbClient) newSgRuleACL(sgName, direction string, rule *kubeovnv1.SgR acl, err := c.newACL(pgName, direction, strconv.Itoa(highestPriority-rule.Priority), match.String(), action, util.NetpolACLTier) if err != nil { klog.Error(err) - return nil, fmt.Errorf("new security group acl for port group %s: %v", pgName, err) + return nil, fmt.Errorf("new security group acl for port group %s: %w", pgName, err) } return acl, nil @@ -1030,7 +1030,7 @@ func newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, protocol, direc oneTCPMatch := NewAndACLMatch( allowedIPMatch, - NewACLMatch(tcpKey, "==", fmt.Sprintf("%d", portID), ""), + NewACLMatch(tcpKey, "==", strconv.Itoa(int(portID)), ""), ) matches = append(matches, oneTCPMatch.String()) @@ -1042,7 +1042,7 @@ func newNetworkPolicyACLMatch(pgName, asAllowName, asExceptName, protocol, direc tcpKey := protocol + ".dst" severalTCPMatch := NewAndACLMatch( allowedIPMatch, - NewACLMatch(tcpKey, "<=", fmt.Sprintf("%d", port.Port.IntVal), fmt.Sprintf("%d", *port.EndPort)), + NewACLMatch(tcpKey, "<=", strconv.Itoa(int(port.Port.IntVal)), strconv.Itoa(int(*port.EndPort))), ) matches = append(matches, severalTCPMatch.String()) } @@ -1108,7 +1108,7 @@ func (c *OVNNbClient) CreateAclsOps(parentName, parentType string, acls ...*ovnn createAclsOp, err := c.ovsDbClient.Create(models...) if err != nil { klog.Error(err) - return nil, fmt.Errorf("generate operations for creating acls: %v", err) + return nil, fmt.Errorf("generate operations for creating acls: %w", err) } var aclAddOp []ovsdb.Operation @@ -1116,13 +1116,13 @@ func (c *OVNNbClient) CreateAclsOps(parentName, parentType string, acls ...*ovnn 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) + return nil, fmt.Errorf("generate operations for adding acls to port group %s: %w", parentName, err) } } else { // acl attach to logical switch 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) + return nil, fmt.Errorf("generate operations for adding acls to logical switch %s: %w", parentName, err) } } @@ -1147,7 +1147,7 @@ func (c *OVNNbClient) DeleteAclsOps(parentName, parentType, direction string, ex acls, err := c.ListAcls(direction, externalIDs) if err != nil { klog.Error(err) - return nil, fmt.Errorf("list type %s %s acls: %v", parentType, parentName, err) + return nil, fmt.Errorf("list type %s %s acls: %w", parentType, parentName, err) } aclUUIDs := make([]string, 0, len(acls)) @@ -1161,13 +1161,13 @@ func (c *OVNNbClient) DeleteAclsOps(parentName, parentType, direction string, ex 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) + return nil, fmt.Errorf("generate operations for deleting acls from port group %s: %w", parentName, err) } } else { // remove acl from logical switch 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 nil, fmt.Errorf("generate operations for deleting acls from logical switch %s: %w", parentName, err) } } @@ -1242,7 +1242,7 @@ func (c *OVNNbClient) sgRuleNoACL(sgName, direction string, rule *kubeovnv1.SgRu exists, err := c.ACLExists(pgName, direction, strconv.Itoa(rule.Priority), match.String()) if err != nil { - err = fmt.Errorf("failed to check acl rule for security group %s: %v", sgName, err) + err = fmt.Errorf("failed to check acl rule for security group %s: %w", sgName, err) klog.Error(err) return false, err } @@ -1315,10 +1315,10 @@ func (c *OVNNbClient) UpdateAnpRuleACLOps(pgName, asName, protocol string, prior matches := newAnpACLMatch(pgName, asName, protocol, direction, rulePorts) for _, m := range matches { - strPriority := fmt.Sprintf("%d", priority) + strPriority := strconv.Itoa(priority) setACL, err := c.newACLWithoutCheck(pgName, direction, strPriority, m, aclAction, tier, options) if err != nil { - return nil, fmt.Errorf("new ingress acl for port group %s: %v", pgName, err) + return nil, fmt.Errorf("new ingress acl for port group %s: %w", pgName, err) } acls = append(acls, setACL) @@ -1372,7 +1372,7 @@ func newAnpACLMatch(pgName, asName, protocol, direction string, rulePorts []v1al oneMatch := NewAndACLMatch( selectIPMatch, - NewACLMatch(protocolKey, "==", fmt.Sprintf("%d", port.PortNumber.Port), ""), + NewACLMatch(protocolKey, "==", strconv.Itoa(int(port.PortNumber.Port)), ""), ) matches = append(matches, oneMatch.String()) case port.PortRange != nil: @@ -1381,7 +1381,7 @@ func newAnpACLMatch(pgName, asName, protocol, direction string, rulePorts []v1al severalMatch := NewAndACLMatch( selectIPMatch, - NewACLMatch(protocolKey, "<=", fmt.Sprintf("%d", port.PortRange.Start), fmt.Sprintf("%d", port.PortRange.End)), + NewACLMatch(protocolKey, "<=", strconv.Itoa(int(port.PortRange.Start)), strconv.Itoa(int(port.PortRange.End))), ) matches = append(matches, severalMatch.String()) default: diff --git a/pkg/ovs/ovn-nb-address_set.go b/pkg/ovs/ovn-nb-address_set.go index 941fab810a5..798bb74194f 100644 --- a/pkg/ovs/ovn-nb-address_set.go +++ b/pkg/ovs/ovn-nb-address_set.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "net" "strings" @@ -39,11 +40,11 @@ func (c *OVNNbClient) CreateAddressSet(asName string, externalIDs map[string]str ops, err := c.ovsDbClient.Create(as) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for creating address set %s: %v", asName, err) + return fmt.Errorf("generate operations for creating address set %s: %w", asName, err) } if err = c.Transact("as-add", ops); err != nil { - return fmt.Errorf("create address set %s: %v", asName, err) + return fmt.Errorf("create address set %s: %w", asName, err) } return nil @@ -55,7 +56,7 @@ func (c *OVNNbClient) AddressSetUpdateAddress(asName string, addresses ...string as, err := c.GetAddressSet(asName, false) if err != nil { klog.Error(err) - return fmt.Errorf("get address set %s: %v", asName, err) + return fmt.Errorf("get address set %s: %w", asName, err) } // format CIDR to keep addresses the same in both nb and sb @@ -77,7 +78,7 @@ func (c *OVNNbClient) AddressSetUpdateAddress(asName string, addresses ...string as.Addresses = addresses if err := c.UpdateAddressSet(as, &as.Addresses); err != nil { - return fmt.Errorf("set address set %s addresses %v: %v", asName, addresses, err) + return fmt.Errorf("set address set %s addresses %v: %w", asName, addresses, err) } return nil @@ -86,18 +87,18 @@ func (c *OVNNbClient) AddressSetUpdateAddress(asName string, addresses ...string // UpdateAddressSet update address set func (c *OVNNbClient) UpdateAddressSet(as *ovnnb.AddressSet, fields ...interface{}) error { if as == nil { - return fmt.Errorf("address_set is nil") + return errors.New("address_set is nil") } op, err := c.Where(as).Update(as, fields...) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for updating address set %s: %v", as.Name, err) + return fmt.Errorf("generate operations for updating address set %s: %w", as.Name, err) } if err = c.Transact("as-update", op); err != nil { klog.Error(err) - return fmt.Errorf("update address set %s: %v", as.Name, err) + return fmt.Errorf("update address set %s: %w", as.Name, err) } return nil @@ -107,7 +108,7 @@ func (c *OVNNbClient) DeleteAddressSet(asName string) error { as, err := c.GetAddressSet(asName, true) if err != nil { klog.Error(err) - return fmt.Errorf("get address set %s: %v", asName, err) + return fmt.Errorf("get address set %s: %w", asName, err) } // not found, skip @@ -122,7 +123,7 @@ func (c *OVNNbClient) DeleteAddressSet(asName string) error { } if err := c.Transact("as-del", op); err != nil { - return fmt.Errorf("delete address set %s: %v", asName, err) + return fmt.Errorf("delete address set %s: %w", asName, err) } return nil @@ -138,11 +139,11 @@ func (c *OVNNbClient) DeleteAddressSets(externalIDs map[string]string) error { op, err := c.WhereCache(addressSetFilter(externalIDs)).Delete() if err != nil { klog.Error(err) - return fmt.Errorf("generate operation for deleting address sets with external IDs %v: %v", externalIDs, err) + return fmt.Errorf("generate operation for deleting address sets with external IDs %v: %w", externalIDs, err) } if err := c.Transact("ass-del", op); err != nil { - return fmt.Errorf("delete address sets with external IDs %v: %v", externalIDs, err) + return fmt.Errorf("delete address sets with external IDs %v: %w", externalIDs, err) } return nil @@ -155,11 +156,11 @@ func (c *OVNNbClient) GetAddressSet(asName string, ignoreNotFound bool) (*ovnnb. as := &ovnnb.AddressSet{Name: asName} if err := c.ovsDbClient.Get(ctx, as); err != nil { - if ignoreNotFound && err == client.ErrNotFound { + if ignoreNotFound && errors.Is(err, client.ErrNotFound) { return nil, nil } klog.Error(err) - return nil, fmt.Errorf("get address set %s: %v", asName, err) + return nil, fmt.Errorf("get address set %s: %w", asName, err) } return as, nil @@ -178,7 +179,7 @@ func (c *OVNNbClient) ListAddressSets(externalIDs map[string]string) ([]ovnnb.Ad asList := make([]ovnnb.AddressSet, 0) if err := c.WhereCache(addressSetFilter(externalIDs)).List(ctx, &asList); err != nil { - return nil, fmt.Errorf("list address set: %v", err) + return nil, fmt.Errorf("list address set: %w", err) } return asList, nil diff --git a/pkg/ovs/ovn-nb-bfd.go b/pkg/ovs/ovn-nb-bfd.go index 3adfc77fa04..2ea3fa5d910 100644 --- a/pkg/ovs/ovn-nb-bfd.go +++ b/pkg/ovs/ovn-nb-bfd.go @@ -25,7 +25,7 @@ func (c *OVNNbClient) ListBFDs(lrpName, dstIP string) ([]ovnnb.BFD, error) { } return dstIP == "" || bfd.DstIP == dstIP }).List(ctx, &bfdList); err != nil { - err := fmt.Errorf("failed to list BFD with logical_port=%s and dst_ip=%s: %v", lrpName, dstIP, err) + err := fmt.Errorf("failed to list BFD with logical_port=%s and dst_ip=%s: %w", lrpName, dstIP, err) klog.Error(err) return nil, err } @@ -44,7 +44,7 @@ func (c *OVNNbClient) ListDownBFDs(dstIP string) ([]ovnnb.BFD, error) { } return false }).List(ctx, &bfdList); err != nil { - err := fmt.Errorf("failed to list down BFDs: %v", err) + err := fmt.Errorf("failed to list down BFDs: %w", err) klog.Error(err) return nil, err } @@ -60,7 +60,7 @@ func (c *OVNNbClient) ListUpBFDs(dstIP string) ([]ovnnb.BFD, error) { if err := c.ovsDbClient.WhereCache(func(bfd *ovnnb.BFD) bool { return bfd.DstIP == dstIP && *bfd.Status == ovnnb.BFDStatusUp }).List(ctx, &bfdList); err != nil { - err := fmt.Errorf("failed to list up BFDs: %v", err) + err := fmt.Errorf("failed to list up BFDs: %w", err) klog.Error(err) return nil, err } @@ -87,18 +87,18 @@ func (c *OVNNbClient) CreateBFD(lrpName, dstIP string, minRx, minTx, detectMult } ops, err := c.Create(bfd) if err != nil { - err := fmt.Errorf("failed to generate operations for BFD creation with logical_port=%s and dst_ip=%s: %v", lrpName, dstIP, err) + err := fmt.Errorf("failed to generate operations for BFD creation with logical_port=%s and dst_ip=%s: %w", lrpName, dstIP, err) klog.Error(err) return nil, err } if err = c.Transact("bfd-add", ops); err != nil { - err := fmt.Errorf("failed to create BFD with logical_port=%s and dst_ip=%s: %v", lrpName, dstIP, err) + err := fmt.Errorf("failed to create BFD with logical_port=%s and dst_ip=%s: %w", lrpName, dstIP, err) klog.Error(err) return nil, err } if bfdList, err = c.ListBFDs(lrpName, dstIP); err != nil { - err := fmt.Errorf("failed to list BFDs: %v", err) + err := fmt.Errorf("failed to list BFDs: %w", err) klog.Error(err) return nil, err } @@ -112,12 +112,12 @@ func (c *OVNNbClient) CreateBFD(lrpName, dstIP string, minRx, minTx, detectMult func (c *OVNNbClient) UpdateBFD(bfd *ovnnb.BFD, fields ...interface{}) error { op, err := c.ovsDbClient.Where(bfd).Update(bfd, fields...) if err != nil { - err := fmt.Errorf("failed to generate bfd update operations for lrp %s with fields %v: %v", bfd.LogicalPort, fields, err) + err := fmt.Errorf("failed to generate bfd update operations for lrp %s with fields %v: %w", bfd.LogicalPort, fields, err) klog.Error(err) return err } if err = c.Transact("bfd-update", op); err != nil { - err := fmt.Errorf("failed to update bfd %s for lrp %s: %v", bfd.UUID, bfd.LogicalPort, err) + err := fmt.Errorf("failed to update bfd %s for lrp %s: %w", bfd.UUID, bfd.LogicalPort, err) klog.Error(err) return err } @@ -136,13 +136,13 @@ func (c *OVNNbClient) DeleteBFD(lrpName, dstIP string) error { for _, bfd := range bfdList { ops, err := c.Where(&bfd).Delete() if err != nil { - err := fmt.Errorf("failed to generate operations for BFD deletion with UUID %s: %v", bfd.UUID, err) + err := fmt.Errorf("failed to generate operations for BFD deletion with UUID %s: %w", bfd.UUID, err) klog.Error(err) return err } klog.Infof("delete lrp %s BFD dst ip %s", lrpName, bfd.DstIP) if err = c.Transact("bfd-del", ops); err != nil { - err := fmt.Errorf("failed to delete BFD with with UUID %s: %v", bfd.UUID, err) + err := fmt.Errorf("failed to delete BFD with with UUID %s: %w", bfd.UUID, err) klog.Error(err) return err } diff --git a/pkg/ovs/ovn-nb-dhcp_options.go b/pkg/ovs/ovn-nb-dhcp_options.go index 0cf963c7003..46af2300724 100644 --- a/pkg/ovs/ovn-nb-dhcp_options.go +++ b/pkg/ovs/ovn-nb-dhcp_options.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "strings" @@ -28,12 +29,12 @@ func (c *OVNNbClient) CreateDHCPOptions(lsName, cidr, options string) error { op, err := c.ovsDbClient.Create(dhcpOpt) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for creating dhcp options 'cidr %s options %s': %v", cidr, options, err) + return fmt.Errorf("generate operations for creating dhcp options 'cidr %s options %s': %w", cidr, options, err) } if err = c.Transact("dhcp-create", op); err != nil { klog.Error(err) - return fmt.Errorf("create dhcp options with cidr %q options %q: %v", cidr, options, err) + return fmt.Errorf("create dhcp options with cidr %q options %q: %w", cidr, options, err) } return nil @@ -51,7 +52,7 @@ func (c *OVNNbClient) UpdateDHCPOptions(subnet *kubeovnv1.Subnet, mtu int) (*DHC /* delete dhcp options */ if !enableDHCP { if err := c.DeleteDHCPOptions(lsName, subnet.Spec.Protocol); err != nil { - return nil, fmt.Errorf("delete dhcp options for logical switch %s: %v", lsName, err) + return nil, fmt.Errorf("delete dhcp options for logical switch %s: %w", lsName, err) } return &DHCPOptionsUUIDs{}, nil } @@ -77,7 +78,7 @@ func (c *OVNNbClient) UpdateDHCPOptions(subnet *kubeovnv1.Subnet, mtu int) (*DHC dhcpV4OptUUID, err := c.updateDHCPv4Options(lsName, v4CIDR, v4Gateway, subnet.Spec.DHCPv4Options, mtu) if err != nil { klog.Error(err) - return nil, fmt.Errorf("update IPv4 dhcp options for logical switch %s: %v", lsName, err) + return nil, fmt.Errorf("update IPv4 dhcp options for logical switch %s: %w", lsName, err) } dhcpOptionsUUIDs.DHCPv4OptionsUUID = dhcpV4OptUUID } @@ -86,7 +87,7 @@ func (c *OVNNbClient) UpdateDHCPOptions(subnet *kubeovnv1.Subnet, mtu int) (*DHC dhcpV6OptUUID, err := c.updateDHCPv6Options(lsName, v6CIDR, subnet.Spec.DHCPv6Options) if err != nil { klog.Error(err) - return nil, fmt.Errorf("update IPv6 dhcp options for logical switch %s: %v", lsName, err) + return nil, fmt.Errorf("update IPv6 dhcp options for logical switch %s: %w", lsName, err) } dhcpOptionsUUIDs.DHCPv6OptionsUUID = dhcpV6OptUUID } @@ -135,7 +136,7 @@ func (c *OVNNbClient) updateDHCPv4Options(lsName, cidr, gateway, options string, /* create */ if err := c.CreateDHCPOptions(lsName, cidr, options); err != nil { - return "", fmt.Errorf("create dhcp options: %v", err) + return "", fmt.Errorf("create dhcp options: %w", err) } dhcpOpt, err = c.GetDHCPOptions(lsName, protocol, false) @@ -188,7 +189,7 @@ func (c *OVNNbClient) updateDHCPv6Options(lsName, cidr, options string) (uuid st /* create */ if err := c.CreateDHCPOptions(lsName, cidr, options); err != nil { - return "", fmt.Errorf("create dhcp options: %v", err) + return "", fmt.Errorf("create dhcp options: %w", err) } dhcpOpt, err = c.GetDHCPOptions(lsName, protocol, false) @@ -203,17 +204,17 @@ func (c *OVNNbClient) updateDHCPv6Options(lsName, cidr, options string) (uuid st // updateDHCPOptions update dhcp options func (c *OVNNbClient) updateDHCPOptions(dhcpOpt *ovnnb.DHCPOptions, fields ...interface{}) error { if dhcpOpt == nil { - return fmt.Errorf("dhcp_options is nil") + return errors.New("dhcp_options is nil") } op, err := c.ovsDbClient.Where(dhcpOpt).Update(dhcpOpt, fields...) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for updating dhcp options %s: %v", dhcpOpt.UUID, err) + return fmt.Errorf("generate operations for updating dhcp options %s: %w", dhcpOpt.UUID, err) } if err = c.Transact("dhcp-options-update", op); err != nil { - return fmt.Errorf("update dhcp options %s: %v", dhcpOpt.UUID, err) + return fmt.Errorf("update dhcp options %s: %w", dhcpOpt.UUID, err) } return nil @@ -236,7 +237,7 @@ func (c *OVNNbClient) DeleteDHCPOptionsByUUIDs(uuidList ...string) error { } if err := c.Transact("dhcp-options-del", ops); err != nil { - return fmt.Errorf("delete dhcp options %v: %v", uuidList, err) + return fmt.Errorf("delete dhcp options %v: %w", uuidList, err) } return nil @@ -255,12 +256,12 @@ func (c *OVNNbClient) DeleteDHCPOptions(lsName, protocol string) error { op, err := c.WhereCache(dhcpOptionsFilter(true, externalIDs)).Delete() if err != nil { klog.Error(err) - return fmt.Errorf("generate operation for deleting dhcp options: %v", err) + return fmt.Errorf("generate operation for deleting dhcp options: %w", err) } if err = c.Transact("dhcp-options-del", op); err != nil { klog.Error(err) - return fmt.Errorf("delete logical switch %s dhcp options: %v", lsName, err) + return fmt.Errorf("delete logical switch %s dhcp options: %w", lsName, err) } return nil @@ -270,11 +271,11 @@ func (c *OVNNbClient) DeleteDHCPOptions(lsName, protocol string) error { // a dhcp options is uniquely identified by switch(lsName) and protocol 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") + return nil, errors.New("the logical router name is required") } if protocol != kubeovnv1.ProtocolIPv4 && protocol != kubeovnv1.ProtocolIPv6 { - return nil, fmt.Errorf("protocol must be IPv4 or IPv6") + return nil, errors.New("protocol must be IPv4 or IPv6") } dhcpOptList, err := c.ListDHCPOptions(true, map[string]string{ @@ -283,7 +284,7 @@ func (c *OVNNbClient) GetDHCPOptions(lsName, protocol string, ignoreNotFound boo }) if err != nil { klog.Error(err) - return nil, fmt.Errorf("get logical switch %s %s dhcp options: %v", lsName, protocol, err) + return nil, fmt.Errorf("get logical switch %s %s dhcp options: %w", lsName, protocol, err) } // not found @@ -292,7 +293,7 @@ func (c *OVNNbClient) GetDHCPOptions(lsName, protocol string, ignoreNotFound boo return nil, nil } - return nil, fmt.Errorf("not found logical switch %s %s dhcp options: %v", lsName, protocol, err) + return nil, fmt.Errorf("not found logical switch %s %s dhcp options: %w", lsName, protocol, err) } if len(dhcpOptList) > 1 { @@ -310,7 +311,7 @@ func (c *OVNNbClient) ListDHCPOptions(needVendorFilter bool, externalIDs map[str dhcpOptList := make([]ovnnb.DHCPOptions, 0) if err := c.WhereCache(dhcpOptionsFilter(needVendorFilter, externalIDs)).List(ctx, &dhcpOptList); err != nil { - return nil, fmt.Errorf("list dhcp options with external IDs %v: %v", externalIDs, err) + return nil, fmt.Errorf("list dhcp options with external IDs %v: %w", externalIDs, err) } return dhcpOptList, nil diff --git a/pkg/ovs/ovn-nb-gateway_chassis.go b/pkg/ovs/ovn-nb-gateway_chassis.go index 20c9bc1db3d..3e41c2d453a 100644 --- a/pkg/ovs/ovn-nb-gateway_chassis.go +++ b/pkg/ovs/ovn-nb-gateway_chassis.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "github.com/ovn-org/libovsdb/client" @@ -17,13 +18,13 @@ import ( func (c *OVNNbClient) CreateGatewayChassises(lrpName string, chassises ...string) error { op, err := c.CreateGatewayChassisesOp(lrpName, chassises) if err != nil { - err := fmt.Errorf("generate operations for creating gateway chassis %v", err) + err := fmt.Errorf("generate operations for creating gateway chassis %w", err) klog.Error(err) return err } if err = c.Transact("gateway-chassises-add", op); err != nil { - err := fmt.Errorf("create gateway chassis %v for logical router port %s: %v", chassises, lrpName, err) + err := fmt.Errorf("create gateway chassis %v for logical router port %s: %w", chassises, lrpName, err) klog.Error(err) return err } @@ -35,12 +36,12 @@ func (c *OVNNbClient) CreateGatewayChassises(lrpName string, chassises ...string func (c *OVNNbClient) UpdateGatewayChassis(gwChassis *ovnnb.GatewayChassis, fields ...interface{}) error { op, err := c.ovsDbClient.Where(gwChassis).Update(gwChassis, fields...) if err != nil { - err := fmt.Errorf("failed to generate operations for gateway chassis %s with fields %v: %v", gwChassis.ChassisName, fields, err) + err := fmt.Errorf("failed to generate operations for gateway chassis %s with fields %v: %w", gwChassis.ChassisName, fields, err) klog.Error(err) return err } if err = c.Transact("gateway-chassis-update", op); err != nil { - err := fmt.Errorf("failed to update gateway chassis %s: %v", gwChassis.ChassisName, err) + err := fmt.Errorf("failed to update gateway chassis %s: %w", gwChassis.ChassisName, err) klog.Error(err) return err } @@ -83,7 +84,7 @@ func (c *OVNNbClient) DeleteGatewayChassises(lrpName string, chassises []string) } if err := c.Transact("gateway-chassises-delete", ops); err != nil { - return fmt.Errorf("delete gateway chassises %v from logical router port %s: %v", chassises, lrpName, err) + return fmt.Errorf("delete gateway chassises %v from logical router port %s: %w", chassises, lrpName, err) } return nil @@ -101,10 +102,10 @@ func (c *OVNNbClient) ListGatewayChassisByLogicalRouterPort(lrpName string, igno } return false }).List(ctx, &gwChassisList); err != nil { - if ignoreNotFound && err == client.ErrNotFound { + if ignoreNotFound && errors.Is(err, client.ErrNotFound) { return nil, nil } - err = fmt.Errorf("failed to list gw chassis for lrp %s: %v", lrpName, err) + err = fmt.Errorf("failed to list gw chassis for lrp %s: %w", lrpName, err) klog.Error(err) return nil, err } @@ -119,11 +120,11 @@ func (c *OVNNbClient) GetGatewayChassis(name string, ignoreNotFound bool) (*ovnn gwChassis := &ovnnb.GatewayChassis{Name: name} if err := c.Get(ctx, gwChassis); err != nil { - if ignoreNotFound && err == client.ErrNotFound { + if ignoreNotFound && errors.Is(err, client.ErrNotFound) { return nil, nil } - return nil, fmt.Errorf("get gateway chassis %s: %v", name, err) + return nil, fmt.Errorf("get gateway chassis %s: %w", name, err) } return gwChassis, nil @@ -196,7 +197,7 @@ func (c *OVNNbClient) CreateGatewayChassisesOp(lrpName string, chassises []strin gwChassisCreateop, err := c.Create(models...) if err != nil { klog.Error(err) - return nil, fmt.Errorf("generate operations for creating gateway chassis %v", err) + return nil, fmt.Errorf("generate operations for creating gateway chassis %w", err) } /* add gateway chassis to logical router port */ diff --git a/pkg/ovs/ovn-nb-load_balancer.go b/pkg/ovs/ovn-nb-load_balancer.go index bb8b67870e2..b17eeff3ed4 100644 --- a/pkg/ovs/ovn-nb-load_balancer.go +++ b/pkg/ovs/ovn-nb-load_balancer.go @@ -49,11 +49,11 @@ func (c *OVNNbClient) CreateLoadBalancer(lbName, protocol, selectFields string) } if ops, err = c.ovsDbClient.Create(lb); err != nil { - return fmt.Errorf("generate operations for creating load balancer %s: %v", lbName, err) + return fmt.Errorf("generate operations for creating load balancer %s: %w", lbName, err) } if err = c.Transact("lb-add", ops); err != nil { - return fmt.Errorf("create load balancer %s: %v", lbName, err) + return fmt.Errorf("create load balancer %s: %w", lbName, err) } return nil } @@ -66,11 +66,11 @@ func (c *OVNNbClient) UpdateLoadBalancer(lb *ovnnb.LoadBalancer, fields ...inter ) if ops, err = c.ovsDbClient.Where(lb).Update(lb, fields...); err != nil { - return fmt.Errorf("generate operations for updating load balancer %s: %v", lb.Name, err) + return fmt.Errorf("generate operations for updating load balancer %s: %w", lb.Name, err) } if err = c.Transact("lb-update", ops); err != nil { - return fmt.Errorf("update load balancer %s: %v", lb.Name, err) + return fmt.Errorf("update load balancer %s: %w", lb.Name, err) } return nil } @@ -120,12 +120,12 @@ func (c *OVNNbClient) LoadBalancerAddVip(lbName, vip string, backends ...string) return mutations }, ); err != nil { - return fmt.Errorf("failed to generate operations when adding vip %s with backends %v to load balancers %s: %v", vip, backends, lbName, err) + return fmt.Errorf("failed to generate operations when adding vip %s with backends %v to load balancers %s: %w", vip, backends, lbName, err) } if ops != nil { if err = c.Transact("lb-add", ops); err != nil { - return fmt.Errorf("failed to add vip %s with backends %v to load balancers %s: %v", vip, backends, lbName, err) + return fmt.Errorf("failed to add vip %s with backends %v to load balancers %s: %w", vip, backends, lbName, err) } } return nil @@ -177,14 +177,14 @@ func (c *OVNNbClient) LoadBalancerDeleteVip(lbName, vipEndpoint string, ignoreHe }, ) if err != nil { - return fmt.Errorf("failed to generate operations when deleting vip %s from load balancers %s: %v", vipEndpoint, lbName, err) + return fmt.Errorf("failed to generate operations when deleting vip %s from load balancers %s: %w", vipEndpoint, lbName, err) } if len(ops) == 0 { return nil } if err = c.Transact("lb-add", ops); err != nil { - return fmt.Errorf("failed to delete vip %s from load balancers %s: %v", vipEndpoint, lbName, err) + return fmt.Errorf("failed to delete vip %s from load balancers %s: %w", vipEndpoint, lbName, err) } return nil } @@ -215,7 +215,7 @@ func (c *OVNNbClient) SetLoadBalancerAffinityTimeout(lbName string, timeout int) lb.Options = options if err = c.UpdateLoadBalancer(lb, &lb.Options); err != nil { - return fmt.Errorf("failed to set affinity timeout of lb %s to %d: %v", lbName, timeout, err) + return fmt.Errorf("failed to set affinity timeout of lb %s to %d: %w", lbName, timeout, err) } return nil } @@ -235,12 +235,12 @@ func (c *OVNNbClient) DeleteLoadBalancers(filter func(lb *ovnnb.LoadBalancer) bo return true }, ).Delete(); err != nil { - return fmt.Errorf("generate operations for delete load balancers: %v", err) + return fmt.Errorf("generate operations for delete load balancers: %w", err) } if err = c.Transact("lb-del", ops); err != nil { klog.Errorf("failed to del lbs: %v", err) - return fmt.Errorf("delete load balancers : %v", err) + return fmt.Errorf("delete load balancers : %w", err) } return nil } @@ -260,7 +260,7 @@ func (c *OVNNbClient) DeleteLoadBalancer(lbName string) error { if err = c.Transact("lb-del", ops); err != nil { klog.Errorf("failed to del lb: %v", err) - return fmt.Errorf("delete load balancer %s: %v", lbName, err) + return fmt.Errorf("delete load balancer %s: %w", lbName, err) } return nil } @@ -282,7 +282,7 @@ func (c *OVNNbClient) GetLoadBalancer(lbName string, ignoreNotFound bool) (*ovnn return lb.Name == lbName }, ).List(ctx, &lbList); err != nil { - return nil, fmt.Errorf("failed to list load balancer %q: %v", lbName, err) + return nil, fmt.Errorf("failed to list load balancer %q: %w", lbName, err) } switch { @@ -325,7 +325,7 @@ func (c *OVNNbClient) ListLoadBalancers(filter func(lb *ovnnb.LoadBalancer) bool return true }, ).List(ctx, &lbList); err != nil { - return nil, fmt.Errorf("failed to list load balancer: %v", err) + return nil, fmt.Errorf("failed to list load balancer: %w", err) } return lbList, nil } @@ -359,7 +359,7 @@ func (c *OVNNbClient) LoadBalancerOp(lbName string, mutationsFunc ...func(lb *ov if ops, err = c.ovsDbClient.Where(lb).Mutate(lb, mutations...); err != nil { klog.Error(err) - return nil, fmt.Errorf("generate operations for mutating load balancer %s: %v", lb.Name, err) + return nil, fmt.Errorf("generate operations for mutating load balancer %s: %w", lb.Name, err) } return ops, nil } @@ -411,11 +411,11 @@ func (c *OVNNbClient) LoadBalancerAddIPPortMapping(lbName, vipEndpoint string, m } }, ); err != nil { - return fmt.Errorf("failed to generate operations when adding ip port mapping with vip %v to load balancers %s: %v", vipEndpoint, lbName, err) + return fmt.Errorf("failed to generate operations when adding ip port mapping with vip %v to load balancers %s: %w", vipEndpoint, lbName, err) } if err = c.Transact("lb-add", ops); err != nil { - return fmt.Errorf("failed to add ip port mapping with vip %v to load balancers %s: %v", vipEndpoint, lbName, err) + return fmt.Errorf("failed to add ip port mapping with vip %v to load balancers %s: %w", vipEndpoint, lbName, err) } return nil } @@ -445,7 +445,7 @@ func (c *OVNNbClient) LoadBalancerDeleteIPPortMapping(lbName, vipEndpoint string } if vip, _, err = net.SplitHostPort(vipEndpoint); err != nil { - err := fmt.Errorf("failed to split host port: %v", err) + err := fmt.Errorf("failed to split host port: %w", err) klog.Error(err) return err } @@ -470,13 +470,13 @@ func (c *OVNNbClient) LoadBalancerDeleteIPPortMapping(lbName, vipEndpoint string } }, ); err != nil { - return fmt.Errorf("failed to generate operations when deleting ip port mapping %s from load balancers %s: %v", vipEndpoint, lbName, err) + return fmt.Errorf("failed to generate operations when deleting ip port mapping %s from load balancers %s: %w", vipEndpoint, lbName, err) } if len(ops) == 0 { return nil } if err = c.Transact("lb-del", ops); err != nil { - return fmt.Errorf("failed to delete ip port mappings %s from load balancer %s: %v", vipEndpoint, lbName, err) + return fmt.Errorf("failed to delete ip port mappings %s from load balancer %s: %w", vipEndpoint, lbName, err) } return nil } @@ -497,10 +497,10 @@ func (c *OVNNbClient) LoadBalancerUpdateIPPortMapping(lbName, vipEndpoint string }, ) if err != nil { - return fmt.Errorf("failed to generate operations when adding ip port mapping with vip %v to load balancers %s: %v", vipEndpoint, lbName, err) + return fmt.Errorf("failed to generate operations when adding ip port mapping with vip %v to load balancers %s: %w", vipEndpoint, lbName, err) } if err = c.Transact("lb-add", ops); err != nil { - return fmt.Errorf("failed to add ip port mapping with vip %v to load balancers %s: %v", vipEndpoint, lbName, err) + return fmt.Errorf("failed to add ip port mapping with vip %v to load balancers %s: %w", vipEndpoint, lbName, err) } } return nil @@ -550,13 +550,13 @@ func (c *OVNNbClient) LoadBalancerDeleteHealthCheck(lbName, uuid string) error { }, ) if err != nil { - return fmt.Errorf("failed to generate operations when deleting health check %s from load balancers %s: %v", uuid, lbName, err) + return fmt.Errorf("failed to generate operations when deleting health check %s from load balancers %s: %w", uuid, lbName, err) } if len(ops) == 0 { return nil } if err = c.Transact("lb-hc-del", ops); err != nil { - return fmt.Errorf("failed to delete health check %s from load balancers %s: %v", uuid, lbName, err) + return fmt.Errorf("failed to delete health check %s from load balancers %s: %w", uuid, lbName, err) } } diff --git a/pkg/ovs/ovn-nb-load_balancer_health_check.go b/pkg/ovs/ovn-nb-load_balancer_health_check.go index 15482ece3e3..41a026f7951 100644 --- a/pkg/ovs/ovn-nb-load_balancer_health_check.go +++ b/pkg/ovs/ovn-nb-load_balancer_health_check.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "slices" @@ -16,7 +17,7 @@ import ( func (c *OVNNbClient) AddLoadBalancerHealthCheck(lbName, vipEndpoint string, externals map[string]string) error { lbhc, err := c.newLoadBalancerHealthCheck(lbName, vipEndpoint, externals) if err != nil { - err := fmt.Errorf("failed to new lb health check: %v", err) + err := fmt.Errorf("failed to new lb health check: %w", err) klog.Error(err) return err } @@ -32,18 +33,18 @@ func (c *OVNNbClient) newLoadBalancerHealthCheck(lbName, vipEndpoint string, ext ) if len(lbName) == 0 { - err = fmt.Errorf("the lb name is required") + err = errors.New("the lb name is required") klog.Error(err) return nil, err } if len(vipEndpoint) == 0 { - err = fmt.Errorf("the vip endpoint is required") + err = errors.New("the vip endpoint is required") klog.Error(err) return nil, err } if exists, err = c.LoadBalancerHealthCheckExists(lbName, vipEndpoint); err != nil { - err := fmt.Errorf("get lb health check %s: %v", vipEndpoint, err) + err := fmt.Errorf("get lb health check %s: %w", vipEndpoint, err) klog.Error(err) return nil, err } @@ -88,19 +89,19 @@ func (c *OVNNbClient) CreateLoadBalancerHealthCheck(lbName, vipEndpoint string, if createLbhcOp, err = c.ovsDbClient.Create(models...); err != nil { klog.Error(err) - return fmt.Errorf("generate operations for creating lbhc: %v", err) + return fmt.Errorf("generate operations for creating lbhc: %w", err) } ops = append(ops, createLbhcOp...) if lbHcAddOp, err = c.LoadBalancerUpdateHealthCheckOp(lbName, lbhcUUIDs, ovsdb.MutateOperationInsert); err != nil { - err = fmt.Errorf("generate operations for adding lbhc to lb %s: %v", lbName, err) + err = fmt.Errorf("generate operations for adding lbhc to lb %s: %w", lbName, err) klog.Error(err) return err } ops = append(ops, lbHcAddOp...) if err = c.Transact("lbhc-add", ops); err != nil { - err = fmt.Errorf("failed to create lb health check for lb %s vip %s: %v", lbName, vipEndpoint, err) + err = fmt.Errorf("failed to create lb health check for lb %s vip %s: %w", lbName, vipEndpoint, err) klog.Error(err) return err } @@ -116,11 +117,11 @@ func (c *OVNNbClient) UpdateLoadBalancerHealthCheck(lbhc *ovnnb.LoadBalancerHeal ) if op, err = c.ovsDbClient.Where(lbhc).Update(lbhc, fields...); err != nil { - return fmt.Errorf("generate operations for updating lb health check %s: %v", lbhc.Vip, err) + return fmt.Errorf("generate operations for updating lb health check %s: %w", lbhc.Vip, err) } if err = c.Transact("lbhc-update", op); err != nil { - return fmt.Errorf("update lb health check %s: %v", lbhc.Vip, err) + return fmt.Errorf("update lb health check %s: %w", lbhc.Vip, err) } return nil @@ -137,11 +138,11 @@ func (c *OVNNbClient) DeleteLoadBalancerHealthChecks(filter func(lb *ovnnb.LoadB }, ).Delete() if err != nil { - return fmt.Errorf("generate operations for delete lb health checks: %v", err) + return fmt.Errorf("generate operations for delete lb health checks: %w", err) } if err := c.Transact("lbhc-del", op); err != nil { - return fmt.Errorf("delete lb health checks : %v", err) + return fmt.Errorf("delete lb health checks : %w", err) } return nil @@ -161,7 +162,7 @@ func (c *OVNNbClient) DeleteLoadBalancerHealthCheck(lbName, vip string) error { } if err = c.Transact("lbhc-del", op); err != nil { - return fmt.Errorf("delete lb %s: %v", lbName, err) + return fmt.Errorf("delete lb %s: %w", lbName, err) } return nil @@ -194,7 +195,7 @@ func (c *OVNNbClient) GetLoadBalancerHealthCheck(lbName, vipEndpoint string, ign healthCheck.Vip == vipEndpoint }, ).List(ctx, &healthCheckList); err != nil { - err = fmt.Errorf("failed to list lb health check lb health check by vip %q: %v", vipEndpoint, err) + err = fmt.Errorf("failed to list lb health check lb health check by vip %q: %w", vipEndpoint, err) klog.Error(err) return nil, nil, err } @@ -235,7 +236,7 @@ func (c *OVNNbClient) ListLoadBalancerHealthChecks(filter func(lbhc *ovnnb.LoadB return true }, ).List(ctx, &lbhcList); err != nil { - return nil, fmt.Errorf("list lb health check: %v", err) + return nil, fmt.Errorf("list lb health check: %w", err) } return lbhcList, nil diff --git a/pkg/ovs/ovn-nb-logical_router.go b/pkg/ovs/ovn-nb-logical_router.go index 4506e721229..e91b89c3884 100644 --- a/pkg/ovs/ovn-nb-logical_router.go +++ b/pkg/ovs/ovn-nb-logical_router.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "slices" "strings" @@ -34,11 +35,11 @@ func (c *OVNNbClient) CreateLogicalRouter(lrName string) error { op, err := c.ovsDbClient.Create(lr) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for creating logical router %s: %v", lrName, err) + return fmt.Errorf("generate operations for creating logical router %s: %w", lrName, err) } if err := c.Transact("lr-add", op); err != nil { - return fmt.Errorf("create logical router %s: %v", lrName, err) + return fmt.Errorf("create logical router %s: %w", lrName, err) } return nil @@ -53,7 +54,7 @@ func (c *OVNNbClient) UpdateLogicalRouter(lr *ovnnb.LogicalRouter, fields ...int } if err = c.Transact("lr-update", op); err != nil { - return fmt.Errorf("update logical router %s: %v", lr.Name, err) + return fmt.Errorf("update logical router %s: %w", lr.Name, err) } return nil @@ -64,7 +65,7 @@ func (c *OVNNbClient) DeleteLogicalRouter(lrName string) error { lr, err := c.GetLogicalRouter(lrName, true) if err != nil { klog.Error(err) - return fmt.Errorf("get logical router %s when delete: %v", lrName, err) + return fmt.Errorf("get logical router %s when delete: %w", lrName, err) } // not found, skip @@ -79,7 +80,7 @@ func (c *OVNNbClient) DeleteLogicalRouter(lrName string) error { } if err := c.Transact("lr-del", op); err != nil { - return fmt.Errorf("delete logical router %s: %v", lrName, err) + return fmt.Errorf("delete logical router %s: %w", lrName, err) } return nil @@ -95,7 +96,7 @@ func (c *OVNNbClient) GetLogicalRouter(lrName string, ignoreNotFound bool) (*ovn if err := c.ovsDbClient.WhereCache(func(lr *ovnnb.LogicalRouter) bool { return lr.Name == lrName }).List(ctx, &lrList); err != nil { - return nil, fmt.Errorf("list logical router %q: %v", lrName, err) + return nil, fmt.Errorf("list logical router %q: %w", lrName, err) } // not found @@ -137,7 +138,7 @@ func (c *OVNNbClient) ListLogicalRouter(needVendorFilter bool, filter func(lr *o return true }).List(ctx, &lrList); err != nil { - return nil, fmt.Errorf("list logical router: %v", err) + return nil, fmt.Errorf("list logical router: %w", err) } return lrList, nil @@ -177,11 +178,11 @@ func (c *OVNNbClient) LogicalRouterUpdateLoadBalancers(lrName string, op ovsdb.M ops, err := c.LogicalRouterOp(lrName, mutation) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for logical router %s update lbs %v: %v", lrName, lbNames, err) + return fmt.Errorf("generate operations for logical router %s update lbs %v: %w", lrName, lbNames, err) } if err := c.Transact("lr-lb-update", ops); err != nil { - return fmt.Errorf("logical router %s update lbs %v: %v", lrName, lbNames, err) + return fmt.Errorf("logical router %s update lbs %v: %w", lrName, lbNames, err) } return nil @@ -190,13 +191,13 @@ func (c *OVNNbClient) LogicalRouterUpdateLoadBalancers(lrName string, op ovsdb.M // UpdateLogicalRouterOp generate operations which update logical router func (c *OVNNbClient) UpdateLogicalRouterOp(lr *ovnnb.LogicalRouter, fields ...interface{}) ([]ovsdb.Operation, error) { if lr == nil { - return nil, fmt.Errorf("logical_router is nil") + return nil, errors.New("logical_router is nil") } op, err := c.ovsDbClient.Where(lr).Update(lr, fields...) if err != nil { klog.Error(err) - return nil, fmt.Errorf("generate operations for updating logical router %s: %v", lr.Name, err) + return nil, fmt.Errorf("generate operations for updating logical router %s: %w", lr.Name, err) } return op, nil @@ -214,7 +215,7 @@ func (c *OVNNbClient) LogicalRouterUpdatePortOp(lrName, lrpUUID string, op ovsdb }) if err != nil { klog.Error(err) - return nil, fmt.Errorf("failed to list LR by LRP UUID %s: %v", lrpUUID, err) + return nil, fmt.Errorf("failed to list LR by LRP UUID %s: %w", lrpUUID, err) } if len(lrList) == 0 { err = fmt.Errorf("no LR found for LRP %s", lrpUUID) @@ -308,7 +309,7 @@ func (c *OVNNbClient) LogicalRouterOp(lrName string, mutationsFunc ...func(lr *o lr, err := c.GetLogicalRouter(lrName, false) if err != nil { klog.Error(err) - return nil, fmt.Errorf("get logical router %s: %v", lrName, err) + return nil, fmt.Errorf("get logical router %s: %w", lrName, err) } if len(mutationsFunc) == 0 { @@ -328,7 +329,7 @@ func (c *OVNNbClient) LogicalRouterOp(lrName string, mutationsFunc ...func(lr *o ops, err := c.ovsDbClient.Where(lr).Mutate(lr, mutations...) if err != nil { klog.Error(err) - return nil, fmt.Errorf("generate operations for mutating logical router %s: %v", lrName, err) + return nil, fmt.Errorf("generate operations for mutating logical router %s: %w", lrName, err) } return ops, nil diff --git a/pkg/ovs/ovn-nb-logical_router_policy.go b/pkg/ovs/ovn-nb-logical_router_policy.go index d8a90412b2d..58938f29213 100644 --- a/pkg/ovs/ovn-nb-logical_router_policy.go +++ b/pkg/ovs/ovn-nb-logical_router_policy.go @@ -25,7 +25,7 @@ func (c *OVNNbClient) AddLogicalRouterPolicy(lrName string, priority int, match, } policyList, err := c.listLogicalRouterPoliciesByFilter(lrName, fnFilter) if err != nil { - return fmt.Errorf("get policy priority %d match %s in logical router %s: %v", priority, match, lrName, err) + return fmt.Errorf("get policy priority %d match %s in logical router %s: %w", priority, match, lrName, err) } duplicate := make([]string, 0, len(policyList)) @@ -52,20 +52,20 @@ func (c *OVNNbClient) AddLogicalRouterPolicy(lrName string, priority int, match, klog.Infof("creating lr policy with priority = %d, match = %q, action = %q, nextHops = %q", priority, match, action, nextHops) policy := c.newLogicalRouterPolicy(priority, match, action, nextHops, externalIDs) if err := c.CreateLogicalRouterPolicies(lrName, policy); err != nil { - return fmt.Errorf("add policy to logical router %s: %v", lrName, err) + return fmt.Errorf("add policy to logical router %s: %w", lrName, err) } } else if !maps.Equal(policyFound.ExternalIDs, externalIDs) { policy := ptr.To(*policyFound) policy.ExternalIDs = externalIDs ops, err := c.Where(policy).Update(policy, &policy.ExternalIDs) if err != nil { - err := fmt.Errorf("failed to generate operations for updating logical router policy: %v", err) + err := fmt.Errorf("failed to generate operations for updating logical router policy: %w", err) klog.Error(err) return err } if err = c.Transact("lr-policy-update", ops); err != nil { - err := fmt.Errorf("failed to update logical router policy: %v", err) + err := fmt.Errorf("failed to update logical router policy: %w", err) klog.Error(err) return err } @@ -92,13 +92,13 @@ func (c *OVNNbClient) CreateLogicalRouterPolicies(lrName string, policies ...*ov createPoliciesOp, err := c.ovsDbClient.Create(models...) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for creating policies: %v", err) + return fmt.Errorf("generate operations for creating policies: %w", err) } policyAddOp, err := c.LogicalRouterUpdatePolicyOp(lrName, policyUUIDs, ovsdb.MutateOperationInsert) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for adding policies to logical router %s: %v", lrName, err) + return fmt.Errorf("generate operations for adding policies to logical router %s: %w", lrName, err) } ops := make([]ovsdb.Operation, 0, len(createPoliciesOp)+len(policyAddOp)) @@ -106,7 +106,7 @@ func (c *OVNNbClient) CreateLogicalRouterPolicies(lrName string, policies ...*ov ops = append(ops, policyAddOp...) if err = c.Transact("lr-policies-add", ops); err != nil { - return fmt.Errorf("add policies to %s: %v", lrName, err) + return fmt.Errorf("add policies to %s: %w", lrName, err) } return nil @@ -149,10 +149,10 @@ func (c *OVNNbClient) DeleteLogicalRouterPolicies(lrName string, priority int, e ops, err := c.LogicalRouterUpdatePolicyOp(lrName, policiesUUIDs, ovsdb.MutateOperationDelete) if err != nil { - return fmt.Errorf("generate operations for removing policy %v from logical router %s: %v", policiesUUIDs, lrName, err) + return fmt.Errorf("generate operations for removing policy %v from logical router %s: %w", policiesUUIDs, lrName, err) } if err = c.Transact("lr-policies-del", ops); err != nil { - return fmt.Errorf("delete logical router policy %v from logical router %s: %v", policiesUUIDs, lrName, err) + return fmt.Errorf("delete logical router policy %v from logical router %s: %w", policiesUUIDs, lrName, err) } return nil } @@ -161,10 +161,10 @@ 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 { - return fmt.Errorf("generate operations for removing policy '%s' from logical router %s: %v", uuid, lrName, err) + return fmt.Errorf("generate operations for removing policy '%s' from logical router %s: %w", uuid, lrName, err) } if err = c.Transact("lr-policy-del", ops); err != nil { - return fmt.Errorf("delete logical router policy '%s' from logical router %s: %v", uuid, lrName, err) + return fmt.Errorf("delete logical router policy '%s' from logical router %s: %w", uuid, lrName, err) } return nil } @@ -192,17 +192,17 @@ func (c *OVNNbClient) DeleteLogicalRouterPolicyByNexthop(lrName string, priority 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) + return fmt.Errorf("get logical router %s: %w", lrName, err) } // clear logical router policy lr.Policies = nil ops, err := c.UpdateLogicalRouterOp(lr, &lr.Policies) if err != nil { - return fmt.Errorf("generate operations for clear logical router %s policy: %v", lrName, err) + return fmt.Errorf("generate operations for clear logical router %s policy: %w", lrName, err) } if err = c.Transact("lr-policy-clear", ops); err != nil { - return fmt.Errorf("clear logical router %s policy: %v", lrName, err) + return fmt.Errorf("clear logical router %s policy: %w", lrName, err) } return nil @@ -213,7 +213,7 @@ func (c *OVNNbClient) ClearLogicalRouterPolicy(lrName string) 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") + return nil, errors.New("the logical router name is required") } fnFilter := func(policy *ovnnb.LogicalRouterPolicy) bool { @@ -221,7 +221,7 @@ func (c *OVNNbClient) GetLogicalRouterPolicy(lrName string, priority int, match } policyList, err := c.listLogicalRouterPoliciesByFilter(lrName, fnFilter) if err != nil { - return nil, fmt.Errorf("get policy priority %d match %s in logical router %s: %v", priority, match, lrName, err) + return nil, fmt.Errorf("get policy priority %d match %s in logical router %s: %w", priority, match, lrName, err) } // not found @@ -317,10 +317,10 @@ func (c *OVNNbClient) DeleteRouterPolicy(lr *ovnnb.LogicalRouter, uuid string) e Value: []string{uuid}, }) if err != nil { - return fmt.Errorf("failed to generate delete operations for router %s: %v", uuid, err) + return fmt.Errorf("failed to generate delete operations for router %s: %w", uuid, err) } if err = c.Transact("lr-policy-delete", ops); err != nil { - return fmt.Errorf("failed to delete route policy %s: %v", uuid, err) + return fmt.Errorf("failed to delete route policy %s: %w", uuid, err) } return nil } diff --git a/pkg/ovs/ovn-nb-logical_router_port.go b/pkg/ovs/ovn-nb-logical_router_port.go index 77fbb73a86b..0a182b28594 100644 --- a/pkg/ovs/ovn-nb-logical_router_port.go +++ b/pkg/ovs/ovn-nb-logical_router_port.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "strings" @@ -50,7 +51,7 @@ func (c *OVNNbClient) CreatePeerRouterPort(localRouter, remoteRouter, localRoute } if err = c.Transact("lrp-add", ops); err != nil { - err := fmt.Errorf("create peer router port %s for logical router%s: %v", localRouterPort, localRouter, err) + err := fmt.Errorf("create peer router port %s for logical router%s: %w", localRouterPort, localRouter, err) klog.Error(err) return err } @@ -110,18 +111,18 @@ func (c *OVNNbClient) UpdateLogicalRouterPortOptions(lrpName string, options map // UpdateLogicalRouterPort update logical router port func (c *OVNNbClient) UpdateLogicalRouterPort(lrp *ovnnb.LogicalRouterPort, fields ...interface{}) error { if lrp == nil { - return fmt.Errorf("logical_router_port is nil") + return errors.New("logical_router_port is nil") } op, err := c.Where(lrp).Update(lrp, fields...) if err != nil { - err := fmt.Errorf("generate operations for updating logical router port %s: %v", lrp.Name, err) + err := fmt.Errorf("generate operations for updating logical router port %s: %w", lrp.Name, err) klog.Error(err) return err } if err = c.Transact("lrp-update", op); err != nil { - err := fmt.Errorf("update logical router port %s: %v", lrp.Name, err) + err := fmt.Errorf("update logical router port %s: %w", lrp.Name, err) klog.Error(err) return err } @@ -155,13 +156,13 @@ func (c *OVNNbClient) CreateLogicalRouterPort(lrName, lrpName, mac string, netwo op, err := c.CreateLogicalRouterPortOp(lrp, lrName) if err != nil { - err := fmt.Errorf("generate operations for creating logical router port %s: %v", lrp.Name, err) + err := fmt.Errorf("generate operations for creating logical router port %s: %w", lrp.Name, err) klog.Error(err) return err } if err = c.Transact("lrp-add", op); err != nil { - err := fmt.Errorf("create logical router port %s: %v", lrp.Name, err) + err := fmt.Errorf("create logical router port %s: %w", lrp.Name, err) klog.Error(err) return err } @@ -173,7 +174,7 @@ func (c *OVNNbClient) CreateLogicalRouterPort(lrName, lrpName, mac string, netwo func (c *OVNNbClient) DeleteLogicalRouterPorts(externalIDs map[string]string, filter func(lrp *ovnnb.LogicalRouterPort) bool) error { lrpList, err := c.ListLogicalRouterPorts(externalIDs, filter) if err != nil { - err := fmt.Errorf("list logical router ports: %v", err) + err := fmt.Errorf("list logical router ports: %w", err) klog.Error(err) return err } @@ -183,13 +184,13 @@ func (c *OVNNbClient) DeleteLogicalRouterPorts(externalIDs map[string]string, fi op, err := c.DeleteLogicalRouterPortOp(lrp.Name) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for deleting logical router port %s: %v", lrp.Name, err) + return fmt.Errorf("generate operations for deleting logical router port %s: %w", lrp.Name, err) } ops = append(ops, op...) } if err := c.Transact("lrps-del", ops); err != nil { - err := fmt.Errorf("del logical router ports: %v", err) + err := fmt.Errorf("del logical router ports: %w", err) klog.Error(err) return err } @@ -201,7 +202,7 @@ func (c *OVNNbClient) DeleteLogicalRouterPorts(externalIDs map[string]string, fi func (c *OVNNbClient) DeleteLogicalRouterPort(lrpName string) error { ops, err := c.DeleteLogicalRouterPortOp(lrpName) if err != nil { - err := fmt.Errorf("generate operations for deleting logical router port %s: %v", lrpName, err) + err := fmt.Errorf("generate operations for deleting logical router port %s: %w", lrpName, err) klog.Error(err) return err } @@ -222,10 +223,10 @@ func (c *OVNNbClient) GetLogicalRouterPort(lrpName string, ignoreNotFound bool) lrp := &ovnnb.LogicalRouterPort{Name: lrpName} if err := c.Get(ctx, lrp); err != nil { - if ignoreNotFound && err == client.ErrNotFound { + if ignoreNotFound && errors.Is(err, client.ErrNotFound) { return nil, nil } - err = fmt.Errorf("get logical router port %s: %v", lrpName, err) + err = fmt.Errorf("get logical router port %s: %w", lrpName, err) klog.Error(err) return nil, err } @@ -240,7 +241,7 @@ func (c *OVNNbClient) GetLogicalRouterPortByUUID(uuid string) (*ovnnb.LogicalRou lrp := &ovnnb.LogicalRouterPort{UUID: uuid} if err := c.Get(ctx, lrp); err != nil { - err := fmt.Errorf("get logical router port by UUID %s: %v", uuid, err) + err := fmt.Errorf("get logical router port by UUID %s: %w", uuid, err) klog.Error(err) return nil, err } @@ -256,7 +257,7 @@ func (c *OVNNbClient) ListLogicalRouterPorts(externalIDs map[string]string, filt lrpList := make([]ovnnb.LogicalRouterPort, 0) if err := c.WhereCache(logicalRouterPortFilter(externalIDs, filter)).List(ctx, &lrpList); err != nil { - err := fmt.Errorf("list logical router ports: %v", err) + err := fmt.Errorf("list logical router ports: %w", err) klog.Error(err) return nil, err } @@ -267,7 +268,7 @@ func (c *OVNNbClient) ListLogicalRouterPorts(externalIDs map[string]string, filt func (c *OVNNbClient) LogicalRouterPortExists(lrpName string) (bool, error) { lrp, err := c.GetLogicalRouterPort(lrpName, true) if err != nil { - err := fmt.Errorf("get logical router port %s: %v", lrpName, err) + err := fmt.Errorf("get logical router port %s: %w", lrpName, err) klog.Error(err) return false, err } @@ -296,7 +297,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) { if lrp == nil { - return nil, fmt.Errorf("logical_router_port is nil") + return nil, errors.New("logical_router_port is nil") } if lrp.ExternalIDs == nil { @@ -310,7 +311,7 @@ func (c *OVNNbClient) CreateLogicalRouterPortOp(lrp *ovnnb.LogicalRouterPort, lr /* create logical router port */ lrpCreateOp, err := c.Create(lrp) if err != nil { - err := fmt.Errorf("generate operations for creating logical router port %s: %v", lrp.Name, err) + err := fmt.Errorf("generate operations for creating logical router port %s: %w", lrp.Name, err) klog.Error(err) return nil, err } @@ -318,7 +319,7 @@ func (c *OVNNbClient) CreateLogicalRouterPortOp(lrp *ovnnb.LogicalRouterPort, lr /* add logical router port to logical router*/ lrpAddOp, err := c.LogicalRouterUpdatePortOp(lrName, lrp.UUID, ovsdb.MutateOperationInsert) if err != nil { - err := fmt.Errorf("generate operations for adding logical router port %s to logical router %s: %v", lrp.Name, lrName, err) + err := fmt.Errorf("generate operations for adding logical router port %s to logical router %s: %w", lrp.Name, lrName, err) klog.Error(err) return nil, err } @@ -334,7 +335,7 @@ func (c *OVNNbClient) CreateLogicalRouterPortOp(lrp *ovnnb.LogicalRouterPort, lr func (c *OVNNbClient) DeleteLogicalRouterPortOp(lrpName string) ([]ovsdb.Operation, error) { lrp, err := c.GetLogicalRouterPort(lrpName, true) if err != nil { - err := fmt.Errorf("get logical router port %s when generate delete operations: %v", lrpName, err) + err := fmt.Errorf("get logical router port %s when generate delete operations: %w", lrpName, err) klog.Error(err) return nil, err } @@ -373,7 +374,7 @@ func (c *OVNNbClient) LogicalRouterPortOp(lrpName string, mutationsFunc ...func( ops, err := c.ovsDbClient.Where(lrp).Mutate(lrp, mutations...) if err != nil { - err := fmt.Errorf("generate operations for mutating logical router port %s: %v", lrpName, err) + err := fmt.Errorf("generate operations for mutating logical router port %s: %w", lrpName, err) klog.Error(err) return nil, err } @@ -459,7 +460,7 @@ func (c *OVNNbClient) AddLogicalRouterPort(lr, name, mac, networks string) error ops = append(ops, mutationOps...) klog.Infof("add vpc lrp %s, networks %s", name, networks) if err := c.Transact("lrp-add", ops); err != nil { - return fmt.Errorf("failed to create logical router port %s: %v", name, err) + return fmt.Errorf("failed to create logical router port %s: %w", name, err) } return nil } diff --git a/pkg/ovs/ovn-nb-logical_router_route.go b/pkg/ovs/ovn-nb-logical_router_route.go index 35ae1ac542a..5ffc56af46e 100644 --- a/pkg/ovs/ovn-nb-logical_router_route.go +++ b/pkg/ovs/ovn-nb-logical_router_route.go @@ -47,12 +47,12 @@ func (c *OVNNbClient) CreateLogicalRouterStaticRoutes(lrName string, routes ...* createRoutesOp, err := c.ovsDbClient.Create(models...) if err != nil { - return fmt.Errorf("generate operations for creating static routes: %v", err) + return fmt.Errorf("generate operations for creating static routes: %w", err) } routeAddOp, err := c.LogicalRouterUpdateStaticRouteOp(lrName, routeUUIDs, ovsdb.MutateOperationInsert) if err != nil { - return fmt.Errorf("generate operations for adding static routes to logical router %s: %v", lrName, err) + return fmt.Errorf("generate operations for adding static routes to logical router %s: %w", lrName, err) } ops := make([]ovsdb.Operation, 0, len(createRoutesOp)+len(routeAddOp)) @@ -60,7 +60,7 @@ func (c *OVNNbClient) CreateLogicalRouterStaticRoutes(lrName string, routes ...* ops = append(ops, routeAddOp...) if err = c.Transact("lr-routes-add", ops); err != nil { - return fmt.Errorf("add static routes to %s: %v", lrName, err) + return fmt.Errorf("add static routes to %s: %w", lrName, err) } return nil @@ -105,14 +105,14 @@ func (c *OVNNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ip ops, err := c.LogicalRouterUpdateStaticRouteOp(lrName, toDel, ovsdb.MutateOperationDelete) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for removing static routes from logical router %s: %v", lrName, err) + return fmt.Errorf("generate operations for removing static routes from logical router %s: %w", lrName, err) } if err = c.Transact("lr-route-del", ops); err != nil { klog.Error(err) - return fmt.Errorf("failed to delete static routes from logical router %s: %v", lrName, err) + return fmt.Errorf("failed to delete static routes from logical router %s: %w", lrName, err) } if err = c.CreateLogicalRouterStaticRoutes(lrName, toAdd...); err != nil { - return fmt.Errorf("failed to add static routes to logical router %s: %v", lrName, err) + return fmt.Errorf("failed to add static routes to logical router %s: %w", lrName, err) } return nil } @@ -120,17 +120,17 @@ func (c *OVNNbClient) AddLogicalRouterStaticRoute(lrName, routeTable, policy, ip // UpdateLogicalRouterStaticRoute update logical router static route func (c *OVNNbClient) UpdateLogicalRouterStaticRoute(route *ovnnb.LogicalRouterStaticRoute, fields ...interface{}) error { if route == nil { - return fmt.Errorf("route is nil") + return errors.New("route is nil") } op, err := c.ovsDbClient.Where(route).Update(route, fields...) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for updating logical router static route 'policy %s ip_prefix %s': %v", *route.Policy, route.IPPrefix, err) + return fmt.Errorf("generate operations for updating logical router static route 'policy %s ip_prefix %s': %w", *route.Policy, route.IPPrefix, err) } if err = c.Transact("net-update", op); err != nil { - return fmt.Errorf("update logical router static route 'policy %s ip_prefix %s': %v", *route.Policy, route.IPPrefix, err) + return fmt.Errorf("update logical router static route 'policy %s ip_prefix %s': %w", *route.Policy, route.IPPrefix, err) } return nil @@ -169,11 +169,11 @@ func (c *OVNNbClient) DeleteLogicalRouterStaticRoute(lrName string, routeTable, ops, err := c.LogicalRouterUpdateStaticRouteOp(lrName, uuids, ovsdb.MutateOperationDelete) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for removing static routes %v from logical router %s: %v", uuids, lrName, err) + return fmt.Errorf("generate operations for removing static routes %v from logical router %s: %w", uuids, lrName, err) } if err = c.Transact("lr-route-del", ops); err != nil { klog.Error(err) - return fmt.Errorf("delete static routes %v from logical router %s: %v", uuids, lrName, err) + return fmt.Errorf("delete static routes %v from logical router %s: %w", uuids, lrName, err) } return nil @@ -184,7 +184,7 @@ func (c *OVNNbClient) ClearLogicalRouterStaticRoute(lrName string) error { lr, err := c.GetLogicalRouter(lrName, false) if err != nil { klog.Error(err) - return fmt.Errorf("get logical router %s: %v", lrName, err) + return fmt.Errorf("get logical router %s: %w", lrName, err) } // clear static route @@ -192,11 +192,11 @@ func (c *OVNNbClient) ClearLogicalRouterStaticRoute(lrName string) error { ops, err := c.UpdateLogicalRouterOp(lr, &lr.StaticRoutes) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for clear logical router %s static route: %v", lrName, err) + return fmt.Errorf("generate operations for clear logical router %s static route: %w", lrName, err) } if err = c.Transact("lr-route-clear", ops); err != nil { klog.Error(err) - return fmt.Errorf("clear logical router %s static routes: %v", lrName, err) + return fmt.Errorf("clear logical router %s static routes: %w", lrName, err) } return nil @@ -222,7 +222,7 @@ func (c *OVNNbClient) GetLogicalRouterStaticRouteByUUID(uuid string) (*ovnnb.Log 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") + return nil, errors.New("the logical router name is required") } fnFilter := func(route *ovnnb.LogicalRouterStaticRoute) bool { @@ -231,7 +231,7 @@ func (c *OVNNbClient) GetLogicalRouterStaticRoute(lrName, routeTable, policy, ip routeList, err := c.listLogicalRouterStaticRoutesByFilter(lrName, fnFilter) if err != nil { klog.Error(err) - return nil, fmt.Errorf("get logical router %s static route 'policy %s ip_prefix %s nexthop %s': %v", lrName, policy, ipPrefix, nexthop, err) + return nil, fmt.Errorf("get logical router %s static route 'policy %s ip_prefix %s nexthop %s': %w", lrName, policy, ipPrefix, nexthop, err) } // not found @@ -302,7 +302,7 @@ func (c *OVNNbClient) LogicalRouterStaticRouteExists(lrName, routeTable, policy, // 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) { if len(lrName) == 0 { - return nil, fmt.Errorf("the logical router name is required") + return nil, errors.New("the logical router name is required") } if len(policy) == 0 { @@ -312,7 +312,7 @@ func (c *OVNNbClient) newLogicalRouterStaticRoute(lrName, routeTable, policy, ip exists, err := c.LogicalRouterStaticRouteExists(lrName, routeTable, policy, ipPrefix, nexthop) if err != nil { klog.Error(err) - return nil, fmt.Errorf("get logical router %s route: %v", lrName, err) + return nil, fmt.Errorf("get logical router %s route: %w", lrName, err) } // found, ignore diff --git a/pkg/ovs/ovn-nb-logical_switch.go b/pkg/ovs/ovn-nb-logical_switch.go index b029f14ff36..df48ce0d15c 100644 --- a/pkg/ovs/ovn-nb-logical_switch.go +++ b/pkg/ovs/ovn-nb-logical_switch.go @@ -65,7 +65,7 @@ func (c *OVNNbClient) CreateLogicalSwitch(lsName, lrName, cidrBlock, gateway, ga } if err := c.RemoveLogicalPatchPort(lspName, lrpName); err != nil { - return fmt.Errorf("remove router type port %s and %s: %v", lspName, lrpName, err) + return fmt.Errorf("remove router type port %s and %s: %w", lspName, lrpName, err) } } @@ -93,11 +93,11 @@ func (c *OVNNbClient) CreateBareLogicalSwitch(lsName string) error { op, err := c.ovsDbClient.Create(ls) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for creating logical switch %s: %v", lsName, err) + return fmt.Errorf("generate operations for creating logical switch %s: %w", lsName, err) } if err := c.Transact("ls-add", op); err != nil { - return fmt.Errorf("create logical switch %s: %v", lsName, err) + return fmt.Errorf("create logical switch %s: %w", lsName, err) } return nil @@ -108,18 +108,18 @@ func (c *OVNNbClient) LogicalSwitchAddPort(lsName, lspName string) error { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) - return fmt.Errorf("get logical switch port %s when logical switch add port: %v", lspName, err) + return fmt.Errorf("get logical switch port %s when logical switch add port: %w", lspName, err) } ops, err := c.LogicalSwitchUpdatePortOp(lsName, lsp.UUID, ovsdb.MutateOperationInsert) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for logical switch %s add port %s: %v", lsName, lspName, err) + return fmt.Errorf("generate operations for logical switch %s add port %s: %w", lsName, lspName, err) } if err := c.Transact("lsp-add", ops); err != nil { klog.Error(err) - return fmt.Errorf("add port %s to logical switch %s: %v", lspName, lsName, err) + return fmt.Errorf("add port %s to logical switch %s: %w", lspName, lsName, err) } return nil @@ -130,7 +130,7 @@ func (c *OVNNbClient) LogicalSwitchDelPort(lsName, lspName string) error { lsp, err := c.GetLogicalSwitchPort(lspName, true) if err != nil { klog.Error(err) - return fmt.Errorf("get logical switch port %s when logical switch del port: %v", lspName, err) + return fmt.Errorf("get logical switch port %s when logical switch del port: %w", lspName, err) } if lsp == nil { @@ -140,11 +140,11 @@ func (c *OVNNbClient) LogicalSwitchDelPort(lsName, lspName string) error { ops, err := c.LogicalSwitchUpdatePortOp(lsName, lsp.UUID, ovsdb.MutateOperationDelete) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for logical switch %s del port %s: %v", lsName, lspName, err) + return fmt.Errorf("generate operations for logical switch %s del port %s: %w", lsName, lspName, err) } if err := c.Transact("lsp-del", ops); err != nil { - return fmt.Errorf("del port %s from logical switch %s: %v", lspName, lsName, err) + return fmt.Errorf("del port %s from logical switch %s: %w", lspName, lsName, err) } return nil @@ -174,11 +174,11 @@ func (c *OVNNbClient) LogicalSwitchUpdateLoadBalancers(lsName string, op ovsdb.M ops, err := c.LogicalSwitchUpdateLoadBalancerOp(lsName, lbUUIDs, op) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for logical switch %s update lbs %v: %v", lsName, lbNames, err) + return fmt.Errorf("generate operations for logical switch %s update lbs %v: %w", lsName, lbNames, err) } if err := c.Transact("ls-lb-update", ops); err != nil { - return fmt.Errorf("logical switch %s update lbs %v: %v", lsName, lbNames, err) + return fmt.Errorf("logical switch %s update lbs %v: %w", lsName, lbNames, err) } return nil @@ -193,11 +193,11 @@ func (c *OVNNbClient) LogicalSwitchUpdateOtherConfig(lsName string, op ovsdb.Mut ops, err := c.LogicalSwitchUpdateOtherConfigOp(lsName, otherConfig, op) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for logical switch %s update other config %v: %v", lsName, otherConfig, err) + return fmt.Errorf("generate operations for logical switch %s update other config %v: %w", lsName, otherConfig, err) } if err := c.Transact("ls-other-config-update", ops); err != nil { - return fmt.Errorf("logical switch %s update other config %v: %v", lsName, otherConfig, err) + return fmt.Errorf("logical switch %s update other config %v: %w", lsName, otherConfig, err) } return nil @@ -212,7 +212,7 @@ func (c *OVNNbClient) DeleteLogicalSwitch(lsName string) error { } if err := c.Transact("ls-del", op); err != nil { - return fmt.Errorf("delete logical switch %s: %v", lsName, err) + return fmt.Errorf("delete logical switch %s: %w", lsName, err) } return nil @@ -228,7 +228,7 @@ func (c *OVNNbClient) GetLogicalSwitch(lsName string, ignoreNotFound bool) (*ovn if err := c.ovsDbClient.WhereCache(func(ls *ovnnb.LogicalSwitch) bool { return ls.Name == lsName }).List(ctx, &lsList); err != nil { - return nil, fmt.Errorf("list switch switch %q: %v", lsName, err) + return nil, fmt.Errorf("list switch switch %q: %w", lsName, err) } // not found @@ -270,7 +270,7 @@ func (c *OVNNbClient) ListLogicalSwitch(needVendorFilter bool, filter func(ls *o return true }).List(ctx, &lsList); err != nil { - return nil, fmt.Errorf("list logical switch: %v", err) + return nil, fmt.Errorf("list logical switch: %w", err) } return lsList, nil @@ -288,7 +288,7 @@ func (c *OVNNbClient) LogicalSwitchUpdatePortOp(lsName, lspUUID string, op ovsdb }) if err != nil { klog.Error(err) - return nil, fmt.Errorf("failed to list LS by LSP UUID %s: %v", lspUUID, err) + return nil, fmt.Errorf("failed to list LS by LSP UUID %s: %w", lspUUID, err) } if len(lsList) == 0 { err = fmt.Errorf("no LS found for LSP %s", lspUUID) @@ -382,7 +382,7 @@ func (c *OVNNbClient) LogicalSwitchOp(lsName string, mutationsFunc ...func(ls *o ls, err := c.GetLogicalSwitch(lsName, false) if err != nil { klog.Error(err) - return nil, fmt.Errorf("get logical switch %s when generate mutate operations: %v", lsName, err) + return nil, fmt.Errorf("get logical switch %s when generate mutate operations: %w", lsName, err) } if len(mutationsFunc) == 0 { @@ -402,7 +402,7 @@ func (c *OVNNbClient) LogicalSwitchOp(lsName string, mutationsFunc ...func(ls *o ops, err := c.ovsDbClient.Where(ls).Mutate(ls, mutations...) if err != nil { klog.Error(err) - return nil, fmt.Errorf("generate operations for mutating logical switch %s: %v", lsName, err) + return nil, fmt.Errorf("generate operations for mutating logical switch %s: %w", lsName, err) } return ops, nil @@ -413,7 +413,7 @@ func (c *OVNNbClient) DeleteLogicalSwitchOp(lsName string) ([]ovsdb.Operation, e ls, err := c.GetLogicalSwitch(lsName, true) if err != nil { klog.Error(err) - return nil, fmt.Errorf("get logical switch %s: %v", lsName, err) + return nil, fmt.Errorf("get logical switch %s: %w", lsName, err) } // not found, skip @@ -424,7 +424,7 @@ func (c *OVNNbClient) DeleteLogicalSwitchOp(lsName string) ([]ovsdb.Operation, e op, err := c.Where(ls).Delete() if err != nil { klog.Error(err) - return nil, fmt.Errorf("generate operations for deleting logical switch %s: %v", lsName, err) + return nil, fmt.Errorf("generate operations for deleting logical switch %s: %w", lsName, err) } return op, nil diff --git a/pkg/ovs/ovn-nb-logical_switch_port.go b/pkg/ovs/ovn-nb-logical_switch_port.go index a85ef03ba09..32e49e71279 100644 --- a/pkg/ovs/ovn-nb-logical_switch_port.go +++ b/pkg/ovs/ovn-nb-logical_switch_port.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "reflect" "slices" @@ -101,7 +102,7 @@ func (c *OVNNbClient) CreateLogicalSwitchPort(lsName, lspName, ip, mac, podName, if existingLsp.ExternalIDs[logicalSwitchKey] == lsName { if err := c.UpdateLogicalSwitchPort(lsp, &lsp.Addresses, &lsp.Dhcpv4Options, &lsp.Dhcpv6Options, &lsp.PortSecurity, &lsp.ExternalIDs); err != nil { klog.Error(err) - return fmt.Errorf("failed to update logical switch port %s: %v", lspName, err) + return fmt.Errorf("failed to update logical switch port %s: %w", lspName, err) } return nil } @@ -114,11 +115,11 @@ func (c *OVNNbClient) CreateLogicalSwitchPort(lsName, lspName, ip, mac, podName, createLspOps, err := c.CreateLogicalSwitchPortOp(lsp, lsName) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for creating logical switch port %s: %v", lspName, err) + return fmt.Errorf("generate operations for creating logical switch port %s: %w", lspName, err) } if err = c.Transact("lsp-add", append(ops, createLspOps...)); err != nil { - return fmt.Errorf("create logical switch port %s: %v", lspName, err) + return fmt.Errorf("create logical switch port %s: %w", lspName, err) } return nil @@ -147,7 +148,7 @@ func (c *OVNNbClient) CreateLocalnetLogicalSwitchPort(lsName, lspName, provider, if !reflect.DeepEqual(lsp.ExternalIDs, externalIDs) { lsp.ExternalIDs = externalIDs if err = c.UpdateLogicalSwitchPort(lsp, &lsp.ExternalIDs); err != nil { - return fmt.Errorf("failed to update external-ids of logical switch port %s: %v", lspName, err) + return fmt.Errorf("failed to update external-ids of logical switch port %s: %w", lspName, err) } } @@ -177,7 +178,7 @@ func (c *OVNNbClient) CreateLocalnetLogicalSwitchPort(lsName, lspName, provider, } if err = c.Transact("lsp-add", ops); err != nil { - return fmt.Errorf("create localnet logical switch port %s: %v", lspName, err) + return fmt.Errorf("create localnet logical switch port %s: %w", lspName, err) } return nil @@ -220,7 +221,7 @@ func (c *OVNNbClient) CreateVirtualLogicalSwitchPorts(lsName string, ips ...stri } if err := c.Transact("lsp-add", ops); err != nil { - return fmt.Errorf("create virtual logical switch ports for logical switch %s: %v", lsName, err) + return fmt.Errorf("create virtual logical switch ports for logical switch %s: %w", lsName, err) } return nil @@ -255,7 +256,7 @@ func (c *OVNNbClient) CreateVirtualLogicalSwitchPort(lspName, lsName, ip string) } if err := c.Transact("lsp-add", op); err != nil { - return fmt.Errorf("create virtual logical switch port %s for logical switch %s: %v", lspName, lsName, err) + return fmt.Errorf("create virtual logical switch port %s for logical switch %s: %w", lspName, lsName, err) } return nil @@ -293,7 +294,7 @@ func (c *OVNNbClient) CreateBareLogicalSwitchPort(lsName, lspName, ip, mac strin } if err = c.Transact("lsp-add", ops); err != nil { - return fmt.Errorf("create logical switch port %s: %v", lspName, err) + return fmt.Errorf("create logical switch port %s: %w", lspName, err) } return nil @@ -308,7 +309,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortVirtualParents(lsName, parents string, lsp, err := c.GetLogicalSwitchPort(lspName, true) if err != nil { klog.Error(err) - return fmt.Errorf("get logical switch port %s: %v", lspName, err) + return fmt.Errorf("get logical switch port %s: %w", lspName, err) } lsp.Options["virtual-parents"] = parents @@ -326,7 +327,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortVirtualParents(lsName, parents string, } if err := c.Transact("lsp-update", ops); err != nil { - return fmt.Errorf("set logical switch port virtual-parents %v", err) + return fmt.Errorf("set logical switch port virtual-parents %w", err) } return nil } @@ -336,7 +337,7 @@ func (c *OVNNbClient) SetVirtualLogicalSwitchPortVirtualParents(lspName, parents lsp, err := c.GetLogicalSwitchPort(lspName, true) if err != nil { klog.Error(err) - return fmt.Errorf("get logical switch port %s: %v", lspName, err) + return fmt.Errorf("get logical switch port %s: %w", lspName, err) } lsp.Options["virtual-parents"] = parents @@ -351,7 +352,7 @@ func (c *OVNNbClient) SetVirtualLogicalSwitchPortVirtualParents(lspName, parents } if err := c.Transact("lsp-update", op); err != nil { - return fmt.Errorf("set logical switch port virtual-parents %v", err) + return fmt.Errorf("set logical switch port virtual-parents %w", err) } return nil } @@ -359,7 +360,7 @@ func (c *OVNNbClient) SetVirtualLogicalSwitchPortVirtualParents(lspName, parents 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) + return fmt.Errorf("get logical switch port %s: %w", lspName, err) } if lsp.Options == nil { lsp.Options = make(map[string]string) @@ -375,7 +376,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortArpProxy(lspName string, enableArpProx return err } if err := c.Transact("lsp-update", op); err != nil { - return fmt.Errorf("failed to set logical switch port option arp_proxy %v", err) + return fmt.Errorf("failed to set logical switch port option arp_proxy %w", err) } return nil } @@ -385,7 +386,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortSecurity(portSecurity bool, lspName, m lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) - return fmt.Errorf("get logical switch port %s: %v", lspName, err) + return fmt.Errorf("get logical switch port %s: %w", lspName, err) } lsp.PortSecurity = nil @@ -419,7 +420,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortSecurity(portSecurity bool, lspName, m } if err := c.UpdateLogicalSwitchPort(lsp, &lsp.PortSecurity, &lsp.ExternalIDs); err != nil { - return fmt.Errorf("set logical switch port %s port_security %v: %v", lspName, lsp.PortSecurity, err) + return fmt.Errorf("set logical switch port %s port_security %v: %w", lspName, lsp.PortSecurity, err) } return nil @@ -430,7 +431,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortExternalIDs(lspName string, externalID lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) - return fmt.Errorf("get logical switch port %s: %v", lspName, err) + return fmt.Errorf("get logical switch port %s: %w", lspName, err) } if lsp.ExternalIDs == nil { @@ -442,7 +443,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortExternalIDs(lspName string, externalID } if err := c.UpdateLogicalSwitchPort(lsp, &lsp.ExternalIDs); err != nil { - return fmt.Errorf("set logical switch port %s external ids %v: %v", lspName, externalIDs, err) + return fmt.Errorf("set logical switch port %s external ids %v: %w", lspName, externalIDs, err) } return nil @@ -456,7 +457,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortSecurityGroup(lsp *ovnnb.LogicalSwitch } if op != "add" && op != "remove" { - return nil, fmt.Errorf("op must be 'add' or 'remove'") + return nil, errors.New("op must be 'add' or 'remove'") } diffSgs := make([]string, 0, len(sgs)) @@ -489,7 +490,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortSecurityGroup(lsp *ovnnb.LogicalSwitch } if err := c.UpdateLogicalSwitchPort(lsp, &lsp.ExternalIDs); err != nil { - return nil, fmt.Errorf("set logical switch port %s security group %v: %v", lsp.Name, newSgs, err) + return nil, fmt.Errorf("set logical switch port %s security group %v: %w", lsp.Name, newSgs, err) } return diffSgs, nil } @@ -498,7 +499,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortSecurityGroup(lsp *ovnnb.LogicalSwitch // op is 'add' or 'remove' func (c *OVNNbClient) SetLogicalSwitchPortsSecurityGroup(sgName, op string) error { if op != "add" && op != "remove" { - return fmt.Errorf("op must be 'add' or 'remove'") + return errors.New("op must be 'add' or 'remove'") } /* list sg port */ @@ -512,13 +513,13 @@ func (c *OVNNbClient) SetLogicalSwitchPortsSecurityGroup(sgName, op string) erro lsps, err := c.ListNormalLogicalSwitchPorts(true, externalIDs) if err != nil { klog.Error(err) - return fmt.Errorf("list logical switch ports with external_ids %v: %v", externalIDs, err) + return fmt.Errorf("list logical switch ports with external_ids %v: %w", externalIDs, err) } /* add to or remove from sgs form port external_ids */ for _, lsp := range lsps { if _, err := c.SetLogicalSwitchPortSecurityGroup(&lsp, op, sgName); err != nil { - return fmt.Errorf("set logical switch port %s security group %s: %v", lsp.Name, sgName, err) + return fmt.Errorf("set logical switch port %s security group %s: %w", lsp.Name, sgName, err) } } @@ -530,7 +531,7 @@ func (c *OVNNbClient) EnablePortLayer2forward(lspName string) error { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) - return fmt.Errorf("get logical switch port %s: %v", lspName, err) + return fmt.Errorf("get logical switch port %s: %w", lspName, err) } if slices.Contains(lsp.Addresses, "unknown") { @@ -539,7 +540,7 @@ func (c *OVNNbClient) EnablePortLayer2forward(lspName string) error { lsp.Addresses = append(lsp.Addresses, "unknown") if err := c.UpdateLogicalSwitchPort(lsp, &lsp.Addresses); err != nil { - return fmt.Errorf("set logical switch port %s addressed=unknown: %v", lspName, err) + return fmt.Errorf("set logical switch port %s addressed=unknown: %w", lspName, err) } return nil @@ -554,7 +555,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortVlanTag(lspName string, vlanID int) er lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { klog.Error(err) - return fmt.Errorf("get logical switch port %s: %v", lspName, err) + return fmt.Errorf("get logical switch port %s: %w", lspName, err) } // no need update vlan id when vlan id is the same @@ -568,7 +569,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortVlanTag(lspName string, vlanID int) er } if err := c.UpdateLogicalSwitchPort(lsp, &lsp.Tag); err != nil { - return fmt.Errorf("set logical switch port %s tag %d: %v", lspName, vlanID, err) + return fmt.Errorf("set logical switch port %s tag %d: %w", lspName, vlanID, err) } return nil @@ -577,7 +578,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 { if lsp == nil { - err := fmt.Errorf("logical switch port is nil") + err := errors.New("logical switch port is nil") klog.Error(err) return err } @@ -585,12 +586,12 @@ func (c *OVNNbClient) UpdateLogicalSwitchPort(lsp *ovnnb.LogicalSwitchPort, fiel op, err := c.Where(lsp).Update(lsp, fields...) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for updating logical switch port %s: %v", lsp.Name, err) + return fmt.Errorf("generate operations for updating logical switch port %s: %w", lsp.Name, err) } if err = c.Transact("lsp-update", op); err != nil { klog.Error(err) - return fmt.Errorf("update logical switch port %s: %v", lsp.Name, err) + return fmt.Errorf("update logical switch port %s: %w", lsp.Name, err) } return nil @@ -625,7 +626,7 @@ func (c *OVNNbClient) DeleteLogicalSwitchPorts(externalIDs map[string]string, fi lspList, err := c.ListLogicalSwitchPorts(false, externalIDs, filter) if err != nil { klog.Error(err) - return fmt.Errorf("list switch ports: %v", err) + return fmt.Errorf("list switch ports: %w", err) } ops := make([]ovsdb.Operation, 0, len(lspList)) @@ -633,13 +634,13 @@ func (c *OVNNbClient) DeleteLogicalSwitchPorts(externalIDs map[string]string, fi op, err := c.DeleteLogicalSwitchPortOp(lsp.Name) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for deleting logical switch port %s: %v", lsp.Name, err) + return fmt.Errorf("generate operations for deleting logical switch port %s: %w", lsp.Name, err) } ops = append(ops, op...) } if err := c.Transact("lsps-del", ops); err != nil { - return fmt.Errorf("del logical switch ports: %v", err) + return fmt.Errorf("del logical switch ports: %w", err) } return nil @@ -651,10 +652,10 @@ func (c *OVNNbClient) GetLogicalSwitchPort(lspName string, ignoreNotFound bool) defer cancel() lsp := &ovnnb.LogicalSwitchPort{Name: lspName} if err := c.Get(ctx, lsp); err != nil { - if ignoreNotFound && err == client.ErrNotFound { + if ignoreNotFound && errors.Is(err, client.ErrNotFound) { return nil, nil } - return nil, fmt.Errorf("get logical switch port %s: %v", lspName, err) + return nil, fmt.Errorf("get logical switch port %s: %w", lspName, err) } return lsp, nil @@ -667,7 +668,7 @@ func (c *OVNNbClient) ListNormalLogicalSwitchPorts(needVendorFilter bool, extern }) if err != nil { klog.Error(err) - return nil, fmt.Errorf("list logical switch ports: %v", err) + return nil, fmt.Errorf("list logical switch ports: %w", err) } return lsps, nil @@ -682,7 +683,7 @@ func (c *OVNNbClient) ListLogicalSwitchPortsWithLegacyExternalIDs() ([]ovnnb.Log if err := c.WhereCache(func(lsp *ovnnb.LogicalSwitchPort) bool { return len(lsp.ExternalIDs) == 0 || lsp.ExternalIDs[logicalSwitchKey] == "" || lsp.ExternalIDs["vendor"] == "" }).List(ctx, &lspList); err != nil { - return nil, fmt.Errorf("failed to list logical switch ports with legacy external-ids: %v", err) + return nil, fmt.Errorf("failed to list logical switch ports with legacy external-ids: %w", err) } return lspList, nil @@ -696,7 +697,7 @@ func (c *OVNNbClient) ListLogicalSwitchPorts(needVendorFilter bool, externalIDs lspList := make([]ovnnb.LogicalSwitchPort, 0) if err := c.WhereCache(logicalSwitchPortFilter(needVendorFilter, externalIDs, filter)).List(ctx, &lspList); err != nil { - return nil, fmt.Errorf("list logical switch ports: %v", err) + return nil, fmt.Errorf("list logical switch ports: %w", err) } return lspList, nil @@ -710,7 +711,7 @@ func (c *OVNNbClient) LogicalSwitchPortExists(name string) (bool, error) { // CreateLogicalSwitchPortOp create operations which create logical switch port func (c *OVNNbClient) CreateLogicalSwitchPortOp(lsp *ovnnb.LogicalSwitchPort, lsName string) ([]ovsdb.Operation, error) { if lsp == nil { - return nil, fmt.Errorf("logical_switch_port is nil") + return nil, errors.New("logical_switch_port is nil") } if lsp.ExternalIDs == nil { @@ -726,7 +727,7 @@ func (c *OVNNbClient) CreateLogicalSwitchPortOp(lsp *ovnnb.LogicalSwitchPort, ls lspCreateOp, err := c.Create(lsp) if err != nil { klog.Error(err) - return nil, fmt.Errorf("generate operations for creating logical switch port %s: %v", lsp.Name, err) + return nil, fmt.Errorf("generate operations for creating logical switch port %s: %w", lsp.Name, err) } /* add logical switch port to logical switch*/ @@ -748,7 +749,7 @@ func (c *OVNNbClient) DeleteLogicalSwitchPortOp(lspName string) ([]ovsdb.Operati lsp, err := c.GetLogicalSwitchPort(lspName, true) if err != nil { klog.Error(err) - return nil, fmt.Errorf("get logical switch port %s when generate delete operations: %v", lspName, err) + return nil, fmt.Errorf("get logical switch port %s when generate delete operations: %w", lspName, err) } // not found, skip @@ -772,7 +773,7 @@ func (c *OVNNbClient) DeleteLogicalSwitchPortOp(lspName string) ([]ovsdb.Operati klog.Infof("delete logical switch port %s with id %s from logical switch %s", lspName, lsp.UUID, lsName) ops, err := c.LogicalSwitchUpdatePortOp(lsName, lsp.UUID, ovsdb.MutateOperationDelete) if err != nil { - return nil, fmt.Errorf("generate operations for removing port %s from logical switch %s: %v", lspName, lsName, err) + return nil, fmt.Errorf("generate operations for removing port %s from logical switch %s: %w", lspName, lsName, err) } return ops, nil } @@ -786,7 +787,7 @@ func (c *OVNNbClient) UpdateLogicalSwitchPortOp(lsp *ovnnb.LogicalSwitchPort, fi op, err := c.Where(lsp).Update(lsp, fields...) if err != nil { - return nil, fmt.Errorf("generate operations for updating logical switch port %s: %v", lsp.Name, err) + return nil, fmt.Errorf("generate operations for updating logical switch port %s: %w", lsp.Name, err) } return op, nil @@ -910,7 +911,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortMigrateOptions(lspName, srcNodeName, t lsp.Options["activation-strategy"] = "rarp" klog.Infof("set migrator logical switch port %s options: %v", lspName, lsp.Options) if err := c.UpdateLogicalSwitchPort(lsp, &lsp.Options); err != nil { - err = fmt.Errorf("failed to set migrator logical switch port %s options requested chassis %s: %v", lspName, requestedChassis, err) + err = fmt.Errorf("failed to set migrator logical switch port %s options requested chassis %s: %w", lspName, requestedChassis, err) klog.Error(err) return err } @@ -921,7 +922,7 @@ func (c *OVNNbClient) SetLogicalSwitchPortMigrateOptions(lspName, srcNodeName, t func (c *OVNNbClient) GetLogicalSwitchPortMigrateOptions(lspName string) (*ovnnb.LogicalSwitchPort, string, string, error) { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { - err = fmt.Errorf("failed to get migrator logical switch port %s: %v", lspName, err) + err = fmt.Errorf("failed to get migrator logical switch port %s: %w", lspName, err) klog.Error(err) return nil, "", "", err } @@ -942,7 +943,7 @@ func (c *OVNNbClient) GetLogicalSwitchPortMigrateOptions(lspName string) (*ovnnb func (c *OVNNbClient) ResetLogicalSwitchPortMigrateOptions(lspName, srcNodeName, targetNodeName string, migratedFail bool) error { lsp, err := c.GetLogicalSwitchPort(lspName, false) if err != nil { - err = fmt.Errorf("failed to get migrator logical switch port %s: %v", lspName, err) + err = fmt.Errorf("failed to get migrator logical switch port %s: %w", lspName, err) klog.Error(err) return err } @@ -964,7 +965,7 @@ func (c *OVNNbClient) ResetLogicalSwitchPortMigrateOptions(lspName, srcNodeName, } delete(lsp.Options, "activation-strategy") if err := c.UpdateLogicalSwitchPort(lsp, &lsp.Options); err != nil { - err = fmt.Errorf("failed to reset options for migrator logical switch port %s: %v", lspName, err) + err = fmt.Errorf("failed to reset options for migrator logical switch port %s: %w", lspName, err) klog.Error(err) return err } @@ -975,7 +976,7 @@ func (c *OVNNbClient) ResetLogicalSwitchPortMigrateOptions(lspName, srcNodeName, func (c *OVNNbClient) CleanLogicalSwitchPortMigrateOptions(lspName string) error { lsp, err := c.GetLogicalSwitchPort(lspName, true) if err != nil { - err = fmt.Errorf("failed to get migrator logical switch port %s: %v", lspName, err) + err = fmt.Errorf("failed to get migrator logical switch port %s: %w", lspName, err) klog.Error(err) return err } @@ -993,7 +994,7 @@ func (c *OVNNbClient) CleanLogicalSwitchPortMigrateOptions(lspName string) error delete(lsp.Options, "requested-chassis") klog.Infof("cleaned migrator logical switch port %s options: %v", lspName, lsp.Options) if err := c.UpdateLogicalSwitchPort(lsp, &lsp.Options); err != nil { - err = fmt.Errorf("failed to clean options for migrator logical switch port %s: %v", lspName, err) + err = fmt.Errorf("failed to clean options for migrator logical switch port %s: %w", lspName, err) klog.Error(err) return err } diff --git a/pkg/ovs/ovn-nb-nat.go b/pkg/ovs/ovn-nb-nat.go index 967c1e6d070..e82ce59162c 100644 --- a/pkg/ovs/ovn-nb-nat.go +++ b/pkg/ovs/ovn-nb-nat.go @@ -64,13 +64,13 @@ func (c *OVNNbClient) CreateNats(lrName string, nats ...*ovnnb.NAT) error { createNatsOp, err := c.ovsDbClient.Create(models...) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for creating nats: %v", err) + return fmt.Errorf("generate operations for creating nats: %w", err) } natAddOp, err := c.LogicalRouterUpdateNatOp(lrName, natUUIDs, ovsdb.MutateOperationInsert) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for adding nats to logical router %s: %v", lrName, err) + return fmt.Errorf("generate operations for adding nats to logical router %s: %w", lrName, err) } ops := make([]ovsdb.Operation, 0, len(createNatsOp)+len(natAddOp)) @@ -78,7 +78,7 @@ func (c *OVNNbClient) CreateNats(lrName string, nats ...*ovnnb.NAT) error { ops = append(ops, natAddOp...) if err = c.Transact("lr-nats-add", ops); err != nil { - return fmt.Errorf("add nats to %s: %v", lrName, err) + return fmt.Errorf("add nats to %s: %w", lrName, err) } return nil @@ -103,12 +103,12 @@ func (c *OVNNbClient) UpdateSnat(lrName, externalIP, logicalIP string) error { /* create nat */ if nat, err = c.newNat(lrName, natType, externalIP, logicalIP, "", ""); err != nil { klog.Error(err) - return fmt.Errorf("new logical router %s nat 'type %s external ip %s logical ip %s': %v", lrName, natType, externalIP, logicalIP, err) + return fmt.Errorf("new logical router %s nat 'type %s external ip %s logical ip %s': %w", lrName, natType, externalIP, logicalIP, err) } if err := c.CreateNats(lrName, nat); err != nil { klog.Error(err) - return fmt.Errorf("add nat 'type %s external ip %s logical ip %s' to logical router %s: %v", natType, externalIP, logicalIP, lrName, err) + return fmt.Errorf("add nat 'type %s external ip %s logical ip %s' to logical router %s: %w", natType, externalIP, logicalIP, lrName, err) } return nil @@ -150,12 +150,12 @@ func (c *OVNNbClient) UpdateDnatAndSnat(lrName, externalIP, logicalIP, lspName, /* create nat */ if nat, err = c.newNat(lrName, natType, externalIP, logicalIP, "", "", options); err != nil { klog.Error(err) - return fmt.Errorf("new logical router %s nat 'type %s external ip %s logical ip %s logical port %s external mac %s': %v", lrName, natType, externalIP, logicalIP, lspName, externalMac, err) + return fmt.Errorf("new logical router %s nat 'type %s external ip %s logical ip %s logical port %s external mac %s': %w", lrName, natType, externalIP, logicalIP, lspName, externalMac, err) } if err := c.CreateNats(lrName, nat); err != nil { klog.Error(err) - return fmt.Errorf("add nat 'type %s external ip %s logical ip %s logical port %s external mac %s' to logical router %s: %v", natType, externalIP, logicalIP, lspName, externalMac, lrName, err) + return fmt.Errorf("add nat 'type %s external ip %s logical ip %s logical port %s external mac %s' to logical router %s: %w", natType, externalIP, logicalIP, lspName, externalMac, lrName, err) } return nil @@ -164,18 +164,18 @@ func (c *OVNNbClient) UpdateDnatAndSnat(lrName, externalIP, logicalIP, lspName, // UpdateNat update nat func (c *OVNNbClient) UpdateNat(nat *ovnnb.NAT, fields ...interface{}) error { if nat == nil { - return fmt.Errorf("nat is nil") + return errors.New("nat is nil") } op, err := c.ovsDbClient.Where(nat).Update(nat, fields...) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for updating nat 'type %s external ip %s logical ip %s': %v", nat.Type, nat.ExternalIP, nat.LogicalIP, err) + return fmt.Errorf("generate operations for updating nat 'type %s external ip %s logical ip %s': %w", nat.Type, nat.ExternalIP, nat.LogicalIP, err) } if err = c.Transact("net-update", op); err != nil { klog.Error(err) - return fmt.Errorf("update nat 'type %s external ip %s logical ip %s': %v", nat.Type, nat.ExternalIP, nat.LogicalIP, err) + return fmt.Errorf("update nat 'type %s external ip %s logical ip %s': %w", nat.Type, nat.ExternalIP, nat.LogicalIP, err) } return nil @@ -187,7 +187,7 @@ func (c *OVNNbClient) DeleteNats(lrName, natType, logicalIP string) error { nats, err := c.ListNats(lrName, natType, logicalIP, nil) if err != nil { klog.Error(err) - return fmt.Errorf("list logical router %s nats 'type %s logical ip %s': %v", lrName, natType, logicalIP, err) + return fmt.Errorf("list logical router %s nats 'type %s logical ip %s': %w", lrName, natType, logicalIP, err) } natsUUIDs := make([]string, 0, len(nats)) @@ -198,10 +198,10 @@ func (c *OVNNbClient) DeleteNats(lrName, natType, logicalIP string) error { ops, err := c.LogicalRouterUpdateNatOp(lrName, natsUUIDs, ovsdb.MutateOperationDelete) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for deleting nats from logical router %s: %v", lrName, err) + return fmt.Errorf("generate operations for deleting nats from logical router %s: %w", lrName, err) } if err = c.Transact("nats-del", ops); err != nil { - return fmt.Errorf("del nats from logical router %s: %v", lrName, err) + return fmt.Errorf("del nats from logical router %s: %w", lrName, err) } return nil @@ -219,10 +219,10 @@ func (c *OVNNbClient) DeleteNat(lrName, natType, externalIP, logicalIP string) e ops, err := c.LogicalRouterUpdateNatOp(lrName, []string{nat.UUID}, ovsdb.MutateOperationDelete) if err != nil { klog.Error(err) - return fmt.Errorf("generate operations for deleting nat from logical router %s: %v", lrName, err) + return fmt.Errorf("generate operations for deleting nat from logical router %s: %w", lrName, err) } if err = c.Transact("lr-nat-del", ops); err != nil { - return fmt.Errorf("del nat from logical router %s: %v", lrName, err) + return fmt.Errorf("del nat from logical router %s: %w", lrName, err) } return nil @@ -247,18 +247,18 @@ func (c *OVNNbClient) GetNATByUUID(uuid string) (*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 { - err := fmt.Errorf("the logical router name is required") + err := errors.New("the logical router name is required") klog.Error(err) return nil, err } if natType == ovnnb.NATTypeDNAT { - err := fmt.Errorf("does not support dnat for now") + err := errors.New("does not support dnat for now") klog.Error(err) return nil, err } if natType != ovnnb.NATTypeSNAT && natType != ovnnb.NATTypeDNATAndSNAT { - err := fmt.Errorf("nat type must one of [ snat, dnat_and_snat ]") + err := errors.New("nat type must one of [ snat, dnat_and_snat ]") klog.Error(err) return nil, err } @@ -290,7 +290,7 @@ func (c *OVNNbClient) GetNat(lrName, natType, externalIP, logicalIP string, igno natList, err := c.listLogicalRouterNatByFilter(lrName, fnFilter) if err != nil { klog.Error(err) - return nil, fmt.Errorf("get logical router %s nat 'type %s external ip %s logical ip %s': %v", lrName, natType, externalIP, logicalIP, err) + return nil, fmt.Errorf("get logical router %s nat 'type %s external ip %s logical ip %s': %w", lrName, natType, externalIP, logicalIP, err) } // not found @@ -327,19 +327,19 @@ func (c *OVNNbClient) NatExists(lrName, natType, externalIP, logicalIP string) ( // a nat rule is uniquely identified by router(lrName), type(natType) and external_ip when dnat_and_snat func (c *OVNNbClient) newNat(lrName, natType, externalIP, logicalIP, logicalMac, port string, options ...func(nat *ovnnb.NAT)) (*ovnnb.NAT, error) { if len(lrName) == 0 { - err := fmt.Errorf("the logical router name is required") + err := errors.New("the logical router name is required") klog.Error(err) return nil, err } if natType == ovnnb.NATTypeDNAT { - err := fmt.Errorf("does not support dnat for now") + err := errors.New("does not support dnat for now") klog.Error(err) return nil, err } if natType != ovnnb.NATTypeSNAT && natType != ovnnb.NATTypeDNATAndSNAT { - err := fmt.Errorf("nat type must one of [ snat, dnat_and_snat ]") + err := errors.New("nat type must one of [ snat, dnat_and_snat ]") klog.Error(err) return nil, err } @@ -362,7 +362,7 @@ func (c *OVNNbClient) newNat(lrName, natType, externalIP, logicalIP, logicalMac, exists, err := c.NatExists(lrName, natType, externalIP, logicalIP) if err != nil { klog.Error(err) - return nil, fmt.Errorf("get logical router %s nat: %v", lrName, err) + return nil, fmt.Errorf("get logical router %s nat: %w", lrName, err) } // found, ignore diff --git a/pkg/ovs/ovn-nb-port_group.go b/pkg/ovs/ovn-nb-port_group.go index 73b1af6d60a..b08af2456f9 100644 --- a/pkg/ovs/ovn-nb-port_group.go +++ b/pkg/ovs/ovn-nb-port_group.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "github.com/ovn-org/libovsdb/client" @@ -20,7 +21,7 @@ func (c *OVNNbClient) CreatePortGroup(pgName string, externalIDs map[string]stri return err } - // ingnore + // ignore if exist { return nil } @@ -32,11 +33,11 @@ func (c *OVNNbClient) CreatePortGroup(pgName string, externalIDs map[string]stri ops, err := c.ovsDbClient.Create(pg) if err != nil { - return fmt.Errorf("generate operations for creating port group %s: %v", pgName, err) + return fmt.Errorf("generate operations for creating port group %s: %w", pgName, err) } if err = c.Transact("pg-add", ops); err != nil { - return fmt.Errorf("create port group %s: %v", pgName, err) + return fmt.Errorf("create port group %s: %w", pgName, err) } return nil @@ -54,12 +55,12 @@ func (c *OVNNbClient) PortGroupRemovePorts(pgName string, lspNames ...string) er func (c *OVNNbClient) PortGroupSetPorts(pgName string, ports []string) error { if pgName == "" { - return fmt.Errorf("port group name is empty") + return errors.New("port group name is empty") } pg, err := c.GetPortGroup(pgName, false) if err != nil { - return fmt.Errorf("get port group %s: %v", pgName, err) + return fmt.Errorf("get port group %s: %w", pgName, err) } expected := strset.NewWithSize(len(ports)) @@ -80,15 +81,15 @@ func (c *OVNNbClient) PortGroupSetPorts(pgName string, ports []string) error { insertOps, err := c.portGroupUpdatePortOp(pgName, toAdd, ovsdb.MutateOperationInsert) if err != nil { - return fmt.Errorf("failed generate operations for adding ports %v to port group %s: %v", toAdd, pgName, err) + return fmt.Errorf("failed generate operations for adding ports %v to port group %s: %w", toAdd, pgName, err) } deleteOps, err := c.portGroupUpdatePortOp(pgName, toDel, ovsdb.MutateOperationDelete) if err != nil { - return fmt.Errorf("failed generate operations for deleting ports %v from port group %s: %v", toDel, pgName, err) + return fmt.Errorf("failed generate operations for deleting ports %v from port group %s: %w", toDel, pgName, err) } if err = c.Transact("pg-ports-update", append(insertOps, deleteOps...)); err != nil { - return fmt.Errorf("port group %s set ports %v: %v", pgName, ports, err) + return fmt.Errorf("port group %s set ports %v: %w", pgName, ports, err) } return nil @@ -98,11 +99,11 @@ func (c *OVNNbClient) PortGroupSetPorts(pgName string, ports []string) 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) + return fmt.Errorf("generate operations for updating port group %s: %w", pg.Name, err) } if err = c.Transact("pg-update", op); err != nil { - return fmt.Errorf("update port group %s: %v", pg.Name, err) + return fmt.Errorf("update port group %s: %w", pg.Name, err) } return nil @@ -131,11 +132,11 @@ func (c *OVNNbClient) PortGroupUpdatePorts(pgName string, op ovsdb.Mutator, lspN ops, err := c.portGroupUpdatePortOp(pgName, lspUUIDs, op) if err != nil { - return fmt.Errorf("generate operations for port group %s update ports %v: %v", pgName, lspNames, err) + return fmt.Errorf("generate operations for port group %s update ports %v: %w", pgName, lspNames, err) } if err := c.Transact("pg-ports-update", ops); err != nil { - return fmt.Errorf("port group %s update ports %v: %v", pgName, lspNames, err) + return fmt.Errorf("port group %s update ports %v: %w", pgName, lspNames, err) } return nil @@ -144,7 +145,7 @@ func (c *OVNNbClient) PortGroupUpdatePorts(pgName string, op ovsdb.Mutator, lspN 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) + return fmt.Errorf("get port group %s when delete: %w", pgName, err) } // not found, skip @@ -159,7 +160,7 @@ func (c *OVNNbClient) DeletePortGroup(pgName string) error { } if err := c.Transact("pg-del", op); err != nil { - return fmt.Errorf("delete port group %s: %v", pgName, err) + return fmt.Errorf("delete port group %s: %w", pgName, err) } return nil @@ -172,10 +173,10 @@ func (c *OVNNbClient) GetPortGroup(pgName string, ignoreNotFound bool) (*ovnnb.P pg := &ovnnb.PortGroup{Name: pgName} if err := c.ovsDbClient.Get(ctx, pg); err != nil { - if ignoreNotFound && err == client.ErrNotFound { + if ignoreNotFound && errors.Is(err, client.ErrNotFound) { return nil, nil } - return nil, fmt.Errorf("get port group %s: %v", pgName, err) + return nil, fmt.Errorf("get port group %s: %w", pgName, err) } return pg, nil @@ -267,7 +268,7 @@ func (c *OVNNbClient) portGroupUpdateACLOp(pgName string, aclUUIDs []string, op 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) + return nil, fmt.Errorf("get port group %s: %w", pgName, err) } if len(mutationsFunc) == 0 { @@ -286,7 +287,7 @@ func (c *OVNNbClient) portGroupOp(pgName string, mutationsFunc ...func(pg *ovnnb ops, err := c.ovsDbClient.Where(pg).Mutate(pg, mutations...) if err != nil { - return nil, fmt.Errorf("generate operations for mutating port group %s: %v", pgName, err) + return nil, fmt.Errorf("generate operations for mutating port group %s: %w", pgName, err) } return ops, nil diff --git a/pkg/ovs/ovn-nb.go b/pkg/ovs/ovn-nb.go index ec5b11ca826..73bf284cfcb 100644 --- a/pkg/ovs/ovn-nb.go +++ b/pkg/ovs/ovn-nb.go @@ -30,16 +30,16 @@ func (c *OVNNbClient) CreateGatewayLogicalSwitch(lsName, lrName, provider, ip, m // delete old localnet lsp when upgrade before v1.12 oldLocalnetLspName := fmt.Sprintf("ln-%s", lsName) if err := c.DeleteLogicalSwitchPort(oldLocalnetLspName); err != nil { - return fmt.Errorf("failed to delete old localnet %s: %v", oldLocalnetLspName, err) + return fmt.Errorf("failed to delete old localnet %s: %w", oldLocalnetLspName, err) } localnetLspName := GetLocalnetName(lsName) if err := c.CreateBareLogicalSwitch(lsName); err != nil { - return fmt.Errorf("create logical switch %s: %v", lsName, err) + return fmt.Errorf("create logical switch %s: %w", lsName, err) } if err := c.CreateLocalnetLogicalSwitchPort(lsName, localnetLspName, provider, "", vlanID); err != nil { - return fmt.Errorf("create localnet logical switch port %s: %v", localnetLspName, err) + return fmt.Errorf("create localnet logical switch port %s: %w", localnetLspName, err) } return c.CreateLogicalPatchPort(lsName, lrName, lspName, lrpName, ip, mac, chassises...) @@ -50,7 +50,7 @@ func (c *OVNNbClient) CreateLogicalPatchPort(lsName, lrName, lspName, lrpName, i if len(ip) != 0 { // check ip format: 192.168.231.1/24,fc00::0af4:01/112 if err := util.CheckCidrs(ip); err != nil { - err := fmt.Errorf("invalid ip %s: %v", ip, err) + err := fmt.Errorf("invalid ip %s: %w", ip, err) klog.Error(err) return err } @@ -62,20 +62,20 @@ func (c *OVNNbClient) CreateLogicalPatchPort(lsName, lrName, lspName, lrpName, i /* create router port */ ops, err := c.CreateRouterPortOp(lsName, lrName, lspName, lrpName, ip, mac) if err != nil { - err := fmt.Errorf("generate operations for creating patch port: %v", err) + err := fmt.Errorf("generate operations for creating patch port: %w", err) klog.Error(err) return err } if err = c.Transact("lrp-lsp-add", ops); err != nil { - err := fmt.Errorf("create logical patch port %s and %s: %v", lspName, lrpName, err) + err := fmt.Errorf("create logical patch port %s and %s: %w", lspName, lrpName, err) klog.Error(err) return err } /* create gateway chassises for logical router port */ if err := c.CreateGatewayChassises(lrpName, chassises...); err != nil { - err := fmt.Errorf("create gateway chassises for logical router port %s: %v", lrpName, err) + err := fmt.Errorf("create gateway chassises for logical router port %s: %w", lrpName, err) klog.Error(err) return err } @@ -89,12 +89,12 @@ func (c *OVNNbClient) DeleteLogicalGatewaySwitch(lsName, lrName string) error { // all corresponding logical switch port(e.g. localnet port and normal port) will be deleted when delete logical switch lsDelOp, err := c.DeleteLogicalSwitchOp(lsName) if err != nil { - return fmt.Errorf("generate operations for deleting gateway switch %s: %v", lsName, err) + return fmt.Errorf("generate operations for deleting gateway switch %s: %w", lsName, err) } lrpDelOp, err := c.DeleteLogicalRouterPortOp(lrpName) if err != nil { - return fmt.Errorf("generate operations for deleting gateway router port %s: %v", lrpName, err) + return fmt.Errorf("generate operations for deleting gateway router port %s: %w", lrpName, err) } ops := make([]ovsdb.Operation, 0, len(lsDelOp)+len(lrpDelOp)) @@ -102,7 +102,7 @@ func (c *OVNNbClient) DeleteLogicalGatewaySwitch(lsName, lrName string) error { ops = append(ops, lrpDelOp...) if err = c.Transact("gw-ls-del", ops); err != nil { - return fmt.Errorf("delete gateway switch %s: %v", lsName, err) + return fmt.Errorf("delete gateway switch %s: %w", lsName, err) } return nil @@ -113,7 +113,7 @@ func (c *OVNNbClient) DeleteSecurityGroup(sgName string) error { // clear acl if err := c.DeleteAcls(pgName, portGroupKey, "", nil); err != nil { - return fmt.Errorf("delete acls from port group %s: %v", pgName, err) + return fmt.Errorf("delete acls from port group %s: %w", pgName, err) } // clear address_set @@ -123,7 +123,7 @@ func (c *OVNNbClient) DeleteSecurityGroup(sgName string) error { if sgName == util.DefaultSecurityGroupName { if err := c.SetLogicalSwitchPortsSecurityGroup(sgName, "remove"); err != nil { - return fmt.Errorf("clear default security group %s from logical switch ports: %v", sgName, err) + return fmt.Errorf("clear default security group %s from logical switch ports: %w", sgName, err) } } @@ -198,7 +198,7 @@ func (c *OVNNbClient) RemoveLogicalPatchPort(lspName, lrpName string) error { ops = append(ops, lrpDelOp...) if err = c.Transact("lrp-lsp-del", ops); err != nil { - return fmt.Errorf("delete logical switch port %s and delete logical router port %s: %v", lspName, lrpName, err) + return fmt.Errorf("delete logical switch port %s and delete logical router port %s: %w", lspName, lrpName, err) } return nil diff --git a/pkg/ovs/ovn-nb_global.go b/pkg/ovs/ovn-nb_global.go index c7aae0beae3..6201c9982be 100644 --- a/pkg/ovs/ovn-nb_global.go +++ b/pkg/ovs/ovn-nb_global.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "reflect" "strings" @@ -15,7 +16,7 @@ func (c *OVNNbClient) CreateNbGlobal(nbGlobal *ovnnb.NBGlobal) error { op, err := c.ovsDbClient.Create(nbGlobal) if err != nil { klog.Error(err) - return fmt.Errorf("failed to generate operations for creating nb global: %v", err) + return fmt.Errorf("failed to generate operations for creating nb global: %w", err) } return c.Transact("nb-global-create", op) @@ -49,11 +50,11 @@ func (c *OVNNbClient) GetNbGlobal() (*ovnnb.NBGlobal, error) { }).List(ctx, &nbGlobalList) if err != nil { klog.Error(err) - return nil, fmt.Errorf("failed to list NB_Global: %v", err) + return nil, fmt.Errorf("failed to list NB_Global: %w", err) } if len(nbGlobalList) == 0 { - return nil, fmt.Errorf("not found nb_global") + return nil, errors.New("not found nb_global") } return &nbGlobalList[0], nil @@ -63,12 +64,12 @@ func (c *OVNNbClient) UpdateNbGlobal(nbGlobal *ovnnb.NBGlobal, fields ...interfa op, err := c.Where(nbGlobal).Update(nbGlobal, fields...) if err != nil { klog.Error(err) - return fmt.Errorf("failed to generate operations for updating nb global: %v", err) + return fmt.Errorf("failed to generate operations for updating nb global: %w", err) } if err := c.Transact("nb-global-update", op); err != nil { klog.Error(err) - return fmt.Errorf("failed to update NB_Global: %v", err) + return fmt.Errorf("failed to update NB_Global: %w", err) } return nil @@ -78,7 +79,7 @@ func (c *OVNNbClient) SetAzName(azName string) error { nbGlobal, err := c.GetNbGlobal() if err != nil { klog.Error(err) - return fmt.Errorf("failed to get nb global: %v", err) + return fmt.Errorf("failed to get nb global: %w", err) } if azName == nbGlobal.Name { return nil // no need to update @@ -87,7 +88,7 @@ func (c *OVNNbClient) SetAzName(azName string) error { nbGlobal.Name = azName if err := c.UpdateNbGlobal(nbGlobal, &nbGlobal.Name); err != nil { klog.Error(err) - return fmt.Errorf("set nb_global az name %s: %v", azName, err) + return fmt.Errorf("set nb_global az name %s: %w", azName, err) } return nil @@ -97,7 +98,7 @@ func (c *OVNNbClient) SetNbGlobalOptions(key string, value interface{}) error { nbGlobal, err := c.GetNbGlobal() if err != nil { klog.Error(err) - return fmt.Errorf("failed to get nb global: %v", err) + return fmt.Errorf("failed to get nb global: %w", err) } v := fmt.Sprintf("%v", value) @@ -112,7 +113,7 @@ func (c *OVNNbClient) SetNbGlobalOptions(key string, value interface{}) error { if err := c.UpdateNbGlobal(nbGlobal, &nbGlobal.Options); err != nil { klog.Error(err) - return fmt.Errorf("failed to set nb global option %s to %v: %v", key, value, err) + return fmt.Errorf("failed to set nb global option %s to %v: %w", key, value, err) } return nil @@ -126,7 +127,7 @@ func (c *OVNNbClient) SetICAutoRoute(enable bool, blackList []string) error { nbGlobal, err := c.GetNbGlobal() if err != nil { klog.Error(err) - return fmt.Errorf("failed to get nb global: %v", err) + return fmt.Errorf("failed to get nb global: %w", err) } options := make(map[string]string, len(nbGlobal.Options)+3) @@ -150,7 +151,7 @@ func (c *OVNNbClient) SetICAutoRoute(enable bool, blackList []string) error { nbGlobal.Options = options if err := c.UpdateNbGlobal(nbGlobal, &nbGlobal.Options); err != nil { klog.Error(err) - return fmt.Errorf("failed to enable ovn-ic auto route, %v", err) + return fmt.Errorf("failed to enable ovn-ic auto route, %w", err) } return nil } @@ -175,7 +176,7 @@ func (c *OVNNbClient) SetNodeLocalDNSIP(nodeLocalDNSIP string) error { nbGlobal, err := c.GetNbGlobal() if err != nil { klog.Error(err) - return fmt.Errorf("failed to get nb global: %v", err) + return fmt.Errorf("failed to get nb global: %w", err) } options := make(map[string]string, len(nbGlobal.Options)) @@ -188,7 +189,7 @@ func (c *OVNNbClient) SetNodeLocalDNSIP(nodeLocalDNSIP string) error { nbGlobal.Options = options if err := c.UpdateNbGlobal(nbGlobal, &nbGlobal.Options); err != nil { klog.Error(err) - return fmt.Errorf("failed to remove NB_Global option node_local_dns_ip, %v", err) + return fmt.Errorf("failed to remove NB_Global option node_local_dns_ip, %w", err) } return nil diff --git a/pkg/ovs/ovn-sb-chassis.go b/pkg/ovs/ovn-sb-chassis.go index dde299d4dd2..b7569f9853b 100644 --- a/pkg/ovs/ovn-sb-chassis.go +++ b/pkg/ovs/ovn-sb-chassis.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "github.com/ovn-org/libovsdb/client" @@ -14,12 +15,12 @@ import ( 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) + err := fmt.Errorf("failed to generate update operations for chassis: %w", err) klog.Error(err) return err } if err = c.Transact("chassis-update", op); err != nil { - err := fmt.Errorf("failed to update chassis %s: %v", chassis.Name, err) + err := fmt.Errorf("failed to update chassis %s: %w", chassis.Name, err) klog.Error(err) return err } @@ -38,10 +39,10 @@ func (c *OVNSbClient) DeleteChassis(chassisName string) error { } ops, err := c.ovsDbClient.Where(chassis).Delete() if err != nil { - return fmt.Errorf("failed to generate delete chassis operations for node %s: %v", chassis.Hostname, err) + return fmt.Errorf("failed to generate delete chassis operations for node %s: %w", chassis.Hostname, err) } if err = c.Transact("chassis-del", ops); err != nil { - return fmt.Errorf("failed to delete chassis for node %s: %v", chassis.Hostname, err) + return fmt.Errorf("failed to delete chassis for node %s: %w", chassis.Hostname, err) } return nil } @@ -51,16 +52,16 @@ func (c *OVNSbClient) GetChassis(chassisName string, ignoreNotFound bool) (*ovns ctx, cancel := context.WithTimeout(context.Background(), c.Timeout) defer cancel() if chassisName == "" { - err := fmt.Errorf("chassis name is empty") + err := errors.New("chassis name is empty") klog.Error(err) return nil, err } chassis := &ovnsb.Chassis{Name: chassisName} if err := c.ovsDbClient.Get(ctx, chassis); err != nil { - if ignoreNotFound && err == client.ErrNotFound { + if ignoreNotFound && errors.Is(err, client.ErrNotFound) { return nil, nil } - return nil, fmt.Errorf("failed to get chassis %s: %v", chassisName, err) + return nil, fmt.Errorf("failed to get chassis %s: %w", chassisName, err) } klog.V(3).Infof("get chassis: %+v", chassis) return chassis, nil @@ -73,7 +74,7 @@ func (c *OVNSbClient) ListChassis() (*[]ovnsb.Chassis, error) { css := []ovnsb.Chassis{} if err := c.ovsDbClient.List(ctx, &css); err != nil { - return nil, fmt.Errorf("failed to list Chassis: %v", err) + return nil, fmt.Errorf("failed to list Chassis: %w", err) } return &css, nil } @@ -86,7 +87,7 @@ func (c *OVNSbClient) GetAllChassisByHost(nodeName string) (*[]ovnsb.Chassis, er if err := c.ovsDbClient.WhereCache(func(chassis *ovnsb.Chassis) bool { return chassis.Hostname == nodeName }).List(ctx, &chassisList); err != nil { - return nil, fmt.Errorf("failed to list Chassis with host name=%s: %v", nodeName, err) + return nil, fmt.Errorf("failed to list Chassis with host name=%s: %w", nodeName, err) } if len(chassisList) == 0 { err := fmt.Errorf("failed to get Chassis with with host name=%s", nodeName) @@ -109,7 +110,7 @@ func (c *OVNSbClient) GetChassisByHost(nodeName string) (*ovnsb.Chassis, error) if err := c.ovsDbClient.WhereCache(func(chassis *ovnsb.Chassis) bool { return chassis.Hostname == nodeName }).List(ctx, &chassisList); err != nil { - return nil, fmt.Errorf("failed to list Chassis with host name=%s: %v", nodeName, err) + return nil, fmt.Errorf("failed to list Chassis with host name=%s: %w", nodeName, err) } if len(chassisList) == 0 { err := fmt.Errorf("failed to get Chassis with with host name=%s", nodeName) @@ -135,13 +136,13 @@ func (c *OVNSbClient) DeleteChassisByHost(nodeName string) error { if err := c.ovsDbClient.WhereCache(func(chassis *ovnsb.Chassis) bool { return chassis.Hostname == nodeName || (chassis.ExternalIDs != nil && chassis.ExternalIDs["node"] == nodeName) }).List(ctx, &chassisList); err != nil { - return fmt.Errorf("failed to list Chassis with host name=%s: %v", nodeName, err) + return fmt.Errorf("failed to list Chassis with host name=%s: %w", nodeName, err) } for _, chassis := range chassisList { klog.Infof("delete chassis: %+v", chassis) if err := c.DeleteChassis(chassis.Name); err != nil { - err := fmt.Errorf("failed to delete chassis %s, %v", chassis.Name, err) + err := fmt.Errorf("failed to delete chassis %s, %w", chassis.Name, err) klog.Error(err) return err } @@ -156,7 +157,7 @@ func (c *OVNSbClient) UpdateChassisTag(chassisName, nodeName string) error { return err } if chassis == nil { - err := fmt.Errorf("faile to get chassis by name=%s", chassisName) + err := fmt.Errorf("fail to get chassis by name=%s", chassisName) // restart kube-ovn-cni, chassis will be created klog.Error(err) return err @@ -171,7 +172,7 @@ func (c *OVNSbClient) UpdateChassisTag(chassisName, nodeName string) error { // not need filter chassis by node name if we use libovsdb chassis.ExternalIDs = externalIDs if err := c.UpdateChassis(chassis, &chassis.ExternalIDs); err != nil { - return fmt.Errorf("failed to init chassis node %s: %v", nodeName, err) + return fmt.Errorf("failed to init chassis node %s: %w", nodeName, err) } } return nil @@ -189,7 +190,7 @@ func (c *OVNSbClient) GetKubeOvnChassisses() (*[]ovnsb.Chassis, error) { } return false }).List(ctx, &chassisList); err != nil { - return nil, fmt.Errorf("failed to list Chassis with vendor=%s: %v", util.CniTypeName, err) + return nil, fmt.Errorf("failed to list Chassis with vendor=%s: %w", util.CniTypeName, err) } return &chassisList, nil } diff --git a/pkg/ovs/ovn.go b/pkg/ovs/ovn.go index 0dda7a70bb5..fd6e209e64f 100644 --- a/pkg/ovs/ovn.go +++ b/pkg/ovs/ovn.go @@ -2,7 +2,7 @@ package ovs import ( "context" - "fmt" + "errors" "reflect" "time" @@ -229,7 +229,7 @@ func (c *ovsDbClient) GetEntityInfo(entity interface{}) error { entityPtr := reflect.ValueOf(entity) if entityPtr.Kind() != reflect.Pointer { - return fmt.Errorf("entity must be pointer") + return errors.New("entity must be pointer") } err := c.Get(ctx, entity) diff --git a/pkg/ovs/ovs-vsctl.go b/pkg/ovs/ovs-vsctl.go index a5ff137add5..3ebcd2ba16d 100644 --- a/pkg/ovs/ovs-vsctl.go +++ b/pkg/ovs/ovs-vsctl.go @@ -73,7 +73,7 @@ func Exec(args ...string) (string, error) { if err != nil { code = "1" klog.Warningf("ovs-vsctl command error: %s %s in %vms", OvsVsCtl, strings.Join(args, " "), elapsed) - return "", fmt.Errorf("failed to run '%s %s': %v\n %q", OvsVsCtl, strings.Join(args, " "), err, output) + return "", fmt.Errorf("failed to run '%s %s': %w\n %q", OvsVsCtl, strings.Join(args, " "), err, output) } else if elapsed > 500 { klog.Warningf("ovs-vsctl command took too long: %s %s in %vms", OvsVsCtl, strings.Join(args, " "), elapsed) } @@ -332,7 +332,7 @@ func ConfigInterfaceMirror(globalMirror bool, open, iface string) error { return err } if len(portUUIDs) != 1 { - return fmt.Errorf(fmt.Sprintf("find port failed, portName=%s", ifName)) + return fmt.Errorf("find port failed, portName=%s", ifName) } portID := portUUIDs[0] if open == "true" { @@ -349,10 +349,10 @@ func ConfigInterfaceMirror(globalMirror bool, open, iface string) error { return err } if len(mirrorPorts) == 0 { - return fmt.Errorf("find mirror failed, mirror name=" + util.MirrorDefaultName) + return fmt.Errorf("find mirror failed, mirror name=%s", util.MirrorDefaultName) } if len(mirrorPorts) > 1 { - return fmt.Errorf("repeated mirror data, mirror name=" + util.MirrorDefaultName) + return fmt.Errorf("repeated mirror data, mirror name=%s", util.MirrorDefaultName) } for _, mirrorPortIDs := range mirrorPorts { if strings.Contains(mirrorPortIDs, portID) { diff --git a/pkg/ovs/ovs-vsctl_linux.go b/pkg/ovs/ovs-vsctl_linux.go index cebf91d2083..be4e76a262e 100644 --- a/pkg/ovs/ovs-vsctl_linux.go +++ b/pkg/ovs/ovs-vsctl_linux.go @@ -71,7 +71,7 @@ func SetInterfaceBandwidth(podName, podNamespace, iface, ingress, egress string) } 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) + return fmt.Errorf("failed to remove rate limit for queue in pod %v/%v, %w", podNamespace, podName, err) } } } diff --git a/pkg/ovs/util.go b/pkg/ovs/util.go index 00d52e35e53..15f21ab1861 100644 --- a/pkg/ovs/util.go +++ b/pkg/ovs/util.go @@ -2,6 +2,7 @@ package ovs import ( "context" + "errors" "fmt" "regexp" "strings" @@ -146,7 +147,7 @@ func (m AndACLMatch) Match() (string, error) { for _, r := range m.matches { match, err := r.Match() if err != nil { - return "", fmt.Errorf("generate match %s: %v", match, err) + return "", fmt.Errorf("generate match %s: %w", match, err) } matches = append(matches, match) } @@ -175,7 +176,7 @@ func (m OrACLMatch) Match() (string, error) { for _, specification := range m.matches { match, err := specification.Match() if err != nil { - return "", fmt.Errorf("generate match %s: %v", match, err) + return "", fmt.Errorf("generate match %s: %w", match, err) } // has more then one rule @@ -219,7 +220,7 @@ func NewACLMatch(key, effect, value, maxValue string) ACLMatch { func (m aclMatch) Match() (string, error) { // key must exist at least if len(m.key) == 0 { - return "", fmt.Errorf("acl rule key is required") + return "", errors.New("acl rule key is required") } // like 'ip' @@ -262,7 +263,7 @@ func (l *Limiter) Wait(ctx context.Context) error { for { select { case <-ctx.Done(): - return fmt.Errorf("context canceled by timeout") + return errors.New("context canceled by timeout") default: if l.limit == 0 { atomic.AddInt32(&l.current, 1) diff --git a/pkg/ovsdb/client/client.go b/pkg/ovsdb/client/client.go index 008bc676422..bd493ab1e94 100644 --- a/pkg/ovsdb/client/client.go +++ b/pkg/ovsdb/client/client.go @@ -75,12 +75,12 @@ func NewOvsDbClient( cert, err := tls.LoadX509KeyPair("/var/run/tls/cert", "/var/run/tls/key") if err != nil { klog.Error(err) - return nil, fmt.Errorf("failed to load x509 cert key pair: %v", err) + return nil, fmt.Errorf("failed to load x509 cert key pair: %w", err) } caCert, err := os.ReadFile("/var/run/tls/cacert") if err != nil { klog.Error(err) - return nil, fmt.Errorf("failed to read ca cert: %v", err) + return nil, fmt.Errorf("failed to read ca cert: %w", err) } certPool := x509.NewCertPool() certPool.AppendCertsFromPEM(caCert) diff --git a/pkg/pinger/ovn.go b/pkg/pinger/ovn.go index 94eebc2bef5..d6958e571a2 100644 --- a/pkg/pinger/ovn.go +++ b/pkg/pinger/ovn.go @@ -177,7 +177,7 @@ func getLogicalPort(chassis string) ([]string, error) { } output, err := exec.Command("ovsdb-client", command...).CombinedOutput() // #nosec G204 if err != nil { - return nil, fmt.Errorf("Failed to query OVSDB: %v, %s", err, output) + return nil, fmt.Errorf("Failed to query OVSDB: %w, %s", err, output) } // Parse the JSON output. diff --git a/pkg/pinger/ping.go b/pkg/pinger/ping.go index 87e6b810b7d..f747dadc371 100644 --- a/pkg/pinger/ping.go +++ b/pkg/pinger/ping.go @@ -2,6 +2,7 @@ package pinger import ( "context" + "errors" "fmt" "math" "net" @@ -88,7 +89,7 @@ func ping(config *Configuration, withMetrics bool) error { } } if errHappens { - return fmt.Errorf("ping failed") + return errors.New("ping failed") } return nil } @@ -142,7 +143,7 @@ func pingNodes(config *Configuration, setMetrics bool) error { klog.Infof("ping node: %s %s, count: %d, loss count %d, average rtt %.2fms", nodeName, nodeIP, 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") + pingErr = errors.New("ping failed") } if setMetrics { SetNodePingMetrics( @@ -216,7 +217,7 @@ func pingPods(config *Configuration, setMetrics bool) error { 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)) if int(math.Abs(float64(stats.PacketsSent-stats.PacketsRecv))) != 0 { - pingErr = fmt.Errorf("ping failed") + pingErr = errors.New("ping failed") } if setMetrics { SetPodPingMetrics( @@ -276,7 +277,7 @@ func pingExternal(config *Configuration, setMetrics bool) error { int(math.Abs(float64(stats.PacketsSent-stats.PacketsRecv)))) } if int(math.Abs(float64(stats.PacketsSent-stats.PacketsRecv))) != 0 { - return fmt.Errorf("ping failed") + return errors.New("ping failed") } } diff --git a/pkg/pinger/util.go b/pkg/pinger/util.go index d38ae4c651f..748928fabac 100644 --- a/pkg/pinger/util.go +++ b/pkg/pinger/util.go @@ -44,7 +44,7 @@ func (e *Exporter) getOvsDatapath() ([]string, error) { cmd := exec.Command("sh", "-c", cmdstr) // #nosec G204 output, err := cmd.CombinedOutput() if err != nil { - return nil, fmt.Errorf("failed to get output of dpctl/dump-dps: %v", err) + return nil, fmt.Errorf("failed to get output of dpctl/dump-dps: %w", err) } for _, kvPair := range strings.Split(string(output), "\n") { @@ -70,7 +70,7 @@ func (e *Exporter) setOvsDpIfMetric(datapathName string) error { cmd := exec.Command("sh", "-c", cmdstr) // #nosec G204 output, err := cmd.CombinedOutput() if err != nil { - return fmt.Errorf("failed to get output of dpctl/show %s: %v", datapathName, err) + return fmt.Errorf("failed to get output of dpctl/show %s: %w", datapathName, err) } var datapathPortCount float64 diff --git a/pkg/request/cniserver.go b/pkg/request/cniserver.go index 75431dba6d1..d605f6b010f 100644 --- a/pkg/request/cniserver.go +++ b/pkg/request/cniserver.go @@ -2,6 +2,7 @@ package request import ( "fmt" + "net/http" "github.com/containernetworking/cni/pkg/types" "github.com/parnurzeal/gorequest" @@ -60,7 +61,7 @@ func (csc CniServerClient) Add(podRequest CniRequest) (*CniResponse, error) { if len(errors) != 0 { return nil, errors[0] } - if res.StatusCode != 200 { + if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("request ip return %d %s", res.StatusCode, resp.Err) } return &resp, nil @@ -72,7 +73,7 @@ func (csc CniServerClient) Del(podRequest CniRequest) error { if len(errors) != 0 { return errors[0] } - if res.StatusCode != 204 { + if res.StatusCode != http.StatusNoContent { return fmt.Errorf("delete ip return %d %s", res.StatusCode, body) } return nil diff --git a/pkg/server/server.go b/pkg/server/server.go new file mode 100644 index 00000000000..e3041693974 --- /dev/null +++ b/pkg/server/server.go @@ -0,0 +1,101 @@ +package server + +import ( + "fmt" + "net" + "net/http" + "os" + "strconv" + "strings" + + "k8s.io/apiserver/pkg/endpoints/filters" + "k8s.io/apiserver/pkg/endpoints/request" + "k8s.io/apiserver/pkg/server" + "k8s.io/apiserver/pkg/server/options" + "k8s.io/client-go/rest" + "k8s.io/klog/v2" + + "github.com/kubeovn/kube-ovn/pkg/client/clientset/versioned/scheme" +) + +func SecureServing(addr, svcName string, handler http.Handler) (<-chan struct{}, error) { + host, port, err := net.SplitHostPort(addr) + if err != nil { + klog.Error(err) + return nil, fmt.Errorf("invalid listen address %q: %w", addr, err) + } + + namespace := os.Getenv("POD_NAMESPACE") + podName := os.Getenv("POD_NAME") + podIPs := os.Getenv("POD_IPS") + alternateDNS := []string{podName, svcName, fmt.Sprintf("%s.%s", svcName, namespace), fmt.Sprintf("%s.%s.svc", svcName, namespace)} + alternateIPs := []net.IP{net.ParseIP("127.0.0.1"), net.IPv6loopback} + for _, podIP := range strings.Split(podIPs, ",") { + if ip := net.ParseIP(podIP); ip != nil { + alternateIPs = append(alternateIPs, ip) + } + } + + var clientConfig *rest.Config + opt := options.NewSecureServingOptions().WithLoopback() + authnOpt := options.NewDelegatingAuthenticationOptions() + authzOpt := options.NewDelegatingAuthorizationOptions() + opt.ServerCert.PairName = svcName + opt.ServerCert.CertDirectory = "" + authnOpt.RemoteKubeConfigFileOptional = true + authzOpt.RemoteKubeConfigFileOptional = true + + if host != "" { + ip := net.ParseIP(host) + if ip == nil { + err = fmt.Errorf("invalid listen address: %q", addr) + klog.Error(err) + return nil, err + } + opt.BindAddress = ip + p, err := strconv.Atoi(port) + if err != nil { + klog.Error(err) + return nil, fmt.Errorf("invalid listen address %q: %w", addr, err) + } + opt.BindPort = p + } + + if err = opt.MaybeDefaultWithSelfSignedCerts("localhost", alternateDNS, alternateIPs); err != nil { + klog.Error(err) + return nil, fmt.Errorf("failed to generate self signed certificates: %w", err) + } + + var serving *server.SecureServingInfo + var authn server.AuthenticationInfo + var authz server.AuthorizationInfo + if err = opt.ApplyTo(&serving, &clientConfig); err != nil { + klog.Error(err) + return nil, fmt.Errorf("failed to apply secure serving options to secure serving info: %w", err) + } + if err = authnOpt.ApplyTo(&authn, serving, nil); err != nil { + klog.Error(err) + return nil, fmt.Errorf("failed to apply authn options to authn info: %w", err) + } + if err = authzOpt.ApplyTo(&authz); err != nil { + klog.Error(err) + return nil, fmt.Errorf("failed to apply authz options to authz info: %w", err) + } + + handler = filters.WithAuthorization(handler, authz.Authorizer, scheme.Codecs) + handler = filters.WithAuthentication(handler, authn.Authenticator, filters.Unauthorized(scheme.Codecs), nil, nil) + + requestInfoResolver := &request.RequestInfoFactory{} + handler = filters.WithRequestInfo(handler, requestInfoResolver) + handler = filters.WithCacheControl(handler) + server.AuthorizeClientBearerToken(clientConfig, &authn, &authz) + + stopCh := make(chan struct{}, 1) + _, listenerStoppedCh, err := serving.Serve(handler, 0, stopCh) + if err != nil { + klog.Error(err) + return nil, fmt.Errorf("failed to serve on %s: %w", addr, err) + } + + return listenerStoppedCh, nil +} diff --git a/pkg/speaker/config.go b/pkg/speaker/config.go index 3127e57c7ca..42df76fe0a8 100644 --- a/pkg/speaker/config.go +++ b/pkg/speaker/config.go @@ -179,11 +179,11 @@ func ParseFlags() (*Configuration, error) { } if err := config.initKubeClient(); err != nil { - return nil, fmt.Errorf("failed to init kube client, %v", err) + return nil, fmt.Errorf("failed to init kube client, %w", err) } if err := config.initBgpServer(); err != nil { - return nil, fmt.Errorf("failed to init bgp server, %v", err) + return nil, fmt.Errorf("failed to init bgp server, %w", err) } return config, nil diff --git a/pkg/speaker/subnet.go b/pkg/speaker/subnet.go index 75478e98732..47e8178f405 100644 --- a/pkg/speaker/subnet.go +++ b/pkg/speaker/subnet.go @@ -213,7 +213,6 @@ func (c *Controller) syncSubnetRoutes() { klog.Error(err) } } - } } diff --git a/pkg/tproxy/tproxy_tcp_linux.go b/pkg/tproxy/tproxy_tcp_linux.go index c231e785cf6..90cd54e786f 100644 --- a/pkg/tproxy/tproxy_tcp_linux.go +++ b/pkg/tproxy/tproxy_tcp_linux.go @@ -3,6 +3,7 @@ package tproxy import ( + "errors" "fmt" "net" "os" @@ -71,7 +72,7 @@ func listenTCP(device, network string, laddr *net.TCPAddr) (net.Listener, error) fileDescriptorSource, err := listener.File() if err != nil { - return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: laddr, Err: fmt.Errorf("get file descriptor: %s", err)} + return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: laddr, Err: fmt.Errorf("get file descriptor: %w", err)} } defer func() { @@ -82,12 +83,12 @@ func listenTCP(device, network string, laddr *net.TCPAddr) (net.Listener, error) if device != "" { if err = syscall.BindToDevice(int(fileDescriptorSource.Fd()), device); err != nil { - return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: laddr, Err: fmt.Errorf("set socket option: SO_BINDTODEVICE(%s): %s", device, err)} + return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: laddr, Err: fmt.Errorf("set socket option: SO_BINDTODEVICE(%s): %w", device, err)} } } if err = syscall.SetsockoptInt(int(fileDescriptorSource.Fd()), syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil { - return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: laddr, Err: fmt.Errorf("set socket option: IP_TRANSPARENT: %s", err)} + return nil, &net.OpError{Op: "listen", Net: network, Source: nil, Addr: laddr, Err: fmt.Errorf("set socket option: IP_TRANSPARENT: %w", err)} } return &Listener{listener}, nil @@ -150,31 +151,31 @@ func DialTCP(laddr, raddr *net.TCPAddr, 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")} + return nil, &net.OpError{Op: "dial", Err: errors.New("empty local address or remote address")} } remoteSocketAddress, err := tcpAddrToSocketAddr(raddr) if err != nil { klog.Error(err) - return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("build destination socket address: %s", err)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("build destination socket address: %w", err)} } localSocketAddress, err := tcpAddrToSocketAddr(laddr) if err != nil { klog.Error(err) - return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("build local socket address: %s", err)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("build local socket address: %w", err)} } fileDescriptor, err := syscall.Socket(tcpAddrFamily("tcp", raddr, laddr), syscall.SOCK_STREAM, syscall.IPPROTO_TCP) if err != nil { klog.Error(err) - return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("socket open: %s", err)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("socket open: %w", err)} } if device != "" { 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)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: SO_BINDTODEVICE(%s): %w", device, err)} } } @@ -183,7 +184,7 @@ func dialTCP(device string, laddr, raddr *net.TCPAddr, dontAssumeRemote, isnonbl klog.Errorf("fileDescriptor %v Close err: %v", fileDescriptor, err) } klog.Error(err) - return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: SO_REUSEADDR: %s", err)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: SO_REUSEADDR: %w", err)} } if err = syscall.SetsockoptInt(fileDescriptor, syscall.SOL_IP, syscall.IP_TRANSPARENT, 1); err != nil { @@ -191,7 +192,7 @@ func dialTCP(device string, laddr, raddr *net.TCPAddr, dontAssumeRemote, isnonbl klog.Errorf("fileDescriptor %v Close err: %v", fileDescriptor, err) } klog.Error(err) - return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: IP_TRANSPARENT: %s", err)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: IP_TRANSPARENT: %w", err)} } if err = syscall.SetNonblock(fileDescriptor, isnonblocking); err != nil { @@ -199,7 +200,7 @@ func dialTCP(device string, laddr, raddr *net.TCPAddr, dontAssumeRemote, isnonbl klog.Errorf("fileDescriptor %v Close err: %v", fileDescriptor, err) } klog.Error(err) - return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: SO_NONBLOCK: %s", err)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("set socket option: SO_NONBLOCK: %w", err)} } if !dontAssumeRemote { @@ -208,7 +209,7 @@ func dialTCP(device string, laddr, raddr *net.TCPAddr, dontAssumeRemote, isnonbl klog.Errorf("fileDescriptor %v Close err: %v", fileDescriptor, err) } klog.Error(err) - return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("socket bind: %s", err)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("socket bind: %w", err)} } } @@ -217,7 +218,7 @@ func dialTCP(device string, laddr, raddr *net.TCPAddr, dontAssumeRemote, isnonbl klog.Errorf("fileDescriptor %v Close err: %v", fileDescriptor, err) } klog.Error(err) - return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("socket connect: %s", err)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("socket connect: %w", err)} } fdFile := os.NewFile(uintptr(fileDescriptor), fmt.Sprintf("net-tcp-dial-%s", raddr.String())) @@ -233,7 +234,7 @@ func dialTCP(device string, laddr, raddr *net.TCPAddr, dontAssumeRemote, isnonbl klog.Errorf("fileDescriptor %v Close err: %v", fileDescriptor, err) } klog.Error(err) - return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("convert file descriptor to connection: %s", err)} + return nil, &net.OpError{Op: "dial", Err: fmt.Errorf("convert file descriptor to connection: %w", err)} } return remoteConn.(*net.TCPConn), nil diff --git a/pkg/util/arp.go b/pkg/util/arp.go index 009c934453c..7f7483ba57a 100644 --- a/pkg/util/arp.go +++ b/pkg/util/arp.go @@ -18,7 +18,7 @@ import ( func ArpResolve(nic, dstIP string, timeout time.Duration, maxRetry int, done chan struct{}) (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) + return nil, 0, fmt.Errorf("failed to parse target address %s: %w", dstIP, err) } if done != nil { @@ -47,7 +47,7 @@ func ArpResolve(nic, dstIP string, timeout time.Duration, maxRetry int, done cha } } if err != nil { - return nil, count, fmt.Errorf("failed to get interface %s: %v", nic, err) + return nil, count, fmt.Errorf("failed to get interface %s: %w", nic, err) } var client *arp.Client @@ -65,7 +65,7 @@ func ArpResolve(nic, dstIP string, timeout time.Duration, maxRetry int, done cha } } if err != nil { - return nil, count, fmt.Errorf("failed to set up ARP client: %v", err) + return nil, count, fmt.Errorf("failed to set up ARP client: %w", err) } var mac net.HardwareAddr @@ -85,7 +85,7 @@ func ArpResolve(nic, dstIP string, timeout time.Duration, maxRetry int, done cha } } - return nil, count, fmt.Errorf("resolve MAC address of %s timeout: %v", dstIP, err) + return nil, count, fmt.Errorf("resolve MAC address of %s timeout: %w", dstIP, err) } func macEqual(a, b net.HardwareAddr) bool { @@ -115,7 +115,7 @@ func ArpDetectIPConflict(nic, ip string, mac net.HardwareAddr) (net.HardwareAddr tpa, err := netip.ParseAddr(ip) if err != nil { - return nil, fmt.Errorf("failed to parse IP address %s: %v", ip, err) + return nil, fmt.Errorf("failed to parse IP address %s: %w", ip, err) } ip = tpa.String() diff --git a/pkg/util/k8s.go b/pkg/util/k8s.go index bec7946c4bb..70ffa968735 100644 --- a/pkg/util/k8s.go +++ b/pkg/util/k8s.go @@ -22,7 +22,7 @@ import ( func DialTCP(host string, timeout time.Duration, verbose bool) error { u, err := url.Parse(host) if err != nil { - return fmt.Errorf("failed to parse host %q: %v", host, err) + return fmt.Errorf("failed to parse host %q: %w", host, err) } var conn net.Conn diff --git a/pkg/util/link.go b/pkg/util/link.go index 5eed6bc66ff..0de470ab3c6 100644 --- a/pkg/util/link.go +++ b/pkg/util/link.go @@ -13,10 +13,10 @@ import ( func SetLinkUp(name string) error { link, err := netlink.LinkByName(name) if err != nil { - return fmt.Errorf("failed to get link %s: %v", name, err) + return fmt.Errorf("failed to get link %s: %w", name, err) } if err = netlink.LinkSetUp(link); err != nil { - return fmt.Errorf("failed to set link %s up: %v", name, err) + return fmt.Errorf("failed to set link %s up: %w", name, err) } return nil diff --git a/pkg/util/net.go b/pkg/util/net.go index 332d3c094e0..e1e9680e3c9 100644 --- a/pkg/util/net.go +++ b/pkg/util/net.go @@ -570,7 +570,7 @@ func TCPConnectivityCheck(address string) error { func TCPConnectivityListen(address string) error { listener, err := net.Listen("tcp", address) if err != nil { - return fmt.Errorf("listen failed with err %v", err) + return fmt.Errorf("listen failed with err %w", err) } go func() { @@ -589,7 +589,7 @@ 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) + return fmt.Errorf("resolve udp addr failed with err %w", err) } conn, err := net.DialUDP("udp", nil, udpAddr) @@ -606,13 +606,13 @@ func UDPConnectivityCheck(address string) error { _, err = conn.Write([]byte("health check")) if err != nil { - return fmt.Errorf("send udp packet failed with err %v", err) + return fmt.Errorf("send udp packet failed with err %w", err) } buffer := make([]byte, 1024) _, err = conn.Read(buffer) if err != nil { - return fmt.Errorf("read udp packet from remote failed %v", err) + return fmt.Errorf("read udp packet from remote failed %w", err) } return nil @@ -621,12 +621,12 @@ func UDPConnectivityCheck(address string) error { func UDPConnectivityListen(address string) error { listenAddr, err := net.ResolveUDPAddr("udp", address) if err != nil { - return fmt.Errorf("resolve udp addr failed with err %v", err) + return fmt.Errorf("resolve udp addr failed with err %w", err) } conn, err := net.ListenUDP("udp", listenAddr) if err != nil { - return fmt.Errorf("listen udp address failed with %v", err) + return fmt.Errorf("listen udp address failed with %w", err) } buffer := make([]byte, 1024) diff --git a/pkg/util/net_test.go b/pkg/util/net_test.go index 3c8930c0fea..c7580ce4cc2 100644 --- a/pkg/util/net_test.go +++ b/pkg/util/net_test.go @@ -434,7 +434,6 @@ func TestGenerateRandomV4IP(t *testing.T) { t.Errorf("%v expected %v, but %v got", c.cidr, c.want, ans) } - } else { ans := GenerateRandomV4IP(c.cidr) if IPNets.Contains(net.ParseIP(GenerateRandomV4IP(c.cidr))) { diff --git a/pkg/util/network_attachment.go b/pkg/util/network_attachment.go index c3dacfe9a45..7c352222b56 100644 --- a/pkg/util/network_attachment.go +++ b/pkg/util/network_attachment.go @@ -2,6 +2,7 @@ package util import ( "encoding/json" + "errors" "fmt" "net" "regexp" @@ -28,7 +29,7 @@ func parsePodNetworkObjectName(podNetwork string) (string, string, string, error networkName = slashItems[0] default: klog.Errorf("parsePodNetworkObjectName: Invalid network object (failed at '/')") - return "", "", "", fmt.Errorf("parsePodNetworkObjectName: Invalid network object (failed at '/')") + return "", "", "", errors.New("parsePodNetworkObjectName: Invalid network object (failed at '/')") } atItems := strings.Split(networkName, "@") @@ -37,7 +38,7 @@ func parsePodNetworkObjectName(podNetwork string) (string, string, string, error netIfName = strings.TrimSpace(atItems[1]) } else if len(atItems) != 1 { klog.Errorf("parsePodNetworkObjectName: Invalid network object (failed at '@')") - return "", "", "", fmt.Errorf("parsePodNetworkObjectName: Invalid network object (failed at '@')") + return "", "", "", errors.New("parsePodNetworkObjectName: Invalid network object (failed at '@')") } // Check and see if each item matches the specification for valid attachment name. @@ -51,9 +52,9 @@ func parsePodNetworkObjectName(podNetwork string) (string, string, string, error klog.Errorf(fmt.Sprintf("parsePodNetworkObjectName: Failed to parse: "+ "one or more items did not match comma-delimited format (must consist of lower case alphanumeric characters). "+ "Must start and end with an alphanumeric character), mismatch @ '%v'", allItems[i])) - return "", "", "", fmt.Errorf(fmt.Sprintf("parsePodNetworkObjectName: Failed to parse: "+ + return "", "", "", fmt.Errorf("parsePodNetworkObjectName: Failed to parse: "+ "one or more items did not match comma-delimited format (must consist of lower case alphanumeric characters). "+ - "Must start and end with an alphanumeric character), mismatch @ '%v'", allItems[i])) + "Must start and end with an alphanumeric character), mismatch @ '%v'", allItems[i]) } } @@ -72,7 +73,7 @@ func ParsePodNetworkAnnotation(podNetworks, defaultNamespace string) ([]*types.N if strings.ContainsAny(podNetworks, "[{\"") { if err := json.Unmarshal([]byte(podNetworks), &networks); err != nil { klog.Errorf("parsePodNetworkAnnotation: failed to parse pod Network Attachment Selection Annotation JSON format: %v", err) - return nil, fmt.Errorf("parsePodNetworkAnnotation: failed to parse pod Network Attachment Selection Annotation JSON format: %v", err) + return nil, fmt.Errorf("parsePodNetworkAnnotation: failed to parse pod Network Attachment Selection Annotation JSON format: %w", err) } } else { // Comma-delimited list of network attachment object names @@ -84,7 +85,7 @@ func ParsePodNetworkAnnotation(podNetworks, defaultNamespace string) ([]*types.N netNsName, networkName, netIfName, err := parsePodNetworkObjectName(item) if err != nil { klog.Errorf("parsePodNetworkAnnotation: %v", err) - return nil, fmt.Errorf("parsePodNetworkAnnotation: %v", err) + return nil, fmt.Errorf("parsePodNetworkAnnotation: %w", err) } networks = append(networks, &types.NetworkSelectionElement{ @@ -103,7 +104,7 @@ func ParsePodNetworkAnnotation(podNetworks, defaultNamespace string) ([]*types.N // validate MAC address if _, err := net.ParseMAC(n.MacRequest); err != nil { klog.Errorf("parsePodNetworkAnnotation: failed to mac: %v", err) - return nil, fmt.Errorf("parsePodNetworkAnnotation: failed to mac: %v", err) + return nil, fmt.Errorf("parsePodNetworkAnnotation: failed to mac: %w", err) } } if n.IPRequest != nil { @@ -112,7 +113,7 @@ func ParsePodNetworkAnnotation(podNetworks, defaultNamespace string) ([]*types.N if strings.Contains(ip, "/") { if _, _, err := net.ParseCIDR(ip); err != nil { klog.Errorf("failed to parse CIDR %q: %v", ip, err) - return nil, fmt.Errorf("failed to parse CIDR %q: %v", ip, err) + return nil, fmt.Errorf("failed to parse CIDR %q: %w", ip, err) } } else if net.ParseIP(ip) == nil { klog.Errorf("failed to parse IP address %q", ip) diff --git a/pkg/util/validator.go b/pkg/util/validator.go index 438c2225da6..911b874e996 100644 --- a/pkg/util/validator.go +++ b/pkg/util/validator.go @@ -1,6 +1,7 @@ package util import ( + "errors" "fmt" "net" "os" @@ -18,7 +19,7 @@ func ValidateSubnet(subnet kubeovnv1.Subnet) error { return fmt.Errorf("gateway %s is not in cidr %s", subnet.Spec.Gateway, subnet.Spec.CIDRBlock) } if err := ValidateNetworkBroadcast(subnet.Spec.CIDRBlock, subnet.Spec.Gateway); err != nil { - return fmt.Errorf("validate gateway %s for cidr %s failed: %v", subnet.Spec.Gateway, subnet.Spec.CIDRBlock, err) + return fmt.Errorf("validate gateway %s for cidr %s failed: %w", subnet.Spec.Gateway, subnet.Spec.CIDRBlock, err) } } @@ -87,11 +88,11 @@ func ValidateSubnet(subnet kubeovnv1.Subnet) error { if egw := subnet.Spec.ExternalEgressGateway; egw != "" { if subnet.Spec.NatOutgoing { - return fmt.Errorf("conflict configuration: natOutgoing and externalEgressGateway") + return errors.New("conflict configuration: natOutgoing and externalEgressGateway") } ips := strings.Split(egw, ",") if len(ips) > 2 { - return fmt.Errorf("invalid external egress gateway configuration") + return errors.New("invalid external egress gateway configuration") } for _, ip := range ips { if net.ParseIP(ip) == nil { @@ -100,7 +101,7 @@ func ValidateSubnet(subnet kubeovnv1.Subnet) error { } egwProtocol, cidrProtocol := CheckProtocol(egw), CheckProtocol(subnet.Spec.CIDRBlock) if egwProtocol != cidrProtocol && cidrProtocol != kubeovnv1.ProtocolDual { - return fmt.Errorf("invalid external egress gateway configuration: address family is conflict with CIDR") + return errors.New("invalid external egress gateway configuration: address family is conflict with CIDR") } } @@ -113,7 +114,7 @@ func ValidateSubnet(subnet kubeovnv1.Subnet) error { } if subnet.Spec.LogicalGateway && subnet.Spec.U2OInterconnection { - return fmt.Errorf("logicalGateway and u2oInterconnection can't be opened at the same time") + return errors.New("logicalGateway and u2oInterconnection can't be opened at the same time") } if len(subnet.Spec.NatOutgoingPolicyRules) != 0 { @@ -140,12 +141,12 @@ func validateNatOutgoingPolicyRules(subnet kubeovnv1.Subnet) error { if rule.Match.SrcIPs != "" { if srcProtocol, err = validateNatOutGoingPolicyRuleIPs(rule.Match.SrcIPs); err != nil { - return fmt.Errorf("validate nat policy rules src ips %s failed with err %v", rule.Match.SrcIPs, err) + return fmt.Errorf("validate nat policy rules src ips %s failed with err %w", rule.Match.SrcIPs, err) } } if rule.Match.DstIPs != "" { if dstProtocol, err = validateNatOutGoingPolicyRuleIPs(rule.Match.DstIPs); err != nil { - return fmt.Errorf("validate nat policy rules dst ips %s failed with err %v", rule.Match.DstIPs, err) + return fmt.Errorf("validate nat policy rules dst ips %s failed with err %w", rule.Match.DstIPs, err) } } @@ -159,7 +160,7 @@ func validateNatOutgoingPolicyRules(subnet kubeovnv1.Subnet) error { func validateNatOutGoingPolicyRuleIPs(matchIPStr string) (string, error) { ipItems := strings.Split(matchIPStr, ",") if len(ipItems) == 0 { - return "", fmt.Errorf("MatchIPStr format error") + return "", errors.New("MatchIPStr format error") } lastProtocol := "" checkProtocolConsistent := func(ipCidr string) bool { diff --git a/pkg/webhook/ip.go b/pkg/webhook/ip.go index 9b585359ee2..b658340bc32 100644 --- a/pkg/webhook/ip.go +++ b/pkg/webhook/ip.go @@ -2,6 +2,7 @@ package webhook import ( "context" + "errors" "fmt" "net" "net/http" @@ -78,8 +79,7 @@ func (v *ValidatingHook) IPUpdateHook(ctx context.Context, req admission.Request func (v *ValidatingHook) ValidateIP(ctx context.Context, ip *ovnv1.IP) error { if ip.Spec.Subnet == "" { - err := fmt.Errorf("subnet parameter cannot be empty") - return err + return errors.New("subnet parameter cannot be empty") } subnet := &ovnv1.Subnet{} @@ -115,13 +115,11 @@ func (v *ValidatingHook) ValidateIP(ctx context.Context, ip *ovnv1.IP) error { } if ip.Spec.Subnet == "" { - err := fmt.Errorf("subnet parameter cannot be empty") - return err + return errors.New("subnet parameter cannot be empty") } if ip.Spec.PodType != "" && ip.Spec.PodType != util.VM && ip.Spec.PodType != util.StatefulSet { - err := fmt.Errorf("podType %s is not supported", ip.Spec.PodType) - return err + return fmt.Errorf("podType %s is not supported", ip.Spec.PodType) } return nil diff --git a/pkg/webhook/ovn_nat_gateway.go b/pkg/webhook/ovn_nat_gateway.go index 712aae28aeb..b9eb490f0b1 100644 --- a/pkg/webhook/ovn_nat_gateway.go +++ b/pkg/webhook/ovn_nat_gateway.go @@ -2,6 +2,7 @@ package webhook import ( "context" + "errors" "fmt" "net" "net/http" @@ -52,7 +53,7 @@ func (v *ValidatingHook) ovnEipUpdateHook(ctx context.Context, req admission.Req if eipOld.Spec != eipNew.Spec { if eipOld.Status.Ready { - err := fmt.Errorf("OvnEip not support change") + err := errors.New("OvnEip not support change") return ctrlwebhook.Errored(http.StatusBadRequest, err) } if err := v.ValidateOvnEip(ctx, &eipNew); err != nil { @@ -142,7 +143,7 @@ func (v *ValidatingHook) ovnDnatUpdateHook(ctx context.Context, req admission.Re if dnatOld.Spec != dnatNew.Spec { if dnatOld.Status.Ready { - err := fmt.Errorf("OvnDnat not support change") + err := errors.New("OvnDnat not support change") return ctrlwebhook.Errored(http.StatusBadRequest, err) } if err := v.ValidateOvnDnat(ctx, &dnatNew); err != nil { @@ -179,7 +180,7 @@ func (v *ValidatingHook) ovnSnatUpdateHook(ctx context.Context, req admission.Re if snatOld.Spec != snatNew.Spec { if snatOld.Status.Ready { - err := fmt.Errorf("OvnSnat not support change") + err := errors.New("OvnSnat not support change") return ctrlwebhook.Errored(http.StatusBadRequest, err) } if err := v.ValidateOvnSnat(ctx, &snatNew); err != nil { @@ -216,7 +217,7 @@ func (v *ValidatingHook) ovnFipUpdateHook(ctx context.Context, req admission.Req if fipNew.Spec != fipOld.Spec { if fipOld.Status.Ready { - err := fmt.Errorf("OvnFip not support change") + err := errors.New("OvnFip not support change") return ctrlwebhook.Errored(http.StatusBadRequest, err) } if err := v.ValidateOvnFip(ctx, &fipNew); err != nil { @@ -265,11 +266,11 @@ func (v *ValidatingHook) ValidateOvnEip(ctx context.Context, eip *ovnv1.OvnEip) func (v *ValidatingHook) ValidateOvnDnat(ctx context.Context, dnat *ovnv1.OvnDnatRule) error { if dnat.Spec.OvnEip == "" { - err := fmt.Errorf("should set spec ovnEip") + err := errors.New("should set spec ovnEip") return err } if dnat.Spec.IPName == "" && dnat.Spec.V4Ip == "" && dnat.Spec.V6Ip == "" { - err := fmt.Errorf("should set spec ipName or v4 or v6 Ip") + err := errors.New("should set spec ipName or v4 or v6 Ip") return err } eip := &ovnv1.OvnEip{} @@ -279,17 +280,17 @@ func (v *ValidatingHook) ValidateOvnDnat(ctx context.Context, dnat *ovnv1.OvnDna } if dnat.Spec.ExternalPort == "" { - err := fmt.Errorf("should set spec externalPort") + err := errors.New("should set spec externalPort") return err } if dnat.Spec.InternalPort == "" { - err := fmt.Errorf("should set spec internalPort") + err := errors.New("should set spec internalPort") return err } if port, err := strconv.Atoi(dnat.Spec.ExternalPort); err != nil { - errMsg := fmt.Errorf("failed to parse spec externalPort %s: %v", dnat.Spec.ExternalPort, err) + errMsg := fmt.Errorf("failed to parse spec externalPort %s: %w", dnat.Spec.ExternalPort, err) return errMsg } else if port < 0 || port > 65535 { err := fmt.Errorf("spec externalPort %s is not a valid port", dnat.Spec.ExternalPort) @@ -297,7 +298,7 @@ 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 spec internalIP %s: %v", dnat.Spec.InternalPort, err) + errMsg := fmt.Errorf("failed to parse spec internalIP %s: %w", dnat.Spec.InternalPort, err) return errMsg } else if port < 0 || port > 65535 { err := fmt.Errorf("spec internalIP %s is not a valid port", dnat.Spec.InternalPort) @@ -306,7 +307,7 @@ func (v *ValidatingHook) ValidateOvnDnat(ctx context.Context, dnat *ovnv1.OvnDna if !strings.EqualFold(dnat.Spec.Protocol, "tcp") && !strings.EqualFold(dnat.Spec.Protocol, "udp") { - err := fmt.Errorf("invaild dnat protocol: %s, support tcp or udp", dnat.Spec.Protocol) + err := fmt.Errorf("invalid dnat protocol: %s, support tcp or udp", dnat.Spec.Protocol) return err } @@ -315,28 +316,23 @@ func (v *ValidatingHook) ValidateOvnDnat(ctx context.Context, dnat *ovnv1.OvnDna func (v *ValidatingHook) ValidateOvnSnat(ctx context.Context, snat *ovnv1.OvnSnatRule) error { if snat.Spec.OvnEip == "" { - err := fmt.Errorf("should set spec OvnEip") - return err + return errors.New("should set spec OvnEip") } if snat.Spec.VpcSubnet != "" && snat.Spec.IPName != "" { - err := fmt.Errorf("should not set spec vpcSubnet and ipName at the same time") - return err + return errors.New("should not set spec vpcSubnet and ipName at the same time") } if snat.Spec.Vpc != "" && snat.Spec.V4IpCidr == "" && snat.Spec.V6IpCidr == "" { - err := fmt.Errorf("should set spec v4 or v6 IpCidr (subnet cidr or ip address) when spec vpc is set") - return err + return errors.New("should set spec v4 or v6 IpCidr (subnet cidr or ip address) when spec vpc is set") } if snat.Spec.Vpc == "" && snat.Spec.V4IpCidr != "" && snat.Spec.V6IpCidr != "" { - err := fmt.Errorf("should set spec vpc while spec v4 or v6 IpCidr is not set") - return err + return errors.New("should set spec vpc while spec v4 or v6 IpCidr is not set") } if snat.Spec.VpcSubnet == "" && snat.Spec.IPName == "" && snat.Spec.Vpc == "" && snat.Spec.V4IpCidr == "" && snat.Spec.V6IpCidr == "" { - err := fmt.Errorf("should set spec vpcSubnet or ipName or vpc and v4 and v6 IpCidr at least") - return err + return errors.New("should set spec vpcSubnet or ipName or vpc and v4 and v6 IpCidr at least") } eip := &ovnv1.OvnEip{} @@ -346,11 +342,11 @@ func (v *ValidatingHook) ValidateOvnSnat(ctx context.Context, snat *ovnv1.OvnSna func (v *ValidatingHook) ValidateOvnFip(ctx context.Context, fip *ovnv1.OvnFip) error { if fip.Spec.OvnEip == "" { - err := fmt.Errorf("should set spec ovnEip") + err := errors.New("should set spec ovnEip") return err } if fip.Spec.IPName == "" && fip.Spec.V4Ip == "" && fip.Spec.V6Ip == "" { - err := fmt.Errorf("should set spec ipName or ip") + err := errors.New("should set spec ipName or ip") return err } eip := &ovnv1.OvnEip{} diff --git a/pkg/webhook/subnet.go b/pkg/webhook/subnet.go index 365fb640550..dd8367562f1 100644 --- a/pkg/webhook/subnet.go +++ b/pkg/webhook/subnet.go @@ -2,6 +2,7 @@ package webhook import ( "context" + "errors" "fmt" "net/http" "slices" @@ -37,7 +38,7 @@ func (v *ValidatingHook) SubnetCreateHook(ctx context.Context, req admission.Req } for _, item := range vpcList.Items { if item.Name == o.Name { - err := fmt.Errorf("vpc and subnet cannot have the same name") + err := errors.New("vpc and subnet cannot have the same name") return ctrlwebhook.Errored(http.StatusBadRequest, err) } @@ -65,8 +66,7 @@ func (v *ValidatingHook) SubnetUpdateHook(ctx context.Context, req admission.Req return ctrlwebhook.Errored(http.StatusBadRequest, err) } if (o.Spec.Gateway != oldSubnet.Spec.Gateway) && (o.Status.V4UsingIPs != 0 || o.Status.V6UsingIPs != 0) { - err := fmt.Errorf("can't update gateway of cidr when any IPs in Using") - return ctrlwebhook.Denied(err.Error()) + return ctrlwebhook.Denied("can't update gateway of cidr when any IPs in Using") } if err := util.ValidateSubnet(o); err != nil { @@ -90,8 +90,7 @@ func (v *ValidatingHook) SubnetDeleteHook(_ context.Context, req admission.Reque return ctrlwebhook.Errored(http.StatusBadRequest, err) } if subnet.Status.V4UsingIPs != 0 || subnet.Status.V6UsingIPs != 0 { - err := fmt.Errorf("can't delete subnet when any IPs in Using") - return ctrlwebhook.Denied(err.Error()) + return ctrlwebhook.Denied("can't delete subnet when any IPs in Using") } return ctrlwebhook.Allowed("by pass") } diff --git a/pkg/webhook/vip.go b/pkg/webhook/vip.go index 4ea188e527d..836b5154d54 100644 --- a/pkg/webhook/vip.go +++ b/pkg/webhook/vip.go @@ -2,6 +2,7 @@ package webhook import ( "context" + "errors" "fmt" "net" "net/http" @@ -47,7 +48,7 @@ func (v *ValidatingHook) VipUpdateHook(ctx context.Context, req admission.Reques return ctrlwebhook.Errored(http.StatusBadRequest, err) } } else { - err := fmt.Errorf("vip has been assigned, not support change") + err := errors.New("vip has been assigned, not support change") return ctrlwebhook.Errored(http.StatusBadRequest, err) } } @@ -56,8 +57,7 @@ func (v *ValidatingHook) VipUpdateHook(ctx context.Context, req admission.Reques func (v *ValidatingHook) ValidateVip(ctx context.Context, vip *ovnv1.Vip) error { if vip.Spec.Subnet == "" { - err := fmt.Errorf("subnet parameter cannot be empty") - return err + return errors.New("subnet parameter cannot be empty") } subnet := &ovnv1.Subnet{} diff --git a/pkg/webhook/vpc.go b/pkg/webhook/vpc.go index f58a0d46783..655a7aeecdf 100644 --- a/pkg/webhook/vpc.go +++ b/pkg/webhook/vpc.go @@ -2,7 +2,7 @@ package webhook import ( "context" - "fmt" + "errors" "net/http" ctrlwebhook "sigs.k8s.io/controller-runtime/pkg/webhook" @@ -24,7 +24,7 @@ func (v *ValidatingHook) VpcCreateHook(ctx context.Context, req admission.Reques } for _, item := range subnetList.Items { if item.Name == vpc.Name { - err := fmt.Errorf("vpc and subnet cannot have the same name") + err := errors.New("vpc and subnet cannot have the same name") return ctrlwebhook.Errored(http.StatusBadRequest, err) } } @@ -55,8 +55,7 @@ func (v *ValidatingHook) VpcDeleteHook(_ context.Context, req admission.Request) return ctrlwebhook.Errored(http.StatusBadRequest, err) } if len(vpc.Status.Subnets) != 0 { - err := fmt.Errorf("can't delete vpc when any subnet in the vpc") - return ctrlwebhook.Denied(err.Error()) + return ctrlwebhook.Denied("can't delete vpc when any subnet in the vpc") } return ctrlwebhook.Allowed("by pass") } diff --git a/pkg/webhook/vpc_nat_gateway.go b/pkg/webhook/vpc_nat_gateway.go index 91c8042ef76..f31f199bf57 100644 --- a/pkg/webhook/vpc_nat_gateway.go +++ b/pkg/webhook/vpc_nat_gateway.go @@ -2,6 +2,7 @@ package webhook import ( "context" + "errors" "fmt" "net" "net/http" @@ -320,8 +321,7 @@ func (v *ValidatingHook) iptablesFipUpdateHook(ctx context.Context, req admissio func (v *ValidatingHook) ValidateVpcNatGW(ctx context.Context, gw *ovnv1.VpcNatGateway) error { if gw.Spec.Vpc == "" { - err := fmt.Errorf("parameter \"vpc\" cannot be empty") - return err + return errors.New("parameter \"vpc\" cannot be empty") } vpc := &ovnv1.Vpc{} key := types.NamespacedName{Name: gw.Spec.Vpc} @@ -330,8 +330,7 @@ func (v *ValidatingHook) ValidateVpcNatGW(ctx context.Context, gw *ovnv1.VpcNatG } if gw.Spec.Subnet == "" { - err := fmt.Errorf("parameter \"subnet\" cannot be empty") - return err + return errors.New("parameter \"subnet\" cannot be empty") } subnet := &ovnv1.Subnet{} @@ -354,14 +353,14 @@ func (v *ValidatingHook) ValidateVpcNatGW(ctx context.Context, gw *ovnv1.VpcNatG for _, t := range gw.Spec.Tolerations { if t.Operator != corev1.TolerationOpExists && t.Operator != corev1.TolerationOpEqual { - err := fmt.Errorf("invaild taint operator: %s, supported params: \"Equal\", \"Exists\"", t.Operator) + err := fmt.Errorf("invalid taint operator: %s, supported params: \"Equal\", \"Exists\"", t.Operator) return err } 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) + err := fmt.Errorf("invalid taint effect: %s, supported params: \"NoSchedule\", \"PreferNoSchedule\", \"NoExecute\"", t.Effect) return err } } @@ -397,8 +396,7 @@ func (v *ValidatingHook) ValidateVpcNatGatewayConfig(ctx context.Context) error func (v *ValidatingHook) ValidateIptablesEIP(ctx context.Context, eip *ovnv1.IptablesEIP) error { if eip.Spec.NatGwDp == "" { - err := fmt.Errorf("parameter \"natGwDp\" cannot be empty") - return err + return errors.New("parameter \"natGwDp\" cannot be empty") } subnet := &ovnv1.Subnet{} @@ -410,8 +408,7 @@ func (v *ValidatingHook) ValidateIptablesEIP(ctx context.Context, eip *ovnv1.Ipt if eip.Spec.V4ip != "" { if net.ParseIP(eip.Spec.V4ip) == nil { - err := fmt.Errorf("v4ip %s is not a valid", eip.Spec.V4ip) - return err + return fmt.Errorf("v4ip %s is not a valid", eip.Spec.V4ip) } if !util.CIDRContainIP(subnet.Spec.CIDRBlock, eip.Spec.V4ip) { @@ -439,8 +436,7 @@ func (v *ValidatingHook) ValidateIptablesEIP(ctx context.Context, eip *ovnv1.Ipt func (v *ValidatingHook) ValidateIptablesDnat(ctx context.Context, dnat *ovnv1.IptablesDnatRule) error { if dnat.Spec.EIP == "" { - err := fmt.Errorf("parameter \"eip\" cannot be empty") - return err + return errors.New("parameter \"eip\" cannot be empty") } eip := &ovnv1.IptablesEIP{} key := types.NamespacedName{Name: dnat.Spec.EIP} @@ -449,17 +445,15 @@ func (v *ValidatingHook) ValidateIptablesDnat(ctx context.Context, dnat *ovnv1.I } if dnat.Spec.ExternalPort == "" { - err := fmt.Errorf("parameter \"externalPort\" cannot be empty") - return err + return errors.New("parameter \"externalPort\" cannot be empty") } if dnat.Spec.InternalPort == "" { - err := fmt.Errorf("parameter \"internalPort\" cannot be empty") - return err + return errors.New("parameter \"internalPort\" cannot be empty") } if port, err := strconv.Atoi(dnat.Spec.ExternalPort); err != nil { - errMsg := fmt.Errorf("failed to parse externalPort %s: %v", dnat.Spec.ExternalPort, err) + errMsg := fmt.Errorf("failed to parse externalPort %s: %w", dnat.Spec.ExternalPort, err) return errMsg } else if port < 0 || port > 65535 { err := fmt.Errorf("externalPort %s is not a valid port", dnat.Spec.ExternalPort) @@ -467,7 +461,7 @@ 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: %w", 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) @@ -481,7 +475,7 @@ func (v *ValidatingHook) ValidateIptablesDnat(ctx context.Context, dnat *ovnv1.I if !strings.EqualFold(dnat.Spec.Protocol, "tcp") && !strings.EqualFold(dnat.Spec.Protocol, "udp") { - err := fmt.Errorf("invaild iptable protocol: %s,supported params: \"tcp\", \"udp\"", dnat.Spec.Protocol) + err := fmt.Errorf("invalid iptable protocol: %s,supported params: \"tcp\", \"udp\"", dnat.Spec.Protocol) return err } @@ -490,8 +484,7 @@ func (v *ValidatingHook) ValidateIptablesDnat(ctx context.Context, dnat *ovnv1.I func (v *ValidatingHook) ValidateIptablesSnat(ctx context.Context, snat *ovnv1.IptablesSnatRule) error { if snat.Spec.EIP == "" { - err := fmt.Errorf("parameter \"eip\" cannot be empty") - return err + return errors.New("parameter \"eip\" cannot be empty") } eip := &ovnv1.IptablesEIP{} key := types.NamespacedName{Name: snat.Spec.EIP} @@ -508,7 +501,7 @@ func (v *ValidatingHook) ValidateIptablesSnat(ctx context.Context, snat *ovnv1.I func (v *ValidatingHook) ValidateIptablesFip(ctx context.Context, fip *ovnv1.IptablesFIPRule) error { if fip.Spec.EIP == "" { - err := fmt.Errorf("parameter \"eip\" cannot be empty") + err := errors.New("parameter \"eip\" cannot be empty") return err } eip := &ovnv1.IptablesEIP{} diff --git a/test/e2e/framework/endpoints.go b/test/e2e/framework/endpoints.go index 6a06e548867..af2dca93a16 100644 --- a/test/e2e/framework/endpoints.go +++ b/test/e2e/framework/endpoints.go @@ -123,7 +123,7 @@ func (c *EndpointsClient) WaitUntil(name string, cond func(s *corev1.Endpoints) endpoints = c.Get(name).DeepCopy() met, err := cond(endpoints) if err != nil { - return false, fmt.Errorf("failed to check condition for endpoints %s: %v", name, err) + return false, fmt.Errorf("failed to check condition for endpoints %s: %w", name, err) } if met { Logf("endpoints %s met condition %q", name, condDesc) diff --git a/test/e2e/framework/ippool.go b/test/e2e/framework/ippool.go index bf6f463d12e..d7f523fd8e6 100644 --- a/test/e2e/framework/ippool.go +++ b/test/e2e/framework/ippool.go @@ -228,7 +228,7 @@ func (c *IPPoolClient) WaitUntil(name string, cond func(s *apiv1.IPPool) (bool, ippool = c.Get(name).DeepCopy() met, err := cond(ippool) if err != nil { - return false, fmt.Errorf("failed to check condition for ippool %s: %v", name, err) + return false, fmt.Errorf("failed to check condition for ippool %s: %w", name, err) } return met, nil }) diff --git a/test/e2e/framework/iproute/iproute.go b/test/e2e/framework/iproute/iproute.go index 7ac28c5d564..ccab6c1097a 100644 --- a/test/e2e/framework/iproute/iproute.go +++ b/test/e2e/framework/iproute/iproute.go @@ -98,12 +98,12 @@ func (e *execer) exec(cmd string, result interface{}) error { return nil } } - return fmt.Errorf("failed to exec cmd %q: %v\nstdout:\n%s\nstderr:\n%s", cmd, err, stdout, stderr) + return fmt.Errorf("failed to exec cmd %q: %w\nstdout:\n%s\nstderr:\n%s", cmd, err, stdout, stderr) } if result != nil { if err = json.Unmarshal(stdout, result); err != nil { - return fmt.Errorf("failed to decode json %q: %v", string(stdout), err) + return fmt.Errorf("failed to decode json %q: %w", string(stdout), err) } } diff --git a/test/e2e/framework/kubectl.go b/test/e2e/framework/kubectl.go index 111e1d4b416..979a8facd0a 100644 --- a/test/e2e/framework/kubectl.go +++ b/test/e2e/framework/kubectl.go @@ -11,7 +11,7 @@ func KubectlExec(namespace, name string, cmd ...string) (stdout, stderr []byte, c := strings.Join(cmd, " ") outStr, errStr, err := e2epodoutput.RunHostCmdWithFullOutput(namespace, name, c) if err != nil { - return nil, nil, fmt.Errorf("failed to exec cmd %q in %s of namespace %s: %v\nstderr:\n%s", c, name, namespace, err, errStr) + return nil, nil, fmt.Errorf("failed to exec cmd %q in %s of namespace %s: %w\nstderr:\n%s", c, name, namespace, err, errStr) } return []byte(outStr), []byte(errStr), nil @@ -21,7 +21,7 @@ func ovnExecSvc(db string, cmd ...string) (stdout, stderr []byte, err error) { c := strings.Join(cmd, " ") outStr, errStr, err := e2epodoutput.RunHostCmdWithFullOutput(KubeOvnNamespace, "svc/ovn-"+db, c) if err != nil { - return nil, nil, fmt.Errorf("failed to exec ovn %s cmd %q: %v\nstderr:\n%s", db, c, err, errStr) + return nil, nil, fmt.Errorf("failed to exec ovn %s cmd %q: %w\nstderr:\n%s", db, c, err, errStr) } return []byte(outStr), []byte(errStr), nil diff --git a/test/e2e/framework/qos-policy.go b/test/e2e/framework/qos-policy.go index 6dd9dcbf5e3..5cb2696e0ab 100644 --- a/test/e2e/framework/qos-policy.go +++ b/test/e2e/framework/qos-policy.go @@ -228,7 +228,7 @@ func (c *QoSPolicyClient) WaitUntil(name string, cond func(s *apiv1.QoSPolicy) ( qosPolicy = c.Get(name).DeepCopy() met, err := cond(qosPolicy) if err != nil { - return false, fmt.Errorf("failed to check condition for qosPolicy %s: %v", name, err) + return false, fmt.Errorf("failed to check condition for qosPolicy %s: %w", name, err) } return met, nil }) diff --git a/test/e2e/framework/service.go b/test/e2e/framework/service.go index 16986706444..b0ade5ee136 100644 --- a/test/e2e/framework/service.go +++ b/test/e2e/framework/service.go @@ -122,7 +122,7 @@ func (c *ServiceClient) WaitUntil(name string, cond func(s *corev1.Service) (boo service = c.Get(name).DeepCopy() met, err := cond(service) if err != nil { - return false, fmt.Errorf("failed to check condition for service %s: %v", name, err) + return false, fmt.Errorf("failed to check condition for service %s: %w", name, err) } if met { Logf("service %s met condition %q", name, condDesc) diff --git a/test/e2e/framework/subnet.go b/test/e2e/framework/subnet.go index 96fc06d4b29..8c52202f944 100644 --- a/test/e2e/framework/subnet.go +++ b/test/e2e/framework/subnet.go @@ -229,7 +229,7 @@ func (c *SubnetClient) WaitUntil(name string, cond func(s *apiv1.Subnet) (bool, subnet = c.Get(name).DeepCopy() met, err := cond(subnet) if err != nil { - return false, fmt.Errorf("failed to check condition for subnet %s: %v", name, err) + return false, fmt.Errorf("failed to check condition for subnet %s: %w", name, err) } return met, nil }) diff --git a/test/e2e/framework/switch-lb-rule.go b/test/e2e/framework/switch-lb-rule.go index 68dad61fbc6..699172a7356 100644 --- a/test/e2e/framework/switch-lb-rule.go +++ b/test/e2e/framework/switch-lb-rule.go @@ -124,7 +124,7 @@ func (c *SwitchLBRuleClient) WaitUntil(name string, cond func(s *apiv1.SwitchLBR rules = c.Get(name).DeepCopy() met, err := cond(rules) if err != nil { - return false, fmt.Errorf("failed to check condition for switch-lb-rule %s: %v", name, err) + return false, fmt.Errorf("failed to check condition for switch-lb-rule %s: %w", name, err) } if met { Logf("switch-lb-rule %s met condition %q", name, condDesc) @@ -160,7 +160,7 @@ func (c *SwitchLBRuleClient) WaitToDisappear(name string, _, timeout time.Durati return nil } -func MakeSwitchLBRule(name, namespace, vip string, sessionAffinity corev1.ServiceAffinity, annotations map[string]string, slector, endpoints []string, ports []apiv1.SlrPort) *apiv1.SwitchLBRule { +func MakeSwitchLBRule(name, namespace, vip string, sessionAffinity corev1.ServiceAffinity, annotations map[string]string, selector, endpoints []string, ports []apiv1.SlrPort) *apiv1.SwitchLBRule { return &apiv1.SwitchLBRule{ ObjectMeta: metav1.ObjectMeta{ Name: name, @@ -170,7 +170,7 @@ func MakeSwitchLBRule(name, namespace, vip string, sessionAffinity corev1.Servic Spec: apiv1.SwitchLBRuleSpec{ Vip: vip, Namespace: namespace, - Selector: slector, + Selector: selector, Endpoints: endpoints, SessionAffinity: string(sessionAffinity), Ports: ports, diff --git a/test/e2e/ha/ha_test.go b/test/e2e/ha/ha_test.go index 0ec5032bc3a..8edf62deda9 100644 --- a/test/e2e/ha/ha_test.go +++ b/test/e2e/ha/ha_test.go @@ -75,7 +75,7 @@ var _ = framework.Describe("[group:ha]", func() { }, "") db := "/etc/ovn/ovnnb_db.db" - checkCmd := fmt.Sprintf("ovsdb-tool check-cluster " + db) + checkCmd := fmt.Sprintf("ovsdb-tool check-cluster %s", db) corruptCmd := fmt.Sprintf(`bash -c 'dd if=/dev/zero of="%s" bs=1 count=$((10+$RANDOM%%10)) seek=$(stat -c %%s "%s")'`, db, db) for _, node := range nodes { ginkgo.By("Getting ovs-ovn pod running on node " + node) diff --git a/test/e2e/iptables-vpc-nat-gw/e2e_test.go b/test/e2e/iptables-vpc-nat-gw/e2e_test.go index d22a96c5c62..960c65eaf80 100644 --- a/test/e2e/iptables-vpc-nat-gw/e2e_test.go +++ b/test/e2e/iptables-vpc-nat-gw/e2e_test.go @@ -681,16 +681,16 @@ func getNicDefaultQoSPolicy(limit int) apiv1.QoSPolicyBandwidthLimitRules { &apiv1.QoSPolicyBandwidthLimitRule{ Name: "net1-ingress", Interface: "net1", - RateMax: fmt.Sprint(limit), - BurstMax: fmt.Sprint(limit), + RateMax: strconv.Itoa(limit), + BurstMax: strconv.Itoa(limit), Priority: 3, Direction: apiv1.DirectionIngress, }, &apiv1.QoSPolicyBandwidthLimitRule{ Name: "net1-egress", Interface: "net1", - RateMax: fmt.Sprint(limit), - BurstMax: fmt.Sprint(limit), + RateMax: strconv.Itoa(limit), + BurstMax: strconv.Itoa(limit), Priority: 3, Direction: apiv1.DirectionEgress, }, @@ -701,15 +701,15 @@ func getEIPQoSRule(limit int) apiv1.QoSPolicyBandwidthLimitRules { return apiv1.QoSPolicyBandwidthLimitRules{ &apiv1.QoSPolicyBandwidthLimitRule{ Name: "eip-ingress", - RateMax: fmt.Sprint(limit), - BurstMax: fmt.Sprint(limit), + RateMax: strconv.Itoa(limit), + BurstMax: strconv.Itoa(limit), Priority: 1, Direction: apiv1.DirectionIngress, }, &apiv1.QoSPolicyBandwidthLimitRule{ Name: "eip-egress", - RateMax: fmt.Sprint(limit), - BurstMax: fmt.Sprint(limit), + RateMax: strconv.Itoa(limit), + BurstMax: strconv.Itoa(limit), Priority: 1, Direction: apiv1.DirectionEgress, }, @@ -721,8 +721,8 @@ func getSpecialQoSRule(limit int, ip string) apiv1.QoSPolicyBandwidthLimitRules &apiv1.QoSPolicyBandwidthLimitRule{ Name: "net1-extip-ingress", Interface: "net1", - RateMax: fmt.Sprint(limit), - BurstMax: fmt.Sprint(limit), + RateMax: strconv.Itoa(limit), + BurstMax: strconv.Itoa(limit), Priority: 2, Direction: apiv1.DirectionIngress, MatchType: apiv1.MatchTypeIP, @@ -731,8 +731,8 @@ func getSpecialQoSRule(limit int, ip string) apiv1.QoSPolicyBandwidthLimitRules &apiv1.QoSPolicyBandwidthLimitRule{ Name: "net1-extip-egress", Interface: "net1", - RateMax: fmt.Sprint(limit), - BurstMax: fmt.Sprint(limit), + RateMax: strconv.Itoa(limit), + BurstMax: strconv.Itoa(limit), Priority: 2, Direction: apiv1.DirectionEgress, MatchType: apiv1.MatchTypeIP, @@ -765,7 +765,7 @@ func defaultQoSCases(f *framework.Framework, ginkgo.By("Patch natgw " + natgwName + " with qos policy " + qosPolicyName) _ = vpcNatGwClient.PatchQoSPolicySync(natgwName, qosPolicyName) - ginkgo.By("Check qos " + qosPolicyName + " is limited to " + fmt.Sprint(defaultNicLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is limited to " + strconv.Itoa(defaultNicLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, defaultNicLimit, true) ginkgo.By("Delete natgw pod " + natgwName + "-0") @@ -775,7 +775,7 @@ func defaultQoSCases(f *framework.Framework, ginkgo.By("Wait for natgw " + natgwName + "qos rebuild") time.Sleep(5 * time.Second) - ginkgo.By("Check qos " + qosPolicyName + " is limited to " + fmt.Sprint(defaultNicLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is limited to " + strconv.Itoa(defaultNicLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, defaultNicLimit, true) ginkgo.By("Remove qos policy " + qosPolicyName + " from natgw " + natgwName) @@ -784,7 +784,7 @@ func defaultQoSCases(f *framework.Framework, ginkgo.By("Deleting qos policy " + qosPolicyName) qosPolicyClient.DeleteSync(qosPolicyName) - ginkgo.By("Check qos " + qosPolicyName + " is not limited to " + fmt.Sprint(defaultNicLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is not limited to " + strconv.Itoa(defaultNicLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, defaultNicLimit, false) } @@ -813,7 +813,7 @@ func eipQoSCases(f *framework.Framework, ginkgo.By("Patch eip " + eipName + " with qos policy " + qosPolicyName) _ = eipClient.PatchQoSPolicySync(eipName, qosPolicyName) - ginkgo.By("Check qos " + qosPolicyName + " is limited to " + fmt.Sprint(eipLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is limited to " + strconv.Itoa(eipLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, eipLimit, true) ginkgo.By("Update qos policy " + qosPolicyName + " with new rate limit") @@ -824,7 +824,7 @@ func eipQoSCases(f *framework.Framework, qosPolicyClient.Patch(qosPolicy, modifiedqosPolicy) qosPolicyClient.WaitToQoSReady(qosPolicyName) - ginkgo.By("Check qos " + qosPolicyName + " is changed to " + fmt.Sprint(updatedEIPLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is changed to " + strconv.Itoa(updatedEIPLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, updatedEIPLimit, true) ginkgo.By("Delete natgw pod " + natgwName + "-0") @@ -834,7 +834,7 @@ func eipQoSCases(f *framework.Framework, ginkgo.By("Wait for natgw " + natgwName + "qos rebuid") time.Sleep(5 * time.Second) - ginkgo.By("Check qos " + qosPolicyName + " is limited to " + fmt.Sprint(updatedEIPLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is limited to " + strconv.Itoa(updatedEIPLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, updatedEIPLimit, true) newQoSPolicyName := "new-eip-qos-policy-" + framework.RandomSuffix() @@ -845,7 +845,7 @@ func eipQoSCases(f *framework.Framework, ginkgo.By("Change qos policy of eip " + eipName + " to " + newQoSPolicyName) _ = eipClient.PatchQoSPolicySync(eipName, newQoSPolicyName) - ginkgo.By("Check qos " + qosPolicyName + " is limited to " + fmt.Sprint(newEIPLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is limited to " + strconv.Itoa(newEIPLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, newEIPLimit, true) ginkgo.By("Remove qos policy " + qosPolicyName + " from natgw " + eipName) @@ -857,7 +857,7 @@ func eipQoSCases(f *framework.Framework, ginkgo.By("Deleting qos policy " + newQoSPolicyName) qosPolicyClient.DeleteSync(newQoSPolicyName) - ginkgo.By("Check qos " + qosPolicyName + " is not limited to " + fmt.Sprint(newEIPLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is not limited to " + strconv.Itoa(newEIPLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, newEIPLimit, false) } @@ -885,7 +885,7 @@ func specifyingIPQoSCases(f *framework.Framework, ginkgo.By("Patch natgw " + natgwName + " with qos policy " + qosPolicyName) _ = vpcNatGwClient.PatchQoSPolicySync(natgwName, qosPolicyName) - ginkgo.By("Check qos " + qosPolicyName + " is limited to " + fmt.Sprint(specificIPLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is limited to " + strconv.Itoa(specificIPLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, specificIPLimit, true) ginkgo.By("Remove qos policy " + qosPolicyName + " from natgw " + natgwName) @@ -894,7 +894,7 @@ func specifyingIPQoSCases(f *framework.Framework, ginkgo.By("Deleting qos policy " + qosPolicyName) qosPolicyClient.DeleteSync(qosPolicyName) - ginkgo.By("Check qos " + qosPolicyName + " is not limited to " + fmt.Sprint(specificIPLimit) + "Mbps") + ginkgo.By("Check qos " + qosPolicyName + " is not limited to " + strconv.Itoa(specificIPLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, specificIPLimit, false) } @@ -936,7 +936,7 @@ func priorityQoSCases(f *framework.Framework, _ = eipClient.PatchQoSPolicySync(eipName, eipQoSPolicyName) // match qos of priority 1 - ginkgo.By("Check qos to match priority 1 is limited to " + fmt.Sprint(eipLimit) + "Mbps") + ginkgo.By("Check qos to match priority 1 is limited to " + strconv.Itoa(eipLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, eipLimit, true) ginkgo.By("Remove qos policy " + eipQoSPolicyName + " from natgw " + eipName) @@ -946,7 +946,7 @@ func priorityQoSCases(f *framework.Framework, qosPolicyClient.DeleteSync(eipQoSPolicyName) // match qos of priority 2 - ginkgo.By("Check qos to match priority 2 is limited to " + fmt.Sprint(specificIPLimit) + "Mbps") + ginkgo.By("Check qos to match priority 2 is limited to " + strconv.Itoa(specificIPLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, specificIPLimit, true) // change qos policy of natgw @@ -961,7 +961,7 @@ func priorityQoSCases(f *framework.Framework, _ = vpcNatGwClient.PatchQoSPolicySync(natgwName, newNatGwQoSPolicyName) // match qos of priority 3 - ginkgo.By("Check qos to match priority 3 is limited to " + fmt.Sprint(specificIPLimit) + "Mbps") + ginkgo.By("Check qos to match priority 3 is limited to " + strconv.Itoa(specificIPLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, defaultNicLimit, true) ginkgo.By("Remove qos policy " + natGwQoSPolicyName + " from natgw " + natgwName) @@ -973,7 +973,7 @@ func priorityQoSCases(f *framework.Framework, ginkgo.By("Deleting qos policy " + newNatGwQoSPolicyName) qosPolicyClient.DeleteSync(newNatGwQoSPolicyName) - ginkgo.By("Check qos " + natGwQoSPolicyName + " is not limited to " + fmt.Sprint(defaultNicLimit) + "Mbps") + ginkgo.By("Check qos " + natGwQoSPolicyName + " is not limited to " + strconv.Itoa(defaultNicLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, defaultNicLimit, false) } @@ -1046,19 +1046,19 @@ func createNatGwAndSetQosCases(f *framework.Framework, fip := framework.MakeIptablesFIPRule(fipName, eipName, vpc1Pod.Status.PodIP) _ = fipClient.CreateSync(fip) - ginkgo.By("Check qos " + eipQoSPolicyName + " is limited to " + fmt.Sprint(eipLimit) + "Mbps") + ginkgo.By("Check qos " + eipQoSPolicyName + " is limited to " + strconv.Itoa(eipLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, eipLimit, true) ginkgo.By("Remove qos policy " + eipQoSPolicyName + " from natgw " + natgwName) _ = eipClient.PatchQoSPolicySync(eipName, "") - ginkgo.By("Check qos " + natgwQoSPolicyName + " is limited to " + fmt.Sprint(defaultNicLimit) + "Mbps") + ginkgo.By("Check qos " + natgwQoSPolicyName + " is limited to " + strconv.Itoa(defaultNicLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, defaultNicLimit, true) ginkgo.By("Remove qos policy " + natgwQoSPolicyName + " from natgw " + natgwName) _ = vpcNatGwClient.PatchQoSPolicySync(natgwName, "") - ginkgo.By("Check qos " + natgwQoSPolicyName + " is not limited to " + fmt.Sprint(defaultNicLimit) + "Mbps") + ginkgo.By("Check qos " + natgwQoSPolicyName + " is not limited to " + strconv.Itoa(defaultNicLimit) + "Mbps") checkQos(f, vpc1Pod, vpc2Pod, vpc1EIP, vpc2EIP, defaultNicLimit, false) ginkgo.By("Deleting qos policy " + natgwQoSPolicyName) diff --git a/test/e2e/kube-ovn/underlay/underlay.go b/test/e2e/kube-ovn/underlay/underlay.go index 7d63c539f9c..bd7c28ff84b 100644 --- a/test/e2e/kube-ovn/underlay/underlay.go +++ b/test/e2e/kube-ovn/underlay/underlay.go @@ -2,6 +2,7 @@ package underlay import ( "context" + "errors" "fmt" "net" "os/exec" @@ -1114,7 +1115,7 @@ func checkU2OFilterOpenFlowExist(clusterName string, pn *apiv1.ProviderNetwork, return fmt.Errorf("getting nodes in kind cluster: %w", err) } if len(nodes) == 0 { - return fmt.Errorf("no nodes found in kind cluster") + return errors.New("no nodes found in kind cluster") } for _, node := range nodes { @@ -1153,9 +1154,9 @@ func checkU2OFilterOpenFlowExist(clusterName string, pn *apiv1.ProviderNetwork, if !success { if expectRuleExist { - return fmt.Errorf("expected rule does not exist after 3 attempts") + return errors.New("expected rule does not exist after 3 attempts") } - return fmt.Errorf("unexpected rule exists after 3 attempts") + return errors.New("unexpected rule exists after 3 attempts") } } } diff --git a/test/server/server.go b/test/server/server.go index 0aa15fd4d62..49dcc438f6b 100644 --- a/test/server/server.go +++ b/test/server/server.go @@ -96,7 +96,7 @@ func main() { config := parseFlag() go func() { - output, err := exec.Command("ping", "-D", "-O", "-c", fmt.Sprintf("%d", config.DurationSeconds*100), "-i", "0.01", config.RemoteAddress).CombinedOutput() + output, err := exec.Command("ping", "-D", "-O", "-c", strconv.Itoa(int(config.DurationSeconds*100)), "-i", "0.01", config.RemoteAddress).CombinedOutput() if err != nil { klog.Errorf("%s, %v", output, err) }