1
0
mirror of https://github.com/docker/cli.git synced 2026-01-23 15:21:32 +03:00

Scope orchestration selection to stack commands only

* Renaming DOCKER_ORCHESTRATOR to DOCKER_STACK_ORCHESTRATOR
* Renaming config file option "orchestrator" to "stackOrchestrator"
* "--orchestrator" flag is no more global but local to stack command and subcommands
* Cleaning all global orchestrator code
* Replicating Hidden flags in help and Supported flags from root command to stack command

Signed-off-by: Silvin Lubecki <silvin.lubecki@docker.com>
This commit is contained in:
Silvin Lubecki
2018-06-20 14:48:50 +02:00
committed by Sebastiaan van Stijn
parent 8de0753869
commit 71272dd203
24 changed files with 329 additions and 278 deletions

View File

@@ -1,50 +1,125 @@
package stack
import (
"errors"
"fmt"
"strings"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
cliconfig "github.com/docker/cli/cli/config"
"github.com/docker/cli/cli/config/configfile"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
var errUnsupportedAllOrchestrator = fmt.Errorf(`no orchestrator specified: use either "kubernetes" or "swarm"`)
type commonOptions struct {
orchestrator command.Orchestrator
}
// NewStackCommand returns a cobra command for `stack` subcommands
func NewStackCommand(dockerCli command.Cli) *cobra.Command {
var opts commonOptions
cmd := &cobra.Command{
Use: "stack",
Short: "Manage Docker stacks",
Args: cli.NoArgs,
RunE: command.ShowHelp(dockerCli.Err()),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
orchestrator, err := getOrchestrator(dockerCli.ConfigFile(), cmd)
if err != nil {
return err
}
opts.orchestrator = orchestrator
hideFlag(cmd, orchestrator)
return checkSupportedFlag(cmd, orchestrator)
},
RunE: command.ShowHelp(dockerCli.Err()),
Annotations: map[string]string{
"kubernetes": "",
"swarm": "",
"version": "1.25",
"version": "1.25",
},
}
defaultHelpFunc := cmd.HelpFunc()
cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
config := cliconfig.LoadDefaultConfigFile(dockerCli.Err()) // dockerCli is not yet initialized, but we only need config file here
o, err := getOrchestrator(config, cmd)
if err != nil {
fmt.Fprint(dockerCli.Err(), err)
return
}
hideFlag(cmd, o)
defaultHelpFunc(cmd, args)
})
cmd.AddCommand(
newDeployCommand(dockerCli),
newListCommand(dockerCli),
newPsCommand(dockerCli),
newRemoveCommand(dockerCli),
newServicesCommand(dockerCli),
newDeployCommand(dockerCli, &opts),
newListCommand(dockerCli, &opts),
newPsCommand(dockerCli, &opts),
newRemoveCommand(dockerCli, &opts),
newServicesCommand(dockerCli, &opts),
)
flags := cmd.PersistentFlags()
flags.String("kubeconfig", "", "Kubernetes config file")
flags.SetAnnotation("kubeconfig", "kubernetes", nil)
flags.String("orchestrator", "", "Orchestrator to use (swarm|kubernetes|all)")
return cmd
}
// NewTopLevelDeployCommand returns a command for `docker deploy`
func NewTopLevelDeployCommand(dockerCli command.Cli) *cobra.Command {
cmd := newDeployCommand(dockerCli)
cmd := newDeployCommand(dockerCli, nil)
// Remove the aliases at the top level
cmd.Aliases = []string{}
cmd.Annotations = map[string]string{
"experimental": "",
"swarm": "",
"version": "1.25",
}
return cmd
}
func getOrchestrator(config *configfile.ConfigFile, cmd *cobra.Command) (command.Orchestrator, error) {
var orchestratorFlag string
if o, err := cmd.Flags().GetString("orchestrator"); err == nil {
orchestratorFlag = o
}
return command.GetStackOrchestrator(orchestratorFlag, config.StackOrchestrator)
}
func hideFlag(cmd *cobra.Command, orchestrator command.Orchestrator) {
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if _, ok := f.Annotations["kubernetes"]; ok && !orchestrator.HasKubernetes() {
f.Hidden = true
}
if _, ok := f.Annotations["swarm"]; ok && !orchestrator.HasSwarm() {
f.Hidden = true
}
})
for _, subcmd := range cmd.Commands() {
hideFlag(subcmd, orchestrator)
}
}
func checkSupportedFlag(cmd *cobra.Command, orchestrator command.Orchestrator) error {
errs := []string{}
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if !f.Changed {
return
}
if _, ok := f.Annotations["kubernetes"]; ok && !orchestrator.HasKubernetes() {
errs = append(errs, fmt.Sprintf(`"--%s" is only supported on a Docker cli with kubernetes features enabled`, f.Name))
}
if _, ok := f.Annotations["swarm"]; ok && !orchestrator.HasSwarm() {
errs = append(errs, fmt.Sprintf(`"--%s" is only supported on a Docker cli with swarm features enabled`, f.Name))
}
})
for _, subcmd := range cmd.Commands() {
if err := checkSupportedFlag(subcmd, orchestrator); err != nil {
errs = append(errs, err.Error())
}
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, "\n"))
}
return nil
}

