summaryrefslogtreecommitdiff
path: root/src/hub/src/spreadspace.org/sfive/s5srv.go
blob: 6742b6f90f9d3ddd61ace9dc791af35491a40aed (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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
//
// 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-2017 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 sfive

import (
	"context"
	"errors"
	"net"
	"net/http"
	"runtime"
	"sync"
	"time"
)

type ingestToken struct {
	updates  []*UpdateFull
	response chan error
}

type Server struct {
	cfg           SrvConfig
	store         *Store
	numWorker     int
	anonymization AnonymizationAlgo
	geoip         GeoIPLookup
	wgWorker      *sync.WaitGroup
	ingestChan    chan ingestToken
	interfaces    struct {
		pipe     net.Listener
		pipegram net.PacketConn
		web      *http.Server
	}
}

func (srv *Server) transform(update *UpdateFull) *UpdateFull {
	bytesSentTotal := uint(0)
	clients := []Client{}
	for _, client := range update.Data.Clients {
		bytesSentTotal += client.BytesSent

		if srv.geoip != nil {
			if info, err := srv.geoip.Lookup(client.IP); err != nil {
				s5l.Printf("srv|xfrm: Geo-IP lookup failed: %v", err)
			} else {
				client.GeoInfo = *info
			}
		}

		if srv.anonymization != nil {
			if aIP, err := srv.anonymization.Anonymize(client.IP); err != nil {
				s5l.Printf("srv|xfrm: anonymization failed: %v", err)
			} else {
				client.IP = aIP
			}
		}

		clients = append(clients, client)
	}
	update.Data.Clients = clients

	if uint(len(update.Data.Clients)) > update.Data.ClientCount {
		if update.Data.ClientCount > 0 {
			s5l.Printf("srv|xfrm: fixing client-count: %d -> %d", update.Data.ClientCount, len(update.Data.Clients))
		}
		update.Data.ClientCount = uint(len(update.Data.Clients))
	}
	if bytesSentTotal > update.Data.BytesSent {
		if update.Data.BytesSent > 0 {
			s5l.Printf("srv|xfrm: fixing bytes-sent: %d -> %d", update.Data.BytesSent, bytesSentTotal)
		}
		update.Data.BytesSent = bytesSentTotal
	}

	return update
}

func (srv *Server) transformMany(updates []*UpdateFull) {
	for _, update := range updates {
		srv.transform(update)
	}
}

func (srv *Server) ingestWorker(idx int) {
	for {
		select {
		case token, ok := <-srv.ingestChan:
			if !ok {
				return
			}
			srv.transformMany(token.updates)
			token.response <- srv.store.AppendMany(token.updates)
		}
	}
}

func (srv *Server) Ingest(update *UpdateFull) error {
	return srv.IngestMany([]*UpdateFull{update})
}

func (srv *Server) IngestMany(updates []*UpdateFull) error {
	token := ingestToken{updates: updates, response: make(chan error, 1)}
	defer close(token.response)
	srv.ingestChan <- token
	return <-token.response
}

func (srv *Server) shutdownInterfaces() (errors int) {
	ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
	c := make(chan error)
	go func() { c <- srv.webStop(ctx) }()
	go func() { c <- srv.pipeStop(ctx) }()
	go func() { c <- srv.pipegramStop(ctx) }()

	errors = 0
	for i := 0; i < 3; i++ {
		if err := <-c; err != nil {
			s5l.Printf("srv: interface shutdown failed failed: %v", err)
			errors++
		}
	}
	close(c) // closing channel here in the hopes that this leads to a panic
	// in case the number of channel reads (for loop above) doesn't match the
	// number of interfaces to be stopped
	cancel()
	return
}

func (srv *Server) Start() (wg sync.WaitGroup, err error) {
	if srv.cfg.Interfaces.Pipe.ListenPath != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			srv.ServePipe(srv.cfg.Interfaces.Pipe)
		}()
	}

	if srv.cfg.Interfaces.Pipegram.ListenPath != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			srv.ServePipegram(srv.cfg.Interfaces.Pipegram)
		}()
	}

	if srv.cfg.Interfaces.Web.ListenAddr != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			srv.ServeWeb(srv.cfg.Interfaces.Web)
		}()
	}

	if srv.cfg.Forwards.SFive.URL != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			srv.RunForwarding(srv.cfg.Forwards.SFive)
		}()
	}

	if srv.cfg.Forwards.Elasticsearch.URL != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			srv.RunForwardingEs(srv.cfg.Forwards.Elasticsearch)
		}()
	}

	if srv.cfg.Forwards.Graphite.Host != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			srv.RunForwardingGraphite(srv.cfg.Forwards.Graphite)
		}()
	}

	if srv.cfg.Forwards.Piwik.URL != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			srv.RunForwardingPiwik(srv.cfg.Forwards.Piwik)
		}()
	}
	return wg, nil
}

func (srv *Server) Shutdown() {
	s5l.Printf("srv: shutting down")

	if errors := srv.shutdownInterfaces(); errors != 0 {
		s5l.Printf("srv: shutdown of at least one interface failed, this is an unclean shutdown!!!")
	}

	close(srv.ingestChan) // close ingest channel to tell worker to stop
	srv.wgWorker.Wait()   // wait for worker to finish up
	s5l.Printf("srv: all worker stopped")

	srv.store.Close()
	s5l.Printf("srv: finished")
}

func NewServer(cfg SrvConfig) (srv *Server, err error) {
	srv = &Server{cfg: cfg}
	if srv.store, err = NewStore(cfg.Store); err != nil {
		return
	}

	if cfg.Transform.Anonymize {
		if srv.anonymization, err = NewCryptopanAnonymization(cfg.Transform.AnonKeyfile); err != nil {
			err = errors.New("failed to initialize IP address anonymization: " + err.Error())
			return
		}
		s5l.Printf("srv|xfrm: using IP address anonymization: %s", srv.anonymization)
	}

	if cfg.Transform.GeoipDB != "" {
		if srv.geoip, err = NewMaxMindGeoIP2(cfg.Transform.GeoipDB); err != nil {
			err = errors.New("failed to initialize Geo-IP Lookup: " + err.Error())
			return
		}
		s5l.Printf("srv|xfrm: using Geo-IP Lookup: %s", srv.geoip)
	}

	srv.numWorker = runtime.NumCPU()
	if cfg.Workers > 0 {
		srv.numWorker = cfg.Workers
	}

	srv.wgWorker = &sync.WaitGroup{}
	srv.ingestChan = make(chan ingestToken, srv.numWorker)
	for i := 0; i < srv.numWorker; i = i + 1 {
		srv.wgWorker.Add(1)
		go func(idx int) {
			defer srv.wgWorker.Done()
			srv.ingestWorker(idx)
		}(i)
	}
	s5l.Printf("srv: started with %d worker", srv.numWorker)
	return
}