mirror of
https://github.com/docker/compose.git
synced 2026-11-20 23:22:29 +00:00
feat(api): reject an unknown recreate policy instead of treating it as diverged
CreateOptions.Recreate and RecreateDependencies are strings, and any value other than force or never silently behaved like diverged: a typo such as "forced" was accepted and did the opposite of what the caller meant. Add CreateOptions.Validate, which rejects such values with an InvalidOptionError matching the new ErrInvalidOption, and call it from Create and, through UpOptions.Validate, from Up, before anything is touched. The empty string keeps meaning diverged, and the Recreate* constants are unchanged, so existing callers are not affected. Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
This commit is contained in:
parent
c86790ce58
commit
bd07e0b4c0
8 changed files with 228 additions and 4 deletions
|
|
@ -350,7 +350,7 @@ type CreateOptions struct {
|
|||
IgnoreOrphans bool
|
||||
// Recreate define the strategy to apply on existing containers: one of
|
||||
// RecreateDiverged (the default, also used for ""), RecreateForce or
|
||||
// RecreateNever.
|
||||
// RecreateNever. Any other value is rejected by Validate.
|
||||
Recreate string
|
||||
// RecreateDependencies define the strategy to apply on dependencies
|
||||
// services, with the same values as Recreate.
|
||||
|
|
|
|||
80
pkg/api/create_options.go
Normal file
80
pkg/api/create_options.go
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
/*
|
||||
Copyright 2020 Docker Compose CLI authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// InvalidOptionError reports an option set to a value it does not accept. It is
|
||||
// returned, before any side effect, by CreateOptions.Validate and therefore by
|
||||
// Compose.Create and Compose.Up.
|
||||
//
|
||||
// It matches ErrInvalidOption with errors.Is, and callers needing the details
|
||||
// can retrieve it with errors.As.
|
||||
type InvalidOptionError struct {
|
||||
// Option names the option field, as a Go selector relative to the options
|
||||
// type that was validated (e.g. "Recreate").
|
||||
Option string
|
||||
// Value is the value that was set.
|
||||
Value string
|
||||
// Allowed lists the values the option accepts.
|
||||
Allowed []string
|
||||
}
|
||||
|
||||
func (e *InvalidOptionError) Error() string {
|
||||
return fmt.Sprintf("%s (%s): %q is not one of %s", ErrInvalidOption, e.Option, e.Value, strings.Join(e.Allowed, ", "))
|
||||
}
|
||||
|
||||
// Unwrap makes errors.Is(err, ErrInvalidOption) hold.
|
||||
func (e *InvalidOptionError) Unwrap() error {
|
||||
return ErrInvalidOption
|
||||
}
|
||||
|
||||
// Validate checks that the values of the options are among the ones they
|
||||
// accept: Recreate and RecreateDependencies must be empty (which means
|
||||
// RecreateDiverged) or one of the Recreate* constants. It is a pure function,
|
||||
// called by Create and Up before they do anything, and can also be called by
|
||||
// integrators to fail early.
|
||||
//
|
||||
// It returns nil, or an error matching ErrInvalidOption. With several invalid
|
||||
// options, the errors are joined with errors.Join: errors.Is still holds, but
|
||||
// errors.As to *InvalidOptionError only yields the first one.
|
||||
func (o CreateOptions) Validate() error {
|
||||
var errs []error
|
||||
errs = append(errs, validateRecreatePolicy("Recreate", o.Recreate)...)
|
||||
errs = append(errs, validateRecreatePolicy("RecreateDependencies", o.RecreateDependencies)...)
|
||||
switch len(errs) {
|
||||
case 0:
|
||||
return nil
|
||||
case 1:
|
||||
return errs[0]
|
||||
default:
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
}
|
||||
|
||||
func validateRecreatePolicy(option, policy string) []error {
|
||||
allowed := []string{RecreateDiverged, RecreateForce, RecreateNever}
|
||||
if policy == "" || slices.Contains(allowed, policy) {
|
||||
return nil
|
||||
}
|
||||
return []error{&InvalidOptionError{Option: option, Value: policy, Allowed: allowed}}
|
||||
}
|
||||
87
pkg/api/create_options_test.go
Normal file
87
pkg/api/create_options_test.go
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
/*
|
||||
Copyright 2020 Docker Compose CLI authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"gotest.tools/v3/assert"
|
||||
)
|
||||
|
||||
func TestCreateOptionsValidate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
options CreateOptions
|
||||
// invalid lists the options expected to be rejected, empty when valid
|
||||
invalid []string
|
||||
}{
|
||||
{name: "zero value is valid", options: CreateOptions{}},
|
||||
{name: "diverged", options: CreateOptions{Recreate: RecreateDiverged, RecreateDependencies: RecreateDiverged}},
|
||||
{name: "force", options: CreateOptions{Recreate: RecreateForce, RecreateDependencies: RecreateForce}},
|
||||
{name: "never", options: CreateOptions{Recreate: RecreateNever, RecreateDependencies: RecreateNever}},
|
||||
{name: "unknown recreate", options: CreateOptions{Recreate: "forced"}, invalid: []string{"Recreate"}},
|
||||
{name: "unknown dependencies recreate", options: CreateOptions{RecreateDependencies: "always"}, invalid: []string{"RecreateDependencies"}},
|
||||
{name: "case matters", options: CreateOptions{Recreate: "Force"}, invalid: []string{"Recreate"}},
|
||||
{name: "both unknown", options: CreateOptions{Recreate: "x", RecreateDependencies: "y"}, invalid: []string{"Recreate", "RecreateDependencies"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := tt.options.Validate()
|
||||
if len(tt.invalid) == 0 {
|
||||
assert.NilError(t, err)
|
||||
return
|
||||
}
|
||||
assert.Assert(t, errors.Is(err, ErrInvalidOption), "got %v", err)
|
||||
assert.Assert(t, IsErrInvalidOption(err))
|
||||
|
||||
// every invalid option is reported, whether the error is a single
|
||||
// *InvalidOptionError or several of them joined
|
||||
var reported []string
|
||||
var walk func(error)
|
||||
walk = func(e error) {
|
||||
if joined, ok := e.(interface{ Unwrap() []error }); ok {
|
||||
for _, inner := range joined.Unwrap() {
|
||||
walk(inner)
|
||||
}
|
||||
return
|
||||
}
|
||||
var invalid *InvalidOptionError
|
||||
if errors.As(e, &invalid) {
|
||||
reported = append(reported, invalid.Option)
|
||||
}
|
||||
}
|
||||
walk(err)
|
||||
assert.DeepEqual(t, reported, tt.invalid)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidOptionErrorMessage(t *testing.T) {
|
||||
err := CreateOptions{Recreate: "forced"}.Validate()
|
||||
assert.Error(t, err, `invalid option (Recreate): "forced" is not one of diverged, force, never`)
|
||||
}
|
||||
|
||||
func TestUpOptionsValidateReportsInvalidCreateOptions(t *testing.T) {
|
||||
err := UpOptions{Create: CreateOptions{Recreate: "forced"}}.Validate()
|
||||
assert.Assert(t, errors.Is(err, ErrInvalidOption), "got %v", err)
|
||||
|
||||
// invalid values and incompatible combinations are reported together
|
||||
err = UpOptions{Create: CreateOptions{Recreate: "forced"}, Start: StartOptions{Wait: true, Attach: nopConsumer{}}}.Validate()
|
||||
assert.Assert(t, errors.Is(err, ErrInvalidOption), "got %v", err)
|
||||
assert.Assert(t, errors.Is(err, ErrIncompatibleOptions), "got %v", err)
|
||||
}
|
||||
|
|
@ -30,8 +30,8 @@
|
|||
// flag also forces the recreation of every container). The CLI default
|
||||
// is to retrieve their data from the previous container (Inherit: true).
|
||||
// - [CreateOptions].Recreate and RecreateDependencies: the empty string
|
||||
// means [RecreateDiverged], and so does any value that is not one of the
|
||||
// Recreate* constants.
|
||||
// means [RecreateDiverged]. Any value other than the Recreate* constants
|
||||
// is rejected by [CreateOptions.Validate] before anything is changed.
|
||||
// - [CreateOptions].RemoveOrphans and IgnoreOrphans: when both are false,
|
||||
// orphan containers are kept and a warning is logged. IgnoreOrphans
|
||||
// silences that warning, RemoveOrphans removes the containers.
|
||||
|
|
|
|||
|
|
@ -48,6 +48,9 @@ var (
|
|||
// ErrIncompatibleOptions is returned when a set of options that cannot be
|
||||
// honored together is requested. See IncompatibleOptionsError.
|
||||
ErrIncompatibleOptions = errors.New("incompatible options")
|
||||
// ErrInvalidOption is returned when an option is set to a value it does
|
||||
// not accept. See InvalidOptionError.
|
||||
ErrInvalidOption = errors.New("invalid option")
|
||||
)
|
||||
|
||||
// IsNotFoundError returns true if the unwrapped error is ErrNotFound
|
||||
|
|
@ -94,3 +97,8 @@ func IsErrCanceled(err error) bool {
|
|||
func IsErrIncompatibleOptions(err error) bool {
|
||||
return errors.Is(err, ErrIncompatibleOptions)
|
||||
}
|
||||
|
||||
// IsErrInvalidOption returns true if the unwrapped error is ErrInvalidOption
|
||||
func IsErrInvalidOption(err error) bool {
|
||||
return errors.Is(err, ErrInvalidOption)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -58,7 +58,8 @@ func incompatible(reason string, options ...string) error {
|
|||
// Validate checks that the options requested for Up can be honored together.
|
||||
// It is a pure function, called by Up before it does anything, and can also be
|
||||
// called by integrators to fail early. It returns nil, or an error matching
|
||||
// ErrIncompatibleOptions describing every conflict found.
|
||||
// ErrIncompatibleOptions describing every conflict found, or ErrInvalidOption
|
||||
// when Create holds a value that CreateOptions.Validate rejects.
|
||||
//
|
||||
// Up has two modes, selected by Start.Attach: detached (nil) returns once the
|
||||
// containers are started, interactive (set) keeps running a foreground session.
|
||||
|
|
@ -78,6 +79,9 @@ func incompatible(reason string, options ...string) error {
|
|||
// flags; Validate is the safety net for programs using the library directly.
|
||||
func (o UpOptions) Validate() error {
|
||||
var errs []error
|
||||
if err := o.Create.Validate(); err != nil {
|
||||
errs = append(errs, err)
|
||||
}
|
||||
errs = append(errs, validateWaitIsDetached(o.Start)...)
|
||||
errs = append(errs, validateDetachedHasNoSession(o.Start)...)
|
||||
switch len(errs) {
|
||||
|
|
|
|||
|
|
@ -68,6 +68,9 @@ type createConfigs struct {
|
|||
}
|
||||
|
||||
func (s *composeService) Create(ctx context.Context, project *types.Project, options api.CreateOptions) error {
|
||||
if err := options.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return Run(ctx, func(ctx context.Context) error {
|
||||
return s.create(ctx, project, options)
|
||||
}, "create", s.events)
|
||||
|
|
|
|||
42
pkg/compose/create_validate_test.go
Normal file
42
pkg/compose/create_validate_test.go
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
/*
|
||||
Copyright 2020 Docker Compose CLI authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package compose
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/compose-spec/compose-go/v2/types"
|
||||
"gotest.tools/v3/assert"
|
||||
|
||||
"github.com/docker/compose/v5/internal/progress"
|
||||
"github.com/docker/compose/v5/pkg/api"
|
||||
)
|
||||
|
||||
// An unknown recreate policy must be rejected before the engine is reached: the
|
||||
// service has no client, so any attempt to go further would panic.
|
||||
func TestCreateAndUpRejectInvalidOptions(t *testing.T) {
|
||||
s := &composeService{events: progress.Noop{}}
|
||||
project := &types.Project{Name: "test"}
|
||||
invalid := api.CreateOptions{Recreate: "forced"}
|
||||
|
||||
err := s.Create(t.Context(), project, invalid)
|
||||
assert.Assert(t, errors.Is(err, api.ErrInvalidOption), "got %v", err)
|
||||
|
||||
err = s.Up(t.Context(), project, api.UpOptions{Create: invalid})
|
||||
assert.Assert(t, errors.Is(err, api.ErrInvalidOption), "got %v", err)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue