-
-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathservice.go
1761 lines (1540 loc) · 50.9 KB
/
service.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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2022-2024 Winlin
//
// SPDX-License-Identifier: MIT
package main
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"github.com/joho/godotenv"
"io"
"io/ioutil"
"net/http"
"path"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/ossrs/go-oryx-lib/errors"
ohttp "github.com/ossrs/go-oryx-lib/http"
"github.com/ossrs/go-oryx-lib/logger"
// Use v8 because we use Go 1.16+, while v9 requires Go 1.18+
"github.com/go-redis/redis/v8"
)
// HttpService is a HTTP server for platform.
type HttpService interface {
Close() error
Run(ctx context.Context) error
}
func NewHTTPService() HttpService {
return &httpService{}
}
type httpService struct {
servers []*http.Server
}
func (v *httpService) Close() error {
servers := v.servers
v.servers = nil
var wg sync.WaitGroup
defer wg.Wait()
for index, server := range servers {
wg.Add(1)
go func(index int, server *http.Server) {
defer wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
logger.Tf(ctx, "service shutting down server #%v/%v: %v", index, len(v.servers), server.Addr)
err := server.Shutdown(ctx)
logger.Tf(ctx, "service shutdown ok, server #%v/%v: %v, err=%v", index, len(v.servers), server.Addr, err)
}(index, server)
}
return nil
}
func (v *httpService) Run(ctx context.Context) error {
var wg sync.WaitGroup
defer wg.Wait()
// For debugging server, listen at 127.0.0.1:22022
go func() {
dh := http.NewServeMux()
handleDebuggingGoroutines(context.Background(), dh)
server := &http.Server{Addr: "127.0.0.1:22022", Handler: dh}
server.ListenAndServe()
}()
ctx, cancel := context.WithCancel(ctx)
handler := http.NewServeMux()
if true {
serviceHandler := http.NewServeMux()
if err := handleHTTPService(ctx, serviceHandler); err != nil {
return errors.Wrapf(err, "handle service")
}
handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Set common header.
ohttp.SetHeader(w)
// Always allow CORS.
httpAllowCORS(w, r)
// Allow OPTIONS for CORS.
if r.Method == http.MethodOptions {
w.Write(nil)
return
}
// Handle by service handler.
serviceHandler.ServeHTTP(w, r)
})
}
var r0 error
if true {
addr := envPlatformListen()
if !strings.HasPrefix(addr, ":") {
addr = fmt.Sprintf(":%v", addr)
}
logger.Tf(ctx, "HTTP listen at %v", addr)
server := &http.Server{Addr: addr, Handler: handler}
v.servers = append(v.servers, server)
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
logger.Tf(ctx, "shutting down HTTP server, addr=%v", addr)
v.Close()
}()
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
if err := server.ListenAndServe(); err != nil && ctx.Err() != context.Canceled {
r0 = errors.Wrapf(err, "listen %v", addr)
}
logger.Tf(ctx, "HTTP server is done, addr=%v", addr)
}()
}
var r1 error
if true {
addr := envMgmtListen()
if !strings.HasPrefix(addr, ":") {
addr = fmt.Sprintf(":%v", addr)
}
logger.Tf(ctx, "HTTP listen at %v", addr)
server := &http.Server{Addr: addr, Handler: handler}
v.servers = append(v.servers, server)
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
logger.Tf(ctx, "shutting down HTTP server, addr=%v", addr)
v.Close()
}()
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
if err := server.ListenAndServe(); err != nil && ctx.Err() != context.Canceled {
r1 = errors.Wrapf(err, "listen %v", addr)
}
logger.Tf(ctx, "HTTP server is done, addr=%v", addr)
}()
}
var r2 error
if true {
addr := envHttpListen()
if !strings.HasPrefix(addr, ":") {
addr = fmt.Sprintf(":%v", addr)
}
logger.Tf(ctx, "HTTPS listen at %v", addr)
server := &http.Server{
Addr: addr,
Handler: handler,
TLSConfig: &tls.Config{
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
return certManager.httpsCertificate, nil
},
},
}
v.servers = append(v.servers, server)
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
logger.Tf(ctx, "shutting down HTTPS server, addr=%v", addr)
v.Close()
}()
wg.Add(1)
go func() {
defer wg.Done()
defer cancel()
if err := server.ListenAndServeTLS("", ""); err != nil && ctx.Err() != context.Canceled {
r2 = errors.Wrapf(err, "listen %v", addr)
}
logger.Tf(ctx, "HTTPS server is done, addr=%v", addr)
}()
}
wg.Wait()
for _, r := range []error{r0, r1, r2} {
if r != nil {
return r
}
}
return nil
}
func handleHTTPService(ctx context.Context, handler *http.ServeMux) error {
ohttp.Server = fmt.Sprintf("Oryx/%v", version)
if err := callbackWorker.Handle(ctx, handler); err != nil {
return errors.Wrapf(err, "handle callback")
}
if err := transcriptWorker.Handle(ctx, handler); err != nil {
return errors.Wrapf(err, "handle transcript")
}
if err := ocrWorker.Handle(ctx, handler); err != nil {
return errors.Wrapf(err, "handle ocr")
}
if err := transcodeWorker.Handle(ctx, handler); err != nil {
return errors.Wrapf(err, "handle transcode")
}
if err := forwardWorker.Handle(ctx, handler); err != nil {
return errors.Wrapf(err, "handle forward")
}
if err := vLiveWorker.Handle(ctx, handler); err != nil {
return errors.Wrapf(err, "handle vLive")
}
if err := cameraWorker.Handle(ctx, handler); err != nil {
return errors.Wrapf(err, "handle IP camera")
}
if err := handleHooksService(ctx, handler); err != nil {
return errors.Wrapf(err, "handle hooks")
}
if err := handleLiveRoomService(ctx, handler); err != nil {
return errors.Wrapf(err, "handle live room")
}
if err := handleDubbingService(ctx, handler); err != nil {
return errors.Wrapf(err, "handle dubbing")
}
if err := handleAITalkService(ctx, handler); err != nil {
return errors.Wrapf(err, "handle AI talk")
}
var ep string
handleHostVersions(ctx, handler)
handleMgmtVersions(ctx, handler)
handleFFmpegVersions(ctx, handler)
handleMgmtInit(ctx, handler)
handleMgmtCheck(ctx, handler)
handleMgmtEnvs(ctx, handler)
handleMgmtToken(ctx, handler)
handleMgmtLogin(ctx, handler)
handleMgmtStatus(ctx, handler)
handleMgmtBilibili(ctx, handler)
handleMgmtLimitsQuery(ctx, handler)
handleMgmtLimitsUpdate(ctx, handler)
handleMgmtOpenAIQuery(ctx, handler)
handleMgmtOpenAIUpdate(ctx, handler)
handleMgmtBeianQuery(ctx, handler)
handleMgmtSecretQuery(ctx, handler)
handleMgmtBeianUpdate(ctx, handler)
handleMgmtNginxHlsUpdate(ctx, handler)
handleMgmtNginxHlsQuery(ctx, handler)
handleMgmtHlsLowLatencyUpdate(ctx, handler)
handleMgmtHlsLowLatencyQuery(ctx, handler)
handleMgmtAutoSelfSignedCertificate(ctx, handler)
handleMgmtSsl(ctx, handler)
handleMgmtLetsEncrypt(ctx, handler)
handleMgmtCertQuery(ctx, handler)
handleMgmtStreamsQuery(ctx, handler)
handleMgmtStreamsKickoff(ctx, handler)
handleMgmtUI(ctx, handler)
proxy2023, err := httpCreateProxy("http://127.0.0.1:2023")
if err != nil {
return err
}
proxy1985, err := httpCreateProxy("http://127.0.0.1:1985")
if err != nil {
return err
}
proxyWhxp, err := httpCreateProxy("http://127.0.0.1:1985")
if err != nil {
return err
}
proxy8080, err := httpCreateProxy("http://127.0.0.1:8080")
if err != nil {
return err
}
platformFileServer := http.FileServer(http.Dir(path.Join(conf.Pwd, "containers/www")))
wellKnownFileServer := http.FileServer(http.Dir(path.Join(conf.Pwd, "containers/data")))
hlsFileServer := http.FileServer(http.Dir(path.Join(conf.Pwd, "containers/objs/nginx/html")))
ep = "/"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
// For version management.
if strings.HasPrefix(r.URL.Path, "/terraform/v1/releases") {
logger.Tf(ctx, "Proxy %v to backend 2023", r.URL.Path)
proxy2023.ServeHTTP(w, r)
return
}
// For HTTPS management.
if strings.HasPrefix(r.URL.Path, "/.well-known/") {
w.Header().Set("Cache-Control", "no-cache, max-age=0")
wellKnownFileServer.ServeHTTP(w, r)
return
}
// We directly serve the static files, because we overwrite the www for DVR.
if strings.HasPrefix(r.URL.Path, "/console/") || strings.HasPrefix(r.URL.Path, "/players/") ||
strings.HasPrefix(r.URL.Path, "/tools/") {
if r.URL.Path != "/tools/player.html" && r.URL.Path != "/tools/xgplayer.html" {
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%v", 30*24*3600))
}
platformFileServer.ServeHTTP(w, r)
return
}
// Proxy to SRS RTC API, by /rtc/ prefix.
if strings.HasPrefix(r.URL.Path, "/rtc/") {
q := r.URL.Query()
if eip := q.Get("eip"); eip != "" {
logger.Tf(ctx, "Proxy %v to backend 1985, eip=%v, query is %v",
r.URL.Path, eip, r.URL.RawQuery)
} else {
// Allow test to mock and overwrite the host.
host := r.Header.Get("X-Real-Host")
if host == "" {
host = r.Host
}
// Resolve the host to ip.
starttime := time.Now()
if ip, err := candidateWorker.Resolve(host); err != nil {
logger.Ef(ctx, "Proxy %v to backend 1985, resolve %v/%v failed, cost=%v, err is %v",
r.URL.Path, r.Host, host, time.Now().Sub(starttime), err)
ohttp.WriteError(ctx, w, r, err)
return
} else if ip != nil {
eip = ip.String()
r.URL.RawQuery += fmt.Sprintf("&eip=%v", eip)
logger.Tf(ctx, "Proxy %v to backend 1985, host=%v/%v, resolved ip=%v, cost=%v, query is %v",
r.URL.Path, r.Host, host, eip, time.Now().Sub(starttime), r.URL.RawQuery)
}
}
proxyWhxp.ServeHTTP(&whxpResponseModifier{w}, r)
return
}
// Use versions API as health check API, no auth.
if r.URL.Path == "/api/v1/versions" {
logger.Tf(ctx, "Proxy %v to backend 1985", r.URL.Path)
proxy1985.ServeHTTP(w, r)
return
}
// Proxy to SRS HTTP API, for console, by /api/ prefix.
if strings.HasPrefix(r.URL.Path, "/api/") {
token := r.URL.Query().Get("token")
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
w.WriteHeader(http.StatusUnauthorized)
ohttp.WriteError(ctx, w, r, err)
return
}
logger.Tf(ctx, "Proxy %v to backend 1985", r.URL.Path)
proxy1985.ServeHTTP(w, r)
return
}
// Always directly serve the HLS ts files.
if fastCache.HLSHighPerformance && strings.HasSuffix(r.URL.Path, ".m3u8") {
var m3u8ExpireInSeconds int = 10
if fastCache.HLSLowLatency {
m3u8ExpireInSeconds = 1 // Note that we use smaller expire time that fragment duration.
}
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%v", m3u8ExpireInSeconds))
hlsFileServer.ServeHTTP(w, r)
return
}
if strings.HasSuffix(r.URL.Path, ".ts") {
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%v", 600))
hlsFileServer.ServeHTTP(w, r)
return
}
if strings.HasSuffix(r.URL.Path, ".flv") || strings.HasSuffix(r.URL.Path, ".m3u8") ||
strings.HasSuffix(r.URL.Path, ".ts") || strings.HasSuffix(r.URL.Path, ".aac") ||
strings.HasSuffix(r.URL.Path, ".mp3") {
logger.Tf(ctx, "Proxy %v to backend 8080", r.URL.Path)
proxy8080.ServeHTTP(w, r)
return
}
http.Redirect(w, r, "/mgmt", http.StatusFound)
})
return nil
}
func handleDebuggingGoroutines(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/debug/goroutines"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
buf := make([]byte, 1<<16)
stacklen := runtime.Stack(buf, true)
fmt.Fprintf(w, "%s", buf[:stacklen])
})
}
func handleHostVersions(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/host/versions"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
ohttp.WriteData(ctx, w, r, &struct {
Version string `json:"version"`
}{
Version: strings.TrimPrefix(version, "v"),
})
})
}
func handleMgmtVersions(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/mgmt/versions"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
ohttp.WriteData(ctx, w, r, &struct {
Version string `json:"version"`
}{
Version: strings.TrimPrefix(version, "v"),
})
})
}
func handleFFmpegVersions(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/ffmpeg/versions"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
ohttp.WriteData(ctx, w, r, &struct {
Version string `json:"version"`
}{
Version: strings.TrimPrefix(version, "v"),
})
})
}
func handleMgmtInit(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/mgmt/init"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return errors.Wrapf(err, "read body")
}
var password string
if len(b) > 0 {
if err := json.Unmarshal(b, &struct {
Password *string `json:"password"`
}{
Password: &password,
}); err != nil {
return errors.Wrapf(err, "json unmarshal %v", string(b))
}
}
// If no password, query the system init status.
if password == "" {
ohttp.WriteData(ctx, w, r, &struct {
Init bool `json:"init"`
}{
Init: envMgmtPassword() != "",
})
return nil
}
// If already initialized, never set it again.
if envMgmtPassword() != "" {
return errors.New("already initialized")
}
// Initialize the system password, save to env.
envFile := path.Join(conf.Pwd, "containers/data/config/.env")
if envs, err := godotenv.Read(envFile); err != nil {
return errors.Wrapf(err, "load envs from %v", envFile)
} else {
envs["MGMT_PASSWORD"] = password
if err := godotenv.Write(envs, envFile); err != nil {
return errors.Wrapf(err, "write %v", envFile)
}
}
logger.Tf(ctx, "init mgmt password %vB ok, file=%v", len(password), envFile)
// Refresh the local token.
if err := godotenv.Overload(envFile); err != nil {
return errors.Wrapf(err, "load %v", envFile)
}
apiSecret := envApiSecret()
expireAt, createAt, token, err := createToken(ctx, envApiSecret())
if err != nil {
return errors.Wrapf(err, "build token")
}
ohttp.WriteData(ctx, w, r, &struct {
Token string `json:"token"`
CreateAt string `json:"createAt"`
ExpireAt string `json:"expireAt"`
// Allow user to directly use Bearer token.
Bearer string `json:"bearer"`
}{
Token: token, CreateAt: createAt.Format(time.RFC3339), ExpireAt: expireAt.Format(time.RFC3339),
Bearer: apiSecret,
})
logger.Tf(ctx, "init password ok, create=%v, expire=%v, password=%vB", createAt, expireAt, len(password))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
}
func handleMgmtCheck(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/mgmt/check"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
// Check whether redis is ok.
if r0, err := rdb.HGet(ctx, SRS_AUTH_SECRET, "pubSecret").Result(); err != nil && err != redis.Nil {
return errors.Wrapf(err, "hget %v pubSecret", SRS_AUTH_SECRET)
} else if r1, err := rdb.HLen(ctx, SRS_FIRST_BOOT).Result(); err != nil && err != redis.Nil {
return errors.Wrapf(err, "get %v", SRS_FIRST_BOOT)
} else if r2, err := rdb.HLen(ctx, SRS_TENCENT_LH).Result(); err != nil && err != redis.Nil {
return errors.Wrapf(err, "get %v", SRS_TENCENT_LH)
} else if r0 == "" || r1 <= 0 || r2 <= 0 {
return errors.New("Redis is not ready")
} else {
logger.Tf(ctx, "system check ok, r0=%v, r1=%v, r2=%v", r0, r1, r2)
}
ohttp.WriteData(ctx, w, r, &struct {
Upgrading bool `json:"upgrading"`
}{
Upgrading: false,
})
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
}
func handleMgmtEnvs(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/mgmt/envs"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var locale string
if err := ParseBody(ctx, r.Body, &struct {
Locale *string `json:"locale"`
}{
Locale: &locale,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
// Filter the locale.
if locale != "en" && locale != "zh" {
locale = "un"
}
if err := rdb.Set(ctx, SRS_LOCALE, locale, 0).Err(); err != nil && err != redis.Nil {
return errors.Wrapf(err, "set %v %v", SRS_LOCALE, locale)
}
var forwardLimit int
if envForwardLimit() != "" {
if iv, err := strconv.ParseInt(envForwardLimit(), 10, 64); err != nil {
return errors.Wrapf(err, "parse env forward limit %v", envForwardLimit())
} else {
forwardLimit = int(iv)
}
}
var vLiveLimit int
if envVLiveLimit() != "" {
if iv, err := strconv.ParseInt(envVLiveLimit(), 10, 64); err != nil {
return errors.Wrapf(err, "parse env virtual live limit %v", envVLiveLimit())
} else {
vLiveLimit = int(iv)
}
}
var cameraLimit int
if envCameraLimit() != "" {
if iv, err := strconv.ParseInt(envCameraLimit(), 10, 64); err != nil {
return errors.Wrapf(err, "parse env camera limit %v", envCameraLimit())
} else {
cameraLimit = int(iv)
}
}
platformDocker := envPlatformDocker() != "off"
candidate := envCandidate() != ""
ohttp.WriteData(ctx, w, r, &struct {
// Whether mgmt run in docker.
MgmtDocker bool `json:"mgmtDocker"`
// Whether platform run in docker.
PlatformDocker bool `json:"platformDocker"`
// Whether set the env CANDIDATE for WebRTC.
Candidate bool `json:"candidate"`
// The exposed RTMP port.
RTMPPort string `json:"rtmpPort"`
// The exposed HTTP port.
HTTPPort string `json:"httpPort"`
// The exposed SRT port.
SRTPort string `json:"srtPort"`
// The exposed RTC port.
RTCPort string `json:"rtcPort"`
// The limit of the number of forwarding streams.
ForwardLimit int `json:"forwardLimit"`
// The limit of the number of vLive streams.
VLiveLimit int `json:"vLiveLimit"`
// The limit of the number of IP camera streams.
CameraLimit int `json:"cameraLimit"`
}{
// Whether in docker.
MgmtDocker: true,
// Whether platform in docker.
PlatformDocker: platformDocker,
// The candidate IP for WebRTC.
Candidate: candidate,
// The export port for RTMP.
RTMPPort: envRtmpPort(),
// The export port for HTTP.
HTTPPort: envHttpPort(),
// The export port for SRT.
SRTPort: envSrtListen(),
// The export port for WebRTC.
RTCPort: envRtcListen(),
// The limit of the number of forwarding streams.
ForwardLimit: forwardLimit,
// The limit of the number of vLive streams.
VLiveLimit: vLiveLimit,
// The limit of the number of IP camera streams.
CameraLimit: cameraLimit,
})
logger.Tf(ctx, "mgmt envs ok, locale=%v, platformDocker=%v, candidate=%v, rtmpPort=%v, httpPort=%v, srtPort=%v, rtcPort=%v, forwardLimit=%v, vLiveLimit=%v, cameraLimit=%v",
locale, platformDocker, candidate, envRtmpPort(), envHttpPort(),
envSrtListen(), envRtcListen(), forwardLimit, vLiveLimit, cameraLimit,
)
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
}
func handleMgmtToken(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/mgmt/token"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
}{
Token: &token,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
expireAt, createAt, token, err := createToken(ctx, envApiSecret())
if err != nil {
return errors.Wrapf(err, "build token")
}
ohttp.WriteData(ctx, w, r, &struct {
Token string `json:"token"`
CreateAt string `json:"createAt"`
ExpireAt string `json:"expireAt"`
}{
Token: token, CreateAt: createAt.Format(time.RFC3339), ExpireAt: expireAt.Format(time.RFC3339),
})
logger.Tf(ctx, "login by token ok, create=%v, expire=%v, token=%vB", createAt, expireAt, len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
}
func handleMgmtLogin(ctx context.Context, handler *http.ServeMux) {
var loginLock sync.Mutex
ep := "/terraform/v1/mgmt/login"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
if !loginLock.TryLock() {
return errors.New("login is running, try later")
}
defer loginLock.Unlock()
if envMgmtPassword() == "" {
return errors.New("not init")
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return errors.Wrapf(err, "read body")
}
var password string
if err := json.Unmarshal(b, &struct {
Password *string `json:"password"`
}{
Password: &password,
}); err != nil {
return errors.Wrapf(err, "json unmarshal %v", string(b))
}
if password == "" {
return errors.New("no password")
}
if password != envMgmtPassword() {
wait := time.Duration(10) * time.Second
logger.Wf(ctx, "Invalid password, wait for %v", wait)
select {
case <-time.After(wait):
case <-ctx.Done():
}
return errors.Errorf("invalid password, wait %v", wait)
}
apiSecret := envApiSecret()
expireAt, createAt, token, err := createToken(ctx, apiSecret)
if err != nil {
return errors.Wrapf(err, "build token")
}
ohttp.WriteData(ctx, w, r, &struct {
Token string `json:"token"`
CreateAt string `json:"createAt"`
ExpireAt string `json:"expireAt"`
// Allow user to directly use Bearer token.
Bearer string `json:"bearer"`
}{
Token: token, CreateAt: createAt.Format(time.RFC3339), ExpireAt: expireAt.Format(time.RFC3339),
Bearer: apiSecret,
})
logger.Tf(ctx, "login by password ok, create=%v, expire=%v, token=%vB", createAt, expireAt, len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
}
func handleMgmtStatus(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/mgmt/status"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
}{
Token: &token,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
upgrading, err := rdb.HGet(ctx, SRS_UPGRADING, "upgrading").Result()
if err != nil && err != redis.Nil {
return errors.Wrapf(err, "hget %v upgrading", SRS_UPGRADING)
}
ohttp.WriteData(ctx, w, r, &struct {
Version string `json:"version"`
Releases Versions `json:"releases"`
Upgrading bool `json:"upgrading"`
Strategy string `json:"strategy"`
}{
Version: conf.Versions.Version,
Releases: conf.Versions,
Upgrading: upgrading == "1",
Strategy: "manual",
})
logger.Tf(ctx, "status ok, versions=%v, upgrading=%v, token=%vB", conf.Versions.String(), upgrading, len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
}
func handleMgmtBilibili(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/mgmt/bilibili"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token, bvid string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
BVID *string `json:"bvid"`
}{
Token: &token, BVID: &bvid,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
if bvid == "" {
return errors.New("no bvid")
}
bilibiliObj := struct {
Update string `json:"update"`
Res map[string]interface{} `json:"res"`
}{}
if bilibili, err := rdb.HGet(ctx, SRS_CACHE_BILIBILI, bvid).Result(); err != nil && err != redis.Nil {
return errors.Wrapf(err, "hget %v %v", SRS_CACHE_BILIBILI, bvid)
} else if bilibili != "" {
if err := json.Unmarshal([]byte(bilibili), &bilibiliObj); err != nil {
return errors.Wrapf(err, "json unmarshal %v", bilibili)
}
}
var cacheExpired bool
if bilibiliObj.Update != "" {
duration := time.Duration(24*3600) * time.Second
if envNodeEnv() == "development" {
duration = time.Duration(300) * time.Second
}
updateAt, err := time.Parse(time.RFC3339, bilibiliObj.Update)
if err != nil {
cacheExpired = true
}
if updateAt.Add(duration).Before(time.Now()) {
cacheExpired = true
}
}
if bilibiliObj.Res == nil || cacheExpired {
bilibiliObj.Update = time.Now().Format(time.RFC3339)
bilibiliURL := fmt.Sprintf("https://api.bilibili.com/x/web-interface/view?bvid=%v", bvid)
res, err := http.Get(bilibiliURL)
if err != nil {
return errors.Wrapf(err, "get %v", bilibiliURL)
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return errors.Wrapf(err, "read %v", bilibiliURL)
}
if err := json.Unmarshal(b, &struct {
Code int `json:"code"`
Message string `json:"message"`
TTL int `json:"ttl"`
Data *map[string]interface{} `json:"data"`
}{
Data: &bilibiliObj.Res,
}); err != nil {
return errors.Wrapf(err, "json unmarshal %v", string(b))
}
}
if b, err := json.Marshal(bilibiliObj); err != nil {
return errors.Wrapf(err, "json marshal %v", bilibiliObj)
} else if err = rdb.HSet(ctx, SRS_CACHE_BILIBILI, bvid, string(b)).Err(); err != nil {
return errors.Wrapf(err, "update redis for %v", string(b))
}
ohttp.WriteData(ctx, w, r, bilibiliObj.Res)
logger.Tf(ctx, "bilibili cache bvid=%v, update=%v, token=%vB", bvid, bilibiliObj.Update, len(token))
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
}
func handleMgmtOpenAIQuery(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/mgmt/openai/query"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
}{
Token: &token,
}); err != nil {
return errors.Wrapf(err, "parse body")
}
apiSecret := envApiSecret()
if err := Authenticate(ctx, apiSecret, token, r.Header); err != nil {
return errors.Wrapf(err, "authenticate")
}
aiSecretKey, err := rdb.HGet(ctx, SRS_SYS_OPENAI, "key").Result()
if err != nil && err != redis.Nil {
return errors.Wrapf(err, "hget %v key", SRS_SYS_OPENAI)
}
aiBaseURL, err := rdb.HGet(ctx, SRS_SYS_OPENAI, "url").Result()
if err != nil && err != redis.Nil {
return errors.Wrapf(err, "hget %v url", SRS_SYS_OPENAI)
}
aiOrganization, err := rdb.HGet(ctx, SRS_SYS_OPENAI, "org").Result()
if err != nil && err != redis.Nil {
return errors.Wrapf(err, "hget %v org", SRS_SYS_OPENAI)
}
ohttp.WriteData(ctx, w, r, &struct {
// The AI secret key.
AISecretKey string `json:"aiSecretKey"`
// The AI base url.
AIBaseURL string `json:"aiBaseURL"`
// The AI organization.
AIOrganization string `json:"aiOrganization"`
}{
AISecretKey: aiSecretKey, AIBaseURL: aiBaseURL, AIOrganization: aiOrganization,
})
logger.Tf(ctx, "settings: query openai ok")
return nil
}(); err != nil {
ohttp.WriteError(ctx, w, r, err)
}
})
}
func handleMgmtOpenAIUpdate(ctx context.Context, handler *http.ServeMux) {
ep := "/terraform/v1/mgmt/openai/update"
logger.Tf(ctx, "Handle %v", ep)
handler.HandleFunc(ep, func(w http.ResponseWriter, r *http.Request) {
if err := func() error {
var token string
var aiSecretKey, aiBaseURL, aiOrganization string
if err := ParseBody(ctx, r.Body, &struct {
Token *string `json:"token"`
AISecretKey *string `json:"aiSecretKey"`
AIBaseURL *string `json:"aiBaseURL"`
AIOrganization *string `json:"aiOrganization"`
}{
Token: &token, AISecretKey: &aiSecretKey, AIBaseURL: &aiBaseURL,
AIOrganization: &aiOrganization,
}); err != nil {