-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlogtailer.go
189 lines (167 loc) · 4.5 KB
/
logtailer.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
package main
import (
"bufio"
"fmt"
"hash/fnv"
"io"
"os"
"os/exec"
"os/signal"
"strings"
"sync"
"time"
)
// This anonymous struct will store some global state
// Note that in our case, having global state is a priori *not* a problem per se,
// but if you think there's a better way, let's discuss it!
var state struct {
Processes []*os.Process
}
// Server model (kind of)
type Server struct {
hostname string
_coloredHostname string
}
// coloredHostname() returns a colorized version of the hostname
// The color shouldn't vary for a given hostname so we calculate
// a numeric hash for the hostname and reduce it to a list of colors
func (s *Server) coloredHostname() string {
if s._coloredHostname != "" {
return s._coloredHostname
}
if !TermSupportsColors() {
return s.hostname
}
validColors := []string{
"33", "34", "35", "36", "37",
}
colorIndex := HashHostnameToInt(s.hostname) % len(validColors)
color := validColors[colorIndex]
colorReset := "\x1b[0m"
colorHost := "\x1b[" + color + "m"
s._coloredHostname = colorHost + s.hostname + colorReset
return s._coloredHostname
}
func main() {
//args parsing
var servers []Server
var files []string
var n string
n = "0"
for _, elem := range os.Args[1:] {
if strings.HasPrefix(elem, "/") {
files = append(files, elem)
} else if strings.HasPrefix(elem, "-n") {
n = elem[2:]
} else {
servers = append(servers, Server{hostname: elem})
}
}
//fail if no server or no file
if len(files) == 0 || len(servers) == 0 {
fmt.Fprintln(os.Stderr, "Please specify at least ONE server and ONE file beginning with '/'")
os.Exit(1)
}
//this will help us wait instead of exiting directly
var wg sync.WaitGroup
//signal handling
go HandleCtrlC()
//for each server, let's tail the logs (async!)
for _, server := range servers {
wg.Add(1)
go func(server Server) {
tailServerLogs(server, files, n)
wg.Done()
}(server)
}
//wait for all goroutines to finish
wg.Wait()
}
//tail logs on a remote server
func tailServerLogs(server Server, files []string, n string) {
//build command
cmdName := "ssh"
tailCmd := "sudo tail -n " + n + " -F " + strings.Join(files, " ")
cmdArgs := []string{server.hostname, tailCmd}
//prepare command
cmd := exec.Command(cmdName, cmdArgs...)
//handle stdout
cmdStdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Fprintln(os.Stderr, "Error creating stdout pipe for command: ", err)
return
}
HandlePipe(cmdStdout, server.coloredHostname(), ColorStream("out", "stdout"))
//handle stderr
cmdStderr, err := cmd.StderrPipe()
if err != nil {
fmt.Fprintln(os.Stderr, "Error creating stderr pipe for command: ", err)
return
}
HandlePipe(cmdStderr, server.coloredHostname(), ColorStream("err", "stderr"))
//launch command
err = cmd.Start()
if err != nil {
fmt.Fprintln(os.Stderr, "Error starting command: ", err)
return
}
fmt.Println("Connecting to", server.hostname)
//add process to state for later kill
state.Processes = append(state.Processes, cmd.Process)
//wait for it to end
err = cmd.Wait()
if err != nil {
fmt.Fprintln(os.Stderr, "Error waiting for command: ", err)
return
}
}
// HashHostnameToInt generates a numeric hash out of a string
func HashHostnameToInt(str string) int {
h := fnv.New32a()
h.Write([]byte(str))
return int(h.Sum32())
}
// ColorStream colorizes stdout/stdin markers (red=err, green=out)
func ColorStream(message string, stream string) string {
if !TermSupportsColors() {
return message
}
colorOkay := "\x1b[32m"
colorFail := "\x1b[31m"
colorReset := "\x1b[0m"
if stream == "stdout" {
return colorOkay + message + colorReset
} else if stream == "stderr" {
return colorFail + message + colorReset
} else {
//turn it into an error?
return message
}
}
// HandlePipe handles reading on stdout/stderr
func HandlePipe(pipe io.ReadCloser, prefix string, marker string) {
scanner := bufio.NewScanner(pipe)
go func() {
for scanner.Scan() {
now := time.Now().Format(time.RFC3339)
fmt.Printf("%s %s %s %s\n", prefix, now, marker, scanner.Text())
}
}()
}
// TermSupportsColors checks whether current terminal support colors
func TermSupportsColors() bool {
return strings.HasPrefix(os.Getenv("TERM"), "xterm")
}
// HandleCtrlC handles SIGINT signal when a user types Ctrl+C to stop execution
func HandleCtrlC() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
<-signals
for _, process := range state.Processes {
if process != nil {
fmt.Println("Stopping process", process.Pid)
process.Kill()
}
}
os.Exit(0)
}