View File

@@ -9,7 +9,7 @@ import (
"github.com/spf13/cobra"
)
func newDeployCommand(dockerCli command.Cli) *cobra.Command {
func newDeployCommand(dockerCli command.Cli, common *commonOptions) *cobra.Command {
var opts options.Deploy
cmd := &cobra.Command{
@@ -20,10 +20,12 @@ func newDeployCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
opts.Namespace = args[0]
switch {
case dockerCli.ClientInfo().HasAll():
case common == nil: // Top level deploy commad
return swarm.RunDeploy(dockerCli, opts)
case common.orchestrator.HasAll():
return errUnsupportedAllOrchestrator
case dockerCli.ClientInfo().HasKubernetes():
kli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags()))
case common.orchestrator.HasKubernetes():
kli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags(), common.orchestrator))
if err != nil {
return err
}

View File

@@ -23,13 +23,16 @@ type KubeCli struct {
// Options contains resolved parameters to initialize kubernetes clients
type Options struct {
Namespace string
Config string
Namespace string
Config string
Orchestrator command.Orchestrator
}
// NewOptions returns an Options initialized with command line flags
func NewOptions(flags *flag.FlagSet) Options {
var opts Options
func NewOptions(flags *flag.FlagSet, orchestrator command.Orchestrator) Options {
opts := Options{
Orchestrator: orchestrator,
}
if namespace, err := flags.GetString("namespace"); err == nil {
opts.Namespace = namespace
}
@@ -73,7 +76,7 @@ func WrapCli(dockerCli command.Cli, opts Options) (*KubeCli, error) {
}
cli.clientSet = clientSet
if dockerCli.ClientInfo().HasAll() {
if opts.Orchestrator.HasAll() {
if err := cli.checkHostsMatch(); err != nil {
return nil, err
}

View File

@@ -13,7 +13,7 @@ import (
"vbom.ml/util/sortorder"
)
func newListCommand(dockerCli command.Cli) *cobra.Command {
func newListCommand(dockerCli command.Cli, common *commonOptions) *cobra.Command {
opts := options.List{}
cmd := &cobra.Command{
@@ -22,7 +22,7 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
Short: "List stacks",
Args: cli.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runList(cmd, dockerCli, opts)
return runList(cmd, dockerCli, opts, common.orchestrator)
},
}
@@ -35,17 +35,17 @@ func newListCommand(dockerCli command.Cli) *cobra.Command {
return cmd
}
func runList(cmd *cobra.Command, dockerCli command.Cli, opts options.List) error {
func runList(cmd *cobra.Command, dockerCli command.Cli, opts options.List, orchestrator command.Orchestrator) error {
stacks := []*formatter.Stack{}
if dockerCli.ClientInfo().HasSwarm() {
if orchestrator.HasSwarm() {
ss, err := swarm.GetStacks(dockerCli)
if err != nil {
return err
}
stacks = append(stacks, ss...)
}
if dockerCli.ClientInfo().HasKubernetes() {
kubeCli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags()))
if orchestrator.HasKubernetes() {
kubeCli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags(), orchestrator))
if err != nil {
return err
}
@@ -55,14 +55,14 @@ func runList(cmd *cobra.Command, dockerCli command.Cli, opts options.List) error
}
stacks = append(stacks, ss...)
}
return format(dockerCli, opts, stacks)
return format(dockerCli, opts, orchestrator, stacks)
}
func format(dockerCli command.Cli, opts options.List, stacks []*formatter.Stack) error {
func format(dockerCli command.Cli, opts options.List, orchestrator command.Orchestrator, stacks []*formatter.Stack) error {
format := opts.Format
if format == "" || format == formatter.TableFormatKey {
format = formatter.SwarmStackTableFormat
if dockerCli.ClientInfo().HasKubernetes() {
if orchestrator.HasKubernetes() {
format = formatter.KubernetesStackTableFormat
}
}

View File

@@ -4,6 +4,7 @@ import (
"io/ioutil"
"testing"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/internal/test"
// Import builders to get the builder function as package function
. "github.com/docker/cli/internal/test/builders"
@@ -14,6 +15,10 @@ import (
"gotest.tools/golden"
)
var (
orchestrator = commonOptions{orchestrator: command.OrchestratorSwarm}
)
func TestListErrors(t *testing.T) {
testCases := []struct {
args []string
@@ -48,7 +53,7 @@ func TestListErrors(t *testing.T) {
for _, tc := range testCases {
cmd := newListCommand(test.NewFakeCli(&fakeClient{
serviceListFunc: tc.serviceListFunc,
}, test.OrchestratorSwarm))
}), &orchestrator)
cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard)
for key, value := range tc.flags {
@@ -69,8 +74,8 @@ func TestListWithFormat(t *testing.T) {
}),
)}, nil
},
}, test.OrchestratorSwarm)
cmd := newListCommand(cli)
})
cmd := newListCommand(cli, &orchestrator)
cmd.Flags().Set("format", "{{ .Name }}")
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "stack-list-with-format.golden")
@@ -86,8 +91,8 @@ func TestListWithoutFormat(t *testing.T) {
}),
)}, nil
},
}, test.OrchestratorSwarm)
cmd := newListCommand(cli)
})
cmd := newListCommand(cli, &orchestrator)
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "stack-list-without-format.golden")
}
@@ -139,8 +144,8 @@ func TestListOrder(t *testing.T) {
serviceListFunc: func(options types.ServiceListOptions) ([]swarm.Service, error) {
return uc.swarmServices, nil
},
}, test.OrchestratorSwarm)
cmd := newListCommand(cli)
})
cmd := newListCommand(cli, &orchestrator)
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), uc.golden)
}

