github.1git.de/docker/cli@v26.1.3+incompatible/cli/command/swarm/unlock.go (about)

     1  package swarm
     2  
     3  import (
     4  	"bufio"
     5  	"context"
     6  	"fmt"
     7  	"io"
     8  	"strings"
     9  
    10  	"github.com/docker/cli/cli"
    11  	"github.com/docker/cli/cli/command"
    12  	"github.com/docker/cli/cli/command/completion"
    13  	"github.com/docker/cli/cli/streams"
    14  	"github.com/docker/docker/api/types/swarm"
    15  	"github.com/pkg/errors"
    16  	"github.com/spf13/cobra"
    17  	"golang.org/x/term"
    18  )
    19  
    20  func newUnlockCommand(dockerCli command.Cli) *cobra.Command {
    21  	cmd := &cobra.Command{
    22  		Use:   "unlock",
    23  		Short: "Unlock swarm",
    24  		Args:  cli.NoArgs,
    25  		RunE: func(cmd *cobra.Command, args []string) error {
    26  			return runUnlock(cmd.Context(), dockerCli)
    27  		},
    28  		Annotations: map[string]string{
    29  			"version": "1.24",
    30  			"swarm":   "manager",
    31  		},
    32  		ValidArgsFunction: completion.NoComplete,
    33  	}
    34  
    35  	return cmd
    36  }
    37  
    38  func runUnlock(ctx context.Context, dockerCli command.Cli) error {
    39  	client := dockerCli.Client()
    40  
    41  	// First see if the node is actually part of a swarm, and if it is actually locked first.
    42  	// If it's in any other state than locked, don't ask for the key.
    43  	info, err := client.Info(ctx)
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	switch info.Swarm.LocalNodeState {
    49  	case swarm.LocalNodeStateInactive:
    50  		return errors.New("Error: This node is not part of a swarm")
    51  	case swarm.LocalNodeStateLocked:
    52  		break
    53  	default:
    54  		return errors.New("Error: swarm is not locked")
    55  	}
    56  
    57  	key, err := readKey(dockerCli.In(), "Please enter unlock key: ")
    58  	if err != nil {
    59  		return err
    60  	}
    61  	req := swarm.UnlockRequest{
    62  		UnlockKey: key,
    63  	}
    64  
    65  	return client.SwarmUnlock(ctx, req)
    66  }
    67  
    68  func readKey(in *streams.In, prompt string) (string, error) {
    69  	if in.IsTerminal() {
    70  		fmt.Print(prompt)
    71  		dt, err := term.ReadPassword(int(in.FD()))
    72  		fmt.Println()
    73  		return string(dt), err
    74  	}
    75  	key, err := bufio.NewReader(in).ReadString('\n')
    76  	if err == io.EOF {
    77  		err = nil
    78  	}
    79  	return strings.TrimSpace(key), err
    80  }