Update to github.com/containers/common v0.49.0

Signed-off-by: Miloslav Trmač <mitr@redhat.com>
This commit is contained in:
Miloslav Trmač
2022-07-25 18:13:11 +02:00
parent 049163fcec
commit 08846d18cc
7 changed files with 81 additions and 69 deletions

View File

@@ -3,6 +3,7 @@ package auth
import (
"bufio"
"context"
"errors"
"fmt"
"net/url"
"os"
@@ -14,7 +15,6 @@ import (
"github.com/containers/image/v5/pkg/docker/config"
"github.com/containers/image/v5/pkg/sysregistriesv2"
"github.com/containers/image/v5/types"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
terminal "golang.org/x/term"
)
@@ -26,8 +26,8 @@ func GetDefaultAuthFile() string {
if authfile := os.Getenv("REGISTRY_AUTH_FILE"); authfile != "" {
return authfile
}
if auth_env := os.Getenv("DOCKER_CONFIG"); auth_env != "" {
return filepath.Join(auth_env, "config.json")
if authEnv := os.Getenv("DOCKER_CONFIG"); authEnv != "" {
return filepath.Join(authEnv, "config.json")
}
return ""
}
@@ -39,7 +39,7 @@ func CheckAuthFile(authfile string) error {
return nil
}
if _, err := os.Stat(authfile); err != nil {
return errors.Wrap(err, "checking authfile")
return fmt.Errorf("checking authfile: %w", err)
}
return nil
}
@@ -97,12 +97,12 @@ func Login(ctx context.Context, systemContext *types.SystemContext, opts *LoginO
authConfig, err := config.GetCredentials(systemContext, key)
if err != nil {
return errors.Wrap(err, "get credentials")
return fmt.Errorf("get credentials: %w", err)
}
if opts.GetLoginSet {
if authConfig.Username == "" {
return errors.Errorf("not logged into %s", key)
return fmt.Errorf("not logged into %s", key)
}
fmt.Fprintf(opts.Stdout, "%s\n", authConfig.Username)
return nil
@@ -139,7 +139,7 @@ func Login(ctx context.Context, systemContext *types.SystemContext, opts *LoginO
username, password, err := getUserAndPass(opts, password, authConfig.Username)
if err != nil {
return errors.Wrap(err, "getting username and password")
return fmt.Errorf("getting username and password: %w", err)
}
if err = docker.CheckAuth(ctx, systemContext, username, password, registry); err == nil {
@@ -158,9 +158,9 @@ func Login(ctx context.Context, systemContext *types.SystemContext, opts *LoginO
}
if unauthorized, ok := err.(docker.ErrUnauthorizedForCredentials); ok {
logrus.Debugf("error logging into %q: %v", key, unauthorized)
return errors.Errorf("error logging into %q: invalid username/password", key)
return fmt.Errorf("error logging into %q: invalid username/password", key)
}
return errors.Wrapf(err, "authenticating creds for %q", key)
return fmt.Errorf("authenticating creds for %q: %w", key, err)
}
// parseCredentialsKey turns the provided argument into a valid credential key
@@ -191,10 +191,10 @@ func parseCredentialsKey(arg string, acceptRepositories bool) (key, registry str
// Ideally c/image should provide dedicated validation functionality.
ref, err := reference.ParseNormalizedNamed(key)
if err != nil {
return "", "", errors.Wrapf(err, "parse reference from %q", key)
return "", "", fmt.Errorf("parse reference from %q: %w", key, err)
}
if !reference.IsNameOnly(ref) {
return "", "", errors.Errorf("reference %q contains tag or digest", ref.String())
return "", "", fmt.Errorf("reference %q contains tag or digest", ref.String())
}
refRegistry := reference.Domain(ref)
if refRegistry != registry { // This should never happen, check just to make sure
@@ -232,7 +232,7 @@ func getUserAndPass(opts *LoginOptions, password, userFromAuthFile string) (user
}
username, err = reader.ReadString('\n')
if err != nil {
return "", "", errors.Wrap(err, "reading username")
return "", "", fmt.Errorf("reading username: %w", err)
}
// If the user just hit enter, use the displayed user from the
// the authentication file. This allows to do a lazy
@@ -246,7 +246,7 @@ func getUserAndPass(opts *LoginOptions, password, userFromAuthFile string) (user
fmt.Fprint(opts.Stdout, "Password: ")
pass, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
return "", "", errors.Wrap(err, "reading password")
return "", "", fmt.Errorf("reading password: %w", err)
}
password = string(pass)
fmt.Fprintln(opts.Stdout)
@@ -298,14 +298,15 @@ func Logout(systemContext *types.SystemContext, opts *LogoutOptions, args []stri
}
err = config.RemoveAuthentication(systemContext, key)
switch errors.Cause(err) {
case nil:
if err == nil {
fmt.Fprintf(opts.Stdout, "Removed login credentials for %s\n", key)
return nil
case config.ErrNotLoggedIn:
}
if errors.Is(err, config.ErrNotLoggedIn) {
authConfig, err := config.GetCredentials(systemContext, key)
if err != nil {
return errors.Wrap(err, "get credentials")
return fmt.Errorf("get credentials: %w", err)
}
authInvalid := docker.CheckAuth(context.Background(), systemContext, authConfig.Username, authConfig.Password, registry)
@@ -313,10 +314,10 @@ func Logout(systemContext *types.SystemContext, opts *LogoutOptions, args []stri
fmt.Printf("Not logged into %s with current tool. Existing credentials were established via docker login. Please use docker logout instead.\n", key)
return nil
}
return errors.Errorf("Not logged into %s\n", key)
default:
return errors.Wrapf(err, "logging out of %q", key)
return fmt.Errorf("not logged into %s", key)
}
return fmt.Errorf("logging out of %q: %w", key, err)
}
// defaultRegistryWhenUnspecified returns first registry from search list of registry.conf
@@ -324,7 +325,7 @@ func Logout(systemContext *types.SystemContext, opts *LogoutOptions, args []stri
func defaultRegistryWhenUnspecified(systemContext *types.SystemContext) (string, error) {
registriesFromFile, err := sysregistriesv2.UnqualifiedSearchRegistries(systemContext)
if err != nil {
return "", errors.Wrap(err, "getting registry from registry.conf, please specify a registry")
return "", fmt.Errorf("getting registry from registry.conf, please specify a registry: %w", err)
}
if len(registriesFromFile) == 0 {
return "", errors.New("no registries found in registries.conf, a registry must be provided")

View File

@@ -6,11 +6,12 @@ package capabilities
// changed significantly to fit the needs of libpod.
import (
"errors"
"fmt"
"sort"
"strings"
"sync"
"github.com/pkg/errors"
"github.com/syndtr/gocapability/capability"
)
@@ -104,8 +105,8 @@ func AllCapabilities() []string {
// NormalizeCapabilities normalizes caps by adding a "CAP_" prefix (if not yet
// present).
func NormalizeCapabilities(caps []string) ([]string, error) {
normalized := make([]string, len(caps))
for i, c := range caps {
normalized := make([]string, 0, len(caps))
for _, c := range caps {
c = strings.ToUpper(c)
if c == All {
normalized = append(normalized, c)
@@ -115,9 +116,9 @@ func NormalizeCapabilities(caps []string) ([]string, error) {
c = "CAP_" + c
}
if !stringInSlice(c, capabilityList) {
return nil, errors.Wrapf(ErrUnknownCapability, "%q", c)
return nil, fmt.Errorf("%q: %w", c, ErrUnknownCapability)
}
normalized[i] = c
normalized = append(normalized, c)
}
sort.Strings(normalized)
return normalized, nil
@@ -127,7 +128,7 @@ func NormalizeCapabilities(caps []string) ([]string, error) {
func ValidateCapabilities(caps []string) error {
for _, c := range caps {
if !stringInSlice(c, capabilityList) {
return errors.Wrapf(ErrUnknownCapability, "%q", c)
return fmt.Errorf("%q: %w", c, ErrUnknownCapability)
}
}
return nil
@@ -140,8 +141,6 @@ func ValidateCapabilities(caps []string) error {
// "ALL" in capAdd adds returns known capabilities
// "All" in capDrop returns only the capabilities specified in capAdd
func MergeCapabilities(base, adds, drops []string) ([]string, error) {
var caps []string
// Normalize the base capabilities
base, err := NormalizeCapabilities(base)
if err != nil {
@@ -178,17 +177,18 @@ func MergeCapabilities(base, adds, drops []string) ([]string, error) {
} else {
for _, add := range capAdd {
if stringInSlice(add, capDrop) {
return nil, errors.Errorf("capability %q cannot be dropped and added", add)
return nil, fmt.Errorf("capability %q cannot be dropped and added", add)
}
}
}
for _, drop := range capDrop {
if stringInSlice(drop, capAdd) {
return nil, errors.Errorf("capability %q cannot be dropped and added", drop)
return nil, fmt.Errorf("capability %q cannot be dropped and added", drop)
}
}
caps := make([]string, 0, len(base)+len(capAdd))
// Drop any capabilities in capDrop that are in base
for _, cap := range base {
if stringInSlice(cap, capDrop) {

View File

@@ -51,7 +51,7 @@ func AutocompleteCapabilities(cmd *cobra.Command, args []string, toComplete stri
offset = 4
}
var completions []string
completions := make([]string, 0, len(caps))
for _, cap := range caps {
completions = append(completions, convertCase(cap)[offset:])
}

View File

@@ -12,25 +12,32 @@ import (
"github.com/docker/distribution/registry/api/errcode"
errcodev2 "github.com/docker/distribution/registry/api/v2"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// RetryOptions defines the option to retry
type RetryOptions struct {
MaxRetry int // The number of times to possibly retry
Delay time.Duration // The delay to use between retries, if set
// Options defines the option to retry.
type Options struct {
MaxRetry int // The number of times to possibly retry.
Delay time.Duration // The delay to use between retries, if set.
}
// RetryIfNecessary retries the operation in exponential backoff with the retryOptions
func RetryIfNecessary(ctx context.Context, operation func() error, retryOptions *RetryOptions) error {
// RetryOptions is deprecated, use Options.
type RetryOptions = Options // nolint:revive
// RetryIfNecessary deprecated function use IfNecessary.
func RetryIfNecessary(ctx context.Context, operation func() error, options *Options) error { // nolint:revive
return IfNecessary(ctx, operation, options)
}
// IfNecessary retries the operation in exponential backoff with the retry Options.
func IfNecessary(ctx context.Context, operation func() error, options *Options) error {
err := operation()
for attempt := 0; err != nil && isRetryable(err) && attempt < retryOptions.MaxRetry; attempt++ {
for attempt := 0; err != nil && isRetryable(err) && attempt < options.MaxRetry; attempt++ {
delay := time.Duration(int(math.Pow(2, float64(attempt)))) * time.Second
if retryOptions.Delay != 0 {
delay = retryOptions.Delay
if options.Delay != 0 {
delay = options.Delay
}
logrus.Warnf("Failed, retrying in %s ... (%d/%d). Error: %v", delay, attempt+1, retryOptions.MaxRetry, err)
logrus.Warnf("Failed, retrying in %s ... (%d/%d). Error: %v", delay, attempt+1, options.MaxRetry, err)
select {
case <-time.After(delay):
break
@@ -43,8 +50,6 @@ func RetryIfNecessary(ctx context.Context, operation func() error, retryOptions
}
func isRetryable(err error) bool {
err = errors.Cause(err)
switch err {
case nil:
return false
@@ -91,6 +96,14 @@ func isRetryable(err error) bool {
}
}
return true
case net.Error:
if e.Timeout() {
return true
}
if unwrappable, ok := e.(unwrapper); ok {
err = unwrappable.Unwrap()
return isRetryable(err)
}
case unwrapper: // Test this last, because various error types might implement .Unwrap()
err = e.Unwrap()
return isRetryable(err)