-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
186 lines (154 loc) · 4.16 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
package main
import (
"bytes"
_ "embed"
"flag"
"fmt"
"html"
"io"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"time"
"github.com/nikolaydubina/watchhttp/args"
"github.com/nikolaydubina/watchhttp/htmldelta"
)
const doc string = `
Run command periodically and expose latest STDOUT as HTTP endpoint
Examples:
$ watchhttp -t 1s -p 9000 -- ls -la
$ watchhttp vmstat
$ watchhttp tail /var/log/system.log
$ watchhttp -json -- cat myfile.json
$ watchhttp -p 9000 -json -- kubectl get pod mypod -o=json
$ watchhttp -p 9000 -- kubectl get pod mypod -o=yaml
$ watchhttp curl ...
$ watchhttp -json -- /bin/sh -c 'curl ... | jq'
Command options:
`
func main() {
flag.Usage = func() {
fmt.Fprint(flag.CommandLine.Output(), doc)
flag.PrintDefaults()
}
cmdargs, hasFlags := args.GetCommandFromArgs(os.Args[1:])
var (
port int = 9000
interval time.Duration = time.Second
contentTypeJSON bool = false
isDelta bool = false
)
if hasFlags {
flag.IntVar(&port, "p", port, "port")
flag.DurationVar(&interval, "t", interval, `interval to execute command (units: ns, us, µs, ms, s, m, h, d, w, y)`)
flag.BoolVar(&contentTypeJSON, "json", contentTypeJSON, "set Content-Type: application/json")
flag.BoolVar(&isDelta, "d", isDelta, "show animated HTML delta difference (only JSON)")
flag.Parse()
}
if len(cmdargs) == 0 {
log.Fatal("missing command")
}
log.Printf("serving at port=%d with interval=%v latest STDOUT of command: %v\n", port, interval, strings.Join(cmdargs, " "))
cmdrunner := &CmdRunner{
ticker: time.NewTicker(interval),
lastStdOut: bytes.NewBuffer(nil),
mtx: &sync.RWMutex{},
cmd: cmdargs,
}
go cmdrunner.Run()
var runner io.WriterTo = cmdrunner
if isDelta && contentTypeJSON {
runner = &JSONHTMLDeltaHandler{
provider: cmdrunner,
renderer: &htmldelta.JSONRenderer{
Title: html.EscapeString(strings.Join(cmdargs, " ")),
},
}
}
runnerHandler := ForwardHandler{
Provider: runner,
Interval: interval,
}
if isDelta {
runnerHandler.ContentType = "text/html; charset=utf-8"
} else if contentTypeJSON {
runnerHandler.ContentType = "application/json"
}
http.HandleFunc("/", runnerHandler.handleRequest)
http.ListenAndServe(":"+strconv.Itoa(port), nil)
}
// ForwardHandler will call Payload from wrapped class and serve it in response
type ForwardHandler struct {
ContentType string
Interval time.Duration
Provider interface {
WriteTo(w io.Writer) (int64, error)
}
}
func (s ForwardHandler) handleRequest(w http.ResponseWriter, req *http.Request) {
if s.ContentType != "" {
w.Header().Set("Content-Type", s.ContentType)
}
w.Header().Set("Refresh", fmt.Sprintf("%.0f", s.Interval.Seconds()))
if _, err := s.Provider.WriteTo(w); err != nil {
log.Fatal(err)
}
}
// JSONHTMLDeltaHandler will pass data from raw JSON provider to HTML JSON delta renderer and return result
type JSONHTMLDeltaHandler struct {
renderer *htmldelta.JSONRenderer
provider interface {
WriteTo(w io.Writer) (int64, error)
}
}
func (s *JSONHTMLDeltaHandler) WriteTo(w io.Writer) (written int64, err error) {
b := &bytes.Buffer{}
b.Grow(1000)
s.provider.WriteTo(b)
if b.Len() == 0 {
return 0, nil
}
return s.renderer.ReadBytes(b.Bytes()).WriteTo(w)
}
// CmdRunner runs command on interval and stores last STDOUT in buffer
type CmdRunner struct {
ticker *time.Ticker
cmd []string
lastStdOut *bytes.Buffer
mtx *sync.RWMutex
}
func (s *CmdRunner) LastStdOutBytes() []byte {
s.mtx.RLock()
defer s.mtx.RUnlock()
return s.lastStdOut.Bytes()
}
func (s *CmdRunner) WriteTo(w io.Writer) (written int64, err error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
return io.Copy(w, bytes.NewReader(s.lastStdOut.Bytes()))
}
func (s *CmdRunner) Run() {
for range s.ticker.C {
cmd := exec.Command(s.cmd[0], s.cmd[1:]...)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatal(err)
}
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
s.mtx.Lock()
s.lastStdOut.Reset()
if _, err := io.Copy(s.lastStdOut, stdout); err != nil {
log.Fatal(err)
}
s.mtx.Unlock()
if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
}
}