github.com/justincormack/cli@v0.0.0-20201215022714-831ebeae9675/cli/command/service/rollback.go (about)

     1  package service
     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"
    10  	"github.com/docker/docker/api/types/versions"
    11  	"github.com/spf13/cobra"
    12  )
    13  
    14  func newRollbackCommand(dockerCli command.Cli) *cobra.Command {
    15  	options := newServiceOptions()
    16  
    17  	cmd := &cobra.Command{
    18  		Use:   "rollback [OPTIONS] SERVICE",
    19  		Short: "Revert changes to a service's configuration",
    20  		Args:  cli.ExactArgs(1),
    21  		RunE: func(cmd *cobra.Command, args []string) error {
    22  			return runRollback(dockerCli, options, args[0])
    23  		},
    24  		Annotations: map[string]string{"version": "1.31"},
    25  	}
    26  
    27  	flags := cmd.Flags()
    28  	flags.BoolVarP(&options.quiet, flagQuiet, "q", false, "Suppress progress output")
    29  	addDetachFlag(flags, &options.detach)
    30  
    31  	return cmd
    32  }
    33  
    34  func runRollback(dockerCli command.Cli, options *serviceOptions, serviceID string) error {
    35  	apiClient := dockerCli.Client()
    36  	ctx := context.Background()
    37  
    38  	service, _, err := apiClient.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{})
    39  	if err != nil {
    40  		return err
    41  	}
    42  
    43  	spec := &service.Spec
    44  	updateOpts := types.ServiceUpdateOptions{
    45  		Rollback: "previous",
    46  	}
    47  
    48  	response, err := apiClient.ServiceUpdate(ctx, service.ID, service.Version, *spec, updateOpts)
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	for _, warning := range response.Warnings {
    54  		fmt.Fprintln(dockerCli.Err(), warning)
    55  	}
    56  
    57  	fmt.Fprintf(dockerCli.Out(), "%s\n", serviceID)
    58  
    59  	if options.detach || versions.LessThan(apiClient.ClientVersion(), "1.29") {
    60  		return nil
    61  	}
    62  
    63  	return waitOnService(ctx, dockerCli, serviceID, options.quiet)
    64  }