mediamtx/metrics.go

87 lines
2.1 KiB
Go
Raw Normal View History

2020-07-30 15:30:50 +00:00
package main
import (
"context"
"fmt"
"io"
"net"
2020-07-30 15:30:50 +00:00
"net/http"
2020-09-19 21:37:54 +00:00
"sync/atomic"
2020-07-30 15:30:50 +00:00
"time"
)
const (
metricsAddress = ":9998"
)
type metrics struct {
p *program
listener net.Listener
mux *http.ServeMux
server *http.Server
2020-07-30 15:30:50 +00:00
}
func newMetrics(p *program) (*metrics, error) {
listener, err := net.Listen("tcp", metricsAddress)
if err != nil {
return nil, err
}
2020-07-30 15:30:50 +00:00
m := &metrics{
p: p,
listener: listener,
2020-07-30 15:30:50 +00:00
}
m.mux = http.NewServeMux()
m.mux.HandleFunc("/metrics", m.onMetrics)
2020-07-30 15:30:50 +00:00
m.server = &http.Server{
Handler: m.mux,
}
m.p.log("[metrics] opened on " + metricsAddress)
return m, nil
2020-07-30 15:30:50 +00:00
}
func (m *metrics) run() {
err := m.server.Serve(m.listener)
2020-07-30 15:30:50 +00:00
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) {
2020-09-19 21:37:54 +00:00
now := time.Now().UnixNano() / 1000000
2020-07-30 15:30:50 +00:00
2020-09-22 06:58:38 +00:00
countClients := atomic.LoadInt64(m.p.countClients)
countPublishers := atomic.LoadInt64(m.p.countPublishers)
countReaders := atomic.LoadInt64(m.p.countReaders)
2020-10-03 19:10:41 +00:00
countSourcesRtsp := atomic.LoadInt64(m.p.countSourcesRtsp)
countSourcesRtspRunning := atomic.LoadInt64(m.p.countSourcesRtspRunning)
countSourcesRtmp := atomic.LoadInt64(m.p.countSourcesRtmp)
countSourcesRtmpRunning := atomic.LoadInt64(m.p.countSourcesRtmpRunning)
2020-07-30 15:30:50 +00:00
out := ""
2020-09-19 21:37:54 +00:00
out += fmt.Sprintf("rtsp_clients{state=\"idle\"} %d %v\n",
countClients-countPublishers-countReaders, now)
out += fmt.Sprintf("rtsp_clients{state=\"publishing\"} %d %v\n",
countPublishers, now)
out += fmt.Sprintf("rtsp_clients{state=\"reading\"} %d %v\n",
countReaders, now)
2020-10-03 19:10:41 +00:00
out += fmt.Sprintf("rtsp_sources{type=\"rtsp\",state=\"idle\"} %d %v\n",
countSourcesRtsp-countSourcesRtspRunning, now)
out += fmt.Sprintf("rtsp_sources{type=\"rtsp\",state=\"running\"} %d %v\n",
countSourcesRtspRunning, now)
out += fmt.Sprintf("rtsp_sources{type=\"rtmp\",state=\"idle\"} %d %v\n",
countSourcesRtmp-countSourcesRtmpRunning, now)
out += fmt.Sprintf("rtsp_sources{type=\"rtmp\",state=\"running\"} %d %v\n",
countSourcesRtmpRunning, now)
2020-07-30 15:30:50 +00:00
w.WriteHeader(http.StatusOK)
io.WriteString(w, out)
}