forked from owncast/owncast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
viewers.go
97 lines (79 loc) · 2.54 KB
/
viewers.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
package metrics
import (
"time"
"github.com/nakabonne/tstorage"
"github.com/owncast/owncast/core"
"github.com/owncast/owncast/core/chat"
"github.com/owncast/owncast/core/data"
log "github.com/sirupsen/logrus"
)
var storage tstorage.Storage
func startViewerCollectionMetrics() {
storage, _ = tstorage.NewStorage(
tstorage.WithTimestampPrecision(tstorage.Seconds),
tstorage.WithDataPath("./data/metrics"),
)
defer storage.Close()
collectViewerCount()
for range time.Tick(viewerMetricsPollingInterval) {
collectViewerCount()
collectChatClientCount()
}
}
func collectViewerCount() {
// Don't collect metrics for viewers if there's no stream active.
if !core.GetStatus().Online {
return
}
count := core.GetStatus().ViewerCount
// Save active viewer count to our Prometheus collector.
activeViewerCount.Set(float64(count))
// Insert active viewer count into our on-disk time series storage.
if err := storage.InsertRows([]tstorage.Row{
{
Metric: activeViewerCountKey,
DataPoint: tstorage.DataPoint{Timestamp: time.Now().Unix(), Value: float64(count)},
},
}); err != nil {
log.Errorln(err)
}
}
func collectChatClientCount() {
count := len(chat.GetClients())
activeChatClientCount.Set(float64(count))
// Total message count
cmc := data.GetMessagesCount()
// Insert message count into Prometheus collector.
currentChatMessageCount.Set(float64(cmc))
// Total user count
uc := data.GetUsersCount()
// Insert user count into Prometheus collector.
chatUserCount.Set(float64(uc))
// Insert active chat user count into our on-disk time series storage.
if err := storage.InsertRows([]tstorage.Row{
{
Metric: activeChatClientCountKey,
DataPoint: tstorage.DataPoint{Timestamp: time.Now().Unix(), Value: float64(count)},
},
}); err != nil {
log.Errorln(err)
}
}
// GetViewersOverTime will return a window of viewer counts over time.
func GetViewersOverTime(start, end time.Time) []TimestampedValue {
p, err := storage.Select(activeViewerCountKey, nil, start.Unix(), end.Unix())
if err != nil && err != tstorage.ErrNoDataPoints {
log.Errorln(err)
}
datapoints := makeTimestampedValuesFromDatapoints(p)
return datapoints
}
// GetChatClientCountOverTime will return a window of connected chat clients over time.
func GetChatClientCountOverTime(start, end time.Time) []TimestampedValue {
p, err := storage.Select(activeChatClientCountKey, nil, start.Unix(), end.Unix())
if err != nil && err != tstorage.ErrNoDataPoints {
log.Errorln(err)
}
datapoints := makeTimestampedValuesFromDatapoints(p)
return datapoints
}