forked from jekiapp/rexec
-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
136 lines (113 loc) · 2.25 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
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"strings"
"github.com/fatih/color"
)
func main() {
flag.Parse()
os.Exit(Main())
}
var (
colorList = []func(string, ...interface{}) string{
color.BlueString,
color.CyanString,
color.GreenString,
color.MagentaString,
color.YellowString,
}
colorCounter int
)
var (
host = flag.String("h", "", "comma separated host")
edit = flag.Bool("e", false, "edit config")
group = flag.String("g", "", "specify group to run")
)
func Main() int {
if len(os.Args) < 2 {
fmt.Println("usage: rexec [-e | -h <hosts>|-g <group>] <command>")
return 0
}
var err error
var hosts []string
if *host != "" {
hosts = strings.Split(*host, ",")
}
args := flag.Args()
if *edit {
err := editConfig()
if err != nil {
fmt.Println(errColor(err.Error()))
}
return 0
}
if len(hosts) == 0 {
hosts, err = readHostConfig(*group)
if err != nil {
fmt.Println(errColor(err.Error()))
}
}
if len(args) == 0 {
return 0
}
var grCount int
errChan := make(chan error)
for _, host := range hosts {
go run(host, args, errChan)
grCount++
}
for grCount != 0 {
err := <-errChan
if err != nil {
println(err.Error())
}
grCount--
}
return 0
}
func run(server string, command []string, err chan error) {
cmds := []string{"tsh", "ssh", server, strings.Join(command, " ")}
fmt.Println("Executing : ", cmds)
cmd := exec.Command(cmds[0], cmds[1:]...)
cmd.Stdout = newWriter(randColor(fmt.Sprintf("[%s] ", server)))
cmd.Stderr = newWriter(errColor(fmt.Sprintf("[%s] ERR : ", server)))
if errno := cmd.Run(); errno != nil {
err <- fmt.Errorf("[%s] %s", server, errno.Error())
return
}
err <- fmt.Errorf("[%s] %s", server, "session closed")
}
func randColor(s string) string {
colorCounter++
if colorCounter == len(colorList) {
colorCounter = 0
}
return colorList[colorCounter](s)
}
func errColor(s string) string {
return color.RedString(s)
}
type writer struct {
prefix string
pipe chan string
}
func newWriter(prefix string) *writer {
w := &writer{
prefix: prefix,
pipe: make(chan string),
}
go w.run()
return w
}
func (c *writer) run() {
for {
fmt.Print(<-c.pipe)
}
}
func (c *writer) Write(b []byte) (int, error) {
c.pipe <- c.prefix + string(b)
return len(b), nil
}