pkg: switch to golang native error wrapping

We now use the golang error wrapping format specifier `%w` instead of
the deprecated github.com/pkg/errors package.

[NO NEW TESTS NEEDED]

Signed-off-by: Sascha Grunert <sgrunert@redhat.com>
This commit is contained in:
Sascha Grunert
2022-07-06 09:48:36 +02:00
parent 862cc42ddc
commit a46f798831
130 changed files with 879 additions and 875 deletions

1
go.mod
View File

@ -51,7 +51,6 @@ require (
github.com/opencontainers/runtime-spec v1.0.3-0.20211214071223-8958f93039ab
github.com/opencontainers/runtime-tools v0.9.1-0.20220110225228-7e2d60f1e41f
github.com/opencontainers/selinux v1.10.1
github.com/pkg/errors v0.9.1
github.com/pmezard/go-difflib v1.0.0
github.com/rootless-containers/rootlesskit v1.0.1
github.com/sirupsen/logrus v1.8.1

View File

@ -3,6 +3,7 @@ package compat
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
@ -14,7 +15,6 @@ import (
api "github.com/containers/podman/v4/pkg/api/types"
"github.com/containers/podman/v4/pkg/domain/entities"
docker "github.com/docker/docker/api/types"
"github.com/pkg/errors"
)
func stripAddressOfScheme(address string) string {
@ -28,7 +28,7 @@ func Auth(w http.ResponseWriter, r *http.Request) {
var authConfig docker.AuthConfig
err := json.NewDecoder(r.Body).Decode(&authConfig)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to parse request"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to parse request: %w", err))
return
}

View File

@ -1,6 +1,7 @@
package compat
import (
"fmt"
"net/http"
"github.com/containers/podman/v4/libpod"
@ -8,7 +9,6 @@ import (
"github.com/containers/podman/v4/pkg/api/handlers/utils"
api "github.com/containers/podman/v4/pkg/api/types"
"github.com/gorilla/schema"
"github.com/pkg/errors"
)
func Changes(w http.ResponseWriter, r *http.Request) {
@ -20,7 +20,7 @@ func Changes(w http.ResponseWriter, r *http.Request) {
DiffType string `schema:"diffType"`
}{}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
var diffType define.DiffType
@ -32,7 +32,7 @@ func Changes(w http.ResponseWriter, r *http.Request) {
case "image":
diffType = define.DiffImage
default:
utils.Error(w, http.StatusBadRequest, errors.Errorf("invalid diffType value %q", query.DiffType))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("invalid diffType value %q", query.DiffType))
return
}

View File

@ -1,6 +1,8 @@
package compat
import (
"errors"
"fmt"
"net/http"
"github.com/containers/podman/v4/libpod"
@ -9,7 +11,6 @@ import (
"github.com/containers/podman/v4/pkg/api/server/idle"
api "github.com/containers/podman/v4/pkg/api/types"
"github.com/gorilla/schema"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -60,13 +61,13 @@ func AttachContainer(w http.ResponseWriter, r *http.Request) {
streams = nil
}
if useStreams && !streams.Stdout && !streams.Stderr && !streams.Stdin {
utils.Error(w, http.StatusBadRequest, errors.Errorf("at least one of stdin, stdout, stderr must be true"))
utils.Error(w, http.StatusBadRequest, errors.New("at least one of stdin, stdout, stderr must be true"))
return
}
// At least one of these must be set
if !query.Stream && !query.Logs {
utils.Error(w, http.StatusBadRequest, errors.Errorf("at least one of Logs or Stream must be set"))
utils.Error(w, http.StatusBadRequest, errors.New("at least one of Logs or Stream must be set"))
return
}
@ -85,16 +86,16 @@ func AttachContainer(w http.ResponseWriter, r *http.Request) {
// For Docker compatibility, we need to re-initialize containers in these states.
if state == define.ContainerStateConfigured || state == define.ContainerStateExited || state == define.ContainerStateStopped {
if err := ctr.Init(r.Context(), ctr.PodID() != ""); err != nil {
utils.Error(w, http.StatusConflict, errors.Wrapf(err, "error preparing container %s for attach", ctr.ID()))
utils.Error(w, http.StatusConflict, fmt.Errorf("error preparing container %s for attach: %w", ctr.ID(), err))
return
}
} else if !(state == define.ContainerStateCreated || state == define.ContainerStateRunning) {
utils.InternalServerError(w, errors.Wrapf(define.ErrCtrStateInvalid, "can only attach to created or running containers - currently in state %s", state.String()))
utils.InternalServerError(w, fmt.Errorf("can only attach to created or running containers - currently in state %s: %w", state.String(), define.ErrCtrStateInvalid))
return
}
logErr := func(e error) {
logrus.Error(errors.Wrapf(e, "error attaching to container %s", ctr.ID()))
logrus.Errorf("Error attaching to container %s: %v", ctr.ID(), e)
}
// Perform HTTP attach.

View File

@ -1,6 +1,7 @@
package compat
import (
"fmt"
"io/ioutil"
"net/http"
"os"
@ -8,7 +9,6 @@ import (
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/pkg/api/handlers/utils"
api "github.com/containers/podman/v4/pkg/api/types"
"github.com/pkg/errors"
)
func ExportContainer(w http.ResponseWriter, r *http.Request) {
@ -21,21 +21,21 @@ func ExportContainer(w http.ResponseWriter, r *http.Request) {
}
tmpfile, err := ioutil.TempFile("", "api.tar")
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "unable to create tempfile"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("unable to create tempfile: %w", err))
return
}
defer os.Remove(tmpfile.Name())
if err := tmpfile.Close(); err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "unable to close tempfile"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("unable to close tempfile: %w", err))
return
}
if err := con.Export(tmpfile.Name()); err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "failed to save image"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to save image: %w", err))
return
}
rdr, err := os.Open(tmpfile.Name())
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "failed to read the exported tarfile"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to read the exported tarfile: %w", err))
return
}
defer rdr.Close()

View File

@ -16,7 +16,6 @@ import (
api "github.com/containers/podman/v4/pkg/api/types"
"github.com/containers/podman/v4/pkg/util"
"github.com/gorilla/schema"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
@ -36,13 +35,13 @@ func LogsFromContainer(w http.ResponseWriter, r *http.Request) {
Tail: "all",
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
if !(query.Stdout || query.Stderr) {
msg := fmt.Sprintf("%s: you must choose at least one stream", http.StatusText(http.StatusBadRequest))
utils.Error(w, http.StatusBadRequest, errors.Errorf("%s for %s", msg, r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("%s for %s", msg, r.URL.String()))
return
}
@ -96,7 +95,7 @@ func LogsFromContainer(w http.ResponseWriter, r *http.Request) {
logChannel := make(chan *logs.LogLine, tail+1)
if err := runtime.Log(r.Context(), []*libpod.Container{ctnr}, options, logChannel); err != nil {
utils.InternalServerError(w, errors.Wrapf(err, "failed to obtain logs for Container '%s'", name))
utils.InternalServerError(w, fmt.Errorf("failed to obtain logs for Container '%s': %w", name, err))
return
}
go func() {
@ -114,7 +113,7 @@ func LogsFromContainer(w http.ResponseWriter, r *http.Request) {
if !utils.IsLibpodRequest(r) {
inspectData, err := ctnr.Inspect(false)
if err != nil {
utils.InternalServerError(w, errors.Wrapf(err, "failed to obtain logs for Container '%s'", name))
utils.InternalServerError(w, fmt.Errorf("failed to obtain logs for Container '%s': %w", name, err))
return
}
writeHeader = !inspectData.Config.Tty

View File

@ -2,6 +2,8 @@ package compat
import (
"bytes"
"errors"
"fmt"
"net/http"
"github.com/containers/podman/v4/libpod"
@ -11,14 +13,13 @@ import (
"github.com/containers/podman/v4/pkg/domain/entities/reports"
"github.com/containers/podman/v4/pkg/domain/filters"
"github.com/containers/podman/v4/pkg/util"
"github.com/pkg/errors"
)
func PruneContainers(w http.ResponseWriter, r *http.Request) {
runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
filtersMap, err := util.PrepareFilters(r)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}

View File

@ -2,6 +2,7 @@ package compat
import (
"encoding/json"
"fmt"
"net/http"
"time"
@ -13,7 +14,6 @@ import (
docker "github.com/docker/docker/api/types"
"github.com/gorilla/schema"
runccgroups "github.com/opencontainers/runc/libcontainer/cgroups"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -30,7 +30,7 @@ func StatsContainer(w http.ResponseWriter, r *http.Request) {
Stream: true,
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
if query.Stream && query.OneShot { // mismatch. one-shot can only be passed with stream=false
@ -47,7 +47,7 @@ func StatsContainer(w http.ResponseWriter, r *http.Request) {
stats, err := ctnr.GetContainerStats(nil)
if err != nil {
utils.InternalServerError(w, errors.Wrapf(err, "failed to obtain Container %s stats", name))
utils.InternalServerError(w, fmt.Errorf("failed to obtain Container %s stats: %w", name, err))
return
}

View File

@ -12,7 +12,6 @@ import (
"github.com/containers/podman/v4/pkg/api/handlers/utils"
api "github.com/containers/podman/v4/pkg/api/types"
"github.com/gorilla/schema"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -33,7 +32,7 @@ func TopContainer(w http.ResponseWriter, r *http.Request) {
PsArgs: psArgs,
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}

View File

@ -1,6 +1,7 @@
package compat
import (
"fmt"
"net/http"
"github.com/containers/podman/v4/libpod"
@ -11,7 +12,6 @@ import (
"github.com/containers/podman/v4/pkg/util"
"github.com/gorilla/schema"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -34,7 +34,7 @@ func GetEvents(w http.ResponseWriter, r *http.Request) {
Stream: true,
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
@ -44,7 +44,7 @@ func GetEvents(w http.ResponseWriter, r *http.Request) {
libpodFilters, err := util.FiltersFromRequest(r)
if err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
eventChannel := make(chan *events.Event)

View File

@ -3,6 +3,7 @@ package compat
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -27,7 +28,6 @@ import (
"github.com/docker/docker/pkg/jsonmessage"
"github.com/gorilla/schema"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -65,7 +65,7 @@ func BuildImage(w http.ResponseWriter, r *http.Request) {
}
err := os.RemoveAll(filepath.Dir(contextDirectory))
if err != nil {
logrus.Warn(errors.Wrapf(err, "failed to remove build scratch directory %q", filepath.Dir(contextDirectory)))
logrus.Warn(fmt.Errorf("failed to remove build scratch directory %q: %w", filepath.Dir(contextDirectory), err))
}
}()
@ -338,7 +338,7 @@ func BuildImage(w http.ResponseWriter, r *http.Request) {
if len(tags) > 0 {
possiblyNormalizedName, err := utils.NormalizeToDockerHub(r, tags[0])
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error normalizing image"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error normalizing image: %w", err))
return
}
output = possiblyNormalizedName
@ -350,7 +350,7 @@ func BuildImage(w http.ResponseWriter, r *http.Request) {
var err error
isolation, err = parseLibPodIsolation(query.Isolation)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "failed to parse isolation"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to parse isolation: %w", err))
return
}
@ -371,7 +371,7 @@ func BuildImage(w http.ResponseWriter, r *http.Request) {
for i := 1; i < len(tags); i++ {
possiblyNormalizedTag, err := utils.NormalizeToDockerHub(r, tags[i])
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error normalizing image"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error normalizing image: %w", err))
return
}
additionalTags = append(additionalTags, possiblyNormalizedTag)
@ -487,7 +487,7 @@ func BuildImage(w http.ResponseWriter, r *http.Request) {
}
con := strings.SplitN(opt, "=", 2)
if len(con) != 2 {
utils.BadRequest(w, "securityopt", query.SecurityOpt, errors.Errorf("Invalid --security-opt name=value pair: %q", opt))
utils.BadRequest(w, "securityopt", query.SecurityOpt, fmt.Errorf("invalid --security-opt name=value pair: %q", opt))
return
}
@ -499,7 +499,7 @@ func BuildImage(w http.ResponseWriter, r *http.Request) {
case "seccomp":
seccomp = con[1]
default:
utils.BadRequest(w, "securityopt", query.SecurityOpt, errors.Errorf("Invalid --security-opt 2: %q", opt))
utils.BadRequest(w, "securityopt", query.SecurityOpt, fmt.Errorf("invalid --security-opt 2: %q", opt))
return
}
}
@ -540,7 +540,7 @@ func BuildImage(w http.ResponseWriter, r *http.Request) {
if fromImage != "" {
possiblyNormalizedName, err := utils.NormalizeToDockerHub(r, fromImage)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error normalizing image"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error normalizing image: %w", err))
return
}
fromImage = possiblyNormalizedName

View File

@ -1,13 +1,13 @@
package compat
import (
"fmt"
"net/http"
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/pkg/api/handlers"
"github.com/containers/podman/v4/pkg/api/handlers/utils"
api "github.com/containers/podman/v4/pkg/api/types"
"github.com/pkg/errors"
)
func HistoryImage(w http.ResponseWriter, r *http.Request) {
@ -16,13 +16,13 @@ func HistoryImage(w http.ResponseWriter, r *http.Request) {
possiblyNormalizedName, err := utils.NormalizeToDockerHub(r, name)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error normalizing image"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error normalizing image: %w", err))
return
}
newImage, _, err := runtime.LibimageRuntime().LookupImage(possiblyNormalizedName, nil)
if err != nil {
utils.ImageNotFound(w, possiblyNormalizedName, errors.Wrapf(err, "failed to find image %s", possiblyNormalizedName))
utils.ImageNotFound(w, possiblyNormalizedName, fmt.Errorf("failed to find image %s: %w", possiblyNormalizedName, err))
return
}
history, err := newImage.History(r.Context())

View File

@ -2,6 +2,7 @@ package compat
import (
"bytes"
"errors"
"fmt"
"net/http"
@ -13,7 +14,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/infra/abi"
"github.com/containers/podman/v4/pkg/util"
"github.com/docker/docker/api/types"
"github.com/pkg/errors"
)
func PruneImages(w http.ResponseWriter, r *http.Request) {
@ -22,7 +22,7 @@ func PruneImages(w http.ResponseWriter, r *http.Request) {
filterMap, err := util.PrepareFilters(r)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}

View File

@ -2,6 +2,7 @@ package compat
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
@ -17,7 +18,6 @@ import (
"github.com/containers/storage"
"github.com/docker/docker/pkg/jsonmessage"
"github.com/gorilla/schema"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -28,7 +28,7 @@ func PushImage(w http.ResponseWriter, r *http.Request) {
digestFile, err := ioutil.TempFile("", "digest.txt")
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "unable to create tempfile"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("unable to create tempfile: %w", err))
return
}
defer digestFile.Close()
@ -50,7 +50,7 @@ func PushImage(w http.ResponseWriter, r *http.Request) {
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
@ -63,19 +63,19 @@ func PushImage(w http.ResponseWriter, r *http.Request) {
}
if _, err := utils.ParseStorageReference(imageName); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "image source %q is not a containers-storage-transport reference", imageName))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("image source %q is not a containers-storage-transport reference: %w", imageName, err))
return
}
possiblyNormalizedName, err := utils.NormalizeToDockerHub(r, imageName)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error normalizing image"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error normalizing image: %w", err))
return
}
imageName = possiblyNormalizedName
localImage, _, err := runtime.LibimageRuntime().LookupImage(possiblyNormalizedName, nil)
if err != nil {
utils.ImageNotFound(w, imageName, errors.Wrapf(err, "failed to find image %s", imageName))
utils.ImageNotFound(w, imageName, fmt.Errorf("failed to find image %s: %w", imageName, err))
return
}
rawManifest, _, err := localImage.Manifest(r.Context())

View File

@ -13,7 +13,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/infra/abi"
"github.com/containers/storage"
"github.com/gorilla/schema"
"github.com/pkg/errors"
)
func SearchImages(w http.ResponseWriter, r *http.Request) {
@ -30,7 +29,7 @@ func SearchImages(w http.ResponseWriter, r *http.Request) {
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}

View File

@ -1,6 +1,7 @@
package compat
import (
"errors"
"fmt"
"net/http"
@ -8,7 +9,6 @@ import (
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/pkg/api/handlers/utils"
api "github.com/containers/podman/v4/pkg/api/types"
"github.com/pkg/errors"
)
func TagImage(w http.ResponseWriter, r *http.Request) {
@ -17,7 +17,7 @@ func TagImage(w http.ResponseWriter, r *http.Request) {
name := utils.GetName(r)
possiblyNormalizedName, err := utils.NormalizeToDockerHub(r, name)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error normalizing image"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error normalizing image: %w", err))
return
}
@ -25,7 +25,7 @@ func TagImage(w http.ResponseWriter, r *http.Request) {
lookupOptions := &libimage.LookupImageOptions{ManifestList: true}
newImage, _, err := runtime.LibimageRuntime().LookupImage(possiblyNormalizedName, lookupOptions)
if err != nil {
utils.ImageNotFound(w, name, errors.Wrapf(err, "failed to find image %s", name))
utils.ImageNotFound(w, name, fmt.Errorf("failed to find image %s: %w", name, err))
return
}
@ -42,7 +42,7 @@ func TagImage(w http.ResponseWriter, r *http.Request) {
possiblyNormalizedTag, err := utils.NormalizeToDockerHub(r, tagName)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error normalizing image"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error normalizing image: %w", err))
return
}

View File

@ -22,7 +22,6 @@ import (
"github.com/docker/docker/api/types/registry"
"github.com/docker/docker/api/types/swarm"
"github.com/google/uuid"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
@ -33,18 +32,18 @@ func GetInfo(w http.ResponseWriter, r *http.Request) {
infoData, err := runtime.Info()
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to obtain system memory info"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to obtain system memory info: %w", err))
return
}
configInfo, err := runtime.GetConfig()
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to obtain runtime config"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to obtain runtime config: %w", err))
return
}
versionInfo, err := define.GetVersion()
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to obtain podman versions"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to obtain podman versions: %w", err))
return
}
stateInfo := getContainersState(runtime)

View File

@ -13,7 +13,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/domain/entities/types"
"github.com/containers/podman/v4/version"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -28,7 +27,7 @@ func VersionHandler(w http.ResponseWriter, r *http.Request) {
info, err := runtime.Info()
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrapf(err, "failed to obtain system memory info"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to obtain system memory info: %w", err))
return
}

View File

@ -3,6 +3,7 @@ package libpod
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
@ -13,7 +14,6 @@ import (
"github.com/containers/podman/v4/pkg/specgen"
"github.com/containers/podman/v4/pkg/specgen/generate"
"github.com/containers/podman/v4/pkg/specgenutil"
"github.com/pkg/errors"
)
// CreateContainer takes a specgenerator and makes a container. It returns
@ -34,7 +34,7 @@ func CreateContainer(w http.ResponseWriter, r *http.Request) {
}
if err := json.NewDecoder(r.Body).Decode(&sg); err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "Decode()"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("decode(): %w", err))
return
}
if sg.Passwd == nil {

View File

@ -2,6 +2,8 @@ package libpod
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/containers/common/pkg/cgroups"
@ -12,7 +14,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/infra/abi"
"github.com/containers/podman/v4/pkg/rootless"
"github.com/gorilla/schema"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -24,8 +25,7 @@ func StatsContainer(w http.ResponseWriter, r *http.Request) {
if rootless.IsRootless() {
// if so, then verify cgroup v2 available (more expensive check)
if isV2, _ := cgroups.IsCgroup2UnifiedMode(); !isV2 {
msg := "Container stats resource only available for cgroup v2"
utils.Error(w, http.StatusConflict, errors.New(msg))
utils.Error(w, http.StatusConflict, errors.New("container stats resource only available for cgroup v2"))
return
}
}
@ -39,7 +39,7 @@ func StatsContainer(w http.ResponseWriter, r *http.Request) {
Interval: 5,
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}

View File

@ -1,6 +1,7 @@
package libpod
import (
"fmt"
"net/http"
"github.com/containers/podman/v4/libpod"
@ -10,7 +11,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/infra/abi"
"github.com/containers/podman/v4/pkg/util"
"github.com/gorilla/schema"
"github.com/pkg/errors"
)
func GenerateSystemd(w http.ResponseWriter, r *http.Request) {
@ -37,7 +37,7 @@ func GenerateSystemd(w http.ResponseWriter, r *http.Request) {
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
@ -76,7 +76,7 @@ func GenerateSystemd(w http.ResponseWriter, r *http.Request) {
report, err := containerEngine.GenerateSystemd(r.Context(), utils.GetName(r), options)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error generating systemd units"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error generating systemd units: %w", err))
return
}
@ -94,7 +94,7 @@ func GenerateKube(w http.ResponseWriter, r *http.Request) {
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
@ -102,7 +102,7 @@ func GenerateKube(w http.ResponseWriter, r *http.Request) {
options := entities.GenerateKubeOptions{Service: query.Service}
report, err := containerEngine.GenerateKube(r.Context(), query.Names, options)
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error generating YAML"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error generating YAML: %w", err))
return
}

View File

@ -3,6 +3,8 @@ package libpod
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/containers/common/libimage"
@ -15,7 +17,6 @@ import (
"github.com/containers/podman/v4/pkg/channel"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/gorilla/schema"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -41,7 +42,7 @@ func ImagesPull(w http.ResponseWriter, r *http.Request) {
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}

View File

@ -3,6 +3,7 @@ package libpod
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
@ -24,7 +25,6 @@ import (
"github.com/gorilla/mux"
"github.com/gorilla/schema"
"github.com/opencontainers/go-digest"
"github.com/pkg/errors"
)
func ManifestCreate(w http.ResponseWriter, r *http.Request) {
@ -45,7 +45,7 @@ func ManifestCreate(w http.ResponseWriter, r *http.Request) {
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest,
errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
@ -54,7 +54,7 @@ func ManifestCreate(w http.ResponseWriter, r *http.Request) {
n, err := url.QueryUnescape(name)
if err != nil {
utils.Error(w, http.StatusBadRequest,
errors.Wrapf(err, "failed to parse name parameter %q", name))
fmt.Errorf("failed to parse name parameter %q: %w", name, err))
return
}
query.Name = n
@ -62,7 +62,7 @@ func ManifestCreate(w http.ResponseWriter, r *http.Request) {
if _, err := reference.ParseNormalizedNamed(query.Name); err != nil {
utils.Error(w, http.StatusBadRequest,
errors.Wrapf(err, "invalid image name %s", query.Name))
fmt.Errorf("invalid image name %s: %w", query.Name, err))
return
}
@ -94,7 +94,7 @@ func ManifestCreate(w http.ResponseWriter, r *http.Request) {
body := new(entities.ManifestModifyOptions)
if err := json.Unmarshal(buffer, body); err != nil {
utils.InternalServerError(w, errors.Wrap(err, "Decode()"))
utils.InternalServerError(w, fmt.Errorf("Decode(): %w", err))
return
}
@ -166,7 +166,7 @@ func ManifestAddV3(w http.ResponseWriter, r *http.Request) {
TLSVerify bool `schema:"tlsVerify"`
}{}
if err := json.NewDecoder(r.Body).Decode(&query); err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "Decode()"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("Decode(): %w", err))
return
}
@ -220,7 +220,7 @@ func ManifestRemoveDigestV3(w http.ResponseWriter, r *http.Request) {
name := utils.GetName(r)
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest,
errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
manifestList, err := runtime.LibimageRuntime().LookupManifestList(name)
@ -256,7 +256,7 @@ func ManifestPushV3(w http.ResponseWriter, r *http.Request) {
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest,
errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
if err := utils.IsRegistryReference(query.Destination); err != nil {
@ -292,7 +292,7 @@ func ManifestPushV3(w http.ResponseWriter, r *http.Request) {
imageEngine := abi.ImageEngine{Libpod: runtime}
digest, err := imageEngine.ManifestPush(context.Background(), source, query.Destination, options)
if err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "error pushing image %q", query.Destination))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("error pushing image %q: %w", query.Destination, err))
return
}
utils.WriteResponse(w, http.StatusOK, entities.IDResponse{ID: digest})
@ -313,7 +313,7 @@ func ManifestPush(w http.ResponseWriter, r *http.Request) {
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest,
errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
@ -325,7 +325,7 @@ func ManifestPush(w http.ResponseWriter, r *http.Request) {
authconf, authfile, err := auth.GetCredentials(r)
if err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse registry header for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse registry header for %s: %w", r.URL.String(), err))
return
}
defer auth.RemoveAuthfile(authfile)
@ -351,7 +351,7 @@ func ManifestPush(w http.ResponseWriter, r *http.Request) {
source := utils.GetName(r)
digest, err := imageEngine.ManifestPush(context.Background(), source, destination, options)
if err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "error pushing image %q", destination))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("error pushing image %q: %w", destination, err))
return
}
utils.WriteResponse(w, http.StatusOK, entities.IDResponse{ID: digest})
@ -364,7 +364,7 @@ func ManifestModify(w http.ResponseWriter, r *http.Request) {
body := new(entities.ManifestModifyOptions)
if err := json.NewDecoder(r.Body).Decode(body); err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "Decode()"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("Decode(): %w", err))
return
}

