Unverified Commit 01f298ef authored by YangKeao's avatar YangKeao Committed by GitHub
Browse files

Use `github.com/pkg/errors` to replace `fmt.Errorf` and `"errors"` (#2780)


* turn to use pkg/errors rather than fmt or errors
Signed-off-by: default avatarYangKeao <yangkeao@chunibyo.icu>

* use wrap to wrap the error
Signed-off-by: default avatarYangKeao <yangkeao@chunibyo.icu>

* fix CI and test
Signed-off-by: default avatarYangKeao <yangkeao@chunibyo.icu>

* restore yarn.lock
Signed-off-by: default avatarYangKeao <yangkeao@chunibyo.icu>

* replace "is empty" to "is required" in webhook message
Signed-off-by: default avatarYangKeao <yangkeao@chunibyo.icu>

* make check!
Signed-off-by: default avatarYangKeao <yangkeao@chunibyo.icu>

* use container with id
Signed-off-by: default avatarYangKeao <yangkeao@chunibyo.icu>

* replace errors.Errorf
Signed-off-by: default avatarYangKeao <yangkeao@chunibyo.icu>
Co-authored-by: default avatarSTRRL <str_ruiling@outlook.com>
parent 214c098f
Showing with 84 additions and 81 deletions
+84 -81
......@@ -19,6 +19,8 @@ import (
"context"
"time"
"github.com/pkg/errors"
"github.com/go-logr/logr"
"go.uber.org/fx"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
......@@ -98,7 +100,7 @@ func (impl *Impl) Recover(ctx context.Context, index int, records []*v1alpha1.Re
defer pbClient.Close()
}
if err != nil {
if utils.IsFailToGet(err) {
if errors.Is(err, utils.ErrContainerNotFound) {
// pretend the disappeared container has been recovered
return v1alpha1.NotInjected, nil
}
......
......@@ -19,6 +19,8 @@ import (
"context"
"time"
"github.com/pkg/errors"
"github.com/go-logr/logr"
"go.uber.org/fx"
"sigs.k8s.io/controller-runtime/pkg/client"
......@@ -84,7 +86,7 @@ func (impl *Impl) Recover(ctx context.Context, index int, records []*v1alpha1.Re
defer pbClient.Close()
}
if err != nil {
if utils.IsFailToGet(err) {
if errors.Is(err, utils.ErrContainerNotFound) {
// pretend the disappeared container has been recovered
return v1alpha1.NotInjected, nil
}
......
......@@ -15,38 +15,13 @@
package utils
import "fmt"
import (
"github.com/pkg/errors"
)
type failToFindContainer struct {
namespace string
name string
containerName string
var (
ErrUnknownType error = errors.New("unknown type")
ErrUnknownAction error = errors.New("unknown action")
err error
}
func NewFailToFindContainer(namespace string, name string, containerName string, err error) error {
return &failToFindContainer{
namespace,
name,
containerName,
err,
}
}
func (e *failToFindContainer) Error() string {
if e.err == nil {
return fmt.Sprintf("fail to find container %s on pod %s/%s", e.containerName, e.namespace, e.name)
}
return e.err.Error()
}
func IsFailToGet(e error) bool {
switch e.(type) {
case *failToFindContainer:
return true
default:
return false
}
}
ErrContainerNotFound error = errors.New("container not found")
)
......@@ -21,6 +21,8 @@ import (
v1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/pkg/errors"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/controllers/utils/chaosdaemon"
"github.com/chaos-mesh/chaos-mesh/controllers/utils/controller"
......@@ -50,20 +52,17 @@ func (d *ContainerRecordDecoder) DecodeContainerRecord(ctx context.Context, reco
var pod v1.Pod
podId, containerName, err := controller.ParseNamespacedNameContainer(record.Id)
if err != nil {
// TODO: organize the error in a better way
err = NewFailToFindContainer(pod.Namespace, pod.Name, containerName, err)
err = errors.Wrapf(ErrContainerNotFound, "container with id %s not found", record.Id)
return
}
err = d.Client.Get(ctx, podId, &pod)
if err != nil {
// TODO: organize the error in a better way
err = NewFailToFindContainer(pod.Namespace, pod.Name, containerName, err)
err = errors.Wrapf(ErrContainerNotFound, "container with id %s not found", record.Id)
return
}
decoded.Pod = &pod
if len(pod.Status.ContainerStatuses) == 0 {
// TODO: organize the error in a better way
err = NewFailToFindContainer(pod.Namespace, pod.Name, containerName, nil)
err = errors.Wrapf(ErrContainerNotFound, "container with id %s not found", record.Id)
return
}
......@@ -74,8 +73,7 @@ func (d *ContainerRecordDecoder) DecodeContainerRecord(ctx context.Context, reco
}
}
if len(decoded.ContainerId) == 0 {
// TODO: organize the error in a better way
err = NewFailToFindContainer(pod.Namespace, pod.Name, containerName, nil)
err = errors.Wrapf(ErrContainerNotFound, "container with id %s not found", record.Id)
return
}
......
......@@ -16,13 +16,14 @@
package config
import (
"fmt"
"os"
"strings"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
"github.com/pkg/errors"
"github.com/chaos-mesh/chaos-mesh/pkg/config"
)
......@@ -52,20 +53,20 @@ func init() {
func validate(config *config.ChaosControllerConfig) error {
if config.WatcherConfig == nil {
return fmt.Errorf("required WatcherConfig is missing")
return errors.New("required WatcherConfig is missing")
}
if config.ClusterScoped != config.WatcherConfig.ClusterScoped {
return fmt.Errorf("K8sConfigMapWatcher config ClusterScoped is not same with controller-manager ClusterScoped. k8s configmap watcher: %t, controller manager: %t", config.WatcherConfig.ClusterScoped, config.ClusterScoped)
return errors.Errorf("K8sConfigMapWatcher config ClusterScoped is not same with controller-manager ClusterScoped. k8s configmap watcher: %t, controller manager: %t", config.WatcherConfig.ClusterScoped, config.ClusterScoped)
}
if !config.ClusterScoped {
if strings.TrimSpace(config.TargetNamespace) == "" {
return fmt.Errorf("no target namespace specified with namespace scoped mode")
return errors.New("no target namespace specified with namespace scoped mode")
}
if config.TargetNamespace != config.WatcherConfig.TargetNamespace {
return fmt.Errorf("K8sConfigMapWatcher config TargertNamespace is not same with controller-manager TargetNamespace. k8s configmap watcher: %s, controller manager: %s", config.WatcherConfig.TargetNamespace, config.TargetNamespace)
return errors.Errorf("K8sConfigMapWatcher config TargertNamespace is not same with controller-manager TargetNamespace. k8s configmap watcher: %s, controller manager: %s", config.WatcherConfig.TargetNamespace, config.TargetNamespace)
}
}
......
......@@ -18,10 +18,10 @@ package podhttpchaos
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/go-logr/logr"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
......@@ -31,6 +31,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
"github.com/chaos-mesh/chaos-mesh/controllers/utils/chaosdaemon"
"github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
)
......@@ -110,7 +111,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
defer pbClient.Close()
if len(pod.Status.ContainerStatuses) == 0 {
err = fmt.Errorf("%s %s can't get the state of container", pod.Namespace, pod.Name)
err = errors.Wrapf(utils.ErrContainerNotFound, "pod %s/%s has empty container status", pod.Namespace, pod.Name)
r.Recorder.Event(obj, "Warning", "Failed", err.Error())
return ctrl.Result{}, nil
}
......@@ -153,7 +154,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
}
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("status(%d), apply fail: %s", res.StatusCode, res.Error)
err = errors.Errorf("status(%d), apply fail: %s", res.StatusCode, res.Error)
r.Recorder.Event(obj, "Warning", "Failed", err.Error())
return ctrl.Result{Requeue: true}, nil
}
......
......@@ -18,10 +18,10 @@ package podiochaos
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/go-logr/logr"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
......@@ -31,6 +31,7 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
"github.com/chaos-mesh/chaos-mesh/controllers/utils/chaosdaemon"
"github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
)
......@@ -114,7 +115,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
defer pbClient.Close()
if len(pod.Status.ContainerStatuses) == 0 {
err = fmt.Errorf("%s %s can't get the state of container", pod.Namespace, pod.Name)
err = errors.Wrapf(utils.ErrContainerNotFound, "pod %s/%s has empty container status", pod.Namespace, pod.Name)
r.Recorder.Event(obj, "Warning", "Failed", err.Error())
return ctrl.Result{}, nil
}
......@@ -130,7 +131,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
}
}
if len(containerID) == 0 {
err = fmt.Errorf("cannot find container with name %s", *obj.Spec.Container)
err = errors.Errorf("cannot find container with name %s", *obj.Spec.Container)
r.Recorder.Event(obj, "Warning", "Failed", err.Error())
return ctrl.Result{}, nil
}
......
......@@ -17,7 +17,6 @@ package podnetworkchaos
import (
"context"
"fmt"
"github.com/go-logr/logr"
"github.com/pkg/errors"
......@@ -184,7 +183,7 @@ func (r *Reconciler) SetIptables(ctx context.Context, pod *corev1.Pod, chaos *v1
} else if chain.Direction == v1alpha1.Output {
direction = pb.Chain_OUTPUT
} else {
err := fmt.Errorf("unknown direction %s", string(chain.Direction))
err := errors.Errorf("unknown direction %s", string(chain.Direction))
r.Log.Error(err, "unknown direction")
return err
}
......@@ -226,7 +225,7 @@ func (r *Reconciler) SetTcs(ctx context.Context, pod *corev1.Pod, chaos *v1alpha
Device: tc.Device,
})
} else {
return fmt.Errorf("unknown tc type")
return errors.New("unknown tc type")
}
}
......
......@@ -23,7 +23,10 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"github.com/pkg/errors"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
"github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/netutils"
"github.com/chaos-mesh/chaos-mesh/controllers/utils/chaosdaemon"
pb "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
......@@ -65,7 +68,8 @@ func FlushIPSets(ctx context.Context, builder *chaosdaemon.ChaosDaemonClientBuil
defer pbClient.Close()
if len(pod.Status.ContainerStatuses) == 0 {
return fmt.Errorf("%s %s can't get the state of container", pod.Namespace, pod.Name)
err = errors.Wrapf(utils.ErrContainerNotFound, "pod %s/%s has empty container status", pod.Namespace, pod.Name)
return err
}
log.Info("Flushing IP Sets....")
......@@ -87,5 +91,5 @@ func FlushIPSets(ctx context.Context, builder *chaosdaemon.ChaosDaemonClientBuil
}
}
return fmt.Errorf("unable to flush ip sets for pod %s", pod.Name)
return errors.Errorf("unable to flush ip sets for pod %s", pod.Name)
}
......@@ -23,7 +23,10 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"github.com/pkg/errors"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
"github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
"github.com/chaos-mesh/chaos-mesh/controllers/podnetworkchaos/netutils"
"github.com/chaos-mesh/chaos-mesh/controllers/utils/chaosdaemon"
pb "github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
......@@ -40,7 +43,9 @@ func SetIptablesChains(ctx context.Context, builder *chaosdaemon.ChaosDaemonClie
defer pbClient.Close()
if len(pod.Status.ContainerStatuses) == 0 {
return fmt.Errorf("%s %s can't get the state of container", pod.Namespace, pod.Name)
err = errors.Wrapf(utils.ErrContainerNotFound, "pod %s/%s has empty container status", pod.Namespace, pod.Name)
return err
}
log.Info("Setting IP Tables Chains...")
......@@ -62,7 +67,7 @@ func SetIptablesChains(ctx context.Context, builder *chaosdaemon.ChaosDaemonClie
}
}
return fmt.Errorf("unable to set ip tables chains for pod %s", pod.Name)
return errors.Errorf("unable to set ip tables chains for pod %s", pod.Name)
}
// GenerateName generates chain name for network chaos
......
......@@ -23,6 +23,9 @@ import (
ctrl "sigs.k8s.io/controller-runtime"
"github.com/pkg/errors"
"github.com/chaos-mesh/chaos-mesh/controllers/chaosimpl/utils"
"github.com/chaos-mesh/chaos-mesh/controllers/utils/chaosdaemon"
"github.com/chaos-mesh/chaos-mesh/pkg/chaosdaemon/pb"
)
......@@ -38,7 +41,9 @@ func SetTcs(ctx context.Context, builder *chaosdaemon.ChaosDaemonClientBuilder,
defer pbClient.Close()
if len(pod.Status.ContainerStatuses) == 0 {
return fmt.Errorf("%s %s can't get the state of container", pod.Namespace, pod.Name)
err = errors.Wrapf(utils.ErrContainerNotFound, "pod %s/%s has empty container status", pod.Namespace, pod.Name)
return err
}
log.Info("Settings Tcs...")
......@@ -61,5 +66,5 @@ func SetTcs(ctx context.Context, builder *chaosdaemon.ChaosDaemonClientBuilder,
}
}
return fmt.Errorf("unable to set tcs for pod %s", pod.Name)
return errors.Errorf("unable to set tcs for pod %s", pod.Name)
}
......@@ -16,9 +16,10 @@
package cron
import (
"fmt"
"time"
"github.com/pkg/errors"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
)
......@@ -30,7 +31,7 @@ import (
func getRecentUnmetScheduleTime(schedule *v1alpha1.Schedule, now time.Time) (*time.Time, *time.Time, error) {
sched, err := v1alpha1.StandardCronParser.Parse(schedule.Spec.Schedule)
if err != nil {
return nil, nil, fmt.Errorf("unparseable schedule: %s : %s", schedule.Spec.Schedule, err)
return nil, nil, errors.Errorf("unparseable schedule: %s : %s", schedule.Spec.Schedule, err)
}
var earliestTime time.Time
......@@ -47,7 +48,7 @@ func getRecentUnmetScheduleTime(schedule *v1alpha1.Schedule, now time.Time) (*ti
}
}
if earliestTime.After(now) {
return nil, nil, fmt.Errorf("earliestTime is later than now: earliestTime: %v, now: %v", earliestTime, now)
return nil, nil, errors.Errorf("earliestTime is later than now: earliestTime: %v, now: %v", earliestTime, now)
}
iterateTime := 0
......@@ -62,7 +63,7 @@ func getRecentUnmetScheduleTime(schedule *v1alpha1.Schedule, now time.Time) (*ti
iterateTime++
if iterateTime > 100 {
// We can't get the most recent times so just return an empty slice
return nil, nil, fmt.Errorf("too many missed start time (> 100). Set or decrease .spec.startingDeadlineSeconds or check clock skew")
return nil, nil, errors.New("too many missed start time (> 100). Set or decrease .spec.startingDeadlineSeconds or check clock skew")
}
}
......
......@@ -16,9 +16,10 @@
package controller
import (
"errors"
"strings"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/types"
)
......
......@@ -16,8 +16,7 @@
package controller
import (
"fmt"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
......@@ -26,7 +25,7 @@ import (
func SetOwnerReference(owner, object metav1.Object, scheme *runtime.Scheme) error {
ro, ok := owner.(runtime.Object)
if !ok {
return fmt.Errorf("%T is not a runtime.Object, cannot call SetControllerReference", owner)
return errors.Errorf("%T is not a runtime.Object, cannot call SetControllerReference", owner)
}
gvk, err := apiutil.GVKForObject(ro, scheme)
......
......@@ -18,10 +18,11 @@ package recorder
import (
"encoding"
"encoding/json"
"errors"
"reflect"
"strconv"
"github.com/pkg/errors"
"github.com/iancoleman/strcase"
)
......
......@@ -31,6 +31,8 @@ import (
"k8s.io/klog"
aggregatorclientset "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset"
"github.com/pkg/errors"
"github.com/chaos-mesh/chaos-mesh/e2e-test/e2e/e2econst"
e2eutil "github.com/chaos-mesh/chaos-mesh/e2e-test/e2e/util"
)
......@@ -68,7 +70,7 @@ func (oa *operatorAction) DeployOperator(info OperatorConfig) error {
klog.Infof(cmd)
output, err := exec.Command("/bin/sh", "-c", cmd).CombinedOutput()
if err != nil {
return fmt.Errorf("failed to create namespace chaos-testing: %v %s", err, string(output))
return errors.Errorf("failed to create namespace chaos-testing: %v %s", err, string(output))
}
klog.Infof("deploying chaos-mesh:%v", info.ReleaseName)
cmd = fmt.Sprintf(`helm install %s %s --namespace %s --set %s --skip-crds`,
......@@ -79,7 +81,7 @@ func (oa *operatorAction) DeployOperator(info OperatorConfig) error {
klog.Info(cmd)
res, err := exec.Command("/bin/sh", "-c", cmd).CombinedOutput()
if err != nil {
return fmt.Errorf("failed to deploy operator: %v, %s", err, string(res))
return errors.Errorf("failed to deploy operator: %v, %s", err, string(res))
}
klog.Infof("start to waiting chaos-mesh ready")
err = wait.Poll(5*time.Second, 5*time.Minute, func() (done bool, err error) {
......
......@@ -24,6 +24,7 @@ import (
"time"
"github.com/onsi/ginkgo"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
......@@ -508,11 +509,11 @@ func getPod(kubeCli kubernetes.Interface, ns string, appLabel string) (*v1.Pod,
}
if len(pods.Items) > 1 {
return nil, fmt.Errorf("select more than one pod")
return nil, errors.New("select more than one pod")
}
if len(pods.Items) == 0 {
return nil, fmt.Errorf("cannot select any pod")
return nil, errors.New("cannot select any pod")
}
return &pods.Items[0], nil
......
......@@ -23,6 +23,8 @@ import (
"strings"
"time"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog"
......@@ -178,7 +180,7 @@ func testDNSServer(c http.Client, port uint16, url string) (string, error) {
result := string(out)
klog.Infof("testDNSServer result: %s", result)
if strings.Contains(result, "failed") {
return "", fmt.Errorf("test DNS server failed")
return "", errors.New("test DNS server failed")
}
return result, nil
......
......@@ -16,12 +16,13 @@
package iochaos
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/pkg/errors"
)
// get pod io delay
......
......@@ -29,6 +29,8 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog"
"github.com/pkg/errors"
"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
)
......@@ -72,7 +74,7 @@ func sendUDPPacket(c http.Client, port uint16, targetIP string) error {
result := string(out)
if result != "send successfully\n" {
return fmt.Errorf("doesn't send successfully: %s", result)
return errors.Errorf("doesn't send successfully: %s", result)
}
klog.Info("send request successfully")
......@@ -97,11 +99,11 @@ func testNetworkDelay(c http.Client, port uint16, targetIP string) (int64, error
result := string(out)
parts := strings.Split(result, " ")
if len(parts) != 2 {
return 0, fmt.Errorf("the length of parts is not 2 %v", parts)
return 0, errors.Errorf("the length of parts is not 2 %v", parts)
}
if parts[0] != "OK" {
return 0, fmt.Errorf("the first part of response is not OK")
return 0, errors.New("the first part of response is not OK")
}
return strconv.ParseInt(parts[1], 10, 64)
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment