/
server.go
564 lines (508 loc) · 14.1 KB
/
server.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
package main
import (
"bufio"
"context"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/ghodss/yaml"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
_ "github.com/tomclegg/canfs"
"github.com/tomclegg/mp3dir"
"github.com/tomclegg/nbtee2"
"github.com/tomclegg/pcm"
)
//go:generate make README.md
//go:generate go run $GOPATH/pkg/mod/github.com/tomclegg/canfs@v0.0.0-20180505155505-ee5f4875da7d/generate.go -pkg=main -id=sysUI -out=generated_sys_ui.go -dir=./ui_sys
//go:generate go run $GOPATH/pkg/mod/github.com/tomclegg/canfs@v0.0.0-20180505155505-ee5f4875da7d/generate.go -pkg=main -id=archiveUI -out=generated_archive_ui.go -dir=./ui_archive
type channel struct {
Input string // input channel (can be empty)
Command string // shell command to run on input
Calm float64 // minimum seconds between restarts
Buffers int // max buffered writes per listener
BufferLow int // min buffered writes after underrun
Chunk int // if > 0, write only fixed-size blocks
MP3 bool // write only complete mp3 frames
ContentType string // Content-Type response header
MP3Dir mp3dir.Writer
archive http.Handler
inject io.Writer
tee nbtee2.Tee
setupOnce sync.Once
hwy3 *hwy3
name string
}
func (ch *channel) setup() {
if ch.Buffers == 0 {
ch.Buffers = 4
}
if ch.MP3 && ch.ContentType == "" {
ch.ContentType = "audio/mpeg"
}
go ch.run()
if ch.MP3Dir.Root != "" {
if ch.MP3Dir.SplitOnSize > 0 {
lgr := logrus.WithFields(logrus.Fields{
"channel": ch.name,
"root": ch.MP3Dir.Root,
})
writer := newStubbornWriter(&ch.MP3Dir, lgr, time.Second)
go ch.hwy3.trackers.Copy(writer, ch.tee.NewReader(ch.BufferLow, ch.Buffers), "write:MP3Dir:"+ch.name)
} else {
logrus.WithField("channel", ch.name).Warn("not writing to MP3Dir -- requires MP3Dir.SplitOnSize")
}
if ch.MP3Dir.BitRate > 0 && strings.HasPrefix(ch.name, "/") {
ch.archive = http.StripPrefix(ch.name, http.FileServer(&ch.MP3Dir))
}
}
if strings.HasPrefix(ch.ContentType, "audio/L16;") {
for _, window := range []time.Duration{400 * time.Millisecond, 3 * time.Second} {
pcma := &pcm.Analyzer{
Window: window,
ObserveEvery: window,
ObserveRMS: ch.hwy3.loudness.WithLabelValues(ch.name, window.String()).Observe,
ObservePeak: ch.hwy3.peak.WithLabelValues(ch.name, window.String()).Observe,
}
pcma.UseMIMEType(ch.ContentType)
go io.Copy(pcma, ch.tee.NewReader(ch.BufferLow, ch.Buffers))
}
}
}
// run data for channel forever.
//
// {inject | input} -> loop { runCommandAndFilter }
func (ch *channel) run() {
log := logrus.WithFields(logrus.Fields{
"channel": ch.name,
})
log.Info("start")
defer log.Info("stop")
var src io.Reader
src, ch.inject = io.Pipe()
if inch, ok := ch.hwy3.Channels[ch.Input]; !ok && ch.Input != "" {
log.Fatalf("bad input channel %q", ch.Input)
} else if ok {
go func() {
r := inch.NewReader(context.Background())
defer r.Close()
ch.hwy3.trackers.Copy(ch.inject, r, "input:"+ch.name)
}()
}
d := time.Duration(ch.Calm * float64(time.Second))
if d <= 0 {
d = time.Second
}
for calm := time.NewTicker(d).C; ; <-calm {
ch.runCommandAndFilter(&ch.tee, src, log)
}
}
// pipe data through command and filters if specified.
//
// {command -> chunk -> mp3 -> tee}
func (ch *channel) runCommandAndFilter(w io.Writer, r io.Reader, log *logrus.Entry) {
var err error
if ch.Command != "" {
cmd := exec.Command("sh", "-c", ch.Command)
cmd.Stdin = r
stderr, err := cmd.StderrPipe()
if err != nil {
log.Fatalf("StderrPipe(): %s", err)
}
go func() {
defer stderr.Close()
log := log.WithField("Stderr", true)
r := bufio.NewReader(stderr)
var s string
var err error
for err == nil {
s, err = r.ReadString('\n')
if s != "" {
log.Info(s)
}
}
}()
if stdout, err := cmd.StdoutPipe(); err != nil {
log.Fatalf("StdoutPipe(): %s", err)
} else {
defer stdout.Close()
r = stdout
}
defer func() {
go func() {
err := cmd.Wait()
log.WithError(err).Error("command exit")
}()
}()
log.WithField("ExecArgs", cmd.Args).Info("command start")
cmd.Start()
}
if ch.MP3 {
mp3w := &MP3Writer{Writer: w}
defer mp3w.Close()
w = mp3w
}
if ch.Chunk > 1 {
w = bufio.NewWriterSize(w, ch.Chunk)
}
size, err := ch.hwy3.trackers.Copy(w, r, "output:"+ch.name)
log.WithField("ReadBytes", size).WithError(err).Info("EOF")
}
func (ch *channel) NewReader(ctx context.Context) io.ReadCloser {
ch.setupOnce.Do(ch.setup)
return ch.tee.NewReaderContext(ctx, ch.BufferLow, ch.Buffers)
}
func (ch *channel) Inject(w http.ResponseWriter, req *http.Request) {
if sv := req.Context().Value(http.ServerContextKey); sv == nil || sv != ch.hwy3.ctlServer {
http.Error(w, "not authorized", http.StatusUnauthorized)
return
}
if ch.inject == nil {
http.Error(w, "cannot inject", http.StatusBadRequest)
}
// TODO: prevent concurrent injects
inj := ch.inject
if xc := req.Header.Get("X-Chunk"); xc != "" {
chunk, err := strconv.Atoi(xc)
if err != nil || chunk > 1<<24 || chunk < 0 {
http.Error(w, fmt.Sprintf("bad x-chunk header %q", xc), http.StatusBadRequest)
return
}
if chunk > 1 {
inj = bufio.NewWriterSize(inj, chunk)
}
}
ch.hwy3.trackers.Copy(inj, req.Body, "input:"+ch.name)
}
func (ch *channel) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != ch.name {
if ch.archive == nil {
code := http.StatusNotFound
http.Error(w, http.StatusText(code), code)
return
}
if req.Method != "GET" && req.Method != "HEAD" {
code := http.StatusMethodNotAllowed
http.Error(w, http.StatusText(code), code)
return
}
if fnm := req.FormValue("filename"); fnm != "" {
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", fnm))
} else {
w.Header().Set("Content-Disposition", "attachment")
}
w.Header().Set("Content-Type", ch.ContentType)
ch.archive.ServeHTTP(w, req)
return
}
if req.Method == http.MethodPost {
ch.Inject(w, req)
return
}
if ch.ContentType != "" {
w.Header().Set("Content-Type", ch.ContentType)
}
if req.Method == http.MethodHead {
return
}
rdr := ch.NewReader(req.Context())
defer rdr.Close()
ch.hwy3.trackers.Copy(w, rdr, "client:"+ch.name+","+req.Header.Get("X-Request-Id")+","+req.Header.Get("X-Forwarded-For")+","+req.RemoteAddr)
}
type counter struct {
http.ResponseWriter
bytes int64
}
func (w *counter) Write(p []byte) (n int, err error) {
n, err = w.ResponseWriter.Write(p)
w.bytes += int64(n)
return
}
type hwy3 struct {
ControlSocket string
Listen string
ListenTLS string
CertFile string
KeyFile string
LogFormat string
Channels map[string]*channel
Theme struct {
Title string `json:"title"`
}
serveUI bool
clients int32
ctlServer *http.Server
cert chan *tls.Certificate // server/updater can safely borrow/replace a *cert
trackers trackers
loudness *prometheus.HistogramVec
peak *prometheus.HistogramVec
metrics http.Handler
}
func (h *hwy3) Inject(channel string, rdr io.Reader, chunk int) error {
hc := http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", h.ControlSocket)
},
},
}
u, err := url.Parse("http://localhost")
if err != nil {
return err
}
addr, err := u.Parse(channel)
if err != nil {
return err
}
req, err := http.NewRequest("POST", addr.String(), rdr)
if err != nil {
return err
}
req.Header.Set("X-Chunk", strconv.FormatInt(int64(chunk), 10))
resp, err := hc.Do(req)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("HTTP status %d", resp.StatusCode)
}
return nil
}
func (h *hwy3) serveTheme(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(h.Theme)
}
func (h *hwy3) serveChannels(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
type chaninfo struct {
Archive bool `json:"archive"`
}
channels := make(map[string]chaninfo, len(h.Channels))
for name, ch := range h.Channels {
channels[name] = chaninfo{
Archive: ch.archive != nil,
}
}
json.NewEncoder(w).Encode(channels)
}
func (h *hwy3) serveStats(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&h.trackers)
}
func (h *hwy3) middleware(mux http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Header.Get("X-Request-Id") == "" {
req.Header.Set("X-Request-Id", fmt.Sprintf("%x", time.Now().UnixNano()))
}
cw := &counter{ResponseWriter: w}
t0 := time.Now()
log := logrus.WithFields(logrus.Fields{
"Request": fmt.Sprintf("%x", t0.UnixNano()),
})
log.WithFields(logrus.Fields{
"RemoteAddr": req.RemoteAddr,
"XForwardedFor": req.Header.Get("X-Forwarded-For"),
"Method": req.Method,
"Path": req.URL.Path,
}).Info("start")
atomic.AddInt32(&h.clients, 1)
defer atomic.AddInt32(&h.clients, -1)
mux.ServeHTTP(cw, req)
t := time.Since(t0)
log.WithFields(logrus.Fields{
"Bytes": cw.bytes,
"BytesPerSecond": int64(float64(cw.bytes) / t.Seconds()),
"Seconds": t.Seconds(),
}).Info("end")
})
}
func (h *hwy3) serveRobotsTxt(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("User-agent: *\nDisallow: /\n"))
}
func (h *hwy3) Start() error {
reg := prometheus.NewRegistry()
h.loudness = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "loudness",
Buckets: prometheus.LinearBuckets(-40, 1, 40),
}, []string{"channel", "window"})
reg.MustRegister(h.loudness)
h.peak = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "peak",
Buckets: prometheus.LinearBuckets(-40, 1, 40),
}, []string{"channel", "window"})
reg.MustRegister(h.peak)
h.metrics = promhttp.HandlerFor(reg, promhttp.HandlerOpts{})
for name, ch := range h.Channels {
ch.name = name
ch.hwy3 = h
}
// Initialize all channels so panics/complaints come early.
var wg sync.WaitGroup
for _, ch := range h.Channels {
wg.Add(1)
go func(ch *channel) {
defer wg.Done()
ch.NewReader(context.Background()).Close()
}(ch)
}
wg.Wait()
for _, ch := range h.Channels {
if ch.archive != nil {
h.serveUI = true
break
}
}
mux := http.NewServeMux()
mux.Handle("/sys/ui/", http.StripPrefix("/sys/ui/", http.FileServer(sysUI)))
if h.serveUI {
mux.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(archiveUI)))
}
mux.HandleFunc("/sys/stats", h.serveStats)
mux.HandleFunc("/sys/channels", h.serveChannels)
mux.HandleFunc("/sys/theme", h.serveTheme)
mux.HandleFunc("/robots.txt", h.serveRobotsTxt)
mux.HandleFunc("/", h.serveHTTP)
stack := h.middleware(mux)
errs := make(chan error)
if h.ControlSocket != "" {
if err := os.Remove(h.ControlSocket); err != nil && !os.IsNotExist(err) {
return err
}
ln, err := net.Listen("unix", h.ControlSocket)
if err != nil {
return err
}
err = os.Chmod(h.ControlSocket, 0777)
if err != nil {
return err
}
h.ctlServer = &http.Server{
Handler: stack,
}
go func() {
errs <- h.ctlServer.Serve(ln)
}()
}
if h.Listen != "" {
srv := &http.Server{
Addr: h.Listen,
Handler: stack,
}
go func() {
errs <- srv.ListenAndServe()
}()
}
if h.ListenTLS != "" {
h.cert = make(chan *tls.Certificate, 1)
go h.ensureCurrentCertificate()
srv := &http.Server{
Addr: h.ListenTLS,
Handler: stack,
TLSConfig: &tls.Config{
GetCertificate: h.getCertificate,
//NextProtos: []string{"h2", "http/1.1"},
PreferServerCipherSuites: true,
CurvePreferences: []tls.CurveID{
tls.CurveP256,
tls.X25519,
},
MinVersion: tls.VersionTLS12,
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
},
},
}
go func() {
errs <- srv.ListenAndServeTLS("", "")
}()
}
return <-errs
}
func (h *hwy3) getCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
if h.cert == nil {
panic("no cert chan")
}
cert := <-h.cert
h.cert <- cert
return cert, nil
}
func (h *hwy3) ensureCurrentCertificate() {
for first := true; ; first = false {
cert, err := tls.LoadX509KeyPair(h.CertFile, h.KeyFile)
if err != nil {
if first {
logrus.WithError(err).Fatal("error loading TLS certificate")
}
logrus.WithError(err).Warn("error loading TLS certificate")
time.Sleep(time.Second)
continue
}
if !first {
<-h.cert
}
h.cert <- &cert
time.Sleep(time.Minute)
}
}
func (h *hwy3) serveHTTP(w http.ResponseWriter, req *http.Request) {
if h.serveUI && req.URL.Path == "/" {
http.Redirect(w, req, "/ui/", http.StatusFound)
return
}
if req.URL.Path == "/metrics" {
h.metrics.ServeHTTP(w, req)
return
}
for last := len(req.URL.Path); last >= 0; last = strings.LastIndexByte(req.URL.Path[:last], '/') {
if ch, ok := h.Channels[req.URL.Path[:last]]; ok {
ch.ServeHTTP(w, req)
break
} else if last == 0 {
http.Error(w, "not found", http.StatusNotFound)
break
}
}
}
func main() {
config := flag.String("config", "hwy3.yaml", "yaml or json configuration `file`")
inject := flag.String("inject", "", "inject stdin to specified `channel`")
chunk := flag.Int("chunk", 0, "use `n`-byte chunks when injecting")
flag.Parse()
var h hwy3
buf, err := ioutil.ReadFile(*config)
if err != nil {
logrus.Fatal(err)
}
err = yaml.Unmarshal(buf, &h)
if err != nil {
logrus.WithField("config", *config).Fatal(err)
}
if h.LogFormat == "json" {
logrus.SetFormatter(&logrus.JSONFormatter{})
}
if *inject != "" {
logrus.Fatal(h.Inject(*inject, os.Stdin, *chunk))
}
logrus.Fatal(h.Start())
}