forked from aws-samples/pixel-streaming-at-scale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matchmaker.js
356 lines (316 loc) · 12.4 KB
/
matchmaker.js
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
// Copyright Epic Games, Inc. All Rights Reserved.
//Start : AWS - expose matchmaker only as api endpoint
var enableRedirectionLinks = false;
//End : AWS - expose matchmaker only as api endpoint
var enableRESTAPI = true;
const defaultConfig = {
// The port clients connect to the matchmaking service over HTTP
HttpPort: 80,
UseHTTPS: false,
// The matchmaking port the signaling service connects to the matchmaker
MatchmakerPort: 9999,
// Log to file
LogToFile: true
};
// Similar to the Signaling Server (SS) code, load in a config.json file for the MM parameters
const argv = require('yargs').argv;
var configFile = (typeof argv.configFile != 'undefined') ? argv.configFile.toString() : 'config.json';
console.log(`configFile ${configFile}`);
const config = require('./modules/config.js').init(configFile, defaultConfig);
console.log("Config: " + JSON.stringify(config, null, '\t'));
const express = require('express');
var cors = require('cors');
const app = express();
const http = require('http').Server(app);
const fs = require('fs');
const path = require('path');
const logging = require('./modules/logging.js');
//Start : AWS - Loaded aws sdk for iterfacing with dynamoDB and SSM paramater store
var AWS = require('aws-sdk');
const { SSMClient, GetParameterCommand } = require("@aws-sdk/client-ssm");
// please change based on region
AWS.config.update({region: config.AWSRegion});
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });
//End : AWS - Loaded aws sdk for iterfacing with dynamoDB and SSM paramater store
logging.RegisterConsoleLogger();
if (config.LogToFile) {
logging.RegisterFileLogger('./logs');
}
// A list of all the Cirrus server which are connected to the Matchmaker.
var cirrusServers = new Map();
var theSSMSecret=''
//
// Parse command line.
//
if (typeof argv.HttpPort != 'undefined') {
config.HttpPort = argv.HttpPort;
}
if (typeof argv.MatchmakerPort != 'undefined') {
config.MatchmakerPort = argv.MatchmakerPort;
}
http.listen(config.HttpPort, () => {
console.log('HTTP listening on *:' + config.HttpPort);
});
if (config.UseHTTPS) {
//HTTPS certificate details
const options = {
key: fs.readFileSync(path.join(__dirname, './certificates/client-key.pem')),
cert: fs.readFileSync(path.join(__dirname, './certificates/client-cert.pem'))
};
var https = require('https').Server(options, app);
//Setup http -> https redirect
console.log('Redirecting http->https');
app.use(function (req, res, next) {
if (!req.secure) {
if (req.get('Host')) {
var hostAddressParts = req.get('Host').split(':');
var hostAddress = hostAddressParts[0];
if (httpsPort != 443) {
hostAddress = `${hostAddress}:${httpsPort}`;
}
return res.redirect(['https://', hostAddress, req.originalUrl].join(''));
} else {
console.error(`unable to get host name from header. Requestor ${req.ip}, url path: '${req.originalUrl}', available headers ${JSON.stringify(req.headers)}`);
return res.status(400).send('Bad Request');
}
}
next();
});
https.listen(443, function () {
console.log('Https listening on 443');
});
}
// No servers are available so send some simple JavaScript to the client to make
// it retry after a short period of time.
function sendRetryResponse(res) {
res.send(`All ${cirrusServers.size} Cirrus servers are in use. Retrying in <span id="countdown">3</span> seconds.
<script>
var countdown = document.getElementById("countdown").textContent;
setInterval(function() {
countdown--;
if (countdown == 0) {
window.location.reload(1);
} else {
document.getElementById("countdown").textContent = countdown;
}
}, 1000);
</script>`);
}
// Get a Cirrus server if there is one available which has no clients connected.
function getAvailableCirrusServer() {
for (cirrusServer of cirrusServers.values()) {
if (cirrusServer.numConnectedClients === 0 && cirrusServer.ready === true) {
// Check if we had at least 10 seconds since the last redirect, avoiding the
// chance of redirecting 2+ users to the same SS before they click Play.
// In other words, give the user 10 seconds to click play button the claim the server.
if( cirrusServer.hasOwnProperty('lastRedirect')) {
if( ((Date.now() - cirrusServer.lastRedirect) / 1000) < 10 )
continue;
}
cirrusServer.lastRedirect = Date.now();
return cirrusServer;
}
}
console.log('WARNING: No empty Cirrus servers are available');
return undefined;
}
//Start : AWS - get client secret for validation from parameter store
const getParameterInfo = async () => {
const client = new SSMClient({ region: "ap-south-1" });
const input = { // GetParameterRequest
Name: "matchmakerclientsecret" // required
};
const paramSSMcommand = new GetParameterCommand(input);
const paramSSMresponse= await client.send(paramSSMcommand);
theSSMSecret=paramSSMresponse.Parameter.Value
}
//End : AWS - get client secret for validation from parameter store
//Start : AWS - Get Query String from DynamoDB for Signalling Instance
const getQueryStringFromDDB = async (instanceId) => {
var qs=''
console.log(instanceId)
var params = {
FilterExpression: "InstanceID = :t",
ExpressionAttributeValues: {
":t": {S: instanceId}
},
ProjectionExpression: "QueryString",
TableName: "instanceMapping"
};
const data =await ddb.scan(params).promise()
qs=data.Items[0].QueryString.S
console.log("Success", qs);
return qs
}
//End : AWS - Get Query String from DynamoDB for Signalling Instance
if(enableRESTAPI) {
// Handle REST signalling server only request.
app.options('/signallingserver', cors())
app.get('/signallingserver', cors(), async(req, res) => {
//Start : AWS - check if a valid secret was provided in header to authenticate calls
console.log(config.AWSRegion)
await getParameterInfo()
if(req.header("clientsecret") != undefined && req.header("clientsecret")==theSSMSecret)
{
cirrusServer = getAvailableCirrusServer();
if (cirrusServer != undefined) {
var qs=await getQueryStringFromDDB(cirrusServer.instanceID);
console.log("Received", qs);
// The original function used to send the instance ip/port to allow connection to Signalling
// We have modified the logic to send a query string which allows to connect to Signalling
// via an external load balancer. The query string is in dynamoDB
res.json({ signallingServer: qs});
console.log(`Returning ${cirrusServer.address}:${cirrusServer.port}`);
} else {
res.status(400).send('No signalling servers available');
}
}else
{
res.status(401).send('Unauthorized');
}
//End : AWS - check if a valid secret was provided in header to authenticate calls
});
}
if(enableRedirectionLinks) {
// Handle standard URL.
app.get('/', (req, res) => {
cirrusServer = getAvailableCirrusServer();
if (cirrusServer != undefined) {
res.redirect(`http://${cirrusServer.address}:${cirrusServer.port}/`);
//console.log(req);
console.log(`Redirect to ${cirrusServer.address}:${cirrusServer.port}`);
} else {
sendRetryResponse(res);
}
});
// Handle URL with custom HTML.
app.get('/custom_html/:htmlFilename', (req, res) => {
cirrusServer = getAvailableCirrusServer();
if (cirrusServer != undefined) {
res.redirect(`http://${cirrusServer.address}:${cirrusServer.port}/custom_html/${req.params.htmlFilename}`);
console.log(`Redirect to ${cirrusServer.address}:${cirrusServer.port}`);
} else {
sendRetryResponse(res);
}
});
}
//
// Connection to Cirrus.
//
const net = require('net');
function disconnect(connection) {
console.log(`Ending connection to remote address ${connection.remoteAddress}`);
connection.end();
}
const matchmaker = net.createServer((connection) => {
connection.on('data', (data) => {
try {
message = JSON.parse(data);
if(message)
console.log(`Message TYPE: ${message.type}`);
} catch(e) {
console.log(`ERROR (${e.toString()}): Failed to parse Cirrus information from data: ${data.toString()}`);
disconnect(connection);
return;
}
if (message.type === 'connect') {
// A Cirrus server connects to this Matchmaker server.
cirrusServer = {
address: message.address,
port: message.port,
numConnectedClients: 0,
lastPingReceived: Date.now(),
instanceID:message.instanceId
};
cirrusServer.ready = message.ready === true;
// Handles disconnects between MM and SS to not add dupes with numConnectedClients = 0 and redirect users to same SS
// Check if player is connected and doing a reconnect. message.playerConnected is a new variable sent from the SS to
// help track whether or not a player is already connected when a 'connect' message is sent (i.e., reconnect).
if(message.playerConnected == true) {
cirrusServer.numConnectedClients = 1;
}
// Find if we already have a ciruss server address connected to (possibly a reconnect happening)
let server = [...cirrusServers.entries()].find(([key, val]) => val.address === cirrusServer.address && val.port === cirrusServer.port);
// if a duplicate server with the same address isn't found -- add it to the map as an available server to send users to.
if (!server || server.size <= 0) {
console.log(`Adding connection for ${cirrusServer.address.split(".")[0]} with playerConnected: ${message.playerConnected}`)
cirrusServers.set(connection, cirrusServer);
} else {
console.log(`RECONNECT: cirrus server address ${cirrusServer.address.split(".")[0]} already found--replacing. playerConnected: ${message.playerConnected}`)
var foundServer = cirrusServers.get(server[0]);
// Make sure to retain the numConnectedClients from the last one before the reconnect to MM
if (foundServer) {
cirrusServers.set(connection, cirrusServer);
console.log(`Replacing server with original with numConn: ${cirrusServer.numConnectedClients}`);
cirrusServers.delete(server[0]);
} else {
cirrusServers.set(connection, cirrusServer);
console.log("Connection not found in Map() -- adding a new one");
}
}
} else if (message.type === 'streamerConnected') {
// The stream connects to a Cirrus server and so is ready to be used
cirrusServer = cirrusServers.get(connection);
if(cirrusServer) {
cirrusServer.ready = true;
console.log(`Cirrus server ${cirrusServer.address}:${cirrusServer.port} ready for use`);
} else {
disconnect(connection);
}
} else if (message.type === 'streamerDisconnected') {
// The stream connects to a Cirrus server and so is ready to be used
cirrusServer = cirrusServers.get(connection);
if(cirrusServer) {
cirrusServer.ready = false;
console.log(`Cirrus server ${cirrusServer.address}:${cirrusServer.port} no longer ready for use`);
} else {
disconnect(connection);
}
} else if (message.type === 'clientConnected') {
// A client connects to a Cirrus server.
cirrusServer = cirrusServers.get(connection);
if(cirrusServer) {
cirrusServer.numConnectedClients++;
console.log(`Client connected to Cirrus server ${cirrusServer.address}:${cirrusServer.port}`);
} else {
disconnect(connection);
}
} else if (message.type === 'clientDisconnected') {
// A client disconnects from a Cirrus server.
cirrusServer = cirrusServers.get(connection);
if(cirrusServer) {
cirrusServer.numConnectedClients--;
console.log(`Client disconnected from Cirrus server ${cirrusServer.address}:${cirrusServer.port}`);
if(cirrusServer.numConnectedClients === 0) {
// this make this server immediately available for a new client
cirrusServer.lastRedirect = 0;
}
} else {
disconnect(connection);
}
} else if (message.type === 'ping') {
cirrusServer = cirrusServers.get(connection);
if(cirrusServer) {
cirrusServer.lastPingReceived = Date.now();
} else {
disconnect(connection);
}
} else {
console.log('ERROR: Unknown data: ' + JSON.stringify(message));
disconnect(connection);
}
});
// A Cirrus server disconnects from this Matchmaker server.
connection.on('error', () => {
cirrusServer = cirrusServers.get(connection);
if(cirrusServer) {
cirrusServers.delete(connection);
console.log(`Cirrus server ${cirrusServer.address}:${cirrusServer.port} disconnected from Matchmaker`);
} else {
console.log(`Disconnected machine that wasn't a registered cirrus server, remote address: ${connection.remoteAddress}`);
}
});
});
matchmaker.listen(config.MatchmakerPort, () => {
console.log('Matchmaker listening on *:' + config.MatchmakerPort);
});