-
Notifications
You must be signed in to change notification settings - Fork 41
/
server.js
1782 lines (1497 loc) · 71.5 KB
/
server.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
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
require("./classes/prototypes.js");
const moment = require("moment");
const express = require("express");
const fileUpload = require("express-fileupload");
const bodyParser = require("body-parser");
const crypto = require("crypto");
const fs = require("fs-extra");
const MongoClient = require("mongodb").MongoClient;
const Long = require("mongodb").Long;
const ObjectId = require("mongodb").ObjectID;
const zlib = require("zlib");
const Cacheman = require("cacheman");
const app = express();
const Busboy = require("busboy");
const weight_parser = require("./classes/weight_parser.js");
const rss_generator = require("./classes/rss_generator.js");
const os = require("os");
const path = require("path");
const discord = require("./classes/discord");
const morgan = require("morgan");
const rfs = require("rotating-file-stream");
const dbutils = require("./classes/dbutils");
const mongoMorgan = require("mongo-morgan");
const Raven = require("raven");
const config = require("./config");
const MONGODB_URL = "mongodb://localhost/test";
if (config.RAVEN_DSN) {
console.log("init raven");
Raven.config(config.RAVEN_DSN, { captureUnhandledRejections: true }).install();
}
/**
* Request Logging
*/
const logDir = path.join(__dirname, "logs");
fs.ensureDirSync(logDir);
const logStream = rfs("access.log", {
interval: "1d", // rotate daily
maxFiles: 7, // keep 1 week worth of logs
path: logDir
});
morgan.token("memory", () => {
const used = process.memoryUsage();
const usage = [];
for (const key in used) {
const size = (used[key] / 1024 / 1024).toFixed(2);
usage.push(`${key}: ${size} MB`);
}
return usage.join(", ");
});
mongoMorgan.token("epochtime", () => Date.now());
// Save access log to `logs` collection
app.use(
mongoMorgan(
MONGODB_URL,
"{\"method\": \":method\", \"url\": \":url\", \"status\": :status, \"response-time\": :response-time, \"time\": :epochtime}",
{ collection: "logs" })
);
app.use(morgan("-->Before :memory", { stream: logStream, immediate: true }));
app.use(morgan(":method :url :status :req[content-length] :response-time ms", { stream: logStream, immediate: false }));
app.use(morgan("-->After :memory", { stream: logStream, immediate: false }));
/**
* Utilities
*/
const {
set_task_verification_secret,
add_match_verification,
check_match_verification,
network_exists,
checksum,
make_seed,
get_timestamp_from_seed,
seed_from_mongolong,
process_games_list,
CalculateEloFromPercent,
objectIdFromDate,
log_memory_stats,
SPRT,
LLR,
asyncMiddleware,
how_many_games_to_queue,
add_gzip_hash
} = require("./classes/utilities.js");
const ELF_NETWORKS = [
"62b5417b64c46976795d10a6741801f15f857e5029681a42d02c9852097df4b9",
"d13c40993740cb77d85c838b82c08cc9c3f0fbc7d8c3761366e5d59e8f371cbd"
];
const auth_key = String(fs.readFileSync(__dirname + "/auth_key")).trim();
set_task_verification_secret(String(fs.readFileSync(__dirname + "/task_secret")).trim());
const cacheIP24hr = new Cacheman("IP24hr");
const cacheIP1hr = new Cacheman("IP1hr");
// Cache information about matches and best network rating
const cachematches = new Cacheman("matches");
let bestRatings = new Map();
const fastClientsMap = new Map();
app.set("view engine", "pug");
// This shouldn't be needed but now and then when I restart test server, I see an uncaught ECONNRESET and I'm not sure
// where it is coming from. In case a server restart did the same thing, this should prevent a crash that would stop nodemon.
//
// It was a bug in nodemon which has now been fixed. It is bad practice to leave this here, eventually remove it.
//
process.on("uncaughtException", err => {
console.error("Caught exception: " + err);
});
// https://blog.tompawlak.org/measure-execution-time-nodejs-javascript
let counter = 0;
let elf_counter = 0;
let best_network_mtimeMs = 0;
let best_network_hash_promise = null;
let db;
// TODO Make a map to store pending match info, use mapReduce to find who to serve out, only
// delete when SPRT fail or needed games have all arrived? Then we can update stats easily on
// all matches except just the current one (end of queue).
//
let pending_matches = [];
const MATCH_EXPIRE_TIME = 30 * 60 * 1000; // matches expire after 30 minutes. After that the match will be lost and an extra request will be made.
function get_options_hash(options) {
if (options.visits) {
return checksum("" + options.visits + options.resignation_percent + options.noise + options.randomcnt).slice(0, 6);
} else {
return checksum("" + options.playouts + options.resignation_percent + options.noise + options.randomcnt).slice(0, 6);
}
}
async function get_fast_clients() {
const start = Date.now();
try {
// Get some recent self-play games to calculate durations from seeds
const games = await db.collection("games").find({}, { ip: 1, movescount: 1, random_seed: 1 })
.sort({ _id: -1 }).limit(1000).toArray();
// Keep track of the move rate of each game by client
fastClientsMap.clear();
games.forEach(game => {
const seed = (s => s instanceof Long ? s : new Long(s))(game.random_seed);
const startTime = get_timestamp_from_seed(seed);
const minutes = (game._id.getTimestamp() / 1000 - startTime) / 60;
// Make sure we have some reasonable duration
if (minutes > 0 && minutes <= 60 * 24)
fastClientsMap.set(game.ip, [...(fastClientsMap.get(game.ip) || []), game.movescount / minutes]);
});
// Clean up the map to be a single rate value with enough entries
for (const [ip, rates] of fastClientsMap) {
// Remove clients that submitted only a couple fast games (in case
// some unexpected seed just happens to match the duration)
if (rates.length < 3)
fastClientsMap.delete(ip);
else
fastClientsMap.set(ip, rates.reduce((t, v) => t + v) / rates.length);
}
// Short circuit if there's nothing interesting to do
if (fastClientsMap.size == 0) {
console.log("No clients found with sufficient rate data");
return;
}
// Print out some statistics on rates
const sortedRates = [...fastClientsMap.values()].sort((a, b) => a - b);
const quartile = n => {
const index = n / 4 * (sortedRates.length - 1);
return index % 1 == 0 ? sortedRates[index] : (sortedRates[Math.floor(index)] + sortedRates[Math.ceil(index)]) / 2;
};
console.log("Client moves per minute rates:", ["min", "25%", "median", "75%", "max"].map((text, index) => `${quartile(index).toFixed(1)} ${text}`).join(", "));
// Keep only clients that have the top 25% rates
const top25Rate = quartile(2);
for (const [ip, rate] of fastClientsMap) {
if (rate < top25Rate)
fastClientsMap.delete(ip);
}
console.log(`In ${Date.now() - start}ms from recent ${games.length} games, found ${fastClientsMap.size} fast clients:`, fastClientsMap);
} catch (err) {
console.log("Failed to get recent games for fast clients:", err);
}
}
// db.matches.aggregate( [ { "$redact": { "$cond": [ { "$gt": [ "$number_to_play", "$game_count" ] }, "$$KEEP", "$$PRUNE" ] } } ] )
//
async function get_pending_matches() {
pending_matches = [];
return new Promise((resolve, reject) => {
db.collection("matches").aggregate([
{ $redact: { $cond:
[
{ $gt: [ "$number_to_play", "$game_count" ] },
"$$KEEP", "$$PRUNE"
] } }
]).sort({ _id: -1 }).forEach(match => {
match.requests = []; // init request list.
// Client only accepts strings for now
//
Object.keys(match.options).map(key => {
match.options[key] = String(match.options[key]);
});
// If SPRT=pass use unshift() instead of push() so "Elo only" matches go last in priority
//
switch (SPRT(match.network1_wins, match.network1_losses)) {
case false:
break;
case true:
pending_matches.unshift(match);
console.log("SPRT: Unshifting: " + JSON.stringify(match));
break;
default:
pending_matches.push(match);
console.log("SPRT: Pushing: " + JSON.stringify(match));
}
}, err => {
if (err) {
console.error("Error fetching matches: " + err);
return reject(err);
}
});
resolve();
});
}
async function get_best_network_hash() {
// Check if file has changed. If not, send cached version instead.
//
return fs.stat(__dirname + "/network/best-network.gz")
.then(stats => {
if (!best_network_hash_promise || best_network_mtimeMs != stats.mtimeMs) {
best_network_mtimeMs = stats.mtimeMs;
best_network_hash_promise = new Promise((resolve, reject) => {
log_memory_stats("best_network_hash_promise begins");
const rstream = fs.createReadStream(__dirname + "/network/best-network.gz");
const gunzip = zlib.createGunzip();
const hash = crypto.createHash("sha256");
hash.setEncoding("hex");
log_memory_stats("Streams prepared");
rstream
.pipe(gunzip)
.pipe(hash)
.on("error", err => {
console.error("Error opening/gunzip/hash best-network.gz: " + err);
reject(err);
})
.on("finish", () => {
const best_network_hash = hash.read();
log_memory_stats("Streams completed: " + best_network_hash);
resolve(best_network_hash);
});
});
}
return best_network_hash_promise;
})
.catch(err => console.error(err));
}
const PESSIMISTIC_RATE = 0.4;
app.enable("trust proxy");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(/\/((?!submit-network).)*/, fileUpload());
app.use("/view/player", express.static("static/eidogo-player-1.2/player"));
app.use("/viewmatch/player", express.static("static/eidogo-player-1.2/player"));
app.use("/view/wgo", express.static("static/wgo"));
app.use("/viewmatch/wgo", express.static("static/wgo"));
app.use("/static", express.static("static", { maxage: "365d", etag: true }));
app.use('/networks',express.static('network'));
// This is async but we don't need it to start the server. I'm calling it during startup so it'll get the value cached right away
// instead of when the first /best-network request comes in, in case a lot of those requests come in at once when server
// starts up.
get_best_network_hash().then(hash => console.log("Current best hash " + hash));
setInterval(() => {
log_memory_stats("10 minute interval");
get_fast_clients()
.then()
.catch();
}, 1000 * 60 * 10);
let last_match_db_check = Date.now();
setInterval(() => {
const now = Date.now();
// In case we have no matches scheduled, we check the db.
//
if (pending_matches.length === 0 && now > last_match_db_check + 30 * 60 * 1000) {
console.log("No matches scheduled. Updating pending list.");
last_match_db_check = now;
get_pending_matches()
.then()
.catch();
}
}, 1000 * 60 * 1);
MongoClient.connect(MONGODB_URL, (err, database) => {
if (err) return console.log(err);
db = database;
db.collection("networks").count()
.then(count => {
console.log(count + " networks.");
});
db.collection("networks").aggregate([
{
$group: {
_id: {
type: {
$cond: {
if: { $in: ["$hash", ELF_NETWORKS] },
then: "ELF",
else: "LZ"
}
}
},
total: { $sum: "$game_count" }
}
}
], (err, res) => {
if (err) console.log(err);
get_fast_clients()
.then()
.catch();
get_pending_matches()
.then()
.catch();
res.forEach(result => {
if (result._id.type == "ELF")
elf_counter = result.total;
else
counter = result.total;
});
console.log(counter + " LZ games, " + elf_counter + " ELF games.");
app.listen(8080, () => {
console.log("listening on 8080");
});
// Listening to both ports while /next people are moving over to real server adddress
//
// app.listen(8081, () => {
// console.log('listening on 8081')
// });
});
});
// Obsolete
//
app.use("/best-network-hash", asyncMiddleware(async(req, res) => {
const hash = await get_best_network_hash();
res.write(hash);
res.write("\n");
// Can remove if autogtp no longer reads this. Required client and leelza versions are in get-task now.
res.write("11");
res.end();
}));
// Server will copy a new best-network to the proper location if validation testing of an uploaded network shows
// it is stronger than the prior network. So we don't need to worry about locking the file/etc when uploading to
// avoid an accidential download of a partial upload.
//
// This is no longer used, as /network/ is served by nginx and best-network.gz downloaded directly from it
//
app.use("/best-network", asyncMiddleware(async(req, res) => {
const hash = await get_best_network_hash();
const readStream = fs.createReadStream(__dirname + "/network/best-network.gz");
readStream.on("error", err => {
res.send("Error: " + err);
console.error("ERROR /best-network : " + err);
});
readStream.on("open", () => {
res.setHeader("Content-Disposition", "attachment; filename=" + hash + ".gz");
res.setHeader("Content-Transfer-Encoding", "binary");
res.setHeader("Content-Type", "application/octet-stream");
});
readStream.pipe(res);
console.log(req.ip + " (" + req.headers["x-real-ip"] + ") " + " downloaded /best-network");
}));
app.post("/request-match", (req, res) => {
// "number_to_play" : 400, "options" : { "playouts" : 1600, "resignation_percent" : 1, "randomcnt" : 0, "noise" : "false" }
if (!req.body.key || req.body.key != auth_key) {
console.log("AUTH FAIL: '" + String(req.body.key) + "' VS '" + String(auth_key) + "'");
return res.status(400).send("Incorrect key provided.");
}
if (!req.body.network1)
return res.status(400).send("No network1 hash specified.");
else if (!network_exists(req.body.network1))
return res.status(400).send("network1 hash not found.");
if (!req.body.network2)
req.body.network2 = null;
else if (!network_exists(req.body.network2))
return res.status(400).send("network2 hash not found.");
// TODO Need to support new --visits flag as an alternative to --playouts. Use visits if both are missing? Don't allow both to be set.
//
if (req.body.playouts && req.body.visits)
return res.status(400).send("Please set only playouts or visits, not both");
if (!req.body.playouts && !req.body.visits)
//req.body.playouts = 1600;
req.body.visits = 1600;
//return res.status(400).send('No playouts specified.');
if (!req.body.resignation_percent)
req.body.resignation_percent = 5;
//return res.status(400).send('No resignation_percent specified.');
if (!req.body.noise)
req.body.noise = false;
//return res.status(400).send('No noise specified.');
if (!req.body.randomcnt)
req.body.randomcnt = 0;
//return res.status(400).send('No randomcnt specified.');
if (!req.body.number_to_play)
req.body.number_to_play = 400;
//return res.status(400).send('No number_to_play specified.');
const options = { resignation_percent: Number(req.body.resignation_percent),
randomcnt: Number(req.body.randomcnt),
noise: String(req.body.noise) };
if (req.body.playouts) {
options.playouts = Number(req.body.playouts);
}
if (req.body.visits) {
options.visits = Number(req.body.visits);
}
// Usage:
// - schedule a Test match, set is_test=true or is_test=1
// curl -F is_test=true <other params>
//
// - schedule a Normal match, leave out the flag
// curl <other params>
//
req.body.is_test = ["true", "1"].includes(req.body.is_test);
const match = { network1: req.body.network1,
network2: req.body.network2, network1_losses: 0,
network1_wins: 0,
game_count: 0, number_to_play: Number(req.body.number_to_play),
is_test: req.body.is_test,
options, options_hash: get_options_hash(options) };
db.collection("matches").insertOne(match)
.then(() => {
// Update cache
dbutils.clear_matches_cache();
// Client only accepts strings for now
Object.keys(match.options).map(key => {
match.options[key] = String(match.options[key]);
});
match.requests = []; // init request list.
pending_matches.unshift(match);
console.log(req.ip + " (" + req.headers["x-real-ip"] + ") " + " Match added!");
res.send((match.is_test ? "Test" : "Regular") + " Match added!\n");
console.log("Pending is now: " + JSON.stringify(pending_matches));
})
.catch(err => {
console.error(req.ip + " (" + req.headers["x-real-ip"] + ") " + " ERROR: Match addition failed: " + err);
res.send("ERROR: Match addition failed\n");
});
});
// curl -F '[email protected]' -F 'training_count=175000' http://localhost:8080/submit-network
//
// Detect if network already exists and if so, inform the uploader and don't overwrite?
// So we don't think the network is newer than it really is. Actually, upsert shouldn't change
// the ObjectID so date will remain original insertion date.
//
app.post("/submit-network", asyncMiddleware((req, res) => {
log_memory_stats("submit network start");
const busboy = new Busboy({ headers: req.headers });
req.body = {};
let file_promise = null;
req.pipe(busboy).on("field", (name, value) => {
req.body[name] = value;
}).on("file", (name, file_stream, file_name) => {
if (!req.files)
req.files = {};
if (name != "weights") {
// Not the file we expected, flush the stream and do nothing
//
file_stream.on("readable", file_stream.read);
return;
}
const temp_file = path.join(os.tmpdir(), file_name);
// Pipes
// - file_stream.pipe(fs_stream)
// - file_stream.pipe(gunzip_stream)
// - gunzip_stream.pipe(hasher)
// - gunzip_stream.pipe(parser)
file_promise = new Promise((resolve, reject) => {
const fs_stream = file_stream.pipe(fs.createWriteStream(temp_file)).on("error", reject);
const gunzip_stream = file_stream.pipe(zlib.createGunzip()).on("error", reject);
Promise.all([
new Promise(resolve => {
fs_stream.on("finish", () => resolve({ path: fs_stream.path }));
}),
new Promise(resolve => {
const hasher = gunzip_stream.pipe(crypto.createHash("sha256")).on("finish", () => resolve({ hash: hasher.read().toString("hex") }));
}),
new Promise(resolve => {
const parser = gunzip_stream.pipe(new weight_parser()).on("finish", () => resolve(parser.read()));
})
]).then(results => {
// consolidate results
results = req.files[name] = Object.assign.apply(null, results);
// Move temp file to network folder with hash name
results.path = path.join(__dirname, "network", results.hash + ".gz");
if (fs.existsSync(temp_file))
fs.moveSync(temp_file, results.path, { overwrite: true });
// We are all done (hash, parse and save file)
resolve();
});
}).catch(err => {
console.error(err);
req.files[name] = { error: err };
// Clean up, flush stream and delete temp file
file_stream.on("readable", file_stream.read);
if (fs.existsSync(temp_file))
fs.removeSync(temp_file);
});
}).on("finish", async() => {
await file_promise;
if (!req.body.key || req.body.key != auth_key) {
console.log("AUTH FAIL: '" + String(req.body.key) + "' VS '" + String(auth_key) + "'");
return res.status(400).send("Incorrect key provided.");
}
if (!req.files || !req.files.weights)
return res.status(400).send("No weights file was uploaded.");
if (req.files.weights.error)
return res.status(400).send(req.files.weights.error.message);
const set = {
hash: req.files.weights.hash,
ip: req.ip,
training_count: +req.body.training_count || null,
training_steps: +req.body.training_steps || null,
filters: req.files.weights.filters,
blocks: req.files.weights.blocks,
description: req.body.description
};
// No training count given, we'll calculate it from database.
//
if (!set.training_count) {
const cursor = db.collection("networks").aggregate([{ $group: { _id: 1, count: { $sum: "$game_count" } } }]);
const totalgames = await cursor.next();
set.training_count = (totalgames ? totalgames.count : 0);
}
// Prepare variables for printing messages
//
const { blocks, filters, hash, training_count } = set;
db.collection("networks").updateOne(
{ hash: set.hash },
{ $set: set },
{ upsert: true },
(err, dbres) => {
if (err) {
res.end(err.message);
console.error(err);
} else {
const msg = "Network weights (" + blocks + " x " + filters + ") " + hash + " (" + training_count + ") " + (dbres.upsertedCount == 0 ? "exists" : "uploaded") + "!";
res.end(msg);
console.log(msg);
log_memory_stats("submit network ends");
}
}
);
});
}));
app.post("/submit-match", asyncMiddleware(async(req, res) => {
const logAndFail = msg => {
console.log(`${req.ip} (${req.headers["x-real-ip"]}) /submit-match: ${msg}`);
console.log(`files: ${JSON.stringify(Object.keys(req.files || {}))}, body: ${JSON.stringify(req.body)}`);
return res.status(400).send(msg);
};
if (!req.files)
return logAndFail("No files were uploaded.");
if (!req.files.sgf)
return logAndFail("No sgf file provided.");
if (!req.body.clientversion)
return logAndFail("No clientversion provided.");
if (!req.body.winnerhash)
return logAndFail("No winner hash provided.");
if (!req.body.loserhash)
return logAndFail("No loser hash provided.");
if (!req.body.winnercolor)
return logAndFail("No winnercolor provided.");
if (!req.body.movescount)
return logAndFail("No movescount provided.");
if (!req.body.score)
return logAndFail("No score provided.");
if (!req.body.options_hash)
return logAndFail("No options_hash provided.");
if (!req.body.random_seed)
return logAndFail("No random_seed provided.");
if (!check_match_verification(req.body))
return logAndFail("Verification failed.");
// Convert random_seed to Long, which is signed, after verifying the string
req.body.random_seed = Long.fromString(req.body.random_seed, 10);
req.body.task_time = get_timestamp_from_seed(req.body.random_seed);
// verify match exists in database
let match = await db.collection("matches").findOne(
{
$or: [
{ network1: req.body.winnerhash, network2: req.body.loserhash },
{ network2: req.body.winnerhash, network1: req.body.loserhash }
],
options_hash: req.body.options_hash
}
);
// Match not found, abort!!
if (!match)
return logAndFail("Match not found.");
// Verify random_seed for the match hasn't been used
if (await db.collection("match_games").findOne(
{
random_seed: req.body.random_seed,
$or: [
{ winnerhash: req.body.winnerhash, loserhash: req.body.loserhash },
{ loserhash: req.body.winnerhash, winnerhash: req.body.loserhash }
],
options_hash: req.body.options_hash
}
))
return logAndFail("Upload match with duplicate random_seed.");
// calculate sgfhash
try {
const sgfbuffer = await new Promise((resolve, reject) => zlib.unzip(req.files.sgf.data, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res);
}
}));
const sgfhash = checksum(sgfbuffer, "sha256");
// upload match game to database
const dbres = await db.collection("match_games").updateOne(
{ sgfhash },
{
$set: {
ip: req.ip, winnerhash: req.body.winnerhash, loserhash: req.body.loserhash, sgf: sgfbuffer.toString(),
options_hash: req.body.options_hash,
clientversion: Number(req.body.clientversion), winnercolor: req.body.winnercolor,
movescount: (req.body.movescount ? Number(req.body.movescount) : null),
score: req.body.score,
random_seed: req.body.random_seed
}
},
{ upsert: true }
);
// Not inserted, we got duplicate sgfhash, abort!
if (!dbres.upsertedId)
return logAndFail("Upload match with duplicate sgf.");
console.log(`${req.ip} (${req.headers["x-real-ip"]}) uploaded in ${Math.round(Date.now() / 1000 - req.body.task_time)}s match: ${sgfhash}`);
res.send("Match data " + sgfhash + " stored in database\n");
} catch (err) {
console.error(err);
return logAndFail("Error with sgf.");
}
// prepare $inc
const $inc = { game_count: 1 };
const is_network1_win = (match.network1 == req.body.winnerhash);
if (is_network1_win)
$inc.network1_wins = 1;
else
$inc.network1_losses = 1;
// save to database using $inc and get modified document
match = (await db.collection("matches").findOneAndUpdate(
{ _id: match._id },
{ $inc },
{ returnOriginal: false } // return modified document
)).value;
// get latest SPRT result
const sprt_result = SPRT(match.network1_wins, match.network1_losses);
const pending_match_index = pending_matches.findIndex(m => m._id.equals(match._id));
// match is found in pending_matches
if (pending_match_index >= 0) {
const m = pending_matches[pending_match_index];
if (sprt_result === false) {
// remove from pending matches
console.log("SPRT: Early fail pop: " + JSON.stringify(m));
pending_matches.splice(pending_match_index, 1);
console.log("SPRT: Early fail post-pop: " + JSON.stringify(pending_matches));
} else {
// remove the match from the requests array.
const index = m.requests.findIndex(e => e.seed === seed_from_mongolong(req.body.random_seed));
if (index !== -1) {
m.requests.splice(index, 1);
}
// update stats
m.game_count++;
if (m.network1 == req.body.winnerhash) {
m.network1_wins++;
} else {
m.network1_losses++;
}
if (sprt_result === true) {
console.log("SPRT: Early pass unshift: " + JSON.stringify(m));
pending_matches.splice(pending_match_index, 1); // cut out the match
if (m.game_count < m.number_to_play) pending_matches.unshift(m); // continue a SPRT pass at end of queue
console.log("SPRT: Early pass post-unshift: " + JSON.stringify(pending_matches));
}
}
}
// Lastly, promotion check!!
const best_network_hash = await get_best_network_hash();
if (
// Best network was being challenged
match.network2 == best_network_hash
// This is not a test match
&& !match.is_test
// SPRT passed OR it has reach 55% after 400 games (stick to the magic number)
&& (
sprt_result === true
|| (match.game_count >= 400 && match.network1_wins / match.game_count >= 0.55)
)) {
const promote_hash = match.network1;
const promote_file = `${__dirname}/network/${promote_hash}.gz`;
fs.copyFileSync(promote_file, __dirname + "/network/best-network.gz");
console.log(`New best network copied from ${promote_file}`);
discord.network_promotion_notify(promote_hash);
}
dbutils.update_matches_stats_cache(db, match._id, is_network1_win);
cachematches.clear(() => console.log("Cleared match cache."));
}));
// curl -F 'networkhash=abc123' -F '[email protected]' http://localhost:8080/submit
// curl -F 'networkhash=abc123' -F '[email protected]' -F '[email protected]' http://localhost:8080/submit
app.post("/submit", (req, res) => {
const logAndFail = msg => {
console.log(`${req.ip} (${req.headers["x-real-ip"]}) /submit: ${msg}`);
console.log(`files: ${JSON.stringify(Object.keys(req.files || {}))}, body: ${JSON.stringify(req.body)}`);
return res.status(400).send(msg);
};
if (!req.files)
return logAndFail("No files were uploaded.");
if (!req.files.sgf)
return logAndFail("No sgf file provided.");
if (!req.files.trainingdata)
return logAndFail("No trainingdata file provided.");
if (!req.body.clientversion)
return logAndFail("No clientversion provided.");
if (!req.body.networkhash)
return logAndFail("No network hash provided.");
if (!req.body.winnercolor)
return logAndFail("No winnercolor provided.");
if (!req.body.movescount)
return logAndFail("No movescount provided.");
if (!req.body.options_hash)
return logAndFail("No options_hash provided.");
if (!req.body.random_seed)
return logAndFail("No random_seed provided.");
req.body.random_seed = Long.fromString(req.body.random_seed, 10);
req.body.task_time = get_timestamp_from_seed(req.body.random_seed);
const clientversion = req.body.clientversion;
const networkhash = req.body.networkhash;
let trainingdatafile;
let sgffile;
let sgfhash;
const sgfbuffer = Buffer.from(req.files.sgf.data);
const trainbuffer = Buffer.from(req.files.trainingdata.data);
if (req.ip == "xxx") {
res.send("Game data " + sgfhash + " stored in database\n");
console.log("FAKE/SPAM reply sent to " + "xxx" + " (" + req.headers["x-real-ip"] + ")");
} else {
zlib.unzip(sgfbuffer, (err, sgfbuffer) => {
if (err) {
console.error(err);
return logAndFail("Error with sgf.");
} else {
sgffile = sgfbuffer.toString();
sgfhash = checksum(sgffile, "sha256");
zlib.unzip(trainbuffer, (err, trainbuffer) => {
if (err) {
console.error(err);
return logAndFail("Error with trainingdata.");
} else {
trainingdatafile = trainbuffer.toString();
db.collection("games").updateOne(
{ sgfhash },
{ $set: { ip: req.ip, networkhash, sgf: sgffile, options_hash: req.body.options_hash,
movescount: (req.body.movescount ? Number(req.body.movescount) : null),
data: trainingdatafile, clientversion: Number(clientversion),
winnercolor: req.body.winnercolor, random_seed: req.body.random_seed } },
{ upsert: true },
err => {
// Need to catch this better perhaps? Although an error here really is totally unexpected/critical.
//
if (err) {
console.log(req.ip + " (" + req.headers["x-real-ip"] + ") " + " uploaded game #" + counter + ": " + sgfhash + " ERROR: " + err);
res.send("Game data " + sgfhash + " stored in database\n");
} else {
let message = `in ${Math.round(Date.now() / 1000 - req.body.task_time)}s `;
if (ELF_NETWORKS.includes(networkhash)) {
elf_counter++;
message += `ELF game #${elf_counter}`;
} else {
counter++;
message += `LZ game #${counter}`;
}
console.log(`${req.ip} (${req.headers["x-real-ip"]}) uploaded ${message}: ${sgfhash}`);
res.send("Game data " + sgfhash + " stored in database\n");
}
}
);
db.collection("networks").updateOne(
{ hash: networkhash },
{ $inc: { game_count: 1 } },
{ },
err => {
if (err) {
if (ELF_NETWORKS.includes(networkhash))
console.log(req.ip + " (" + req.headers["x-real-ip"] + ") " + " uploaded ELF game #" + elf_counter + ": " + sgfhash + " INCREMENT ERROR: " + err);
else
console.log(req.ip + " (" + req.headers["x-real-ip"] + ") " + " uploaded LZ game #" + counter + ": " + sgfhash + " INCREMENT ERROR: " + err);
} else {
//console.log("Incremented " + networkhash);
}
}
);
}
});
}
});
}
});
app.get("/matches", asyncMiddleware(async(req, res) => {
const pug_data = {
matches: await dbutils.get_matches_from_cache(db)
};
res.render("matches", pug_data);
}));
app.get("/matches-all", asyncMiddleware(async(req, res) => {
const pug_data = {
matches: await dbutils.get_matches_from_db(db, { limit: 1000000 })
};
res.render("matches-all", pug_data);
}));
app.get("/network-profiles", asyncMiddleware(async(req, res) => {
const networks = await db.collection("networks")
.find({
hash: { $not: { $in: ELF_NETWORKS } },
$or: [
{ game_count: { $gt: 0 } },
{ hash: get_best_network_hash() }
]
})
.sort({ _id: -1 })
.toArray();
const pug_data = { networks, menu: "network-profiles" };
pug_data.networks.forEach(network => {
network.time = network._id.getTimestamp().getTime();
});
res.render("networks/index", pug_data);
}));
app.get("/network-profiles/:hash(\\w+)", asyncMiddleware(async(req, res) => {
const network = await db.collection("networks")
.findOne({ hash: req.params.hash });
if (!network) {
return res.status(404).render("404");
}
// If it's one of the best network, then find it's #
if ((network.game_count > 0 || network.hash == get_best_network_hash()) && !ELF_NETWORKS.includes(network.hash)) {
network.networkID = await db.collection("networks")
.count({
_id: { $lt: network._id },
game_count: { $gt: 0 },
hash: { $not: { $in: ELF_NETWORKS } }
});
}
// Prepare Avatar