View File

@@ -10,7 +10,7 @@ import (
"github.com/spf13/cobra"
)
func newPsCommand(dockerCli command.Cli) *cobra.Command {
func newPsCommand(dockerCli command.Cli, common *commonOptions) *cobra.Command {
opts := options.PS{Filter: cliopts.NewFilterOpt()}
cmd := &cobra.Command{
@@ -20,10 +20,10 @@ func newPsCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
opts.Namespace = args[0]
switch {
case dockerCli.ClientInfo().HasAll():
case common.orchestrator.HasAll():
return errUnsupportedAllOrchestrator
case dockerCli.ClientInfo().HasKubernetes():
kli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags()))
case common.orchestrator.HasKubernetes():
kli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags(), common.orchestrator))
if err != nil {
return err
}

View File

@@ -44,7 +44,7 @@ func TestStackPsErrors(t *testing.T) {
for _, tc := range testCases {
cmd := newPsCommand(test.NewFakeCli(&fakeClient{
taskListFunc: tc.taskListFunc,
}))
}), &orchestrator)
cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
@@ -57,7 +57,7 @@ func TestStackPsEmptyStack(t *testing.T) {
return []swarm.Task{}, nil
},
})
cmd := newPsCommand(fakeCli)
cmd := newPsCommand(fakeCli, &orchestrator)
cmd.SetArgs([]string{"foo"})
cmd.SetOutput(ioutil.Discard)
@@ -71,7 +71,7 @@ func TestStackPsWithQuietOption(t *testing.T) {
return []swarm.Task{*Task(TaskID("id-foo"))}, nil
},
})
cmd := newPsCommand(cli)
cmd := newPsCommand(cli, &orchestrator)
cmd.SetArgs([]string{"foo"})
cmd.Flags().Set("quiet", "true")
assert.NilError(t, cmd.Execute())
@@ -85,7 +85,7 @@ func TestStackPsWithNoTruncOption(t *testing.T) {
return []swarm.Task{*Task(TaskID("xn4cypcov06f2w8gsbaf2lst3"))}, nil
},
})
cmd := newPsCommand(cli)
cmd := newPsCommand(cli, &orchestrator)
cmd.SetArgs([]string{"foo"})
cmd.Flags().Set("no-trunc", "true")
cmd.Flags().Set("format", "{{ .ID }}")
@@ -104,7 +104,7 @@ func TestStackPsWithNoResolveOption(t *testing.T) {
return *Node(NodeName("node-name-bar")), nil, nil
},
})
cmd := newPsCommand(cli)
cmd := newPsCommand(cli, &orchestrator)
cmd.SetArgs([]string{"foo"})
cmd.Flags().Set("no-resolve", "true")
cmd.Flags().Set("format", "{{ .Node }}")
@@ -118,7 +118,7 @@ func TestStackPsWithFormat(t *testing.T) {
return []swarm.Task{*Task(TaskServiceID("service-id-foo"))}, nil
},
})
cmd := newPsCommand(cli)
cmd := newPsCommand(cli, &orchestrator)
cmd.SetArgs([]string{"foo"})
cmd.Flags().Set("format", "{{ .Name }}")
assert.NilError(t, cmd.Execute())
@@ -134,7 +134,7 @@ func TestStackPsWithConfigFormat(t *testing.T) {
cli.SetConfigFile(&configfile.ConfigFile{
TasksFormat: "{{ .Name }}",
})
cmd := newPsCommand(cli)
cmd := newPsCommand(cli, &orchestrator)
cmd.SetArgs([]string{"foo"})
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-config-format.golden")
@@ -156,7 +156,7 @@ func TestStackPsWithoutFormat(t *testing.T) {
return *Node(NodeName("node-name-bar")), nil, nil
},
})
cmd := newPsCommand(cli)
cmd := newPsCommand(cli, &orchestrator)
cmd.SetArgs([]string{"foo"})
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "stack-ps-without-format.golden")

