forked from bluenviron/mediamtx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.go
77 lines (62 loc) · 1.34 KB
/
metrics.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
package main
import (
"context"
"fmt"
"io"
"net/http"
"time"
)
const (
metricsAddress = ":9998"
)
type metricsData struct {
clientCount int
publisherCount int
readerCount int
}
type metrics struct {
p *program
mux *http.ServeMux
server *http.Server
}
func newMetrics(p *program) *metrics {
m := &metrics{
p: p,
}
m.mux = http.NewServeMux()
m.mux.HandleFunc("/metrics", m.onMetrics)
m.server = &http.Server{
Addr: metricsAddress,
Handler: m.mux,
}
m.log("opened on " + metricsAddress)
return m
}
func (m *metrics) log(format string, args ...interface{}) {
m.p.log("[metrics] "+format, args...)
}
func (m *metrics) run() {
err := m.server.ListenAndServe()
if err != http.ErrServerClosed {
panic(err)
}
}
func (m *metrics) close() {
m.server.Shutdown(context.Background())
}
func (m *metrics) onMetrics(w http.ResponseWriter, req *http.Request) {
res := make(chan *metricsData)
m.p.events <- programEventMetrics{res}
data := <-res
if data == nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
out := ""
now := time.Now().UnixNano() / 1000000
out += fmt.Sprintf("clients %d %v\n", data.clientCount, now)
out += fmt.Sprintf("publishers %d %v\n", data.publisherCount, now)
out += fmt.Sprintf("readers %d %v\n", data.readerCount, now)
w.WriteHeader(http.StatusOK)
io.WriteString(w, out)
}