/
gogettr.go
334 lines (289 loc) · 7.07 KB
/
gogettr.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package main
import (
"bytes"
"golang.org/x/crypto/ssh"
"fmt"
"github.com/codegangsta/cli"
"github.com/dustin/go-humanize"
"github.com/wsxiaoys/terminal/color"
"io/ioutil"
"log"
"os"
"os/user"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
)
var config *ssh.ClientConfig
type Result struct {
Host string
Res string
}
func strip(v string) string {
return strings.TrimSpace(strings.Trim(v, "\n"))
}
func filterHosts(hosts []string) []string {
var res []string
for _, host := range hosts {
var conn string
token := strings.Split(host, ":")
if len(token) == 1 {
conn = host + ":22"
} else {
conn = host
}
res = append(res, conn)
}
return res
}
func getKeyFile() (key ssh.Signer, err error) {
usr, _ := user.Current()
file := usr.HomeDir + "/.ssh/id_rsa"
buf, err := ioutil.ReadFile(file)
if err != nil {
return
}
key, err = ssh.ParsePrivateKey(buf)
if err != nil {
return
}
return
}
func main() {
key, err := getKeyFile()
if err != nil {
panic(err)
}
usr, _ := user.Current()
config = &ssh.ClientConfig{
User: usr.Username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(key),
},
}
app := cli.NewApp()
app.Name = "Docker Ruby Manager"
app.Usage = "Manage your ruby versions with Docker"
app.Version = "0.1.0"
app.Author = "Daniel Barker"
app.EnableBashCompletion = true
app.Commands = []cli.Command{
{
Name: "sshcmd",
Usage: "Run any cmd through ssh",
Action: sshcmd,
Flags: []cli.Flag{
cli.StringSliceFlag{
Name: "node, n",
Usage: "A node to run the cmd on. Use multiple times",
},
cli.StringFlag{
Name: "nodes",
Usage: "A comma separated list of nodes for the cmd",
},
cli.StringFlag{
Name: "cmd, c",
Usage: "The cmd to run",
},
},
},
{
Name: "largestWithNodes",
Usage: "Get a listing of largest files across all nodes",
Action: largestWithNodes,
Flags: []cli.Flag{
cli.StringSliceFlag{
Name: "node, n",
Usage: "A node to run the cmd on. Use multiple times",
},
cli.StringFlag{
Name: "nodes",
Usage: "A comma separated list of nodes for the cmd",
},
cli.BoolFlag{
Name: "sudo",
Usage: "Set to true for sudo",
},
},
},
}
app.Run(os.Args)
}
func sshcmd(c *cli.Context) {
command := c.String("cmd")
debug := true
command = fmt.Sprintf("/bin/bash <<CMD\nexport PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin\n%s\nCMD", command)
if debug {
color.Printf("@{b}%s\n", command)
}
var conns []string
if c.IsSet("nodes") {
conns = filterHosts(strings.Split(c.String("nodes"), ","))
} else if c.IsSet("node") {
conns = filterHosts(c.StringSlice("node"))
} else {
fmt.Errorf("Node or Nodes must be specified")
}
results := runSsh(conns, command, debug)
fmt.Println(results)
}
func largestWithNodes(c *cli.Context) {
debug := true
command := "find / ! -readable -prune -type f -printf '%s %p\n' 2> /dev/null | sort -nr | head -n 15"
if c.Bool("sudo") == true {
command = fmt.Sprintf("/usr/bin/sudo -n bash <<CMD\nexport PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin\n%s\nCMD", command)
} else {
command = fmt.Sprintf("/bin/bash <<CMD\nexport PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin\n%s\nCMD", command)
}
if debug {
color.Printf("@{b}%s\n", command)
}
var conns []string
if c.IsSet("nodes") {
conns = filterHosts(strings.Split(c.String("nodes"), ","))
} else if c.IsSet("node") {
conns = filterHosts(c.StringSlice("node"))
} else {
fmt.Errorf("Node or Nodes must be specified")
}
pathToSizeAndNodes := make(map[string]sizeByNodes)
results := runSsh(conns, command, debug)
for _, r := range results {
lines := strings.Split(r.Res, "\n")
for _, line := range lines {
items := strings.Fields(line)
fmt.Println(items[0])
fmt.Println(items[1])
path := items[1]
if _, ok := pathToSizeAndNodes[path]; ok == false {
size, err := strconv.ParseUint(items[0], 0, 0)
if err != nil {
panic(err)
}
pathToSizeAndNodes[path] = sizeByNodes{Size: size, Nodes: []string{r.Host}}
} else {
nodes := append(pathToSizeAndNodes[path].Nodes, r.Host)
pathToSizeAndNodes[path] = sizeByNodes{Size: pathToSizeAndNodes[path].Size, Nodes: nodes}
}
}
}
for _, res := range sortedKeys(pathToSizeAndNodes) {
fmt.Printf("%s\t%s\t%v\n", humanize.Bytes(pathToSizeAndNodes[res].Size), res, pathToSizeAndNodes[res].Nodes)
}
}
type sizeByNodes struct {
Nodes []string
Size uint64
}
type sortedMap struct {
m map[string]sizeByNodes
s []string
}
func (sm *sortedMap) Len() int {
return len(sm.m)
}
func (sm *sortedMap) Less(i, j int) bool {
return sm.m[sm.s[i]].Size > sm.m[sm.s[j]].Size
}
func (sm *sortedMap) Swap(i, j int) {
sm.s[i], sm.s[j] = sm.s[j], sm.s[i]
}
func sortedKeys(m map[string]sizeByNodes) []string {
sm := new(sortedMap)
sm.m = m
sm.s = make([]string, len(m))
i := 0
for key, _ := range m {
sm.s[i] = key
i++
}
sort.Sort(sm)
return sm.s
}
func runSsh(conns []string, command string, debug bool) []Result {
var wg sync.WaitGroup
queue := make(chan Result)
count := new(int)
// Change if you need
workers := 24
var results []Result
for _, conn := range conns {
wg.Add(1)
*count++
if debug {
color.Printf("@{y}%s\t\tcounter %3d\n", conn, *count)
}
for *count >= workers {
time.Sleep(10 * time.Millisecond)
}
go func(h string) {
defer wg.Done()
var r Result
r.Host = h
client, err := ssh.Dial("tcp", h, config)
if err != nil {
color.Printf("@{!r}%s: Failed to connect: %s\n", h, err.Error())
*count--
if debug {
color.Printf("@{y}%s\t\tcounter %3d\n", conn, *count)
}
return
}
session, err := client.NewSession()
if err != nil {
color.Printf("@{!r}%s: Failed to create session: %s\n", h, err.Error())
*count--
if debug {
color.Printf("@{y}%s\t\tcounter %3d\n", conn, *count)
}
return
}
defer session.Close()
// Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
var b bytes.Buffer
var e bytes.Buffer
session.Stdout = &b
session.Stderr = &e
if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
log.Fatalf("request for pseudo terminal failed: %s", err)
}
if err := session.Start(command); err != nil {
color.Printf("@{!r}%s: Failed to run: %s\n", h, err.Error())
color.Printf("@{!r}%s\n", strip(e.String()))
*count--
if debug {
color.Printf("@{y}%s\t\tcounter %3d\n", conn, *count)
}
return
}
if err := session.Wait(); err != nil {
log.Fatalf("Command failed: %s", err)
}
r.Res = strip(b.String())
color.Printf("@{!g}%s\n", r.Host)
fmt.Println(r.Res)
*count--
if debug {
color.Printf("@{y}%s\t\tcounter %3d\n", conn, *count)
}
runtime.Gosched()
queue <- r
}(conn)
}
go func() {
defer wg.Done()
for r := range queue {
results = append(results, r)
}
}()
wg.Wait()
return results
}