View File

@@ -9,7 +9,7 @@ import (
"github.com/spf13/cobra"
)
func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
func newRemoveCommand(dockerCli command.Cli, common *commonOptions) *cobra.Command {
var opts options.Remove
cmd := &cobra.Command{
@@ -20,10 +20,10 @@ func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
opts.Namespaces = args
switch {
case dockerCli.ClientInfo().HasAll():
case common.orchestrator.HasAll():
return errUnsupportedAllOrchestrator
case dockerCli.ClientInfo().HasKubernetes():
kli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags()))
case common.orchestrator.HasKubernetes():
kli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags(), common.orchestrator))
if err != nil {
return err
}

View File

@@ -43,7 +43,7 @@ func fakeClientForRemoveStackTest(version string) *fakeClient {
func TestRemoveStackVersion124DoesNotRemoveConfigsOrSecrets(t *testing.T) {
client := fakeClientForRemoveStackTest("1.24")
cmd := newRemoveCommand(test.NewFakeCli(client))
cmd := newRemoveCommand(test.NewFakeCli(client), &orchestrator)
cmd.SetArgs([]string{"foo", "bar"})
assert.NilError(t, cmd.Execute())
@@ -55,7 +55,7 @@ func TestRemoveStackVersion124DoesNotRemoveConfigsOrSecrets(t *testing.T) {
func TestRemoveStackVersion125DoesNotRemoveConfigs(t *testing.T) {
client := fakeClientForRemoveStackTest("1.25")
cmd := newRemoveCommand(test.NewFakeCli(client))
cmd := newRemoveCommand(test.NewFakeCli(client), &orchestrator)
cmd.SetArgs([]string{"foo", "bar"})
assert.NilError(t, cmd.Execute())
@@ -67,7 +67,7 @@ func TestRemoveStackVersion125DoesNotRemoveConfigs(t *testing.T) {
func TestRemoveStackVersion130RemovesEverything(t *testing.T) {
client := fakeClientForRemoveStackTest("1.30")
cmd := newRemoveCommand(test.NewFakeCli(client))
cmd := newRemoveCommand(test.NewFakeCli(client), &orchestrator)
cmd.SetArgs([]string{"foo", "bar"})
assert.NilError(t, cmd.Execute())
@@ -98,7 +98,7 @@ func TestRemoveStackSkipEmpty(t *testing.T) {
configs: allConfigs,
}
fakeCli := test.NewFakeCli(fakeClient)
cmd := newRemoveCommand(fakeCli)
cmd := newRemoveCommand(fakeCli, &orchestrator)
cmd.SetArgs([]string{"foo", "bar"})
assert.NilError(t, cmd.Execute())
@@ -146,7 +146,7 @@ func TestRemoveContinueAfterError(t *testing.T) {
return nil
},
}
cmd := newRemoveCommand(test.NewFakeCli(cli))
cmd := newRemoveCommand(test.NewFakeCli(cli), &orchestrator)
cmd.SetOutput(ioutil.Discard)
cmd.SetArgs([]string{"foo", "bar"})

View File

@@ -10,7 +10,7 @@ import (
"github.com/spf13/cobra"
)
func newServicesCommand(dockerCli command.Cli) *cobra.Command {
func newServicesCommand(dockerCli command.Cli, common *commonOptions) *cobra.Command {
opts := options.Services{Filter: cliopts.NewFilterOpt()}
cmd := &cobra.Command{
@@ -20,10 +20,10 @@ func newServicesCommand(dockerCli command.Cli) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
opts.Namespace = args[0]
switch {
case dockerCli.ClientInfo().HasAll():
case common.orchestrator.HasAll():
return errUnsupportedAllOrchestrator
case dockerCli.ClientInfo().HasKubernetes():
kli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags()))
case common.orchestrator.HasKubernetes():
kli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags(), common.orchestrator))
if err != nil {
return err
}

View File

@@ -70,7 +70,7 @@ func TestStackServicesErrors(t *testing.T) {
nodeListFunc: tc.nodeListFunc,
taskListFunc: tc.taskListFunc,
})
cmd := newServicesCommand(cli)
cmd := newServicesCommand(cli, &orchestrator)
cmd.SetArgs(tc.args)
for key, value := range tc.flags {
cmd.Flags().Set(key, value)
@@ -86,7 +86,7 @@ func TestStackServicesEmptyServiceList(t *testing.T) {
return []swarm.Service{}, nil
},
})
cmd := newServicesCommand(fakeCli)
cmd := newServicesCommand(fakeCli, &orchestrator)
cmd.SetArgs([]string{"foo"})
assert.NilError(t, cmd.Execute())
assert.Check(t, is.Equal("", fakeCli.OutBuffer().String()))
@@ -99,7 +99,7 @@ func TestStackServicesWithQuietOption(t *testing.T) {
return []swarm.Service{*Service(ServiceID("id-foo"))}, nil
},
})
cmd := newServicesCommand(cli)
cmd := newServicesCommand(cli, &orchestrator)
cmd.Flags().Set("quiet", "true")
cmd.SetArgs([]string{"foo"})
assert.NilError(t, cmd.Execute())
@@ -114,7 +114,7 @@ func TestStackServicesWithFormat(t *testing.T) {
}, nil
},
})
cmd := newServicesCommand(cli)
cmd := newServicesCommand(cli, &orchestrator)
cmd.SetArgs([]string{"foo"})
cmd.Flags().Set("format", "{{ .Name }}")
assert.NilError(t, cmd.Execute())
@@ -132,7 +132,7 @@ func TestStackServicesWithConfigFormat(t *testing.T) {
cli.SetConfigFile(&configfile.ConfigFile{
ServicesFormat: "{{ .Name }}",
})
cmd := newServicesCommand(cli)
cmd := newServicesCommand(cli, &orchestrator)
cmd.SetArgs([]string{"foo"})
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "stack-services-with-config-format.golden")
@@ -155,7 +155,7 @@ func TestStackServicesWithoutFormat(t *testing.T) {
)}, nil
},
})
cmd := newServicesCommand(cli)
cmd := newServicesCommand(cli, &orchestrator)
cmd.SetArgs([]string{"foo"})
assert.NilError(t, cmd.Execute())
golden.Assert(t, cli.OutBuffer().String(), "stack-services-without-format.golden")