View File

@ -1,6 +1,7 @@
package libpod
import (
"fmt"
"net"
"net/http"
@ -12,7 +13,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/domain/infra/abi"
"github.com/gorilla/schema"
"github.com/pkg/errors"
)
func PlayKube(w http.ResponseWriter, r *http.Request) {
@ -34,7 +34,7 @@ func PlayKube(w http.ResponseWriter, r *http.Request) {
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
@ -42,7 +42,7 @@ func PlayKube(w http.ResponseWriter, r *http.Request) {
for _, ipString := range query.StaticIPs {
ip := net.ParseIP(ipString)
if ip == nil {
utils.Error(w, http.StatusBadRequest, errors.Errorf("Invalid IP address %s", ipString))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("invalid IP address %s", ipString))
return
}
staticIPs = append(staticIPs, ip)
@ -103,7 +103,7 @@ func PlayKube(w http.ResponseWriter, r *http.Request) {
report, err := containerEngine.PlayKube(r.Context(), r.Body, options)
_ = r.Body.Close()
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error playing YAML file"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error playing YAML file: %w", err))
return
}
utils.WriteResponse(w, http.StatusOK, report)
@ -116,7 +116,7 @@ func PlayKubeDown(w http.ResponseWriter, r *http.Request) {
report, err := containerEngine.PlayKubeDown(r.Context(), r.Body, *options)
_ = r.Body.Close()
if err != nil {
utils.Error(w, http.StatusInternalServerError, errors.Wrap(err, "error tearing down YAML file"))
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("error tearing down YAML file: %w", err))
return
}
utils.WriteResponse(w, http.StatusOK, report)

View File

@ -1,6 +1,7 @@
package libpod
import (
"fmt"
"net/http"
"github.com/containers/podman/v4/libpod"
@ -9,7 +10,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/domain/infra/abi"
"github.com/gorilla/schema"
"github.com/pkg/errors"
)
func CreateSecret(w http.ResponseWriter, r *http.Request) {
@ -27,7 +27,7 @@ func CreateSecret(w http.ResponseWriter, r *http.Request) {
}
opts := entities.SecretCreateOptions{}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}

View File

@ -1,11 +1,12 @@
package libpod
import (
"errors"
"fmt"
"net/http"
"os"
"github.com/containers/podman/v4/pkg/api/handlers/utils"
"github.com/pkg/errors"
)
// DefaultPodmanSwaggerSpec provides the default path to the podman swagger spec file
@ -18,7 +19,7 @@ func ServeSwagger(w http.ResponseWriter, r *http.Request) {
}
if _, err := os.Stat(path); err != nil {
if errors.Is(err, os.ErrNotExist) {
utils.InternalServerError(w, errors.Errorf("swagger spec %q does not exist", path))
utils.InternalServerError(w, fmt.Errorf("swagger spec %q does not exist", path))
return
}
utils.InternalServerError(w, err)

View File

@ -1,6 +1,7 @@
package libpod
import (
"fmt"
"net/http"
"github.com/containers/podman/v4/libpod"
@ -10,7 +11,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/infra/abi"
"github.com/containers/podman/v4/pkg/util"
"github.com/gorilla/schema"
"github.com/pkg/errors"
)
// SystemPrune removes unused data
@ -25,13 +25,13 @@ func SystemPrune(w http.ResponseWriter, r *http.Request) {
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest,
errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
filterMap, err := util.PrepareFilters(r)
if err != nil {
utils.Error(w, http.StatusBadRequest,
errors.Wrapf(err, "failed to parse parameters for %s", r.URL.String()))
fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}

View File

@ -2,6 +2,7 @@ package handlers
import (
"context"
"fmt"
"time"
"github.com/containers/common/libimage"
@ -10,7 +11,6 @@ import (
dockerContainer "github.com/docker/docker/api/types/container"
dockerNetwork "github.com/docker/docker/api/types/network"
"github.com/docker/go-connections/nat"
"github.com/pkg/errors"
)
type AuthConfig struct {
@ -237,17 +237,17 @@ func portsToPortSet(input map[string]struct{}) (nat.PortSet, error) {
case "tcp", "":
p, err := nat.NewPort("tcp", port)
if err != nil {
return nil, errors.Wrapf(err, "unable to create tcp port from %s", k)
return nil, fmt.Errorf("unable to create tcp port from %s: %w", k, err)
}
ports[p] = struct{}{}
case "udp":
p, err := nat.NewPort("udp", port)
if err != nil {
return nil, errors.Wrapf(err, "unable to create tcp port from %s", k)
return nil, fmt.Errorf("unable to create tcp port from %s: %w", k, err)
}
ports[p] = struct{}{}
default:
return nil, errors.Errorf("invalid port proto %q in %q", proto, k)
return nil, fmt.Errorf("invalid port proto %q in %q", proto, k)
}
}
return ports, nil

View File

@ -1,6 +1,7 @@
package utils
import (
"errors"
"fmt"
"io"
"net/http"
@ -13,7 +14,6 @@ import (
"github.com/containers/podman/v4/version"
"github.com/gorilla/mux"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -42,11 +42,11 @@ func SupportedVersion(r *http.Request, condition string) (semver.Version, error)
}
safeVal, err := url.PathUnescape(val)
if err != nil {
return version, errors.Wrapf(err, "unable to unescape given API version: %q", val)
return version, fmt.Errorf("unable to unescape given API version: %q: %w", val, err)
}
version, err = semver.ParseTolerant(safeVal)
if err != nil {
return version, errors.Wrapf(err, "unable to parse given API version: %q from %q", safeVal, val)
return version, fmt.Errorf("unable to parse given API version: %q from %q: %w", safeVal, val, err)
}
inRange, err := semver.ParseRange(condition)
@ -178,7 +178,7 @@ func GetVar(r *http.Request, k string) string {
val := mux.Vars(r)[k]
safeVal, err := url.PathUnescape(val)
if err != nil {
logrus.Error(errors.Wrapf(err, "failed to unescape mux key %s, value %s", k, val))
logrus.Error(fmt.Errorf("failed to unescape mux key %s, value %s: %w", k, val, err))
return val
}
return safeVal

View File

@ -1,11 +1,10 @@
package server
import (
"fmt"
"net"
"os"
"path/filepath"
"github.com/pkg/errors"
)
// ListenUnix follows stdlib net.Listen() API, providing a unix listener for given path
@ -14,18 +13,18 @@ func ListenUnix(network string, path string) (net.Listener, error) {
// set up custom listener for API server
err := os.MkdirAll(filepath.Dir(path), 0770)
if err != nil {
return nil, errors.Wrapf(err, "api.ListenUnix() failed to create %s", filepath.Dir(path))
return nil, fmt.Errorf("api.ListenUnix() failed to create %s: %w", filepath.Dir(path), err)
}
os.Remove(path)
listener, err := net.Listen(network, path)
if err != nil {
return nil, errors.Wrapf(err, "api.ListenUnix() failed to create net.Listen(%s, %s)", network, path)
return nil, fmt.Errorf("api.ListenUnix() failed to create net.Listen(%s, %s): %w", network, path, err)
}
_, err = os.Stat(path)
if err != nil {
return nil, errors.Wrapf(err, "net.Listen(%s, %s) failed to report the failure to create socket", network, path)
return nil, fmt.Errorf("net.Listen(%s, %s) failed to report the failure to create socket: %w", network, path, err)
}
return listener, nil

View File

@ -3,6 +3,7 @@ package auth
import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
@ -11,7 +12,6 @@ import (
imageAuth "github.com/containers/image/v5/pkg/docker/config"
"github.com/containers/image/v5/types"
dockerAPITypes "github.com/docker/docker/api/types"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -47,7 +47,7 @@ func GetCredentials(r *http.Request) (*types.DockerAuthConfig, string, error) {
return nil, "", nil
}
if err != nil {
return nil, "", errors.Wrapf(err, "failed to parse %q header for %s", headerName, r.URL.String())
return nil, "", fmt.Errorf("failed to parse %q header for %s: %w", headerName, r.URL.String(), err)
}
var authFile string
@ -56,7 +56,7 @@ func GetCredentials(r *http.Request) (*types.DockerAuthConfig, string, error) {
} else {
authFile, err = authConfigsToAuthFile(fileContents)
if err != nil {
return nil, "", errors.Wrapf(err, "failed to parse %q header for %s", headerName, r.URL.String())
return nil, "", fmt.Errorf("failed to parse %q header for %s: %w", headerName, r.URL.String(), err)
}
}
return override, authFile, nil
@ -72,13 +72,13 @@ func getConfigCredentials(r *http.Request, headers []string) (*types.DockerAuthC
for _, h := range headers {
param, err := base64.URLEncoding.DecodeString(h)
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to decode %q", xRegistryConfigHeader)
return nil, nil, fmt.Errorf("failed to decode %q: %w", xRegistryConfigHeader, err)
}
ac := make(map[string]dockerAPITypes.AuthConfig)
err = json.Unmarshal(param, &ac)
if err != nil {
return nil, nil, errors.Wrapf(err, "failed to unmarshal %q", xRegistryConfigHeader)
return nil, nil, fmt.Errorf("failed to unmarshal %q: %w", xRegistryConfigHeader, err)
}
for k, v := range ac {
@ -238,10 +238,10 @@ func authConfigsToAuthFile(authConfigs map[string]types.DockerAuthConfig) (strin
return "", err
}
if _, err := tmpFile.Write([]byte{'{', '}'}); err != nil {
return "", errors.Wrap(err, "error initializing temporary auth file")
return "", fmt.Errorf("error initializing temporary auth file: %w", err)
}
if err := tmpFile.Close(); err != nil {
return "", errors.Wrap(err, "error closing temporary auth file")
return "", fmt.Errorf("error closing temporary auth file: %w", err)
}
authFilePath := tmpFile.Name()
@ -255,7 +255,7 @@ func authConfigsToAuthFile(authConfigs map[string]types.DockerAuthConfig) (strin
// that all credentials are valid. They'll be used on demand
// later.
if err := imageAuth.SetAuthentication(&sys, key, config.Username, config.Password); err != nil {
return "", errors.Wrapf(err, "error storing credentials in temporary auth file (key: %q / %q, user: %q)", authFileKey, key, config.Username)
return "", fmt.Errorf("error storing credentials in temporary auth file (key: %q / %q, user: %q): %w", authFileKey, key, config.Username, err)
}
}

View File

@ -2,6 +2,7 @@ package autoupdate
import (
"context"
"fmt"
"os"
"sort"
@ -17,7 +18,6 @@ import (
"github.com/containers/podman/v4/pkg/systemd"
systemdDefine "github.com/containers/podman/v4/pkg/systemd/define"
"github.com/coreos/go-systemd/v22/dbus"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -73,7 +73,7 @@ func LookupPolicy(s string) (Policy, error) {
}
sort.Strings(keys)
return "", errors.Errorf("invalid auto-update policy %q: valid policies are %+q", s, keys)
return "", fmt.Errorf("invalid auto-update policy %q: valid policies are %+q", s, keys)
}
// ValidateImageReference checks if the specified imageName is a fully-qualified
@ -85,17 +85,17 @@ func ValidateImageReference(imageName string) error {
// Make sure the input image is a docker.
imageRef, err := alltransports.ParseImageName(imageName)
if err == nil && imageRef.Transport().Name() != docker.Transport.Name() {
return errors.Errorf("auto updates require the docker image transport but image is of transport %q", imageRef.Transport().Name())
return fmt.Errorf("auto updates require the docker image transport but image is of transport %q", imageRef.Transport().Name())
} else if err != nil {
repo, err := reference.Parse(imageName)
if err != nil {
return errors.Wrap(err, "enforcing fully-qualified docker transport reference for auto updates")
return fmt.Errorf("enforcing fully-qualified docker transport reference for auto updates: %w", err)
}
if _, ok := repo.(reference.NamedTagged); !ok {
return errors.Errorf("auto updates require fully-qualified image references (no tag): %q", imageName)
return fmt.Errorf("auto updates require fully-qualified image references (no tag): %q", imageName)
}
if _, ok := repo.(reference.Digested); ok {
return errors.Errorf("auto updates require fully-qualified image references without digest: %q", imageName)
return fmt.Errorf("auto updates require fully-qualified image references without digest: %q", imageName)
}
}
return nil
@ -151,7 +151,7 @@ func AutoUpdate(ctx context.Context, runtime *libpod.Runtime, options entities.A
for imageID, policyMapper := range containerMap {
image, exists := imageMap[imageID]
if !exists {
errs = append(errs, errors.Errorf("container image ID %q not found in local storage", imageID))
errs = append(errs, fmt.Errorf("container image ID %q not found in local storage", imageID))
return nil, errs
}
@ -184,13 +184,13 @@ func autoUpdateRegistry(ctx context.Context, image *libimage.Image, ctr *libpod.
cid := ctr.ID()
rawImageName := ctr.RawImageName()
if rawImageName == "" {
return nil, errors.Errorf("registry auto-updating container %q: raw-image name is empty", cid)
return nil, fmt.Errorf("registry auto-updating container %q: raw-image name is empty", cid)
}
labels := ctr.Labels()
unit, exists := labels[systemdDefine.EnvVariable]
if !exists {
return nil, errors.Errorf("auto-updating container %q: no %s label found", ctr.ID(), systemdDefine.EnvVariable)
return nil, fmt.Errorf("auto-updating container %q: no %s label found", ctr.ID(), systemdDefine.EnvVariable)
}
report := &entities.AutoUpdateReport{
@ -214,7 +214,7 @@ func autoUpdateRegistry(ctx context.Context, image *libimage.Image, ctr *libpod.
authfile := getAuthfilePath(ctr, options)
needsUpdate, err := newerRemoteImageAvailable(ctx, image, rawImageName, authfile)
if err != nil {
return report, errors.Wrapf(err, "registry auto-updating container %q: image check for %q failed", cid, rawImageName)
return report, fmt.Errorf("registry auto-updating container %q: image check for %q failed: %w", cid, rawImageName, err)
}
if !needsUpdate {
@ -228,7 +228,7 @@ func autoUpdateRegistry(ctx context.Context, image *libimage.Image, ctr *libpod.
}
if _, err := updateImage(ctx, runtime, rawImageName, authfile); err != nil {
return report, errors.Wrapf(err, "registry auto-updating container %q: image update for %q failed", cid, rawImageName)
return report, fmt.Errorf("registry auto-updating container %q: image update for %q failed: %w", cid, rawImageName, err)
}
updatedRawImages[rawImageName] = true
@ -245,10 +245,10 @@ func autoUpdateRegistry(ctx context.Context, image *libimage.Image, ctr *libpod.
// To fallback, simply retag the old image and restart the service.
if err := image.Tag(rawImageName); err != nil {
return report, errors.Wrap(err, "falling back to previous image")
return report, fmt.Errorf("falling back to previous image: %w", err)
}
if err := restartSystemdUnit(ctx, ctr, unit, conn); err != nil {
return report, errors.Wrap(err, "restarting unit with old image during fallback")
return report, fmt.Errorf("restarting unit with old image during fallback: %w", err)
}
report.Updated = "rolled back"
@ -260,13 +260,13 @@ func autoUpdateLocally(ctx context.Context, image *libimage.Image, ctr *libpod.C
cid := ctr.ID()
rawImageName := ctr.RawImageName()
if rawImageName == "" {
return nil, errors.Errorf("locally auto-updating container %q: raw-image name is empty", cid)
return nil, fmt.Errorf("locally auto-updating container %q: raw-image name is empty", cid)
}
labels := ctr.Labels()
unit, exists := labels[systemdDefine.EnvVariable]
if !exists {
return nil, errors.Errorf("auto-updating container %q: no %s label found", ctr.ID(), systemdDefine.EnvVariable)
return nil, fmt.Errorf("auto-updating container %q: no %s label found", ctr.ID(), systemdDefine.EnvVariable)
}
report := &entities.AutoUpdateReport{
@ -280,7 +280,7 @@ func autoUpdateLocally(ctx context.Context, image *libimage.Image, ctr *libpod.C
needsUpdate, err := newerLocalImageAvailable(runtime, image, rawImageName)
if err != nil {
return report, errors.Wrapf(err, "locally auto-updating container %q: image check for %q failed", cid, rawImageName)
return report, fmt.Errorf("locally auto-updating container %q: image check for %q failed: %w", cid, rawImageName, err)
}
if !needsUpdate {
@ -306,10 +306,10 @@ func autoUpdateLocally(ctx context.Context, image *libimage.Image, ctr *libpod.C
// To fallback, simply retag the old image and restart the service.
if err := image.Tag(rawImageName); err != nil {
return report, errors.Wrap(err, "falling back to previous image")
return report, fmt.Errorf("falling back to previous image: %w", err)
}
if err := restartSystemdUnit(ctx, ctr, unit, conn); err != nil {
return report, errors.Wrap(err, "restarting unit with old image during fallback")
return report, fmt.Errorf("restarting unit with old image during fallback: %w", err)
}
report.Updated = "rolled back"
@ -320,7 +320,7 @@ func autoUpdateLocally(ctx context.Context, image *libimage.Image, ctr *libpod.C
func restartSystemdUnit(ctx context.Context, ctr *libpod.Container, unit string, conn *dbus.Conn) error {
restartChan := make(chan string)
if _, err := conn.RestartUnitContext(ctx, unit, "replace", restartChan); err != nil {
return errors.Wrapf(err, "auto-updating container %q: restarting systemd unit %q failed", ctr.ID(), unit)
return fmt.Errorf("auto-updating container %q: restarting systemd unit %q failed: %w", ctr.ID(), unit, err)
}
// Wait for the restart to finish and actually check if it was
@ -333,7 +333,7 @@ func restartSystemdUnit(ctx context.Context, ctr *libpod.Container, unit string,
return nil
default:
return errors.Errorf("auto-updating container %q: restarting systemd unit %q failed: expected %q but received %q", ctr.ID(), unit, "done", result)
return fmt.Errorf("auto-updating container %q: restarting systemd unit %q failed: expected %q but received %q", ctr.ID(), unit, "done", result)
}
}

View File

@ -2,6 +2,7 @@ package bindings
import (
"context"
"errors"
"fmt"
"io"
"net"
@ -15,7 +16,6 @@ import (
"github.com/blang/semver"
"github.com/containers/podman/v4/pkg/terminal"
"github.com/containers/podman/v4/version"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
@ -43,7 +43,7 @@ func GetClient(ctx context.Context) (*Connection, error) {
if c, ok := ctx.Value(clientKey).(*Connection); ok {
return c, nil
}
return nil, errors.Errorf("%s not set in context", clientKey)
return nil, fmt.Errorf("%s not set in context", clientKey)
}
// ServiceVersion from context build by NewConnection()
@ -92,7 +92,7 @@ func NewConnectionWithIdentity(ctx context.Context, uri string, identity string)
_url, err := url.Parse(uri)
if err != nil {
return nil, errors.Wrapf(err, "Value of CONTAINER_HOST is not a valid url: %s", uri)
return nil, fmt.Errorf("value of CONTAINER_HOST is not a valid url: %s: %w", uri, err)
}
// Now we set up the http Client to use the connection above
@ -117,16 +117,16 @@ func NewConnectionWithIdentity(ctx context.Context, uri string, identity string)
}
connection = tcpClient(_url)
default:
return nil, errors.Errorf("unable to create connection. %q is not a supported schema", _url.Scheme)
return nil, fmt.Errorf("unable to create connection. %q is not a supported schema", _url.Scheme)
}
if err != nil {
return nil, errors.Wrapf(err, "unable to connect to Podman. failed to create %sClient", _url.Scheme)
return nil, fmt.Errorf("unable to connect to Podman. failed to create %sClient: %w", _url.Scheme, err)
}
ctx = context.WithValue(ctx, clientKey, &connection)
serviceVersion, err := pingNewConnection(ctx)
if err != nil {
return nil, errors.Wrap(err, "unable to connect to Podman socket")
return nil, fmt.Errorf("unable to connect to Podman socket: %w", err)
}
ctx = context.WithValue(ctx, versionKey, serviceVersion)
return ctx, nil
@ -177,11 +177,11 @@ func pingNewConnection(ctx context.Context) (*semver.Version, error) {
// Server's job when Client version is equal or older
return &versionSrv, nil
case 1:
return nil, errors.Errorf("server API version is too old. Client %q server %q",
return nil, fmt.Errorf("server API version is too old. Client %q server %q",
version.APIVersion[version.Libpod][version.MinimalAPI].String(), versionSrv.String())
}
}
return nil, errors.Errorf("ping response was %d", response.StatusCode)
return nil, fmt.Errorf("ping response was %d", response.StatusCode)
}
func sshClient(_url *url.URL, secure bool, passPhrase string, identity string) (Connection, error) {
@ -193,7 +193,7 @@ func sshClient(_url *url.URL, secure bool, passPhrase string, identity string) (
if len(identity) > 0 {
s, err := terminal.PublicKey(identity, []byte(passPhrase))
if err != nil {
return Connection{}, errors.Wrapf(err, "failed to parse identity %q", identity)
return Connection{}, fmt.Errorf("failed to parse identity %q: %w", identity, err)
}
signers = append(signers, s)
@ -289,7 +289,7 @@ func sshClient(_url *url.URL, secure bool, passPhrase string, identity string) (
},
)
if err != nil {
return Connection{}, errors.Wrapf(err, "connection to bastion host (%s) failed", _url.String())
return Connection{}, fmt.Errorf("connection to bastion host (%s) failed: %w", _url.String(), err)
}
connection := Connection{URI: _url}
@ -379,7 +379,7 @@ func (c *Connection) GetDialer(ctx context.Context) (net.Conn, error) {
return transport.DialContext(ctx, c.URI.Scheme, c.URI.String())
}
return nil, errors.New("Unable to get dial context")
return nil, errors.New("unable to get dial context")
}
// IsInformational returns true if the response code is 1xx

View File

@ -2,6 +2,7 @@ package containers
import (
"context"
"errors"
"io"
"net/http"
"net/url"
@ -9,7 +10,6 @@ import (
"github.com/containers/podman/v4/pkg/bindings"
"github.com/containers/podman/v4/pkg/copy"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/pkg/errors"
)
// Stat checks if the specified path is on the container. Note that the stat

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
@ -18,7 +19,6 @@ import (
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/bindings"
"github.com/moby/term"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
terminal "golang.org/x/term"
)
@ -75,7 +75,7 @@ func Attach(ctx context.Context, nameOrID string, stdin io.Reader, stdout io.Wri
detachKeysInBytes, err = term.ToBytes(options.GetDetachKeys())
if err != nil {
return errors.Wrapf(err, "invalid detach keys")
return fmt.Errorf("invalid detach keys: %w", err)
}
}
if isSet.stdin {
@ -261,7 +261,7 @@ func DemuxHeader(r io.Reader, buffer []byte) (fd, sz int, err error) {
fd = int(buffer[0])
if fd < 0 || fd > 3 {
err = errors.Wrapf(ErrLostSync, fmt.Sprintf(`channel "%d" found, 0-3 supported`, fd))
err = fmt.Errorf(`channel "%d" found, 0-3 supported: %w`, fd, ErrLostSync)
return
}

View File

@ -2,6 +2,8 @@ package containers
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
@ -12,7 +14,6 @@ import (
"github.com/containers/podman/v4/pkg/bindings"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/domain/entities/reports"
"github.com/pkg/errors"
)
var (
@ -447,7 +448,7 @@ func ContainerInit(ctx context.Context, nameOrID string, options *InitOptions) e
defer response.Body.Close()
if response.StatusCode == http.StatusNotModified {
return errors.Wrapf(define.ErrCtrStateInvalid, "container %s has already been created in runtime", nameOrID)
return fmt.Errorf("container %s has already been created in runtime: %w", nameOrID, define.ErrCtrStateInvalid)
}
return response.Process(nil)
}

View File

@ -3,6 +3,8 @@ package containers
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"strings"
@ -11,7 +13,6 @@ import (
"github.com/containers/podman/v4/pkg/bindings"
"github.com/containers/podman/v4/pkg/domain/entities"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -27,12 +28,12 @@ func ExecCreate(ctx context.Context, nameOrID string, config *handlers.ExecCreat
}
if config == nil {
return "", errors.Errorf("must provide a configuration for exec session")
return "", errors.New("must provide a configuration for exec session")
}
requestJSON, err := json.Marshal(config)
if err != nil {
return "", errors.Wrapf(err, "error marshalling exec config to JSON")
return "", fmt.Errorf("error marshalling exec config to JSON: %w", err)
}
jsonReader := strings.NewReader(string(requestJSON))

View File

@ -2,13 +2,13 @@ package containers
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"github.com/containers/podman/v4/pkg/bindings"
"github.com/pkg/errors"
)
// Logs obtains a container's logs given the options provided. The logs are then sent to the

View File

@ -2,10 +2,11 @@ package bindings
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"github.com/containers/podman/v4/pkg/errorhandling"
"github.com/pkg/errors"
)
var (
@ -30,7 +31,7 @@ func (h APIResponse) Process(unmarshalInto interface{}) error {
func (h APIResponse) ProcessWithError(unmarshalInto interface{}, unmarshalErrorInto interface{}) error {
data, err := ioutil.ReadAll(h.Response.Body)
if err != nil {
return errors.Wrap(err, "unable to process API response")
return fmt.Errorf("unable to process API response: %w", err)
}
if h.IsSuccess() || h.IsRedirection() {
if unmarshalInto != nil {

View File

@ -5,6 +5,7 @@ import (
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
@ -28,7 +29,6 @@ import (
"github.com/docker/go-units"
"github.com/hashicorp/go-multierror"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -543,14 +543,14 @@ func Build(ctx context.Context, containerFiles []string, options entities.BuildO
if err := dec.Decode(&s); err != nil {
if errors.Is(err, io.ErrUnexpectedEOF) {
return nil, errors.Wrap(err, "server probably quit")
return nil, fmt.Errorf("server probably quit: %w", err)
}
// EOF means the stream is over in which case we need
// to have read the id.
if errors.Is(err, io.EOF) && id != "" {
break
}
return &entities.BuildReport{ID: id}, errors.Wrap(err, "decoding stream")
return &entities.BuildReport{ID: id}, fmt.Errorf("decoding stream: %w", err)
}
switch {
@ -574,11 +574,11 @@ func Build(ctx context.Context, containerFiles []string, options entities.BuildO
func nTar(excludes []string, sources ...string) (io.ReadCloser, error) {
pm, err := fileutils.NewPatternMatcher(excludes)
if err != nil {
return nil, errors.Wrapf(err, "error processing excludes list %v", excludes)
return nil, fmt.Errorf("error processing excludes list %v: %w", excludes, err)
}
if len(sources) == 0 {
return nil, errors.New("No source(s) provided for build")
return nil, errors.New("no source(s) provided for build")
}
pr, pw := io.Pipe()
@ -623,7 +623,7 @@ func nTar(excludes []string, sources ...string) (io.ReadCloser, error) {
excluded, err := pm.Matches(name) //nolint:staticcheck
if err != nil {
return errors.Wrapf(err, "error checking if %q is excluded", name)
return fmt.Errorf("error checking if %q is excluded: %w", name, err)
}
if excluded {
// Note: filepath.SkipDir is not possible to use given .dockerignore semantics.
@ -726,7 +726,7 @@ func parseDockerignore(root string) ([]string, error) {
var dockerIgnoreErr error
ignore, dockerIgnoreErr = ioutil.ReadFile(filepath.Join(root, ".dockerignore"))
if dockerIgnoreErr != nil && !os.IsNotExist(dockerIgnoreErr) {
return nil, errors.Wrapf(err, "error reading .containerignore: '%s'", root)
return nil, fmt.Errorf("error reading .containerignore: '%s': %w", root, err)
}
}
rawexcludes := strings.Split(string(ignore), "\n")

View File

@ -2,6 +2,7 @@ package images
import (
"context"
"errors"
"fmt"
"io"
"net/http"
@ -14,7 +15,6 @@ import (
"github.com/containers/podman/v4/pkg/bindings"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/domain/entities/reports"
"github.com/pkg/errors"
)
// Exists a lightweight way to determine if an image exists in local storage. It returns a

View File

@ -3,6 +3,7 @@ package images
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@ -15,7 +16,6 @@ import (
"github.com/containers/podman/v4/pkg/bindings"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/errorhandling"
"github.com/pkg/errors"
)
// Pull is the binding for libpod's v2 endpoints for pulling images. Note that
@ -91,7 +91,7 @@ func Pull(ctx context.Context, rawImage string, options *PullOptions) ([]string,
images = report.Images
case report.ID != "":
default:
return images, errors.Errorf("failed to parse pull results stream, unexpected input: %v", report)
return images, fmt.Errorf("failed to parse pull results stream, unexpected input: %v", report)
}
}
return images, errorhandling.JoinErrors(pullErrors)

View File

@ -2,6 +2,8 @@ package manifests
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net/http"
"strconv"
@ -15,7 +17,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/errorhandling"
jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
)
// Create creates a manifest for the given name. Optional images to be associated with
@ -219,13 +220,13 @@ func Modify(ctx context.Context, name string, images []string, options *ModifyOp
data, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", errors.Wrap(err, "unable to process API response")
return "", fmt.Errorf("unable to process API response: %w", err)
}
if response.IsSuccess() || response.IsRedirection() {
var report entities.ManifestModifyReport
if err = jsoniter.Unmarshal(data, &report); err != nil {
return "", errors.Wrap(err, "unable to decode API response")
return "", fmt.Errorf("unable to decode API response: %w", err)
}
err = errorhandling.JoinErrors(report.Errors)
@ -244,7 +245,7 @@ func Modify(ctx context.Context, name string, images []string, options *ModifyOp
ResponseCode: response.StatusCode,
}
if err = jsoniter.Unmarshal(data, &errModel); err != nil {
return "", errors.Wrap(err, "unable to decode API response")
return "", fmt.Errorf("unable to decode API response: %w", err)
}
return "", &errModel
}

View File

@ -3,6 +3,7 @@ package system
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -11,7 +12,6 @@ import (
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/bindings"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -37,7 +37,7 @@ func Events(ctx context.Context, eventChan chan entities.Event, cancelChan chan
go func() {
<-cancelChan
err = response.Body.Close()
logrus.Error(errors.Wrap(err, "unable to close event response body"))
logrus.Errorf("Unable to close event response body: %v", err)
}()
}
@ -56,7 +56,7 @@ func Events(ctx context.Context, eventChan chan entities.Event, cancelChan chan
case errors.Is(err, io.EOF):
return nil
default:
return errors.Wrap(err, "unable to decode event response")
return fmt.Errorf("unable to decode event response: %w", err)
}
}

View File

@ -16,7 +16,6 @@ import (
"github.com/containers/podman/v4/pkg/specgen"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega/gexec"
"github.com/pkg/errors"
)
type testImage struct {
@ -127,7 +126,7 @@ func (b *bindingTest) runPodman(command []string) *gexec.Session {
fmt.Printf("Running: %s %s\n", podmanBinary, strings.Join(cmd, " "))
session, err := gexec.Start(c, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter)
if err != nil {
panic(errors.Errorf("unable to run podman command: %q", cmd))
panic(fmt.Errorf("unable to run podman command: %q", cmd))
}
return session
}

View File

@ -1,10 +1,9 @@
package channel
import (
"errors"
"io"
"sync"
"github.com/pkg/errors"
)
// WriteCloser is an io.WriteCloser that that proxies Write() calls to a channel

View File

@ -2,6 +2,8 @@ package checkpoint
import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
@ -16,7 +18,6 @@ import (
"github.com/containers/podman/v4/pkg/specgen/generate"
"github.com/containers/podman/v4/pkg/specgenutil"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -65,7 +66,7 @@ func CRImportCheckpoint(ctx context.Context, runtime *libpod.Runtime, restoreOpt
// This should not happen as checkpoints with these options are not exported.
if len(ctrConfig.Dependencies) > 0 {
return nil, errors.Errorf("Cannot import checkpoints of containers with dependencies")
return nil, errors.New("cannot import checkpoints of containers with dependencies")
}
// Volumes included in the checkpoint should not exist
@ -76,7 +77,7 @@ func CRImportCheckpoint(ctx context.Context, runtime *libpod.Runtime, restoreOpt
return nil, err
}
if exists {
return nil, errors.Errorf("volume with name %s already exists. Use --ignore-volumes to not restore content of volumes", vol.Name)
return nil, fmt.Errorf("volume with name %s already exists. Use --ignore-volumes to not restore content of volumes", vol.Name)
}
}
}
@ -106,11 +107,11 @@ func CRImportCheckpoint(ctx context.Context, runtime *libpod.Runtime, restoreOpt
if restoreOptions.Pod != "" {
// Restoring into a Pod requires much newer versions of CRIU
if !criu.CheckForCriu(criu.PodCriuVersion) {
return nil, errors.Errorf("restoring containers into pods requires at least CRIU %d", criu.PodCriuVersion)
return nil, fmt.Errorf("restoring containers into pods requires at least CRIU %d", criu.PodCriuVersion)
}
// The runtime also has to support it
if !crutils.CRRuntimeSupportsPodCheckpointRestore(runtime.GetOCIRuntimePath()) {
return nil, errors.Errorf("runtime %s does not support pod restore", runtime.GetOCIRuntimePath())
return nil, fmt.Errorf("runtime %s does not support pod restore", runtime.GetOCIRuntimePath())
}
// Restoring into an existing Pod
ctrConfig.Pod = restoreOptions.Pod
@ -120,12 +121,12 @@ func CRImportCheckpoint(ctx context.Context, runtime *libpod.Runtime, restoreOpt
// Let's make sure we a restoring into a pod with the same shared namespaces.
pod, err := runtime.LookupPod(ctrConfig.Pod)
if err != nil {
return nil, errors.Wrapf(err, "pod %q cannot be retrieved", ctrConfig.Pod)
return nil, fmt.Errorf("pod %q cannot be retrieved: %w", ctrConfig.Pod, err)
}
infraContainer, err := pod.InfraContainer()
if err != nil {
return nil, errors.Wrapf(err, "cannot retrieve infra container from pod %q", ctrConfig.Pod)
return nil, fmt.Errorf("cannot retrieve infra container from pod %q: %w", ctrConfig.Pod, err)
}
// If a namespaces was shared (!= "") it needs to be set to the new infrastructure container
@ -133,14 +134,14 @@ func CRImportCheckpoint(ctx context.Context, runtime *libpod.Runtime, restoreOpt
// container we abort.
if ctrConfig.IPCNsCtr != "" {
if !pod.SharesIPC() {
return nil, errors.Errorf("pod %s does not share the IPC namespace", ctrConfig.Pod)
return nil, fmt.Errorf("pod %s does not share the IPC namespace", ctrConfig.Pod)
}
ctrConfig.IPCNsCtr = infraContainer.ID()
}
if ctrConfig.NetNsCtr != "" {
if !pod.SharesNet() {
return nil, errors.Errorf("pod %s does not share the network namespace", ctrConfig.Pod)
return nil, fmt.Errorf("pod %s does not share the network namespace", ctrConfig.Pod)
}
ctrConfig.NetNsCtr = infraContainer.ID()
for net, opts := range ctrConfig.Networks {
@ -154,21 +155,21 @@ func CRImportCheckpoint(ctx context.Context, runtime *libpod.Runtime, restoreOpt
if ctrConfig.PIDNsCtr != "" {
if !pod.SharesPID() {
return nil, errors.Errorf("pod %s does not share the PID namespace", ctrConfig.Pod)
return nil, fmt.Errorf("pod %s does not share the PID namespace", ctrConfig.Pod)
}
ctrConfig.PIDNsCtr = infraContainer.ID()
}
if ctrConfig.UTSNsCtr != "" {
if !pod.SharesUTS() {
return nil, errors.Errorf("pod %s does not share the UTS namespace", ctrConfig.Pod)
return nil, fmt.Errorf("pod %s does not share the UTS namespace", ctrConfig.Pod)
}
ctrConfig.UTSNsCtr = infraContainer.ID()
}
if ctrConfig.CgroupNsCtr != "" {
if !pod.SharesCgroup() {
return nil, errors.Errorf("pod %s does not share the cgroup namespace", ctrConfig.Pod)
return nil, fmt.Errorf("pod %s does not share the cgroup namespace", ctrConfig.Pod)
}
ctrConfig.CgroupNsCtr = infraContainer.ID()
}
@ -180,7 +181,7 @@ func CRImportCheckpoint(ctx context.Context, runtime *libpod.Runtime, restoreOpt
// Fix parent cgroup
cgroupPath, err := pod.CgroupPath()
if err != nil {
return nil, errors.Wrapf(err, "cannot retrieve cgroup path from pod %q", ctrConfig.Pod)
return nil, fmt.Errorf("cannot retrieve cgroup path from pod %q: %w", ctrConfig.Pod, err)
}
ctrConfig.CgroupParent = cgroupPath
@ -228,14 +229,14 @@ func CRImportCheckpoint(ctx context.Context, runtime *libpod.Runtime, restoreOpt
containerConfig := container.Config()
ctrName := ctrConfig.Name
if containerConfig.Name != ctrName {
return nil, errors.Errorf("Name of restored container (%s) does not match requested name (%s)", containerConfig.Name, ctrName)
return nil, fmt.Errorf("name of restored container (%s) does not match requested name (%s)", containerConfig.Name, ctrName)
}
if !newName {
// Only check ID for a restore with the same name.
// Using -n to request a new name for the restored container, will also create a new ID
if containerConfig.ID != ctrID {
return nil, errors.Errorf("ID of restored container (%s) does not match requested ID (%s)", containerConfig.ID, ctrID)
return nil, fmt.Errorf("ID of restored container (%s) does not match requested ID (%s)", containerConfig.ID, ctrID)
}
}

View File

@ -2,6 +2,8 @@ package crutils
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
@ -12,7 +14,6 @@ import (
"github.com/checkpoint-restore/go-criu/v5/stats"
"github.com/containers/storage/pkg/archive"
"github.com/opencontainers/selinux/go-selinux/label"
"github.com/pkg/errors"
)
// This file mainly exist to make the checkpoint/restore functions
@ -23,7 +24,7 @@ import (
func CRImportCheckpointWithoutConfig(destination, input string) error {
archiveFile, err := os.Open(input)
if err != nil {
return errors.Wrapf(err, "Failed to open checkpoint archive %s for import", input)
return fmt.Errorf("failed to open checkpoint archive %s for import: %w", input, err)
}
defer archiveFile.Close()
@ -35,7 +36,7 @@ func CRImportCheckpointWithoutConfig(destination, input string) error {
},
}
if err = archive.Untar(archiveFile, destination, options); err != nil {
return errors.Wrapf(err, "Unpacking of checkpoint archive %s failed", input)
return fmt.Errorf("unpacking of checkpoint archive %s failed: %w", input, err)
}
return nil
@ -47,7 +48,7 @@ func CRImportCheckpointWithoutConfig(destination, input string) error {
func CRImportCheckpointConfigOnly(destination, input string) error {
archiveFile, err := os.Open(input)
if err != nil {
return errors.Wrapf(err, "Failed to open checkpoint archive %s for import", input)
return fmt.Errorf("failed to open checkpoint archive %s for import: %w", input, err)
}
defer archiveFile.Close()
@ -65,7 +66,7 @@ func CRImportCheckpointConfigOnly(destination, input string) error {
},
}
if err = archive.Untar(archiveFile, destination, options); err != nil {
return errors.Wrapf(err, "Unpacking of checkpoint archive %s failed", input)
return fmt.Errorf("unpacking of checkpoint archive %s failed: %w", input, err)
}
return nil
@ -81,14 +82,14 @@ func CRRemoveDeletedFiles(id, baseDirectory, containerRootDirectory string) erro
}
if err != nil {
return errors.Wrapf(err, "failed to read deleted files file")
return fmt.Errorf("failed to read deleted files file: %w", err)
}
for _, deleteFile := range deletedFiles {
// Using RemoveAll as deletedFiles, which is generated from 'podman diff'
// lists completely deleted directories as a single entry: 'D /root'.
if err := os.RemoveAll(filepath.Join(containerRootDirectory, deleteFile)); err != nil {
return errors.Wrapf(err, "failed to delete files from container %s during restore", id)
return fmt.Errorf("failed to delete files from container %s during restore: %w", id, err)
}
}
@ -105,12 +106,12 @@ func CRApplyRootFsDiffTar(baseDirectory, containerRootDirectory string) error {
if errors.Is(err, os.ErrNotExist) {
return nil
}
return errors.Wrap(err, "failed to open root file-system diff file")
return fmt.Errorf("failed to open root file-system diff file: %w", err)
}
defer rootfsDiffFile.Close()
if err := archive.Untar(rootfsDiffFile, containerRootDirectory, nil); err != nil {
return errors.Wrapf(err, "failed to apply root file-system diff file %s", rootfsDiffPath)
return fmt.Errorf("failed to apply root file-system diff file %s: %w", rootfsDiffPath, err)
}
return nil
@ -158,11 +159,11 @@ func CRCreateRootFsDiffTar(changes *[]archive.Change, mountPoint, destination st
IncludeFiles: rootfsIncludeFiles,
})
if err != nil {
return includeFiles, errors.Wrapf(err, "error exporting root file-system diff to %q", rootfsDiffPath)
return includeFiles, fmt.Errorf("error exporting root file-system diff to %q: %w", rootfsDiffPath, err)
}
rootfsDiffFile, err := os.Create(rootfsDiffPath)
if err != nil {
return includeFiles, errors.Wrapf(err, "error creating root file-system diff file %q", rootfsDiffPath)
return includeFiles, fmt.Errorf("error creating root file-system diff file %q: %w", rootfsDiffPath, err)
}
defer rootfsDiffFile.Close()
if _, err = io.Copy(rootfsDiffFile, rootfsTar); err != nil {
@ -195,11 +196,11 @@ func CRCreateFileWithLabel(directory, fileName, fileLabel string) error {
logFile, err := os.OpenFile(logFileName, os.O_CREATE, 0o600)
if err != nil {
return errors.Wrapf(err, "failed to create file %q", logFileName)
return fmt.Errorf("failed to create file %q: %w", logFileName, err)
}
defer logFile.Close()
if err = label.SetFileLabel(logFileName, fileLabel); err != nil {
return errors.Wrapf(err, "failed to label file %q", logFileName)
return fmt.Errorf("failed to label file %q: %w", logFileName, err)
}
return nil

View File

@ -3,13 +3,14 @@ package copy
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/containers/podman/v4/libpod/define"
"github.com/pkg/errors"
)
// XDockerContainerPathStatHeader is the *key* in http headers pointing to the
@ -18,7 +19,7 @@ const XDockerContainerPathStatHeader = "X-Docker-Container-Path-Stat"
// ErrENOENT mimics the stdlib's ErrENOENT and can be used to implement custom logic
// while preserving the user-visible error message.
var ErrENOENT = errors.New("No such file or directory")
var ErrENOENT = errors.New("no such file or directory")
// FileInfo describes a file or directory and is returned by
// (*CopyItem).Stat().
@ -29,7 +30,7 @@ type FileInfo = define.FileInfo
func EncodeFileInfo(info *FileInfo) (string, error) {
buf, err := json.Marshal(&info)
if err != nil {
return "", errors.Wrap(err, "failed to serialize file stats")
return "", fmt.Errorf("failed to serialize file stats: %w", err)
}
return base64.URLEncoding.EncodeToString(buf), nil
}

View File

@ -1,9 +1,8 @@
package copy
import (
"fmt"
"strings"
"github.com/pkg/errors"
)
// ParseSourceAndDestination parses the source and destination input into a
@ -19,7 +18,7 @@ func ParseSourceAndDestination(source, destination string) (string, string, stri
destContainer, destPath := parseUserInput(destination)
if len(sourcePath) == 0 || len(destPath) == 0 {
return "", "", "", "", errors.Errorf("invalid arguments %q, %q: you must specify paths", source, destination)
return "", "", "", "", fmt.Errorf("invalid arguments %q, %q: you must specify paths", source, destination)
}
return sourceContainer, sourcePath, destContainer, destPath, nil

View File

@ -1,13 +1,13 @@
package entities
import (
"errors"
"sort"
"strings"
"time"
"github.com/containers/common/libnetwork/types"
"github.com/containers/podman/v4/pkg/ps/define"
"github.com/pkg/errors"
)
// ListContainer describes a container suitable for listing
@ -166,7 +166,7 @@ func SortPsOutput(sortBy string, psOutput SortListContainers) (SortListContainer
case "pod":
sort.Sort(psSortedPod{psOutput})
default:
return nil, errors.Errorf("invalid option for --sort, options are: command, created, id, image, names, runningfor, size, or status")
return nil, errors.New("invalid option for --sort, options are: command, created, id, image, names, runningfor, size, or status")
}
return psOutput, nil
}

View File

@ -1,6 +1,8 @@
package filters
import (
"errors"
"fmt"
"strconv"
"strings"
@ -8,7 +10,6 @@ import (
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/util"
"github.com/pkg/errors"
)
// GeneratePodFilterFunc takes a filter and filtervalue (key, value)
@ -59,7 +60,7 @@ func GeneratePodFilterFunc(filter string, filterValues []string, r *libpod.Runti
case "ctr-status":
for _, filterValue := range filterValues {
if !cutil.StringInSlice(filterValue, []string{"created", "running", "paused", "stopped", "exited", "unknown"}) {
return nil, errors.Errorf("%s is not a valid status", filterValue)
return nil, fmt.Errorf("%s is not a valid status", filterValue)
}
}
return func(p *libpod.Pod) bool {
@ -96,7 +97,7 @@ func GeneratePodFilterFunc(filter string, filterValues []string, r *libpod.Runti
case "status":
for _, filterValue := range filterValues {
if !cutil.StringInSlice(filterValue, []string{"stopped", "running", "paused", "exited", "dead", "created", "degraded"}) {
return nil, errors.Errorf("%s is not a valid pod status", filterValue)
return nil, fmt.Errorf("%s is not a valid pod status", filterValue)
}
}
return func(p *libpod.Pod) bool {
@ -158,5 +159,5 @@ func GeneratePodFilterFunc(filter string, filterValues []string, r *libpod.Runti
return false
}, nil
}
return nil, errors.Errorf("%s is an invalid filter", filter)
return nil, fmt.Errorf("%s is an invalid filter", filter)
}

View File

@ -1,13 +1,13 @@
package filters
import (
"fmt"
"net/url"
"regexp"
"strings"
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/pkg/util"
"github.com/pkg/errors"
)
func GenerateVolumeFilters(filters url.Values) ([]libpod.VolumeFilter, error) {
@ -72,7 +72,7 @@ func GenerateVolumeFilters(filters url.Values) ([]libpod.VolumeFilter, error) {
// invert the result of IsDangling.
invert = true
default:
return nil, errors.Errorf("%q is not a valid value for the \"dangling\" filter - must be true or false", danglingVal)
return nil, fmt.Errorf("%q is not a valid value for the \"dangling\" filter - must be true or false", danglingVal)
}
vf = append(vf, func(v *libpod.Volume) bool {
dangling, err := v.IsDangling()
@ -85,7 +85,7 @@ func GenerateVolumeFilters(filters url.Values) ([]libpod.VolumeFilter, error) {
return dangling
})
default:
return nil, errors.Errorf("%q is an invalid volume filter", filter)
return nil, fmt.Errorf("%q is an invalid volume filter", filter)
}
}
}
@ -109,7 +109,7 @@ func GeneratePruneVolumeFilters(filters url.Values) ([]libpod.VolumeFilter, erro
}
vf = append(vf, f)
default:
return nil, errors.Errorf("%q is an invalid volume filter", filter)
return nil, fmt.Errorf("%q is an invalid volume filter", filter)
}
}
}

View File

@ -12,7 +12,6 @@ import (
k8sAPI "github.com/containers/podman/v4/pkg/k8s.io/api/core/v1"
"github.com/containers/podman/v4/pkg/systemd/generate"
"github.com/ghodss/yaml"
"github.com/pkg/errors"
)
func (ic *ContainerEngine) GenerateSystemd(ctx context.Context, nameOrID string, options entities.GenerateSystemdOptions) (*entities.GenerateSystemdReport, error) {
@ -30,8 +29,8 @@ func (ic *ContainerEngine) GenerateSystemd(ctx context.Context, nameOrID string,
// If it's not a container, we either have a pod or garbage.
pod, err := ic.Libpod.LookupPod(nameOrID)
if err != nil {
err = errors.Wrap(ctrErr, err.Error())
return nil, errors.Wrapf(err, "%s does not refer to a container or pod", nameOrID)
err = fmt.Errorf("%v: %w", err.Error(), ctrErr)
return nil, fmt.Errorf("%s does not refer to a container or pod: %w", nameOrID, err)
}
// Generate the units for the pod and all its containers.
@ -63,7 +62,7 @@ func (ic *ContainerEngine) GenerateKube(ctx context.Context, nameOrIDs []string,
// now that infra holds NS data, we need to support dependencies.
// we cannot deal with ctrs already in a pod.
if len(ctr.PodID()) > 0 {
return nil, errors.Errorf("container %s is associated with pod %s: use generate on the pod itself", ctr.ID(), ctr.PodID())
return nil, fmt.Errorf("container %s is associated with pod %s: use generate on the pod itself", ctr.ID(), ctr.PodID())
}
ctrs = append(ctrs, ctr)
continue
@ -92,7 +91,7 @@ func (ic *ContainerEngine) GenerateKube(ctx context.Context, nameOrIDs []string,
}
// If it reaches here is because the name or id did not exist.
return nil, errors.Errorf("Name or ID %q not found", nameOrID)
return nil, fmt.Errorf("name or ID %q not found", nameOrID)
}
// Generate kube persistent volume claims from volumes.

View File

@ -2,10 +2,10 @@ package abi
import (
"context"
"fmt"
"github.com/containers/common/libimage"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/pkg/errors"
)
func (ir *ImageEngine) List(ctx context.Context, opts entities.ImageListOptions) ([]*entities.ImageSummary, error) {
@ -28,11 +28,11 @@ func (ir *ImageEngine) List(ctx context.Context, opts entities.ImageListOptions)
for _, img := range images {
repoDigests, err := img.RepoDigests()
if err != nil {
return nil, errors.Wrapf(err, "getting repoDigests from image %q", img.ID())
return nil, fmt.Errorf("getting repoDigests from image %q: %w", img.ID(), err)
}
isDangling, err := img.IsDangling(ctx)
if err != nil {
return nil, errors.Wrapf(err, "error checking if image %q is dangling", img.ID())
return nil, fmt.Errorf("error checking if image %q is dangling: %w", img.ID(), err)
}
e := entities.ImageSummary{
@ -49,18 +49,18 @@ func (ir *ImageEngine) List(ctx context.Context, opts entities.ImageListOptions)
}
e.Labels, err = img.Labels(ctx)
if err != nil {
return nil, errors.Wrapf(err, "error retrieving label for image %q: you may need to remove the image to resolve the error", img.ID())
return nil, fmt.Errorf("error retrieving label for image %q: you may need to remove the image to resolve the error: %w", img.ID(), err)
}
ctnrs, err := img.Containers()
if err != nil {
return nil, errors.Wrapf(err, "error retrieving containers for image %q: you may need to remove the image to resolve the error", img.ID())
return nil, fmt.Errorf("error retrieving containers for image %q: you may need to remove the image to resolve the error: %w", img.ID(), err)
}
e.Containers = len(ctnrs)
sz, err := img.Size()
if err != nil {
return nil, errors.Wrapf(err, "error retrieving size of image %q: you may need to remove the image to resolve the error", img.ID())
return nil, fmt.Errorf("error retrieving size of image %q: you may need to remove the image to resolve the error: %w", img.ID(), err)
}
e.Size = sz
// This is good enough for now, but has to be
@ -69,7 +69,7 @@ func (ir *ImageEngine) List(ctx context.Context, opts entities.ImageListOptions)
parent, err := img.Parent(ctx)
if err != nil {
return nil, errors.Wrapf(err, "error retrieving parent of image %q: you may need to remove the image to resolve the error", img.ID())
return nil, fmt.Errorf("error retrieving parent of image %q: you may need to remove the image to resolve the error: %w", img.ID(), err)
}
if parent != nil {
e.ParentId = parent.ID()

View File

@ -1,13 +1,13 @@
package parse
import (
"fmt"
"strconv"
"strings"
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/libpod/define"
units "github.com/docker/go-units"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -32,7 +32,7 @@ func VolumeOptions(opts map[string]string) ([]libpod.VolumeCreateOption, error)
case "size":
size, err := units.FromHumanSize(splitO[1])
if err != nil {
return nil, errors.Wrapf(err, "cannot convert size %s to integer", splitO[1])
return nil, fmt.Errorf("cannot convert size %s to integer: %w", splitO[1], err)
}
libpodOptions = append(libpodOptions, libpod.WithVolumeSize(uint64(size)))
finalVal = append(finalVal, o)
@ -41,7 +41,7 @@ func VolumeOptions(opts map[string]string) ([]libpod.VolumeCreateOption, error)
case "inodes":
inodes, err := strconv.ParseUint(splitO[1], 10, 64)
if err != nil {
return nil, errors.Wrapf(err, "cannot convert inodes %s to integer", splitO[1])
return nil, fmt.Errorf("cannot convert inodes %s to integer: %w", splitO[1], err)
}
libpodOptions = append(libpodOptions, libpod.WithVolumeInodes(inodes))
finalVal = append(finalVal, o)
@ -49,11 +49,11 @@ func VolumeOptions(opts map[string]string) ([]libpod.VolumeCreateOption, error)
volumeOptions["INODES"] = splitO[1]
case "uid":
if len(splitO) != 2 {
return nil, errors.Wrapf(define.ErrInvalidArg, "uid option must provide a UID")
return nil, fmt.Errorf("uid option must provide a UID: %w", define.ErrInvalidArg)
}
intUID, err := strconv.Atoi(splitO[1])
if err != nil {
return nil, errors.Wrapf(err, "cannot convert UID %s to integer", splitO[1])
return nil, fmt.Errorf("cannot convert UID %s to integer: %w", splitO[1], err)
}
logrus.Debugf("Removing uid= from options and adding WithVolumeUID for UID %d", intUID)
libpodOptions = append(libpodOptions, libpod.WithVolumeUID(intUID), libpod.WithVolumeNoChown())
@ -62,11 +62,11 @@ func VolumeOptions(opts map[string]string) ([]libpod.VolumeCreateOption, error)
volumeOptions["UID"] = splitO[1]
case "gid":
if len(splitO) != 2 {
return nil, errors.Wrapf(define.ErrInvalidArg, "gid option must provide a GID")
return nil, fmt.Errorf("gid option must provide a GID: %w", define.ErrInvalidArg)
}
intGID, err := strconv.Atoi(splitO[1])
if err != nil {
return nil, errors.Wrapf(err, "cannot convert GID %s to integer", splitO[1])
return nil, fmt.Errorf("cannot convert GID %s to integer: %w", splitO[1], err)
}
logrus.Debugf("Removing gid= from options and adding WithVolumeGID for GID %d", intGID)
libpodOptions = append(libpodOptions, libpod.WithVolumeGID(intGID), libpod.WithVolumeNoChown())
@ -80,11 +80,11 @@ func VolumeOptions(opts map[string]string) ([]libpod.VolumeCreateOption, error)
volumeOptions["NOQUOTA"] = "true"
case "timeout":
if len(splitO) != 2 {
return nil, errors.Wrapf(define.ErrInvalidArg, "timeout option must provide a valid timeout in seconds")
return nil, fmt.Errorf("timeout option must provide a valid timeout in seconds: %w", define.ErrInvalidArg)
}
intTimeout, err := strconv.Atoi(splitO[1])
if err != nil {
return nil, errors.Wrapf(err, "cannot convert Timeout %s to an integer", splitO[1])
return nil, fmt.Errorf("cannot convert Timeout %s to an integer: %w", splitO[1], err)
}
logrus.Debugf("Removing timeout from options and adding WithTimeout for Timeout %d", intTimeout)
libpodOptions = append(libpodOptions, libpod.WithVolumeDriverTimeout(intTimeout))

View File

@ -2,6 +2,7 @@ package abi
import (
"context"
"errors"
"fmt"
"github.com/containers/common/pkg/cgroups"
@ -10,7 +11,6 @@ import (
"github.com/containers/podman/v4/pkg/rootless"
"github.com/containers/podman/v4/utils"
"github.com/docker/go-units"
"github.com/pkg/errors"
)
// PodStats implements printing stats about pods.
@ -28,7 +28,7 @@ func (ic *ContainerEngine) PodStats(ctx context.Context, namesOrIds []string, op
// Get the (running) pods and convert them to the entities format.
pods, err := getPodsByContext(options.All, options.Latest, namesOrIds, ic.Libpod)
if err != nil {
return nil, errors.Wrap(err, "unable to get list of pods")
return nil, fmt.Errorf("unable to get list of pods: %w", err)
}
return ic.podsToStatsReport(pods)
}

View File

@ -2,13 +2,13 @@ package terminal
import (
"context"
"fmt"
"os"
"os/signal"
"github.com/containers/common/pkg/resize"
lsignal "github.com/containers/podman/v4/pkg/signal"
"github.com/moby/term"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -89,7 +89,7 @@ func handleTerminalAttach(ctx context.Context, resize chan resize.TerminalSize)
if err != nil {
// allow caller to not have to do any cleaning up if we error here
cancel()
return nil, nil, errors.Wrapf(err, "unable to save terminal state")
return nil, nil, fmt.Errorf("unable to save terminal state: %w", err)
}
logrus.SetFormatter(&RawTtyFormatter{})

View File

@ -9,7 +9,6 @@ import (
"github.com/containers/common/pkg/resize"
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/libpod/define"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/term"
)
@ -104,7 +103,7 @@ func StartAttachCtr(ctx context.Context, ctr *libpod.Container, stdout, stderr,
err = <-attachChan
if err != nil {
return errors.Wrapf(err, "error attaching to container %s", ctr.ID())
return fmt.Errorf("error attaching to container %s: %w", ctr.ID(), err)
}
return nil

View File

@ -3,13 +3,14 @@ package abi
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/trust"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -35,11 +36,11 @@ func (ir *ImageEngine) ShowTrust(ctx context.Context, args []string, options ent
}
policyContentStruct, err := trust.GetPolicy(policyPath)
if err != nil {
return nil, errors.Wrapf(err, "could not read trust policies")
return nil, fmt.Errorf("could not read trust policies: %w", err)
}
report.Policies, err = getPolicyShowOutput(policyContentStruct, report.SystemRegistriesDirPath)
if err != nil {
return nil, errors.Wrapf(err, "could not show trust policies")
return nil, fmt.Errorf("could not show trust policies: %w", err)
}
return &report, nil
}
@ -56,7 +57,7 @@ func (ir *ImageEngine) SetTrust(ctx context.Context, args []string, options enti
pubkeysfile := options.PubKeysFile
if len(pubkeysfile) == 0 && trustType == "signedBy" {
return errors.Errorf("At least one public key must be defined for type 'signedBy'")
return errors.New("at least one public key must be defined for type 'signedBy'")
}
policyPath := trust.DefaultPolicyPath(ir.Libpod.SystemContext())
@ -70,7 +71,7 @@ func (ir *ImageEngine) SetTrust(ctx context.Context, args []string, options enti
return err
}
if err := json.Unmarshal(policyContent, &policyContentStruct); err != nil {
return errors.Errorf("could not read trust policies")
return errors.New("could not read trust policies")
}
}
if len(pubkeysfile) != 0 {
@ -84,7 +85,7 @@ func (ir *ImageEngine) SetTrust(ctx context.Context, args []string, options enti
policyContentStruct.Default = newReposContent
} else {
if len(policyContentStruct.Default) == 0 {
return errors.Errorf("default trust policy must be set")
return errors.New("default trust policy must be set")
}
registryExists := false
for transport, transportval := range policyContentStruct.Transports {
@ -107,7 +108,7 @@ func (ir *ImageEngine) SetTrust(ctx context.Context, args []string, options enti
data, err := json.MarshalIndent(policyContentStruct, "", " ")
if err != nil {
return errors.Wrapf(err, "error setting trust policy")
return fmt.Errorf("error setting trust policy: %w", err)
}
return ioutil.WriteFile(policyPath, data, 0644)
}

View File

@ -5,6 +5,7 @@ package infra
import (
"context"
"errors"
"fmt"
"os"
"os/signal"
@ -18,7 +19,6 @@ import (
"github.com/containers/podman/v4/pkg/rootless"
"github.com/containers/storage/pkg/idtools"
"github.com/containers/storage/types"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
flag "github.com/spf13/pflag"
)
@ -316,7 +316,7 @@ func ParseIDMapping(mode namespaces.UsernsMode, uidMapSlice, gidMapSlice []strin
uids, gids, err := rootless.GetConfiguredMappings()
if err != nil {
return nil, errors.Wrapf(err, "cannot read mappings")
return nil, fmt.Errorf("cannot read mappings: %w", err)
}
maxUID, maxGID := 0, 0
for _, u := range uids {

View File

@ -2,9 +2,9 @@ package tunnel
import (
"context"
"errors"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/pkg/errors"
)
func (ic *ContainerEngine) AutoUpdate(ctx context.Context, options entities.AutoUpdateOptions) ([]*entities.AutoUpdateReport, []error) {

View File

@ -2,13 +2,12 @@ package tunnel
import (
"context"
"fmt"
"strings"
"github.com/containers/podman/v4/libpod/events"
"github.com/containers/podman/v4/pkg/bindings/system"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/pkg/errors"
)
func (ic *ContainerEngine) Events(ctx context.Context, opts entities.EventsOptions) error {
@ -17,7 +16,7 @@ func (ic *ContainerEngine) Events(ctx context.Context, opts entities.EventsOptio
for _, filter := range opts.Filter {
split := strings.Split(filter, "=")
if len(split) < 2 {
return errors.Errorf("invalid filter %q", filter)
return fmt.Errorf("invalid filter %q", filter)
}
filters[split[0]] = append(filters[split[0]], strings.Join(split[1:], "="))
}
@ -56,7 +55,7 @@ func (ic *ContainerEngine) GetLastContainerEvent(ctx context.Context, nameOrID s
return nil, err
}
if len(containerEvents) < 1 {
return nil, errors.Wrapf(events.ErrEventNotFound, "%s not found", containerEvent.String())
return nil, fmt.Errorf("%s not found: %w", containerEvent.String(), events.ErrEventNotFound)
}
// return the last element in the slice
return containerEvents[len(containerEvents)-1], nil

View File

@ -2,13 +2,14 @@ package tunnel
import (
"context"
"errors"
"fmt"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/bindings/containers"
"github.com/containers/podman/v4/pkg/bindings/pods"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/errorhandling"
"github.com/pkg/errors"
)
// FIXME: the `ignore` parameter is very likely wrong here as it should rather
@ -69,7 +70,7 @@ func getContainersAndInputByContext(contextWithConnection context.Context, all,
}
if !found && !ignore {
return nil, nil, errors.Wrapf(define.ErrNoSuchCtr, "unable to find container %q", nameOrID)
return nil, nil, fmt.Errorf("unable to find container %q: %w", nameOrID, define.ErrNoSuchCtr)
}
}
return filtered, rawInputs, nil
@ -102,7 +103,7 @@ func getPodsByContext(contextWithConnection context.Context, all bool, namesOrID
inspectData, err := pods.Inspect(contextWithConnection, nameOrID, nil)
if err != nil {
if errorhandling.Contains(err, define.ErrNoSuchPod) {
return nil, errors.Wrapf(define.ErrNoSuchPod, "unable to find pod %q", nameOrID)
return nil, fmt.Errorf("unable to find pod %q: %w", nameOrID, define.ErrNoSuchPod)
}
return nil, err
}
@ -120,7 +121,7 @@ func getPodsByContext(contextWithConnection context.Context, all bool, namesOrID
}
if !found {
return nil, errors.Wrapf(define.ErrNoSuchPod, "unable to find pod %q", nameOrID)
return nil, fmt.Errorf("unable to find pod %q: %w", nameOrID, define.ErrNoSuchPod)
}
}
return filtered, nil

View File

@ -2,6 +2,7 @@ package tunnel
import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
@ -19,7 +20,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/utils"
"github.com/containers/podman/v4/pkg/errorhandling"
utils2 "github.com/containers/podman/v4/utils"
"github.com/pkg/errors"
)
func (ir *ImageEngine) Exists(_ context.Context, nameOrID string) (*entities.BoolReport, error) {
@ -131,7 +131,7 @@ func (ir *ImageEngine) Tag(ctx context.Context, nameOrID string, tags []string,
)
ref, err := reference.Parse(newTag)
if err != nil {
return errors.Wrapf(err, "error parsing reference %q", newTag)
return fmt.Errorf("error parsing reference %q: %w", newTag, err)
}
if t, ok := ref.(reference.Tagged); ok {
tag = t.Tag()
@ -140,7 +140,7 @@ func (ir *ImageEngine) Tag(ctx context.Context, nameOrID string, tags []string,
repo = r.Name()
}
if len(repo) < 1 {
return errors.Errorf("invalid image name %q", nameOrID)
return fmt.Errorf("invalid image name %q", nameOrID)
}
if err := images.Tag(ir.ClientCtx, nameOrID, tag, repo, options); err != nil {
return err
@ -161,7 +161,7 @@ func (ir *ImageEngine) Untag(ctx context.Context, nameOrID string, tags []string
)
ref, err := reference.Parse(newTag)
if err != nil {
return errors.Wrapf(err, "error parsing reference %q", newTag)
return fmt.Errorf("error parsing reference %q: %w", newTag, err)
}
if t, ok := ref.(reference.Tagged); ok {
tag = t.Tag()
@ -173,7 +173,7 @@ func (ir *ImageEngine) Untag(ctx context.Context, nameOrID string, tags []string
repo = r.Name()
}
if len(repo) < 1 {
return errors.Errorf("invalid image name %q", nameOrID)
return fmt.Errorf("invalid image name %q", nameOrID)
}
if err := images.Untag(ir.ClientCtx, nameOrID, tag, repo, options); err != nil {
return err
@ -194,7 +194,7 @@ func (ir *ImageEngine) Inspect(ctx context.Context, namesOrIDs []string, opts en
return nil, nil, err
}
if errModel.ResponseCode == 404 {
errs = append(errs, errors.Wrapf(err, "unable to inspect %q", i))
errs = append(errs, fmt.Errorf("unable to inspect %q: %w", i, err))
continue
}
return nil, nil, err
@ -215,7 +215,7 @@ func (ir *ImageEngine) Load(ctx context.Context, opts entities.ImageLoadOptions)
return nil, err
}
if fInfo.IsDir() {
return nil, errors.Errorf("remote client supports archives only but %q is a directory", opts.Input)
return nil, fmt.Errorf("remote client supports archives only but %q is a directory", opts.Input)
}
return images.Load(ir.ClientCtx, f)
}
@ -296,7 +296,7 @@ func (ir *ImageEngine) Save(ctx context.Context, nameOrID string, tags []string,
switch {
case err == nil:
if info.Mode().IsRegular() {
return errors.Errorf("%q already exists as a regular file", opts.Output)
return fmt.Errorf("%q already exists as a regular file", opts.Output)
}
case os.IsNotExist(err):
if err := os.Mkdir(opts.Output, 0755); err != nil {

View File

@ -3,6 +3,7 @@ package tunnel
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
@ -10,7 +11,6 @@ import (
"github.com/containers/podman/v4/pkg/bindings/images"
"github.com/containers/podman/v4/pkg/bindings/manifests"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/pkg/errors"
)
// ManifestCreate implements manifest create via ImageEngine
@ -18,7 +18,7 @@ func (ir *ImageEngine) ManifestCreate(ctx context.Context, name string, images [
options := new(manifests.CreateOptions).WithAll(opts.All)
imageID, err := manifests.Create(ir.ClientCtx, name, images, options)
if err != nil {
return imageID, errors.Wrapf(err, "error creating manifest")
return imageID, fmt.Errorf("error creating manifest: %w", err)
}
return imageID, err
}
@ -36,12 +36,12 @@ func (ir *ImageEngine) ManifestExists(ctx context.Context, name string) (*entiti
func (ir *ImageEngine) ManifestInspect(_ context.Context, name string) ([]byte, error) {
list, err := manifests.Inspect(ir.ClientCtx, name, nil)
if err != nil {
return nil, errors.Wrapf(err, "error getting content of manifest list or image %s", name)
return nil, fmt.Errorf("error getting content of manifest list or image %s: %w", name, err)
}
buf, err := json.MarshalIndent(list, "", " ")
if err != nil {
return buf, errors.Wrapf(err, "error rendering manifest for display")
return buf, fmt.Errorf("error rendering manifest for display: %w", err)
}
return buf, err
}
@ -56,7 +56,7 @@ func (ir *ImageEngine) ManifestAdd(_ context.Context, name string, imageNames []
for _, annotationSpec := range opts.Annotation {
spec := strings.SplitN(annotationSpec, "=", 2)
if len(spec) != 2 {
return "", errors.Errorf("no value given for annotation %q", spec[0])
return "", fmt.Errorf("no value given for annotation %q", spec[0])
}
annotations[spec[0]] = spec[1]
}
@ -72,7 +72,7 @@ func (ir *ImageEngine) ManifestAdd(_ context.Context, name string, imageNames []
id, err := manifests.Add(ir.ClientCtx, name, options)
if err != nil {
return id, errors.Wrapf(err, "error adding to manifest list %s", name)
return id, fmt.Errorf("error adding to manifest list %s: %w", name, err)
}
return id, nil
}
@ -86,7 +86,7 @@ func (ir *ImageEngine) ManifestAnnotate(ctx context.Context, name, images string
func (ir *ImageEngine) ManifestRemoveDigest(ctx context.Context, name string, image string) (string, error) {
updatedListID, err := manifests.Remove(ir.ClientCtx, name, image, nil)
if err != nil {
return updatedListID, errors.Wrapf(err, "error removing from manifest %s", name)
return updatedListID, fmt.Errorf("error removing from manifest %s: %w", name, err)
}
return fmt.Sprintf("%s :%s\n", updatedListID, image), nil
}

View File

@ -2,13 +2,14 @@ package tunnel
import (
"context"
"errors"
"fmt"
"github.com/containers/common/libnetwork/types"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/bindings/network"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/errorhandling"
"github.com/pkg/errors"
)
func (ic *ContainerEngine) NetworkList(ctx context.Context, opts entities.NetworkListOptions) ([]types.Network, error) {
@ -30,7 +31,7 @@ func (ic *ContainerEngine) NetworkInspect(ctx context.Context, namesOrIds []stri
return nil, nil, err
}
if errModel.ResponseCode == 404 {
errs = append(errs, errors.Wrapf(define.ErrNoSuchNetwork, "network %s", name))
errs = append(errs, fmt.Errorf("network %s: %w", name, define.ErrNoSuchNetwork))
continue
}
return nil, nil, err

View File

@ -2,12 +2,12 @@ package tunnel
import (
"context"
"fmt"
"io"
"github.com/containers/podman/v4/pkg/bindings/secrets"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/errorhandling"
"github.com/pkg/errors"
)
func (ic *ContainerEngine) SecretCreate(ctx context.Context, name string, reader io.Reader, options entities.SecretCreateOptions) (*entities.SecretCreateReport, error) {
@ -33,7 +33,7 @@ func (ic *ContainerEngine) SecretInspect(ctx context.Context, nameOrIDs []string
return nil, nil, err
}
if errModel.ResponseCode == 404 {
errs = append(errs, errors.Errorf("no such secret %q", name))
errs = append(errs, fmt.Errorf("no such secret %q", name))
continue
}
return nil, nil, err
@ -73,7 +73,7 @@ func (ic *ContainerEngine) SecretRm(ctx context.Context, nameOrIDs []string, opt
}
if errModel.ResponseCode == 404 {
allRm = append(allRm, &entities.SecretRmReport{
Err: errors.Errorf("no secret with name or id %q: no such secret ", name),
Err: fmt.Errorf("no secret with name or id %q: no such secret ", name),
ID: "",
})
continue

View File

@ -2,12 +2,13 @@ package tunnel
import (
"context"
"errors"
"fmt"
"github.com/containers/podman/v4/pkg/bindings/volumes"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/domain/entities/reports"
"github.com/containers/podman/v4/pkg/errorhandling"
"github.com/pkg/errors"
)
func (ic *ContainerEngine) VolumeCreate(ctx context.Context, opts entities.VolumeCreateOptions) (*entities.IDOrNameResponse, error) {
@ -64,7 +65,7 @@ func (ic *ContainerEngine) VolumeInspect(ctx context.Context, namesOrIds []strin
return nil, nil, err
}
if errModel.ResponseCode == 404 {
errs = append(errs, errors.Errorf("no such volume %q", id))
errs = append(errs, fmt.Errorf("no such volume %q", id))
continue
}
return nil, nil, err

View File

@ -20,7 +20,6 @@ import (
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/terminal"
"github.com/docker/distribution/reference"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
@ -44,7 +43,7 @@ func ExecuteTransfer(src, dst string, parentFlags []string, quiet bool) (*entiti
confR, err := config.NewConfig("") // create a hand made config for the remote engine since we might use remote and native at once
if err != nil {
return nil, nil, nil, nil, errors.Wrapf(err, "could not make config")
return nil, nil, nil, nil, fmt.Errorf("could not make config: %w", err)
}
cfg, err := config.ReadCustomConfig() // get ready to set ssh destination if necessary
@ -75,9 +74,9 @@ func ExecuteTransfer(src, dst string, parentFlags []string, quiet bool) (*entiti
case len(locations) == 1:
switch {
case len(locations[0].Image) == 0:
return nil, nil, nil, nil, errors.Wrapf(define.ErrInvalidArg, "no source image specified")
return nil, nil, nil, nil, fmt.Errorf("no source image specified: %w", define.ErrInvalidArg)
case len(locations[0].Image) > 0 && !locations[0].Remote && len(locations[0].User) == 0: // if we have podman image scp $IMAGE
return nil, nil, nil, nil, errors.Wrapf(define.ErrInvalidArg, "must specify a destination")
return nil, nil, nil, nil, fmt.Errorf("must specify a destination: %w", define.ErrInvalidArg)
}
}
@ -158,7 +157,7 @@ func ExecuteTransfer(src, dst string, parentFlags []string, quiet bool) (*entiti
if source.User == "" {
u, err := user.Current()
if err != nil {
return nil, nil, nil, nil, errors.Wrapf(err, "could not obtain user, make sure the environmental variable $USER is set")
return nil, nil, nil, nil, fmt.Errorf("could not obtain user, make sure the environmental variable $USER is set: %w", err)
}
source.User = u.Username
}
@ -231,11 +230,11 @@ func LoadToRemote(dest entities.ImageScpOptions, localFile string, tag string, u
n, err := scpD.CopyTo(dial, localFile, remoteFile)
if err != nil {
errOut := strconv.Itoa(int(n)) + " Bytes copied before error"
return " ", "", errors.Wrapf(err, errOut)
return " ", "", fmt.Errorf("%v: %w", errOut, err)
}
var run string
if tag != "" {
return "", "", errors.Wrapf(define.ErrInvalidArg, "Renaming of an image is currently not supported")
return "", "", fmt.Errorf("renaming of an image is currently not supported: %w", define.ErrInvalidArg)
}
podman := os.Args[0]
run = podman + " image load --input=" + remoteFile + ";rm " + remoteFile // run ssh image load of the file copied via scp
@ -268,7 +267,7 @@ func SaveToRemote(image, localFile string, tag string, uri *url.URL, iden string
defer dial.Close()
if tag != "" {
return errors.Wrapf(define.ErrInvalidArg, "Renaming of an image is currently not supported")
return fmt.Errorf("renaming of an image is currently not supported: %w", define.ErrInvalidArg)
}
podman := os.Args[0]
run := podman + " image save " + image + " --format=oci-archive --output=" + remoteFile // run ssh image load of the file copied via scp. Files are reverse in this case...
@ -282,7 +281,7 @@ func SaveToRemote(image, localFile string, tag string, uri *url.URL, iden string
}
if err != nil {
errOut := strconv.Itoa(int(n)) + " Bytes copied before error"
return errors.Wrapf(err, errOut)
return fmt.Errorf("%v: %w", errOut, err)
}
return nil
}
@ -307,7 +306,7 @@ func CreateConnection(url *url.URL, iden string) (*ssh.Client, string, error) {
}
dialAdd, err := ssh.Dial("tcp", url.Host, cfg) // dial the client
if err != nil {
return nil, "", errors.Wrapf(err, "failed to connect")
return nil, "", fmt.Errorf("failed to connect: %w", err)
}
file, err := MakeRemoteFile(dialAdd)
if err != nil {
@ -429,14 +428,14 @@ func ValidateImagePortion(location entities.ImageScpOptions, arg string) (entiti
// validateSCPArgs takes the array of source and destination options and checks for common errors
func ValidateSCPArgs(locations []*entities.ImageScpOptions) error {
if len(locations) > 2 {
return errors.Wrapf(define.ErrInvalidArg, "cannot specify more than two arguments")
return fmt.Errorf("cannot specify more than two arguments: %w", define.ErrInvalidArg)
}
switch {
case len(locations[0].Image) > 0 && len(locations[1].Image) > 0:
locations[1].Tag = locations[1].Image
locations[1].Image = ""
case len(locations[0].Image) == 0 && len(locations[1].Image) == 0:
return errors.Wrapf(define.ErrInvalidArg, "a source image must be specified")
return fmt.Errorf("a source image must be specified: %w", define.ErrInvalidArg)
}
return nil
}
@ -475,7 +474,7 @@ func ExecRemoteCommand(dial *ssh.Client, run string) ([]byte, error) {
sess.Stdout = &buffer // output from client funneled into buffer
sess.Stderr = &bufferErr // err form client funneled into buffer
if err := sess.Run(run); err != nil { // run the command on the ssh client
return nil, errors.Wrapf(err, bufferErr.String())
return nil, fmt.Errorf("%v: %w", bufferErr.String(), err)
}
return buffer.Bytes(), nil
}
@ -488,12 +487,12 @@ func GetUserInfo(uri *url.URL) (*url.Userinfo, error) {
if u, found := os.LookupEnv("_CONTAINERS_ROOTLESS_UID"); found {
usr, err = user.LookupId(u)
if err != nil {
return nil, errors.Wrapf(err, "failed to lookup rootless user")
return nil, fmt.Errorf("failed to lookup rootless user: %w", err)
}
} else {
usr, err = user.Current()
if err != nil {
return nil, errors.Wrapf(err, "failed to obtain current user")
return nil, fmt.Errorf("failed to obtain current user: %w", err)
}
}
@ -514,7 +513,7 @@ func ValidateAndConfigure(uri *url.URL, iden string) (*ssh.ClientConfig, error)
value := iden
s, err := terminal.PublicKey(value, []byte(passwd))
if err != nil {
return nil, errors.Wrapf(err, "failed to read identity %q", value)
return nil, fmt.Errorf("failed to read identity %q: %w", value, err)
}
signers = append(signers, s)
logrus.Debugf("SSH Ident Key %q %s %s", value, ssh.FingerprintSHA256(s.PublicKey()), s.PublicKey().Type())

View File

@ -1,11 +1,11 @@
package utils
import (
"fmt"
"strings"
"github.com/containers/common/pkg/secrets"
"github.com/containers/podman/v4/pkg/util"
"github.com/pkg/errors"
)
func IfPassesSecretsFilter(s secrets.Secret, filters map[string][]string) (bool, error) {
@ -17,7 +17,7 @@ func IfPassesSecretsFilter(s secrets.Secret, filters map[string][]string) (bool,
case "id":
result = util.StringMatchRegexSlice(s.ID, filterValues)
default:
return false, errors.Errorf("invalid filter %q", key)
return false, fmt.Errorf("invalid filter %q", key)
}
}
return result, nil

8
pkg/env/env.go vendored
View File

@ -8,8 +8,6 @@ import (
"fmt"
"os"
"strings"
"github.com/pkg/errors"
)
const whiteSpaces = " \t"
@ -56,7 +54,7 @@ func ParseFile(path string) (_ map[string]string, err error) {
env := make(map[string]string)
defer func() {
if err != nil {
err = errors.Wrapf(err, "error parsing env file %q", path)
err = fmt.Errorf("error parsing env file %q: %w", path, err)
}
}()
@ -85,12 +83,12 @@ func parseEnv(env map[string]string, line string) error {
// catch invalid variables such as "=" or "=A"
if data[0] == "" {
return errors.Errorf("invalid environment variable: %q", line)
return fmt.Errorf("invalid environment variable: %q", line)
}
// trim the front of a variable, but nothing else
name := strings.TrimLeft(data[0], whiteSpaces)
if strings.ContainsAny(name, whiteSpaces) {
return errors.Errorf("name %q has white spaces, poorly formatted name", name)
return fmt.Errorf("name %q has white spaces, poorly formatted name", name)
}
if len(data) > 1 {

View File

@ -3,12 +3,12 @@ package hook
import (
"encoding/json"
"errors"
"fmt"
"os"
"regexp"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
)
// Version is the hook configuration version defined in this package.
@ -50,16 +50,16 @@ func (hook *Hook) Validate(extensionStages []string) (err error) {
for key, value := range hook.When.Annotations {
if _, err = regexp.Compile(key); err != nil {
return errors.Wrapf(err, "invalid annotation key %q", key)
return fmt.Errorf("invalid annotation key %q: %w", key, err)
}
if _, err = regexp.Compile(value); err != nil {
return errors.Wrapf(err, "invalid annotation value %q", value)
return fmt.Errorf("invalid annotation value %q: %w", value, err)
}
}
for _, command := range hook.When.Commands {
if _, err = regexp.Compile(command); err != nil {
return errors.Wrapf(err, "invalid command %q", command)
return fmt.Errorf("invalid command %q: %w", command, err)
}
}

View File

@ -1,10 +1,11 @@
package hook
import (
"errors"
"fmt"
"regexp"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
)
// When holds hook-injection conditions.
@ -52,12 +53,12 @@ func (when *When) Match(config *rspec.Spec, annotations map[string]string, hasBi
for key, value := range annotations {
match, err = regexp.MatchString(keyPattern, key)
if err != nil {
return false, errors.Wrap(err, "annotation key")
return false, fmt.Errorf("annotation key: %w", err)
}
if match {
match, err = regexp.MatchString(valuePattern, value)
if err != nil {
return false, errors.Wrap(err, "annotation value")
return false, fmt.Errorf("annotation value: %w", err)
}
if match {
break
@ -82,7 +83,7 @@ func (when *When) Match(config *rspec.Spec, annotations map[string]string, hasBi
for _, cmdPattern := range when.Commands {
match, err := regexp.MatchString(cmdPattern, command)
if err != nil {
return false, errors.Wrap(err, "command")
return false, fmt.Errorf("command: %w", err)
}
if match {
return true, nil

View File

@ -10,7 +10,6 @@ import (
"time"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -46,7 +45,7 @@ func Run(ctx context.Context, hook *rspec.Hook, state []byte, stdout io.Writer,
go func() {
err := cmd.Wait()
if err != nil {
err = errors.Wrapf(err, "executing %v", cmd.Args)
err = fmt.Errorf("executing %v: %w", cmd.Args, err)
}
exit <- err
}()

View File

@ -4,12 +4,12 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"reflect"
"time"
"github.com/davecgh/go-spew/spew"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/pmezard/go-difflib/difflib"
"github.com/sirupsen/logrus"
)
@ -43,7 +43,7 @@ func RuntimeConfigFilter(ctx context.Context, hooks []spec.Hook, config *spec.Sp
err = json.Unmarshal(data, &newConfig)
if err != nil {
logrus.Debugf("invalid JSON from config-filter hook %d:\n%s", i, string(data))
return nil, errors.Wrapf(err, "unmarshal output from config-filter hook %d", i)
return nil, fmt.Errorf("unmarshal output from config-filter hook %d: %w", i, err)
}
if !reflect.DeepEqual(config, &newConfig) {

View File

@ -11,7 +11,6 @@ import (
current "github.com/containers/podman/v4/pkg/hooks/1.0.0"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -105,7 +104,7 @@ func (m *Manager) Hooks(config *rspec.Spec, annotations map[string]string, hasBi
for _, namedHook := range hooks {
match, err := namedHook.hook.When.Match(config, annotations, hasBindMounts)
if err != nil {
return extensionStageHooks, errors.Wrapf(err, "matching hook %q", namedHook.name)
return extensionStageHooks, fmt.Errorf("matching hook %q: %w", namedHook.name, err)
}
if match {
logrus.Debugf("hook %s matched; adding to stages %v", namedHook.name, namedHook.hook.Stages)

View File

@ -3,6 +3,8 @@ package hooks
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
@ -10,7 +12,6 @@ import (
old "github.com/containers/podman/v4/pkg/hooks/0.1.0"
current "github.com/containers/podman/v4/pkg/hooks/1.0.0"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -36,7 +37,7 @@ func Read(path string, extensionStages []string) (*current.Hook, error) {
}
hook, err := read(content)
if err != nil {
return nil, errors.Wrapf(err, "parsing hook %q", path)
return nil, fmt.Errorf("parsing hook %q: %w", path, err)
}
err = hook.Validate(extensionStages)
return hook, err
@ -45,16 +46,16 @@ func Read(path string, extensionStages []string) (*current.Hook, error) {
func read(content []byte) (hook *current.Hook, err error) {
var ver version
if err := json.Unmarshal(content, &ver); err != nil {
return nil, errors.Wrap(err, "version check")
return nil, fmt.Errorf("version check: %w", err)
}
reader, ok := Readers[ver.Version]
if !ok {
return nil, errors.Errorf("unrecognized hook version: %q", ver.Version)
return nil, fmt.Errorf("unrecognized hook version: %q", ver.Version)
}
hook, err = reader(content)
if err != nil {
return hook, errors.Wrap(err, ver.Version)
return hook, fmt.Errorf("%v: %w", ver.Version, err)
}
return hook, err
}
@ -83,7 +84,7 @@ func ReadDir(path string, extensionStages []string, hooks map[string]*current.Ho
if res == nil {
res = err
} else {
res = errors.Wrapf(res, "%v", err)
res = fmt.Errorf("%v: %w", err, res)
}
continue
}

View File

@ -4,7 +4,7 @@
package machine
import (
errors2 "errors"
"errors"
"io/ioutil"
"net"
"net/url"
@ -13,7 +13,6 @@ import (
"time"
"github.com/containers/storage/pkg/homedir"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -256,11 +255,11 @@ func (m *VMFile) GetPath() string {
// the actual path
func (m *VMFile) Delete() error {
if m.Symlink != nil {
if err := os.Remove(*m.Symlink); err != nil && !errors2.Is(err, os.ErrNotExist) {
if err := os.Remove(*m.Symlink); err != nil && !errors.Is(err, os.ErrNotExist) {
logrus.Errorf("unable to remove symlink %q", *m.Symlink)
}
}
if err := os.Remove(m.Path); err != nil && !errors2.Is(err, os.ErrNotExist) {
if err := os.Remove(m.Path); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
@ -274,14 +273,14 @@ func (m *VMFile) Read() ([]byte, error) {
// NewMachineFile is a constructor for VMFile
func NewMachineFile(path string, symlink *string) (*VMFile, error) {
if len(path) < 1 {
return nil, errors2.New("invalid machine file path")
return nil, errors.New("invalid machine file path")
}
if symlink != nil && len(*symlink) < 1 {
return nil, errors2.New("invalid symlink path")
return nil, errors.New("invalid symlink path")
}
mf := VMFile{Path: path}
if symlink != nil && len(path) > maxSocketPathLength {
if err := mf.makeSymlink(symlink); err != nil && !errors2.Is(err, os.ErrExist) {
if err := mf.makeSymlink(symlink); err != nil && !errors.Is(err, os.ErrExist) {
return nil, err
}
}
@ -297,7 +296,7 @@ func (m *VMFile) makeSymlink(symlink *string) error {
}
sl := filepath.Join(homeDir, ".podman", *symlink)
// make the symlink dir and throw away if it already exists
if err := os.MkdirAll(filepath.Dir(sl), 0700); err != nil && !errors2.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(filepath.Dir(sl), 0700); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
m.Symlink = &sl

View File

@ -4,10 +4,10 @@
package machine
import (
"errors"
"fmt"
"github.com/containers/common/pkg/config"
"github.com/pkg/errors"
)
func AddConnection(uri fmt.Stringer, name, identity string, isDefault bool) error {
@ -72,7 +72,7 @@ func RemoveConnection(name string) error {
if _, ok := cfg.Engine.ServiceDestinations[name]; ok {
delete(cfg.Engine.ServiceDestinations, name)
} else {
return errors.Errorf("unable to find connection named %q", name)
return fmt.Errorf("unable to find connection named %q", name)
}
return cfg.Write()
}

View File

@ -17,7 +17,6 @@ import (
"github.com/coreos/stream-metadata-go/fedoracoreos"
"github.com/coreos/stream-metadata-go/release"
"github.com/coreos/stream-metadata-go/stream"
"github.com/pkg/errors"
digest "github.com/opencontainers/go-digest"
"github.com/sirupsen/logrus"
@ -156,7 +155,7 @@ func GetFCOSDownload(imageStream string) (*FcosDownloadInfo, error) {
case "stable":
streamType = fedoracoreos.StreamStable
default:
return nil, errors.Errorf("invalid stream %s: valid streams are `testing` and `stable`", imageStream)
return nil, fmt.Errorf("invalid stream %s: valid streams are `testing` and `stable`", imageStream)
}
streamurl := getStreamURL(streamType)
resp, err := http.Get(streamurl.String())

View File

@ -4,6 +4,7 @@
package machine
import (
"errors"
"fmt"
"io"
"io/ioutil"
@ -13,7 +14,6 @@ import (
"path/filepath"
"regexp"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -107,12 +107,12 @@ func getFedoraDownload(releaseStream string) (string, *url.URL, int64, error) {
newLocation := rawURL + file
downloadURL, err := url.Parse(newLocation)
if err != nil {
return "", nil, -1, errors.Wrapf(err, "invalid URL generated from discovered Fedora file: %s", newLocation)
return "", nil, -1, fmt.Errorf("invalid URL generated from discovered Fedora file: %s: %w", newLocation, err)
}
resp, err := http.Head(newLocation)
if err != nil {
return "", nil, -1, errors.Wrapf(err, "head request failed: %s", newLocation)
return "", nil, -1, fmt.Errorf("head request failed: %s: %w", newLocation, err)
}
_ = resp.Body.Close()

View File

@ -4,6 +4,7 @@
package machine
import (
"errors"
"fmt"
"io"
"io/ioutil"
@ -12,7 +13,6 @@ import (
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)

View File

@ -6,6 +6,7 @@ package wsl
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
@ -22,7 +23,6 @@ import (
"github.com/containers/podman/v4/pkg/machine"
"github.com/containers/podman/v4/utils"
"github.com/containers/storage/pkg/homedir"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/text/encoding/unicode"
"golang.org/x/text/transform"
@ -277,7 +277,7 @@ func readAndMigrate(configPath string, name string) (*MachineVM, error) {
b, err := os.ReadFile(configPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, errors.Wrap(machine.ErrNoSuchVM, name)
return nil, fmt.Errorf("%v: %w", name, machine.ErrNoSuchVM)
}
return vm, err
}
@ -407,7 +407,7 @@ func (v *MachineVM) writeConfig() error {
return err
}
if err := ioutil.WriteFile(jsonFile, b, 0644); err != nil {
return errors.Wrap(err, "could not write machine json config")
return fmt.Errorf("could not write machine json config: %w", err)
}
return nil
@ -445,38 +445,38 @@ func provisionWSLDist(v *MachineVM) (string, error) {
distDir := filepath.Join(vmDataDir, "wsldist")
distTarget := filepath.Join(distDir, v.Name)
if err := os.MkdirAll(distDir, 0755); err != nil {
return "", errors.Wrap(err, "could not create wsldist directory")
return "", fmt.Errorf("could not create wsldist directory: %w", err)
}
dist := toDist(v.Name)
fmt.Println("Importing operating system into WSL (this may take 5+ minutes on a new WSL install)...")
if err = runCmdPassThrough("wsl", "--import", dist, distTarget, v.ImagePath); err != nil {
return "", errors.Wrap(err, "WSL import of guest OS failed")
return "", fmt.Errorf("the WSL import of guest OS failed: %w", err)
}
fmt.Println("Installing packages (this will take awhile)...")
if err = runCmdPassThrough("wsl", "-d", dist, "dnf", "upgrade", "-y"); err != nil {
return "", errors.Wrap(err, "package upgrade on guest OS failed")
return "", fmt.Errorf("package upgrade on guest OS failed: %w", err)
}
fmt.Println("Enabling Copr")
if err = runCmdPassThrough("wsl", "-d", dist, "dnf", "install", "-y", "'dnf-command(copr)'"); err != nil {
return "", errors.Wrap(err, "enabling copr failed")
return "", fmt.Errorf("enabling copr failed: %w", err)
}
fmt.Println("Enabling podman4 repo")
if err = runCmdPassThrough("wsl", "-d", dist, "dnf", "-y", "copr", "enable", "rhcontainerbot/podman4"); err != nil {
return "", errors.Wrap(err, "enabling copr failed")
return "", fmt.Errorf("enabling copr failed: %w", err)
}
if err = runCmdPassThrough("wsl", "-d", dist, "dnf", "install",
"podman", "podman-docker", "openssh-server", "procps-ng", "-y"); err != nil {
return "", errors.Wrap(err, "package installation on guest OS failed")
return "", fmt.Errorf("package installation on guest OS failed: %w", err)
}
// Fixes newuidmap
if err = runCmdPassThrough("wsl", "-d", dist, "dnf", "reinstall", "shadow-utils", "-y"); err != nil {
return "", errors.Wrap(err, "package reinstallation of shadow-utils on guest OS failed")
return "", fmt.Errorf("package reinstallation of shadow-utils on guest OS failed: %w", err)
}
// Windows 11 (NT Version = 10, Build 22000) generates harmless but scary messages on every
@ -495,28 +495,28 @@ func createKeys(v *MachineVM, dist string, sshDir string) error {
user := v.RemoteUsername
if err := os.MkdirAll(sshDir, 0700); err != nil {
return errors.Wrap(err, "could not create ssh directory")
return fmt.Errorf("could not create ssh directory: %w", err)
}
if err := runCmdPassThrough("wsl", "--terminate", dist); err != nil {
return errors.Wrap(err, "could not cycle WSL dist")
return fmt.Errorf("could not cycle WSL dist: %w", err)
}
key, err := machine.CreateSSHKeysPrefix(sshDir, v.Name, true, true, "wsl", "-d", dist)
if err != nil {
return errors.Wrap(err, "could not create ssh keys")
return fmt.Errorf("could not create ssh keys: %w", err)
}
if err := pipeCmdPassThrough("wsl", key+"\n", "-d", dist, "sh", "-c", "mkdir -p /root/.ssh;"+
"cat >> /root/.ssh/authorized_keys; chmod 600 /root/.ssh/authorized_keys"); err != nil {
return errors.Wrap(err, "could not create root authorized keys on guest OS")
return fmt.Errorf("could not create root authorized keys on guest OS: %w", err)
}
userAuthCmd := withUser("mkdir -p /home/[USER]/.ssh;"+
"cat >> /home/[USER]/.ssh/authorized_keys; chown -R [USER]:[USER] /home/[USER]/.ssh;"+
"chmod 600 /home/[USER]/.ssh/authorized_keys", user)
if err := pipeCmdPassThrough("wsl", key+"\n", "-d", dist, "sh", "-c", userAuthCmd); err != nil {
return errors.Wrapf(err, "could not create '%s' authorized keys on guest OS", v.RemoteUsername)
return fmt.Errorf("could not create '%s' authorized keys on guest OS: %w", v.RemoteUsername, err)
}
return nil
@ -525,25 +525,25 @@ func createKeys(v *MachineVM, dist string, sshDir string) error {
func configureSystem(v *MachineVM, dist string) error {
user := v.RemoteUsername
if err := runCmdPassThrough("wsl", "-d", dist, "sh", "-c", fmt.Sprintf(appendPort, v.Port, v.Port)); err != nil {
return errors.Wrap(err, "could not configure SSH port for guest OS")
return fmt.Errorf("could not configure SSH port for guest OS: %w", err)
}
if err := pipeCmdPassThrough("wsl", withUser(configServices, user), "-d", dist, "sh"); err != nil {
return errors.Wrap(err, "could not configure systemd settings for guest OS")
return fmt.Errorf("could not configure systemd settings for guest OS: %w", err)
}
if err := pipeCmdPassThrough("wsl", sudoers, "-d", dist, "sh", "-c", "cat >> /etc/sudoers"); err != nil {
return errors.Wrap(err, "could not add wheel to sudoers")
return fmt.Errorf("could not add wheel to sudoers: %w", err)
}
if err := pipeCmdPassThrough("wsl", overrideSysusers, "-d", dist, "sh", "-c",
"cat > /etc/systemd/system/systemd-sysusers.service.d/override.conf"); err != nil {
return errors.Wrap(err, "could not generate systemd-sysusers override for guest OS")
return fmt.Errorf("could not generate systemd-sysusers override for guest OS: %w", err)
}
lingerCmd := withUser("cat > /home/[USER]/.config/systemd/[USER]/linger-example.service", user)
if err := pipeCmdPassThrough("wsl", lingerService, "-d", dist, "sh", "-c", lingerCmd); err != nil {
return errors.Wrap(err, "could not generate linger service for guest OS")
return fmt.Errorf("could not generate linger service for guest OS: %w", err)
}
if err := enableUserLinger(v, dist); err != nil {
@ -551,15 +551,15 @@ func configureSystem(v *MachineVM, dist string) error {
}
if err := pipeCmdPassThrough("wsl", withUser(lingerSetup, user), "-d", dist, "sh"); err != nil {
return errors.Wrap(err, "could not configure systemd settomgs for guest OS")
return fmt.Errorf("could not configure systemd settomgs for guest OS: %w", err)
}
if err := pipeCmdPassThrough("wsl", containersConf, "-d", dist, "sh", "-c", "cat > /etc/containers/containers.conf"); err != nil {
return errors.Wrap(err, "could not create containers.conf for guest OS")
return fmt.Errorf("could not create containers.conf for guest OS: %w", err)
}
if err := runCmdPassThrough("wsl", "-d", dist, "sh", "-c", "echo wsl > /etc/containers/podman-machine"); err != nil {
return errors.Wrap(err, "could not create podman-machine file for guest OS")
return fmt.Errorf("could not create podman-machine file for guest OS: %w", err)
}
return nil
@ -584,7 +584,7 @@ func configureProxy(dist string, useProxy bool) error {
if err := pipeCmdPassThrough("wsl", content, "-d", dist, "sh", "-c", proxyConfigAttempt); err != nil {
const failMessage = "Failure creating proxy configuration"
if exitErr, isExit := err.(*exec.ExitError); isExit && exitErr.ExitCode() != 42 {
return errors.Wrap(err, failMessage)
return fmt.Errorf("%v: %w", failMessage, err)
}
fmt.Println("Installing proxy support")
@ -592,7 +592,7 @@ func configureProxy(dist string, useProxy bool) error {
"cat > /usr/local/bin/proxyinit; chmod 755 /usr/local/bin/proxyinit")
if err = pipeCmdPassThrough("wsl", content, "-d", dist, "/usr/local/bin/proxyinit"); err != nil {
return errors.Wrap(err, failMessage)
return fmt.Errorf("%v: %w", failMessage, err)
}
}
@ -602,7 +602,7 @@ func configureProxy(dist string, useProxy bool) error {
func enableUserLinger(v *MachineVM, dist string) error {
lingerCmd := "mkdir -p /var/lib/systemd/linger; touch /var/lib/systemd/linger/" + v.RemoteUsername
if err := runCmdPassThrough("wsl", "-d", dist, "sh", "-c", lingerCmd); err != nil {
return errors.Wrap(err, "could not enable linger for remote user on guest OS")
return fmt.Errorf("could not enable linger for remote user on guest OS: %w", err)
}
return nil
@ -611,26 +611,26 @@ func enableUserLinger(v *MachineVM, dist string) error {
func installScripts(dist string) error {
if err := pipeCmdPassThrough("wsl", enterns, "-d", dist, "sh", "-c",
"cat > /usr/local/bin/enterns; chmod 755 /usr/local/bin/enterns"); err != nil {
return errors.Wrap(err, "could not create enterns script for guest OS")
return fmt.Errorf("could not create enterns script for guest OS: %w", err)
}
if err := pipeCmdPassThrough("wsl", profile, "-d", dist, "sh", "-c",
"cat > /etc/profile.d/enterns.sh"); err != nil {
return errors.Wrap(err, "could not create motd profile script for guest OS")
return fmt.Errorf("could not create motd profile script for guest OS: %w", err)
}
if err := pipeCmdPassThrough("wsl", wslmotd, "-d", dist, "sh", "-c", "cat > /etc/wslmotd"); err != nil {
return errors.Wrap(err, "could not create a WSL MOTD for guest OS")
return fmt.Errorf("could not create a WSL MOTD for guest OS: %w", err)
}
if err := pipeCmdPassThrough("wsl", bootstrap, "-d", dist, "sh", "-c",
"cat > /root/bootstrap; chmod 755 /root/bootstrap"); err != nil {
return errors.Wrap(err, "could not create bootstrap script for guest OS")
return fmt.Errorf("could not create bootstrap script for guest OS: %w", err)
}
if err := pipeCmdPassThrough("wsl", proxyConfigSetup, "-d", dist, "sh", "-c",
"cat > /usr/local/bin/proxyinit; chmod 755 /usr/local/bin/proxyinit"); err != nil {
return errors.Wrap(err, "could not create proxyinit script for guest OS")
return fmt.Errorf("could not create proxyinit script for guest OS: %w", err)
}
return nil
@ -673,10 +673,10 @@ func checkAndInstallWSL(opts machine.InitOptions) (bool, error) {
func attemptFeatureInstall(opts machine.InitOptions, admin bool) error {
if !winVersionAtLeast(10, 0, 18362) {
return errors.Errorf("Your version of Windows does not support WSL. Update to Windows 10 Build 19041 or later")
return errors.New("your version of Windows does not support WSL. Update to Windows 10 Build 19041 or later")
} else if !winVersionAtLeast(10, 0, 19041) {
fmt.Fprint(os.Stderr, wslOldVersion)
return errors.Errorf("WSL can not be automatically installed")
return errors.New("the WSL can not be automatically installed")
}
message := "WSL is not installed on this system, installing it.\n\n"
@ -690,7 +690,7 @@ func attemptFeatureInstall(opts machine.InitOptions, admin bool) error {
"If you prefer, you may abort now, and perform a manual installation using the \"wsl --install\" command."
if !opts.ReExec && MessageBox(message, "Podman Machine", false) != 1 {
return errors.Errorf("WSL installation aborted")
return errors.New("the WSL installation aborted")
}
if !opts.ReExec && !admin {
@ -726,12 +726,12 @@ func installWsl() error {
defer log.Close()
if err := runCmdPassThroughTee(log, "dism", "/online", "/enable-feature",
"/featurename:Microsoft-Windows-Subsystem-Linux", "/all", "/norestart"); isMsiError(err) {
return errors.Wrap(err, "could not enable WSL Feature")
return fmt.Errorf("could not enable WSL Feature: %w", err)
}
if err = runCmdPassThroughTee(log, "dism", "/online", "/enable-feature",
"/featurename:VirtualMachinePlatform", "/all", "/norestart"); isMsiError(err) {
return errors.Wrap(err, "could not enable Virtual Machine Feature")
return fmt.Errorf("could not enable Virtual Machine Feature: %w", err)
}
log.Close()
@ -765,7 +765,7 @@ func installWslKernel() error {
}
if err != nil {
return errors.Wrap(err, "could not install WSL Kernel")
return fmt.Errorf("could not install WSL Kernel: %w", err)
}
return nil
@ -922,23 +922,23 @@ func (v *MachineVM) Set(_ string, opts machine.SetOptions) ([]error, error) {
if opts.Rootful != nil && v.Rootful != *opts.Rootful {
err := v.setRootful(*opts.Rootful)
if err != nil {
setErrors = append(setErrors, errors.Wrapf(err, "error setting rootful option"))
setErrors = append(setErrors, fmt.Errorf("error setting rootful option: %w", err))
} else {
v.Rootful = *opts.Rootful
}
}
if opts.CPUs != nil {
setErrors = append(setErrors, errors.Errorf("changing CPUs not supported for WSL machines"))
setErrors = append(setErrors, errors.New("changing CPUs not supported for WSL machines"))
}
if opts.Memory != nil {
setErrors = append(setErrors, errors.Errorf("changing memory not supported for WSL machines"))
setErrors = append(setErrors, errors.New("changing memory not supported for WSL machines"))
}
if opts.DiskSize != nil {
setErrors = append(setErrors, errors.Errorf("changing Disk Size not supported for WSL machines"))
setErrors = append(setErrors, errors.New("changing Disk Size not supported for WSL machines"))
}
return setErrors, v.writeConfig()
@ -946,7 +946,7 @@ func (v *MachineVM) Set(_ string, opts machine.SetOptions) ([]error, error) {
func (v *MachineVM) Start(name string, _ machine.StartOptions) error {
if v.isRunning() {
return errors.Errorf("%q is already running", name)
return fmt.Errorf("%q is already running", name)
}
dist := toDist(name)
@ -957,7 +957,7 @@ func (v *MachineVM) Start(name string, _ machine.StartOptions) error {
err := runCmdPassThrough("wsl", "-d", dist, "/root/bootstrap")
if err != nil {
return errors.Wrap(err, "WSL bootstrap script failed")
return fmt.Errorf("the WSL bootstrap script failed: %w", err)
}
if !v.Rootful {
@ -999,7 +999,7 @@ func (v *MachineVM) Start(name string, _ machine.StartOptions) error {
func launchWinProxy(v *MachineVM) (bool, string, error) {
machinePipe := toDist(v.Name)
if !pipeAvailable(machinePipe) {
return false, "", errors.Errorf("could not start api proxy since expected pipe is not available: %s", machinePipe)
return false, "", fmt.Errorf("could not start api proxy since expected pipe is not available: %s", machinePipe)
}
globalName := false
@ -1047,7 +1047,7 @@ func launchWinProxy(v *MachineVM) (bool, string, error) {
return globalName, pipePrefix + waitPipe, waitPipeExists(waitPipe, 30, func() error {
active, exitCode := getProcessState(cmd.Process.Pid)
if !active {
return errors.Errorf("win-sshproxy.exe failed to start, exit code: %d (see windows event logs)", exitCode)
return fmt.Errorf("win-sshproxy.exe failed to start, exit code: %d (see windows event logs)", exitCode)
}
return nil
@ -1185,7 +1185,7 @@ func (v *MachineVM) Stop(name string, _ machine.StopOptions) error {
}
if !wsl || !sysd {
return errors.Errorf("%q is not running", v.Name)
return fmt.Errorf("%q is not running", v.Name)
}
_, _, _ = v.updateTimeStamps(true)
@ -1197,12 +1197,12 @@ func (v *MachineVM) Stop(name string, _ machine.StopOptions) error {
cmd := exec.Command("wsl", "-d", dist, "sh")
cmd.Stdin = strings.NewReader(waitTerm)
if err = cmd.Start(); err != nil {
return errors.Wrap(err, "Error executing wait command")
return fmt.Errorf("executing wait command: %w", err)
}
exitCmd := exec.Command("wsl", "-d", dist, "/usr/local/bin/enterns", "systemctl", "exit", "0")
if err = exitCmd.Run(); err != nil {
return errors.Wrap(err, "Error stopping sysd")
return fmt.Errorf("stopping sysd: %w", err)
}
if err = cmd.Wait(); err != nil {
@ -1283,7 +1283,7 @@ func (v *MachineVM) Remove(name string, opts machine.RemoveOptions) (string, fun
var files []string
if v.isRunning() {
return "", nil, errors.Errorf("running vm %q cannot be destroyed", v.Name)
return "", nil, fmt.Errorf("running vm %q cannot be destroyed", v.Name)
}
// Collect all the files that need to be destroyed
@ -1355,7 +1355,7 @@ func (v *MachineVM) isRunning() bool {
// Added ssh function to VM interface: pkg/machine/config/go : line 58
func (v *MachineVM) SSH(name string, opts machine.SSHOptions) error {
if !v.isRunning() {
return errors.Errorf("vm %q is not running.", v.Name)
return fmt.Errorf("vm %q is not running.", v.Name)
}
username := opts.Username

View File

@ -2,6 +2,7 @@ package wsl
import (
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"os"
@ -11,7 +12,6 @@ import (
"unicode/utf16"
"unsafe"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry"
@ -157,9 +157,9 @@ func relaunchElevatedWait() error {
case syscall.WAIT_OBJECT_0:
break
case syscall.WAIT_FAILED:
return errors.Wrap(err, "could not wait for process, failed")
return fmt.Errorf("could not wait for process, failed: %w", err)
default:
return errors.Errorf("could not wait for process, unknown error")
return errors.New("could not wait for process, unknown error")
}
var code uint32
if err := syscall.GetExitCodeProcess(handle, &code); err != nil {
@ -174,7 +174,7 @@ func relaunchElevatedWait() error {
func wrapMaybe(err error, message string) error {
if err != nil {
return errors.Wrap(err, message)
return fmt.Errorf("%v: %w", message, err)
}
return errors.New(message)
@ -182,10 +182,10 @@ func wrapMaybe(err error, message string) error {
func wrapMaybef(err error, format string, args ...interface{}) error {
if err != nil {
return errors.Wrapf(err, format, args...)
return fmt.Errorf(format+": %w", append(args, err)...)
}
return errors.Errorf(format, args...)
return fmt.Errorf(format, args...)
}
func reboot() error {
@ -202,14 +202,14 @@ func reboot() error {
dataDir, err := homedir.GetDataHome()
if err != nil {
return errors.Wrap(err, "could not determine data directory")
return fmt.Errorf("could not determine data directory: %w", err)
}
if err := os.MkdirAll(dataDir, 0755); err != nil {
return errors.Wrap(err, "could not create data directory")
return fmt.Errorf("could not create data directory: %w", err)
}
commFile := filepath.Join(dataDir, "podman-relaunch.dat")
if err := ioutil.WriteFile(commFile, []byte(encoded), 0600); err != nil {
return errors.Wrap(err, "could not serialize command state")
return fmt.Errorf("could not serialize command state: %w", err)
}
command := fmt.Sprintf(pShellLaunch, commFile)
@ -244,7 +244,7 @@ func reboot() error {
procExit := user32.NewProc("ExitWindowsEx")
if ret, _, err := procExit.Call(EWX_REBOOT|EWX_RESTARTAPPS|EWX_FORCEIFHUNG,
SHTDN_REASON_MAJOR_APPLICATION|SHTDN_REASON_MINOR_INSTALLATION|SHTDN_REASON_FLAG_PLANNED); ret != 1 {
return errors.Wrap(err, "reboot failed")
return fmt.Errorf("reboot failed: %w", err)
}
return nil
@ -262,19 +262,19 @@ func obtainShutdownPrivilege() error {
var hToken uintptr
if ret, _, err := OpenProcessToken.Call(uintptr(proc), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, uintptr(unsafe.Pointer(&hToken))); ret != 1 {
return errors.Wrap(err, "error opening process token")
return fmt.Errorf("error opening process token: %w", err)
}
var privs TokenPrivileges
if ret, _, err := LookupPrivilegeValue.Call(uintptr(0), uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(SeShutdownName))), uintptr(unsafe.Pointer(&(privs.privileges[0].luid)))); ret != 1 {
return errors.Wrap(err, "error looking up shutdown privilege")
return fmt.Errorf("error looking up shutdown privilege: %w", err)
}
privs.privilegeCount = 1
privs.privileges[0].attributes = SE_PRIVILEGE_ENABLED
if ret, _, err := AdjustTokenPrivileges.Call(hToken, 0, uintptr(unsafe.Pointer(&privs)), 0, uintptr(0), 0); ret != 1 {
return errors.Wrap(err, "error enabling shutdown privilege on token")
return fmt.Errorf("error enabling shutdown privilege on token: %w", err)
}
return nil
@ -295,13 +295,13 @@ func getProcessState(pid int) (active bool, exitCode int) {
func addRunOnceRegistryEntry(command string) error {
k, _, err := registry.CreateKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\RunOnce`, registry.WRITE)
if err != nil {
return errors.Wrap(err, "could not open RunOnce registry entry")
return fmt.Errorf("could not open RunOnce registry entry: %w", err)
}
defer k.Close()
if err := k.SetExpandStringValue("podman-machine", command); err != nil {
return errors.Wrap(err, "could not open RunOnce registry entry")
return fmt.Errorf("could not open RunOnce registry entry: %w", err)
}
return nil

View File

@ -2,9 +2,10 @@ package parallel
import (
"context"
"errors"
"fmt"
"sync"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sync/semaphore"
)
@ -59,7 +60,7 @@ func Enqueue(ctx context.Context, fn func() error) <-chan error {
defer close(retChan)
if err := jobControl.Acquire(ctx, 1); err != nil {
retChan <- errors.Wrapf(err, "error acquiring job control semaphore")
retChan <- fmt.Errorf("error acquiring job control semaphore: %w", err)
return
}

View File

@ -6,6 +6,7 @@ package rootless
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
@ -23,7 +24,6 @@ import (
"github.com/containers/storage/pkg/idtools"
pmount "github.com/containers/storage/pkg/mount"
"github.com/containers/storage/pkg/unshare"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/syndtr/gocapability/capability"
"golang.org/x/sys/unix"
@ -126,7 +126,7 @@ func tryMappingTool(uid bool, pid int, hostID int, mappings []idtools.IDMap) err
}
path, err := exec.LookPath(tool)
if err != nil {
return errors.Wrapf(err, "command required for rootless mode with multiple IDs")
return fmt.Errorf("command required for rootless mode with multiple IDs: %w", err)
}
appendTriplet := func(l []string, a, b, c int) []string {
@ -143,7 +143,7 @@ func tryMappingTool(uid bool, pid int, hostID int, mappings []idtools.IDMap) err
what = "GID"
where = "/etc/subgid"
}
return errors.Errorf("invalid configuration: the specified mapping %d:%d in %q includes the user %s", i.HostID, i.Size, where, what)
return fmt.Errorf("invalid configuration: the specified mapping %d:%d in %q includes the user %s", i.HostID, i.Size, where, what)
}
args = appendTriplet(args, i.ContainerID+1, i.HostID, i.Size)
}
@ -160,7 +160,7 @@ func tryMappingTool(uid bool, pid int, hostID int, mappings []idtools.IDMap) err
} else if !isSet {
errorStr = fmt.Sprintf("%s: should have %s or have filecaps %s", errorStr, idtype, idtype)
}
return errors.Wrapf(err, errorStr)
return fmt.Errorf("%v: %w", errorStr, err)
}
return nil
}
@ -182,7 +182,7 @@ func joinUserAndMountNS(pid uint, pausePid string) (bool, int, error) {
pidC := C.reexec_userns_join(C.int(pid), cPausePid)
if int(pidC) < 0 {
return false, -1, errors.Errorf("cannot re-exec process to join the existing user namespace")
return false, -1, fmt.Errorf("cannot re-exec process to join the existing user namespace")
}
ret := C.reexec_in_user_namespace_wait(pidC, 0)
@ -313,7 +313,7 @@ func becomeRootInUserNS(pausePid, fileToRead string, fileOutput *os.File) (_ boo
pidC := C.reexec_in_user_namespace(C.int(r.Fd()), cPausePid, cFileToRead, fileOutputFD)
pid = int(pidC)
if pid < 0 {
return false, -1, errors.Errorf("cannot re-exec process")
return false, -1, fmt.Errorf("cannot re-exec process")
}
uids, gids, err := GetConfiguredMappings()
@ -343,13 +343,13 @@ func becomeRootInUserNS(pausePid, fileToRead string, fileOutput *os.File) (_ boo
setgroups := fmt.Sprintf("/proc/%d/setgroups", pid)
err = ioutil.WriteFile(setgroups, []byte("deny\n"), 0666)
if err != nil {
return false, -1, errors.Wrapf(err, "cannot write setgroups file")
return false, -1, fmt.Errorf("cannot write setgroups file: %w", err)
}
logrus.Debugf("write setgroups file exited with 0")
err = ioutil.WriteFile(uidMap, []byte(fmt.Sprintf("%d %d 1\n", 0, os.Geteuid())), 0666)
if err != nil {
return false, -1, errors.Wrapf(err, "cannot write uid_map")
return false, -1, fmt.Errorf("cannot write uid_map: %w", err)
}
logrus.Debugf("write uid_map exited with 0")
}
@ -369,19 +369,19 @@ func becomeRootInUserNS(pausePid, fileToRead string, fileOutput *os.File) (_ boo
if !gidsMapped {
err = ioutil.WriteFile(gidMap, []byte(fmt.Sprintf("%d %d 1\n", 0, os.Getegid())), 0666)
if err != nil {
return false, -1, errors.Wrapf(err, "cannot write gid_map")
return false, -1, fmt.Errorf("cannot write gid_map: %w", err)
}
}
_, err = w.Write([]byte("0"))
if err != nil {
return false, -1, errors.Wrapf(err, "write to sync pipe")
return false, -1, fmt.Errorf("write to sync pipe: %w", err)
}
b := make([]byte, 1)
_, err = w.Read(b)
if err != nil {
return false, -1, errors.Wrapf(err, "read from sync pipe")
return false, -1, fmt.Errorf("read from sync pipe: %w", err)
}
if fileOutput != nil {
@ -474,7 +474,7 @@ func TryJoinFromFilePaths(pausePidPath string, needNewNamespace bool, paths []st
pausePid, err = strconv.Atoi(string(data))
if err != nil {
lastErr = errors.Wrapf(err, "cannot parse file %q", path)
lastErr = fmt.Errorf("cannot parse file %q: %w", path, err)
continue
}
} else {
@ -503,7 +503,7 @@ func TryJoinFromFilePaths(pausePidPath string, needNewNamespace bool, paths []st
n, err := r.Read(b)
if err != nil {
lastErr = errors.Wrapf(err, "cannot read %q", path)
lastErr = fmt.Errorf("cannot read %q: %w", path, err)
continue
}
@ -525,7 +525,7 @@ func TryJoinFromFilePaths(pausePidPath string, needNewNamespace bool, paths []st
if lastErr != nil {
return false, 0, lastErr
}
return false, 0, errors.Wrapf(unix.ESRCH, "could not find any running process")
return false, 0, fmt.Errorf("could not find any running process: %w", unix.ESRCH)
}
// ReadMappingsProc parses and returns the ID mappings at the specified path.
@ -545,7 +545,7 @@ func ReadMappingsProc(path string) ([]idtools.IDMap, error) {
if err == io.EOF {
return mappings, nil
}
return nil, errors.Wrapf(err, "cannot read line from %s", path)
return nil, fmt.Errorf("cannot read line from %s: %w", path, err)
}
if line == nil {
return mappings, nil
@ -553,7 +553,7 @@ func ReadMappingsProc(path string) ([]idtools.IDMap, error) {
containerID, hostID, size := 0, 0, 0
if _, err := fmt.Sscanf(string(line), "%d %d %d", &containerID, &hostID, &size); err != nil {
return nil, errors.Wrapf(err, "cannot parse %s", string(line))
return nil, fmt.Errorf("cannot parse %s: %w", string(line), err)
}
mappings = append(mappings, idtools.IDMap{ContainerID: containerID, HostID: hostID, Size: size})
}

View File

@ -4,10 +4,10 @@
package rootless
import (
"errors"
"os"
"github.com/containers/storage/pkg/idtools"
"github.com/pkg/errors"
)
// IsRootless returns whether the user is rootless

View File

@ -1,9 +1,8 @@
package seccomp
import (
"fmt"
"sort"
"github.com/pkg/errors"
)
// ContainerImageLabel is the key of the image annotation embedding a seccomp
@ -50,5 +49,5 @@ func LookupPolicy(s string) (Policy, error) {
}
sort.Strings(keys)
return -1, errors.Errorf("invalid seccomp policy %q: valid policies are %+q", s, keys)
return -1, fmt.Errorf("invalid seccomp policy %q: valid policies are %+q", s, keys)
}

View File

@ -4,9 +4,10 @@
package specgen
import (
"errors"
"github.com/containers/common/libimage"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
)
func (s *SpecGenerator) getSeccompConfig(configSpec *spec.Spec, img *libimage.Image) (*spec.LinuxSeccomp, error) {

View File

@ -1,6 +1,8 @@
package specgen
import (
"errors"
"fmt"
"strconv"
"strings"
@ -8,7 +10,6 @@ import (
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/rootless"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
)
var (
@ -23,7 +24,7 @@ var (
)
func exclusiveOptions(opt1, opt2 string) error {
return errors.Errorf("%s and %s are mutually exclusive options", opt1, opt2)
return fmt.Errorf("%s and %s are mutually exclusive options", opt1, opt2)
}
// Validate verifies that the given SpecGenerator is valid and satisfies required
@ -33,18 +34,18 @@ func (s *SpecGenerator) Validate() error {
// associated with them because those should be on the infra container.
if len(s.Pod) > 0 && s.NetNS.NSMode == FromPod {
if len(s.Networks) > 0 {
return errors.Wrap(define.ErrNetworkOnPodContainer, "networks must be defined when the pod is created")
return fmt.Errorf("networks must be defined when the pod is created: %w", define.ErrNetworkOnPodContainer)
}
if len(s.PortMappings) > 0 || s.PublishExposedPorts {
return errors.Wrap(define.ErrNetworkOnPodContainer, "published or exposed ports must be defined when the pod is created")
return fmt.Errorf("published or exposed ports must be defined when the pod is created: %w", define.ErrNetworkOnPodContainer)
}
if len(s.HostAdd) > 0 {
return errors.Wrap(define.ErrNetworkOnPodContainer, "extra host entries must be specified on the pod")
return fmt.Errorf("extra host entries must be specified on the pod: %w", define.ErrNetworkOnPodContainer)
}
}
if s.NetNS.IsContainer() && len(s.HostAdd) > 0 {
return errors.Wrap(ErrInvalidSpecConfig, "cannot set extra host entries when the container is joined to another containers network namespace")
return fmt.Errorf("cannot set extra host entries when the container is joined to another containers network namespace: %w", ErrInvalidSpecConfig)
}
//
@ -52,23 +53,23 @@ func (s *SpecGenerator) Validate() error {
//
// Rootfs and Image cannot both populated
if len(s.ContainerStorageConfig.Image) > 0 && len(s.ContainerStorageConfig.Rootfs) > 0 {
return errors.Wrap(ErrInvalidSpecConfig, "both image and rootfs cannot be simultaneously")
return fmt.Errorf("both image and rootfs cannot be simultaneously: %w", ErrInvalidSpecConfig)
}
// Cannot set hostname and utsns
if len(s.ContainerBasicConfig.Hostname) > 0 && !s.ContainerBasicConfig.UtsNS.IsPrivate() {
if s.ContainerBasicConfig.UtsNS.IsPod() {
return errors.Wrap(ErrInvalidSpecConfig, "cannot set hostname when joining the pod UTS namespace")
return fmt.Errorf("cannot set hostname when joining the pod UTS namespace: %w", ErrInvalidSpecConfig)
}
return errors.Wrap(ErrInvalidSpecConfig, "cannot set hostname when running in the host UTS namespace")
return fmt.Errorf("cannot set hostname when running in the host UTS namespace: %w", ErrInvalidSpecConfig)
}
// systemd values must be true, false, or always
if len(s.ContainerBasicConfig.Systemd) > 0 && !util.StringInSlice(strings.ToLower(s.ContainerBasicConfig.Systemd), SystemDValues) {
return errors.Wrapf(ErrInvalidSpecConfig, "--systemd values must be one of %q", strings.Join(SystemDValues, ", "))
return fmt.Errorf("--systemd values must be one of %q: %w", strings.Join(SystemDValues, ", "), ErrInvalidSpecConfig)
}
// sdnotify values must be container, conmon, or ignore
if len(s.ContainerBasicConfig.SdNotifyMode) > 0 && !util.StringInSlice(strings.ToLower(s.ContainerBasicConfig.SdNotifyMode), SdNotifyModeValues) {
return errors.Wrapf(ErrInvalidSpecConfig, "--sdnotify values must be one of %q", strings.Join(SdNotifyModeValues, ", "))
return fmt.Errorf("--sdnotify values must be one of %q: %w", strings.Join(SdNotifyModeValues, ", "), ErrInvalidSpecConfig)
}
//
@ -80,12 +81,12 @@ func (s *SpecGenerator) Validate() error {
}
// imagevolumemode must be one of ignore, tmpfs, or anonymous if given
if len(s.ContainerStorageConfig.ImageVolumeMode) > 0 && !util.StringInSlice(strings.ToLower(s.ContainerStorageConfig.ImageVolumeMode), ImageVolumeModeValues) {
return errors.Errorf("invalid ImageVolumeMode %q, value must be one of %s",
return fmt.Errorf("invalid ImageVolumeMode %q, value must be one of %s",
s.ContainerStorageConfig.ImageVolumeMode, strings.Join(ImageVolumeModeValues, ","))
}
// shmsize conflicts with IPC namespace
if s.ContainerStorageConfig.ShmSize != nil && (s.ContainerStorageConfig.IpcNS.IsHost() || s.ContainerStorageConfig.IpcNS.IsNone()) {
return errors.Errorf("cannot set shmsize when running in the %s IPC Namespace", s.ContainerStorageConfig.IpcNS)
return fmt.Errorf("cannot set shmsize when running in the %s IPC Namespace", s.ContainerStorageConfig.IpcNS)
}
//
@ -93,7 +94,7 @@ func (s *SpecGenerator) Validate() error {
//
// userns and idmappings conflict
if s.UserNS.IsPrivate() && s.IDMappings == nil {
return errors.Wrap(ErrInvalidSpecConfig, "IDMappings are required when not creating a User namespace")
return fmt.Errorf("IDMappings are required when not creating a User namespace: %w", ErrInvalidSpecConfig)
}
//
@ -143,11 +144,11 @@ func (s *SpecGenerator) Validate() error {
for _, limit := range tmpnproc {
limitSplit := strings.SplitN(limit, "=", 2)
if len(limitSplit) < 2 {
return errors.Wrapf(invalidUlimitFormatError, "missing = in %s", limit)
return fmt.Errorf("missing = in %s: %w", limit, invalidUlimitFormatError)
}
valueSplit := strings.SplitN(limitSplit[1], ":", 2)
if len(valueSplit) < 2 {
return errors.Wrapf(invalidUlimitFormatError, "missing : in %s", limit)
return fmt.Errorf("missing : in %s: %w", limit, invalidUlimitFormatError)
}
hard, err := strconv.Atoi(valueSplit[0])
if err != nil {
@ -197,7 +198,7 @@ func (s *SpecGenerator) Validate() error {
}
if s.NetNS.NSMode != Bridge && len(s.Networks) > 0 {
// Note that we also get the ip and mac in the networks map
return errors.New("Networks and static ip/mac address can only be used with Bridge mode networking")
return errors.New("networks and static ip/mac address can only be used with Bridge mode networking")
}
return nil

View File

@ -13,7 +13,6 @@ import (
"github.com/containers/podman/v4/pkg/util"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
@ -46,7 +45,7 @@ func DevicesFromPath(g *generate.Generator, devicePath string) error {
}
if len(devs) > 2 {
if devmode != "" {
return errors.Wrapf(unix.EINVAL, "invalid device specification %s", devicePath)
return fmt.Errorf("invalid device specification %s: %w", devicePath, unix.EINVAL)
}
devmode = devs[2]
}
@ -60,7 +59,7 @@ func DevicesFromPath(g *generate.Generator, devicePath string) error {
device = fmt.Sprintf("%s:%s", device, devmode)
}
if err := addDevice(g, device); err != nil {
return errors.Wrapf(err, "failed to add %s device", dpath)
return fmt.Errorf("failed to add %s device: %w", dpath, err)
}
}
return nil
@ -68,7 +67,7 @@ func DevicesFromPath(g *generate.Generator, devicePath string) error {
return err
}
if !found {
return errors.Wrapf(unix.EINVAL, "no devices found in %s", devicePath)
return fmt.Errorf("no devices found in %s: %w", devicePath, unix.EINVAL)
}
return nil
}
@ -131,7 +130,7 @@ func addDevice(g *generate.Generator, device string) error {
}
dev, err := util.DeviceFromPath(src)
if err != nil {
return errors.Wrapf(err, "%s is not a valid device", src)
return fmt.Errorf("%s is not a valid device: %w", src, err)
}
if rootless.IsRootless() {
if _, err := os.Stat(src); err != nil {

View File

@ -5,6 +5,8 @@ package generate
import (
"context"
"errors"
"fmt"
"io/ioutil"
"github.com/containers/common/libimage"
@ -12,7 +14,6 @@ import (
"github.com/containers/podman/v4/pkg/seccomp"
"github.com/containers/podman/v4/pkg/specgen"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -39,7 +40,7 @@ func getSeccompConfig(s *specgen.SpecGenerator, configSpec *spec.Spec, img *libi
logrus.Debug("Loading seccomp profile from the security config")
seccompConfig, err = goSeccomp.LoadProfile(imagePolicy, configSpec)
if err != nil {
return nil, errors.Wrap(err, "loading seccomp profile failed")
return nil, fmt.Errorf("loading seccomp profile failed: %w", err)
}
return seccompConfig, nil
}
@ -48,17 +49,17 @@ func getSeccompConfig(s *specgen.SpecGenerator, configSpec *spec.Spec, img *libi
logrus.Debugf("Loading seccomp profile from %q", s.SeccompProfilePath)
seccompProfile, err := ioutil.ReadFile(s.SeccompProfilePath)
if err != nil {
return nil, errors.Wrap(err, "opening seccomp profile failed")
return nil, fmt.Errorf("opening seccomp profile failed: %w", err)
}
seccompConfig, err = goSeccomp.LoadProfile(string(seccompProfile), configSpec)
if err != nil {
return nil, errors.Wrapf(err, "loading seccomp profile (%s) failed", s.SeccompProfilePath)
return nil, fmt.Errorf("loading seccomp profile (%s) failed: %w", s.SeccompProfilePath, err)
}
} else {
logrus.Debug("Loading default seccomp profile")
seccompConfig, err = goSeccomp.GetDefaultProfile(configSpec)
if err != nil {
return nil, errors.Wrapf(err, "loading seccomp profile (%s) failed", s.SeccompProfilePath)
return nil, fmt.Errorf("loading seccomp profile (%s) failed: %w", s.SeccompProfilePath, err)
}
}

View File

@ -3,6 +3,7 @@ package generate
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
@ -17,7 +18,6 @@ import (
"github.com/containers/podman/v4/pkg/signal"
"github.com/containers/podman/v4/pkg/specgen"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
@ -115,7 +115,7 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat
// Get Default Environment from containers.conf
defaultEnvs, err := envLib.ParseSlice(rtc.GetDefaultEnvEx(s.EnvHost, s.HTTPProxy))
if err != nil {
return nil, errors.Wrap(err, "error parsing fields in containers.conf")
return nil, fmt.Errorf("error parsing fields in containers.conf: %w", err)
}
var envs map[string]string
@ -125,7 +125,7 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat
// already, overriding the default environments
envs, err = envLib.ParseSlice(inspectData.Config.Env)
if err != nil {
return nil, errors.Wrap(err, "Env fields from image failed to parse")
return nil, fmt.Errorf("env fields from image failed to parse: %w", err)
}
defaultEnvs = envLib.Join(envLib.DefaultEnvVariables(), envLib.Join(defaultEnvs, envs))
}
@ -141,7 +141,7 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat
// any case.
osEnv, err := envLib.ParseSlice(os.Environ())
if err != nil {
return nil, errors.Wrap(err, "error parsing host environment variables")
return nil, fmt.Errorf("error parsing host environment variables: %w", err)
}
// Caller Specified defaults
if s.EnvHost {

View File

@ -3,6 +3,8 @@ package generate
import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strings"
@ -15,7 +17,6 @@ import (
"github.com/containers/podman/v4/pkg/util"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/selinux/go-selinux/label"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -34,7 +35,7 @@ func MakeContainer(ctx context.Context, rt *libpod.Runtime, s *specgen.SpecGener
if s.Pod != "" {
pod, err = rt.LookupPod(s.Pod)
if err != nil {
return nil, nil, nil, errors.Wrapf(err, "error retrieving pod %s", s.Pod)
return nil, nil, nil, fmt.Errorf("error retrieving pod %s: %w", s.Pod, err)
}
if pod.HasInfraContainer() {
infra, err = pod.InfraContainer()
@ -140,7 +141,7 @@ func MakeContainer(ctx context.Context, rt *libpod.Runtime, s *specgen.SpecGener
s.Hostname = ""
}
if err := s.Validate(); err != nil {
return nil, nil, nil, errors.Wrap(err, "invalid config provided")
return nil, nil, nil, fmt.Errorf("invalid config provided: %w", err)
}
finalMounts, finalVolumes, finalOverlays, err := finalizeMounts(ctx, s, rt, rtc, newImage)
@ -332,7 +333,7 @@ func createContainerOptions(rt *libpod.Runtime, s *specgen.SpecGenerator, pod *l
}
}
default:
return nil, errors.Wrapf(err, "invalid value %q systemd option requires 'true, false, always'", s.Systemd)
return nil, fmt.Errorf("invalid value %q systemd option requires 'true, false, always': %w", s.Systemd, err)
}
logrus.Debugf("using systemd mode: %t", useSystemd)
if useSystemd {
@ -341,7 +342,7 @@ func createContainerOptions(rt *libpod.Runtime, s *specgen.SpecGenerator, pod *l
if s.StopSignal == nil {
stopSignal, err := util.ParseSignal("RTMIN+3")
if err != nil {
return nil, errors.Wrapf(err, "error parsing systemd signal")
return nil, fmt.Errorf("error parsing systemd signal: %w", err)
}
s.StopSignal = &stopSignal
}
@ -536,7 +537,7 @@ func createContainerOptions(rt *libpod.Runtime, s *specgen.SpecGenerator, pod *l
for _, ctr := range s.DependencyContainers {
depCtr, err := rt.LookupContainer(ctr)
if err != nil {
return nil, errors.Wrapf(err, "%q is not a valid container, cannot be used as a dependency", ctr)
return nil, fmt.Errorf("%q is not a valid container, cannot be used as a dependency: %w", ctr, err)
}
deps = append(deps, depCtr)
}

View File

@ -3,6 +3,7 @@ package kube
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"net"
@ -29,7 +30,6 @@ import (
"github.com/docker/docker/pkg/system"
"github.com/docker/go-units"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -146,7 +146,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
// pod name should be non-empty for Deployment objects to be able to create
// multiple pods having containers with unique names
if len(opts.PodName) < 1 {
return nil, errors.Errorf("got empty pod name on container creation when playing kube")
return nil, errors.New("got empty pod name on container creation when playing kube")
}
s.Name = fmt.Sprintf("%s-%s", opts.PodName, opts.Container.Name)
@ -163,7 +163,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
for _, o := range opts.LogOptions {
split := strings.SplitN(o, "=", 2)
if len(split) < 2 {
return nil, errors.Errorf("invalid log option %q", o)
return nil, fmt.Errorf("invalid log option %q", o)
}
switch strings.ToLower(split[0]) {
case "driver":
@ -179,7 +179,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
default:
switch len(split[1]) {
case 0:
return nil, errors.Wrapf(define.ErrInvalidArg, "invalid log option")
return nil, fmt.Errorf("invalid log option: %w", define.ErrInvalidArg)
default:
// tags for journald only
if s.LogConfiguration.Driver == "" || s.LogConfiguration.Driver == define.JournaldLogging {
@ -196,7 +196,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
setupSecurityContext(s, opts.Container.SecurityContext, opts.PodSecurityContext)
err := setupLivenessProbe(s, opts.Container, opts.RestartPolicy)
if err != nil {
return nil, errors.Wrap(err, "Failed to configure livenessProbe")
return nil, fmt.Errorf("failed to configure livenessProbe: %w", err)
}
// Since we prefix the container name with pod name to work-around the uniqueness requirement,
@ -207,7 +207,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
s.ResourceLimits = &spec.LinuxResources{}
milliCPU, err := quantityToInt64(opts.Container.Resources.Limits.Cpu())
if err != nil {
return nil, errors.Wrap(err, "Failed to set CPU quota")
return nil, fmt.Errorf("failed to set CPU quota: %w", err)
}
if milliCPU > 0 {
period, quota := util.CoresToPeriodAndQuota(float64(milliCPU))
@ -219,12 +219,12 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
limit, err := quantityToInt64(opts.Container.Resources.Limits.Memory())
if err != nil {
return nil, errors.Wrap(err, "Failed to set memory limit")
return nil, fmt.Errorf("failed to set memory limit: %w", err)
}
memoryRes, err := quantityToInt64(opts.Container.Resources.Requests.Memory())
if err != nil {
return nil, errors.Wrap(err, "Failed to set memory reservation")
return nil, fmt.Errorf("failed to set memory reservation: %w", err)
}
if limit > 0 || memoryRes > 0 {
@ -337,7 +337,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
for _, volume := range opts.Container.VolumeMounts {
volumeSource, exists := opts.Volumes[volume.Name]
if !exists {
return nil, errors.Errorf("Volume mount %s specified for container but not configured in volumes", volume.Name)
return nil, fmt.Errorf("volume mount %s specified for container but not configured in volumes", volume.Name)
}
// Skip if the volume is optional. This means that a configmap for a configmap volume was not found but it was
// optional so we can move on without throwing an error
@ -399,7 +399,7 @@ func ToSpecGen(ctx context.Context, opts *CtrSpecGenOptions) (*specgen.SpecGener
}
s.Devices = append(s.Devices, device)
default:
return nil, errors.Errorf("Unsupported volume source type")
return nil, errors.New("unsupported volume source type")
}
}
@ -432,21 +432,21 @@ func parseMountPath(mountPath string, readOnly bool, propagationMode *v1.MountPr
options := []string{}
splitVol := strings.Split(mountPath, ":")
if len(splitVol) > 2 {
return "", options, errors.Errorf("%q incorrect volume format, should be ctr-dir[:option]", mountPath)
return "", options, fmt.Errorf("%q incorrect volume format, should be ctr-dir[:option]", mountPath)
}
dest := splitVol[0]
if len(splitVol) > 1 {
options = strings.Split(splitVol[1], ",")
}
if err := parse.ValidateVolumeCtrDir(dest); err != nil {
return "", options, errors.Wrapf(err, "parsing MountPath")
return "", options, fmt.Errorf("parsing MountPath: %w", err)
}
if readOnly {
options = append(options, "ro")
}
opts, err := parse.ValidateVolumeOpts(options)
if err != nil {
return "", opts, errors.Wrapf(err, "parsing MountOptions")
return "", opts, fmt.Errorf("parsing MountOptions: %w", err)
}
if propagationMode != nil {
switch *propagationMode {
@ -457,7 +457,7 @@ func parseMountPath(mountPath string, readOnly bool, propagationMode *v1.MountPr
case v1.MountPropagationBidirectional:
opts = append(opts, "rshared")
default:
return "", opts, errors.Errorf("unknown propagation mode %q", *propagationMode)
return "", opts, fmt.Errorf("unknown propagation mode %q", *propagationMode)
}
}
return dest, opts, nil
@ -504,7 +504,7 @@ func setupLivenessProbe(s *specgen.SpecGenerator, containerYAML v1.Container, re
func makeHealthCheck(inCmd string, interval int32, retries int32, timeout int32, startPeriod int32) (*manifest.Schema2HealthConfig, error) {
// Every healthcheck requires a command
if len(inCmd) == 0 {
return nil, errors.New("Must define a healthcheck command for all healthchecks")
return nil, errors.New("must define a healthcheck command for all healthchecks")
}
// first try to parse option value as JSON array of strings...
@ -630,7 +630,7 @@ func quantityToInt64(quantity *resource.Quantity) (int64, error) {
return i, nil
}
return 0, errors.Errorf("Quantity cannot be represented as int64: %v", quantity)
return 0, fmt.Errorf("quantity cannot be represented as int64: %v", quantity)
}
// read a k8s secret in JSON format from the secret manager
@ -642,7 +642,7 @@ func k8sSecretFromSecretManager(name string, secretsManager *secrets.SecretsMana
var secrets map[string][]byte
if err := json.Unmarshal(jsonSecret, &secrets); err != nil {
return nil, errors.Errorf("Secret %v is not valid JSON: %v", name, err)
return nil, fmt.Errorf("secret %v is not valid JSON: %v", name, err)
}
return secrets, nil
}
@ -653,7 +653,7 @@ func envVarsFrom(envFrom v1.EnvFromSource, opts *CtrSpecGenOptions) (map[string]
if envFrom.ConfigMapRef != nil {
cmRef := envFrom.ConfigMapRef
err := errors.Errorf("Configmap %v not found", cmRef.Name)
err := fmt.Errorf("configmap %v not found", cmRef.Name)
for _, c := range opts.ConfigMaps {
if cmRef.Name == c.Name {
@ -689,14 +689,14 @@ func envVarValue(env v1.EnvVar, opts *CtrSpecGenOptions) (*string, error) {
if env.ValueFrom != nil {
if env.ValueFrom.ConfigMapKeyRef != nil {
cmKeyRef := env.ValueFrom.ConfigMapKeyRef
err := errors.Errorf("Cannot set env %v: configmap %v not found", env.Name, cmKeyRef.Name)
err := fmt.Errorf("cannot set env %v: configmap %v not found", env.Name, cmKeyRef.Name)
for _, c := range opts.ConfigMaps {
if cmKeyRef.Name == c.Name {
if value, ok := c.Data[cmKeyRef.Key]; ok {
return &value, nil
}
err = errors.Errorf("Cannot set env %v: key %s not found in configmap %v", env.Name, cmKeyRef.Key, cmKeyRef.Name)
err = fmt.Errorf("cannot set env %v: key %s not found in configmap %v", env.Name, cmKeyRef.Key, cmKeyRef.Name)
break
}
}
@ -714,10 +714,10 @@ func envVarValue(env v1.EnvVar, opts *CtrSpecGenOptions) (*string, error) {
value := string(val)
return &value, nil
}
err = errors.Errorf("Secret %v has not %v key", secKeyRef.Name, secKeyRef.Key)
err = fmt.Errorf("secret %v has not %v key", secKeyRef.Name, secKeyRef.Key)
}
if secKeyRef.Optional == nil || !*secKeyRef.Optional {
return nil, errors.Errorf("Cannot set env %v: %v", env.Name, err)
return nil, fmt.Errorf("cannot set env %v: %v", env.Name, err)
}
return nil, nil
}
@ -761,8 +761,8 @@ func envVarValueFieldRef(env v1.EnvVar, opts *CtrSpecGenOptions) (*string, error
return &annotationValue, nil
}
return nil, errors.Errorf(
"Can not set env %v. Reason: fieldPath %v is either not valid or not supported",
return nil, fmt.Errorf(
"can not set env %v. Reason: fieldPath %v is either not valid or not supported",
env.Name, fieldPath,
)
}
@ -796,15 +796,15 @@ func envVarValueResourceFieldRef(env v1.EnvVar, opts *CtrSpecGenOptions) (*strin
value = resources.Requests.Cpu()
isValidDivisor = isCPUDivisor(divisor)
default:
return nil, errors.Errorf(
"Can not set env %v. Reason: resource %v is either not valid or not supported",
return nil, fmt.Errorf(
"can not set env %v. Reason: resource %v is either not valid or not supported",
env.Name, resourceName,
)
}
if !isValidDivisor {
return nil, errors.Errorf(
"Can not set env %s. Reason: divisor value %s is not valid",
return nil, fmt.Errorf(
"can not set env %s. Reason: divisor value %s is not valid",
env.Name, divisor.String(),
)
}

View File

@ -1,12 +1,12 @@
package kube
import (
"fmt"
"path/filepath"
"strings"
"github.com/containers/podman/v4/libpod"
v1 "github.com/containers/podman/v4/pkg/k8s.io/api/core/v1"
"github.com/pkg/errors"
)
// KubeSeccompPaths holds information about a pod YAML's seccomp configuration
@ -42,7 +42,7 @@ func InitializeSeccompPaths(annotations map[string]string, profileRoot string) (
// this could be caused by a user inputting either of
// container.seccomp.security.alpha.kubernetes.io{,/}
// both of which are invalid
return nil, errors.Errorf("Invalid seccomp path: %s", prefixAndCtr[0])
return nil, fmt.Errorf("invalid seccomp path: %s", prefixAndCtr[0])
}
path, err := verifySeccompPath(seccomp, profileRoot)
@ -80,6 +80,6 @@ func verifySeccompPath(path string, profileRoot string) (string, error) {
if parts[0] == "localhost" {
return filepath.Join(profileRoot, parts[1]), nil
}
return "", errors.Errorf("invalid seccomp path: %s", path)
return "", fmt.Errorf("invalid seccomp path: %s", path)
}
}

View File

@ -1,12 +1,13 @@
package kube
import (
"errors"
"fmt"
"os"
"github.com/containers/common/pkg/parse"
"github.com/containers/podman/v4/libpod"
v1 "github.com/containers/podman/v4/pkg/k8s.io/api/core/v1"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -56,13 +57,13 @@ func VolumeFromHostPath(hostPath *v1.HostPathVolumeSource) (*KubeVolume, error)
}
// Label a newly created volume
if err := libpod.LabelVolumePath(hostPath.Path); err != nil {
return nil, errors.Wrapf(err, "error giving %s a label", hostPath.Path)
return nil, fmt.Errorf("error giving %s a label: %w", hostPath.Path, err)
}
case v1.HostPathFileOrCreate:
if _, err := os.Stat(hostPath.Path); os.IsNotExist(err) {
f, err := os.OpenFile(hostPath.Path, os.O_RDONLY|os.O_CREATE, kubeFilePermission)
if err != nil {
return nil, errors.Wrap(err, "error creating HostPath")
return nil, fmt.Errorf("error creating HostPath: %w", err)
}
if err := f.Close(); err != nil {
logrus.Warnf("Error in closing newly created HostPath file: %v", err)
@ -70,23 +71,23 @@ func VolumeFromHostPath(hostPath *v1.HostPathVolumeSource) (*KubeVolume, error)
}
// unconditionally label a newly created volume
if err := libpod.LabelVolumePath(hostPath.Path); err != nil {
return nil, errors.Wrapf(err, "error giving %s a label", hostPath.Path)
return nil, fmt.Errorf("error giving %s a label: %w", hostPath.Path, err)
}
case v1.HostPathSocket:
st, err := os.Stat(hostPath.Path)
if err != nil {
return nil, errors.Wrap(err, "error checking HostPathSocket")
return nil, fmt.Errorf("error checking HostPathSocket: %w", err)
}
if st.Mode()&os.ModeSocket != os.ModeSocket {
return nil, errors.Errorf("checking HostPathSocket: path %s is not a socket", hostPath.Path)
return nil, fmt.Errorf("checking HostPathSocket: path %s is not a socket", hostPath.Path)
}
case v1.HostPathBlockDev:
dev, err := os.Stat(hostPath.Path)
if err != nil {
return nil, errors.Wrap(err, "error checking HostPathBlockDevice")
return nil, fmt.Errorf("error checking HostPathBlockDevice: %w", err)
}
if dev.Mode()&os.ModeCharDevice == os.ModeCharDevice {
return nil, errors.Errorf("checking HostPathDevice: path %s is not a block device", hostPath.Path)
return nil, fmt.Errorf("checking HostPathDevice: path %s is not a block device", hostPath.Path)
}
return &KubeVolume{
Type: KubeVolumeTypeBlockDevice,
@ -95,10 +96,10 @@ func VolumeFromHostPath(hostPath *v1.HostPathVolumeSource) (*KubeVolume, error)
case v1.HostPathCharDev:
dev, err := os.Stat(hostPath.Path)
if err != nil {
return nil, errors.Wrap(err, "error checking HostPathCharDevice")
return nil, fmt.Errorf("error checking HostPathCharDevice: %w", err)
}
if dev.Mode()&os.ModeCharDevice != os.ModeCharDevice {
return nil, errors.Errorf("checking HostPathCharDevice: path %s is not a character device", hostPath.Path)
return nil, fmt.Errorf("checking HostPathCharDevice: path %s is not a character device", hostPath.Path)
}
return &KubeVolume{
Type: KubeVolumeTypeCharDevice,
@ -110,12 +111,12 @@ func VolumeFromHostPath(hostPath *v1.HostPathVolumeSource) (*KubeVolume, error)
// do nothing here because we will verify the path exists in validateVolumeHostDir
break
default:
return nil, errors.Errorf("Invalid HostPath type %v", hostPath.Type)
return nil, fmt.Errorf("invalid HostPath type %v", hostPath.Type)
}
}
if err := parse.ValidateVolumeHostDir(hostPath.Path); err != nil {
return nil, errors.Wrapf(err, "error in parsing HostPath in YAML")
return nil, fmt.Errorf("error in parsing HostPath in YAML: %w", err)
}
return &KubeVolume{
@ -152,7 +153,7 @@ func VolumeFromConfigMap(configMapVolumeSource *v1.ConfigMapVolumeSource, config
kv.Optional = *configMapVolumeSource.Optional
return kv, nil
}
return nil, errors.Errorf("no such ConfigMap %q", configMapVolumeSource.Name)
return nil, fmt.Errorf("no such ConfigMap %q", configMapVolumeSource.Name)
}
// If there are Items specified in the volumeSource, that overwrites the Data from the configmap
@ -180,7 +181,7 @@ func VolumeFromSource(volumeSource v1.VolumeSource, configMaps []v1.ConfigMap) (
case volumeSource.ConfigMap != nil:
return VolumeFromConfigMap(volumeSource.ConfigMap, configMaps)
default:
return nil, errors.Errorf("HostPath, ConfigMap, and PersistentVolumeClaim are currently the only supported VolumeSource")
return nil, errors.New("HostPath, ConfigMap, and PersistentVolumeClaim are currently the only supported VolumeSource")
}
}
@ -191,7 +192,7 @@ func InitializeVolumes(specVolumes []v1.Volume, configMaps []v1.ConfigMap) (map[
for _, specVolume := range specVolumes {
volume, err := VolumeFromSource(specVolume.VolumeSource, configMaps)
if err != nil {
return nil, errors.Wrapf(err, "failed to create volume %q", specVolume.Name)
return nil, fmt.Errorf("failed to create volume %q: %w", specVolume.Name, err)
}
volumes[specVolume.Name] = volume

View File

@ -1,6 +1,7 @@
package generate
import (
"errors"
"fmt"
"os"
"strings"
@ -15,7 +16,6 @@ import (
"github.com/containers/podman/v4/pkg/util"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
@ -94,7 +94,7 @@ func GetDefaultNamespaceMode(nsType string, cfg *config.Config, pod *libpod.Pod)
return ns, err
}
return toReturn, errors.Wrapf(define.ErrInvalidArg, "invalid namespace type %q passed", nsType)
return toReturn, fmt.Errorf("invalid namespace type %q passed: %w", nsType, define.ErrInvalidArg)
}
// namespaceOptions generates container creation options for all
@ -113,18 +113,18 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod.
if err != nil {
// This is likely to be of the fatal kind (pod was
// removed) so hard fail
return nil, errors.Wrapf(err, "error looking up pod %s infra container", pod.ID())
return nil, fmt.Errorf("error looking up pod %s infra container: %w", pod.ID(), err)
}
if infraID != "" {
ctr, err := rt.GetContainer(infraID)
if err != nil {
return nil, errors.Wrapf(err, "error retrieving pod %s infra container %s", pod.ID(), infraID)
return nil, fmt.Errorf("error retrieving pod %s infra container %s: %w", pod.ID(), infraID, err)
}
infraCtr = ctr
}
}
errNoInfra := errors.Wrapf(define.ErrInvalidArg, "cannot use pod namespace as container is not joining a pod or pod has no infra container")
errNoInfra := fmt.Errorf("cannot use pod namespace as container is not joining a pod or pod has no infra container: %w", define.ErrInvalidArg)
// PID
switch s.PidNS.NSMode {
@ -136,7 +136,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod.
case specgen.FromContainer:
pidCtr, err := rt.LookupContainer(s.PidNS.Value)
if err != nil {
return nil, errors.Wrapf(err, "error looking up container to share pid namespace with")
return nil, fmt.Errorf("error looking up container to share pid namespace with: %w", err)
}
toReturn = append(toReturn, libpod.WithPIDNSFrom(pidCtr))
}
@ -155,10 +155,10 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod.
case specgen.FromContainer:
ipcCtr, err := rt.LookupContainer(s.IpcNS.Value)
if err != nil {
return nil, errors.Wrapf(err, "error looking up container to share ipc namespace with")
return nil, fmt.Errorf("error looking up container to share ipc namespace with: %w", err)
}
if ipcCtr.ConfigNoCopy().NoShmShare {
return nil, errors.Errorf("joining IPC of container %s is not allowed: non-shareable IPC (hint: use IpcMode:shareable for the donor container)", ipcCtr.ID())
return nil, fmt.Errorf("joining IPC of container %s is not allowed: non-shareable IPC (hint: use IpcMode:shareable for the donor container)", ipcCtr.ID())
}
toReturn = append(toReturn, libpod.WithIPCNSFrom(ipcCtr))
if !ipcCtr.ConfigNoCopy().NoShm {
@ -187,7 +187,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod.
case specgen.FromContainer:
utsCtr, err := rt.LookupContainer(s.UtsNS.Value)
if err != nil {
return nil, errors.Wrapf(err, "error looking up container to share uts namespace with")
return nil, fmt.Errorf("error looking up container to share uts namespace with: %w", err)
}
toReturn = append(toReturn, libpod.WithUTSNSFrom(utsCtr))
}
@ -222,7 +222,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod.
case specgen.FromContainer:
userCtr, err := rt.LookupContainer(s.UserNS.Value)
if err != nil {
return nil, errors.Wrapf(err, "error looking up container to share user namespace with")
return nil, fmt.Errorf("error looking up container to share user namespace with: %w", err)
}
toReturn = append(toReturn, libpod.WithUserNSFrom(userCtr))
}
@ -234,7 +234,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod.
if pod == nil {
toReturn = append(toReturn, libpod.WithIDMappings(*s.IDMappings))
} else if pod.HasInfraContainer() && (len(s.IDMappings.UIDMap) > 0 || len(s.IDMappings.GIDMap) > 0) {
return nil, errors.Wrapf(define.ErrInvalidArg, "cannot specify a new uid/gid map when entering a pod with an infra container")
return nil, fmt.Errorf("cannot specify a new uid/gid map when entering a pod with an infra container: %w", define.ErrInvalidArg)
}
}
if s.User != "" {
@ -254,7 +254,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod.
case specgen.FromContainer:
cgroupCtr, err := rt.LookupContainer(s.CgroupNS.Value)
if err != nil {
return nil, errors.Wrapf(err, "error looking up container to share cgroup namespace with")
return nil, fmt.Errorf("error looking up container to share cgroup namespace with: %w", err)
}
toReturn = append(toReturn, libpod.WithCgroupNSFrom(cgroupCtr))
}
@ -282,7 +282,7 @@ func namespaceOptions(s *specgen.SpecGenerator, rt *libpod.Runtime, pod *libpod.
case specgen.FromContainer:
netCtr, err := rt.LookupContainer(s.NetNS.Value)
if err != nil {
return nil, errors.Wrapf(err, "error looking up container to share net namespace with")
return nil, fmt.Errorf("error looking up container to share net namespace with: %w", err)
}
toReturn = append(toReturn, libpod.WithNetNSFrom(netCtr))
case specgen.Slirp:
@ -362,7 +362,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt
switch s.PidNS.NSMode {
case specgen.Path:
if _, err := os.Stat(s.PidNS.Value); err != nil {
return errors.Wrap(err, "cannot find specified PID namespace path")
return fmt.Errorf("cannot find specified PID namespace path: %w", err)
}
if err := g.AddOrReplaceLinuxNamespace(string(spec.PIDNamespace), s.PidNS.Value); err != nil {
return err
@ -381,7 +381,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt
switch s.IpcNS.NSMode {
case specgen.Path:
if _, err := os.Stat(s.IpcNS.Value); err != nil {
return errors.Wrap(err, "cannot find specified IPC namespace path")
return fmt.Errorf("cannot find specified IPC namespace path: %w", err)
}
if err := g.AddOrReplaceLinuxNamespace(string(spec.IPCNamespace), s.IpcNS.Value); err != nil {
return err
@ -400,7 +400,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt
switch s.UtsNS.NSMode {
case specgen.Path:
if _, err := os.Stat(s.UtsNS.Value); err != nil {
return errors.Wrap(err, "cannot find specified UTS namespace path")
return fmt.Errorf("cannot find specified UTS namespace path: %w", err)
}
if err := g.AddOrReplaceLinuxNamespace(string(spec.UTSNamespace), s.UtsNS.Value); err != nil {
return err
@ -423,13 +423,13 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt
case s.UtsNS.NSMode == specgen.FromContainer:
utsCtr, err := rt.LookupContainer(s.UtsNS.Value)
if err != nil {
return errors.Wrapf(err, "error looking up container to share uts namespace with")
return fmt.Errorf("error looking up container to share uts namespace with: %w", err)
}
hostname = utsCtr.Hostname()
case (s.NetNS.NSMode == specgen.Host && hostname == "") || s.UtsNS.NSMode == specgen.Host:
tmpHostname, err := os.Hostname()
if err != nil {
return errors.Wrap(err, "unable to retrieve hostname of the host")
return fmt.Errorf("unable to retrieve hostname of the host: %w", err)
}
hostname = tmpHostname
default:
@ -458,7 +458,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt
switch s.CgroupNS.NSMode {
case specgen.Path:
if _, err := os.Stat(s.CgroupNS.Value); err != nil {
return errors.Wrap(err, "cannot find specified cgroup namespace path")
return fmt.Errorf("cannot find specified cgroup namespace path: %w", err)
}
if err := g.AddOrReplaceLinuxNamespace(string(spec.CgroupNamespace), s.CgroupNS.Value); err != nil {
return err
@ -477,7 +477,7 @@ func specConfigureNamespaces(s *specgen.SpecGenerator, g *generate.Generator, rt
switch s.NetNS.NSMode {
case specgen.Path:
if _, err := os.Stat(s.NetNS.Value); err != nil {
return errors.Wrap(err, "cannot find specified network namespace path")
return fmt.Errorf("cannot find specified network namespace path: %w", err)
}
if err := g.AddOrReplaceLinuxNamespace(string(spec.NetworkNamespace), s.NetNS.Value); err != nil {
return err
@ -521,7 +521,7 @@ func GetNamespaceOptions(ns []string, netnsIsHost bool) ([]libpod.PodCreateOptio
case "net":
options = append(options, libpod.WithPodNet())
case "mnt":
return erroredOptions, errors.Errorf("Mount sharing functionality not supported on pod level")
return erroredOptions, fmt.Errorf("mount sharing functionality not supported on pod level")
case "pid":
options = append(options, libpod.WithPodPID())
case "user":
@ -534,7 +534,7 @@ func GetNamespaceOptions(ns []string, netnsIsHost bool) ([]libpod.PodCreateOptio
case "none":
return erroredOptions, nil
default:
return erroredOptions, errors.Errorf("Invalid kernel namespace to share: %s. Options are: cgroup, ipc, net, pid, uts or none", toShare)
return erroredOptions, fmt.Errorf("invalid kernel namespace to share: %s. Options are: cgroup, ipc, net, pid, uts or none", toShare)
}
}
return options, nil

View File

@ -3,6 +3,7 @@ package generate
import (
"context"
"encoding/json"
"fmt"
"path"
"strings"
@ -15,7 +16,6 @@ import (
"github.com/containers/podman/v4/pkg/specgen"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
@ -117,7 +117,7 @@ func makeCommand(s *specgen.SpecGenerator, imageData *libimage.ImageData, rtc *c
finalCommand = append(finalCommand, command...)
if len(finalCommand) == 0 {
return nil, errors.Errorf("no command or entrypoint provided, and no CMD or ENTRYPOINT from image")
return nil, fmt.Errorf("no command or entrypoint provided, and no CMD or ENTRYPOINT from image")
}
if s.Init {
@ -126,7 +126,7 @@ func makeCommand(s *specgen.SpecGenerator, imageData *libimage.ImageData, rtc *c
initPath = rtc.Engine.InitPath
}
if initPath == "" {
return nil, errors.Errorf("no path to init binary found but container requested an init")
return nil, fmt.Errorf("no path to init binary found but container requested an init")
}
finalCommand = append([]string{define.ContainerInitPath, "--"}, finalCommand...)
}
@ -348,7 +348,7 @@ func SpecGenToOCI(ctx context.Context, s *specgen.SpecGenerator, rt *libpod.Runt
for k, v := range s.WeightDevice {
statT := unix.Stat_t{}
if err := unix.Stat(k, &statT); err != nil {
return nil, errors.Wrapf(err, "failed to inspect '%s' in --blkio-weight-device", k)
return nil, fmt.Errorf("failed to inspect '%s' in --blkio-weight-device: %w", k, err)
}
g.AddLinuxResourcesBlockIOWeightDevice((int64(unix.Major(uint64(statT.Rdev)))), (int64(unix.Minor(uint64(statT.Rdev)))), *v.Weight) //nolint: unconvert
}

Some files were not shown because too many files have changed in this diff Show More