Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion cmd/compose/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,13 @@ func applyScaleOpts(project *types.Project, opts []string) error {
}
replicas, err := strconv.Atoi(val)
if err != nil {
return err
return fmt.Errorf("invalid --scale option %q: %w", scale, err)
}
if replicas < 0 {
return &api.InvalidOptionError{
Option: "scale",
Reason: fmt.Sprintf("%s: replica count must be greater than or equal to 0", scale),
}
}
err = setServiceScale(project, name, replicas)
if err != nil {
Expand Down
6 changes: 6 additions & 0 deletions cmd/compose/scale.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,12 @@ func parseServicesReplicasArgs(args []string) (map[string]int, error) {
if err != nil {
return nil, fmt.Errorf("invalid scale specifier: can't parse replica value as int: %v", arg)
}
if intValue < 0 {
return nil, &api.InvalidOptionError{
Option: "scale",
Reason: fmt.Sprintf("%s: replica count must be greater than or equal to 0", arg),
}
}
serviceReplicaTuples[key] = intValue
}
return serviceReplicaTuples, nil
Expand Down
131 changes: 131 additions & 0 deletions cmd/compose/scale_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/*
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/docker/compose/v5/pkg/api"
"gotest.tools/v3/assert"
)

func TestParseServicesReplicasArgs(t *testing.T) {
tests := []struct {
name string
args []string
want map[string]int
wantErr string
}{
{
name: "single service",
args: []string{"web=2"},
want: map[string]int{"web": 2},
},
{
name: "multiple services",
args: []string{"web=2", "db=1"},
want: map[string]int{"web": 2, "db": 1},
},
{
name: "zero replicas is allowed",
args: []string{"web=0"},
want: map[string]int{"web": 0},
},
{
name: "negative replicas is rejected",
args: []string{"web=-1"},
wantErr: "invalid option (scale): web=-1: replica count must be greater than or equal to 0",
},
{
name: "one negative among valid services is rejected",
args: []string{"web=2", "db=-3"},
wantErr: "invalid option (scale): db=-3: replica count must be greater than or equal to 0",
},
{
name: "missing equals sign",
args: []string{"web"},
wantErr: "invalid scale specifier: web",
},
{
name: "empty value",
args: []string{"web="},
wantErr: "invalid scale specifier: web=",
},
{
name: "non numeric value",
args: []string{"web=abc"},
wantErr: "invalid scale specifier: can't parse replica value as int: web=abc",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseServicesReplicasArgs(tt.args)
if tt.wantErr != "" {
assert.ErrorContains(t, err, tt.wantErr)
assert.Assert(t, got == nil, "a rejected specifier must not return partial results")
return
}
assert.NilError(t, err)
assert.DeepEqual(t, got, tt.want)
})
}
}

// TestParseServicesReplicasArgsNegativeIsInvalidOption pins the error kind the
// rest of the package relies on, so the CLI failure is indistinguishable from
// the same rejection made through the SDK options.
func TestParseServicesReplicasArgsNegativeIsInvalidOption(t *testing.T) {
_, err := parseServicesReplicasArgs([]string{"web=-1"})
assert.Assert(t, errors.Is(err, api.ErrInvalidOption))

var invalid *api.InvalidOptionError
assert.Assert(t, errors.As(err, &invalid))
assert.Equal(t, invalid.Option, "scale")
}

// TestScaleOptionsValidate covers the SDK path, which bypasses the CLI parser
// entirely. api.Compose.Scale must refuse a negative count before touching the
// project model.
func TestScaleOptionsValidate(t *testing.T) {
tests := []struct {
name string
replicas map[string]int
wantErr bool
}{
{name: "empty is valid", replicas: nil},
{name: "positive is valid", replicas: map[string]int{"web": 2}},
{name: "zero is valid", replicas: map[string]int{"web": 0}},
{name: "negative is rejected", replicas: map[string]int{"web": -1}, wantErr: true},
{name: "one negative among valid is rejected", replicas: map[string]int{"web": 2, "db": -1}, wantErr: true},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := api.ScaleOptions{Replicas: tt.replicas}.Validate()
if !tt.wantErr {
assert.NilError(t, err)
return
}
assert.Assert(t, errors.Is(err, api.ErrInvalidOption))
var invalid *api.InvalidOptionError
assert.Assert(t, errors.As(err, &invalid))
assert.Equal(t, invalid.Option, "Replicas")
})
}
}
3 changes: 3 additions & 0 deletions cmd/compose/up_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ func TestApplyScaleOpt(t *testing.T) {

err = applyScaleOpts(&p, []string{"=2"})
assert.Error(t, err, `invalid --scale option "=2". Should be SERVICE=NUM`)

err = applyScaleOpts(&p, []string{"foo=-1"})
assert.ErrorContains(t, err, `invalid option (scale): foo=-1: replica count must be greater than or equal to 0`)
}

func TestUpOptions_OnExit(t *testing.T) {
Expand Down
17 changes: 17 additions & 0 deletions pkg/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,23 @@ type ScaleOptions struct {
Services []string
}

// Validate checks that every requested replica count is non-negative. The
// compose file loader already rejects a negative `scale:` or `deploy.replicas:`
// (see checkServiceScale in compose-go), so an operation must not accept
// through its options what it would reject through a file. Zero is valid and
// scales a service down to nothing.
func (o ScaleOptions) Validate() error {
for name, replicas := range o.Replicas {
if replicas < 0 {
return &InvalidOptionError{
Option: "Replicas",
Reason: fmt.Sprintf("service %q must have a replica count greater than or equal to 0, got %d", name, replicas),
}
}
}
return nil
}

type WaitOptions struct {
// Services passed in the command line to be waited
Services []string
Expand Down
3 changes: 3 additions & 0 deletions pkg/compose/scale.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ import (
)

func (s *composeService) Scale(ctx context.Context, project *types.Project, options api.ScaleOptions) error {
if err := options.Validate(); err != nil {
return err
}
return Run(ctx, tracing.SpanWrapFunc("project/scale", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error {
if err := applyReplicas(project, options.Replicas); err != nil {
return err
Expand Down
31 changes: 31 additions & 0 deletions pkg/compose/scale_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ limitations under the License.
package compose

import (
"context"
"errors"
"testing"

"github.com/compose-spec/compose-go/v2/types"
"github.com/docker/compose/v5/pkg/api"
"gotest.tools/v3/assert"
)

Expand All @@ -40,3 +43,31 @@ func TestApplyReplicas(t *testing.T) {
err = applyReplicas(project, map[string]int{"unknown": 1})
assert.ErrorContains(t, err, "no such service: unknown")
}

// TestScaleRejectsNegativeReplicasBeforeSideEffects asserts the SDK entry point
// refuses a negative replica count itself, before it mutates the project model
// or reaches the backend. The CLI parser is not in this path.
func TestScaleRejectsNegativeReplicasBeforeSideEffects(t *testing.T) {
project := &types.Project{
Services: types.Services{
"web": types.ServiceConfig{Name: "web"},
},
}

svc := &composeService{}
err := svc.Scale(context.Background(), project, api.ScaleOptions{
Replicas: map[string]int{"web": -1},
})

assert.Assert(t, err != nil, "a negative replica count must be refused")
assert.Assert(t, errors.Is(err, api.ErrInvalidOption))

var invalid *api.InvalidOptionError
assert.Assert(t, errors.As(err, &invalid))
assert.Equal(t, invalid.Option, "Replicas")

// The project model must be untouched: SetScale must not have run.
service, err := project.GetService("web")
assert.NilError(t, err)
assert.Assert(t, service.Scale == nil, "Scale must not be applied when the options are invalid")
}