summaryrefslogtreecommitdiff
path: root/src/daq/s5proxy/src/s5proxy/stats.go
blob: 7b291b7ec0c42f080ada04116d6fbc5af97aec1a (plain) (blame)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
//
// sfive
//
// sfive - spreadspace streaming statistics suite is a generic
// statistic collection tool for streaming server infrastuctures.
// The system collects and stores meta data like number of views
// and throughput from a number of streaming servers and stores
// it in a global data store.
// The data acquisition is designed to be generic and extensible in
// order to support different streaming software.
// sfive also contains tools and applications to filter and visualize
// live and recorded data.
//
//
// Copyright (C) 2014-2016 Christian Pointner <equinox@spreadspace.org>
//                         Markus Grüneis <gimpf@gimpf.org>
//
// This file is part of sfive.
//
// sfive is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// sfive is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with sfive. If not, see <http://www.gnu.org/licenses/>.
//

package main

import (
	"errors"
	"fmt"
	"net"
	"os"
	"strings"
	"time"
)

// TODO: this is basically a copy from src/hub....

type StreamID struct {
	ContentID string `json:"content-id"`
	Format    string `json:"format"`
	Quality   string `json:"quality"`
}

type ClientData struct {
	IP        string `json:"ip"`
	UserAgent string `json:"user-agent"`
	BytesSent uint   `json:"bytes-sent"`
}

type SourceData struct {
	ClientCount   uint         `json:"client-count"`
	BytesReceived uint         `json:"bytes-received"`
	BytesSent     uint         `json:"bytes-sent"`
	Clients       []ClientData `json:"clients,omitempty"`
}

type DataUpdate struct {
	Version   uint       `json:"version"`
	Hostname  string     `json:"hostname"`
	StreamID  StreamID   `json:"streamer-id"`
	Tags      []string   `json:"tags,omitempty"`
	StartTime time.Time  `json:"start-time"`
	Duration  int64      `json:"duration-ms"`
	Data      SourceData `json:"data"`
}

type StatsWorker struct {
	stream  StreamID
	current map[string]*ClientData
	trigger chan time.Time
	output  chan<- *DataUpdate
	input   chan *ClientData
}

func NewStatsWorker(stream StreamID, updates chan<- *DataUpdate) (sw StatsWorker) {
	sw.stream = stream
	sw.current = make(map[string]*ClientData)
	sw.trigger = make(chan time.Time)
	sw.output = updates
	sw.input = make(chan *ClientData, 100)
	return
}

func (sw StatsWorker) Run() {
	for {
		select {
		case t := <-sw.trigger:
			if t.UnixNano() != 0 {
				upd := &DataUpdate{StreamID: sw.stream, StartTime: t}
				upd.Data.ClientCount = uint(len(sw.current))
				for _, c := range sw.current {
					upd.Data.Clients = append(upd.Data.Clients, *c)
					upd.Data.BytesSent += c.BytesSent
				}
				sw.output <- upd
			}
			sw.current = make(map[string]*ClientData)
		case upd := <-sw.input:
			if data, exists := sw.current[upd.IP]; exists {
				data.BytesSent += upd.BytesSent
			} else {
				sw.current[upd.IP] = upd
			}
		}
	}
}

type Stats struct {
	conf    *Config
	sock    net.Conn
	updates chan *DataUpdate
	workers map[string]StatsWorker
}

func (s *Stats) GetUpdateChannel(url string) chan<- *ClientData {
	s5l.Printf("STATS: got new client for url: %s", url)
	for name, worker := range s.workers {
		if strings.Contains(url, name) {
			return worker.input
		}
	}
	return nil
}

func parseStreamerDescriptionElement(desc, desctype string) (e []string, err error) {
	parts := strings.Split(desc, ",")
	for _, p := range parts {
		if p = strings.TrimSpace(p); p == "" {
			err = fmt.Errorf("invalid streamer description %s: '%s'", desctype, desc)
			return
		}
		e = append(e, p)
	}
	return
}

func parseStreamerDescription(desc string) (c, f, q []string, err error) {
	parts := strings.Split(desc, "/")
	if len(parts) != 3 {
		err = fmt.Errorf("invalid streamer description: '%s'", desc)
		return
	}
	if c, err = parseStreamerDescriptionElement(parts[0], "content-id"); err != nil {
		return
	}
	if f, err = parseStreamerDescriptionElement(parts[1], "format"); err != nil {
		return
	}
	if q, err = parseStreamerDescriptionElement(parts[2], "quality"); err != nil {
		return
	}
	return
}

func generateStreamerName(format, c, f, q string) string {
	return os.Expand(format, func(k string) string {
		switch k {
		case "content-id":
			return c
		case "format":
			return f
		case "quality":
			return q
		default:
			return ""
		}
	})
}

func NewStats(conf *Config) (s *Stats, err error) {
	s = &Stats{conf: conf}
	if s.sock, err = net.DialTimeout("unixgram", conf.SFive.Sock, time.Second); err != nil {
		return
	}
	s5l.Printf("STATS: connected to sfive-hub on '%s'", conf.SFive.Sock)
	s.updates = make(chan *DataUpdate, 100)

	s.workers = make(map[string]StatsWorker)
	var content, format, quality []string
	for _, desc := range conf.SFive.Streamer {
		if content, format, quality, err = parseStreamerDescription(desc); err != nil {
			return
		}
		for _, c := range content {
			for _, f := range format {
				for _, q := range quality {
					name := generateStreamerName(conf.SFive.Format, c, f, q)
					s.workers[name] = NewStatsWorker(StreamID{c, f, q}, s.updates)
					s5l.Printf("STATS: adding streamer '%s'", name)
				}
			}
		}
	}
	if len(s.workers) < 1 {
		err = errors.New("no streamers defined")
		return
	}
	return
}

func (s *Stats) Run() (err error) {
	for _, worker := range s.workers {
		go worker.Run()
	}

	d := time.Duration(s.conf.SFive.Duration) * time.Millisecond
	offset := d - (time.Duration(time.Now().UnixNano()) % d)
	s5l.Printf("STATS: waiting %v for the next duration boundary", offset)
	time.Sleep(offset)
	s5l.Printf("STATS: starting ticker")
	ticker := time.NewTicker(d)
	for _, worker := range s.workers {
		worker.trigger <- time.Unix(0, 0) // stats-worker will not send data but just reset
	}
	for {
		select {
		case t := <-ticker.C:
			t = t.Add(-1 * d)
			for _, worker := range s.workers {
				worker.trigger <- t
			}
		case upd := <-s.updates:
			upd.Version = 1
			upd.Hostname = s.conf.SFive.Hostname
			upd.Tags = s.conf.SFive.Tags
			upd.Duration = int64(s.conf.SFive.Duration)
			s5l.Printf("STATS: got data update for '%v'", upd)
			// TODO: send it out on socket
			// TODO: if sock error ... try reconnect
		}
	}
	return
}