2
0

srs.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. // Copyright (c) 2024 Winlin
  2. //
  3. // SPDX-License-Identifier: MIT
  4. package main
  5. import (
  6. "context"
  7. "encoding/json"
  8. "fmt"
  9. "math/rand"
  10. "os"
  11. "strconv"
  12. "strings"
  13. "time"
  14. // Use v8 because we use Go 1.16+, while v9 requires Go 1.18+
  15. "github.com/go-redis/redis/v8"
  16. "srs-proxy/errors"
  17. "srs-proxy/logger"
  18. "srs-proxy/sync"
  19. )
  20. // If server heartbeat in this duration, it's alive.
  21. const srsServerAliveDuration = 300 * time.Second
  22. // If HLS streaming update in this duration, it's alive.
  23. const srsHLSAliveDuration = 120 * time.Second
  24. // If WebRTC streaming update in this duration, it's alive.
  25. const srsRTCAliveDuration = 120 * time.Second
  26. type SRSServer struct {
  27. // The server IP.
  28. IP string `json:"ip,omitempty"`
  29. // The server device ID, configured by user.
  30. DeviceID string `json:"device_id,omitempty"`
  31. // The server id of SRS, store in file, may not change, mandatory.
  32. ServerID string `json:"server_id,omitempty"`
  33. // The service id of SRS, always change when restarted, mandatory.
  34. ServiceID string `json:"service_id,omitempty"`
  35. // The process id of SRS, always change when restarted, mandatory.
  36. PID string `json:"pid,omitempty"`
  37. // The RTMP listen endpoints.
  38. RTMP []string `json:"rtmp,omitempty"`
  39. // The HTTP Stream listen endpoints.
  40. HTTP []string `json:"http,omitempty"`
  41. // The HTTP API listen endpoints.
  42. API []string `json:"api,omitempty"`
  43. // The SRT server listen endpoints.
  44. SRT []string `json:"srt,omitempty"`
  45. // The RTC server listen endpoints.
  46. RTC []string `json:"rtc,omitempty"`
  47. // Last update time.
  48. UpdatedAt time.Time `json:"update_at,omitempty"`
  49. }
  50. func (v *SRSServer) ID() string {
  51. return fmt.Sprintf("%v-%v-%v", v.ServerID, v.ServiceID, v.PID)
  52. }
  53. func (v *SRSServer) String() string {
  54. return fmt.Sprintf("%v", v)
  55. }
  56. func (v *SRSServer) Format(f fmt.State, c rune) {
  57. switch c {
  58. case 'v', 's':
  59. if f.Flag('+') {
  60. var sb strings.Builder
  61. sb.WriteString(fmt.Sprintf("pid=%v, server=%v, service=%v", v.PID, v.ServerID, v.ServiceID))
  62. if v.DeviceID != "" {
  63. sb.WriteString(fmt.Sprintf(", device=%v", v.DeviceID))
  64. }
  65. if len(v.RTMP) > 0 {
  66. sb.WriteString(fmt.Sprintf(", rtmp=[%v]", strings.Join(v.RTMP, ",")))
  67. }
  68. if len(v.HTTP) > 0 {
  69. sb.WriteString(fmt.Sprintf(", http=[%v]", strings.Join(v.HTTP, ",")))
  70. }
  71. if len(v.API) > 0 {
  72. sb.WriteString(fmt.Sprintf(", api=[%v]", strings.Join(v.API, ",")))
  73. }
  74. if len(v.SRT) > 0 {
  75. sb.WriteString(fmt.Sprintf(", srt=[%v]", strings.Join(v.SRT, ",")))
  76. }
  77. if len(v.RTC) > 0 {
  78. sb.WriteString(fmt.Sprintf(", rtc=[%v]", strings.Join(v.RTC, ",")))
  79. }
  80. sb.WriteString(fmt.Sprintf(", update=%v", v.UpdatedAt.Format("2006-01-02 15:04:05.999")))
  81. fmt.Fprintf(f, "SRS ip=%v, id=%v, %v", v.IP, v.ID(), sb.String())
  82. } else {
  83. fmt.Fprintf(f, "SRS ip=%v, id=%v", v.IP, v.ID())
  84. }
  85. default:
  86. fmt.Fprintf(f, "%v, fmt=%%%c", v, c)
  87. }
  88. }
  89. func NewSRSServer(opts ...func(*SRSServer)) *SRSServer {
  90. v := &SRSServer{}
  91. for _, opt := range opts {
  92. opt(v)
  93. }
  94. return v
  95. }
  96. // NewDefaultSRSForDebugging initialize the default SRS media server, for debugging only.
  97. func NewDefaultSRSForDebugging() (*SRSServer, error) {
  98. if envDefaultBackendEnabled() != "on" {
  99. return nil, nil
  100. }
  101. if envDefaultBackendIP() == "" {
  102. return nil, fmt.Errorf("empty default backend ip")
  103. }
  104. if envDefaultBackendRTMP() == "" {
  105. return nil, fmt.Errorf("empty default backend rtmp")
  106. }
  107. server := NewSRSServer(func(srs *SRSServer) {
  108. srs.IP = envDefaultBackendIP()
  109. srs.RTMP = []string{envDefaultBackendRTMP()}
  110. srs.ServerID = fmt.Sprintf("default-%v", logger.GenerateContextID())
  111. srs.ServiceID = logger.GenerateContextID()
  112. srs.PID = fmt.Sprintf("%v", os.Getpid())
  113. srs.UpdatedAt = time.Now()
  114. })
  115. if envDefaultBackendHttp() != "" {
  116. server.HTTP = []string{envDefaultBackendHttp()}
  117. }
  118. if envDefaultBackendAPI() != "" {
  119. server.API = []string{envDefaultBackendAPI()}
  120. }
  121. if envDefaultBackendRTC() != "" {
  122. server.RTC = []string{envDefaultBackendRTC()}
  123. }
  124. if envDefaultBackendSRT() != "" {
  125. server.SRT = []string{envDefaultBackendSRT()}
  126. }
  127. return server, nil
  128. }
  129. // SRSLoadBalancer is the interface to load balance the SRS servers.
  130. type SRSLoadBalancer interface {
  131. // Initialize the load balancer.
  132. Initialize(ctx context.Context) error
  133. // Update the backer server.
  134. Update(ctx context.Context, server *SRSServer) error
  135. // Pick a backend server for the specified stream URL.
  136. Pick(ctx context.Context, streamURL string) (*SRSServer, error)
  137. // Load or store the HLS streaming for the specified stream URL.
  138. LoadOrStoreHLS(ctx context.Context, streamURL string, value *HLSPlayStream) (*HLSPlayStream, error)
  139. // Load the HLS streaming by SPBHID, the SRS Proxy Backend HLS ID.
  140. LoadHLSBySPBHID(ctx context.Context, spbhid string) (*HLSPlayStream, error)
  141. // Store the WebRTC streaming for the specified stream URL.
  142. StoreWebRTC(ctx context.Context, streamURL string, value *RTCConnection) error
  143. // Load the WebRTC streaming by ufrag, the ICE username.
  144. LoadWebRTCByUfrag(ctx context.Context, ufrag string) (*RTCConnection, error)
  145. }
  146. // srsLoadBalancer is the global SRS load balancer.
  147. var srsLoadBalancer SRSLoadBalancer
  148. // srsMemoryLoadBalancer stores state in memory.
  149. type srsMemoryLoadBalancer struct {
  150. // All available SRS servers, key is server ID.
  151. servers sync.Map[string, *SRSServer]
  152. // The picked server to servce client by specified stream URL, key is stream url.
  153. picked sync.Map[string, *SRSServer]
  154. // The HLS streaming, key is stream URL.
  155. hlsStreamURL sync.Map[string, *HLSPlayStream]
  156. // The HLS streaming, key is SPBHID.
  157. hlsSPBHID sync.Map[string, *HLSPlayStream]
  158. // The WebRTC streaming, key is stream URL.
  159. rtcStreamURL sync.Map[string, *RTCConnection]
  160. // The WebRTC streaming, key is ufrag.
  161. rtcUfrag sync.Map[string, *RTCConnection]
  162. }
  163. func NewMemoryLoadBalancer() SRSLoadBalancer {
  164. return &srsMemoryLoadBalancer{}
  165. }
  166. func (v *srsMemoryLoadBalancer) Initialize(ctx context.Context) error {
  167. if server, err := NewDefaultSRSForDebugging(); err != nil {
  168. return errors.Wrapf(err, "initialize default SRS")
  169. } else if server != nil {
  170. if err := v.Update(ctx, server); err != nil {
  171. return errors.Wrapf(err, "update default SRS %+v", server)
  172. }
  173. // Keep alive.
  174. go func() {
  175. for {
  176. select {
  177. case <-ctx.Done():
  178. return
  179. case <-time.After(30 * time.Second):
  180. if err := v.Update(ctx, server); err != nil {
  181. logger.Wf(ctx, "update default SRS %+v failed, %+v", server, err)
  182. }
  183. }
  184. }
  185. }()
  186. logger.Df(ctx, "MemoryLB: Initialize default SRS media server, %+v", server)
  187. }
  188. return nil
  189. }
  190. func (v *srsMemoryLoadBalancer) Update(ctx context.Context, server *SRSServer) error {
  191. v.servers.Store(server.ID(), server)
  192. return nil
  193. }
  194. func (v *srsMemoryLoadBalancer) Pick(ctx context.Context, streamURL string) (*SRSServer, error) {
  195. // Always proxy to the same server for the same stream URL.
  196. if server, ok := v.picked.Load(streamURL); ok {
  197. return server, nil
  198. }
  199. // Gather all servers that were alive within the last few seconds.
  200. var servers []*SRSServer
  201. v.servers.Range(func(key string, server *SRSServer) bool {
  202. if time.Since(server.UpdatedAt) < srsServerAliveDuration {
  203. servers = append(servers, server)
  204. }
  205. return true
  206. })
  207. // If no servers available, use all possible servers.
  208. if len(servers) == 0 {
  209. v.servers.Range(func(key string, server *SRSServer) bool {
  210. servers = append(servers, server)
  211. return true
  212. })
  213. }
  214. // No server found, failed.
  215. if len(servers) == 0 {
  216. return nil, fmt.Errorf("no server available for %v", streamURL)
  217. }
  218. // Pick a server randomly from servers.
  219. server := servers[rand.Intn(len(servers))]
  220. v.picked.Store(streamURL, server)
  221. return server, nil
  222. }
  223. func (v *srsMemoryLoadBalancer) LoadHLSBySPBHID(ctx context.Context, spbhid string) (*HLSPlayStream, error) {
  224. // Load the HLS streaming for the SPBHID, for TS files.
  225. if actual, ok := v.hlsSPBHID.Load(spbhid); !ok {
  226. return nil, errors.Errorf("no HLS streaming for SPBHID %v", spbhid)
  227. } else {
  228. return actual, nil
  229. }
  230. }
  231. func (v *srsMemoryLoadBalancer) LoadOrStoreHLS(ctx context.Context, streamURL string, value *HLSPlayStream) (*HLSPlayStream, error) {
  232. // Update the HLS streaming for the stream URL, for M3u8.
  233. actual, _ := v.hlsStreamURL.LoadOrStore(streamURL, value)
  234. if actual == nil {
  235. return nil, errors.Errorf("load or store HLS streaming for %v failed", streamURL)
  236. }
  237. // Update the HLS streaming for the SPBHID, for TS files.
  238. v.hlsSPBHID.Store(value.SRSProxyBackendHLSID, actual)
  239. return actual, nil
  240. }
  241. func (v *srsMemoryLoadBalancer) StoreWebRTC(ctx context.Context, streamURL string, value *RTCConnection) error {
  242. // Update the WebRTC streaming for the stream URL.
  243. v.rtcStreamURL.Store(streamURL, value)
  244. // Update the WebRTC streaming for the ufrag.
  245. v.rtcUfrag.Store(value.Ufrag, value)
  246. return nil
  247. }
  248. func (v *srsMemoryLoadBalancer) LoadWebRTCByUfrag(ctx context.Context, ufrag string) (*RTCConnection, error) {
  249. if actual, ok := v.rtcUfrag.Load(ufrag); !ok {
  250. return nil, errors.Errorf("no WebRTC streaming for ufrag %v", ufrag)
  251. } else {
  252. return actual, nil
  253. }
  254. }
  255. type srsRedisLoadBalancer struct {
  256. // The redis client sdk.
  257. rdb *redis.Client
  258. }
  259. func NewRedisLoadBalancer() SRSLoadBalancer {
  260. return &srsRedisLoadBalancer{}
  261. }
  262. func (v *srsRedisLoadBalancer) Initialize(ctx context.Context) error {
  263. redisDatabase, err := strconv.Atoi(envRedisDB())
  264. if err != nil {
  265. return errors.Wrapf(err, "invalid PROXY_REDIS_DB %v", envRedisDB())
  266. }
  267. rdb := redis.NewClient(&redis.Options{
  268. Addr: fmt.Sprintf("%v:%v", envRedisHost(), envRedisPort()),
  269. Password: envRedisPassword(),
  270. DB: redisDatabase,
  271. })
  272. v.rdb = rdb
  273. if err := rdb.Ping(ctx).Err(); err != nil {
  274. return errors.Wrapf(err, "unable to connect to redis %v", rdb.String())
  275. }
  276. logger.Df(ctx, "RedisLB: connected to redis %v ok", rdb.String())
  277. if server, err := NewDefaultSRSForDebugging(); err != nil {
  278. return errors.Wrapf(err, "initialize default SRS")
  279. } else if server != nil {
  280. if err := v.Update(ctx, server); err != nil {
  281. return errors.Wrapf(err, "update default SRS %+v", server)
  282. }
  283. // Keep alive.
  284. go func() {
  285. for {
  286. select {
  287. case <-ctx.Done():
  288. return
  289. case <-time.After(30 * time.Second):
  290. if err := v.Update(ctx, server); err != nil {
  291. logger.Wf(ctx, "update default SRS %+v failed, %+v", server, err)
  292. }
  293. }
  294. }
  295. }()
  296. logger.Df(ctx, "RedisLB: Initialize default SRS media server, %+v", server)
  297. }
  298. return nil
  299. }
  300. func (v *srsRedisLoadBalancer) Update(ctx context.Context, server *SRSServer) error {
  301. b, err := json.Marshal(server)
  302. if err != nil {
  303. return errors.Wrapf(err, "marshal server %+v", server)
  304. }
  305. key := v.redisKeyServer(server.ID())
  306. if err = v.rdb.Set(ctx, key, b, srsServerAliveDuration).Err(); err != nil {
  307. return errors.Wrapf(err, "set key=%v server %+v", key, server)
  308. }
  309. // Query all servers from redis, in json string.
  310. var serverKeys []string
  311. if b, err := v.rdb.Get(ctx, v.redisKeyServers()).Bytes(); err == nil {
  312. if err := json.Unmarshal(b, &serverKeys); err != nil {
  313. return errors.Wrapf(err, "unmarshal key=%v servers %v", v.redisKeyServers(), string(b))
  314. }
  315. }
  316. // Check each server expiration, if not exists in redis, remove from servers.
  317. for i := len(serverKeys) - 1; i >= 0; i-- {
  318. if _, err := v.rdb.Get(ctx, serverKeys[i]).Bytes(); err != nil {
  319. serverKeys = append(serverKeys[:i], serverKeys[i+1:]...)
  320. }
  321. }
  322. // Add server to servers if not exists.
  323. var found bool
  324. for _, serverKey := range serverKeys {
  325. if serverKey == key {
  326. found = true
  327. break
  328. }
  329. }
  330. if !found {
  331. serverKeys = append(serverKeys, key)
  332. }
  333. // Update all servers to redis.
  334. b, err = json.Marshal(serverKeys)
  335. if err != nil {
  336. return errors.Wrapf(err, "marshal servers %+v", serverKeys)
  337. }
  338. if err = v.rdb.Set(ctx, v.redisKeyServers(), b, 0).Err(); err != nil {
  339. return errors.Wrapf(err, "set key=%v servers %+v", v.redisKeyServers(), serverKeys)
  340. }
  341. return nil
  342. }
  343. func (v *srsRedisLoadBalancer) Pick(ctx context.Context, streamURL string) (*SRSServer, error) {
  344. key := fmt.Sprintf("srs-proxy-url:%v", streamURL)
  345. // Always proxy to the same server for the same stream URL.
  346. if serverKey, err := v.rdb.Get(ctx, key).Result(); err == nil {
  347. // If server not exists, ignore and pick another server for the stream URL.
  348. if b, err := v.rdb.Get(ctx, serverKey).Bytes(); err == nil && len(b) > 0 {
  349. var server SRSServer
  350. if err := json.Unmarshal(b, &server); err != nil {
  351. return nil, errors.Wrapf(err, "unmarshal key=%v server %v", key, string(b))
  352. }
  353. // TODO: If server fail, we should migrate the streams to another server.
  354. return &server, nil
  355. }
  356. }
  357. // Query all servers from redis, in json string.
  358. var serverKeys []string
  359. if b, err := v.rdb.Get(ctx, v.redisKeyServers()).Bytes(); err == nil {
  360. if err := json.Unmarshal(b, &serverKeys); err != nil {
  361. return nil, errors.Wrapf(err, "unmarshal key=%v servers %v", v.redisKeyServers(), string(b))
  362. }
  363. }
  364. // No server found, failed.
  365. if len(serverKeys) == 0 {
  366. return nil, fmt.Errorf("no server available for %v", streamURL)
  367. }
  368. // All server should be alive, if not, should have been removed by redis. So we only
  369. // random pick one that is always available.
  370. var serverKey string
  371. var server SRSServer
  372. for i := 0; i < 3; i++ {
  373. tryServerKey := serverKeys[rand.Intn(len(serverKeys))]
  374. b, err := v.rdb.Get(ctx, tryServerKey).Bytes()
  375. if err == nil && len(b) > 0 {
  376. if err := json.Unmarshal(b, &server); err != nil {
  377. return nil, errors.Wrapf(err, "unmarshal key=%v server %v", serverKey, string(b))
  378. }
  379. serverKey = tryServerKey
  380. break
  381. }
  382. }
  383. if serverKey == "" {
  384. return nil, errors.Errorf("no server available in %v for %v", serverKeys, streamURL)
  385. }
  386. // Update the picked server for the stream URL.
  387. if err := v.rdb.Set(ctx, key, []byte(serverKey), 0).Err(); err != nil {
  388. return nil, errors.Wrapf(err, "set key=%v server %v", key, serverKey)
  389. }
  390. return &server, nil
  391. }
  392. func (v *srsRedisLoadBalancer) LoadHLSBySPBHID(ctx context.Context, spbhid string) (*HLSPlayStream, error) {
  393. key := v.redisKeySPBHID(spbhid)
  394. b, err := v.rdb.Get(ctx, key).Bytes()
  395. if err != nil {
  396. return nil, errors.Wrapf(err, "get key=%v HLS", key)
  397. }
  398. var actual HLSPlayStream
  399. if err := json.Unmarshal(b, &actual); err != nil {
  400. return nil, errors.Wrapf(err, "unmarshal key=%v HLS %v", key, string(b))
  401. }
  402. return &actual, nil
  403. }
  404. func (v *srsRedisLoadBalancer) LoadOrStoreHLS(ctx context.Context, streamURL string, value *HLSPlayStream) (*HLSPlayStream, error) {
  405. b, err := json.Marshal(value)
  406. if err != nil {
  407. return nil, errors.Wrapf(err, "marshal HLS %v", value)
  408. }
  409. key := v.redisKeyHLS(streamURL)
  410. if err = v.rdb.Set(ctx, key, b, srsHLSAliveDuration).Err(); err != nil {
  411. return nil, errors.Wrapf(err, "set key=%v HLS %v", key, value)
  412. }
  413. key2 := v.redisKeySPBHID(value.SRSProxyBackendHLSID)
  414. if err := v.rdb.Set(ctx, key2, b, srsHLSAliveDuration).Err(); err != nil {
  415. return nil, errors.Wrapf(err, "set key=%v HLS %v", key2, value)
  416. }
  417. // Query the HLS streaming from redis.
  418. b2, err := v.rdb.Get(ctx, key).Bytes()
  419. if err != nil {
  420. return nil, errors.Wrapf(err, "get key=%v HLS", key)
  421. }
  422. var actual HLSPlayStream
  423. if err := json.Unmarshal(b2, &actual); err != nil {
  424. return nil, errors.Wrapf(err, "unmarshal key=%v HLS %v", key, string(b2))
  425. }
  426. return &actual, nil
  427. }
  428. func (v *srsRedisLoadBalancer) StoreWebRTC(ctx context.Context, streamURL string, value *RTCConnection) error {
  429. b, err := json.Marshal(value)
  430. if err != nil {
  431. return errors.Wrapf(err, "marshal WebRTC %v", value)
  432. }
  433. key := v.redisKeyRTC(streamURL)
  434. if err = v.rdb.Set(ctx, key, b, srsRTCAliveDuration).Err(); err != nil {
  435. return errors.Wrapf(err, "set key=%v WebRTC %v", key, value)
  436. }
  437. key2 := v.redisKeyUfrag(value.Ufrag)
  438. if err := v.rdb.Set(ctx, key2, b, srsRTCAliveDuration).Err(); err != nil {
  439. return errors.Wrapf(err, "set key=%v WebRTC %v", key2, value)
  440. }
  441. return nil
  442. }
  443. func (v *srsRedisLoadBalancer) LoadWebRTCByUfrag(ctx context.Context, ufrag string) (*RTCConnection, error) {
  444. key := v.redisKeyUfrag(ufrag)
  445. b, err := v.rdb.Get(ctx, key).Bytes()
  446. if err != nil {
  447. return nil, errors.Wrapf(err, "get key=%v WebRTC", key)
  448. }
  449. var actual RTCConnection
  450. if err := json.Unmarshal(b, &actual); err != nil {
  451. return nil, errors.Wrapf(err, "unmarshal key=%v WebRTC %v", key, string(b))
  452. }
  453. return &actual, nil
  454. }
  455. func (v *srsRedisLoadBalancer) redisKeyUfrag(ufrag string) string {
  456. return fmt.Sprintf("srs-proxy-ufrag:%v", ufrag)
  457. }
  458. func (v *srsRedisLoadBalancer) redisKeyRTC(streamURL string) string {
  459. return fmt.Sprintf("srs-proxy-rtc:%v", streamURL)
  460. }
  461. func (v *srsRedisLoadBalancer) redisKeySPBHID(spbhid string) string {
  462. return fmt.Sprintf("srs-proxy-spbhid:%v", spbhid)
  463. }
  464. func (v *srsRedisLoadBalancer) redisKeyHLS(streamURL string) string {
  465. return fmt.Sprintf("srs-proxy-hls:%v", streamURL)
  466. }
  467. func (v *srsRedisLoadBalancer) redisKeyServer(serverID string) string {
  468. return fmt.Sprintf("srs-proxy-server:%v", serverID)
  469. }
  470. func (v *srsRedisLoadBalancer) redisKeyServers() string {
  471. return fmt.Sprintf("srs-proxy-all-servers")
  472. }