forked from etcd-io/etcd
-
Notifications
You must be signed in to change notification settings - Fork 22
/
initial-cluster.go
274 lines (229 loc) · 8.98 KB
/
initial-cluster.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package discover_etcd_initial_cluster
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"google.golang.org/grpc"
"go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/etcdserver/etcdserverpb"
"go.etcd.io/etcd/pkg/transport"
)
type DiscoverEtcdInitialClusterOptions struct {
// TargetPeerURLHost is the host portion of the peer URL. It is used to match on. (either IP or hostname)
TargetPeerURLHost string
// TargetName is the name to assign to this peer if we create it
TargetName string
// CABundleFile is the file to use to trust the etcd server
CABundleFile string
// ClientCertFile is the client cert to use to authenticate this binary to etcd
ClientCertFile string
// ClientKeyFile is the client key to use to authenticate this binary to etcd
ClientKeyFile string
// Endpoints is a list of all the endpoints to use to try to contact etcd
Endpoints []string
// DataDir is the directory created when etcd starts the first time
DataDir string
}
func NewDiscoverEtcdInitialCluster() *DiscoverEtcdInitialClusterOptions {
return &DiscoverEtcdInitialClusterOptions{}
}
func NewDiscoverEtcdInitialClusterCommand() *cobra.Command {
o := NewDiscoverEtcdInitialCluster()
cmd := &cobra.Command{
Use: "discover-etcd-initial-cluster",
Short: "output the value for ETCD_INITIAL_CLUSTER in openshift etcd static pod",
Long: `output the value for ETCD_INITIAL_CLUSTER in openshift etcd static pod
1. If --data-dir exists, output a marker value and exit.
2. It tries to contact every available etcd to get a list of member.
3. Check each member to see if any one of them is the target.
4. If so, and if it is started, use the member list to create the ETCD_INITIAL_CLUSTER value and print it out.
5. If so, and if it it not started, use the existing member list and append the target value to create the ETCD_INITIAL_CLUSTER value and print it out.
6. If not, try again until either you have it or you time out.
`,
Run: func(cmd *cobra.Command, args []string) {
if err := o.Validate(); err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
if err := o.Run(); err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
},
}
o.BindFlags(cmd.Flags())
return cmd
}
func (o *DiscoverEtcdInitialClusterOptions) BindFlags(flags *pflag.FlagSet) {
flags.StringVar(&o.CABundleFile, "cacert", o.CABundleFile, "file to use to verify the identity of the etcd server")
flags.StringVar(&o.ClientCertFile, "cert", o.ClientCertFile, "client cert to use to authenticate this binary to etcd")
flags.StringVar(&o.ClientKeyFile, "key", o.ClientKeyFile, "client key to use to authenticate this binary to etcd")
flags.StringSliceVar(&o.Endpoints, "endpoints", o.Endpoints, "list of all the endpoints to use to try to contact etcd")
flags.StringVar(&o.DataDir, "data-dir", o.DataDir, "dir to stat for existence of the member directory")
flags.StringVar(&o.TargetPeerURLHost, "target-peer-url-host", o.TargetPeerURLHost, "host portion of the peer URL. It is used to match on. (either IP or hostname)")
flags.StringVar(&o.TargetName, "target-name", o.TargetName, "name to assign to this peer if we create it")
}
func (o *DiscoverEtcdInitialClusterOptions) Validate() error {
if len(o.CABundleFile) == 0 {
return fmt.Errorf("missing --cacert")
}
if len(o.ClientCertFile) == 0 {
return fmt.Errorf("missing --cert")
}
if len(o.ClientKeyFile) == 0 {
return fmt.Errorf("missing --key")
}
if len(o.Endpoints) == 0 {
return fmt.Errorf("missing --endpoints")
}
if len(o.DataDir) == 0 {
return fmt.Errorf("missing --data-dir")
}
if len(o.TargetPeerURLHost) == 0 {
return fmt.Errorf("missing --target-peer-url-host")
}
if len(o.TargetName) == 0 {
return fmt.Errorf("missing --target-name")
}
return nil
}
func (o *DiscoverEtcdInitialClusterOptions) Run() error {
//Temporary hack to work with the current pod.yaml
var memberDir string
if strings.HasSuffix(o.DataDir, "member") {
memberDir = o.DataDir
o.DataDir = filepath.Dir(o.DataDir)
} else {
memberDir = filepath.Join(o.DataDir, "member")
}
memberDirExists := false
_, err := os.Stat(memberDir)
switch {
case os.IsNotExist(err):
// do nothing. This just means we fall through to the polling logic
case err == nil:
fmt.Fprintf(os.Stderr, "memberDir %s is present on %s\n", memberDir, o.TargetName)
memberDirExists = true
case err != nil:
return err
}
client, err := o.getClient()
if err != nil && memberDirExists {
// we weren't able to get client and need to return based previous memberDir so we can restart. This is the off and on again flow.
fmt.Fprintf(os.Stderr, "Couldn't get client, but memberDir %s is present on %s, err=%s. Returning with no error.\n", memberDir, o.TargetName, err)
fmt.Printf(o.TargetName)
return nil
} else if err != nil {
return err
}
defer client.Close()
var targetMember *etcdserverpb.Member
var allMembers []*etcdserverpb.Member
for i := 0; i < 10; i++ {
fmt.Fprintf(os.Stderr, "#### attempt %d\n", i)
targetMember, allMembers, err = o.checkForTarget(client)
for _, member := range allMembers {
fmt.Fprintf(os.Stderr, " member=%v\n", stringifyMember(member))
}
fmt.Fprintf(os.Stderr, " target=%v, err=%v\n", stringifyMember(targetMember), err)
// we're done because we found what we want.
if targetMember != nil && err == nil {
break
}
fmt.Fprintf(os.Stderr, "#### sleeping...\n")
time.Sleep(1 * time.Second)
}
switch {
case targetMember == nil && memberDirExists:
// we weren't able to locate other members and need to return based previous memberDir so we can restart. This is again the off and on flow.
fmt.Fprintf(os.Stderr, "Couldn't get targetMember, but memberDir %s is present on %s. Returning with no error.\n", memberDir, o.TargetName)
fmt.Printf(o.TargetName)
return nil
case err != nil:
fmt.Fprintf(os.Stderr, "Couldn't get targetMember. Returning error.\n")
return err
case targetMember == nil && !memberDirExists:
// our member has not been added to the cluster and we have no previous data to start based on.
return fmt.Errorf("timed out")
case targetMember != nil && len(targetMember.Name) == 0 && memberDirExists:
// our member has been added to the cluster and has never been started before, but a data directory exists. This means that we have dirty data we must remove
fmt.Fprintf(os.Stderr, "Found targetMember but is unstarted and memberDir exists. Archiving memberrDir\n")
archiveDataDir(memberDir)
default:
// a target member was found, but no exception circumstances.
}
etcdInitialClusterEntries := []string{}
for _, member := range allMembers {
if len(member.Name) == 0 { // this is the signal for whether or not a given peer is started
continue
}
for _, peerURL := range member.PeerURLs {
etcdInitialClusterEntries = append(etcdInitialClusterEntries, fmt.Sprintf("%s=%s", member.Name, peerURL))
}
}
if len(targetMember.Name) == 0 {
fmt.Fprintf(os.Stderr, "Adding the unstarted member to the end %s\n", o.TargetName)
etcdInitialClusterEntries = append(etcdInitialClusterEntries, fmt.Sprintf("%s=%s", o.TargetName, targetMember.PeerURLs[0]))
}
fmt.Printf(strings.Join(etcdInitialClusterEntries, ","))
return nil
}
// TO DO: instead of archiving, we should remove the directory to avoid any confusion with the backups.
func archiveDataDir(sourceDir string) error {
targetDir := filepath.Join(sourceDir + "-removed-archive-" + time.Now().Format("2006-01-02-030405"))
fmt.Fprintf(os.Stderr, "attempting to archive %s to %s", sourceDir, targetDir)
if err := os.Rename(sourceDir, targetDir); err != nil {
return err
}
return nil
}
func stringifyMember(member *etcdserverpb.Member) string {
if member == nil {
return "nil"
}
return fmt.Sprintf("{name=%q, peerURLs=[%s}, clientURLs=[%s]", member.Name, strings.Join(member.PeerURLs, ","), strings.Join(member.ClientURLs, ","))
}
func (o *DiscoverEtcdInitialClusterOptions) checkForTarget(client *clientv3.Client) (*etcdserverpb.Member, []*etcdserverpb.Member, error) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
memberResponse, err := client.MemberList(ctx)
if err != nil {
return nil, nil, err
}
var targetMember *etcdserverpb.Member
for i := range memberResponse.Members {
member := memberResponse.Members[i]
for _, peerURL := range member.PeerURLs {
if peerURL == ("https://" + o.TargetPeerURLHost + ":2380") {
targetMember = member
}
}
}
return targetMember, memberResponse.Members, err
}
func (o *DiscoverEtcdInitialClusterOptions) getClient() (*clientv3.Client, error) {
dialOptions := []grpc.DialOption{
grpc.WithBlock(), // block until the underlying connection is up
}
tlsInfo := transport.TLSInfo{
CertFile: o.ClientCertFile,
KeyFile: o.ClientKeyFile,
TrustedCAFile: o.CABundleFile,
}
tlsConfig, err := tlsInfo.ClientConfig()
if err != nil {
return nil, err
}
cfg := &clientv3.Config{
DialOptions: dialOptions,
Endpoints: o.Endpoints,
DialTimeout: 15 * time.Second,
TLS: tlsConfig,
}
return clientv3.New(*cfg)
}