diff --git a/components/blobserve/pkg/blobserve/refstore_test.go b/components/blobserve/pkg/blobserve/refstore_test.go index 9c1a329eb0cd68..bfdf1427c80192 100644 --- a/components/blobserve/pkg/blobserve/refstore_test.go +++ b/components/blobserve/pkg/blobserve/refstore_test.go @@ -10,7 +10,6 @@ import ( "compress/gzip" "context" "encoding/json" - "fmt" "io" "net/http" "sync" @@ -20,6 +19,7 @@ import ( "github.com/google/go-cmp/cmp" ociv1 "github.com/opencontainers/image-spec/specs-go/v1" "golang.org/x/sync/errgroup" + "golang.org/x/xerrors" ) func TestBlobFor(t *testing.T) { @@ -172,7 +172,7 @@ func TestBlobFor(t *testing.T) { ExtraAction: func(t *testing.T, s *refstore) (err error) { _, _, err = s.BlobFor(context.Background(), refDescriptor, false) if err == nil { - return fmt.Errorf("found layer although we shouldn't have") + return xerrors.Errorf("found layer although we shouldn't have") } s.Resolver = func() remotes.Resolver { return &fakeFetcher{ @@ -233,7 +233,7 @@ func TestBlobFor(t *testing.T) { } _, _, err := s.BlobFor(ctx, refDescriptor, false) if err != nil { - return fmt.Errorf("client %03d: %w", i, err) + return xerrors.Errorf("client %03d: %w", i, err) } return nil }) @@ -355,11 +355,11 @@ func TestBlobFor(t *testing.T) { oadd := bs.Adder bs.Adder = func(ctx context.Context, name string, in io.Reader) (err error) { - return fmt.Errorf("failed to download") + return xerrors.Errorf("failed to download") } _, _, err := s.BlobFor(context.Background(), refDescriptor, false) if err == nil { - return fmt.Errorf("first download didn't fail") + return xerrors.Errorf("first download didn't fail") } bs.Adder = oadd @@ -457,7 +457,7 @@ func (f *fakeFetcher) Resolve(ctx context.Context, ref string) (name string, des name = ref fc, ok := f.Content[ref] if !ok { - err = fmt.Errorf("not found") + err = xerrors.Errorf("not found") return } c, err := fc() @@ -471,7 +471,7 @@ func (f *fakeFetcher) Resolve(ctx context.Context, ref string) (name string, des // Pusher returns a new pusher for the provided reference func (f *fakeFetcher) Pusher(ctx context.Context, ref string) (remotes.Pusher, error) { - return nil, fmt.Errorf("not implemented") + return nil, xerrors.Errorf("not implemented") } // Fetcher returns a new fetcher for the provided reference. @@ -484,7 +484,7 @@ func (f *fakeFetcher) Fetcher(ctx context.Context, ref string) (remotes.Fetcher, func (f *fakeFetcher) Fetch(ctx context.Context, desc ociv1.Descriptor) (io.ReadCloser, error) { fc, ok := f.Content[desc.Digest.Encoded()] if !ok { - return nil, fmt.Errorf("%s not found", desc.Digest.Encoded()) + return nil, xerrors.Errorf("%s not found", desc.Digest.Encoded()) } c, err := fc() if err != nil { diff --git a/components/content-service/pkg/initializer/initializer.go b/components/content-service/pkg/initializer/initializer.go index 0ebdd46045af4e..37c02c346cab9e 100644 --- a/components/content-service/pkg/initializer/initializer.go +++ b/components/content-service/pkg/initializer/initializer.go @@ -186,7 +186,7 @@ type fromBackupInitializer struct { func (bi *fromBackupInitializer) Run(ctx context.Context, mappings []archive.IDMapping) (src csapi.WorkspaceInitSource, err error) { hasBackup, err := bi.RemoteStorage.Download(ctx, bi.Location, storage.DefaultBackup, mappings) if !hasBackup { - return src, fmt.Errorf("no backup found") + return src, xerrors.Errorf("no backup found") } if err != nil { return src, xerrors.Errorf("cannot restore backup: %w", err) diff --git a/components/content-service/pkg/logs/logs.go b/components/content-service/pkg/logs/logs.go index d006d1b33bf6b1..a1cb8b11c2aa00 100644 --- a/components/content-service/pkg/logs/logs.go +++ b/components/content-service/pkg/logs/logs.go @@ -10,6 +10,8 @@ import ( "os" "path/filepath" "strings" + + "golang.org/x/xerrors" ) const ( @@ -84,7 +86,7 @@ func ParseTaskIDFromPrebuildLogFilePath(filePath string) (string, error) { streamID = strings.TrimPrefix(fileName, prebuildLogFilePrefix) } if streamID == "" { - return "", fmt.Errorf("cannot parse stream ID from filePath: '%s'", fileName) + return "", xerrors.Errorf("cannot parse stream ID from filePath: '%s'", fileName) } return streamID, nil diff --git a/components/content-service/pkg/storage/gcloud.go b/components/content-service/pkg/storage/gcloud.go index 06ab0b60c56d71..3a8b0d33c64ee6 100644 --- a/components/content-service/pkg/storage/gcloud.go +++ b/components/content-service/pkg/storage/gcloud.go @@ -318,7 +318,7 @@ func (rs *DirectGCPStorage) Qualify(name string) string { // UploadInstance takes all files from a local location and uploads it to the per-instance remote storage func (rs *DirectGCPStorage) UploadInstance(ctx context.Context, source string, name string, opts ...UploadOption) (bucket, object string, err error) { if rs.InstanceID == "" { - return "", "", fmt.Errorf("instanceID is required to comput object name") + return "", "", xerrors.Errorf("instanceID is required to comput object name") } return rs.Upload(ctx, source, InstanceObjectName(rs.InstanceID, name), opts...) } diff --git a/components/content-service/pkg/storage/minio.go b/components/content-service/pkg/storage/minio.go index 93e09caf009e4c..6014888583a351 100644 --- a/components/content-service/pkg/storage/minio.go +++ b/components/content-service/pkg/storage/minio.go @@ -247,7 +247,7 @@ func (rs *DirectMinIOStorage) Qualify(name string) string { // UploadInstance takes all files from a local location and uploads it to the per-instance remote storage func (rs *DirectMinIOStorage) UploadInstance(ctx context.Context, source string, name string, opts ...UploadOption) (bucket, object string, err error) { if rs.InstanceID == "" { - return "", "", fmt.Errorf("instanceID is required to comput object name") + return "", "", xerrors.Errorf("instanceID is required to comput object name") } return rs.Upload(ctx, source, InstanceObjectName(rs.InstanceID, name), opts...) } diff --git a/components/content-service/pkg/storage/storage.go b/components/content-service/pkg/storage/storage.go index c6491036ab262d..1aff473d180568 100644 --- a/components/content-service/pkg/storage/storage.go +++ b/components/content-service/pkg/storage/storage.go @@ -32,7 +32,7 @@ const ( var ( // ErrNotFound is returned when an object is not found - ErrNotFound = fmt.Errorf("not found") + ErrNotFound = xerrors.Errorf("not found") ) // BucketNamer provides names for storage buckets diff --git a/components/docker-up/docker-up/main.go b/components/docker-up/docker-up/main.go index bd2237a50de0d3..58feb22f9625a6 100644 --- a/components/docker-up/docker-up/main.go +++ b/components/docker-up/docker-up/main.go @@ -29,6 +29,7 @@ import ( "github.com/sirupsen/logrus" "github.com/spf13/pflag" "golang.org/x/sys/unix" + "golang.org/x/xerrors" ) var log *logrus.Entry @@ -106,7 +107,7 @@ func runWithinNetns() (err error) { return err } if msg.Stage != 1 { - return fmt.Errorf("expected stage 1 message, got %+q", msg) + return xerrors.Errorf("expected stage 1 message, got %+q", msg) } log.Debug("parent is ready") @@ -284,7 +285,7 @@ func ensurePrerequisites() error { return nil } - errMissingPrerequisites := fmt.Errorf("missing prerequisites") + errMissingPrerequisites := xerrors.Errorf("missing prerequisites") if !opts.AutoInstall { return errMissingPrerequisites } @@ -323,7 +324,7 @@ func installDocker() error { return nil } - return fmt.Errorf("Unable to extract container: %v\n", err) + return xerrors.Errorf("Unable to extract container: %v\n", err) } hdrInfo := hdr.FileInfo() @@ -340,12 +341,12 @@ func installDocker() error { case tar.TypeReg, tar.TypeRegA: file, err := os.OpenFile(dstpath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode) if err != nil { - return fmt.Errorf("unable to create file: %v", err) + return xerrors.Errorf("unable to create file: %v", err) } if _, err := io.Copy(file, tarReader); err != nil { file.Close() - return fmt.Errorf("unable to write file: %v", err) + return xerrors.Errorf("unable to write file: %v", err) } file.Close() diff --git a/components/docker-up/runc-facade/main.go b/components/docker-up/runc-facade/main.go index 5ef71bb57bebe1..5b5a1dae9f877d 100644 --- a/components/docker-up/runc-facade/main.go +++ b/components/docker-up/runc-facade/main.go @@ -6,13 +6,13 @@ package main import ( "encoding/json" - "fmt" "os" "os/exec" "syscall" "github.com/opencontainers/runtime-spec/specs-go" "github.com/sirupsen/logrus" + "golang.org/x/xerrors" ) var ( @@ -50,31 +50,31 @@ func main() { func createAndRunc(runcPath string) error { fc, err := os.ReadFile("config.json") if err != nil { - return fmt.Errorf("cannot read config.json: %w", err) + return xerrors.Errorf("cannot read config.json: %w", err) } var cfg specs.Spec err = json.Unmarshal(fc, &cfg) if err != nil { - return fmt.Errorf("cannot decode config.json: %w", err) + return xerrors.Errorf("cannot decode config.json: %w", err) } cfg.Process.OOMScoreAdj = &defaultOOMScoreAdj fc, err = json.Marshal(cfg) if err != nil { - return fmt.Errorf("cannot encode config.json: %w", err) + return xerrors.Errorf("cannot encode config.json: %w", err) } for _, fn := range []string{"config.json", "/tmp/debug.json"} { err = os.WriteFile(fn, fc, 0644) if err != nil { - return fmt.Errorf("cannot encode config.json: %w", err) + return xerrors.Errorf("cannot encode config.json: %w", err) } } err = syscall.Exec(runcPath, os.Args, os.Environ()) if err != nil { - return fmt.Errorf("exec %s: %w", runcPath, err) + return xerrors.Errorf("exec %s: %w", runcPath, err) } return nil } diff --git a/components/docker-up/slirp-docker-proxy/main.go b/components/docker-up/slirp-docker-proxy/main.go index a57f89a1cf0992..a0938c8bd469bf 100644 --- a/components/docker-up/slirp-docker-proxy/main.go +++ b/components/docker-up/slirp-docker-proxy/main.go @@ -71,7 +71,7 @@ func xmain(f *os.File) error { if examplePort == 0 { examplePort = 8080 } - return fmt.Errorf("Workspace (host) port needs to be > 1024, e.g. %d:%d instead of %d:%d", examplePort, *containerPort, *hostPort, *containerPort) + return xerrors.Errorf("Workspace (host) port needs to be > 1024, e.g. %d:%d instead of %d:%d", examplePort, *containerPort, *hostPort, *containerPort) } id, err := exposePort(socketPath) @@ -196,7 +196,7 @@ func sendRequest(socketPath string, req request) (resp map[string]interface{}, e } if len(rep.Error) > 0 { - return nil, fmt.Errorf("error reply: %+v", rep.Error) + return nil, xerrors.Errorf("error reply: %+v", rep.Error) } return rep.Return, nil } diff --git a/components/ee/agent-smith/cmd/run.go b/components/ee/agent-smith/cmd/run.go index 970d4040de3b72..c006d8db2005ac 100644 --- a/components/ee/agent-smith/cmd/run.go +++ b/components/ee/agent-smith/cmd/run.go @@ -22,6 +22,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/spf13/cobra" + "golang.org/x/xerrors" ) // runCmd represents the run command @@ -182,7 +183,7 @@ func notifySlack(webhook string, hostURL string, ws agent.InfringingWorkspace, p for i, err := range errs { allerr[i] = err.Error() } - return fmt.Errorf("notifySlack: %s", strings.Join(allerr, ", ")) + return xerrors.Errorf("notifySlack: %s", strings.Join(allerr, ", ")) } return nil diff --git a/components/ee/agent-smith/pkg/agent/actions.go b/components/ee/agent-smith/pkg/agent/actions.go index faacaee1b34efb..c55982a50c355b 100644 --- a/components/ee/agent-smith/pkg/agent/actions.go +++ b/components/ee/agent-smith/pkg/agent/actions.go @@ -6,13 +6,13 @@ package agent import ( "context" - "fmt" wsk8s "github.com/gitpod-io/gitpod/common-go/kubernetes" "github.com/gitpod-io/gitpod/common-go/log" protocol "github.com/gitpod-io/gitpod/gitpod-protocol" "golang.org/x/sys/unix" + "golang.org/x/xerrors" corev1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/util/retry" ) @@ -38,7 +38,7 @@ func (agent *Smith) stopWorkspaceAndBlockUser(supervisorPID int, ownerID string) func (agent *Smith) blockUser(ownerID string) error { if agent.GitpodAPI == nil { - return fmt.Errorf("not connected to Gitpod API") + return xerrors.Errorf("not connected to Gitpod API") } req := protocol.AdminBlockUserRequest{ @@ -50,10 +50,10 @@ func (agent *Smith) blockUser(ownerID string) error { func (agent *Smith) limitCPUUse(podname string) error { if agent.Kubernetes == nil { - return fmt.Errorf("not connected to Kubernetes - cannot limit CPU usage") + return xerrors.Errorf("not connected to Kubernetes - cannot limit CPU usage") } if agent.Config.Enforcement.CPULimitPenalty == "" { - return fmt.Errorf("no CPU limit penalty specified - cannot limit CPU usage") + return xerrors.Errorf("no CPU limit penalty specified - cannot limit CPU usage") } ctx := context.Background() diff --git a/components/ee/agent-smith/pkg/agent/agent.go b/components/ee/agent-smith/pkg/agent/agent.go index 6411e5d5d6358f..676729f4a59d20 100644 --- a/components/ee/agent-smith/pkg/agent/agent.go +++ b/components/ee/agent-smith/pkg/agent/agent.go @@ -321,7 +321,7 @@ func (g GradedInfringementKind) Kind() (InfringementKind, error) { } } - return "", fmt.Errorf("unknown kind") + return "", xerrors.Errorf("unknown kind") } // defaultRuleset is the name ("remote origin URL") of the default enforcement rules @@ -334,7 +334,7 @@ type EnforcementRules map[GradedInfringementKind]PenaltyKind func (er EnforcementRules) Validate() error { for k := range er { if _, err := k.Kind(); err != nil { - return fmt.Errorf("%s: %w", k, err) + return xerrors.Errorf("%s: %w", k, err) } } @@ -346,7 +346,7 @@ func (er EnforcementRules) Validate() error { } for _, v := range er { if _, ok := validPenalties[v]; !ok { - return fmt.Errorf("%s: unknown penalty", v) + return xerrors.Errorf("%s: unknown penalty", v) } } @@ -803,7 +803,7 @@ func getWorkspaceFromProcess(tid int) (res *InfringingWorkspace, err error) { } } if supervisor.PID == 0 || workspacekit.PID == 0 { - return nil, fmt.Errorf("did not find supervisor or workspacekit parent") + return nil, xerrors.Errorf("did not find supervisor or workspacekit parent") } env, err := workspacekit.Environ() diff --git a/components/ee/agent-smith/pkg/bpf/bpf.go b/components/ee/agent-smith/pkg/bpf/bpf.go index b4d9942c1b473c..5747d6df5a0b91 100644 --- a/components/ee/agent-smith/pkg/bpf/bpf.go +++ b/components/ee/agent-smith/pkg/bpf/bpf.go @@ -6,12 +6,12 @@ package bpf import ( "encoding/binary" - "fmt" "os" "runtime" "time" "golang.org/x/sys/unix" + "golang.org/x/xerrors" "github.com/cilium/ebpf" "github.com/cilium/ebpf/link" @@ -92,10 +92,10 @@ func adjustPerCPUMaps(maps map[string]*ebpf.MapSpec) { func getMap(coll *ebpf.Collection, name string) (*ebpf.Map, error) { mapObj, ok := coll.Maps[name] if !ok { - return nil, fmt.Errorf("%s not found", name) + return nil, xerrors.Errorf("%s not found", name) } if mapObj == nil { - return nil, fmt.Errorf("%s is nil", name) + return nil, xerrors.Errorf("%s is nil", name) } return mapObj, nil } @@ -144,7 +144,7 @@ func populateSyscallTableMap(coll *ebpf.Collection) error { } for k, v := range SyscallsTable { if err := syscallTableMap.Update(k, &v, ebpf.UpdateAny); err != nil { - return fmt.Errorf("error updating the syscalls table map: %v", err) + return xerrors.Errorf("error updating the syscalls table map: %v", err) } } return nil @@ -157,7 +157,7 @@ func populateFillersTableMap(coll *ebpf.Collection) error { } for k, v := range FillersTable { if err := fillersTableMap.Update(k, &v, ebpf.UpdateAny); err != nil { - return fmt.Errorf("error updating the syscalls table map: %v", err) + return xerrors.Errorf("error updating the syscalls table map: %v", err) } } return nil @@ -170,7 +170,7 @@ func populateEventTableMap(coll *ebpf.Collection) error { } for k, v := range EventTable { if err := eventTableMap.Update(k, &v, ebpf.UpdateAny); err != nil { - return fmt.Errorf("error updating the event table map: %v", err) + return xerrors.Errorf("error updating the event table map: %v", err) } } return nil @@ -188,7 +188,7 @@ func populateFillersMap(coll *ebpf.Collection) error { fillerID := fillersHash[name] progfd := uint32(prog.FD()) if err := tailMapObj.Update(&fillerID, &progfd, ebpf.UpdateAny); err != nil { - return fmt.Errorf("error updating the fillers map: %v", err) + return xerrors.Errorf("error updating the fillers map: %v", err) } } return nil @@ -218,18 +218,18 @@ func LoadAndAttach(elfPath string) (*AgentSmithBPFProgram, error) { enterProg, ok := coll.Programs[bpfSysEnterProgram] if !ok { - return nil, fmt.Errorf("syscall enter program not found") + return nil, xerrors.Errorf("syscall enter program not found") } if enterProg == nil { - return nil, fmt.Errorf("syscall enter program is nil") + return nil, xerrors.Errorf("syscall enter program is nil") } exitProg, ok := coll.Programs[bpfSysExitProgram] if !ok { - return nil, fmt.Errorf("syscall exit program not found") + return nil, xerrors.Errorf("syscall exit program not found") } if exitProg == nil { - return nil, fmt.Errorf("syscall exit program is nil") + return nil, xerrors.Errorf("syscall exit program is nil") } if err := populateFillersMap(coll); err != nil { @@ -285,7 +285,7 @@ func LoadAndAttach(elfPath string) (*AgentSmithBPFProgram, error) { enterHook, err := link.AttachRawTracepoint(enterRawTracepoint) if err != nil { - return nil, fmt.Errorf("error registering enter hook for enter raw tracepoint: %s", err.Error()) + return nil, xerrors.Errorf("error registering enter hook for enter raw tracepoint: %s", err.Error()) } abpf.enterLink = &enterHook @@ -296,7 +296,7 @@ func LoadAndAttach(elfPath string) (*AgentSmithBPFProgram, error) { exitHook, err := link.AttachRawTracepoint(exitRawTracepoint) if err != nil { - return nil, fmt.Errorf("error registering exit hook for exit raw tracepoint: %s", err.Error()) + return nil, xerrors.Errorf("error registering exit hook for exit raw tracepoint: %s", err.Error()) } abpf.exitLink = &exitHook @@ -308,7 +308,7 @@ func LoadAndAttach(elfPath string) (*AgentSmithBPFProgram, error) { eventsReader, err := perf.NewReader(perfMapObj, totalSize) if err != nil { - return nil, fmt.Errorf("error setting up perf reader for events: %s", err.Error()) + return nil, xerrors.Errorf("error setting up perf reader for events: %s", err.Error()) } abpf.reader = eventsReader diff --git a/components/ee/kedge/cmd/root.go b/components/ee/kedge/cmd/root.go index 51ccc0fee68dee..bc062f1b9e1014 100644 --- a/components/ee/kedge/cmd/root.go +++ b/components/ee/kedge/cmd/root.go @@ -14,6 +14,7 @@ import ( "github.com/gitpod-io/gitpod/common-go/util" "github.com/gitpod-io/gitpod/kedge/pkg/kedge" "github.com/spf13/cobra" + "golang.org/x/xerrors" ) var ( @@ -53,7 +54,7 @@ func init() { func getConfig() (*config, error) { fc, err := ioutil.ReadFile(cfgFile) if err != nil { - return nil, fmt.Errorf("cannot read config: %w", err) + return nil, xerrors.Errorf("cannot read config: %w", err) } var cfg config diff --git a/components/ee/kedge/go.mod b/components/ee/kedge/go.mod index 549c03eeeac163..467fc1ee0de5a5 100644 --- a/components/ee/kedge/go.mod +++ b/components/ee/kedge/go.mod @@ -6,6 +6,7 @@ require ( github.com/alecthomas/jsonschema v0.0.0-20190122210438-a6952de1bbe6 github.com/gitpod-io/gitpod/common-go v0.0.0-00010101000000-000000000000 github.com/spf13/cobra v1.1.3 + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 k8s.io/api v0.22.0 k8s.io/apimachinery v0.22.0 k8s.io/client-go v0.0.0 diff --git a/components/ee/kedge/pkg/kedge/collector.go b/components/ee/kedge/pkg/kedge/collector.go index 9a446193915c0a..0e816eb997b11b 100644 --- a/components/ee/kedge/pkg/kedge/collector.go +++ b/components/ee/kedge/pkg/kedge/collector.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "golang.org/x/xerrors" "k8s.io/client-go/kubernetes" ) @@ -21,22 +22,22 @@ func Collect(url, token string) ([]Service, error) { } req, err := http.NewRequest("GET", url, nil) if err != nil { - return nil, fmt.Errorf("cannot create new HTTP request: %w", err) + return nil, xerrors.Errorf("cannot create new HTTP request: %w", err) } // req.SetBasicAuth("Bearer", token) req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) response, err := client.Do(req) if err != nil { - return nil, fmt.Errorf("unable to make request: %w", err) + return nil, xerrors.Errorf("unable to make request: %w", err) } defer response.Body.Close() if response.StatusCode != http.StatusOK { - return nil, fmt.Errorf("HTTP request returned non-OK status: %s", response.Status) + return nil, xerrors.Errorf("HTTP request returned non-OK status: %s", response.Status) } var result []Service if err := json.NewDecoder(response.Body).Decode(&result); err != nil { - return nil, fmt.Errorf("cannot unmarshal response: %w", err) + return nil, xerrors.Errorf("cannot unmarshal response: %w", err) } return result, nil } diff --git a/components/ee/kedge/pkg/kedge/kubernetes.go b/components/ee/kedge/pkg/kedge/kubernetes.go index 4b696fe43ec174..2ae0ed6ef81e51 100644 --- a/components/ee/kedge/pkg/kedge/kubernetes.go +++ b/components/ee/kedge/pkg/kedge/kubernetes.go @@ -12,6 +12,7 @@ import ( "time" "github.com/gitpod-io/gitpod/common-go/log" + "golang.org/x/xerrors" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -62,7 +63,7 @@ func Discover(clientset kubernetes.Interface, namespace string, services []strin api := clientset.CoreV1() existingServiceList, err := api.Services(namespace).List(context.Background(), metav1.ListOptions{}) if err != nil { - return nil, fmt.Errorf("cannot get services: %w", err) + return nil, xerrors.Errorf("cannot get services: %w", err) } existingServiceIdx := make(map[string]corev1.Service) for _, s := range existingServiceList.Items { @@ -70,7 +71,7 @@ func Discover(clientset kubernetes.Interface, namespace string, services []strin } endpoints, err := api.Endpoints(namespace).List(context.Background(), metav1.ListOptions{}) if err != nil { - return nil, fmt.Errorf("cannot get endpoints: %w", err) + return nil, xerrors.Errorf("cannot get endpoints: %w", err) } endpointIdx := make(map[string]corev1.Endpoints) for _, e := range endpoints.Items { @@ -103,7 +104,7 @@ func Install(clientset kubernetes.Interface, namespace string, source string, se api := clientset.CoreV1() serviceList, err := api.Services(namespace).List(context.Background(), metav1.ListOptions{}) if err != nil { - return nil, fmt.Errorf("cannot get services: %w", err) + return nil, xerrors.Errorf("cannot get services: %w", err) } serviceIdx := make(map[string]corev1.Service) for _, s := range serviceList.Items { @@ -121,7 +122,7 @@ func Install(clientset kubernetes.Interface, namespace string, source string, se } } else { if err := createTargetService(clientset, namespace, source, serviceName, srv); err != nil { - return nil, fmt.Errorf("cannot create target service: %w", err) + return nil, xerrors.Errorf("cannot create target service: %w", err) } log.WithField("src", srv.Service.Name).WithField("dst", serviceName).Debug("created service") res = append(res, serviceName) @@ -129,12 +130,12 @@ func Install(clientset kubernetes.Interface, namespace string, source string, se shouldCreateEndpoint, err := clearTargetEndpoints(clientset, namespace, serviceName, srv) if err != nil { - return nil, fmt.Errorf("cannot clear target endpoints: %w", err) + return nil, xerrors.Errorf("cannot clear target endpoints: %w", err) } if shouldCreateEndpoint { err := createTargetEndpoints(clientset, namespace, source, serviceName, srv) if err != nil { - return nil, fmt.Errorf("cannot create target endooints: %w", err) + return nil, xerrors.Errorf("cannot create target endooints: %w", err) } log.WithField("src", srv.Service.Name).WithField("dst", serviceName).Debug("created endpoints") } @@ -151,7 +152,7 @@ func ClearLegacyServices(clientset kubernetes.Interface, namespace string) (err servicesAPI := clientset.CoreV1().Services(namespace) services, err := servicesAPI.List(context.Background(), metav1.ListOptions{LabelSelector: kedgeLegacyLabelSelector}) if err != nil { - return fmt.Errorf("cannot get services: %w", err) + return xerrors.Errorf("cannot get services: %w", err) } for _, s := range services.Items { err = servicesAPI.Delete(context.Background(), s.Name, metav1.DeleteOptions{ @@ -168,7 +169,7 @@ func ClearLegacyServices(clientset kubernetes.Interface, namespace string) (err endpointsAPI := clientset.CoreV1().Endpoints(namespace) endpoints, err := endpointsAPI.List(context.Background(), metav1.ListOptions{LabelSelector: kedgeLegacyLabelSelector}) if err != nil { - return fmt.Errorf("cannot get endpoints: %w", err) + return xerrors.Errorf("cannot get endpoints: %w", err) } for _, e := range endpoints.Items { err = endpointsAPI.Delete(context.Background(), e.Name, metav1.DeleteOptions{ @@ -190,7 +191,7 @@ func ClearServices(clientset kubernetes.Interface, namespace, source string) (er servicesAPI := clientset.CoreV1().Services(namespace) services, err := servicesAPI.List(context.Background(), metav1.ListOptions{LabelSelector: fmt.Sprintf("%s=%s", LabelSource, source)}) if err != nil { - return fmt.Errorf("cannot get services: %w", err) + return xerrors.Errorf("cannot get services: %w", err) } for _, s := range services.Items { err = servicesAPI.Delete(context.Background(), s.Name, metav1.DeleteOptions{ @@ -207,7 +208,7 @@ func ClearServices(clientset kubernetes.Interface, namespace, source string) (er endpointsAPI := clientset.CoreV1().Endpoints(namespace) endpoints, err := endpointsAPI.List(context.Background(), metav1.ListOptions{LabelSelector: fmt.Sprintf("%s=%s", LabelSource, source)}) if err != nil { - return fmt.Errorf("cannot get endpoints: %w", err) + return xerrors.Errorf("cannot get endpoints: %w", err) } for _, e := range endpoints.Items { err = endpointsAPI.Delete(context.Background(), e.Name, metav1.DeleteOptions{ @@ -259,7 +260,7 @@ func createTargetService(clientset kubernetes.Interface, namespace, source, name _, err := api.Services(namespace).Create(context.Background(), targetService, metav1.CreateOptions{}) if err != nil { - return fmt.Errorf("cannot create target service: %w", err) + return xerrors.Errorf("cannot create target service: %w", err) } return nil } @@ -268,7 +269,7 @@ func clearTargetEndpoints(clientset kubernetes.Interface, namespace string, name api := clientset.CoreV1().Endpoints(namespace) endpoints, err := api.List(context.Background(), metav1.ListOptions{LabelSelector: kedgeLabelSelector}) if err != nil { - return false, fmt.Errorf("cannot get endpoints: %w", err) + return false, xerrors.Errorf("cannot get endpoints: %w", err) } found := false @@ -301,7 +302,7 @@ func clearTargetEndpoints(clientset kubernetes.Interface, namespace string, name err = api.Delete(context.Background(), name, metav1.DeleteOptions{PropagationPolicy: &defaultPropagationPolicy}) if err != nil { - return false, fmt.Errorf("cannot delete existing endpoint: %w", err) + return false, xerrors.Errorf("cannot delete existing endpoint: %w", err) } log.WithField("name", name).WithField("namespace", namespace).Debug("deleted previous endpoint") @@ -336,7 +337,7 @@ func clearTargetEndpoints(clientset kubernetes.Interface, namespace string, name case <-done: return true, nil case <-time.After(120 * time.Second): - return false, fmt.Errorf("timeout while waiting for the endpoints to be deleted") + return false, xerrors.Errorf("timeout while waiting for the endpoints to be deleted") } } @@ -365,7 +366,7 @@ func createTargetEndpoints(clientset kubernetes.Interface, namespace, source, na _, err := clientset.CoreV1().Endpoints(namespace).Create(context.Background(), targetEndpoint, metav1.CreateOptions{}) if err != nil { - return fmt.Errorf("cannot create endpoint: %w", err) + return xerrors.Errorf("cannot create endpoint: %w", err) } return nil } diff --git a/components/ee/kedge/pkg/registration/pool.go b/components/ee/kedge/pkg/registration/pool.go index eeb222746f8ab0..fc200d6bd85b46 100644 --- a/components/ee/kedge/pkg/registration/pool.go +++ b/components/ee/kedge/pkg/registration/pool.go @@ -6,12 +6,12 @@ package registration import ( "errors" - "fmt" "sync" "time" "github.com/gitpod-io/gitpod/common-go/log" "github.com/gitpod-io/gitpod/kedge/pkg/kedge" + "golang.org/x/xerrors" "k8s.io/client-go/kubernetes" ) @@ -61,12 +61,12 @@ func (c *CollectorPool) Start(period time.Duration) { func (c *CollectorPool) AddCollector(collector kedge.Collector) error { err := c.Store.Add(collector) if err != nil { - return fmt.Errorf("cannot add collector: %w", err) + return xerrors.Errorf("cannot add collector: %w", err) } err = c.collect(collector, true) if err != nil { - return fmt.Errorf("initial collection failed: %w", err) + return xerrors.Errorf("initial collection failed: %w", err) } return nil @@ -98,14 +98,14 @@ func (c *CollectorPool) collect(collector kedge.Collector, isDynamic bool) error log.Warn("removing dynamic collector") err = c.Store.Remove(name) if err != nil { - return fmt.Errorf("cannot remove failed collector from store: %w", err) + return xerrors.Errorf("cannot remove failed collector from store: %w", err) } } if failures >= c.FailureTTLService || collectorFailure { log.Warn("removing collected services") err = kedge.ClearServices(c.Clientset, c.Namespace, name) if err != nil { - return fmt.Errorf("cannot clear previously collected services: %w", err) + return xerrors.Errorf("cannot clear previously collected services: %w", err) } } @@ -116,7 +116,7 @@ func (c *CollectorPool) collect(collector kedge.Collector, isDynamic bool) error // maybe the install failed though if err != nil { - return fmt.Errorf("cannot install service endpoints: %w", err) + return xerrors.Errorf("cannot install service endpoints: %w", err) } // everything went according to plan - let's tell the world diff --git a/components/ee/kedge/pkg/registration/store.go b/components/ee/kedge/pkg/registration/store.go index 8511e2c70d21ee..278da29e3c5385 100644 --- a/components/ee/kedge/pkg/registration/store.go +++ b/components/ee/kedge/pkg/registration/store.go @@ -8,10 +8,10 @@ import ( "context" "encoding/json" "errors" - "fmt" "net/http" "github.com/gitpod-io/gitpod/kedge/pkg/kedge" + "golang.org/x/xerrors" corev1 "k8s.io/api/core/v1" k8serr "k8s.io/apimachinery/pkg/api/errors" @@ -77,7 +77,7 @@ func NewKubernetesStore(clientset kubernetes.Interface, namespace, secretName st }, }, metav1.CreateOptions{}) if err != nil { - return nil, fmt.Errorf("cannot create storage secret: %w", err) + return nil, xerrors.Errorf("cannot create storage secret: %w", err) } } @@ -106,7 +106,7 @@ func (ks *KubernetesStore) Add(c kedge.Collector) error { } if _, exists := obj.Data[c.Name]; exists { - return fmt.Errorf("%s: %w", c.Name, ErrAlreadyExists) + return xerrors.Errorf("%s: %w", c.Name, ErrAlreadyExists) } obj.Data[c.Name] = data diff --git a/components/ee/ws-scheduler/pkg/scheduler/internal/kubernetes.go b/components/ee/ws-scheduler/pkg/scheduler/internal/kubernetes.go index d6d970b819e1c4..eb05f1f4c211ef 100644 --- a/components/ee/ws-scheduler/pkg/scheduler/internal/kubernetes.go +++ b/components/ee/ws-scheduler/pkg/scheduler/internal/kubernetes.go @@ -5,8 +5,7 @@ package internal import ( - "fmt" - + "golang.org/x/xerrors" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/labels" @@ -92,7 +91,7 @@ func nodeSelectorRequirementsAsSelector(nsm []corev1.NodeSelectorRequirement) (l case corev1.NodeSelectorOpLt: op = selection.LessThan default: - return nil, fmt.Errorf("%q is not a valid node selector operator", expr.Operator) + return nil, xerrors.Errorf("%q is not a valid node selector operator", expr.Operator) } r, err := labels.NewRequirement(expr.Key, op, expr.Values) if err != nil { @@ -115,20 +114,20 @@ func nodeSelectorRequirementsAsFieldSelector(nsm []corev1.NodeSelectorRequiremen switch expr.Operator { case corev1.NodeSelectorOpIn: if len(expr.Values) != 1 { - return nil, fmt.Errorf("unexpected number of value (%d) for node field selector operator %q", + return nil, xerrors.Errorf("unexpected number of value (%d) for node field selector operator %q", len(expr.Values), expr.Operator) } selectors = append(selectors, fields.OneTermEqualSelector(expr.Key, expr.Values[0])) case corev1.NodeSelectorOpNotIn: if len(expr.Values) != 1 { - return nil, fmt.Errorf("unexpected number of value (%d) for node field selector operator %q", + return nil, xerrors.Errorf("unexpected number of value (%d) for node field selector operator %q", len(expr.Values), expr.Operator) } selectors = append(selectors, fields.OneTermNotEqualSelector(expr.Key, expr.Values[0])) default: - return nil, fmt.Errorf("%q is not a valid node field selector operator", expr.Operator) + return nil, xerrors.Errorf("%q is not a valid node field selector operator", expr.Operator) } } diff --git a/components/ee/ws-scheduler/pkg/scheduler/scheduler_scheduling_test.go b/components/ee/ws-scheduler/pkg/scheduler/scheduler_scheduling_test.go index e8f35b7ca63e08..1b023186471fae 100644 --- a/components/ee/ws-scheduler/pkg/scheduler/scheduler_scheduling_test.go +++ b/components/ee/ws-scheduler/pkg/scheduler/scheduler_scheduling_test.go @@ -6,12 +6,12 @@ package scheduler import ( "context" - "fmt" "strings" "testing" "time" wsk8s "github.com/gitpod-io/gitpod/common-go/kubernetes" + "golang.org/x/xerrors" corev1 "k8s.io/api/core/v1" res "k8s.io/apimachinery/pkg/api/resource" @@ -414,7 +414,7 @@ func TestSchedulePod(t *testing.T) { p.Spec.NodeName = nodeName return nil } - return fmt.Errorf("could not find pod to bind: %s", pod.Name) + return xerrors.Errorf("could not find pod to bind: %s", pod.Name) } createEvent := func(ctx context.Context, namespace string, event *corev1.Event, opts metav1.CreateOptions) error { // drop all events as they are not needed for functionality and the fake clienset does not support them diff --git a/components/gitpod-cli/cmd/env.go b/components/gitpod-cli/cmd/env.go index f3ce8934cb1ee8..0585d0010d842f 100644 --- a/components/gitpod-cli/cmd/env.go +++ b/components/gitpod-cli/cmd/env.go @@ -296,18 +296,18 @@ func parseArgs(args []string, pattern string) ([]*serverapi.UserEnvVarValue, err for i, arg := range args { kv := strings.SplitN(arg, "=", 1) if len(kv) != 1 || kv[0] == "" { - return nil, fmt.Errorf("empty string (correct format is key=value)") + return nil, xerrors.Errorf("empty string (correct format is key=value)") } if !strings.Contains(kv[0], "=") { - return nil, fmt.Errorf("%s has no equal character (correct format is %s=some_value)", arg, arg) + return nil, xerrors.Errorf("%s has no equal character (correct format is %s=some_value)", arg, arg) } parts := strings.SplitN(kv[0], "=", 2) key := strings.TrimSpace(parts[0]) if key == "" { - return nil, fmt.Errorf("variable must have a name") + return nil, xerrors.Errorf("variable must have a name") } // Do not trim value - the user might want whitespace here @@ -319,7 +319,7 @@ func parseArgs(args []string, pattern string) ([]*serverapi.UserEnvVarValue, err val = strings.ReplaceAll(val, `\ `, " ") if val == "" { - return nil, fmt.Errorf("variable must have a value; use -u to unset a variable") + return nil, xerrors.Errorf("variable must have a value; use -u to unset a variable") } vars[i] = &serverapi.UserEnvVarValue{Name: key, Value: val, RepositoryPattern: pattern} diff --git a/components/gitpod-cli/pkg/theialib/mock.go b/components/gitpod-cli/pkg/theialib/mock.go index 32e5d53204f64d..7ba116a96820f7 100644 --- a/components/gitpod-cli/pkg/theialib/mock.go +++ b/components/gitpod-cli/pkg/theialib/mock.go @@ -9,8 +9,9 @@ package theialib import ( - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" ) // MockTheiaCLIService is a mock of TheiaCLIService interface diff --git a/components/gitpod-cli/pkg/theialib/service.go b/components/gitpod-cli/pkg/theialib/service.go index aa2b42c1b51d93..185488346d0f35 100644 --- a/components/gitpod-cli/pkg/theialib/service.go +++ b/components/gitpod-cli/pkg/theialib/service.go @@ -15,6 +15,7 @@ import ( "time" "github.com/pkg/errors" + "golang.org/x/xerrors" ) // HTTPTheiaService provides access to Theia's CLI service @@ -38,7 +39,7 @@ func NewServiceFromEnv() (*HTTPTheiaService, error) { apiToken := os.Getenv("GITPOD_CLI_APITOKEN") if apiToken == "" { - return nil, fmt.Errorf("No GITPOD_CLI_APITOKEN environment variable set") + return nil, xerrors.Errorf("No GITPOD_CLI_APITOKEN environment variable set") } service := &HTTPTheiaService{ @@ -58,7 +59,7 @@ func NewServiceFromEnv() (*HTTPTheiaService, error) { service.ideError = err } if resp.StatusCode != http.StatusOK { - service.ideError = fmt.Errorf("IDE is not ready, %d %s", resp.StatusCode, resp.Status) + service.ideError = xerrors.Errorf("IDE is not ready, %d %s", resp.StatusCode, resp.Status) } }() @@ -72,7 +73,7 @@ type request struct { var ( // ErrNotFound is returned when an object is not found - ErrNotFound = fmt.Errorf("not found") + ErrNotFound = xerrors.Errorf("not found") ) func (service *HTTPTheiaService) sendRequest(req request) ([]byte, error) { @@ -98,11 +99,11 @@ func (service *HTTPTheiaService) sendRequest(req request) ([]byte, error) { } if resp.StatusCode == 403 { - return nil, fmt.Errorf("not authenticated") + return nil, xerrors.Errorf("not authenticated") } else if resp.StatusCode == 404 { return nil, ErrNotFound } else if resp.StatusCode != 200 { - return nil, fmt.Errorf("invalid request: %v", resp.StatusCode) + return nil, xerrors.Errorf("invalid request: %v", resp.StatusCode) } res, err := io.ReadAll(resp.Body) @@ -153,7 +154,7 @@ func (service *HTTPTheiaService) OpenFile(params OpenFileRequest) (*OpenFileResp } else if err != nil { return nil, err } else if stat.IsDir() { - return nil, fmt.Errorf("%s is a directory - can only open files", absPath) + return nil, xerrors.Errorf("%s is a directory - can only open files", absPath) } params.Path = absPath diff --git a/components/gitpod-protocol/go/gitpod-config-types.go b/components/gitpod-protocol/go/gitpod-config-types.go index b1b6ce6fa88a57..3a4a9fc3bc8801 100644 --- a/components/gitpod-protocol/go/gitpod-config-types.go +++ b/components/gitpod-protocol/go/gitpod-config-types.go @@ -10,7 +10,8 @@ import ( "bytes" "encoding/json" "errors" - "fmt" + + "golang.org/x/xerrors" ) // Env Environment variables to set. @@ -175,7 +176,7 @@ func (strct *Github) UnmarshalJSON(b []byte) error { return err } default: - return fmt.Errorf("additional property not allowed: \"" + k + "\"") + return xerrors.Errorf("additional property not allowed: \"" + k + "\"") } } return nil @@ -335,7 +336,7 @@ func (strct *GitpodConfig) UnmarshalJSON(b []byte) error { return err } default: - return fmt.Errorf("additional property not allowed: \"" + k + "\"") + return xerrors.Errorf("additional property not allowed: \"" + k + "\"") } } return nil @@ -394,7 +395,7 @@ func (strct *Image_object) UnmarshalJSON(b []byte) error { } fileReceived = true default: - return fmt.Errorf("additional property not allowed: \"" + k + "\"") + return xerrors.Errorf("additional property not allowed: \"" + k + "\"") } } // check if file (a required property) was received @@ -502,7 +503,7 @@ func (strct *PortsItems) UnmarshalJSON(b []byte) error { return err } default: - return fmt.Errorf("additional property not allowed: \"" + k + "\"") + return xerrors.Errorf("additional property not allowed: \"" + k + "\"") } } // check if port (a required property) was received @@ -651,7 +652,7 @@ func (strct *TasksItems) UnmarshalJSON(b []byte) error { return err } default: - return fmt.Errorf("additional property not allowed: \"" + k + "\"") + return xerrors.Errorf("additional property not allowed: \"" + k + "\"") } } return nil @@ -691,7 +692,7 @@ func (strct *Vscode) UnmarshalJSON(b []byte) error { return err } default: - return fmt.Errorf("additional property not allowed: \"" + k + "\"") + return xerrors.Errorf("additional property not allowed: \"" + k + "\"") } } return nil diff --git a/components/image-builder-bob/go.mod b/components/image-builder-bob/go.mod index 26bd75ff16cf6d..f689ba9ac13a1c 100644 --- a/components/image-builder-bob/go.mod +++ b/components/image-builder-bob/go.mod @@ -15,6 +15,7 @@ require ( go.opencensus.io v0.23.0 // indirect golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 google.golang.org/grpc v1.39.1 ) diff --git a/components/image-builder-bob/pkg/builder/builder.go b/components/image-builder-bob/pkg/builder/builder.go index fcf6ca1cdfb3d2..f60782d1577883 100644 --- a/components/image-builder-bob/pkg/builder/builder.go +++ b/components/image-builder-bob/pkg/builder/builder.go @@ -7,7 +7,6 @@ package builder import ( "context" "errors" - "fmt" "io/ioutil" "os" "os/exec" @@ -23,6 +22,7 @@ import ( "github.com/moby/buildkit/session" "github.com/moby/buildkit/util/progress/progressui" "golang.org/x/sync/errgroup" + "golang.org/x/xerrors" ) const ( @@ -93,7 +93,7 @@ func (b *Builder) buildBaseLayer(ctx context.Context, cl *client.Client) error { if baselayerAuth := b.Config.BaseLayerAuth; baselayerAuth != "" { auth, err := newAuthProviderFromEnvvar(baselayerAuth) if err != nil { - return fmt.Errorf("invalid base layer authentication: %w", err) + return xerrors.Errorf("invalid base layer authentication: %w", err) } sess = append(sess, auth) } @@ -155,7 +155,7 @@ func (b *Builder) buildBaseLayer(ctx context.Context, cl *client.Client) error { if lauth := b.Config.WorkspaceLayerAuth; lauth != "" { auth, err := newAuthProviderFromEnvvar(lauth) if err != nil { - return fmt.Errorf("invalid gp layer authentication: %w", err) + return xerrors.Errorf("invalid gp layer authentication: %w", err) } solveOpt.Session = []session.Attachable{auth} } @@ -221,7 +221,7 @@ func (b *Builder) buildWorkspaceImage(ctx context.Context, cl *client.Client) (e eg.Go(func() error { _, err := cl.Solve(ctx, def, solveOpt, ch) if err != nil { - return fmt.Errorf("cannot build Gitpod layer: %w", err) + return xerrors.Errorf("cannot build Gitpod layer: %w", err) } return nil }) @@ -262,11 +262,11 @@ func waitForBuildContext(ctx context.Context) error { func StartBuildkit(socketPath string) (cl *client.Client, teardown func() error, err error) { stderr, err := ioutil.TempFile(os.TempDir(), "buildkitd_stderr") if err != nil { - return nil, nil, fmt.Errorf("cannot create buildkitd log file: %w", err) + return nil, nil, xerrors.Errorf("cannot create buildkitd log file: %w", err) } stdout, err := ioutil.TempFile(os.TempDir(), "buildkitd_stdout") if err != nil { - return nil, nil, fmt.Errorf("cannot create buildkitd log file: %w", err) + return nil, nil, xerrors.Errorf("cannot create buildkitd log file: %w", err) } cmd := exec.Command("buildkitd", "--addr="+socketPath, "--oci-worker-net=host", "--root=/workspace/buildkit") @@ -293,7 +293,7 @@ func StartBuildkit(socketPath string) (cl *client.Client, teardown func() error, log.WithField("buildkitd-stderr", string(serr)).WithField("buildkitd-stdout", string(sout)).Error("buildkitd failure") }() if err != nil { - return nil, nil, fmt.Errorf("cannot start buildkitd: %w", err) + return nil, nil, xerrors.Errorf("cannot start buildkitd: %w", err) } teardown = func() error { @@ -341,5 +341,5 @@ func connectToBuildkitd(socketPath string) (cl *client.Client, err error) { return } - return nil, fmt.Errorf("cannot connect to buildkitd") + return nil, xerrors.Errorf("cannot connect to buildkitd") } diff --git a/components/image-builder-bob/pkg/builder/config.go b/components/image-builder-bob/pkg/builder/config.go index ad6e67bbd855b1..53a320685925f9 100644 --- a/components/image-builder-bob/pkg/builder/config.go +++ b/components/image-builder-bob/pkg/builder/config.go @@ -8,12 +8,12 @@ import ( "crypto/aes" "crypto/cipher" "encoding/base64" - "fmt" "os" "path/filepath" "strings" "github.com/moby/buildkit/client" + "golang.org/x/xerrors" ) // Config configures a builder @@ -46,32 +46,32 @@ func GetConfigFromEnv() (*Config, error) { } if cfg.BaseRef == "" { - return nil, fmt.Errorf("BOB_BASE_REF must not be empty") + return nil, xerrors.Errorf("BOB_BASE_REF must not be empty") } if cfg.TargetRef == "" { - return nil, fmt.Errorf("BOB_TARGET_REF must not be empty") + return nil, xerrors.Errorf("BOB_TARGET_REF must not be empty") } if cfg.BuildBase { if cfg.Dockerfile == "" { - return nil, fmt.Errorf("When building the base image BOB_DOCKERFILE_PATH is mandatory") + return nil, xerrors.Errorf("When building the base image BOB_DOCKERFILE_PATH is mandatory") } var err error cfg.Dockerfile, err = filepath.Abs(cfg.Dockerfile) if err != nil { - return nil, fmt.Errorf("cannot make BOB_DOCKERFILE_PATH absolute: %w", err) + return nil, xerrors.Errorf("cannot make BOB_DOCKERFILE_PATH absolute: %w", err) } if !strings.HasPrefix(cfg.Dockerfile, "/workspace") { - return nil, fmt.Errorf("BOB_DOCKERFILE_PATH must begin with /workspace") + return nil, xerrors.Errorf("BOB_DOCKERFILE_PATH must begin with /workspace") } if stat, err := os.Stat(cfg.Dockerfile); err != nil || stat.IsDir() { - return nil, fmt.Errorf("BOB_DOCKERFILE_PATH does not exist or isn't a file") + return nil, xerrors.Errorf("BOB_DOCKERFILE_PATH does not exist or isn't a file") } } var authKey = os.Getenv("BOB_AUTH_KEY") if authKey != "" { if len(authKey) != 32 { - return nil, fmt.Errorf("BOB_AUTH_KEY must be exactly 32 bytes long") + return nil, xerrors.Errorf("BOB_AUTH_KEY must be exactly 32 bytes long") } // we have an authkey, hence assume that the auth fields are base64 encoded and encrypted @@ -79,22 +79,22 @@ func GetConfigFromEnv() (*Config, error) { dec := make([]byte, base64.RawStdEncoding.DecodedLen(len(cfg.BaseLayerAuth))) _, err := base64.RawStdEncoding.Decode(dec, []byte(cfg.BaseLayerAuth)) if err != nil { - return nil, fmt.Errorf("BOB_BASELAYER_AUTH is not base64 encoded but BOB_AUTH_KEY is present") + return nil, xerrors.Errorf("BOB_BASELAYER_AUTH is not base64 encoded but BOB_AUTH_KEY is present") } cfg.BaseLayerAuth, err = decrypt(dec, authKey) if err != nil { - return nil, fmt.Errorf("cannot decrypt BOB_BASELAYER_AUTH: %w", err) + return nil, xerrors.Errorf("cannot decrypt BOB_BASELAYER_AUTH: %w", err) } } if cfg.WorkspaceLayerAuth != "" { dec := make([]byte, base64.RawStdEncoding.DecodedLen(len(cfg.WorkspaceLayerAuth))) _, err := base64.RawStdEncoding.Decode(dec, []byte(cfg.WorkspaceLayerAuth)) if err != nil { - return nil, fmt.Errorf("BOB_WSLAYER_AUTH is not base64 encoded but BOB_AUTH_KEY is present") + return nil, xerrors.Errorf("BOB_WSLAYER_AUTH is not base64 encoded but BOB_AUTH_KEY is present") } cfg.WorkspaceLayerAuth, err = decrypt(dec, authKey) if err != nil { - return nil, fmt.Errorf("cannot decrypt BOB_WSLAYER_AUTH: %w", err) + return nil, xerrors.Errorf("cannot decrypt BOB_WSLAYER_AUTH: %w", err) } } } @@ -132,7 +132,7 @@ func decrypt(ciphertext []byte, key string) (string, error) { nonceSize := gcm.NonceSize() if len(ciphertext) < nonceSize { - return "", fmt.Errorf("ciphertext too short") + return "", xerrors.Errorf("ciphertext too short") } nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:] diff --git a/components/image-builder-mk3/pkg/orchestrator/monitor.go b/components/image-builder-mk3/pkg/orchestrator/monitor.go index f045861cb76221..95dc532980cd34 100644 --- a/components/image-builder-mk3/pkg/orchestrator/monitor.go +++ b/components/image-builder-mk3/pkg/orchestrator/monitor.go @@ -161,7 +161,7 @@ func (m *buildMonitor) handleHeadlessLogs(buildID string) listenToHeadlessLogsCa } } -var errOutOfRetries = fmt.Errorf("out of retries") +var errOutOfRetries = xerrors.Errorf("out of retries") // retry makes multiple attempts to execute op if op returns an UNAVAILABLE gRPC status code func retry(ctx context.Context, op func(ctx context.Context) error, retry func(err error) bool, initialBackoff time.Duration, retries int) (err error) { diff --git a/components/image-builder-mk3/pkg/orchestrator/orchestrator.go b/components/image-builder-mk3/pkg/orchestrator/orchestrator.go index ab5e3643bc5f99..c079d692cebfb7 100644 --- a/components/image-builder-mk3/pkg/orchestrator/orchestrator.go +++ b/components/image-builder-mk3/pkg/orchestrator/orchestrator.go @@ -112,7 +112,7 @@ func NewOrchestratingBuilder(cfg Configuration) (res *Orchestrator, err error) { return } if len(data) != 32 { - err = fmt.Errorf("builder auth key must be exactly 32 bytes long") + err = xerrors.Errorf("builder auth key must be exactly 32 bytes long") return } copy(builderAuthKey[:], data) diff --git a/components/image-builder-mk3/pkg/resolve/resolve.go b/components/image-builder-mk3/pkg/resolve/resolve.go index 9680ecb2bd0254..d7e3651622a180 100644 --- a/components/image-builder-mk3/pkg/resolve/resolve.go +++ b/components/image-builder-mk3/pkg/resolve/resolve.go @@ -6,7 +6,6 @@ package resolve import ( "context" - "fmt" "strings" "sync" "time" @@ -23,7 +22,7 @@ import ( ) // ErrNotFound is returned when the reference was not found -var ErrNotFound = fmt.Errorf("not found") +var ErrNotFound = xerrors.Errorf("not found") // StandaloneRefResolver can resolve image references without a Docker daemon type StandaloneRefResolver struct { diff --git a/components/image-builder-mk3/pkg/resolve/resolve_test.go b/components/image-builder-mk3/pkg/resolve/resolve_test.go index fa30fcea77f1d9..1633647794308a 100644 --- a/components/image-builder-mk3/pkg/resolve/resolve_test.go +++ b/components/image-builder-mk3/pkg/resolve/resolve_test.go @@ -6,7 +6,6 @@ package resolve_test import ( "context" - "fmt" "testing" "github.com/containerd/containerd/errdefs" @@ -14,6 +13,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/opencontainers/go-digest" ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "golang.org/x/xerrors" "github.com/gitpod-io/gitpod/image-builder/pkg/resolve" ) @@ -101,8 +101,8 @@ func (f *fakeResolver) Resolve(ctx context.Context, ref string) (name string, de return c.Name, c.Desc, nil } func (*fakeResolver) Fetcher(ctx context.Context, ref string) (remotes.Fetcher, error) { - return nil, fmt.Errorf("not supporter") + return nil, xerrors.Errorf("not supporter") } func (*fakeResolver) Pusher(ctx context.Context, ref string) (remotes.Pusher, error) { - return nil, fmt.Errorf("not supporter") + return nil, xerrors.Errorf("not supporter") } diff --git a/components/image-builder/go.mod b/components/image-builder/go.mod index df75afe20f6428..fe936813fb3c8f 100644 --- a/components/image-builder/go.mod +++ b/components/image-builder/go.mod @@ -22,7 +22,6 @@ require ( github.com/mattn/go-isatty v0.0.11 github.com/morikuni/aec v1.0.0 // indirect github.com/opencontainers/go-digest v1.0.0 - github.com/opencontainers/image-spec v1.0.1 github.com/opentracing/opentracing-go v1.2.0 github.com/prometheus/client_golang v1.11.0 github.com/sirupsen/logrus v1.8.1 @@ -65,6 +64,7 @@ require ( github.com/moby/term v0.0.0-20210610120745-9d4ed1856297 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.1 // indirect + github.com/opencontainers/image-spec v1.0.1 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/prometheus/client_model v0.2.0 // indirect github.com/prometheus/common v0.26.0 // indirect diff --git a/components/image-builder/pkg/resolve/dockerclient_mock_test.go b/components/image-builder/pkg/resolve/dockerclient_mock_test.go index 7a5faa0eb9ac79..01fc1fc5f982a9 100644 --- a/components/image-builder/pkg/resolve/dockerclient_mock_test.go +++ b/components/image-builder/pkg/resolve/dockerclient_mock_test.go @@ -10,9 +10,10 @@ package resolve_test import ( context "context" + reflect "reflect" + registry "github.com/docker/docker/api/types/registry" gomock "github.com/golang/mock/gomock" - reflect "reflect" ) // MockDistributionAPIClient is a mock of DistributionAPIClient interface diff --git a/components/image-builder/pkg/resolve/resolve_test.go b/components/image-builder/pkg/resolve/resolve_test.go index c84662532add4d..678775c70386f2 100644 --- a/components/image-builder/pkg/resolve/resolve_test.go +++ b/components/image-builder/pkg/resolve/resolve_test.go @@ -11,12 +11,13 @@ import ( "fmt" "testing" - "github.com/gitpod-io/gitpod/image-builder/pkg/resolve" - registry "github.com/docker/docker/api/types/registry" "github.com/golang/mock/gomock" digest "github.com/opencontainers/go-digest" - "github.com/opencontainers/image-spec/specs-go/v1" + v1 "github.com/opencontainers/image-spec/specs-go/v1" + "golang.org/x/xerrors" + + "github.com/gitpod-io/gitpod/image-builder/pkg/resolve" ) func TestDockerRegistryResolver(t *testing.T) { @@ -28,7 +29,7 @@ func TestDockerRegistryResolver(t *testing.T) { {"alpine:latest", "docker.io/library/alpine:latest", nil}, {"alpine:3.14", "docker.io/library/alpine:3.14", nil}, {"gitpod/workspace-full:build-branch-master", "docker.io/gitpod/workspace-full:build-branch-master", nil}, - {"gitpod/does-not-exist", "docker.io/gitpod/does-not-exist", fmt.Errorf("does not exist")}, + {"gitpod/does-not-exist", "docker.io/gitpod/does-not-exist", xerrors.Errorf("does not exist")}, } ctrl := gomock.NewController(t) diff --git a/components/licensor/ee/cmd/sign.go b/components/licensor/ee/cmd/sign.go index 292b7c5aa59c01..212376ed5c3bea 100644 --- a/components/licensor/ee/cmd/sign.go +++ b/components/licensor/ee/cmd/sign.go @@ -12,6 +12,7 @@ import ( "time" "github.com/spf13/cobra" + "golang.org/x/xerrors" "github.com/gitpod-io/gitpod/licensor/ee/pkg/licensor" ) @@ -29,10 +30,10 @@ var signCmd = &cobra.Command{ } block, _ := pem.Decode(fc) if block == nil { - return fmt.Errorf("no PEM encoded key found in %s", keyfn) + return xerrors.Errorf("no PEM encoded key found in %s", keyfn) } if block.Type != "PRIVATE KEY" { - return fmt.Errorf("unknown PEM block type %s", block.Type) + return xerrors.Errorf("unknown PEM block type %s", block.Type) } priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { @@ -47,24 +48,24 @@ var signCmd = &cobra.Command{ validFor, _ = cmd.Flags().GetDuration("valid-for") ) if domain == "" { - return fmt.Errorf("--domain is mandatory") + return xerrors.Errorf("--domain is mandatory") } if id == "" { - return fmt.Errorf("--id is mandatory") + return xerrors.Errorf("--id is mandatory") } if level == "" { - return fmt.Errorf("--level is mandatory") + return xerrors.Errorf("--level is mandatory") } if seats < 0 { - return fmt.Errorf("--seats must be positive") + return xerrors.Errorf("--seats must be positive") } if validFor <= 0 { - return fmt.Errorf("--valid-for must be positive") + return xerrors.Errorf("--valid-for must be positive") } lvl, ok := licensor.NamedLevel[level] if !ok { - return fmt.Errorf("invalid license level: %s", level) + return xerrors.Errorf("invalid license level: %s", level) } l := licensor.LicensePayload{ diff --git a/components/licensor/ee/cmd/validate.go b/components/licensor/ee/cmd/validate.go index 3227ed04177faf..ccc2d54b906c8d 100644 --- a/components/licensor/ee/cmd/validate.go +++ b/components/licensor/ee/cmd/validate.go @@ -11,6 +11,7 @@ import ( "os" "github.com/spf13/cobra" + "golang.org/x/xerrors" "github.com/gitpod-io/gitpod/licensor/ee/pkg/licensor" ) @@ -34,7 +35,7 @@ var validateCmd = &cobra.Command{ domain, _ := cmd.Flags().GetString("domain") e := licensor.NewEvaluator(lic, domain) if msg, valid := e.Validate(); !valid { - return fmt.Errorf(msg) + return xerrors.Errorf(msg) } b, _ := json.MarshalIndent(e.Inspect(), "", " ") diff --git a/components/licensor/go.mod b/components/licensor/go.mod index 0168a1cdf3fa59..646a8a0da393e5 100644 --- a/components/licensor/go.mod +++ b/components/licensor/go.mod @@ -6,6 +6,7 @@ require ( github.com/32leaves/bel v1.0.1 github.com/sirupsen/logrus v1.8.1 github.com/spf13/cobra v1.1.3 + golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 ) require ( diff --git a/components/licensor/go.sum b/components/licensor/go.sum index aa79c587c76627..aa600d71f34135 100644 --- a/components/licensor/go.sum +++ b/components/licensor/go.sum @@ -262,6 +262,7 @@ golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= diff --git a/components/local-app/go.mod b/components/local-app/go.mod index 205ebfd1e286e3..f1ac1169391bb6 100644 --- a/components/local-app/go.mod +++ b/components/local-app/go.mod @@ -19,6 +19,7 @@ require ( github.com/zalando/go-keyring v0.1.1 golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a golang.org/x/oauth2 v0.0.0-20210615190721-d04028783cf1 + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 google.golang.org/grpc v1.39.1 google.golang.org/protobuf v1.27.1 nhooyr.io/websocket v1.8.7 // indirect @@ -40,7 +41,6 @@ require ( golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 // indirect golang.org/x/sys v0.0.0-20210510120138-977fb7262007 // indirect golang.org/x/text v0.3.5 // indirect - golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/appengine v1.6.6 // indirect google.golang.org/genproto v0.0.0-20210617175327-b9e0b3197ced // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/components/local-app/pkg/auth/auth.go b/components/local-app/pkg/auth/auth.go index 4b23c29f04cc68..e134af77a87659 100644 --- a/components/local-app/pkg/auth/auth.go +++ b/components/local-app/pkg/auth/auth.go @@ -18,6 +18,7 @@ import ( "github.com/skratchdot/open-golang/open" keyring "github.com/zalando/go-keyring" "golang.org/x/oauth2" + "golang.org/x/xerrors" ) const ( @@ -78,7 +79,7 @@ func Login(ctx context.Context, opts LoginOpts) (token string, err error) { defer rl.Close() } if rl == nil { - return "", fmt.Errorf("could not open any valid port in range %d - %d", STARTING_PORT_NUM, ENDING_PORT_NUM) + return "", xerrors.Errorf("could not open any valid port in range %d - %d", STARTING_PORT_NUM, ENDING_PORT_NUM) } var ( @@ -147,7 +148,7 @@ func Login(ctx context.Context, opts LoginOpts) (token string, err error) { // open a browser window to the authorizationURL err = open.Start(authorizationURL) if err != nil { - return "", fmt.Errorf("cannot open browser to URL %s: %s\n", authorizationURL, err) + return "", xerrors.Errorf("cannot open browser to URL %s: %s\n", authorizationURL, err) } var query url.Values diff --git a/components/local-app/pkg/bastion/bastion.go b/components/local-app/pkg/bastion/bastion.go index 26e2e078819343..d9f18e9778a584 100644 --- a/components/local-app/pkg/bastion/bastion.go +++ b/components/local-app/pkg/bastion/bastion.go @@ -23,16 +23,17 @@ import ( "sync" "time" - gitpod "github.com/gitpod-io/gitpod/gitpod-protocol" - app "github.com/gitpod-io/gitpod/local-app/api" - supervisor "github.com/gitpod-io/gitpod/supervisor/api" "github.com/google/uuid" "github.com/kevinburke/ssh_config" + "github.com/sirupsen/logrus" "golang.org/x/crypto/ssh" + "golang.org/x/xerrors" "google.golang.org/grpc" "google.golang.org/protobuf/proto" - "github.com/sirupsen/logrus" + gitpod "github.com/gitpod-io/gitpod/gitpod-protocol" + app "github.com/gitpod-io/gitpod/local-app/api" + supervisor "github.com/gitpod-io/gitpod/supervisor/api" ) var ( @@ -425,13 +426,13 @@ func generateSSHKeys(instanceID string) (privateKeyFN string, publicKey string, func (b *Bastion) connectTunnelClient(ctx context.Context, ws *Workspace) error { if ws.URL == "" { - return fmt.Errorf("IDE URL is empty") + return xerrors.Errorf("IDE URL is empty") } if ws.OwnerToken == "" { - return fmt.Errorf("owner token is empty") + return xerrors.Errorf("owner token is empty") } if ws.tunnelClientConnected { - return fmt.Errorf("tunnel: ssh client is already connected") + return xerrors.Errorf("tunnel: ssh client is already connected") } ws.tunnelClientConnected = true @@ -520,10 +521,10 @@ func newTunnelClient(ctx context.Context, ws *Workspace, reconnecting *gitpod.Re func (b *Bastion) establishTunnel(ctx context.Context, ws *Workspace, logprefix string, remotePort int, targetPort int, visibility supervisor.TunnelVisiblity) (*TunnelListener, error) { if !ws.tunnelClientConnected { - return nil, fmt.Errorf("tunnel client is not connected") + return nil, xerrors.Errorf("tunnel client is not connected") } if visibility == supervisor.TunnelVisiblity_none { - return nil, fmt.Errorf("tunnel visibility is none") + return nil, xerrors.Errorf("tunnel visibility is none") } targetHost := "127.0.0.1" @@ -614,12 +615,12 @@ func (b *Bastion) establishTunnel(ctx context.Context, ws *Workspace, logprefix func (b *Bastion) establishSSHTunnel(ws *Workspace) (listener *TunnelListener, err error) { if ws.SSHPublicKey == "" { - return nil, fmt.Errorf("no public key generated") + return nil, xerrors.Errorf("no public key generated") } err = installSSHAuthorizedKey(ws, ws.SSHPublicKey) if err != nil { - return nil, fmt.Errorf("cannot install authorized key: %w", err) + return nil, xerrors.Errorf("cannot install authorized key: %w", err) } listener, err = b.establishTunnel(ws.ctx, ws, "ssh", 23001, 0, supervisor.TunnelVisiblity_host) return listener, err @@ -677,7 +678,7 @@ func installSSHAuthorizedKey(ws *Workspace, key string) error { return ctx.Err() case success := <-done: if !success { - return fmt.Errorf("unable to upload SSH key") + return xerrors.Errorf("unable to upload SSH key") } } diff --git a/components/local-app/pkg/bastion/service.go b/components/local-app/pkg/bastion/service.go index 08338fb61d413c..22e73a855617f8 100644 --- a/components/local-app/pkg/bastion/service.go +++ b/components/local-app/pkg/bastion/service.go @@ -7,9 +7,10 @@ package bastion import ( "context" - "github.com/gitpod-io/gitpod/local-app/api" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + + "github.com/gitpod-io/gitpod/local-app/api" ) type LocalAppService struct { diff --git a/components/registry-facade-api/go/go.mod b/components/registry-facade-api/go/go.mod index 1646ee5a3ced25..0a639bc0a2e9d4 100644 --- a/components/registry-facade-api/go/go.mod +++ b/components/registry-facade-api/go/go.mod @@ -3,6 +3,7 @@ module github.com/gitpod-io/gitpod/registry-facade/api go 1.17 require ( + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 google.golang.org/grpc v1.39.1 google.golang.org/protobuf v1.27.1 ) diff --git a/components/registry-facade-api/go/imagespec.go b/components/registry-facade-api/go/imagespec.go index bd08463a06913f..9d036168ad3f73 100644 --- a/components/registry-facade-api/go/imagespec.go +++ b/components/registry-facade-api/go/imagespec.go @@ -6,8 +6,8 @@ package api import ( "encoding/base64" - "fmt" + "golang.org/x/xerrors" "google.golang.org/protobuf/proto" ) @@ -19,7 +19,7 @@ func (spec *ImageSpec) ToBase64() (res string, err error) { rspec, err := proto.Marshal(spec) if err != nil { - return "", fmt.Errorf("cannot marshal image spec: %w", err) + return "", xerrors.Errorf("cannot marshal image spec: %w", err) } return base64.StdEncoding.EncodeToString(rspec), nil @@ -33,13 +33,13 @@ func ImageSpecFromBase64(input string) (res *ImageSpec, err error) { specPB, err := base64.StdEncoding.DecodeString(input) if err != nil { - return nil, fmt.Errorf("cannot decode image spec: %w", err) + return nil, xerrors.Errorf("cannot decode image spec: %w", err) } var spec ImageSpec err = proto.Unmarshal(specPB, &spec) if err != nil { - return nil, fmt.Errorf("cannot unmarshal image spec: %w", err) + return nil, xerrors.Errorf("cannot unmarshal image spec: %w", err) } return &spec, nil diff --git a/components/registry-facade/pkg/registry/imagecfg.go b/components/registry-facade/pkg/registry/imagecfg.go index dc6ebd1af17f19..13c1ae5c79cfee 100644 --- a/components/registry-facade/pkg/registry/imagecfg.go +++ b/components/registry-facade/pkg/registry/imagecfg.go @@ -6,7 +6,6 @@ package registry import ( "context" - "fmt" "sync" lru "github.com/hashicorp/golang-lru" @@ -19,7 +18,7 @@ import ( ) // ErrRefInvalid is returned by spec provider who cannot interpret the ref -var ErrRefInvalid = fmt.Errorf("invalid ref") +var ErrRefInvalid = xerrors.Errorf("invalid ref") // ImageSpecProvider provide the image spec for an image pull // based on the ref diff --git a/components/registry-facade/pkg/registry/layersource_test.go b/components/registry-facade/pkg/registry/layersource_test.go index 58b406f2fd5b3c..2cfab6a41d4271 100644 --- a/components/registry-facade/pkg/registry/layersource_test.go +++ b/components/registry-facade/pkg/registry/layersource_test.go @@ -9,13 +9,13 @@ import ( "context" "encoding/json" "flag" - "fmt" "io" "os" "testing" "time" ctesting "github.com/gitpod-io/gitpod/common-go/testing" + "golang.org/x/xerrors" "github.com/containerd/containerd/remotes" "github.com/containerd/containerd/remotes/docker" @@ -134,7 +134,7 @@ func (f *fakeFetcher) Resolve(ctx context.Context, ref string) (name string, des name = ref c, ok := f.Content[ref] if !ok { - err = fmt.Errorf("not found") + err = xerrors.Errorf("not found") return } @@ -144,7 +144,7 @@ func (f *fakeFetcher) Resolve(ctx context.Context, ref string) (name string, des // Pusher returns a new pusher for the provided reference func (f *fakeFetcher) Pusher(ctx context.Context, ref string) (remotes.Pusher, error) { - return nil, fmt.Errorf("not implemented") + return nil, xerrors.Errorf("not implemented") } // Fetcher returns a new fetcher for the provided reference. @@ -157,7 +157,7 @@ func (f *fakeFetcher) Fetcher(ctx context.Context, ref string) (remotes.Fetcher, func (f *fakeFetcher) Fetch(ctx context.Context, desc ocispec.Descriptor) (io.ReadCloser, error) { c, ok := f.Content[desc.Digest.Encoded()] if !ok { - return nil, fmt.Errorf("not found") + return nil, xerrors.Errorf("not found") } return io.NopCloser(bytes.NewReader(c)), nil } diff --git a/components/registry-facade/pkg/registry/manifest.go b/components/registry-facade/pkg/registry/manifest.go index 12a84d5a423cf2..277117d93100a6 100644 --- a/components/registry-facade/pkg/registry/manifest.go +++ b/components/registry-facade/pkg/registry/manifest.go @@ -25,6 +25,7 @@ import ( ociv1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/opentracing/opentracing-go" "github.com/pkg/errors" + "golang.org/x/xerrors" "github.com/gitpod-io/gitpod/common-go/log" "github.com/gitpod-io/gitpod/common-go/tracing" @@ -245,19 +246,19 @@ func DownloadConfig(ctx context.Context, fetcher remotes.Fetcher, desc ociv1.Des if desc.MediaType != images.MediaTypeDockerSchema2Config && desc.MediaType != ociv1.MediaTypeImageConfig { - return nil, fmt.Errorf("unsupported media type") + return nil, xerrors.Errorf("unsupported media type") } rc, err := fetcher.Fetch(ctx, desc) if err != nil { - return nil, fmt.Errorf("cannot download config: %w", err) + return nil, xerrors.Errorf("cannot download config: %w", err) } defer rc.Close() var res ociv1.Image err = json.NewDecoder(rc).Decode(&res) if err != nil { - return nil, fmt.Errorf("cannot decode config: %w", err) + return nil, xerrors.Errorf("cannot decode config: %w", err) } return &res, nil @@ -303,7 +304,7 @@ func DownloadManifest(ctx context.Context, fetcher remotes.Fetcher, desc ociv1.D placeInStore = true rc, err = fetcher.Fetch(ctx, desc) if err != nil { - err = fmt.Errorf("cannot download manifest: %w", err) + err = xerrors.Errorf("cannot download manifest: %w", err) return } } @@ -311,7 +312,7 @@ func DownloadManifest(ctx context.Context, fetcher remotes.Fetcher, desc ociv1.D inpt, err := io.ReadAll(rc) rc.Close() if err != nil { - err = fmt.Errorf("cannot download manifest: %w", err) + err = xerrors.Errorf("cannot download manifest: %w", err) return } @@ -324,11 +325,11 @@ func DownloadManifest(ctx context.Context, fetcher remotes.Fetcher, desc ociv1.D var list ociv1.Index err = json.Unmarshal(inpt, &list) if err != nil { - err = fmt.Errorf("cannot unmarshal index: %w", err) + err = xerrors.Errorf("cannot unmarshal index: %w", err) return } if len(list.Manifests) == 0 { - err = fmt.Errorf("empty manifest") + err = xerrors.Errorf("empty manifest") return } @@ -336,14 +337,14 @@ func DownloadManifest(ctx context.Context, fetcher remotes.Fetcher, desc ociv1.D md := list.Manifests[0] rc, err = fetcher.Fetch(ctx, md) if err != nil { - err = fmt.Errorf("cannot download config: %w", err) + err = xerrors.Errorf("cannot download config: %w", err) return } rdesc = &md inpt, err = io.ReadAll(rc) rc.Close() if err != nil { - err = fmt.Errorf("cannot download manifest: %w", err) + err = xerrors.Errorf("cannot download manifest: %w", err) return } } @@ -351,14 +352,14 @@ func DownloadManifest(ctx context.Context, fetcher remotes.Fetcher, desc ociv1.D switch rdesc.MediaType { case images.MediaTypeDockerSchema2Manifest, ociv1.MediaTypeImageManifest: default: - err = fmt.Errorf("unsupported media type") + err = xerrors.Errorf("unsupported media type") return } var res ociv1.Manifest err = json.Unmarshal(inpt, &res) if err != nil { - err = fmt.Errorf("cannot decode config: %w", err) + err = xerrors.Errorf("cannot decode config: %w", err) return } diff --git a/components/registry-facade/pkg/registry/registry.go b/components/registry-facade/pkg/registry/registry.go index b9781a9caca817..5d76cbbb21b8f4 100644 --- a/components/registry-facade/pkg/registry/registry.go +++ b/components/registry-facade/pkg/registry/registry.go @@ -71,17 +71,17 @@ func buildStaticLayer(ctx context.Context, cfg []StaticLayerCfg, newResolver Res case "file": src, err := NewFileLayerSource(ctx, sl.Ref) if err != nil { - return nil, fmt.Errorf("cannot source layer from %s: %w", sl.Ref, err) + return nil, xerrors.Errorf("cannot source layer from %s: %w", sl.Ref, err) } l = append(l, src) case "image": src, err := NewStaticSourceFromImage(ctx, newResolver(), sl.Ref) if err != nil { - return nil, fmt.Errorf("cannot source layer from %s: %w", sl.Ref, err) + return nil, xerrors.Errorf("cannot source layer from %s: %w", sl.Ref, err) } l = append(l, src) default: - return nil, fmt.Errorf("unknown static layer type: %s", sl.Type) + return nil, xerrors.Errorf("unknown static layer type: %s", sl.Type) } } return l, nil diff --git a/components/supervisor/go.mod b/components/supervisor/go.mod index aaff61a0b0b10d..bdbb67f85605c9 100644 --- a/components/supervisor/go.mod +++ b/components/supervisor/go.mod @@ -12,7 +12,6 @@ require ( github.com/gitpod-io/gitpod/gitpod-protocol v0.0.0-00010101000000-000000000000 github.com/gitpod-io/gitpod/supervisor/api v0.0.0-00010101000000-000000000000 github.com/golang/mock v1.6.0 - github.com/golang/protobuf v1.5.2 github.com/google/go-cmp v0.5.6 github.com/google/uuid v1.2.0 github.com/gorilla/websocket v1.4.2 @@ -47,6 +46,7 @@ require ( github.com/fsnotify/fsnotify v1.4.9 // indirect github.com/go-ozzo/ozzo-validation v3.5.0+incompatible // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/protobuf v1.5.2 // indirect github.com/googleapis/gax-go/v2 v2.0.5 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect github.com/json-iterator/go v1.1.11 // indirect diff --git a/components/supervisor/pkg/activation/activation.go b/components/supervisor/pkg/activation/activation.go index 0e97ea85b9375f..8112ae4b15823a 100644 --- a/components/supervisor/pkg/activation/activation.go +++ b/components/supervisor/pkg/activation/activation.go @@ -6,12 +6,12 @@ package activation import ( "context" - "fmt" "net" "os" "sync" "github.com/mailru/easygo/netpoll" + "golang.org/x/xerrors" ) // Callback is called when a listener is written to. Receivers are expected to close socketFD. @@ -64,7 +64,7 @@ func Listen(ctx context.Context, l net.Listener, activate Callback) error { case *net.TCPListener: f, err = ll.File() default: - return fmt.Errorf("unsuported listener") + return xerrors.Errorf("unsuported listener") } if err != nil { return err diff --git a/components/supervisor/pkg/ports/tunnel.go b/components/supervisor/pkg/ports/tunnel.go index 2d83886f99f474..fc7ce314f251aa 100644 --- a/components/supervisor/pkg/ports/tunnel.go +++ b/components/supervisor/pkg/ports/tunnel.go @@ -123,10 +123,10 @@ func (p *TunneledPortsService) Observe(ctx context.Context) (<-chan []PortTunnel func (desc *PortTunnelDescription) validate() (err error) { if desc.LocalPort <= 0 || desc.LocalPort > 0xFFFF { - return fmt.Errorf("bad local port: %d", desc.LocalPort) + return xerrors.Errorf("bad local port: %d", desc.LocalPort) } if desc.TargetPort < 0 || desc.TargetPort > 0xFFFF { - return fmt.Errorf("bad target port: %d", desc.TargetPort) + return xerrors.Errorf("bad target port: %d", desc.TargetPort) } return nil } @@ -142,7 +142,7 @@ func (p *TunneledPortsService) Tunnel(ctx context.Context, options *TunnelOption if err == nil { err = descErr } else { - err = fmt.Errorf("%s\n%s", err, descErr) + err = xerrors.Errorf("%s\n%s", err, descErr) } continue } @@ -195,7 +195,7 @@ func (p *TunneledPortsService) CloseTunnel(ctx context.Context, localPorts ...ui if err == nil { err = closeErr } else { - err = fmt.Errorf("%s\n%s", err, closeErr) + err = xerrors.Errorf("%s\n%s", err, closeErr) } } } diff --git a/components/supervisor/pkg/supervisor/config.go b/components/supervisor/pkg/supervisor/config.go index 8916606ea64833..d321a8e7a74b1d 100644 --- a/components/supervisor/pkg/supervisor/config.go +++ b/components/supervisor/pkg/supervisor/config.go @@ -41,13 +41,13 @@ type Config struct { // Validate validates the configuration func (c Config) Validate() error { if err := c.StaticConfig.Validate(); err != nil { - return fmt.Errorf("static supervisor config is invalid: %w", err) + return xerrors.Errorf("static supervisor config is invalid: %w", err) } if err := c.IDEConfig.Validate(); err != nil { - return fmt.Errorf("IDE config is invalid: %w", err) + return xerrors.Errorf("IDE config is invalid: %w", err) } if err := c.WorkspaceConfig.Validate(); err != nil { - return fmt.Errorf("Workspace config is invalid: %w", err) + return xerrors.Errorf("Workspace config is invalid: %w", err) } return nil @@ -80,16 +80,16 @@ type StaticConfig struct { // Validate validates this configuration func (c StaticConfig) Validate() error { if c.IDEConfigLocation == "" { - return fmt.Errorf("ideConfigLocation is required") + return xerrors.Errorf("ideConfigLocation is required") } if c.FrontendLocation == "" { - return fmt.Errorf("frontendLocation is required") + return xerrors.Errorf("frontendLocation is required") } if !(0 < c.APIEndpointPort && c.APIEndpointPort <= math.MaxUint16) { - return fmt.Errorf("apiEndpointPort must be between 0 and %d", math.MaxUint16) + return xerrors.Errorf("apiEndpointPort must be between 0 and %d", math.MaxUint16) } if !(0 < c.SSHPort && c.SSHPort <= math.MaxUint16) { - return fmt.Errorf("sshPort must be between 0 and %d", math.MaxUint16) + return xerrors.Errorf("sshPort must be between 0 and %d", math.MaxUint16) } return nil @@ -136,16 +136,16 @@ type IDEConfig struct { // Validate validates this configuration func (c IDEConfig) Validate() error { if c.Entrypoint == "" { - return fmt.Errorf("entrypoint is required") + return xerrors.Errorf("entrypoint is required") } if stat, err := os.Stat(c.Entrypoint); err != nil { - return fmt.Errorf("invalid entrypoint: %w", err) + return xerrors.Errorf("invalid entrypoint: %w", err) } else if stat.IsDir() { - return fmt.Errorf("entrypoint is a directory, but should be a file") + return xerrors.Errorf("entrypoint is a directory, but should be a file") } if c.IDELogRateLimit < 0 { - return fmt.Errorf("logRateLimit must be >= 0") + return xerrors.Errorf("logRateLimit must be >= 0") } return nil @@ -234,15 +234,15 @@ type TaskConfig struct { // Validate validates this configuration func (c WorkspaceConfig) Validate() error { if !(0 < c.IDEPort && c.IDEPort <= math.MaxUint16) { - return fmt.Errorf("GITPOD_THEIA_PORT must be between 0 and %d", math.MaxUint16) + return xerrors.Errorf("GITPOD_THEIA_PORT must be between 0 and %d", math.MaxUint16) } if c.WorkspaceRoot == "" { - return fmt.Errorf("THEIA_WORKSPACE_ROOT is required") + return xerrors.Errorf("THEIA_WORKSPACE_ROOT is required") } if c.WorkspaceLogRateLimit < 0 { - return fmt.Errorf("logRateLimit must be >= 0") + return xerrors.Errorf("logRateLimit must be >= 0") } if _, err := c.GetTokens(false); err != nil { @@ -265,7 +265,7 @@ func (c WorkspaceConfig) GetTokens(downloadOTS bool) ([]WorkspaceGitpodToken, er var tks []WorkspaceGitpodToken err := json.Unmarshal([]byte(c.Tokens), &tks) if err != nil { - return nil, fmt.Errorf("cannot parse tokens: %w", err) + return nil, xerrors.Errorf("cannot parse tokens: %w", err) } if downloadOTS { @@ -280,15 +280,15 @@ func (c WorkspaceConfig) GetTokens(downloadOTS bool) ([]WorkspaceGitpodToken, er resp, err := client.Get(tks[i].TokenOTS) if err != nil { - return nil, fmt.Errorf("cannot download token OTS: %w", err) + return nil, xerrors.Errorf("cannot download token OTS: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("cannot download token OTS: %d (%s)", resp.StatusCode, resp.Status) + return nil, xerrors.Errorf("cannot download token OTS: %d (%s)", resp.StatusCode, resp.Status) } tkn, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { - return nil, fmt.Errorf("cannot download token OTS: %w", err) + return nil, xerrors.Errorf("cannot download token OTS: %w", err) } tks[i].Token = string(tkn) } @@ -325,7 +325,7 @@ func (c WorkspaceConfig) getGitpodTasks() (tasks *[]TaskConfig, err error) { } err = json.Unmarshal([]byte(c.GitpodTasks), &tasks) if err != nil { - return nil, fmt.Errorf("cannot parse tasks: %w", err) + return nil, xerrors.Errorf("cannot parse tasks: %w", err) } return } @@ -337,7 +337,7 @@ func (c WorkspaceConfig) getCommit() (commit *gitpod.Commit, err error) { } err = json.Unmarshal([]byte(c.WorkspaceContext), &commit) if err != nil { - return nil, fmt.Errorf("cannot parse workspace context as a commit: %w", err) + return nil, xerrors.Errorf("cannot parse workspace context as a commit: %w", err) } return } diff --git a/components/supervisor/pkg/supervisor/supervisor.go b/components/supervisor/pkg/supervisor/supervisor.go index 71a23b6a313206..cc29913b987ee4 100644 --- a/components/supervisor/pkg/supervisor/supervisor.go +++ b/components/supervisor/pkg/supervisor/supervisor.go @@ -27,7 +27,6 @@ import ( "syscall" "time" - "github.com/golang/protobuf/proto" "github.com/gorilla/websocket" grpcruntime "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/improbable-eng/grpc-web/go/grpcweb" @@ -36,6 +35,7 @@ import ( "golang.org/x/crypto/ssh" "golang.org/x/sys/unix" "google.golang.org/grpc" + "google.golang.org/protobuf/proto" "github.com/gitpod-io/gitpod/common-go/analytics" "github.com/gitpod-io/gitpod/common-go/log" diff --git a/components/supervisor/pkg/supervisor/user.go b/components/supervisor/pkg/supervisor/user.go index d1eff6cfc54d6a..a4297145393684 100644 --- a/components/supervisor/pkg/supervisor/user.go +++ b/components/supervisor/pkg/supervisor/user.go @@ -5,13 +5,13 @@ package supervisor import ( - "fmt" "os/exec" "os/user" "strconv" "strings" "github.com/gitpod-io/gitpod/common-go/log" + "golang.org/x/xerrors" ) type lookup interface { @@ -81,11 +81,11 @@ func hasGroup(name string, gid int) (bool, error) { } if grpByID != nil && grpByName == nil { // a group with this GID exists already, but has a different name - return true, fmt.Errorf("group %s already uses GID %d", grpByID.Name, gid) + return true, xerrors.Errorf("group %s already uses GID %d", grpByID.Name, gid) } if grpByID == nil && grpByName != nil { // a group with this name already exists, but has a different GID - return true, fmt.Errorf("group named %s exists but uses different GID %s", name, grpByName.Gid) + return true, xerrors.Errorf("group named %s exists but uses different GID %s", name, grpByName.Gid) } // group exists and all is well @@ -115,21 +115,21 @@ func hasUser(u *user.User) (bool, error) { } if userByID != nil && userByName == nil { // a user with this GID exists already, but has a different name - return true, fmt.Errorf("user %s already uses UID %s", userByID.Username, u.Uid) + return true, xerrors.Errorf("user %s already uses UID %s", userByID.Username, u.Uid) } if userByID == nil && userByName != nil { // a user with this name already exists, but has a different GID - return true, fmt.Errorf("user named %s exists but uses different UID %s", u.Username, userByName.Uid) + return true, xerrors.Errorf("user named %s exists but uses different UID %s", u.Username, userByName.Uid) } // at this point it doesn't matter if we use userByID or byName - they're likely the same // because of the way we looked them up. existingUser := userByID if existingUser.Gid != u.Gid { - return true, fmt.Errorf("existing user %s has different GID %s (instead of %s)", existingUser.Username, existingUser.Gid, u.Gid) + return true, xerrors.Errorf("existing user %s has different GID %s (instead of %s)", existingUser.Username, existingUser.Gid, u.Gid) } if existingUser.HomeDir != u.HomeDir { - return true, fmt.Errorf("existing user %s has different home directory %s (instead of %s)", existingUser.Username, existingUser.HomeDir, u.HomeDir) + return true, xerrors.Errorf("existing user %s has different home directory %s (instead of %s)", existingUser.Username, existingUser.HomeDir, u.HomeDir) } // user exists and all is well @@ -139,13 +139,13 @@ func hasUser(u *user.User) (bool, error) { func addGroup(name string, gid int) error { flavour := determineAdduserFlavour() if flavour == adduserUnknown { - return fmt.Errorf("no addgroup command found") + return xerrors.Errorf("no addgroup command found") } args := addgroupCommand[flavour](name, gid) out, err := exec.Command(args[0], args[1:]...).CombinedOutput() if err != nil { - return fmt.Errorf("%w: %s", err, string(out)) + return xerrors.Errorf("%w: %s", err, string(out)) } log.WithField("args", args).Debug("addgroup") @@ -155,13 +155,13 @@ func addGroup(name string, gid int) error { func addUser(opts *user.User) error { flavour := determineAdduserFlavour() if flavour == adduserUnknown { - return fmt.Errorf("no adduser command found") + return xerrors.Errorf("no adduser command found") } args := adduserCommand[flavour](opts) out, err := exec.Command(args[0], args[1:]...).CombinedOutput() if err != nil { - return fmt.Errorf("%v: %w: %s", args, err, string(out)) + return xerrors.Errorf("%v: %w: %s", args, err, string(out)) } log.WithField("args", args).Debug("adduser") diff --git a/components/supervisor/pkg/terminal/ring-buffer.go b/components/supervisor/pkg/terminal/ring-buffer.go index b2264bdd895904..26199306a0a18a 100644 --- a/components/supervisor/pkg/terminal/ring-buffer.go +++ b/components/supervisor/pkg/terminal/ring-buffer.go @@ -4,9 +4,7 @@ package terminal -import ( - "fmt" -) +import "golang.org/x/xerrors" // RingBuffer implements a ring buffer. It is a fixed size, // and new writes overwrite older data, such that for a buffer @@ -23,7 +21,7 @@ type RingBuffer struct { // must be greater than 0. func NewRingBuffer(size int64) (*RingBuffer, error) { if size <= 0 { - return nil, fmt.Errorf("Size must be positive") + return nil, xerrors.Errorf("Size must be positive") } b := &RingBuffer{ diff --git a/components/workspacekit/cmd/rings.go b/components/workspacekit/cmd/rings.go index 95518941e35497..2d2bea2e0598bb 100644 --- a/components/workspacekit/cmd/rings.go +++ b/components/workspacekit/cmd/rings.go @@ -28,6 +28,7 @@ import ( libseccomp "github.com/seccomp/libseccomp-golang" "github.com/spf13/cobra" "golang.org/x/sys/unix" + "golang.org/x/xerrors" "google.golang.org/grpc" "github.com/gitpod-io/gitpod/common-go/log" @@ -406,7 +407,7 @@ var ring1Cmd = &cobra.Command{ ring2Conn = c.(*net.UnixConn) brek = true case <-time.After(ring2StartupTimeout): - err = fmt.Errorf("ring2 did not connect in time") + err = xerrors.Errorf("ring2 did not connect in time") brek = true } if brek { @@ -581,7 +582,7 @@ func receiveSeccmpFd(conn *net.UnixConn) (libseccomp.ScmpFd, error) { return 0, err } if len(msgs) != 1 { - return 0, fmt.Errorf("expected a single socket control message") + return 0, xerrors.Errorf("expected a single socket control message") } fds, err := unix.ParseUnixRights(&msgs[0]) @@ -589,7 +590,7 @@ func receiveSeccmpFd(conn *net.UnixConn) (libseccomp.ScmpFd, error) { return 0, err } if len(fds) == 0 { - return 0, fmt.Errorf("expected a single socket FD") + return 0, xerrors.Errorf("expected a single socket FD") } return libseccomp.ScmpFd(fds[0]), nil @@ -687,12 +688,12 @@ func pivotRoot(rootfs string, fsshift api.FSShiftMethod) error { if fsshift == api.FSShiftMethod_FUSE { err := unix.Chroot(rootfs) if err != nil { - return fmt.Errorf("cannot chroot: %v", err) + return xerrors.Errorf("cannot chroot: %v", err) } err = unix.Chdir("/") if err != nil { - return fmt.Errorf("cannot chdir to new root :%v", err) + return xerrors.Errorf("cannot chdir to new root :%v", err) } return nil @@ -716,7 +717,7 @@ func pivotRoot(rootfs string, fsshift api.FSShiftMethod) error { } if err := unix.PivotRoot(".", "."); err != nil { - return fmt.Errorf("pivot_root %s", err) + return xerrors.Errorf("pivot_root %s", err) } // Currently our "." is oldroot (according to the current kernel code). @@ -743,7 +744,7 @@ func pivotRoot(rootfs string, fsshift api.FSShiftMethod) error { // Switch back to our shiny new root. if err := unix.Chdir("/"); err != nil { - return fmt.Errorf("chdir / %s", err) + return xerrors.Errorf("chdir / %s", err) } return nil @@ -806,7 +807,7 @@ func connectToInWorkspaceDaemonService(ctx context.Context) (*inWorkspaceService case <-t.C: continue case <-ctx.Done(): - return nil, fmt.Errorf("socket did not appear before context was canceled") + return nil, xerrors.Errorf("socket did not appear before context was canceled") } } diff --git a/components/workspacekit/go.mod b/components/workspacekit/go.mod index 5cd2016bc5d929..2bf227a483c3dc 100644 --- a/components/workspacekit/go.mod +++ b/components/workspacekit/go.mod @@ -13,6 +13,7 @@ require ( github.com/seccomp/libseccomp-golang v0.9.1 github.com/spf13/cobra v1.1.3 golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 google.golang.org/grpc v1.39.1 ) diff --git a/components/workspacekit/pkg/lift/lift.go b/components/workspacekit/pkg/lift/lift.go index 5ec0c386c76313..be0a247c140a55 100644 --- a/components/workspacekit/pkg/lift/lift.go +++ b/components/workspacekit/pkg/lift/lift.go @@ -20,6 +20,7 @@ import ( "github.com/gitpod-io/gitpod/common-go/log" "golang.org/x/sys/unix" + "golang.org/x/xerrors" ) const ( @@ -98,7 +99,7 @@ func serveLiftClient(conn net.Conn) error { } if len(msgs) != 1 { - return fmt.Errorf("expected a single socket control message") + return xerrors.Errorf("expected a single socket control message") } fds, err := unix.ParseUnixRights(&msgs[0]) @@ -107,7 +108,7 @@ func serveLiftClient(conn net.Conn) error { } if len(fds) != 3 { - return fmt.Errorf("expected three file descriptors") + return xerrors.Errorf("expected three file descriptors") } rd := bufio.NewReader(f) @@ -123,7 +124,7 @@ func serveLiftClient(conn net.Conn) error { } if len(msg.Command) == 0 { - return fmt.Errorf("expected non-empty command") + return xerrors.Errorf("expected non-empty command") } log.WithField("command", msg.Command).Info("running lifted command") diff --git a/components/workspacekit/pkg/seccomp/notify.go b/components/workspacekit/pkg/seccomp/notify.go index 8e63b5c6b56e58..df311312140363 100644 --- a/components/workspacekit/pkg/seccomp/notify.go +++ b/components/workspacekit/pkg/seccomp/notify.go @@ -16,6 +16,7 @@ import ( "github.com/moby/sys/mountinfo" "golang.org/x/sys/unix" + "golang.org/x/xerrors" "github.com/gitpod-io/gitpod/common-go/log" "github.com/gitpod-io/gitpod/workspacekit/pkg/readarg" @@ -50,15 +51,15 @@ func mapHandler(h SyscallHandler) map[string]syscallHandler { func LoadFilter() (libseccomp.ScmpFd, error) { filter, err := libseccomp.NewFilter(libseccomp.ActAllow) if err != nil { - return 0, fmt.Errorf("cannot create filter: %w", err) + return 0, xerrors.Errorf("cannot create filter: %w", err) } err = filter.SetTsync(false) if err != nil { - return 0, fmt.Errorf("cannot set tsync: %w", err) + return 0, xerrors.Errorf("cannot set tsync: %w", err) } err = filter.SetNoNewPrivsBit(false) if err != nil { - return 0, fmt.Errorf("cannot set no_new_privs: %w", err) + return 0, xerrors.Errorf("cannot set no_new_privs: %w", err) } // we explicitly prohibit open_tree/move_mount to prevent container workloads @@ -70,11 +71,11 @@ func LoadFilter() (libseccomp.ScmpFd, error) { for _, sc := range deniedSyscalls { syscallID, err := libseccomp.GetSyscallFromName(sc) if err != nil { - return 0, fmt.Errorf("unknown syscall %s: %w", sc, err) + return 0, xerrors.Errorf("unknown syscall %s: %w", sc, err) } err = filter.AddRule(syscallID, libseccomp.ActErrno.SetReturnCode(int16(unix.EPERM))) if err != nil { - return 0, fmt.Errorf("cannot add rule for %s: %w", sc, err) + return 0, xerrors.Errorf("cannot add rule for %s: %w", sc, err) } } @@ -82,22 +83,22 @@ func LoadFilter() (libseccomp.ScmpFd, error) { for sc := range handledSyscalls { syscallID, err := libseccomp.GetSyscallFromName(sc) if err != nil { - return 0, fmt.Errorf("unknown syscall %s: %w", sc, err) + return 0, xerrors.Errorf("unknown syscall %s: %w", sc, err) } err = filter.AddRule(syscallID, libseccomp.ActNotify) if err != nil { - return 0, fmt.Errorf("cannot add rule for %s: %w", sc, err) + return 0, xerrors.Errorf("cannot add rule for %s: %w", sc, err) } } err = filter.Load() if err != nil { - return 0, fmt.Errorf("cannot load filter: %w", err) + return 0, xerrors.Errorf("cannot load filter: %w", err) } fd, err := filter.GetNotifFd() if err != nil { - return 0, fmt.Errorf("cannot get inotif fd: %w", err) + return 0, xerrors.Errorf("cannot get inotif fd: %w", err) } return fd, nil diff --git a/components/ws-daemon/nsinsider/go.mod b/components/ws-daemon/nsinsider/go.mod index e85bd248657738..d3a3826130043e 100644 --- a/components/ws-daemon/nsinsider/go.mod +++ b/components/ws-daemon/nsinsider/go.mod @@ -8,6 +8,7 @@ require ( github.com/gitpod-io/gitpod/common-go v0.0.0-00010101000000-000000000000 github.com/urfave/cli/v2 v2.3.0 golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 ) require ( diff --git a/components/ws-daemon/nsinsider/go.sum b/components/ws-daemon/nsinsider/go.sum index 4de22a09796809..7961a10625a115 100644 --- a/components/ws-daemon/nsinsider/go.sum +++ b/components/ws-daemon/nsinsider/go.sum @@ -18,5 +18,7 @@ github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/X golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 h1:RqytpXGR1iVNX7psjB3ff8y7sNFinVFvkx1c8SjBkio= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/components/ws-daemon/nsinsider/main.go b/components/ws-daemon/nsinsider/main.go index 893dc81fc14e42..1d4b49539883db 100644 --- a/components/ws-daemon/nsinsider/main.go +++ b/components/ws-daemon/nsinsider/main.go @@ -14,6 +14,7 @@ import ( cli "github.com/urfave/cli/v2" "golang.org/x/sys/unix" + "golang.org/x/xerrors" "github.com/gitpod-io/gitpod/common-go/log" _ "github.com/gitpod-io/gitpod/ws-daemon/nsinsider/pkg/nsenter" @@ -137,7 +138,7 @@ func main() { out, err := cmd.CombinedOutput() if err != nil { - return fmt.Errorf("fuse-overlayfs (%v) failed: %q\n%v", + return xerrors.Errorf("fuse-overlayfs (%v) failed: %q\n%v", cmd.Args, string(out), err, diff --git a/components/ws-daemon/nsinsider/pkg/nsenter/utils.go b/components/ws-daemon/nsinsider/pkg/nsenter/utils.go index 14c28283b5194f..a496cca0ee5c36 100644 --- a/components/ws-daemon/nsinsider/pkg/nsenter/utils.go +++ b/components/ws-daemon/nsinsider/pkg/nsenter/utils.go @@ -14,6 +14,7 @@ import ( "strconv" "golang.org/x/sys/unix" + "golang.org/x/xerrors" "github.com/gitpod-io/gitpod/common-go/log" ) @@ -67,7 +68,7 @@ func Run(pid int, args []string, addFD []*os.File, enterNamespace ...Namespace) f, err := os.OpenFile(ns.Source, ns.Flags, 0) if err != nil { - return fmt.Errorf("cannot open %s: %w", ns.Source, err) + return xerrors.Errorf("cannot open %s: %w", ns.Source, err) } defer f.Close() cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%d", ns.Env, stdioFdCount+len(cmd.ExtraFiles))) @@ -79,7 +80,7 @@ func Run(pid int, args []string, addFD []*os.File, enterNamespace ...Namespace) cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { - return fmt.Errorf("cannot run handler: %w", err) + return xerrors.Errorf("cannot run handler: %w", err) } return nil } diff --git a/components/ws-daemon/pkg/container/container.go b/components/ws-daemon/pkg/container/container.go index ca4401a5437fa0..9a20658e4013b8 100644 --- a/components/ws-daemon/pkg/container/container.go +++ b/components/ws-daemon/pkg/container/container.go @@ -6,7 +6,8 @@ package container import ( "context" - "fmt" + + "golang.org/x/xerrors" ) // Runtime abstracts over the different container runtimes out there w.r.t. to the features we need from those runtimes @@ -50,13 +51,13 @@ type Runtime interface { var ( // ErrNotFound means the container was not found - ErrNotFound = fmt.Errorf("not found") + ErrNotFound = xerrors.Errorf("not found") // ErrNoUpperdir means the container has no upperdir - ErrNoUpperdir = fmt.Errorf("no upperdir available") + ErrNoUpperdir = xerrors.Errorf("no upperdir available") // ErrNoCGroup means the container has no cgroup - ErrNoCGroup = fmt.Errorf("no cgroup available") + ErrNoCGroup = xerrors.Errorf("no cgroup available") ) // ID represents the ID of a CRI container diff --git a/components/ws-daemon/pkg/content/archive.go b/components/ws-daemon/pkg/content/archive.go index 1c8f24b8adf734..8748902f28e2d3 100644 --- a/components/ws-daemon/pkg/content/archive.go +++ b/components/ws-daemon/pkg/content/archive.go @@ -8,7 +8,6 @@ import ( "archive/tar" "bufio" "context" - "fmt" "io" "os" @@ -38,7 +37,7 @@ func BuildTarbal(ctx context.Context, src string, dst string, fullWorkspaceBacku // ensure the src actually exists before trying to tar it if _, err := os.Stat(src); err != nil { - return fmt.Errorf("Unable to tar files: %v", err.Error()) + return xerrors.Errorf("Unable to tar files: %v", err.Error()) } uidMaps := make([]idtools.IDMap, len(cfg.UIDMaps)) @@ -105,7 +104,7 @@ func BuildTarbal(ctx context.Context, src string, dst string, fullWorkspaceBacku } // ErrMaxSizeExceeded is emitted by LimitWriter when a write tries to write beyond the max number of bytes allowed -var ErrMaxSizeExceeded = fmt.Errorf("maximum size exceeded") +var ErrMaxSizeExceeded = xerrors.Errorf("maximum size exceeded") // cleanCorruptedTarballAndReturnError cleans up the file located at path dst and returns the error err passed to it func cleanCorruptedTarballAndReturnError(dst string, err error) error { diff --git a/components/ws-daemon/pkg/content/config.go b/components/ws-daemon/pkg/content/config.go index ccadcfedd8a44c..f34dd92613592a 100644 --- a/components/ws-daemon/pkg/content/config.go +++ b/components/ws-daemon/pkg/content/config.go @@ -5,13 +5,13 @@ package content import ( - "fmt" "strings" "github.com/gitpod-io/gitpod/common-go/util" "github.com/gitpod-io/gitpod/content-service/pkg/storage" "github.com/gitpod-io/gitpod/ws-daemon/api" "github.com/gitpod-io/gitpod/ws-daemon/pkg/quota" + "golang.org/x/xerrors" ) // Config configures the workspace content service @@ -71,7 +71,7 @@ func (m *FSShiftMethod) UnmarshalJSON(data []byte) error { input := strings.ToUpper(strings.Trim(string(data), "\"")) v, ok := api.FSShiftMethod_value[input] if !ok { - return fmt.Errorf("invalid shift method: %v", input) + return xerrors.Errorf("invalid shift method: %v", input) } *m = FSShiftMethod(v) return nil diff --git a/components/ws-daemon/pkg/content/initializer.go b/components/ws-daemon/pkg/content/initializer.go index 748121a538ab00..cbc3383be838e3 100644 --- a/components/ws-daemon/pkg/content/initializer.go +++ b/components/ws-daemon/pkg/content/initializer.go @@ -8,7 +8,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "net/http" "os" "os/exec" @@ -241,7 +240,7 @@ func RunInitializer(ctx context.Context, destination string, initializer *csapi. if exiterr, ok := err.(*exec.ExitError); ok { // The program has exited with an exit code != 0. If it's 42, it was deliberate. if status, ok := exiterr.Sys().(syscall.WaitStatus); ok && status.ExitStatus() == 42 { - return fmt.Errorf("content initializer failed") + return xerrors.Errorf("content initializer failed") } } @@ -361,12 +360,12 @@ func (rs *remoteContentStorage) Qualify(name string) string { // Upload does nothing func (rs *remoteContentStorage) Upload(ctx context.Context, source string, name string, opts ...storage.UploadOption) (string, string, error) { - return "", "", fmt.Errorf("not implemented") + return "", "", xerrors.Errorf("not implemented") } // UploadInstance takes all files from a local location and uploads it to the remote storage func (rs *remoteContentStorage) UploadInstance(ctx context.Context, source string, name string, options ...storage.UploadOption) (bucket, obj string, err error) { - return "", "", fmt.Errorf("not implemented") + return "", "", xerrors.Errorf("not implemented") } // Bucket returns an empty string diff --git a/components/ws-daemon/pkg/diskguard/guard.go b/components/ws-daemon/pkg/diskguard/guard.go index 871cd455a79d8d..0c3b73e987f54c 100644 --- a/components/ws-daemon/pkg/diskguard/guard.go +++ b/components/ws-daemon/pkg/diskguard/guard.go @@ -6,10 +6,10 @@ package diskguard import ( "context" - "fmt" "syscall" "time" + "golang.org/x/xerrors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/util/retry" @@ -122,7 +122,7 @@ func getAvailableBytes(path string) (bvail uint64, err error) { var stat syscall.Statfs_t err = syscall.Statfs(path, &stat) if err != nil { - return 0, fmt.Errorf("cannot stat %s: %w", path, err) + return 0, xerrors.Errorf("cannot stat %s: %w", path, err) } bvail = stat.Bavail * uint64(stat.Bsize) diff --git a/components/ws-daemon/pkg/internal/session/store.go b/components/ws-daemon/pkg/internal/session/store.go index 01be031027b0e5..ed3157c35c04f0 100644 --- a/components/ws-daemon/pkg/internal/session/store.go +++ b/components/ws-daemon/pkg/internal/session/store.go @@ -6,7 +6,6 @@ package session import ( "context" - "fmt" "path/filepath" "strings" "sync" @@ -21,7 +20,7 @@ import ( var ( // ErrAlreadyExists is returned when one tries to create a session which exists already - ErrAlreadyExists = fmt.Errorf("session already exists") + ErrAlreadyExists = xerrors.Errorf("session already exists") ) const ( diff --git a/components/ws-daemon/pkg/iws/iws.go b/components/ws-daemon/pkg/iws/iws.go index 80dcc54bf7151e..261d3a19da9681 100644 --- a/components/ws-daemon/pkg/iws/iws.go +++ b/components/ws-daemon/pkg/iws/iws.go @@ -451,7 +451,7 @@ func (wbs *InWorkspaceServiceServer) UmountProc(ctx context.Context, req *api.Um return } if len(msgs) != 1 { - fdrecv <- fdresp{Err: fmt.Errorf("expected a single socket control message")} + fdrecv <- fdresp{Err: xerrors.Errorf("expected a single socket control message")} return } @@ -461,7 +461,7 @@ func (wbs *InWorkspaceServiceServer) UmountProc(ctx context.Context, req *api.Um return } if len(fds) == 0 { - fdrecv <- fdresp{Err: fmt.Errorf("expected a single socket FD")} + fdrecv <- fdresp{Err: xerrors.Errorf("expected a single socket FD")} return } @@ -660,7 +660,7 @@ func nsinsider(instanceID string, targetPid int, mod func(*exec.Cmd), opts ...ns for _, ns := range nss { f, err := os.OpenFile(ns.Source, ns.Flags, 0) if err != nil { - return fmt.Errorf("cannot open %s: %w", ns.Source, err) + return xerrors.Errorf("cannot open %s: %w", ns.Source, err) } defer f.Close() cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%d", ns.Env, stdioFdCount+len(cmd.ExtraFiles))) @@ -674,7 +674,7 @@ func nsinsider(instanceID string, targetPid int, mod func(*exec.Cmd), opts ...ns cmd.Stderr = rw err = cmd.Run() if err != nil { - return fmt.Errorf("cannot run nsinsider: %w", err) + return xerrors.Errorf("cannot run nsinsider: %w", err) } return nil } diff --git a/components/ws-daemon/pkg/iws/uidmap.go b/components/ws-daemon/pkg/iws/uidmap.go index 6047966ffdc302..b097232d28b96c 100644 --- a/components/ws-daemon/pkg/iws/uidmap.go +++ b/components/ws-daemon/pkg/iws/uidmap.go @@ -156,7 +156,7 @@ func (m *Uidmapper) findHostPID(containerPID, inContainerPID uint64) (uint64, er for { if len(paths) == 0 { - return 0, fmt.Errorf("cannot find in-container PID %d on the node", inContainerPID) + return 0, xerrors.Errorf("cannot find in-container PID %d on the node", inContainerPID) } p := paths[0] diff --git a/components/ws-manager/cmd/debug-decode-imagespec.go b/components/ws-manager/cmd/debug-decode-imagespec.go index e5e5081225c767..f51cac1e3e4670 100644 --- a/components/ws-manager/cmd/debug-decode-imagespec.go +++ b/components/ws-manager/cmd/debug-decode-imagespec.go @@ -9,6 +9,7 @@ import ( "os" "github.com/spf13/cobra" + "golang.org/x/xerrors" "google.golang.org/protobuf/encoding/protojson" regapi "github.com/gitpod-io/gitpod/registry-facade/api" @@ -22,7 +23,7 @@ var debugDecodeInitializer = &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { spec, err := regapi.ImageSpecFromBase64(args[0]) if err != nil { - return fmt.Errorf("cannot unmarshal init config: %w", err) + return xerrors.Errorf("cannot unmarshal init config: %w", err) } marshaler := protojson.MarshalOptions{ diff --git a/components/ws-manager/cmd/debug-decode-initializer.go b/components/ws-manager/cmd/debug-decode-initializer.go index 59faee35c6742a..4766df84c9dd7e 100644 --- a/components/ws-manager/cmd/debug-decode-initializer.go +++ b/components/ws-manager/cmd/debug-decode-initializer.go @@ -10,6 +10,7 @@ import ( "os" "github.com/spf13/cobra" + "golang.org/x/xerrors" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" @@ -24,13 +25,13 @@ var debugDecodeImageSpec = &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { initializerPB, err := base64.StdEncoding.DecodeString(args[0]) if err != nil { - return fmt.Errorf("cannot decode init config: %w", err) + return xerrors.Errorf("cannot decode init config: %w", err) } var initializer csapi.WorkspaceInitializer err = proto.Unmarshal(initializerPB, &initializer) if err != nil { - return fmt.Errorf("cannot unmarshal init config: %w", err) + return xerrors.Errorf("cannot unmarshal init config: %w", err) } marshaler := protojson.MarshalOptions{ diff --git a/components/ws-manager/cmd/integrationtest-objs.go b/components/ws-manager/cmd/integrationtest-objs.go index 42d3d11caa9aa0..313e0677c3cab6 100644 --- a/components/ws-manager/cmd/integrationtest-objs.go +++ b/components/ws-manager/cmd/integrationtest-objs.go @@ -13,6 +13,7 @@ import ( "github.com/spf13/cobra" "golang.org/x/sync/errgroup" + "golang.org/x/xerrors" "k8s.io/apimachinery/pkg/util/yaml" "github.com/gitpod-io/gitpod/common-go/log" @@ -56,7 +57,7 @@ func getIntegrationTestPrerequisiteObjects(out io.Writer, namespace, gpHelmChart } } if helm == "" { - return fmt.Errorf("no helm executable found in path") + return xerrors.Errorf("no helm executable found in path") } // This command renders the helm template and selects everything workspace related. @@ -73,7 +74,7 @@ func getIntegrationTestPrerequisiteObjects(out io.Writer, namespace, gpHelmChart helmCmd.Stderr = os.Stderr err := helmCmd.Run() if err != nil { - return fmt.Errorf("cannot run helm: %w", err) + return xerrors.Errorf("cannot run helm: %w", err) } ro.Close() return nil @@ -87,7 +88,7 @@ func getIntegrationTestPrerequisiteObjects(out io.Writer, namespace, gpHelmChart break } if err != nil { - return fmt.Errorf("cannot read YAML document: %w", err) + return xerrors.Errorf("cannot read YAML document: %w", err) } var ingest bool diff --git a/components/ws-manager/pkg/manager/integration_test.go b/components/ws-manager/pkg/manager/integration_test.go index 79c2fe191fba20..63c541aae6cfb1 100644 --- a/components/ws-manager/pkg/manager/integration_test.go +++ b/components/ws-manager/pkg/manager/integration_test.go @@ -243,7 +243,7 @@ func ensureIntegrationTestTheiaLabelOnNodes(clientset client.Client, namespace s } if len(nodes.Items) == 0 { - return "", fmt.Errorf("no nodes with the gitpod.io/theia.%s label available", version) + return "", xerrors.Errorf("no nodes with the gitpod.io/theia.%s label available", version) } return diff --git a/components/ws-manager/pkg/manager/monitor.go b/components/ws-manager/pkg/manager/monitor.go index 42fa60552fca1f..94555031ef4c8c 100644 --- a/components/ws-manager/pkg/manager/monitor.go +++ b/components/ws-manager/pkg/manager/monitor.go @@ -155,7 +155,7 @@ func (m *Monitor) onPodEvent(evt watch.Event) error { pod, ok := evt.Object.(*corev1.Pod) if !ok { - return fmt.Errorf("received non-pod event") + return xerrors.Errorf("received non-pod event") } // We start with the default kubernetes operation timeout to not block everything in case completing @@ -231,7 +231,7 @@ func actOnPodEvent(ctx context.Context, m actingManager, status *api.WorkspaceSt workspaceID, ok := pod.Annotations[workspaceIDAnnotation] if !ok { - return fmt.Errorf("cannot act on pod %s: has no %s annotation", pod.Name, workspaceIDAnnotation) + return xerrors.Errorf("cannot act on pod %s: has no %s annotation", pod.Name, workspaceIDAnnotation) } if status.Phase == api.WorkspacePhase_STOPPING || status.Phase == api.WorkspacePhase_STOPPED { @@ -869,7 +869,7 @@ func (m *Monitor) finalizeWorkspaceContent(ctx context.Context, wso *workspaceOb if err != nil { tracing.LogError(span, err) log.WithError(err).Warn("cannot take snapshot") - err = fmt.Errorf("cannot take snapshot: %v", err) + err = xerrors.Errorf("cannot take snapshot: %v", err) } if res != nil { @@ -877,7 +877,7 @@ func (m *Monitor) finalizeWorkspaceContent(ctx context.Context, wso *workspaceOb if err != nil { tracing.LogError(span, err) log.WithError(err).Warn("cannot mark headless workspace with snapshot - that's one prebuild lost") - err = fmt.Errorf("cannot remember snapshot: %v", err) + err = xerrors.Errorf("cannot remember snapshot: %v", err) } } } @@ -988,7 +988,7 @@ func (m *Monitor) deleteDanglingServices(ctx context.Context) error { workspaceID, ok := endpoints.Labels[wsk8s.WorkspaceIDLabel] if !ok { - m.OnError(fmt.Errorf("service endpoint %s does not have %s label", service.Name, wsk8s.WorkspaceIDLabel)) + m.OnError(xerrors.Errorf("service endpoint %s does not have %s label", service.Name, wsk8s.WorkspaceIDLabel)) continue } diff --git a/components/ws-manager/pkg/manager/testdata/tabularasa.go b/components/ws-manager/pkg/manager/testdata/tabularasa.go index 6505a186ea10ce..0e8d1e0978bfb8 100644 --- a/components/ws-manager/pkg/manager/testdata/tabularasa.go +++ b/components/ws-manager/pkg/manager/testdata/tabularasa.go @@ -2,6 +2,7 @@ // Licensed under the GNU Affero General Public License (AGPL). // See License-AGPL.txt in the project root for license information. +//go:build ignore // +build ignore // Tabularasa tries to remove test fixtures which did no add to the code coverage. It removes every single fixture one by one, diff --git a/components/ws-manager/pkg/test/client.go b/components/ws-manager/pkg/test/client.go index 618658aaccc83d..9d008ee14aab60 100644 --- a/components/ws-manager/pkg/test/client.go +++ b/components/ws-manager/pkg/test/client.go @@ -6,10 +6,10 @@ package test import ( "context" - "fmt" "os" "path/filepath" + "golang.org/x/xerrors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" @@ -27,7 +27,7 @@ func GetIntegrationTestClient(kubecfgfn string) (client kubernetes.Interface, na var home string home, err = os.UserHomeDir() if err != nil { - err = fmt.Errorf("cannot determine user home dir: %w", err) + err = xerrors.Errorf("cannot determine user home dir: %w", err) return } kubeconfig = filepath.Join(home, ".kube", "config") @@ -41,13 +41,13 @@ func GetIntegrationTestClient(kubecfgfn string) (client kubernetes.Interface, na ) namespace, _, err = cfg.Namespace() if err != nil { - err = fmt.Errorf("cannot get namespace from kubeconfig: %w", err) + err = xerrors.Errorf("cannot get namespace from kubeconfig: %w", err) return } res, err := clientcmd.BuildConfigFromFlags("", kubeconfig) if err != nil { - err = fmt.Errorf("cannot build kubeconfig: %w", err) + err = xerrors.Errorf("cannot build kubeconfig: %w", err) return } @@ -59,7 +59,7 @@ func GetIntegrationTestClient(kubecfgfn string) (client kubernetes.Interface, na log.WithError(err).Warn("cannot ensure there's no ws-manager running - test may fail inexplicably") } if len(ps.Items) > 0 { - err = fmt.Errorf("there's a ws-manager running in the namespace %s - this would break the tests. Please scale down that ws-manager prior to running the test (kubectl scale --replicas=0 --namespace=%s deployment/ws-manager)", namespace, namespace) + err = xerrors.Errorf("there's a ws-manager running in the namespace %s - this would break the tests. Please scale down that ws-manager prior to running the test (kubectl scale --replicas=0 --namespace=%s deployment/ws-manager)", namespace, namespace) return } diff --git a/components/ws-proxy/pkg/proxy/config.go b/components/ws-proxy/pkg/proxy/config.go index 72fb366e2418c5..b82335e7ba7036 100644 --- a/components/ws-proxy/pkg/proxy/config.go +++ b/components/ws-proxy/pkg/proxy/config.go @@ -5,7 +5,6 @@ package proxy import ( - "fmt" "os" "path/filepath" @@ -132,7 +131,7 @@ func (c *BlobServerConfig) Validate() error { validation.Field(&c.Host, validation.Required), ) if err != nil { - return fmt.Errorf("invalid blobserver config: %w", err) + return xerrors.Errorf("invalid blobserver config: %w", err) } return nil } diff --git a/components/ws-proxy/pkg/proxy/infoprovider.go b/components/ws-proxy/pkg/proxy/infoprovider.go index 17cf1674b3b16c..a2108e75e8328e 100644 --- a/components/ws-proxy/pkg/proxy/infoprovider.go +++ b/components/ws-proxy/pkg/proxy/infoprovider.go @@ -8,7 +8,6 @@ import ( "context" "crypto/tls" "crypto/x509" - "fmt" "io" "io/ioutil" "net/url" @@ -166,7 +165,7 @@ func (p *RemoteWorkspaceInfoProvider) Run() (err error) { return err } if !certPool.AppendCertsFromPEM(ca) { - return fmt.Errorf("failed appending CA cert") + return xerrors.Errorf("failed appending CA cert") } cert, err := tls.LoadX509KeyPair(p.Config.TLS.Cert, p.Config.TLS.Key) if err != nil { diff --git a/components/ws-proxy/pkg/proxy/routes.go b/components/ws-proxy/pkg/proxy/routes.go index 9c34d8e1e1d024..632d642cbbed08 100644 --- a/components/ws-proxy/pkg/proxy/routes.go +++ b/components/ws-proxy/pkg/proxy/routes.go @@ -607,7 +607,7 @@ func (t *blobserveTransport) DoRoundTrip(req *http.Request) (resp *http.Response } // treat any client or server error code as a http error - return nil, fmt.Errorf("blobserver error: (%d) %s", resp.StatusCode, string(respBody)) + return nil, xerrors.Errorf("blobserver error: (%d) %s", resp.StatusCode, string(respBody)) } break } diff --git a/dev/blowtorch/go.mod b/dev/blowtorch/go.mod index 7282fc9c78d8e3..e316f531f1299d 100644 --- a/dev/blowtorch/go.mod +++ b/dev/blowtorch/go.mod @@ -7,6 +7,7 @@ require ( github.com/Shopify/toxiproxy v2.1.4+incompatible github.com/sirupsen/logrus v1.8.1 github.com/spf13/cobra v1.1.3 + golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 k8s.io/api v0.0.0-20190620084959-7cf5895f2711 k8s.io/apimachinery v0.0.0-20190612205821-1799e75a0719 k8s.io/client-go v0.0.0-00010101000000-000000000000 diff --git a/dev/blowtorch/go.sum b/dev/blowtorch/go.sum index ef9b591f05b59e..b550283adfe4c0 100644 --- a/dev/blowtorch/go.sum +++ b/dev/blowtorch/go.sum @@ -305,6 +305,7 @@ golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= diff --git a/dev/blowtorch/pkg/dart/injector.go b/dev/blowtorch/pkg/dart/injector.go index b2a4fcafabc57f..3d9e425ae0cae1 100644 --- a/dev/blowtorch/pkg/dart/injector.go +++ b/dev/blowtorch/pkg/dart/injector.go @@ -10,6 +10,7 @@ import ( "time" log "github.com/sirupsen/logrus" + "golang.org/x/xerrors" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -73,7 +74,7 @@ func Inject(cfg *rest.Config, namespace, targetService string, options ...Inject return nil, err } if len(pods.Items) == 0 { - return nil, fmt.Errorf("found no pods matching the service selector") + return nil, xerrors.Errorf("found no pods matching the service selector") } originalPod := pods.Items[0] log.WithField("name", originalPod.Name).Info("original pods found") @@ -221,7 +222,7 @@ func Inject(cfg *rest.Config, namespace, targetService string, options ...Inject }) if err != nil { - return nil, fmt.Errorf("cannot wait for proxy pod: %w", err) + return nil, xerrors.Errorf("cannot wait for proxy pod: %w", err) } log.Info("proxy pod up and running") @@ -230,19 +231,19 @@ func Inject(cfg *rest.Config, namespace, targetService string, options ...Inject return nil, nil } if len(proxyPods.Items) == 0 { - return nil, fmt.Errorf("no proxy pod found") + return nil, xerrors.Errorf("no proxy pod found") } tppod := proxyPods.Items[0].Name tpc, err := NewProxiedToxiproxy(cfg, namespace, tppod) if err != nil { - return nil, fmt.Errorf("cannot start proxy: %w", err) + return nil, xerrors.Errorf("cannot start proxy: %w", err) } for _, p := range oldService.Spec.Ports { _, err := tpc.CreateProxy(targetService, fmt.Sprintf(":%d", p.TargetPort.IntVal), fmt.Sprintf("%s:%d", renamedService.Name, p.Port)) if err != nil { - return nil, fmt.Errorf("cannot proxy port %d -> %d: %w", p.TargetPort.IntVal, p.Port, err) + return nil, xerrors.Errorf("cannot proxy port %d -> %d: %w", p.TargetPort.IntVal, p.Port, err) } log.WithField("port", p.Port).Infof("toxiproxy for port %d -> %d set up", p.TargetPort.IntVal, p.Port) } diff --git a/dev/blowtorch/pkg/dart/toxiproxy.go b/dev/blowtorch/pkg/dart/toxiproxy.go index 5b74097fe83c05..d81f7df2028530 100644 --- a/dev/blowtorch/pkg/dart/toxiproxy.go +++ b/dev/blowtorch/pkg/dart/toxiproxy.go @@ -16,6 +16,7 @@ import ( toxiproxy "github.com/Shopify/toxiproxy/client" log "github.com/sirupsen/logrus" + "golang.org/x/xerrors" "k8s.io/client-go/rest" "k8s.io/client-go/tools/portforward" "k8s.io/client-go/transport/spdy" @@ -106,7 +107,7 @@ func forwardPort(ctx context.Context, config *rest.Config, namespace, pod, port } if errOut.Len() != 0 { - errchan <- fmt.Errorf(errOut.String()) + errchan <- xerrors.Errorf(errOut.String()) return } diff --git a/dev/gpctl/pkg/prettyprint/prettyprint.go b/dev/gpctl/pkg/prettyprint/prettyprint.go index e2ca6cc8120400..38814b80cf325e 100644 --- a/dev/gpctl/pkg/prettyprint/prettyprint.go +++ b/dev/gpctl/pkg/prettyprint/prettyprint.go @@ -12,6 +12,7 @@ import ( "text/tabwriter" "github.com/Masterminds/sprig" + "golang.org/x/xerrors" "k8s.io/client-go/util/jsonpath" ) @@ -87,7 +88,7 @@ type Printer struct { func (pp *Printer) Print(obj interface{}) error { formatter, ok := formatter[pp.Format] if !ok { - return fmt.Errorf("Unknown format: %s", pp.Format) + return xerrors.Errorf("Unknown format: %s", pp.Format) } return formatter(pp, obj) diff --git a/dev/gpctl/pkg/util/kubernetes.go b/dev/gpctl/pkg/util/kubernetes.go index 7a864e850b767f..64e1762bdbf84a 100644 --- a/dev/gpctl/pkg/util/kubernetes.go +++ b/dev/gpctl/pkg/util/kubernetes.go @@ -107,7 +107,7 @@ func ForwardPort(ctx context.Context, config *rest.Config, namespace, pod, port } if errOut.Len() != 0 { - errchan <- fmt.Errorf(errOut.String()) + errchan <- xerrors.Errorf(errOut.String()) return } @@ -128,7 +128,7 @@ func CertPoolFromSecret(clientSet kubernetes.Interface, namespace, secretName st certFile := secret.Data[file] if !cert.AppendCertsFromPEM(certFile) { - return nil, fmt.Errorf("credentials: failed to append certificates") + return nil, xerrors.Errorf("credentials: failed to append certificates") } } return diff --git a/dev/telepresence-hack/copy-mounts/main.go b/dev/telepresence-hack/copy-mounts/main.go index 7feb88d0323673..11ed957e8af35d 100644 --- a/dev/telepresence-hack/copy-mounts/main.go +++ b/dev/telepresence-hack/copy-mounts/main.go @@ -6,13 +6,13 @@ package main import ( "context" - "fmt" "io/ioutil" "os" "path/filepath" "time" "github.com/gitpod-io/gitpod/common-go/log" + "golang.org/x/xerrors" "github.com/spf13/pflag" corev1 "k8s.io/api/core/v1" @@ -92,7 +92,7 @@ func run() error { for _, cv := range c.VolumeMounts { v, ok := volumes[cv.Name] if !ok { - return fmt.Errorf("did not find volume %s in %s", cv.Name, c.Name) + return xerrors.Errorf("did not find volume %s in %s", cv.Name, c.Name) } err = downloadVolume(ctx, client, namespace, cv, v) @@ -121,7 +121,7 @@ func downloadVolume(ctx context.Context, client kubernetes.Interface, namespace func downloadConfigMap(ctx context.Context, client kubernetes.Interface, namespace string, mount corev1.VolumeMount, volume corev1.Volume) (err error) { defer func() { if err != nil { - err = fmt.Errorf("cannot download config map %s", volume.Name) + err = xerrors.Errorf("cannot download config map %s", volume.Name) } }() @@ -149,7 +149,7 @@ func downloadConfigMap(ctx context.Context, client kubernetes.Interface, namespa func downloadSecret(ctx context.Context, client kubernetes.Interface, namespace string, mount corev1.VolumeMount, volume corev1.Volume) (err error) { defer func() { if err != nil { - err = fmt.Errorf("cannot download config map %s", volume.Name) + err = xerrors.Errorf("cannot download config map %s", volume.Name) } }() diff --git a/dev/telepresence-hack/go.mod b/dev/telepresence-hack/go.mod index 10cfb078fdfe55..b066471db08a18 100644 --- a/dev/telepresence-hack/go.mod +++ b/dev/telepresence-hack/go.mod @@ -55,6 +55,7 @@ replace k8s.io/mount-utils => k8s.io/mount-utils v0.22.0 // leeway indirect from require ( github.com/gitpod-io/gitpod/common-go v0.0.0-00010101000000-000000000000 github.com/spf13/pflag v1.0.5 + golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 k8s.io/api v0.22.0 k8s.io/apimachinery v0.22.0 k8s.io/client-go v0.22.0 diff --git a/dev/version-manifest/go.mod b/dev/version-manifest/go.mod index 0bfb42198f3214..a45dca98235aee 100644 --- a/dev/version-manifest/go.mod +++ b/dev/version-manifest/go.mod @@ -4,5 +4,6 @@ go 1.17 require ( github.com/google/go-cmp v0.5.6 + golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b ) diff --git a/dev/version-manifest/main.go b/dev/version-manifest/main.go index 522b5e6f337401..89efb7faf96d72 100644 --- a/dev/version-manifest/main.go +++ b/dev/version-manifest/main.go @@ -13,6 +13,7 @@ import ( "sort" "strings" + "golang.org/x/xerrors" "gopkg.in/yaml.v3" ) @@ -38,7 +39,7 @@ func produceManifest(out io.Writer, dir fs.FS) error { var mdobj MD err = yaml.Unmarshal(b, &mdobj) if err != nil { - return fmt.Errorf("cannot unmarshal %s: %w", md, err) + return xerrors.Errorf("cannot unmarshal %s: %w", md, err) } if mdobj.HelmComponent == "" { continue @@ -46,13 +47,13 @@ func produceManifest(out io.Writer, dir fs.FS) error { imgf, err := fs.ReadFile(dir, filepath.Join(filepath.Dir(md), "imgnames.txt")) if err != nil { - return fmt.Errorf("cannot read image names for %s: %w", md, err) + return xerrors.Errorf("cannot read image names for %s: %w", md, err) } imgs := strings.Split(strings.TrimSpace(string(imgf)), "\n") img := imgs[len(imgs)-1] segs := strings.Split(img, ":") if len(segs) != 2 { - return fmt.Errorf("invalid image format: %s", img) + return xerrors.Errorf("invalid image format: %s", img) } version := segs[1] versions[mdobj.HelmComponent] = version @@ -109,7 +110,7 @@ func produceManifest(out io.Writer, dir fs.FS) error { continue } - return fmt.Errorf("unknown value type - this should never happen") + return xerrors.Errorf("unknown value type - this should never happen") } return nil } diff --git a/test/go.mod b/test/go.mod index 890ba771d3e2b9..0ffd112bd26085 100644 --- a/test/go.mod +++ b/test/go.mod @@ -12,7 +12,7 @@ require ( github.com/gitpod-io/gitpod/ws-manager/api v0.0.0-00010101000000-000000000000 github.com/go-sql-driver/mysql v1.5.0 github.com/google/uuid v1.2.0 - github.com/prometheus/procfs v0.7.3 // indirect + github.com/prometheus/procfs v0.7.3 golang.org/x/sync v0.0.0-20210220032951-036812b2e83c golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 @@ -66,7 +66,6 @@ require ( github.com/prometheus/client_golang v1.11.0 // indirect github.com/prometheus/client_model v0.2.0 // indirect github.com/prometheus/common v0.26.0 // indirect - github.com/prometheus/procfs v0.6.0 // indirect github.com/rs/xid v1.2.1 // indirect github.com/sirupsen/logrus v1.8.1 // indirect github.com/sourcegraph/jsonrpc2 v0.0.0-20200429184054-15c2290dcb37 // indirect @@ -80,7 +79,6 @@ require ( golang.org/x/mod v0.4.2 // indirect golang.org/x/net v0.0.0-20210520170846-37e1c6afe023 // indirect golang.org/x/oauth2 v0.0.0-20210615190721-d04028783cf1 // indirect - golang.org/x/sys v0.0.0-20210616094352-59db8d763f22 // indirect golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d // indirect golang.org/x/text v0.3.6 // indirect golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac // indirect diff --git a/test/go.sum b/test/go.sum index 6b3f3fb1b4a373..fb91da9d932209 100644 --- a/test/go.sum +++ b/test/go.sum @@ -639,7 +639,6 @@ github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDa github.com/prometheus/procfs v0.0.5/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.6.0 h1:mxy4L2jP6qMonqmq+aTtOx1ifVWUgG/TAmntgbh3xv4= github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= github.com/prometheus/procfs v0.7.3 h1:4jVXhlkAyzOScmCkXBTOLRLTz8EeU+eyjrwB/EPq0VU= github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= diff --git a/test/pkg/integration/apis.go b/test/pkg/integration/apis.go index ecc313f07ed7a7..2822d42818e786 100644 --- a/test/pkg/integration/apis.go +++ b/test/pkg/integration/apis.go @@ -38,7 +38,7 @@ import ( ) var ( - errNoSuitableUser = fmt.Errorf("no suitable user found: make sure there's at least one non-builtin user in the database (e.g. login)") + errNoSuitableUser = xerrors.Errorf("no suitable user found: make sure there's at least one non-builtin user in the database (e.g. login)") ) // API provides access to the individual component's API @@ -325,7 +325,7 @@ func (c *ComponentAPI) WorkspaceManager() wsmanapi.WorkspaceManagerClient { log.Debug("using TLS config to connect ws-manager") certPool := x509.NewCertPool() if !certPool.AppendCertsFromPEM(caCrt) { - rerr = fmt.Errorf("failed appending CA cert") + rerr = xerrors.Errorf("failed appending CA cert") return nil } cert, err := tls.X509KeyPair(tlsCrt, tlsKey) @@ -476,7 +476,7 @@ func (c *ComponentAPI) findDBConfig() (*DBConfig, error) { } } if remotePort == 0 { - return nil, fmt.Errorf("no ports found on service: %s", svc.Name) + return nil, xerrors.Errorf("no ports found on service: %s", svc.Name) } // find pod to forward to @@ -487,7 +487,7 @@ func (c *ComponentAPI) findDBConfig() (*DBConfig, error) { return nil, err } if len(pods.Items) == 0 { - return nil, fmt.Errorf("no pods for service %s found", svc.Name) + return nil, xerrors.Errorf("no pods for service %s found", svc.Name) } var pod *corev1.Pod for _, p := range pods.Items { @@ -510,7 +510,7 @@ func (c *ComponentAPI) findDBConfig() (*DBConfig, error) { break } if pod == nil { - return nil, fmt.Errorf("no active pod for service %s found", svc.Name) + return nil, xerrors.Errorf("no active pod for service %s found", svc.Name) } localPort, err := getFreePort() @@ -536,7 +536,7 @@ func (c *ComponentAPI) findDBConfigFromPodEnv(componentName string) (*DBConfig, return nil, err } if len(list.Items) == 0 { - return nil, fmt.Errorf("no pods found for: %s", lblSelector) + return nil, xerrors.Errorf("no pods found for: %s", lblSelector) } pod := list.Items[0] @@ -551,7 +551,7 @@ OuterLoop: } else if v.Name == "DB_PORT" { pPort, err := strconv.ParseUint(v.Value, 10, 16) if err != nil { - return nil, fmt.Errorf("error parsing DB_PORT '%s' on pod %s!", v.Value, pod.Name) + return nil, xerrors.Errorf("error parsing DB_PORT '%s' on pod %s!", v.Value, pod.Name) } port = int32(pPort) } else if v.Name == "DB_HOST" { @@ -563,7 +563,7 @@ OuterLoop: } } if password == "" || port == 0 || host == "" { - return nil, fmt.Errorf("could not find complete DBConfig on pod %s!", pod.Name) + return nil, xerrors.Errorf("could not find complete DBConfig on pod %s!", pod.Name) } config := DBConfig{ Host: host, diff --git a/test/pkg/integration/integration.go b/test/pkg/integration/integration.go index d608206a07ce2e..41ba6d23fb17a5 100644 --- a/test/pkg/integration/integration.go +++ b/test/pkg/integration/integration.go @@ -266,7 +266,7 @@ func (it *Test) Instrument(component ComponentType, agentName string, opts ...In if err != nil { return nil, err } - return nil, fmt.Errorf("agent stopped unexepectedly") + return nil, xerrors.Errorf("agent stopped unexepectedly") case <-time.After(1 * time.Second): } @@ -314,7 +314,7 @@ func (it *Test) Instrument(component ComponentType, agentName string, opts ...In return nil } if err != nil { - return fmt.Errorf("cannot shutdown agent: %w", err) + return xerrors.Errorf("cannot shutdown agent: %w", err) } return nil }) @@ -399,7 +399,7 @@ func forwardPort(ctx context.Context, config *rest.Config, namespace, pod, port } if errOut.Len() != 0 { - errchan <- fmt.Errorf(errOut.String()) + errchan <- xerrors.Errorf(errOut.String()) return } @@ -533,7 +533,7 @@ func (t *Test) buildAgent(name string) (loc string, err error) { ) out, err := cmd.CombinedOutput() if err != nil { - return "", fmt.Errorf("%w: %s", err, string(out)) + return "", xerrors.Errorf("%w: %s", err, string(out)) } return f.Name(), nil @@ -610,7 +610,7 @@ func envvarFromPod(pods *corev1.PodList, name, containerName string) (value stri } } if container == nil { - return "", fmt.Errorf("envvarFromPod: cannot find container %s", containerName) + return "", xerrors.Errorf("envvarFromPod: cannot find container %s", containerName) } for _, e := range container.Env { if e.Name == name { diff --git a/test/pkg/integration/workspace.go b/test/pkg/integration/workspace.go index de0ce84a60b51c..d4af3bf6aa8041 100644 --- a/test/pkg/integration/workspace.go +++ b/test/pkg/integration/workspace.go @@ -13,6 +13,7 @@ import ( "time" "github.com/google/uuid" + "golang.org/x/xerrors" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "k8s.io/apimachinery/pkg/api/errors" @@ -249,7 +250,7 @@ func LaunchWorkspaceFromContextURL(it *Test, contextURL string, serverOpts ...Gi it.t.Fatalf("cannot get workspace: %q", err) } if nfo.LatestInstance == nil { - err = fmt.Errorf("CreateWorkspace did not start the workspace") + err = xerrors.Errorf("CreateWorkspace did not start the workspace") it.t.Fatal(err) } @@ -588,7 +589,7 @@ func (it *Test) resolveOrBuildImage(baseRef string) (absref string, err error) { if resp.Status == imgbldr.BuildStatus_done_success { break } else if resp.Status == imgbldr.BuildStatus_done_failure { - return "", fmt.Errorf("cannot build workspace image: %s", resp.Message) + return "", xerrors.Errorf("cannot build workspace image: %s", resp.Message) } } diff --git a/test/tests/imagebuilder/builder_test.go b/test/tests/imagebuilder/builder_test.go index ebeeb2d051bcd2..bb63741aaba79f 100644 --- a/test/tests/imagebuilder/builder_test.go +++ b/test/tests/imagebuilder/builder_test.go @@ -6,7 +6,6 @@ package imagerbuilder_test import ( "context" - "fmt" "io" "testing" "time" @@ -15,6 +14,7 @@ import ( imgapi "github.com/gitpod-io/gitpod/image-builder/api" "github.com/gitpod-io/gitpod/test/pkg/integration" "golang.org/x/sync/errgroup" + "golang.org/x/xerrors" ) func TestBaseImageBuild(t *testing.T) { @@ -119,16 +119,16 @@ func TestParallelBaseImageBuild(t *testing.T) { for { msg, err := cl.Recv() if err != nil && err != io.EOF { - return fmt.Errorf("image builder error: %v", err) + return xerrors.Errorf("image builder error: %v", err) } if err := ctx.Err(); err != nil { - return fmt.Errorf("context error: %v", err) + return xerrors.Errorf("context error: %v", err) } if msg.Status == imgapi.BuildStatus_done_success { break } else if msg.Status == imgapi.BuildStatus_done_failure { - return fmt.Errorf("image build failed: %s", msg.Message) + return xerrors.Errorf("image build failed: %s", msg.Message) } else { t.Logf("build output: %s", msg.Message) } diff --git a/test/tests/workspace/common/git-client.go b/test/tests/workspace/common/git-client.go index 9322b7af4c781f..6f931119998595 100644 --- a/test/tests/workspace/common/git-client.go +++ b/test/tests/workspace/common/git-client.go @@ -5,11 +5,11 @@ package common import ( - "fmt" "net/rpc" "strings" agent "github.com/gitpod-io/gitpod/test/tests/workspace/workspace_agent/api" + "golang.org/x/xerrors" ) type GitClient struct { @@ -28,10 +28,10 @@ func (g GitClient) GetBranch(workspaceRoot string) (string, error) { Args: []string{"rev-parse", "--abbrev-ref", "HEAD"}, }, &resp) if err != nil { - return "", fmt.Errorf("getBranch error: %w", err) + return "", xerrors.Errorf("getBranch error: %w", err) } if resp.ExitCode != 0 { - return "", fmt.Errorf("getBranch rc!=0: %d", resp.ExitCode) + return "", xerrors.Errorf("getBranch rc!=0: %d", resp.ExitCode) } return strings.Trim(resp.Stdout, " \t\n"), nil } @@ -53,7 +53,7 @@ func (g GitClient) Add(dir string, files ...string) error { return err } if resp.ExitCode != 0 { - return fmt.Errorf("commit returned rc: %d", resp.ExitCode) + return xerrors.Errorf("commit returned rc: %d", resp.ExitCode) } return nil } @@ -73,7 +73,7 @@ func (g GitClient) Commit(dir string, message string, all bool) error { return err } if resp.ExitCode != 0 { - return fmt.Errorf("commit returned rc: %d", resp.ExitCode) + return xerrors.Errorf("commit returned rc: %d", resp.ExitCode) } return nil } @@ -96,7 +96,7 @@ func (g GitClient) Push(dir string, force bool, moreArgs ...string) error { return err } if resp.ExitCode != 0 { - return fmt.Errorf("commit returned rc: %d", resp.ExitCode) + return xerrors.Errorf("commit returned rc: %d", resp.ExitCode) } return nil } diff --git a/test/tests/workspace/workspace_agent/main.go b/test/tests/workspace/workspace_agent/main.go index 19fe891a31b335..059b2a4b46c07e 100644 --- a/test/tests/workspace/workspace_agent/main.go +++ b/test/tests/workspace/workspace_agent/main.go @@ -17,6 +17,7 @@ import ( "github.com/gitpod-io/gitpod/test/tests/workspace/workspace_agent/api" "github.com/prometheus/procfs" "golang.org/x/sys/unix" + "golang.org/x/xerrors" ) func main() { @@ -35,7 +36,7 @@ func enterSupervisorNamespaces() error { nsenter, err := exec.LookPath("nsenter") if err != nil { - return fmt.Errorf("cannot find nsenter") + return xerrors.Errorf("cannot find nsenter") } // This agent expectes to be called using the workspacekit lift (i.e. in ring1). @@ -63,7 +64,7 @@ func enterSupervisorNamespaces() error { } } if supervisorPID == 0 { - return fmt.Errorf("no supervisor process found") + return xerrors.Errorf("no supervisor process found") } // Then we copy ourselves to a location that we can access from the supervisor NS @@ -83,7 +84,7 @@ func enterSupervisorNamespaces() error { defer selfFD.Close() _, err = io.Copy(dst, selfFD) if err != nil { - return fmt.Errorf("error copying agent: %w", err) + return xerrors.Errorf("error copying agent: %w", err) } return unix.Exec(nsenter, append([]string{nsenter, "-t", strconv.Itoa(supervisorPID), "-m", "-p", "/agent"}, os.Args[1:]...), append(os.Environ(), "AGENT_IN_RING2=true")) @@ -137,7 +138,7 @@ func (*WorkspaceAgent) Exec(req *api.ExecRequest, resp *api.ExecResponse) (err e exitError, ok := err.(*exec.ExitError) if !ok { fullCommand := strings.Join(append([]string{req.Command}, req.Args...), " ") - return fmt.Errorf("%s: %w", fullCommand, err) + return xerrors.Errorf("%s: %w", fullCommand, err) } rc = exitError.ExitCode() err = nil