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