| 1 | package net.minecraft.util.profiling.jfr;
|
| 2 |
|
| 3 | import com.mojang.logging.LogUtils;
|
| 4 | import java.io.BufferedReader;
|
| 5 | import java.io.IOException;
|
| 6 | import java.io.InputStreamReader;
|
| 7 | import java.io.Reader;
|
| 8 | import java.net.SocketAddress;
|
| 9 | import java.net.URL;
|
| 10 | import java.nio.charset.StandardCharsets;
|
| 11 | import java.nio.file.Path;
|
| 12 | import java.nio.file.Paths;
|
| 13 | import java.text.ParseException;
|
| 14 | import java.time.Instant;
|
| 15 | import java.time.ZoneId;
|
| 16 | import java.time.format.DateTimeFormatter;
|
| 17 | import java.time.format.DateTimeFormatterBuilder;
|
| 18 | import java.util.Iterator;
|
| 19 | import java.util.List;
|
| 20 | import java.util.Locale;
|
| 21 | import java.util.Map;
|
| 22 | import java.util.concurrent.ConcurrentHashMap;
|
| 23 | import jdk.jfr.Configuration;
|
| 24 | import jdk.jfr.Event;
|
| 25 | import jdk.jfr.FlightRecorder;
|
| 26 | import jdk.jfr.FlightRecorderListener;
|
| 27 | import jdk.jfr.Recording;
|
| 28 | import net.minecraft.SharedConstants;
|
| 29 | import net.minecraft.core.Holder;
|
| 30 | import net.minecraft.network.ConnectionProtocol;
|
| 31 | import net.minecraft.network.protocol.PacketType;
|
| 32 | import net.minecraft.resources.ResourceKey;
|
| 33 | import net.minecraft.util.FileUtil;
|
| 34 | import net.minecraft.util.Util;
|
| 35 | import net.minecraft.util.profiling.jfr.callback.ProfiledDuration;
|
| 36 | import net.minecraft.util.profiling.jfr.event.ChunkGenerationEvent;
|
| 37 | import net.minecraft.util.profiling.jfr.event.ChunkRegionReadEvent;
|
| 38 | import net.minecraft.util.profiling.jfr.event.ChunkRegionWriteEvent;
|
| 39 | import net.minecraft.util.profiling.jfr.event.ClientFpsEvent;
|
| 40 | import net.minecraft.util.profiling.jfr.event.NetworkSummaryEvent;
|
| 41 | import net.minecraft.util.profiling.jfr.event.PacketReceivedEvent;
|
| 42 | import net.minecraft.util.profiling.jfr.event.PacketSentEvent;
|
| 43 | import net.minecraft.util.profiling.jfr.event.ServerTickTimeEvent;
|
| 44 | import net.minecraft.util.profiling.jfr.event.StructureGenerationEvent;
|
| 45 | import net.minecraft.util.profiling.jfr.event.WorldLoadFinishedEvent;
|
| 46 | import net.minecraft.world.level.ChunkPos;
|
| 47 | import net.minecraft.world.level.Level;
|
| 48 | import net.minecraft.world.level.chunk.storage.RegionFileVersion;
|
| 49 | import net.minecraft.world.level.chunk.storage.RegionStorageInfo;
|
| 50 | import net.minecraft.world.level.levelgen.structure.Structure;
|
| 51 | import org.jspecify.annotations.Nullable;
|
| 52 | import org.slf4j.Logger;
|
| 53 |
|
| 54 | public class JfrProfiler implements JvmProfiler {
|
| 55 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 56 | public static final String ROOT_CATEGORY = "Minecraft";
|
| 57 | public static final String WORLD_GEN_CATEGORY = "World Generation";
|
| 58 | public static final String TICK_CATEGORY = "Ticking";
|
| 59 | public static final String NETWORK_CATEGORY = "Network";
|
| 60 | public static final String STORAGE_CATEGORY = "Storage";
|
| 61 | private static final List<Class<? extends Event>> CUSTOM_EVENTS = List.of(
|
| 62 | ChunkGenerationEvent.class,
|
| 63 | ChunkRegionReadEvent.class,
|
| 64 | ChunkRegionWriteEvent.class,
|
| 65 | PacketReceivedEvent.class,
|
| 66 | PacketSentEvent.class,
|
| 67 | NetworkSummaryEvent.class,
|
| 68 | ServerTickTimeEvent.class,
|
| 69 | ClientFpsEvent.class,
|
| 70 | StructureGenerationEvent.class,
|
| 71 | WorldLoadFinishedEvent.class
|
| 72 | );
|
| 73 | private static final String FLIGHT_RECORDER_CONFIG = "/flightrecorder-config.jfc";
|
| 74 | private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
|
| 75 | .appendPattern("yyyy-MM-dd-HHmmss")
|
| 76 | .toFormatter(Locale.ROOT)
|
| 77 | .withZone(ZoneId.systemDefault());
|
| 78 | private static final JfrProfiler INSTANCE = new JfrProfiler();
|
| 79 | private @Nullable Recording recording;
|
| 80 | private int currentFPS;
|
| 81 | private float currentAverageTickTimeServer;
|
| 82 | private final Map<String, NetworkSummaryEvent.SumAggregation> networkTrafficByAddress = new ConcurrentHashMap<>();
|
| 83 | private final Runnable periodicClientFps = () -> new ClientFpsEvent(this.currentFPS).commit();
|
| 84 | private final Runnable periodicServerTickTime = () -> new ServerTickTimeEvent(this.currentAverageTickTimeServer).commit();
|
| 85 | private final Runnable periodicNetworkSummary = () -> {
|
| 86 | Iterator<NetworkSummaryEvent.SumAggregation> iterator = this.networkTrafficByAddress.values().iterator();
|
| 87 |
|
| 88 | while (iterator.hasNext()) {
|
| 89 | iterator.next().commitEvent();
|
| 90 | iterator.remove();
|
| 91 | }
|
| 92 | };
|
| 93 |
|
| 94 | private JfrProfiler() {
|
| 95 | CUSTOM_EVENTS.forEach(FlightRecorder::register);
|
| 96 | this.registerPeriodicEvents();
|
| 97 | FlightRecorder.addListener(new FlightRecorderListener() {
|
| 98 | @Override
|
| 99 | public void recordingStateChanged(final Recording rec) {
|
| 100 | switch (rec.getState()) {
|
| 101 | case STOPPED:
|
| 102 | JfrProfiler.this.registerPeriodicEvents();
|
| 103 | case NEW:
|
| 104 | case DELAYED:
|
| 105 | case RUNNING:
|
| 106 | case CLOSED:
|
| 107 | }
|
| 108 | }
|
| 109 | });
|
| 110 | }
|
| 111 |
|
| 112 | private void registerPeriodicEvents() {
|
| 113 | addPeriodicEvent(ClientFpsEvent.class, this.periodicClientFps);
|
| 114 | addPeriodicEvent(ServerTickTimeEvent.class, this.periodicServerTickTime);
|
| 115 | addPeriodicEvent(NetworkSummaryEvent.class, this.periodicNetworkSummary);
|
| 116 | }
|
| 117 |
|
| 118 | private static void addPeriodicEvent(final Class<? extends Event> eventClass, final Runnable runnable) {
|
| 119 | FlightRecorder.removePeriodicEvent(runnable);
|
| 120 | FlightRecorder.addPeriodicEvent(eventClass, runnable);
|
| 121 | }
|
| 122 |
|
| 123 | public static JfrProfiler getInstance() {
|
| 124 | return INSTANCE;
|
| 125 | }
|
| 126 |
|
| 127 | @Override
|
| 128 | public boolean start(final Environment environment) {
|
| 129 | URL resource = JfrProfiler.class.getResource("/flightrecorder-config.jfc");
|
| 130 | if (resource == null) {
|
| 131 | LOGGER.warn("Could not find default flight recorder config at {}", "/flightrecorder-config.jfc");
|
| 132 | return false;
|
| 133 | }
|
| 134 |
|
| 135 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.openStream(), StandardCharsets.UTF_8))) {
|
| 136 | return this.start(reader, environment);
|
| 137 | } catch (IOException e) {
|
| 138 | LOGGER.warn("Failed to start flight recorder using configuration at {}", resource, e);
|
| 139 | return false;
|
| 140 | }
|
| 141 | }
|
| 142 |
|
| 143 | @Override
|
| 144 | public Path stop() {
|
| 145 | if (this.recording == null) {
|
| 146 | throw new IllegalStateException("Not currently profiling");
|
| 147 | }
|
| 148 |
|
| 149 | this.networkTrafficByAddress.clear();
|
| 150 | Path report = this.recording.getDestination();
|
| 151 | this.recording.stop();
|
| 152 | return report;
|
| 153 | }
|
| 154 |
|
| 155 | @Override
|
| 156 | public boolean isRunning() {
|
| 157 | return this.recording != null;
|
| 158 | }
|
| 159 |
|
| 160 | @Override
|
| 161 | public boolean isAvailable() {
|
| 162 | return FlightRecorder.isAvailable();
|
| 163 | }
|
| 164 |
|
| 165 | private boolean start(final Reader configurationFile, final Environment environment) {
|
| 166 | if (this.isRunning()) {
|
| 167 | LOGGER.warn("Profiling already in progress");
|
| 168 | return false;
|
| 169 | }
|
| 170 |
|
| 171 | try {
|
| 172 | Configuration jfrConfig = Configuration.create(configurationFile);
|
| 173 | String startTimestamp = DATE_TIME_FORMATTER.format(Instant.now());
|
| 174 | this.recording = Util.make(new Recording(jfrConfig), self -> {
|
| 175 | CUSTOM_EVENTS.forEach(self::enable);
|
| 176 | self.setDumpOnExit(true);
|
| 177 | self.setToDisk(true);
|
| 178 | self.setName(String.format(Locale.ROOT, "%s-%s-%s", environment.getDescription(), SharedConstants.getCurrentVersion().name(), startTimestamp));
|
| 179 | });
|
| 180 | Path destination = Paths.get(String.format(Locale.ROOT, "debug/%s-%s.jfr", environment.getDescription(), startTimestamp));
|
| 181 | FileUtil.createDirectoriesSafe(destination.getParent());
|
| 182 | this.recording.setDestination(destination);
|
| 183 | this.recording.start();
|
| 184 | this.setupSummaryListener();
|
| 185 | } catch (IOException | ParseException exception) {
|
| 186 | LOGGER.warn("Failed to start jfr profiling", exception);
|
| 187 | return false;
|
| 188 | }
|
| 189 |
|
| 190 | LOGGER.info(
|
| 191 | "Started flight recorder profiling id({}):name({}) - will dump to {} on exit or stop command",
|
| 192 | this.recording.getId(),
|
| 193 | this.recording.getName(),
|
| 194 | this.recording.getDestination()
|
| 195 | );
|
| 196 | return true;
|
| 197 | }
|
| 198 |
|
| 199 | private void setupSummaryListener() {
|
| 200 | FlightRecorder.addListener(new FlightRecorderListener() {
|
| 201 | private final SummaryReporter summaryReporter = new SummaryReporter(() -> JfrProfiler.this.recording = null);
|
| 202 |
|
| 203 | @Override
|
| 204 | public void recordingStateChanged(final Recording rec) {
|
| 205 | if (rec == JfrProfiler.this.recording) {
|
| 206 | switch (rec.getState()) {
|
| 207 | case STOPPED:
|
| 208 | this.summaryReporter.recordingStopped(rec.getDestination());
|
| 209 | FlightRecorder.removeListener(this);
|
| 210 | case NEW:
|
| 211 | case DELAYED:
|
| 212 | case RUNNING:
|
| 213 | case CLOSED:
|
| 214 | }
|
| 215 | }
|
| 216 | }
|
| 217 | });
|
| 218 | }
|
| 219 |
|
| 220 | @Override
|
| 221 | public void onClientTick(final int fps) {
|
| 222 | if (ClientFpsEvent.TYPE.isEnabled()) {
|
| 223 | this.currentFPS = fps;
|
| 224 | }
|
| 225 | }
|
| 226 |
|
| 227 | @Override
|
| 228 | public void onServerTick(final float currentAverageTickTime) {
|
| 229 | if (ServerTickTimeEvent.TYPE.isEnabled()) {
|
| 230 | this.currentAverageTickTimeServer = currentAverageTickTime;
|
| 231 | }
|
| 232 | }
|
| 233 |
|
| 234 | @Override
|
| 235 | public void onPacketReceived(final ConnectionProtocol protocol, final PacketType<?> packetId, final SocketAddress remoteAddress, final int readableBytes) {
|
| 236 | if (PacketReceivedEvent.TYPE.isEnabled()) {
|
| 237 | new PacketReceivedEvent(protocol.id(), packetId.flow().id(), packetId.id().toString(), remoteAddress, readableBytes).commit();
|
| 238 | }
|
| 239 |
|
| 240 | if (NetworkSummaryEvent.TYPE.isEnabled()) {
|
| 241 | this.networkStatFor(remoteAddress).trackReceivedPacket(readableBytes);
|
| 242 | }
|
| 243 | }
|
| 244 |
|
| 245 | @Override
|
| 246 | public void onPacketSent(final ConnectionProtocol protocol, final PacketType<?> packetId, final SocketAddress remoteAddress, final int writtenBytes) {
|
| 247 | if (PacketSentEvent.TYPE.isEnabled()) {
|
| 248 | new PacketSentEvent(protocol.id(), packetId.flow().id(), packetId.id().toString(), remoteAddress, writtenBytes).commit();
|
| 249 | }
|
| 250 |
|
| 251 | if (NetworkSummaryEvent.TYPE.isEnabled()) {
|
| 252 | this.networkStatFor(remoteAddress).trackSentPacket(writtenBytes);
|
| 253 | }
|
| 254 | }
|
| 255 |
|
| 256 | private NetworkSummaryEvent.SumAggregation networkStatFor(final SocketAddress remoteAddress) {
|
| 257 | return this.networkTrafficByAddress.computeIfAbsent(remoteAddress.toString(), NetworkSummaryEvent.SumAggregation::new);
|
| 258 | }
|
| 259 |
|
| 260 | @Override
|
| 261 | public void onRegionFileRead(final RegionStorageInfo info, final ChunkPos pos, final RegionFileVersion version, final int readBytes) {
|
| 262 | if (ChunkRegionReadEvent.TYPE.isEnabled()) {
|
| 263 | new ChunkRegionReadEvent(info, pos, version, readBytes).commit();
|
| 264 | }
|
| 265 | }
|
| 266 |
|
| 267 | @Override
|
| 268 | public void onRegionFileWrite(final RegionStorageInfo info, final ChunkPos pos, final RegionFileVersion version, final int writtenBytes) {
|
| 269 | if (ChunkRegionWriteEvent.TYPE.isEnabled()) {
|
| 270 | new ChunkRegionWriteEvent(info, pos, version, writtenBytes).commit();
|
| 271 | }
|
| 272 | }
|
| 273 |
|
| 274 | @Override
|
| 275 | public @Nullable ProfiledDuration onWorldLoadedStarted() {
|
| 276 | if (!WorldLoadFinishedEvent.TYPE.isEnabled()) {
|
| 277 | return null;
|
| 278 | }
|
| 279 |
|
| 280 | WorldLoadFinishedEvent event = new WorldLoadFinishedEvent();
|
| 281 | event.begin();
|
| 282 | return ignored -> event.commit();
|
| 283 | }
|
| 284 |
|
| 285 | @Override
|
| 286 | public @Nullable ProfiledDuration onChunkGenerate(final ChunkPos pos, final ResourceKey<Level> dimension, final String name) {
|
| 287 | if (!ChunkGenerationEvent.TYPE.isEnabled()) {
|
| 288 | return null;
|
| 289 | }
|
| 290 |
|
| 291 | ChunkGenerationEvent event = new ChunkGenerationEvent(pos, dimension, name);
|
| 292 | event.begin();
|
| 293 | return ignored -> event.commit();
|
| 294 | }
|
| 295 |
|
| 296 | @Override
|
| 297 | public @Nullable ProfiledDuration onStructureGenerate(final ChunkPos sourceChunkPos, final ResourceKey<Level> dimension, final Holder<Structure> structure) {
|
| 298 | if (!StructureGenerationEvent.TYPE.isEnabled()) {
|
| 299 | return null;
|
| 300 | }
|
| 301 |
|
| 302 | StructureGenerationEvent event = new StructureGenerationEvent(sourceChunkPos, structure, dimension);
|
| 303 | event.begin();
|
| 304 | return success -> {
|
| 305 | event.success = success;
|
| 306 | event.commit();
|
| 307 | };
|
| 308 | }
|
| 309 | }
|
| 310 |
|