forked from l7mp/stunner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stunner.go
297 lines (255 loc) · 8.6 KB
/
stunner.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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Package stunner contains the public API for l7mp/stunner, a Kubernetes ingress gateway for WebRTC
package stunner
import (
"fmt"
"os"
"github.com/google/uuid"
"github.com/pion/logging"
"github.com/pion/transport/v3"
"github.com/pion/transport/v3/stdnet"
"github.com/l7mp/stunner/internal/manager"
"github.com/l7mp/stunner/internal/object"
"github.com/l7mp/stunner/internal/resolver"
"github.com/l7mp/stunner/internal/telemetry"
stnrv1 "github.com/l7mp/stunner/pkg/apis/v1"
"github.com/l7mp/stunner/pkg/logger"
)
const DefaultLogLevel = "all:WARN"
var DefaultInstanceId = fmt.Sprintf("default/stunnerd-%s", uuid.New().String())
// Stunner is an instance of the STUNner deamon.
type Stunner struct {
name, version string
adminManager, authManager, listenerManager, clusterManager manager.Manager
suppressRollback, dryRun bool
resolver resolver.DnsResolver
udpThreadNum int
telemetry *telemetry.Telemetry
logger logger.LoggerFactory
log logging.LeveledLogger
net transport.Net
ready, shutdown bool
}
// NewStunner creates a new STUNner deamon for the specified Options. Call Reconcile to reconcile
// the daemon for a new configuration. Object lifecycle is as follows: the daemon is "alive"
// (answers liveness probes if healthchecking is enabled) once the main object is successfully
// initialized, and "ready" after the first successful reconciliation (answers readiness probes if
// healthchecking is enabled). Calling program should catch SIGTERM signals and call Shutdown(),
// which will keep on serving connections but will fail readiness probes.
func NewStunner(options Options) *Stunner {
logger := logger.NewLoggerFactory(DefaultLogLevel)
if options.LogLevel != "" {
logger.SetLevel(options.LogLevel)
}
log := logger.NewLogger("stunner")
r := options.Resolver
if r == nil {
r = resolver.NewDnsResolver("dns-resolver", logger)
}
var vnet transport.Net
if options.Net == nil {
net, err := stdnet.NewNet() // defaults to native operation
if err != nil {
log.Error("Could not create vnet")
return nil
}
vnet = net
} else {
vnet = options.Net
log.Warn("Virtual net (vnet) is enabled")
}
udpThreadNum := 0
if options.UDPListenerThreadNum > 0 {
udpThreadNum = options.UDPListenerThreadNum
}
id := options.Name
if id == "" {
if h, err := os.Hostname(); err != nil {
id = DefaultInstanceId
} else {
id = fmt.Sprintf("default/stunnerd-%s", h)
}
}
s := &Stunner{
name: id,
version: stnrv1.ApiVersion,
logger: logger,
log: log,
suppressRollback: options.SuppressRollback,
dryRun: options.DryRun,
resolver: r,
udpThreadNum: udpThreadNum,
net: vnet,
}
s.adminManager = manager.NewManager("admin-manager",
object.NewAdminFactory(options.DryRun, s.NewReadinessHandler(), s.NewStatusHandler(), logger), logger)
s.authManager = manager.NewManager("auth-manager",
object.NewAuthFactory(logger), logger)
s.listenerManager = manager.NewManager("listener-manager",
object.NewListenerFactory(vnet, s.NewRealmHandler(), logger), logger)
s.clusterManager = manager.NewManager("cluster-manager",
object.NewClusterFactory(r, logger), logger)
telemetryCallbacks := telemetry.Callbacks{
GetAllocationCount: func() int64 { return s.GetActiveConnections() },
}
t, err := telemetry.New(telemetryCallbacks, s.dryRun, logger.NewLogger("metrics"))
if err != nil {
log.Errorf("Could not initialize metric provider: %s", err.Error())
return nil
}
s.telemetry = t
if !s.dryRun {
s.resolver.Start()
}
s.ready = true
return s
}
// GetId returns the id of the current stunnerd instance.
func (s *Stunner) GetId() string {
return s.name
}
// GetVersion returns the STUNner API version.
func (s *Stunner) GetVersion() string {
return s.version
}
// IsReady returns true if the STUNner instance is ready to serve allocation requests.
func (s *Stunner) IsReady() bool {
return s.ready
}
// Shutdown causes STUNner to fail the readiness check. Manwhile, it will keep on serving
// connections. This function should be called after the main program catches a SIGTERM.
func (s *Stunner) Shutdown() {
s.shutdown = true
s.ready = false
}
// GetAdmin returns the admin object underlying STUNner.
func (s *Stunner) GetAdmin() *object.Admin {
a, found := s.adminManager.Get(stnrv1.DefaultAdminName)
if !found {
panic("internal error: no Admin found")
}
return a.(*object.Admin)
}
// GetAuth returns the authenitation object underlying STUNner.
func (s *Stunner) GetAuth() *object.Auth {
a, found := s.authManager.Get(stnrv1.DefaultAuthName)
if !found {
panic("internal error: no Auth found")
}
return a.(*object.Auth)
}
// GetListener returns a STUNner listener or nil of no listener with the given name was found.
func (s *Stunner) GetListener(name string) *object.Listener {
l, found := s.listenerManager.Get(name)
if !found {
return nil
}
return l.(*object.Listener)
}
// GetCluster returns a STUNner cluster or nil if no cluster with the given name was found.
func (s *Stunner) GetCluster(name string) *object.Cluster {
l, found := s.clusterManager.Get(name)
if !found {
return nil
}
return l.(*object.Cluster)
}
// GetRealm returns the current STUN/TURN authentication realm.
func (s *Stunner) GetRealm() string {
auth := s.GetAuth()
if auth == nil {
return ""
}
return auth.Realm
}
// GetLogger returns the logger factory of the running daemon. Useful for creating a sub-logger.
func (s *Stunner) GetLogger() logging.LoggerFactory {
return s.logger
}
// SetLogLevel sets the loglevel.
func (s *Stunner) SetLogLevel(levelSpec string) {
s.logger.SetLevel(levelSpec)
}
// GetAllocations returns the number of active allocations summed over all listeners. It can be
// used to drain the server before closing.
func (s *Stunner) AllocationCount() int {
n := 0
listeners := s.listenerManager.Keys()
for _, name := range listeners {
l := s.GetListener(name)
if l.Server != nil {
n += l.Server.AllocationCount()
}
}
return n
}
// Status returns the status for the running STUNner instance.
func (s *Stunner) Status() stnrv1.Status {
status := stnrv1.StunnerStatus{ApiVersion: s.version}
if admin := s.GetAdmin(); admin != nil {
status.Admin = admin.Status().(*stnrv1.AdminStatus)
}
if auth := s.GetAuth(); auth != nil {
status.Auth = auth.Status().(*stnrv1.AuthStatus)
}
ls := s.listenerManager.Keys()
status.Listeners = make([]*stnrv1.ListenerStatus, len(ls))
for i, lName := range ls {
if l := s.GetListener(lName); l != nil {
status.Listeners[i] = l.Status().(*stnrv1.ListenerStatus)
}
}
cs := s.clusterManager.Keys()
status.Clusters = make([]*stnrv1.ClusterStatus, len(cs))
for i, cName := range cs {
if c := s.GetCluster(cName); c != nil {
status.Clusters[i] = c.Status().(*stnrv1.ClusterStatus)
}
}
status.AllocationCount = s.AllocationCount()
stat := "READY"
if !s.ready {
stat = "NOT-READY"
}
if s.shutdown {
stat = "TERMINATING"
}
status.Status = stat
return &status
}
// Close stops the STUNner daemon, cleans up any internal state, and closes all connections
// including the health-check and the metrics server listeners.
func (s *Stunner) Close() {
s.log.Info("closing STUNner")
// ignore restart-required errors
if len(s.adminManager.Keys()) > 0 {
_ = s.GetAdmin().Close()
}
if len(s.authManager.Keys()) > 0 {
_ = s.GetAuth().Close()
}
listeners := s.listenerManager.Keys()
for _, name := range listeners {
l := s.GetListener(name)
if err := l.Close(); err != nil && err != object.ErrRestartRequired {
s.log.Errorf("Error closing listener %q at adddress %s: %s",
l.Proto.String(), l.Addr, err.Error())
}
}
clusters := s.clusterManager.Keys()
for _, name := range clusters {
c := s.GetCluster(name)
if err := c.Close(); err != nil && err != object.ErrRestartRequired {
s.log.Errorf("Error closing cluster %q: %s", c.ObjectName(),
err.Error())
}
}
if err := s.telemetry.Close(); err != nil { // blocks until finished
s.log.Errorf("Could not shutdown metric provider cleanly: %s", err.Error())
}
s.resolver.Close()
}
// GetActiveConnections returns the number of active downstream (listener-side) TURN allocations.
func (s *Stunner) GetActiveConnections() int64 {
count := s.AllocationCount()
return int64(count)
}