github.com/itscaro/cli@v0.0.0-20190705081621-c9db0fe93829/cli/command/swarm/update.go (about)

     1  package swarm
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/docker/cli/cli"
     8  	"github.com/docker/cli/cli/command"
     9  	"github.com/docker/docker/api/types/swarm"
    10  	"github.com/pkg/errors"
    11  	"github.com/spf13/cobra"
    12  	"github.com/spf13/pflag"
    13  )
    14  
    15  func newUpdateCommand(dockerCli command.Cli) *cobra.Command {
    16  	opts := swarmOptions{}
    17  
    18  	cmd := &cobra.Command{
    19  		Use:   "update [OPTIONS]",
    20  		Short: "Update the swarm",
    21  		Args:  cli.NoArgs,
    22  		RunE: func(cmd *cobra.Command, args []string) error {
    23  			return runUpdate(dockerCli, cmd.Flags(), opts)
    24  		},
    25  		PreRunE: func(cmd *cobra.Command, args []string) error {
    26  			if cmd.Flags().NFlag() == 0 {
    27  				return pflag.ErrHelp
    28  			}
    29  			return nil
    30  		},
    31  	}
    32  
    33  	cmd.Flags().BoolVar(&opts.autolock, flagAutolock, false, "Change manager autolocking setting (true|false)")
    34  	addSwarmFlags(cmd.Flags(), &opts)
    35  	return cmd
    36  }
    37  
    38  func runUpdate(dockerCli command.Cli, flags *pflag.FlagSet, opts swarmOptions) error {
    39  	client := dockerCli.Client()
    40  	ctx := context.Background()
    41  
    42  	var updateFlags swarm.UpdateFlags
    43  
    44  	swarmInspect, err := client.SwarmInspect(ctx)
    45  	if err != nil {
    46  		return err
    47  	}
    48  
    49  	prevAutoLock := swarmInspect.Spec.EncryptionConfig.AutoLockManagers
    50  
    51  	opts.mergeSwarmSpec(&swarmInspect.Spec, flags, swarmInspect.ClusterInfo.TLSInfo.TrustRoot)
    52  
    53  	curAutoLock := swarmInspect.Spec.EncryptionConfig.AutoLockManagers
    54  
    55  	err = client.SwarmUpdate(ctx, swarmInspect.Version, swarmInspect.Spec, updateFlags)
    56  	if err != nil {
    57  		return err
    58  	}
    59  
    60  	fmt.Fprintln(dockerCli.Out(), "Swarm updated.")
    61  
    62  	if curAutoLock && !prevAutoLock {
    63  		unlockKeyResp, err := client.SwarmGetUnlockKey(ctx)
    64  		if err != nil {
    65  			return errors.Wrap(err, "could not fetch unlock key")
    66  		}
    67  		printUnlockCommand(dockerCli.Out(), unlockKeyResp.UnlockKey)
    68  	}
    69  
    70  	return nil
    71  }