This commit is contained in:
Stefan Schwarz 2020-12-28 01:26:55 +01:00
commit b6a86b5401
3 changed files with 86 additions and 0 deletions

14
Dockerfile Normal file
View File

@ -0,0 +1,14 @@
FROM golang:1.15 as build
ADD . /app
WORKDIR /app
ENV GOOS=linux
ENV CGO_ENABLED=0
RUN go build .
# ---
FROM busybox
COPY --from=build /app/viewercount /usr/local/bin/viewercount
CMD /usr/local/bin/viewercount

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module foosinn/viewercount
go 1.15

69
main.go Normal file
View File

@ -0,0 +1,69 @@
package main
import (
"bufio"
"fmt"
"log"
"os"
"regexp"
"strconv"
"net/http"
)
const COUNTER_SLOTS = 20
func main() {
counter := NewCounter()
go counter.ScanStdin()
http.HandleFunc("/", counter.MetricsHandler)
err := http.ListenAndServe(":8080", nil)
log.Fatalf("unable to listen: %s", err)
}
type Counter struct {
counters []int
names []string
current int
}
func NewCounter() *Counter {
return &Counter{
counters: make([]int, COUNTER_SLOTS),
names: make([]string, COUNTER_SLOTS),
}
}
func (c *Counter) MetricsHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "text/plain")
for i, name := range c.names {
fmt.Fprintf(w, "rc3_stream_count[name=%q] %d\n", name, c.counters[i])
}
fmt.Fprintf(w, "rc3_stream_current[name=\"%d\"] 1\n", c.current)
}
func (c *Counter) ScanStdin() {
matcher := regexp.MustCompile(`/hls/stream-([0-9]*).ts`)
scanner := bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
matches := matcher.FindStringSubmatch(scanner.Text())
if len(matches) == 2 {
c.countViewers(matches[1])
}
}
}
func (c *Counter) countViewers(part string) {
i, _ := strconv.Atoi(part)
mod := i % COUNTER_SLOTS
if c.names[mod] != part {
c.counters[mod] = 0
}
c.current = i
c.counters[mod] += 1
c.names[mod] = part
}