forked from coreos/etcd-manager
/
main.go
275 lines (234 loc) · 6.15 KB
/
main.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
275
package main
import (
"bytes"
"flag"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"sync"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
var defaultGitRepoUrl = "https://github.com/coreos/etcd.git"
var (
stdoutChan chan string
stderrChan chan string
)
var (
etcdBinary string
gitCommit string
gitRepoUrl string
gitTag string
hosts string
sshUser string
verbose bool
)
func init() {
flag.StringVar(&etcdBinary, "etcd-binary", "", "etcd binary to deploy")
flag.StringVar(&gitCommit, "commit", "", "git commit to deploy")
flag.StringVar(&gitRepoUrl, "repo-url", defaultGitRepoUrl, "git repo to deploy from")
flag.StringVar(&gitTag, "tag", "", "git tag to deploy")
flag.StringVar(&hosts, "hosts", "", "comma separated list of etcd hosts")
flag.StringVar(&sshUser, "user", "core", "ssh login username")
flag.BoolVar(&verbose, "verbose", false, "enable verbose output")
}
var clientConfig *ssh.ClientConfig
func main() {
if !(len(os.Args) > 1) {
log.Fatal("action required.")
}
action := os.Args[1]
os.Args = append(os.Args[:1], os.Args[2:]...)
flag.Parse()
authSocket := os.Getenv("SSH_AUTH_SOCK")
if authSocket == "" {
log.Fatal("SSH_AUTH_SOCK required, check that your ssh agent is running")
}
agentUnixSock, err := net.Dial("unix", authSocket)
if err != nil {
log.Fatal(err)
}
agent := agent.NewClient(agentUnixSock)
signers, err := agent.Signers()
if err != nil {
log.Fatal(err)
}
clientConfig = &ssh.ClientConfig{
User: sshUser,
Auth: []ssh.AuthMethod{ssh.PublicKeys(signers...)},
}
hostsList := strings.Split(hosts, ",")
if !(len(hostsList) > 0) {
log.Fatal("one or more hosts required, use the -host flag")
}
stderrChan = make(chan string, 0)
stdoutChan = make(chan string, 0)
go consoleWriter()
switch action {
case "deploy":
if etcdBinary != "" {
deployFromEtcdBinary(etcdBinary, hostsList)
os.Exit(0)
}
if gitCommit != "" {
deployFromGitCommit(gitCommit, hostsList)
os.Exit(0)
}
if gitTag != "" {
deployFromGitTag(gitTag, hostsList)
os.Exit(0)
}
case "version":
etcdVersion(hostsList)
}
}
func consoleWriter() {
for {
select {
case msg := <-stderrChan:
fmt.Fprintf(os.Stderr, msg)
case msg := <-stdoutChan:
fmt.Fprintf(os.Stdout, msg)
}
}
}
func deployFromEtcdBinary(path string, hosts []string) {
copyOnAll(hosts, path)
etcdVersion(hosts)
}
func deployFromGitCommit(commit string, hosts []string) {
commands := []string{
"sudo bash -c 'if [ ! -e /opt/etcd ] ; then git clone https://github.com/coreos/etcd.git /opt/etcd ; fi'",
"sudo bash -c 'cd /opt/etcd && git fetch'",
fmt.Sprintf("sudo bash -c 'cd /opt/etcd && git reset --hard %s'", commit),
"docker run -v /opt/etcd:/opt/etcd -t google/golang /bin/bash -c 'cd /opt/etcd && ./build'",
"/opt/etcd/bin/etcd --version",
"sudo bash -c 'systemctl restart etcd'",
}
runOnAll(hosts, commands)
}
func deployFromGitTag(tag string, hosts []string) {
commands := []string{
"sudo bash -c 'if [ ! -e /opt/etcd ] ; then git clone https://github.com/coreos/etcd.git /opt/etcd ; fi'",
"sudo bash -c 'cd /opt/etcd && git fetch'",
"sudo bash -c 'cd /opt/etcd && git reset --hard HEAD'",
fmt.Sprintf("sudo bash -c 'cd /opt/etcd && git checkout tags/%s'", tag),
"docker run -v /opt/etcd:/opt/etcd -t google/golang /bin/bash -c 'cd /opt/etcd && ./build'",
"/opt/etcd/bin/etcd --version",
"sudo bash -c 'systemctl restart etcd'",
}
runOnAll(hosts, commands)
}
func etcdVersion(hosts []string) {
commands := []string{
"/opt/etcd/bin/etcd --version",
}
runOnAll(hosts, commands)
}
func restartCluster(hosts []string) {
commands := []string{
"sudo bash -c 'systemctl restart etcd'",
"sudo bash -c 'systemctl status etcd'",
}
for _, host := range hosts {
connectAndExec(host, commands, nil)
}
}
func runOnAll(hosts, commands []string) {
var wg sync.WaitGroup
for _, host := range hosts {
h := host
wg.Add(1)
go connectAndExec(h, commands, &wg)
}
wg.Wait()
}
func copyOnAll(hosts []string, path string) {
var wg sync.WaitGroup
for _, host := range hosts {
h := host
wg.Add(1)
f, err := os.Open(path)
if err != nil {
fmt.Println(err)
continue
}
go connectAndUpload(h, f, &wg)
}
wg.Wait()
}
func logStderr(host, message string) {
stderrChan <- fmt.Sprintf("%s:\n => %s\n", host, message)
return
}
func connectAndExec(host string, commands []string, wg *sync.WaitGroup) error {
if wg != nil {
defer wg.Done()
}
client, err := ssh.Dial("tcp", host, clientConfig)
if err != nil {
logStderr(host, fmt.Sprintf("failed to create SSH connection: %s\n", err))
return err
}
for _, command := range commands {
if verbose {
logStderr(host, fmt.Sprintf("executing %s", command))
}
session, err := client.NewSession()
if err != nil {
logStderr(host, fmt.Sprintf("failed to create SSH session: %s", err))
return err
}
defer session.Close()
var b bytes.Buffer
session.Stdout = &b
if err := session.Run(command); err != nil {
logStderr(host, fmt.Sprintf("error running command: %s", err))
return err
}
output := b.String()
if output != "" {
logStderr(host, output)
}
}
return nil
}
func connectAndUpload(host string, r io.Reader, wg *sync.WaitGroup) error {
defer wg.Done()
client, err := ssh.Dial("tcp", host, clientConfig)
if err != nil {
logStderr(host, fmt.Sprintf("failed to create SSH connection: %s", err))
return err
}
sftpClient, err := sftp.NewClient(client)
if err != nil {
logStderr(host, fmt.Sprintf("failed to create sftp client: %s", err))
return err
}
f, err := sftpClient.Create("/tmp/etcd")
if err != nil {
logStderr(host, fmt.Sprintf("failed to create /tmp/etcd: %s", err))
return err
}
logStderr(host, "uploading etcd binary")
if _, err := io.Copy(f, r); err != nil {
f.Close()
logStderr(host, fmt.Sprintf("upload failed: %s", err))
return err
}
f.Close()
err = connectAndExec(host, []string{"sudo mv /tmp/etcd /opt/etcd/bin/etcd"}, nil)
if err != nil {
return err
}
if err := sftpClient.Chmod("/opt/etcd/bin/etcd", 0755); err != nil {
logStderr(host, fmt.Sprintf("failed to chmod remote etcd binary: %s", err))
return err
}
logStderr(host, "upload complete.")
return nil
}