This repository was archived by the owner on Jan 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathMinecraftServer.java
1727 lines (1443 loc) · 49.9 KB
/
MinecraftServer.java
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
package net.minecraft.server;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.security.KeyPair;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import javax.imageio.ImageIO;
import ga.windpvp.windspigot.random.FastRandom;
import io.papermc.paper.util.linkedqueue.CachedSizeConcurrentLinkedQueue;
import org.apache.commons.lang3.Validate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bukkit.craftbukkit.Main;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.GameProfileRepository;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import co.aikar.timings.SpigotTimings; // Spigot
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufOutputStream;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.base64.Base64;
import io.netty.util.ResourceLeakDetector;
// CraftBukkit start
import jline.console.ConsoleReader;
import joptsimple.OptionSet;
// CraftBukkit end
// NachoSpigot start
import xyz.sculas.nacho.async.AsyncExplosions;
// NachoSpigot end
// WindSpigot start
import net.openhft.affinity.AffinityLock;
import ga.windpvp.windspigot.WindSpigot;
import ga.windpvp.windspigot.config.WindSpigotConfig;
import ga.windpvp.windspigot.statistics.StatisticsClient;
import ga.windpvp.windspigot.tickloop.ReentrantIAsyncHandler;
import ga.windpvp.windspigot.tickloop.TasksPerTick;
import ga.windpvp.windspigot.world.WorldTickManager;
// WindSpigot end
public abstract class MinecraftServer extends ReentrantIAsyncHandler<TasksPerTick> implements ICommandListener, IAsyncTaskHandler, IMojangStatistics {
public static final Logger LOGGER = LogManager.getLogger();
public static final File a = new File("usercache.json");
private static MinecraftServer l;
public Convertable convertable;
private final MojangStatisticsGenerator n = new MojangStatisticsGenerator("server", this, az());
public File universe;
private final List<IUpdatePlayerListBox> p = Lists.newArrayList();
protected final ICommandHandler b;
public final MethodProfiler methodProfiler = new MethodProfiler();
private ServerConnection q; // Spigot
private final ServerPing r = new ServerPing();
private final Random s = new FastRandom();
private String serverIp;
private int u = -1;
public int getServerPort() {
return u;
} // Nacho - OBFHELPER
public WorldServer[] worldServer;
private PlayerList v;
private boolean isRunning = true;
private boolean isStopped;
private int ticks;
protected final Proxy e;
public String f;
public int g;
private boolean onlineMode;
private boolean spawnAnimals;
private boolean spawnNPCs;
private boolean pvpMode;
private boolean allowFlight;
private String motd;
private int F;
private int G = 0;
public final long[] h = new long[100];
public long[][] i;
private KeyPair H;
private String I;
private String J;
private boolean demoMode;
private boolean N;
private String O = "";
private String P = "";
private boolean Q;
private long R;
private String S;
private boolean T;
private boolean U;
private final YggdrasilAuthenticationService V;
private final MinecraftSessionService W;
private long X = 0L;
private final GameProfileRepository Y;
private final UserCache Z;
protected final Queue<FutureTask<?>> j = new CachedSizeConcurrentLinkedQueue<>(); // Spigot, PAIL: Rename // Paper - Make size() constant-time
private Thread serverThread;
private long ab = az();
// CraftBukkit start
public List<WorldServer> worlds = Lists.newCopyOnWriteArrayList();
public org.bukkit.craftbukkit.CraftServer server;
public OptionSet options;
public org.bukkit.command.ConsoleCommandSender console;
public org.bukkit.command.RemoteConsoleCommandSender remoteConsole;
public ConsoleReader reader;
public static int currentTick = 0; // PaperSpigot - Further improve tick loop
public final Thread primaryThread;
public java.util.Queue<Runnable> processQueue = new java.util.concurrent.ConcurrentLinkedQueue<Runnable>();
public java.util.Queue<Runnable> priorityProcessQueue = new java.util.concurrent.ConcurrentLinkedQueue<Runnable>(); // WindSpigot
public int autosavePeriod;
// CraftBukkit end
// WindSpigot - instance
protected WindSpigot windSpigot;
// WindSpigot - MSPT for tps command
private double lastMspt;
// WindSpigot start - backport modern tick loop
private long nextTickTime;
private long delayedTasksMaxNextTickTime;
private boolean mayHaveDelayedTasks;
private boolean forceTicks;
private volatile boolean isReady;
private long lastOverloadWarning;
public long serverStartTime;
public volatile Thread shutdownThread; // Paper
public static <S extends MinecraftServer> S spin(Function<Thread, S> serverFactory) {
AtomicReference<S> reference = new AtomicReference<>();
Thread thread = new Thread(() -> reference.get().run(), "Server thread");
thread.setUncaughtExceptionHandler((thread1, throwable) -> MinecraftServer.LOGGER.error(throwable));
S server = serverFactory.apply(thread); // CraftBukkit - decompile error
reference.set(server);
thread.setPriority(Thread.NORM_PRIORITY + 2); // Paper - boost priority
thread.start();
return server;
}
// WindSpigot end
public MinecraftServer(OptionSet options, Proxy proxy, File file1, Thread thread) {
super("Server"); // WindSpigot - backport modern tick loop
io.netty.util.ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED); // [Nacho-0040] Change
// deprecated Netty
// parameter // Spigot -
// disable
this.e = proxy;
MinecraftServer.l = this;
// this.universe = file; // CraftBukkit
// this.q = new ServerConnection(this); // Spigot
this.Z = new UserCache(this, file1);
this.b = this.h();
// this.convertable = new WorldLoaderServer(file); // CraftBukkit - moved to
// DedicatedServer.init
this.V = new YggdrasilAuthenticationService(proxy, UUID.randomUUID().toString());
this.W = this.V.createMinecraftSessionService();
this.Y = this.V.createProfileRepository();
// WindSpigot start - backport modern tick loop
this.nextTickTime = getMillis();
this.serverThread = thread;
this.primaryThread = thread;
// WindSpigot end
// CraftBukkit start
this.options = options;
// Try to see if we're actually running in a terminal, disable jline if not
if (System.console() == null && System.getProperty("jline.terminal") == null) {
System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
Main.useJline = false;
}
try {
reader = new ConsoleReader(System.in, System.out);
reader.setExpandEvents(false); // Avoid parsing exceptions for uncommonly used event designators
} catch (Throwable e) {
try {
// Try again with jline disabled for Windows users without C++ 2008
// Redistributable
System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
System.setProperty("user.language", "en");
Main.useJline = false;
reader = new ConsoleReader(System.in, System.out);
reader.setExpandEvents(false);
} catch (IOException ex) {
LOGGER.warn((String) null, ex);
}
}
Runtime.getRuntime().addShutdownHook(new org.bukkit.craftbukkit.util.ServerShutdownThread(this));
}
public abstract PropertyManager getPropertyManager();
// CraftBukkit end
protected CommandDispatcher h() {
return new CommandDispatcher();
}
protected abstract boolean init() throws IOException;
protected void a(String s) {
if (this.getConvertable().isConvertable(s)) {
MinecraftServer.LOGGER.info("Converting map!");
this.b("menu.convertingLevel");
this.getConvertable().convert(s, new IProgressUpdate() {
private long b = System.currentTimeMillis();
@Override
public void a(String s) {
}
@Override
public void a(int i) {
if (System.currentTimeMillis() - this.b >= 1000L) {
this.b = System.currentTimeMillis();
MinecraftServer.LOGGER.info("Converting... " + i + "%");
}
}
@Override
public void c(String s) {
}
});
}
}
protected synchronized void b(String s) {
this.S = s;
}
protected void a(String s, String s1, long i, WorldType worldtype, String s2) {
this.a(s);
this.b("menu.loadingLevel");
this.worldServer = new WorldServer[3];
/*
* CraftBukkit start - Remove ticktime arrays and worldsettings this.i = new
* long[this.worldServer.length][100]; IDataManager idatamanager =
* this.convertable.a(s, true);
*
* this.a(this.U(), idatamanager); WorldData worlddata =
* idatamanager.getWorldData(); WorldSettings worldsettings;
*
* if (worlddata == null) { if (this.X()) { worldsettings = DemoWorldServer.a; }
* else { worldsettings = new WorldSettings(i, this.getGamemode(),
* this.getGenerateStructures(), this.isHardcore(), worldtype);
* worldsettings.setGeneratorSettings(s2); if (this.M) { worldsettings.a(); } }
*
* worlddata = new WorldData(worldsettings, s1); } else { worlddata.a(s1);
* worldsettings = new WorldSettings(worlddata); }
*/
int worldCount = 3;
for (int j = 0; j < worldCount; ++j) {
WorldServer world;
byte dimension = 0;
if (j == 1) {
if (getAllowNether()) {
dimension = -1;
} else {
continue;
}
}
if (j == 2) {
if (server.getAllowEnd()) {
dimension = 1;
} else {
continue;
}
}
String worldType = org.bukkit.World.Environment.getEnvironment(dimension).toString().toLowerCase();
String name = (dimension == 0) ? s : s + "_" + worldType;
org.bukkit.generator.ChunkGenerator gen = this.server.getGenerator(name);
WorldSettings worldsettings = new WorldSettings(i, this.getGamemode(), this.getGenerateStructures(),
this.isHardcore(), worldtype);
worldsettings.setGeneratorSettings(s2);
if (j == 0) {
IDataManager idatamanager = new ServerNBTManager(server.getWorldContainer(), s1, true);
WorldData worlddata = idatamanager.getWorldData();
if (worlddata == null) {
worlddata = new WorldData(worldsettings, s1);
}
worlddata.checkName(s1); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to
// take the last loaded world as respawn (in this case the end)
if (this.X()) {
world = (WorldServer) (new DemoWorldServer(this, idatamanager, worlddata, dimension,
this.methodProfiler)).b();
} else {
world = (WorldServer) (new WorldServer(this, idatamanager, worlddata, dimension,
this.methodProfiler, org.bukkit.World.Environment.getEnvironment(dimension), gen)).b();
}
world.a(worldsettings);
this.server.scoreboardManager = new org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager(this,
world.getScoreboard());
} else {
String dim = "DIM" + dimension;
File newWorld = new File(new File(name), dim);
File oldWorld = new File(new File(s), dim);
if ((!newWorld.isDirectory()) && (oldWorld.isDirectory())) {
MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder required ----");
MinecraftServer.LOGGER.info(
"Unfortunately due to the way that Minecraft implemented multiworld support in 1.6, Bukkit requires that you move your "
+ worldType + " folder to a new location in order to operate correctly.");
MinecraftServer.LOGGER.info(
"We will move this folder for you, but it will mean that you need to move it back should you wish to stop using Bukkit in the future.");
MinecraftServer.LOGGER.info("Attempting to move " + oldWorld + " to " + newWorld + "...");
if (newWorld.exists()) {
MinecraftServer.LOGGER.warn("A file or folder already exists at " + newWorld + "!");
MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
} else if (newWorld.getParentFile().mkdirs()) {
if (oldWorld.renameTo(newWorld)) {
MinecraftServer.LOGGER.info("Success! To restore " + worldType
+ " in the future, simply move " + newWorld + " to " + oldWorld);
// Migrate world data too.
try {
com.google.common.io.Files.copy(new File(new File(s), "level.dat"),
new File(new File(name), "level.dat"));
} catch (IOException exception) {
MinecraftServer.LOGGER.warn("Unable to migrate world data.");
}
MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder complete ----");
} else {
MinecraftServer.LOGGER.warn("Could not move folder " + oldWorld + " to " + newWorld + "!");
MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
}
} else {
MinecraftServer.LOGGER.warn("Could not create path for " + newWorld + "!");
MinecraftServer.LOGGER.info("---- Migration of old " + worldType + " folder failed ----");
}
}
IDataManager idatamanager = new ServerNBTManager(server.getWorldContainer(), name, true);
// world =, b0 to dimension, s1 to name, added Environment and gen
WorldData worlddata = idatamanager.getWorldData();
if (worlddata == null) {
worlddata = new WorldData(worldsettings, name);
}
worlddata.checkName(name); // CraftBukkit - Migration did not rewrite the level.dat; This forces 1.8 to
// take the last loaded world as respawn (in this case the end)
world = (WorldServer) new SecondaryWorldServer(this, idatamanager, dimension, this.worlds.get(0),
this.methodProfiler, worlddata, org.bukkit.World.Environment.getEnvironment(dimension), gen)
.b();
}
this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldInitEvent(world.getWorld()));
world.addIWorldAccess(new WorldManager(this, world));
if (!this.T()) {
world.getWorldData().setGameType(this.getGamemode());
}
worlds.add(world);
getPlayerList().setPlayerFileData(worlds.toArray(new WorldServer[worlds.size()]));
}
// CraftBukkit end
this.a(this.getDifficulty());
this.k();
}
protected void k() {
this.b("menu.generatingTerrain");
// CraftBukkit start - fire WorldLoadEvent and handle whether or not to keep the
// spawn in memory
for (int m = 0; m < worlds.size(); m++) {
WorldServer worldserver = this.worlds.get(m);
LOGGER.info("Preparing start region for level " + m + " (Seed: " + worldserver.getSeed() + ")");
if (!worldserver.getWorld().getKeepSpawnInMemory()) {
continue;
}
BlockPosition blockposition = worldserver.getSpawn();
long j = az();
int i = 0;
for (int k = -192; k <= 192 && this.isRunning(); k += 16) {
for (int l = -192; l <= 192 && this.isRunning(); l += 16) {
long i1 = az();
if (i1 - j > 1000L) {
this.a_("Preparing spawn area", i * 100 / 625);
j = i1;
}
++i;
worldserver.chunkProviderServer.getChunkAt(blockposition.getX() + k >> 4,
blockposition.getZ() + l >> 4);
}
}
}
for (WorldServer world : this.worlds) {
this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldLoadEvent(world.getWorld()));
}
// CraftBukkit end
this.s();
}
protected void a(String s, IDataManager idatamanager) {
File file = new File(idatamanager.getDirectory(), "resources.zip");
if (file.isFile()) {
this.setResourcePack("level://" + s + "/" + file.getName(), "");
}
}
public abstract boolean getGenerateStructures();
public abstract WorldSettings.EnumGamemode getGamemode();
public abstract EnumDifficulty getDifficulty();
public abstract boolean isHardcore();
public abstract int p();
public abstract boolean q();
public abstract boolean r();
protected void a_(String s, int i) {
this.f = s;
this.g = i;
MinecraftServer.LOGGER.info(s + ": " + i + "%");
}
protected void s() {
this.f = null;
this.g = 0;
this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD); // CraftBukkit
}
protected void saveChunks(boolean flag) throws ExceptionWorldConflict { // CraftBukkit - added throws
if (!this.N) {
WorldServer[] aworldserver = this.worldServer;
int i = aworldserver.length;
// CraftBukkit start
for (int j = 0; j < worlds.size(); ++j) {
WorldServer worldserver = worlds.get(j);
// CraftBukkit end
if (worldserver != null) {
if (!flag) {
MinecraftServer.LOGGER.info("Saving chunks for level \'" + worldserver.getWorldData().getName()
+ "\'/" + worldserver.worldProvider.getName());
}
try {
worldserver.save(true, (IProgressUpdate) null);
worldserver.saveLevel(); // CraftBukkit
} catch (ExceptionWorldConflict exceptionworldconflict) {
MinecraftServer.LOGGER.warn(exceptionworldconflict.getMessage());
}
}
}
}
}
// CraftBukkit start
private boolean hasStopped = false;
private final Object stopLock = new Object();
// CraftBukkit end
public void stop() throws ExceptionWorldConflict, InterruptedException { // CraftBukkit - added throws
// CraftBukkit start - prevent double
// stopping on multiple threads
synchronized (stopLock) {
if (hasStopped) {
return;
}
hasStopped = true;
}
// CraftBukkit end
if (!this.N) {
MinecraftServer.LOGGER.info("Stopping server");
SpigotTimings.stopServer(); // Spigot
// CraftBukkit start
if (this.server != null) {
this.server.disablePlugins();
}
// CraftBukkit end
if (this.aq() != null) {
this.aq().stopServer();
}
if (this.v != null) {
MinecraftServer.LOGGER.info("Saving players");
this.v.savePlayers();
this.v.u();
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
} // CraftBukkit - SPIGOT-625 - give server at least a chance to send packets
}
if (this.worldServer != null) {
MinecraftServer.LOGGER.info("Saving worlds");
this.saveChunks(false);
/*
* CraftBukkit start - Handled in saveChunks for (int i = 0; i <
* this.worldServer.length; ++i) { WorldServer worldserver =
* this.worldServer[i];
*
* worldserver.saveLevel(); } // CraftBukkit end
*/
}
if (this.n.d()) {
this.n.e();
}
// Spigot start
if (org.spigotmc.SpigotConfig.saveUserCacheOnStopOnly) {
LOGGER.info("Saving usercache.json");
this.Z.c();
}
// Spigot end
AsyncExplosions.stopExecutor(); // Nacho
}
}
public String getServerIp() {
return this.serverIp;
}
public void c(String s) {
this.serverIp = s;
}
public boolean isRunning() {
return this.isRunning;
}
public void safeShutdown() {
this.isRunning = false;
}
// Paper start - Further improve server tick loop
private static final int TPS = 20;
private static final long SEC_IN_NANO = 1000000000;
private static final long TICK_TIME = SEC_IN_NANO / TPS;
private static final long MAX_CATCHUP_BUFFER = TICK_TIME * TPS * 60L;
// WindSpigot start - backport modern tick loop
private long lastTick = 0;
private long catchupTime = 0;
// WindSpigot end
private static final int SAMPLE_INTERVAL = 20;
public final RollingAverage tps1 = new RollingAverage(60);
public final RollingAverage tps5 = new RollingAverage(60 * 5);
public final RollingAverage tps15 = new RollingAverage(60 * 15);
public double[] recentTps = new double[3]; // PaperSpigot - Fine have your darn compat with bad plugins
public static class RollingAverage {
private final int size;
private long time;
private java.math.BigDecimal total;
private int index = 0;
private final java.math.BigDecimal[] samples;
private final long[] times;
RollingAverage(int size) {
this.size = size;
this.time = size * SEC_IN_NANO;
this.total = dec(TPS).multiply(dec(SEC_IN_NANO)).multiply(dec(size));
this.samples = new java.math.BigDecimal[size];
this.times = new long[size];
for (int i = 0; i < size; i++) {
this.samples[i] = dec(TPS);
this.times[i] = SEC_IN_NANO;
}
}
private static java.math.BigDecimal dec(long t) {
return new java.math.BigDecimal(t);
}
public void add(java.math.BigDecimal x, long t) {
time -= times[index];
total = total.subtract(samples[index].multiply(dec(times[index])));
samples[index] = x;
times[index] = t;
time += t;
total = total.add(x.multiply(dec(t)));
if (++index == size) {
index = 0;
}
}
public double getAverage() {
return total.divide(dec(time), 30, java.math.RoundingMode.HALF_UP).doubleValue();
}
}
private static final java.math.BigDecimal TPS_BASE = new java.math.BigDecimal(1E9).multiply(new java.math.BigDecimal(SAMPLE_INTERVAL));
// Paper End
private AffinityLock lock = null;
// WindSpigot - thread affinity
public AffinityLock getLock() {
return this.lock;
}
public void run() {
// Don't disable statistics if server failed to start
boolean disableStatistics = false;
try {
serverStartTime = getNanos(); // Paper
if (this.init()) {
//WindSpigot - statistics
disableStatistics = true;
// WindSpigot start - implement thread affinity
if (WindSpigotConfig.threadAffinity) {
LOGGER.info(" ");
LOGGER.info("Enabling Thread Affinity...");
lock = AffinityLock.acquireLock();
if (lock.cpuId() != -1) {
LOGGER.info("CPU " + lock.cpuId() + " locked for server usage.");
LOGGER.info("This will boost the server's performance if configured properly.");
LOGGER.info("If not it will most likely decrease performance.");
LOGGER.info(
"See https://github.com/OpenHFT/Java-Thread-Affinity#isolcpus for configuration!");
LOGGER.info(" ");
} else {
LOGGER.error("An error occured whilst enabling thread affinity!");
LOGGER.error(" ");
}
WindSpigot.debug(AffinityLock.dumpLocks());
}
// WindSpigot end
// WindSpigot - parallel worlds
this.worldTickerManager = new WorldTickManager();
this.ab = az();
this.r.setMOTD(new ChatComponentText(this.motd));
this.r.setServerInfo(new ServerPing.ServerData("1.8.8", 47));
this.a(this.r);
// Spigot start
// PaperSpigot start - Further improve tick loop
Arrays.fill(recentTps, 20);
long start = System.nanoTime(), curTime, tickSection = start; // Paper - Further improve server tick loop
lastTick = start - TICK_TIME;
// PaperSpigot end
while (this.isRunning) {
long i = ((curTime = System.nanoTime()) / (1000L * 1000L)) - this.nextTickTime; // Paper
if (i > 5000L && this.nextTickTime - this.lastOverloadWarning >= 30000L && ticks > 500) { // CraftBukkit // WindSpigot - prevent display of overload on first 500 ticks
long j = i / 50L;
if (this.server.getWarnOnOverload()) // CraftBukkit
MinecraftServer.LOGGER.warn("Can't keep up! Is the server overloaded? Running {}ms or {} ticks behind", i, j);
this.nextTickTime += j * 50L;
this.lastOverloadWarning = this.nextTickTime;
}
if (++MinecraftServer.currentTick % MinecraftServer.SAMPLE_INTERVAL == 0) {
final long diff = curTime - tickSection;
//double currentTps = 1E9 / diff * SAMPLE_INTERVAL;
java.math.BigDecimal currentTps = TPS_BASE.divide(new java.math.BigDecimal(diff), 30, java.math.RoundingMode.HALF_UP);
tps1.add(currentTps, diff);
tps5.add(currentTps, diff);
tps15.add(currentTps, diff);
// Backwards compat with bad plugins
recentTps[0] = tps1.getAverage();
recentTps[1] = tps5.getAverage();
recentTps[2] = tps15.getAverage();
tickSection = curTime;
// PaperSpigot end
}
lastTick = curTime;
this.nextTickTime += 50L;
this.methodProfiler.a("tick"); // push
this.A(this::haveTime);
this.methodProfiler.c("nextTickWait"); // popPush
this.mayHaveDelayedTasks = true;
this.delayedTasksMaxNextTickTime = Math.max(getMillis() + 50L, this.nextTickTime);
this.waitUntilNextTick();
this.methodProfiler.b(); // pop
this.isReady = true;
}
// Spigot end
} else {
this.a((CrashReport) null);
}
} catch (Throwable throwable) {
MinecraftServer.LOGGER.error("Encountered an unexpected exception", throwable);
// Spigot Start
if (throwable.getCause() != null) {
MinecraftServer.LOGGER.error("\tCause of unexpected exception was", throwable.getCause());
}
// Spigot End
CrashReport crashreport = null;
if (throwable instanceof ReportedException) {
crashreport = this.b(((ReportedException) throwable).a());
} else {
crashreport = this.b(new CrashReport("Exception in server tick loop", throwable));
}
File file = new File(new File(this.y(), "crash-reports"),
"crash-" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + "-server.txt");
if (crashreport.a(file)) {
MinecraftServer.LOGGER.error("This crash report has been saved to: " + file.getAbsolutePath());
} else {
MinecraftServer.LOGGER.error("We were unable to save this crash report to disk.");
}
this.a(crashreport);
} finally {
// WindSpigot start - thread affinity
if (lock != null) {
lock.release();
MinecraftServer.LOGGER.info("Released CPU " + lock.cpuId() + " from server usage.");
}
// WindSpigot end
// WindSpigot start - stop statistics connection
Thread statisticsThread = null;
if (disableStatistics) {
StatisticsClient client = this.getWindSpigot().getClient();
if (client != null && client.isConnected) {
Runnable runnable = (() -> {
try {
// Signal that there is one less server
client.sendMessage("removed server");
// This tells the server to stop listening for messages from this client
client.sendMessage(".");
client.stop();
} catch (IOException e) {
e.printStackTrace();
}
});
statisticsThread = new Thread(runnable);
statisticsThread.start();
}
}
// WindSpigot end
try {
org.spigotmc.WatchdogThread.doStop();
this.isStopped = true;
this.stop();
} catch (Throwable throwable1) {
MinecraftServer.LOGGER.error("Exception stopping the server", throwable1);
} finally {
// CraftBukkit start - Restore terminal to original settings
try {
reader.getTerminal().restore();
} catch (Exception ignored) {
}
// CraftBukkit end
this.z();
}
// WindSpigot - wait for statistics to finish stopping
try {
if (this.getWindSpigot().getClient().isConnected) {
statisticsThread.join(1500);
}
} catch (Throwable ignored) {
}
}
}
// WindSpigot start - backport modern tick loop
private boolean haveTime() {
// CraftBukkit start
if (isOversleep) return canOversleep();// Paper - because of our changes, this logic is broken
return this.forceTicks || this.runningTask() || getMillis() < (this.mayHaveDelayedTasks ? this.delayedTasksMaxNextTickTime : this.nextTickTime);
}
// Paper start
boolean isOversleep = false;
private boolean canOversleep() {
return this.mayHaveDelayedTasks && getMillis() < this.delayedTasksMaxNextTickTime;
}
private boolean canSleepForTickNoOversleep() {
return this.forceTicks || this.runningTask() || getMillis() < this.nextTickTime;
}
// Paper end
private void executeModerately() {
this.runAllRunnable();
LockSupport.parkNanos("executing tasks", 1000L);
}
// CraftBukkit end
protected void waitUntilNextTick() {
this.controlTerminate(() -> !this.canSleepForTickNoOversleep());
}
@Override
protected TasksPerTick packUpRunnable(Runnable runnable) {
// Paper start - anything that does try to post to main during watchdog crash, run on watchdog
if (this.hasStopped && Thread.currentThread().equals(shutdownThread)) {
runnable.run();
runnable = () -> {};
}
// Paper end
return new TasksPerTick(this.ticks, runnable);
}
@Override
protected boolean shouldRun(TasksPerTick task) {
return task.getTick() + 3 < this.ticks || this.haveTime();
}
@Override
public boolean drawRunnable() {
boolean flag = this.pollTaskInternal();
this.mayHaveDelayedTasks = flag;
return flag;
}
// TODO: WorldServer ticker
private boolean pollTaskInternal() {
if (super.drawRunnable()) {
return true;
} else {
if (this.haveTime()) {
// for (WorldServer worldserver : this.worldServer) {
// if (worldserver.chunkProviderServer.pollTask()) {
// return true;
// }
// }
}
return false;
}
}
@Override
public Thread getMainThread() {
return serverThread;
}
// WindSpigot end
private void a(ServerPing serverping) {
File file = this.d("server-icon.png");
if (file.isFile()) {
ByteBuf bytebuf = Unpooled.buffer();
ByteBuf bytebuf1 = null; // Paper - cleanup favicon bytebuf
try {
BufferedImage bufferedimage = ImageIO.read(file);
Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
ImageIO.write(bufferedimage, "PNG", new ByteBufOutputStream(bytebuf));
/* ByteBuf */ bytebuf1 = Base64.encode(bytebuf); // Paper - cleanup favicon bytebuf
serverping.setFavicon("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8));
} catch (Exception exception) {
MinecraftServer.LOGGER.error("Couldn\'t load server icon", exception);
} finally {
bytebuf.release();
// Paper start - cleanup favicon bytebuf
if (bytebuf1 != null) {
bytebuf1.release();
}
// Paper end - cleanup favicon bytebuf
}
}
}
public File y() {
return new File(".");
}
protected void a(CrashReport crashreport) {
}
protected void z() {
}
// WindSpigot - backport modern tick loop
protected void A(BooleanSupplier shouldKeepTicking) throws ExceptionWorldConflict { // CraftBukkit - added throws
co.aikar.timings.TimingsManager.FULL_SERVER_TICK.startTiming(); // Spigot
// WindSpigot start - backport modern tick loop
long i = getNanos();
// Paper start - move oversleep into full server tick
isOversleep = true;
this.controlTerminate(() -> !this.canOversleep());
isOversleep = false;
// Paper end
this.server.getPluginManager().callEvent(new com.destroystokyo.paper.event.server.ServerTickStartEvent(this.ticks+1)); // Paper
// WindSpigot end
++this.ticks;
if (this.T) {
this.T = false;
this.methodProfiler.a = true;
this.methodProfiler.a();
}
this.methodProfiler.a("root");
this.B();
if (i - this.X >= 5000000000L) {
this.X = i;
this.r.setPlayerSample(new ServerPing.ServerPingPlayerSample(this.J(), this.I()));
GameProfile[] agameprofile = new GameProfile[Math.min(this.I(), 12)];
int j = MathHelper.nextInt(this.s, 0, this.I() - agameprofile.length);
for (int k = 0; k < agameprofile.length; ++k) {
agameprofile[k] = this.v.v().get(j + k).getProfile();
}
Collections.shuffle(Arrays.asList(agameprofile));
this.r.b().a(agameprofile);
}
if (autosavePeriod > 0 && this.ticks % autosavePeriod == 0) { // CraftBukkit
SpigotTimings.worldSaveTimer.startTiming(); // Spigot
this.methodProfiler.a("save");
this.v.savePlayers();
// Spigot Start
// We replace this with saving each individual world as this.saveChunks(...) is
// broken,
// and causes the main thread to sleep for random amounts of time depending on
// chunk activity
// Also pass flag to only save modified chunks
server.playerCommandState = true;
for (World world : worlds) {
world.getWorld().save(false);
}
server.playerCommandState = false;
// this.saveChunks(true);
// Spigot End
this.methodProfiler.b();
SpigotTimings.worldSaveTimer.stopTiming(); // Spigot
}
// WindSpigot start - backport modern tick loop
// Paper start
long endTime = System.nanoTime();
long remaining = (TICK_TIME - (endTime - lastTick)) - catchupTime;
this.lastMspt = ((double) (endTime - lastTick) / 1000000D);
this.server.getPluginManager().callEvent(new com.destroystokyo.paper.event.server.ServerTickEndEvent(this.ticks, this.lastMspt, remaining));
// Paper end
// WindSpigot end