Skip to content

Commit

Permalink
Merge pull request #4299 from twz123/drop-multierr
Browse files Browse the repository at this point in the history
Drop multierr module and rely on the standard lib
  • Loading branch information
twz123 authored May 22, 2024
2 parents 93370aa + 8dca11d commit a3bc75d
Show file tree
Hide file tree
Showing 19 changed files with 103 additions and 82 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ require (
go.etcd.io/etcd/client/pkg/v3 v3.5.13
go.etcd.io/etcd/client/v3 v3.5.13
go.etcd.io/etcd/etcdutl/v3 v3.5.13
go.uber.org/multierr v1.11.0
go.uber.org/zap v1.27.0
golang.org/x/crypto v0.23.0
golang.org/x/mod v0.17.0
Expand Down Expand Up @@ -255,6 +254,7 @@ require (
go.opentelemetry.io/otel/trace v1.20.0 // indirect
go.opentelemetry.io/proto/otlp v1.0.0 // indirect
go.starlark.net v0.0.0-20230525235612-a134d8f9ddca // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/oauth2 v0.18.0 // indirect
Expand Down
29 changes: 20 additions & 9 deletions internal/pkg/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ import (
"path/filepath"

"github.com/k0sproject/k0s/internal/pkg/users"

"go.uber.org/multierr"
)

// Exists checks if a file exists and is not a directory before we
Expand Down Expand Up @@ -60,7 +58,7 @@ func Copy(src, dst string) (err error) {
if err != nil {
return err
}
defer multierr.AppendInvoke(&err, multierr.Close(in))
defer func() { err = errors.Join(err, in.Close()) }()

sourceFileStat, err := in.Stat()
if err != nil {
Expand Down Expand Up @@ -97,19 +95,32 @@ func WriteAtomically(fileName string, perm os.FileMode, write func(file io.Write
tmpFileName := fd.Name()
close := true
defer func() {
remove := err != nil
var errs []error
if err != nil {
errs = append(errs, err)
}

if close {
err = multierr.Append(err, fd.Close())
if err := fd.Close(); err != nil {
errs = append(errs, err)
}
}
if remove {
removeErr := os.Remove(tmpFileName)

if err != nil {
err := os.Remove(tmpFileName)
// Don't propagate any fs.ErrNotExist errors. There is no point in
// doing this, since the desired state is already reached: The
// temporary file is no longer present on the file system.
if removeErr != nil && !errors.Is(err, fs.ErrNotExist) {
err = multierr.Append(err, removeErr)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
errs = append(errs, err)
}
}

if len(errs) == 1 {
err = errs[0]
} else {
err = errors.Join(errs...)
}
}()

err = write(fd)
Expand Down
21 changes: 15 additions & 6 deletions internal/pkg/file/file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/multierr"
)

func TestWriteAtomically(t *testing.T) {
Expand Down Expand Up @@ -103,7 +102,7 @@ func TestWriteAtomically(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "file")

errs := multierr.Errors(WriteAtomically(file, 0644, func(file io.Writer) error {
errs := unwrap(WriteAtomically(file, 0644, func(file io.Writer) error {
c, ok := file.(io.Closer)
require.True(t, ok, "Not closeable: %T", file)
require.NoError(t, c.Close())
Expand Down Expand Up @@ -150,7 +149,7 @@ func TestWriteAtomically(t *testing.T) {
return nil
})

assert.Len(t, multierr.Errors(err), 1)
assert.Len(t, unwrap(err), 1)

// The error should be about the failed chmod.
if err, ok := assertPathError(t, err, "chmod", dir); ok {
Expand All @@ -168,15 +167,15 @@ func TestWriteAtomically(t *testing.T) {
// Obstruct the file path, so that the rename fails.
require.NoError(t, os.Mkdir(file, 0700))

errs := multierr.Errors(WriteAtomically(file, 0644, func(file io.Writer) error {
errs := unwrap(WriteAtomically(file, 0644, func(file io.Writer) error {
_, err := file.Write([]byte("obstructed"))
return err
}))

require.Len(t, errs, 1)

var linkErr *os.LinkError
if assert.True(t, errors.As(errs[0], &linkErr), "Not a LinkError: %v", linkErr) {
if assert.True(t, errors.As(errs[0], &linkErr), "Not a LinkError: %#+v", errs[0]) {
assert.Equal(t, "rename", linkErr.Op)
assert.Equal(
t, dir, filepath.Dir(linkErr.Old),
Expand Down Expand Up @@ -214,7 +213,7 @@ func TestWriteAtomically(t *testing.T) {
require.NoError(t, os.Mkdir(file, 0700))

var tempPath string
errs := multierr.Errors(WriteAtomically(file, 0755, func(file io.Writer) error {
errs := unwrap(WriteAtomically(file, 0755, func(file io.Writer) error {
n, ok := file.(interface{ Name() string })
require.True(t, ok, "Doesn't have a name: %T", file)
tempPath = n.Name()
Expand Down Expand Up @@ -307,3 +306,13 @@ func TestExists(t *testing.T) {
}
})
}

func unwrap(err error) []error {
if err, ok := err.(interface{ Unwrap() []error }); ok {
if errs := err.Unwrap(); len(errs) > 0 {
return errs
}
}

return []error{err}
}
11 changes: 4 additions & 7 deletions internal/pkg/iptablesutils/iptables.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,13 @@ package iptablesutils

import (
"bufio"
"errors"
"fmt"
"os/exec"
"path/filepath"
"strings"

"github.com/sirupsen/logrus"
"go.uber.org/multierr"
)

const (
Expand Down Expand Up @@ -68,12 +68,12 @@ func DetectHostIPTablesMode(k0sBinPath string) (string, error) {

iptablesPath, err := exec.LookPath("iptables")
if err != nil {
return "", multierr.Combine(err, nftErr, legacyErr)
return "", errors.Join(err, nftErr, legacyErr)
}

out, err := exec.Command(iptablesPath, "--version").CombinedOutput()
if err != nil {
return "", multierr.Combine(err, nftErr, legacyErr)
return "", errors.Join(err, nftErr, legacyErr)
}

outStr := strings.TrimSpace(string(out))
Expand Down Expand Up @@ -119,10 +119,7 @@ func findMatchingEntries(k0sBinPath, mode string, entries ...string) (entriesFou

v4Err, v6Err := findMatches("iptables-save"), findMatches("ip6tables-save")
if v4Err != nil && v6Err != nil {
return false, 0, multierr.Combine(
fmt.Errorf("iptables-save: %w", v4Err),
fmt.Errorf("ip6tables-save: %w", v6Err),
)
return false, 0, fmt.Errorf("iptables-save: %w; ip6tables-save: %w", v4Err, v6Err)
}

return entriesFound, total, nil
Expand Down
5 changes: 3 additions & 2 deletions internal/pkg/iptablesutils/iptables_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ import (
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/multierr"
)

func TestDetectHostIPTablesMode(t *testing.T) {
Expand Down Expand Up @@ -173,7 +172,9 @@ func TestDetectHostIPTablesMode(t *testing.T) {
writeXtables(t, binDir, "legacy", "exit 77", "exit 66")

_, err := iptablesutils.DetectHostIPTablesMode(binDir)
errs := multierr.Errors(err)
var composite interface{ Unwrap() []error }
require.ErrorAs(t, err, &composite, "No wrapped errors")
errs := composite.Unwrap()
require.Len(t, errs, 3)
assert.ErrorIs(t, errs[0], exec.ErrNotFound)
assert.ErrorContains(t, errs[1], "99")
Expand Down
11 changes: 6 additions & 5 deletions inttest/common/airgap.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,12 @@ package common

import (
"context"
"errors"
"fmt"
"net"
"os"
"os/exec"
"strings"

"go.uber.org/multierr"
)

type Airgap struct {
Expand Down Expand Up @@ -63,13 +62,15 @@ func tryBlockIPv6() error {

err = exec.Command("modprobe", "ip6table_filter").Run()
if err != nil && os.Geteuid() != 0 {
errs := []error{err}
for _, cmd := range []string{"sudo", "doas"} {
userErr := exec.Command(cmd, "-n", "modprobe", "ip6table_filter").Run()
if userErr == nil {
err := exec.Command(cmd, "-n", "modprobe", "ip6table_filter").Run()
if err == nil {
return nil
}
err = multierr.Append(err, userErr)
errs = append(errs, err)
}
err = errors.Join(errs...)
}

return err
Expand Down
9 changes: 4 additions & 5 deletions inttest/common/bootloosesuite.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"go.uber.org/multierr"
"golang.org/x/sync/errgroup"
)

Expand Down Expand Up @@ -444,18 +443,18 @@ func (s *BootlooseSuite) dumpNodeLogs(ctx context.Context, t *testing.T, node, d

outLog, errLog := log{path: outPath}, log{path: errPath}
for _, log := range []*log{&outLog, &errLog} {
file, err := os.Create(log.path)
if err != nil {
t.Logf("Failed to create log file: %s", err.Error())
file, createErr := os.Create(log.path)
if createErr != nil {
t.Log("Failed to create log file:", createErr)
continue
}

defer multierr.AppendInvoke(&err, multierr.Close(file))
buf := bufio.NewWriter(file)
defer func() {
if err == nil {
err = buf.Flush()
}
err = errors.Join(err, file.Close())
}()
log.writer = buf
}
Expand Down
5 changes: 2 additions & 3 deletions inttest/common/launchdelegate.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,12 @@ package common

import (
"context"
"errors"
"fmt"
"io"
"runtime"
"strings"
"sync"

"go.uber.org/multierr"
)

type LaunchMode string
Expand Down Expand Up @@ -248,7 +247,7 @@ func (*openRCLaunchDelegate) ReadK0sLogs(ctx context.Context, conn *SSHConnectio

wg.Wait()

return multierr.Append(outErr, errErr)
return errors.Join(outErr, errErr)
}

// installK0sServiceOpenRC will install an OpenRC k0s-type service (controller/worker)
Expand Down
3 changes: 1 addition & 2 deletions inttest/nllb/nllb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ import (
kubeletv1beta1 "k8s.io/kubelet/config/v1beta1"

testifysuite "github.com/stretchr/testify/suite"
"go.uber.org/multierr"
"golang.org/x/sync/errgroup"
"sigs.k8s.io/yaml"
)
Expand Down Expand Up @@ -272,7 +271,7 @@ func (s *suite) checkClusterReadiness(ctx context.Context, clients *kubernetes.C
}
return true, logs.Close()
}); err != nil {
return multierr.Append(fmt.Errorf("failed to get pod logs from %s/%s", kubeSystem, nllbPodName), logsErr)
return fmt.Errorf("failed to get pod logs from %s/%s: %w", kubeSystem, nllbPodName, logsErr)
}

s.T().Logf("Got some pod logs from %s/%s", kubeSystem, nllbPodName)
Expand Down
8 changes: 4 additions & 4 deletions pkg/component/controller/clusterConfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package controller

import (
"context"
"errors"
"fmt"
"os"
"time"
Expand All @@ -32,12 +33,11 @@ import (
kubeutil "github.com/k0sproject/k0s/pkg/kubernetes"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"

"github.com/sirupsen/logrus"
"go.uber.org/multierr"
)

// ClusterConfigReconciler reconciles a ClusterConfig object
Expand Down Expand Up @@ -89,7 +89,7 @@ func (r *ClusterConfigReconciler) Start(ctx context.Context) error {
r.log.Debug("Cluster configuration created")
return true, nil
}
if errors.IsAlreadyExists(err) {
if apierrors.IsAlreadyExists(err) {
// An already existing configuration is just fine.
r.log.Debug("Cluster configuration already exists")
return true, nil
Expand Down Expand Up @@ -121,7 +121,7 @@ func (r *ClusterConfigReconciler) Start(ctx context.Context) error {
r.log.Debug("config source closed channel")
return
}
err := multierr.Combine(cfg.Validate()...)
err := errors.Join(cfg.Validate()...)
if err != nil {
err = fmt.Errorf("failed to validate cluster configuration: %w", err)
} else {
Expand Down
Loading

0 comments on commit a3bc75d

Please sign in to comment.