-
Notifications
You must be signed in to change notification settings - Fork 9
/
backend.go
624 lines (547 loc) · 14.8 KB
/
backend.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
package cluster
import (
"context"
"errors"
"fmt"
"math"
"net/http"
"net/url"
"time"
sq "github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v4"
"github.com/rs/zerolog/log"
"github.com/b3scale/b3scale/pkg/bbb"
"github.com/b3scale/b3scale/pkg/store"
"github.com/b3scale/b3scale/pkg/templates"
)
// BackendStates: The state of the cluster backend node.
const (
BackendStateInit = "init"
BackendStateReady = "ready"
BackendStateError = "error"
BackendStateStopped = "stopped"
BackendStateDecommissioned = "decommissioned"
)
var (
// ErrRecordingNotFound indicates, that the recording
// state could not retrieved.
ErrRecordingNotFound = errors.New("recording could not be found")
)
// A Backend is a BigBlueButton instance in the cluster.
//
// It has a bbb.backend secret for request authentication,
// stored in the backend state. The state is shared across all
// instances.
type Backend struct {
state *store.BackendState
client *bbb.Client
}
// NewBackend creates a new backend instance with
// a fresh bbb client.
func NewBackend(state *store.BackendState) *Backend {
return &Backend{
client: bbb.NewClient(),
state: state,
}
}
// ID retrievs the backend id
func (b *Backend) ID() string {
return b.state.ID
}
// Host retrievs the backend host
func (b *Backend) Host() string {
if b.state.Backend == nil {
return ""
}
return b.state.Backend.Host
}
// Tags retrievs the backend's tags from it's state
func (b *Backend) Tags() []string {
return b.state.Settings.Tags
}
// HasTag checks for the presence of a tag
func (b *Backend) HasTag(tag string) bool {
if tag == "" {
return true // no tag is always present
}
for _, t := range b.Tags() {
if t == tag {
return true
}
}
return false
}
// HasTags checks for the presence of all tags
func (b *Backend) HasTags(tags []string) bool {
for _, required := range tags {
if !b.HasTag(required) {
return false
}
}
return true
}
// GetBackends retrievs all backends from the store,
// filterable with a query.
func GetBackends(
ctx context.Context,
q sq.SelectBuilder,
) ([]*Backend, error) {
conn := store.ConnectionFromContext(ctx)
tx, err := conn.Begin(ctx)
if err != nil {
return nil, err
}
states, err := store.GetBackendStates(ctx, tx, q)
if err != nil {
return nil, err
}
tx.Rollback(ctx)
// Make cluster backend from each state
backends := make([]*Backend, 0, len(states))
for _, s := range states {
backends = append(backends, NewBackend(s))
}
return backends, nil
}
// GetBackend retrievs a single backend by query criteria
func GetBackend(
ctx context.Context,
q sq.SelectBuilder,
) (*Backend, error) {
backends, err := GetBackends(ctx, q)
if err != nil {
return nil, err
}
if len(backends) == 0 {
return nil, nil
}
return backends[0], nil
}
// Stress calculates the current node load
func (b *Backend) Stress() float64 {
f := b.state.LoadFactor
// Assume a base load of n attendees. This should come from
// some a config or should be set per frontend.
attendeeBaseLoad := 15.0
attendeeLoad := math.Max(attendeeBaseLoad, float64(b.state.AttendeesCount))
return f * (float64(b.state.MeetingsCount) + attendeeLoad)
}
// refreshNodeState will fetch all meetings from the backend.
// The meetings are then processed in two passes:
// 1st pass: for each meeting from backend
// If the meeting is in our store there are two cases:
// - It is assigned to this backend, everything is well.
// Update meeting stats with info retrieved from the backend.
// - Otherwise: reassign this meeting to this backend.
//
// If the meeting is not in our state:
// - Ignore.
//
// 2nd pass: for each meeting assigned to backend in store:
// If the meeting is not present in the backend, remove meeting,
// from store
func (b *Backend) refreshNodeState(
ctx context.Context,
) error {
log.Debug().
Str("backend", b.state.Backend.Host).
Msg("processing backend meetings")
conn := store.ConnectionFromContext(ctx)
tx, err := conn.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
// Measure latency
t0 := time.Now()
req := bbb.GetMeetingsRequest(bbb.Params{}).WithBackend(b.state.Backend)
rep, err := b.client.Do(ctx, req)
if err != nil {
// The backend does not even respond, we mark this
// as an error, however our refresh was "successful".
errMsg := fmt.Sprintf("%s", err)
b.state.NodeState = "error"
b.state.LastError = &errMsg
if err := b.state.Save(ctx, tx); err != nil {
return err
}
return tx.Commit(ctx)
}
t1 := time.Now()
latency := t1.Sub(t0)
res := rep.(*bbb.GetMeetingsResponse)
if res.Returncode != "SUCCESS" {
// Update backend state
errMsg := fmt.Sprintf("%s: %s", res.MessageKey, res.Message)
b.state.LastError = &errMsg
b.state.NodeState = "error"
if err := b.state.Save(ctx, tx); err != nil {
return err
}
return tx.Commit(ctx)
}
// Update state
b.state.SyncedAt = time.Now().UTC()
b.state.LastError = nil
b.state.Latency = latency
if b.state.AdminState == "ready" {
b.state.NodeState = "ready"
}
if err := b.state.Save(ctx, tx); err != nil {
return err
}
if err := tx.Commit(ctx); err != nil {
log.Error().
Err(err).
Msg("could not save node state - commit error")
}
// Update meetings: 1st pass
backendMeetings := make([]string, 0, len(res.Meetings))
for _, meeting := range res.Meetings {
tx, err := conn.Begin(ctx)
if err != nil {
continue
}
defer tx.Rollback(ctx)
if err := b.state.CreateOrUpdateMeetingState(ctx, tx, meeting); err != nil {
tx.Rollback(ctx)
log.Error().
Err(err).
Str("meetingID", meeting.MeetingID).
Str("internalMeetingID", meeting.InternalMeetingID).
Msg("could not save meeting state during node refresh")
continue
}
if err := tx.Commit(ctx); err != nil {
log.Error().Err(err).Msg("commit error")
continue
}
backendMeetings = append(backendMeetings, meeting.InternalMeetingID)
}
// Cleanup meetings: 2nd pass
tx, err = conn.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
count, err := store.DeleteOrphanMeetings(ctx, tx, b.state.ID, backendMeetings)
if err != nil {
return err
}
if count > 0 {
log.Info().
Int("orphans", int(count)).
Str("backend", b.state.Backend.Host).
Msg("removed orphan meetings associated with backend")
}
if err := tx.Commit(ctx); err != nil {
return err
}
tx, err = conn.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if err := b.state.UpdateStatCounters(ctx, tx); err != nil {
return err
}
return tx.Commit(ctx)
}
// Meeting State Sync: loadMeetingState will make
// a request to the backend with a get meeting info request.
// This is done for a specific meeting e.g. to sync the
// attendees list - however - most of these things should
// already be handled throught the b3scalenoded on the
// backend instance.
func (b *Backend) refreshMeetingState(
ctx context.Context,
state *store.MeetingState,
) error {
conn := store.ConnectionFromContext(ctx)
req := bbb.GetMeetingInfoRequest(bbb.Params{
"meetingID": state.ID,
}).WithBackend(b.state.Backend)
rep, err := b.client.Do(ctx, req)
if err != nil {
return err
}
tx, err := conn.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
res := rep.(*bbb.GetMeetingInfoResponse)
if res.XMLResponse.Returncode != "SUCCESS" {
// The meeting could not be found
// For now, let's remove the meeting from our state
if err := store.DeleteMeetingStateByInternalID(
ctx, tx, state.InternalID); err != nil {
return err
}
return tx.Commit(ctx)
}
// Update meeting state
state.Meeting = res.Meeting
state.MarkSynced()
if err := state.Save(ctx, tx); err != nil {
return err
}
return tx.Commit(ctx)
}
// BBB API Implementation
func meetingStateFromRequest(
ctx context.Context,
tx pgx.Tx,
req *bbb.Request,
) (*store.MeetingState, error) {
meetingID, ok := req.Params.MeetingID()
if !ok {
return nil, fmt.Errorf("meetingID required")
}
meetingState, err := store.GetMeetingState(ctx, tx, store.Q().
Where("id = ?", meetingID))
return meetingState, err
}
// Create a new Meeting
func (b *Backend) Create(
ctx context.Context,
req *bbb.Request,
) (*bbb.CreateResponse, error) {
// Ensure content-type is application/xml, because some
// frontends do not set this at all and so no presentations
// are uploaded.
if req.Body != nil {
req.Request.Header.Set("content-type", "application/xml")
}
res, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
createRes := res.(*bbb.CreateResponse)
if createRes.Meeting == nil {
log.Error().
Msg("create returned without a meeting")
return nil, fmt.Errorf("meeting was not created on server")
}
conn := store.ConnectionFromContext(ctx)
tx, err := conn.Begin(ctx)
if err != nil {
return nil, err
}
meetingState, err := meetingStateFromRequest(ctx, tx, req)
if err != nil {
return nil, err
}
if meetingState == nil {
_, err = b.state.CreateMeetingState(ctx, tx, req.Frontend, createRes.Meeting)
if err != nil {
return nil, err
}
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return createRes, nil
}
// Join via redirect: The client will receive a
// redirect to the BBB backend and will join there directly.
func (b *Backend) Join(
ctx context.Context,
req *bbb.Request,
) (*bbb.JoinResponse, error) {
// Joining a meeting is a process entirely handled by the
// client. Because of a JSESSIONID which is used for preventing
// session stealing, just passing through the location response
// does not work. The JSESSIONID cookie is not associated with
// the backend domain and thus the sessionToken is not accepted
// as valid.
req = req.WithBackend(b.state.Backend)
url := req.URL()
body := templates.Redirect(url)
// Create custom join response
res := &bbb.JoinResponse{
XMLResponse: new(bbb.XMLResponse),
}
res.SetStatus(http.StatusFound)
res.SetRaw(body)
res.SetHeader(http.Header{
"content-type": []string{"text/html"},
"location": []string{req.URL()},
})
return res, nil
}
// JoinProxy makes a request on behalf of the client.
// A reverse proxy needs to pass all subsequent requests
// to the BBB backend.
func (b *Backend) JoinProxy(
ctx context.Context,
req *bbb.Request,
) (*bbb.JoinResponse, error) {
res, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
joinRes := res.(*bbb.JoinResponse)
if joinRes.Status() != 302 {
return joinRes, nil // Not the expected redirect
}
hostURL, _ := url.Parse(b.state.Backend.Host)
// Rewrite redirect to us, also keep the jsession cookie
// and add the backend host to the query for pinning
joinURL, err := url.Parse(joinRes.Header().Get("Location"))
if err != nil {
return nil, err
}
joinURL.Scheme = ""
joinURL.Host = ""
q := joinURL.Query()
q.Add("b3shost", hostURL.Host)
joinURL.RawQuery = q.Encode()
joinRes.Header().Set("Location", joinURL.String())
return joinRes, nil
}
// IsMeetingRunning returns the is meeting running state
func (b *Backend) IsMeetingRunning(
ctx context.Context,
req *bbb.Request,
) (*bbb.IsMeetingRunningResponse, error) {
res, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
isMeetingRunningRes := res.(*bbb.IsMeetingRunningResponse)
return isMeetingRunningRes, err
}
// End a meeting
func (b *Backend) End(
ctx context.Context,
req *bbb.Request,
) (*bbb.EndResponse, error) {
res, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
return res.(*bbb.EndResponse), err
}
// GetMeetingInfo gets the meeting details
func (b *Backend) GetMeetingInfo(
ctx context.Context,
req *bbb.Request,
) (*bbb.GetMeetingInfoResponse, error) {
rep, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
res := rep.(*bbb.GetMeetingInfoResponse)
if res.XMLResponse.Returncode != "SUCCESS" {
return res, nil
}
// We have successuflly retrieved an update from
// the server, so we should update our local state
tx, err := store.ConnectionFromContext(ctx).Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
meetingID, _ := req.Params.MeetingID()
mstate, err := store.GetMeetingState(ctx, tx, store.Q().
Where("id = ?", meetingID))
if err != nil {
// We only log the error, as this might fail
// without impacting the service
log.Error().
Err(err).
Str("backend", b.state.Backend.Host).
Msg("GetMeetingState")
} else {
if mstate == nil {
log.Warn().
Str("backend", b.state.Backend.Host).
Str("meetingID", meetingID).
Msg("GetMeetingInfo for unknown meeting")
} else {
// Update meeting state
mstate.Meeting = res.Meeting
mstate.SyncedAt = time.Now().UTC()
if err := mstate.Save(ctx, tx); err != nil {
log.Error().
Err(err).
Str("backend", b.state.Backend.Host).
Msg("Save")
}
}
}
// Persist changes
if err := tx.Commit(ctx); err != nil {
log.Error().
Err(err).
Msg("failed to commit meeting info")
}
return res, nil
}
// GetMeetings retrieves a list of meetings
func (b *Backend) GetMeetings(
ctx context.Context,
req *bbb.Request,
) (*bbb.GetMeetingsResponse, error) {
res, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
return res.(*bbb.GetMeetingsResponse), nil
}
// GetDefaultConfigXML retrieves the default config xml
func (b *Backend) GetDefaultConfigXML(
ctx context.Context,
req *bbb.Request,
) (*bbb.GetDefaultConfigXMLResponse, error) {
res, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
return res.(*bbb.GetDefaultConfigXMLResponse), nil
}
// SetConfigXML sets the? config xml
func (b *Backend) SetConfigXML(
ctx context.Context,
req *bbb.Request,
) (*bbb.SetConfigXMLResponse, error) {
res, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
return res.(*bbb.SetConfigXMLResponse), nil
}
// PutRecordingTextTrack adds a text track
func (b *Backend) PutRecordingTextTrack(
ctx context.Context,
req *bbb.Request,
) (*bbb.PutRecordingTextTrackResponse, error) {
res, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
return res.(*bbb.PutRecordingTextTrackResponse), nil
}
// GetRecordingTextTracks retrieves the text tracks from a recording
func (b *Backend) GetRecordingTextTracks(
ctx context.Context,
req *bbb.Request,
) (*bbb.GetRecordingTextTracksResponse, error) {
res, err := b.client.Do(ctx, req.WithBackend(b.state.Backend))
if err != nil {
return nil, err
}
return res.(*bbb.GetRecordingTextTracksResponse), nil
}
// String stringifies the Backend
func (b *Backend) String() string {
if b.state != nil {
host := "unknown host"
if b.state.Backend != nil {
host = b.state.Backend.Host
}
return fmt.Sprintf("<Backend id='%v' host='%v'>", b.state.ID, host)
}
return "<Backend>"
}