-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontrol_connection.go
More file actions
385 lines (296 loc) · 8.49 KB
/
control_connection.go
File metadata and controls
385 lines (296 loc) · 8.49 KB
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
// Control server connection
package main
import (
"fmt"
"net/http"
"net/url"
"os"
"sync"
"time"
messages "github.com/AgustinSRG/go-simple-rpc-message"
"github.com/gorilla/websocket"
)
// Status data of the connection with the coordinator server
type ControlServerConnection struct {
server *RTMPServer // Reference to the RTMP server
connectionURL string // Connection URL
connection *websocket.Conn // Websocket connection
lock *sync.Mutex // Mutex to control access to this struct
nextRequestId uint64 // ID for the next request ID
requests map[string]*ControlServerPendingRequest // Pending requests. Map: ID -> Request status data
enabled bool // True if the connection is enabled (will reconnect)
}
// Status data for a pending request
type ControlServerPendingRequest struct {
waiter chan PublishResponse // Channel to wait for the response
}
// Response for a publish request
type PublishResponse struct {
accepted bool // True if accepted, false if denied
streamId string // If accepted, the stream ID
}
// Initializes connection
// server - Reference to the RTMP server
func (c *ControlServerConnection) Initialize(server *RTMPServer) {
c.server = server
c.lock = &sync.Mutex{}
c.nextRequestId = 0
c.requests = make(map[string]*ControlServerPendingRequest)
baseURL := os.Getenv("CONTROL_BASE_URL")
if baseURL == "" {
LogWarning("CONTROL_BASE_URL not provided. The server will run in stand-alone mode.")
c.enabled = false
return
}
connectionURL, err := url.Parse(baseURL)
if err != nil {
LogError(err)
LogWarning("CONTROL_BASE_URL not provided. The server will run in stand-alone mode.")
c.enabled = false
return
}
pathURL, err := url.Parse("/ws/control/rtmp")
if err != nil {
LogError(err)
LogWarning("CONTROL_BASE_URL not provided. The server will run in stand-alone mode.")
c.enabled = false
return
}
c.connectionURL = connectionURL.ResolveReference(pathURL).String()
c.enabled = true
go c.Connect()
go c.RunHeartBeatLoop()
}
// Connect to the websocket server
func (c *ControlServerConnection) Connect() {
c.lock.Lock()
if c.connection != nil {
c.lock.Unlock()
return // Already connected
}
LogInfo("[WS-CONTROL] Connecting to " + c.connectionURL)
headers := http.Header{}
authToken := MakeWebsocketAuthenticationToken()
if authToken != "" {
headers.Set("x-control-auth-token", authToken)
}
externalIP := os.Getenv("EXTERNAL_IP")
if externalIP != "" {
headers.Set("x-external-ip", externalIP)
}
externalPort := os.Getenv("EXTERNAL_PORT")
if externalPort != "" {
headers.Set("x-custom-port", externalPort)
}
useSSL := os.Getenv("EXTERNAL_SSL")
if useSSL == "YES" {
headers.Set("x-ssl-use", "true")
}
conn, _, err := websocket.DefaultDialer.Dial(c.connectionURL, headers)
if err != nil {
c.lock.Unlock()
LogErrorMessage("[WS-CONTROL] Connection error: " + err.Error())
go c.Reconnect()
return
}
c.connection = conn
c.lock.Unlock()
// After a connection is established, any previous publishing sessions must be killed,
// since the coordinator server thinks the streaming server went down
c.server.KillAllActivePublishers()
go c.RunReaderLoop(conn)
}
// Waits 10 seconds and reconnects
func (c *ControlServerConnection) Reconnect() {
LogInfo("[WS-CONTROL] Waiting 10 seconds to reconnect.")
time.Sleep(10 * time.Second)
c.Connect()
}
// Called when disconnected
// err - Disconnection error
func (c *ControlServerConnection) OnDisconnect(err error) {
c.lock.Lock()
c.connection = nil
LogInfo("[WS-CONTROL] Disconnected: " + err.Error())
c.lock.Unlock()
go c.Connect() // Reconnect
}
// Sends a message
// msg - The message
// Returns true if the message was successfully sent
func (c *ControlServerConnection) Send(msg messages.RPCMessage) bool {
c.lock.Lock()
defer c.lock.Unlock()
if c.connection == nil {
return false
}
err := c.connection.WriteMessage(websocket.TextMessage, []byte(msg.Serialize()))
if err != nil {
return false
}
if LOG_DEBUG_ENABLED {
LogDebug("[WS-CONTROL] >>>\n" + string(msg.Serialize()))
}
return true
}
// Generates a new request-id
func (c *ControlServerConnection) GetNextRequestId() uint64 {
c.lock.Lock()
defer c.lock.Unlock()
requestId := c.nextRequestId
c.nextRequestId++
return requestId
}
// Reads messages until the connection is finished
// conn - Websocket connection
func (c *ControlServerConnection) RunReaderLoop(conn *websocket.Conn) {
for {
err := conn.SetReadDeadline(time.Now().Add(60 * time.Second))
if err != nil {
conn.Close()
c.OnDisconnect(err)
return
}
_, message, err := conn.ReadMessage()
if err != nil {
conn.Close()
c.OnDisconnect(err)
return
}
msgStr := string(message)
if LOG_DEBUG_ENABLED {
LogDebug("[WS-CONTROL] <<<\n" + msgStr)
}
msg := messages.ParseRPCMessage(msgStr)
c.ParseIncomingMessage(&msg)
}
}
// Parses an incoming message
// msg - Received parsed message
func (c *ControlServerConnection) ParseIncomingMessage(msg *messages.RPCMessage) {
switch msg.Method {
case "ERROR":
LogErrorMessage("[WS-CONTROL] Remote error. Code=" + msg.GetParam("Error-Code") + " / Details: " + msg.GetParam("Error-Message"))
case "PUBLISH-ACCEPT":
c.OnPublishAccept(msg.GetParam("Request-Id"), msg.GetParam("Stream-Id"))
case "PUBLISH-DENY":
c.OnPublishDeny(msg.GetParam("Request-Id"))
case "STREAM-KILL":
c.OnStreamKill(msg.GetParam("Stream-Channel"), msg.GetParam("Stream-Id"))
}
}
// Handles a PUBLISH-ACCEPT message
// requestId - Request ID
// streamId - Stream ID
func (c *ControlServerConnection) OnPublishAccept(requestId string, streamId string) {
c.lock.Lock()
req := c.requests[requestId]
c.lock.Unlock()
if req == nil {
return
}
res := PublishResponse{
accepted: true,
streamId: streamId,
}
req.waiter <- res
}
// Handles a PUBLISH-DENY message
// requestId - Request ID
func (c *ControlServerConnection) OnPublishDeny(requestId string) {
c.lock.Lock()
req := c.requests[requestId]
c.lock.Unlock()
if req == nil {
return
}
res := PublishResponse{
accepted: false,
streamId: "",
}
req.waiter <- res
}
// Handles a STREAM-KILL message
// channel - Streaming channel
// streamId - Stream ID or the * wildcard
func (c *ControlServerConnection) OnStreamKill(channel string, streamId string) {
if streamId == "*" || streamId == "" {
publisher := c.server.GetPublisher(channel)
if publisher != nil {
publisher.Kill()
}
} else {
publisher := c.server.GetPublisher(channel)
if publisher != nil && publisher.stream_id == streamId {
publisher.Kill()
}
}
}
// Sends heart-beat messages to keep the connection alive
func (c *ControlServerConnection) RunHeartBeatLoop() {
for {
time.Sleep(20 * time.Second)
// Send heartbeat message
heartbeatMessage := messages.RPCMessage{
Method: "HEARTBEAT",
}
c.Send(heartbeatMessage)
}
}
// Requests publishing to the coordinator server
// channel - RTMP channel ID
// key - Publishing key
// userIP - IP address of the user
// Returns:
// - accepted - True if the key was accepted
// - streamId - Contains the Stream ID if accepted
//
// This method waits for the server to return a response
func (c *ControlServerConnection) RequestPublish(channel string, key string, userIP string) (accepted bool, streamId string) {
if !c.enabled {
return true, ""
}
requestId := fmt.Sprint(c.GetNextRequestId())
request := ControlServerPendingRequest{
waiter: make(chan PublishResponse),
}
msgParams := make(map[string]string)
msgParams["Request-ID"] = requestId
msgParams["Stream-Channel"] = channel
msgParams["Stream-Key"] = key
msgParams["User-IP"] = userIP
msg := messages.RPCMessage{
Method: "PUBLISH-REQUEST",
Params: msgParams,
}
c.lock.Lock()
c.requests[requestId] = &request
c.lock.Unlock()
success := c.Send(msg)
if !success {
c.lock.Lock()
delete(c.requests, requestId)
c.lock.Unlock()
return false, ""
}
time.AfterFunc(20*time.Second, func() { request.waiter <- PublishResponse{accepted: false, streamId: ""} }) // Timeout
res := <-request.waiter // Wait
c.lock.Lock()
delete(c.requests, requestId)
c.lock.Unlock()
return res.accepted, res.streamId
}
// Send Publish-End message to the coordinator server
// channel - Streaming channel
// streamId - Streaming session ID
// Returns true if success
func (c *ControlServerConnection) PublishEnd(channel string, streamId string) bool {
msgParams := make(map[string]string)
msgParams["Stream-Channel"] = channel
msgParams["Stream-ID"] = streamId
msg := messages.RPCMessage{
Method: "PUBLISH-END",
Params: msgParams,
}
return c.Send(msg)
}