Skip to content

Commit

Permalink
Merge pull request #826 from ncopa/std-error-handling
Browse files Browse the repository at this point in the history
Use fmt.Errorf everywhere for error handling
  • Loading branch information
jnummelin authored Apr 7, 2021
2 parents e405176 + 5de216d commit b18a14d
Show file tree
Hide file tree
Showing 30 changed files with 92 additions and 116 deletions.
5 changes: 2 additions & 3 deletions cmd/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"time"

"github.com/avast/retry-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"

Expand Down Expand Up @@ -135,7 +134,7 @@ func (c *CmdOpts) startController() error {
join = true
joinClient, err = token.JoinClientFromToken(c.TokenArg)
if err != nil {
return errors.Wrapf(err, "failed to create join client")
return fmt.Errorf("failed to create join client: %w", err)
}

componentManager.AddSync(&controller.CASyncer{
Expand Down Expand Up @@ -175,7 +174,7 @@ func (c *CmdOpts) startController() error {
LogLevel: c.Logging["etcd"],
}
default:
return errors.New(fmt.Sprintf("Invalid storage type: %s", c.ClusterConfig.Spec.Storage.Type))
return fmt.Errorf("Invalid storage type: %s", c.ClusterConfig.Spec.Storage.Type)
}
logrus.Infof("Using storage backend %s", c.ClusterConfig.Spec.Storage.Type)
componentManager.Add(storageBackend)
Expand Down
6 changes: 3 additions & 3 deletions cmd/kubeconfig/admin.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ limitations under the License.
package kubeconfig

import (
"fmt"
"io/ioutil"
"os"
"strings"

"github.com/cloudflare/cfssl/log"
"github.com/k0sproject/k0s/internal/util"
"github.com/k0sproject/k0s/pkg/config"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)

Expand All @@ -45,12 +45,12 @@ func kubeConfigAdminCmd() *cobra.Command {

clusterAPIURL, err := c.getAPIURL()
if err != nil {
return errors.Wrap(err, "failed to fetch cluster's API Address: %v.")
return fmt.Errorf("failed to fetch cluster's API Address: %w", err)
}
newContent := strings.Replace(string(content), "https://localhost:6443", clusterAPIURL, -1)
os.Stdout.Write([]byte(newContent))
} else {
return errors.Errorf("failed to read admin config, is the control plane initialized on this node?")
return fmt.Errorf("failed to read admin config, is the control plane initialized on this node?")
}
return nil
},
Expand Down
6 changes: 3 additions & 3 deletions cmd/kubeconfig/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import (
"bytes"
"encoding/base64"
"fmt"

"github.com/cloudflare/cfssl/log"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"html/template"
Expand Down Expand Up @@ -75,7 +75,7 @@ Note: A certificate once signed cannot be revoked for a particular user`,
log.Level = log.LevelFatal

if len(args) == 0 {
return errors.New("Username is mandatory")
return fmt.Errorf("Username is mandatory")
}
var username = args[0]
c := CmdOpts(config.GetCmdOpts())
Expand All @@ -86,7 +86,7 @@ Note: A certificate once signed cannot be revoked for a particular user`,
}
caCert, err := ioutil.ReadFile(path.Join(c.K0sVars.CertRootDir, "ca.crt"))
if err != nil {
return errors.Wrapf(err, "failed to read cluster ca certificate, is the control plane initialized on this node?")
return fmt.Errorf("failed to read cluster ca certificate: %w, is the control plane initialized on this node?", err)
}
caCertPath, caCertKey := path.Join(c.K0sVars.CertRootDir, "ca.crt"), path.Join(c.K0sVars.CertRootDir, "ca.key")
userReq := certificate.Request{
Expand Down
6 changes: 3 additions & 3 deletions internal/util/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ limitations under the License.
package util

import (
"fmt"
"net"

"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)

Expand All @@ -28,7 +28,7 @@ func AllAddresses() ([]string, error) {

addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, errors.Wrap(err, "failed to list network interfaces")
return nil, fmt.Errorf("failed to list network interfaces: %w", err)
}

for _, a := range addrs {
Expand All @@ -49,7 +49,7 @@ func AllAddresses() ([]string, error) {
func FirstPublicAddress() (string, error) {
ifs, err := net.Interfaces()
if err != nil {
return "127.0.0.1", errors.Wrap(err, "failed to list network interfaces")
return "127.0.0.1", fmt.Errorf("failed to list network interfaces: %w", err)
}
for _, i := range ifs {
if i.Name == "vxlan.calico" {
Expand Down
8 changes: 4 additions & 4 deletions internal/util/templatewriter.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ limitations under the License.
package util

import (
"fmt"
"html/template"
"io"
"os"

"github.com/Masterminds/sprig"
"github.com/pkg/errors"

"github.com/k0sproject/k0s/pkg/constant"
)
Expand All @@ -38,7 +38,7 @@ type TemplateWriter struct {
func (p *TemplateWriter) Write() error {
podFile, err := os.OpenFile(p.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, constant.CertMode)
if err != nil {
return errors.Wrapf(err, "failed to open pod file for %s", p.Name)
return fmt.Errorf("failed to open pod file for %s: %w", p.Name, err)
}
return p.WriteToBuffer(podFile)
}
Expand All @@ -47,11 +47,11 @@ func (p *TemplateWriter) Write() error {
func (p *TemplateWriter) WriteToBuffer(w io.Writer) error {
t, err := template.New(p.Name).Funcs(sprig.FuncMap()).Parse(p.Template)
if err != nil {
return errors.Wrapf(err, "failed to parse template for %s", p.Name)
return fmt.Errorf("failed to parse template for %s: %w", p.Name, err)
}
err = t.Execute(w, p.Data)
if err != nil {
return errors.Wrapf(err, "failed to execute template for %s", p.Name)
return fmt.Errorf("failed to execute template for %s: %w", p.Name, err)
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions pkg/apis/v1beta1/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ limitations under the License.
package v1beta1

import (
"fmt"
"io"
"io/ioutil"

"github.com/k0sproject/k0s/pkg/constant"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)

Expand Down Expand Up @@ -96,7 +96,7 @@ func (c *ClusterConfig) Validate() []error {
func FromYamlFile(filename string, k0sVars constant.CfgVars) (*ClusterConfig, error) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return nil, errors.Wrapf(err, "failed to read config file at %s", filename)
return nil, fmt.Errorf("failed to read config file at %s: %w", filename, err)
}

return FromYamlString(string(buf), k0sVars)
Expand Down
7 changes: 3 additions & 4 deletions pkg/apis/v1beta1/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import (
"fmt"
"net"

"github.com/pkg/errors"
utilnet "k8s.io/utils/net"
)

Expand Down Expand Up @@ -82,7 +81,7 @@ func (n *Network) Validate() []error {
func (n *Network) DNSAddress() (string, error) {
_, ipnet, err := net.ParseCIDR(n.ServiceCIDR)
if err != nil {
return "", errors.Wrapf(err, "failed to parse service CIDR %s: %s", n.ServiceCIDR, err.Error())
return "", fmt.Errorf("failed to parse service CIDR %s: %w", n.ServiceCIDR, err)
}

address := ipnet.IP.To4()
Expand All @@ -94,7 +93,7 @@ func (n *Network) DNSAddress() (string, error) {
}

if !ipnet.Contains(address) {
return "", errors.Wrapf(err, "failed to calculate a valid DNS address: %s", address.String())
return "", fmt.Errorf("failed to calculate a valid DNS address: %s", address.String())
}

return address.String(), nil
Expand All @@ -110,7 +109,7 @@ func (n *Network) InternalAPIAddresses() ([]string, error) {

parsedCIDRs, err := utilnet.ParseCIDRs(cidrs)
if err != nil {
return nil, fmt.Errorf("can't parse service cidr to build internal API address: %v", err)
return nil, fmt.Errorf("can't parse service cidr to build internal API address: %w", err)
}

stringifiedAddresses := make([]string, len(parsedCIDRs))
Expand Down
4 changes: 2 additions & 2 deletions pkg/applier/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ package applier

import (
"context"
"fmt"
"path"

"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"gopkg.in/fsnotify.v1"

Expand Down Expand Up @@ -48,7 +48,7 @@ type Manager struct {
func (m *Manager) Init() error {
err := util.InitDirectory(m.K0sVars.ManifestsDir, constant.ManifestsDirMode)
if err != nil {
return errors.Wrapf(err, "failed to create manifest bundle dir %s", m.K0sVars.ManifestsDir)
return fmt.Errorf("failed to create manifest bundle dir %s: %w", m.K0sVars.ManifestsDir, err)
}
m.log = logrus.WithField("component", "applier-manager")
m.stacks = make(map[string]*StackApplier)
Expand Down
11 changes: 5 additions & 6 deletions pkg/applier/stack.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import (
"sync"

jsonpatch "github.com/evanphx/json-patch"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
Expand Down Expand Up @@ -206,7 +205,7 @@ func (s *Stack) findPruneableResources(ctx context.Context, mapper *restmapper.D
if discovery.IsGroupDiscoveryFailedError(err) {
log.Debugf("error in api discovery for pruning: %s", err.Error())
} else {
return nil, errors.Wrapf(err, "failed to list api groups for pruning")
return nil, fmt.Errorf("failed to list api groups for pruning: %w", err)
}
}

Expand Down Expand Up @@ -251,13 +250,13 @@ func (s *Stack) deleteResource(ctx context.Context, mapper *restmapper.DeferredD
propagationPolicy := metav1.DeletePropagationForeground
drClient, err := s.clientForResource(mapper, resource)
if err != nil {
return errors.Wrapf(err, "failed to get dynamic client for resource %s", resource.GetSelfLink())
return fmt.Errorf("failed to get dynamic client for resource %s: %w", resource.GetSelfLink(), err)
}
err = drClient.Delete(ctx, resource.GetName(), metav1.DeleteOptions{
PropagationPolicy: &propagationPolicy,
})
if !apiErrors.IsNotFound(err) && !apiErrors.IsGone(err) {
return errors.Wrapf(err, "deleting resource failed")
return fmt.Errorf("deleting resource failed: %w", err)
}
return nil
}
Expand Down Expand Up @@ -347,11 +346,11 @@ func (s *Stack) patchResource(ctx context.Context, drClient dynamic.ResourceInte

patch, err := jsonpatch.CreateMergePatch([]byte(original), modified)
if err != nil {
return errors.Wrapf(err, "failed to create jsonpatch data")
return fmt.Errorf("failed to create jsonpatch data: %w", err)
}
_, err = drClient.Patch(ctx, localResource.GetName(), types.MergePatchType, patch, metav1.PatchOptions{})
if err != nil {
return errors.Wrapf(err, "failed to patch resource")
return fmt.Errorf("failed to patch resource: %w", err)
}

return nil
Expand Down
16 changes: 8 additions & 8 deletions pkg/assets/stage.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ package assets

import (
"compress/gzip"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"

"github.com/pkg/errors"
"github.com/sirupsen/logrus"

"github.com/k0sproject/k0s/internal/util"
Expand Down Expand Up @@ -71,7 +71,7 @@ func Stage(dataDir string, name string, filemode os.FileMode) error {

err := util.InitDirectory(filepath.Dir(p), filemode)
if err != nil {
return errors.Wrapf(err, "failed to create dir %s", filepath.Dir(p))
return fmt.Errorf("failed to create dir %s: %w", filepath.Dir(p), err)
}

if ExecutableIsOlder(p) {
Expand Down Expand Up @@ -101,11 +101,11 @@ func Stage(dataDir string, name string, filemode os.FileMode) error {

// find location at EOF - BinDataSize + offs
if _, err := infile.Seek(-BinDataSize+bin.offset, 2); err != nil {
return errors.Wrapf(err, "Failed to find embedded file position for %s", name)
return fmt.Errorf("Failed to find embedded file position for %s: %w", name, err)
}
gz, err := gzip.NewReader(io.LimitReader(infile, bin.size))
if err != nil {
return errors.Wrapf(err, "Failed to create gzip reader for %s", name)
return fmt.Errorf("Failed to create gzip reader for %s: %w", name, err)
}

logrus.Debug("Writing static file: ", p)
Expand All @@ -114,7 +114,7 @@ func Stage(dataDir string, name string, filemode os.FileMode) error {
return err
}
if err := os.Chmod(p, 0550); err != nil {
return errors.Wrapf(err, "Failed to chmod %s", name)
return fmt.Errorf("Failed to chmod %s: %w", name, err)
}
return nil
}
Expand All @@ -123,15 +123,15 @@ func copyTo(p string, gz io.Reader) error {
_ = os.Remove(p)
f, err := os.Create(p)
if err != nil {
return errors.Wrapf(err, "failed to create %s", p)
return fmt.Errorf("failed to create %s: %w", p, err)
}
defer f.Close()
if err != nil {
return errors.Wrapf(err, "failed to create %s", p)
return fmt.Errorf("failed to create %s: %w", p, err)
}
_, err = io.Copy(f, gz)
if err != nil {
return errors.Wrapf(err, "failed to write to %s", p)
return fmt.Errorf("failed to write to %s: %w", p, err)
}
return nil
}
6 changes: 2 additions & 4 deletions pkg/certificate/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ import (
"os"
"path/filepath"

"github.com/pkg/errors"

"github.com/cloudflare/cfssl/certinfo"
"github.com/cloudflare/cfssl/cli"
"github.com/cloudflare/cfssl/cli/genkey"
Expand Down Expand Up @@ -171,11 +169,11 @@ func (m *Manager) EnsureCertificate(certReq Request, ownerName string) (Certific

cert, err := ioutil.ReadFile(certFile)
if err != nil {
return Certificate{}, errors.Wrapf(err, "failed to read ca cert %s for %s", certFile, certReq.Name)
return Certificate{}, fmt.Errorf("failed to read ca cert %s for %s: %w", certFile, certReq.Name, err)
}
key, err := ioutil.ReadFile(keyFile)
if err != nil {
return Certificate{}, errors.Wrapf(err, "failed to read ca key %s for %s", keyFile, certReq.Name)
return Certificate{}, fmt.Errorf("failed to read ca key %s for %s: %w", keyFile, certReq.Name, err)
}

return Certificate{
Expand Down
7 changes: 3 additions & 4 deletions pkg/component/controller/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
"net/http"
"path"

"github.com/pkg/errors"
"github.com/sirupsen/logrus"

"github.com/k0sproject/k0s/internal/util"
Expand Down Expand Up @@ -76,7 +75,7 @@ func (a *APIServer) Init() error {
var err error
a.uid, err = util.GetUID(constant.ApiserverUser)
if err != nil {
logrus.Warning(errors.Wrap(err, "Running kube-apiserver as root"))
logrus.Warning(fmt.Errorf("Running kube-apiserver as root: %w", err))
}
return assets.Stage(a.K0sVars.BinDir, "kube-apiserver", constant.BinDirMode)
}
Expand Down Expand Up @@ -159,7 +158,7 @@ func (a *APIServer) Run() error {
fmt.Sprintf("--etcd-certfile=%s", path.Join(a.K0sVars.CertRootDir, "apiserver-etcd-client.crt")),
fmt.Sprintf("--etcd-keyfile=%s", path.Join(a.K0sVars.CertRootDir, "apiserver-etcd-client.key")))
default:
return errors.New(fmt.Sprintf("invalid storage type: %s", a.ClusterConfig.Spec.Storage.Type))
return fmt.Errorf("invalid storage type: %s", a.ClusterConfig.Spec.Storage.Type)
}
return a.supervisor.Supervise()
}
Expand All @@ -175,7 +174,7 @@ func (a *APIServer) writeKonnectivityConfig() error {
}
err := tw.Write()
if err != nil {
return errors.Wrap(err, "failed to write konnectivity config")
return fmt.Errorf("failed to write konnectivity config: %w", err)
}

return nil
Expand Down
Loading

0 comments on commit b18a14d

Please sign in to comment.