2020-10-02 10:06:14 +03:00
|
|
|
package metrics
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
2022-03-07 06:43:57 +03:00
|
|
|
"github.com/nakabonne/tstorage"
|
|
|
|
"github.com/owncast/owncast/core"
|
2022-03-07 04:26:52 +03:00
|
|
|
"github.com/owncast/owncast/core/chat"
|
|
|
|
"github.com/owncast/owncast/core/data"
|
2022-03-07 06:43:57 +03:00
|
|
|
log "github.com/sirupsen/logrus"
|
2020-10-02 10:06:14 +03:00
|
|
|
)
|
|
|
|
|
2020-11-13 02:14:59 +03:00
|
|
|
// How often we poll for updates.
|
2020-11-24 09:21:20 +03:00
|
|
|
const viewerMetricsPollingInterval = 2 * time.Minute
|
2020-10-02 10:06:14 +03:00
|
|
|
|
2022-03-07 06:43:57 +03:00
|
|
|
var storage tstorage.Storage
|
|
|
|
|
2020-10-02 10:06:14 +03:00
|
|
|
func startViewerCollectionMetrics() {
|
2022-03-07 06:43:57 +03:00
|
|
|
storage, _ = tstorage.NewStorage(
|
|
|
|
tstorage.WithTimestampPrecision(tstorage.Seconds),
|
|
|
|
tstorage.WithDataPath("./data/metrics"),
|
|
|
|
)
|
|
|
|
defer storage.Close()
|
|
|
|
|
2020-10-02 10:06:14 +03:00
|
|
|
collectViewerCount()
|
2022-03-07 06:43:57 +03:00
|
|
|
handlePolling()
|
2020-10-02 10:06:14 +03:00
|
|
|
|
|
|
|
for range time.Tick(viewerMetricsPollingInterval) {
|
|
|
|
collectViewerCount()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func collectViewerCount() {
|
2022-03-07 06:43:57 +03:00
|
|
|
// Don't collect metrics for viewers if there's no stream active.
|
|
|
|
if !core.GetStatus().Online {
|
|
|
|
return
|
2020-10-02 10:06:14 +03:00
|
|
|
}
|
2022-03-07 06:43:57 +03:00
|
|
|
}
|
2020-10-02 10:06:14 +03:00
|
|
|
|
2022-03-07 06:43:57 +03:00
|
|
|
func collectChatClientCount() {
|
|
|
|
count := len(chat.GetClients())
|
|
|
|
activeChatClientCount.Set(float64(count))
|
2022-03-07 04:26:52 +03:00
|
|
|
|
|
|
|
// Save to our Prometheus collector.
|
|
|
|
activeViewerCount.Set(float64(count))
|
|
|
|
|
|
|
|
// Total message count
|
|
|
|
cmc := data.GetMessagesCount()
|
|
|
|
currentChatMessageCount.Set(float64(cmc))
|
|
|
|
|
|
|
|
// Total user count
|
|
|
|
uc := data.GetUsersCount()
|
|
|
|
chatUserCount.Set(float64(uc))
|
2022-03-07 06:43:57 +03:00
|
|
|
|
|
|
|
if err := storage.InsertRows([]tstorage.Row{
|
|
|
|
{
|
|
|
|
Metric: "viewercount",
|
|
|
|
DataPoint: tstorage.DataPoint{Timestamp: time.Now().Unix(), Value: float64(count)},
|
|
|
|
},
|
|
|
|
}); err != nil {
|
|
|
|
log.Errorln(err)
|
|
|
|
}
|
2022-03-07 04:26:52 +03:00
|
|
|
}
|
|
|
|
|
2022-03-07 06:43:57 +03:00
|
|
|
// GetViewersOverTime will return a window of viewer counts over time.
|
|
|
|
func GetViewersOverTime(start, end time.Time) []timestampedValue {
|
|
|
|
p, err := storage.Select("viewercount", nil, start.Unix(), end.Unix())
|
|
|
|
if err != nil && err != tstorage.ErrNoDataPoints {
|
|
|
|
log.Errorln(err)
|
|
|
|
}
|
|
|
|
datapoints := makeTimestampedValuesFromDatapoints(p)
|
|
|
|
|
|
|
|
return datapoints
|
2020-10-02 10:06:14 +03:00
|
|
|
}
|