github.com/kunnos/engine@v1.13.1/cli/command/swarm/join_token.go (about) 1 package swarm 2 3 import ( 4 "errors" 5 "fmt" 6 7 "github.com/spf13/cobra" 8 9 "github.com/docker/docker/api/types/swarm" 10 "github.com/docker/docker/cli" 11 "github.com/docker/docker/cli/command" 12 "golang.org/x/net/context" 13 ) 14 15 func newJoinTokenCommand(dockerCli *command.DockerCli) *cobra.Command { 16 var rotate, quiet bool 17 18 cmd := &cobra.Command{ 19 Use: "join-token [OPTIONS] (worker|manager)", 20 Short: "Manage join tokens", 21 Args: cli.ExactArgs(1), 22 RunE: func(cmd *cobra.Command, args []string) error { 23 worker := args[0] == "worker" 24 manager := args[0] == "manager" 25 26 if !worker && !manager { 27 return errors.New("unknown role " + args[0]) 28 } 29 30 client := dockerCli.Client() 31 ctx := context.Background() 32 33 if rotate { 34 var flags swarm.UpdateFlags 35 36 swarm, err := client.SwarmInspect(ctx) 37 if err != nil { 38 return err 39 } 40 41 flags.RotateWorkerToken = worker 42 flags.RotateManagerToken = manager 43 44 err = client.SwarmUpdate(ctx, swarm.Version, swarm.Spec, flags) 45 if err != nil { 46 return err 47 } 48 if !quiet { 49 fmt.Fprintf(dockerCli.Out(), "Successfully rotated %s join token.\n\n", args[0]) 50 } 51 } 52 53 swarm, err := client.SwarmInspect(ctx) 54 if err != nil { 55 return err 56 } 57 58 if quiet { 59 if worker { 60 fmt.Fprintln(dockerCli.Out(), swarm.JoinTokens.Worker) 61 } else { 62 fmt.Fprintln(dockerCli.Out(), swarm.JoinTokens.Manager) 63 } 64 } else { 65 info, err := client.Info(ctx) 66 if err != nil { 67 return err 68 } 69 return printJoinCommand(ctx, dockerCli, info.Swarm.NodeID, worker, manager) 70 } 71 return nil 72 }, 73 } 74 75 flags := cmd.Flags() 76 flags.BoolVar(&rotate, flagRotate, false, "Rotate join token") 77 flags.BoolVarP(&quiet, flagQuiet, "q", false, "Only display token") 78 79 return cmd 80 } 81 82 func printJoinCommand(ctx context.Context, dockerCli *command.DockerCli, nodeID string, worker bool, manager bool) error { 83 client := dockerCli.Client() 84 85 swarm, err := client.SwarmInspect(ctx) 86 if err != nil { 87 return err 88 } 89 90 node, _, err := client.NodeInspectWithRaw(ctx, nodeID) 91 if err != nil { 92 return err 93 } 94 95 if node.ManagerStatus != nil { 96 if worker { 97 fmt.Fprintf(dockerCli.Out(), "To add a worker to this swarm, run the following command:\n\n docker swarm join \\\n --token %s \\\n %s\n\n", swarm.JoinTokens.Worker, node.ManagerStatus.Addr) 98 } 99 if manager { 100 fmt.Fprintf(dockerCli.Out(), "To add a manager to this swarm, run the following command:\n\n docker swarm join \\\n --token %s \\\n %s\n\n", swarm.JoinTokens.Manager, node.ManagerStatus.Addr) 101 } 102 } 103 104 return nil 105 }