| 1 | package net.minecraft.util.profiling.metrics.storage;
|
| 2 |
|
| 3 | import com.mojang.logging.LogUtils;
|
| 4 | import java.io.IOException;
|
| 5 | import java.io.UncheckedIOException;
|
| 6 | import java.io.Writer;
|
| 7 | import java.nio.charset.StandardCharsets;
|
| 8 | import java.nio.file.Files;
|
| 9 | import java.nio.file.Path;
|
| 10 | import java.nio.file.Paths;
|
| 11 | import java.time.ZoneId;
|
| 12 | import java.time.format.DateTimeFormatter;
|
| 13 | import java.util.List;
|
| 14 | import java.util.Locale;
|
| 15 | import java.util.Map;
|
| 16 | import java.util.Set;
|
| 17 | import java.util.stream.Collectors;
|
| 18 | import java.util.stream.Stream;
|
| 19 | import net.minecraft.resources.Identifier;
|
| 20 | import net.minecraft.util.CsvOutput;
|
| 21 | import net.minecraft.util.Util;
|
| 22 | import net.minecraft.util.profiling.ProfileResults;
|
| 23 | import net.minecraft.util.profiling.metrics.MetricCategory;
|
| 24 | import net.minecraft.util.profiling.metrics.MetricSampler;
|
| 25 | import org.apache.commons.io.IOUtils;
|
| 26 | import org.slf4j.Logger;
|
| 27 |
|
| 28 | public class MetricsPersister {
|
| 29 | public static final Path PROFILING_RESULTS_DIR = Paths.get("debug/profiling");
|
| 30 | public static final String METRICS_DIR_NAME = "metrics";
|
| 31 | public static final String DEVIATIONS_DIR_NAME = "deviations";
|
| 32 | public static final String PROFILING_RESULT_FILENAME = "profiling.txt";
|
| 33 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 34 | private final String rootFolderName;
|
| 35 |
|
| 36 | public MetricsPersister(final String rootFolderName) {
|
| 37 | this.rootFolderName = rootFolderName;
|
| 38 | }
|
| 39 |
|
| 40 | public Path saveReports(
|
| 41 | final Set<MetricSampler> samplers, final Map<MetricSampler, List<RecordedDeviation>> deviationsBySampler, final ProfileResults profilerResults
|
| 42 | ) {
|
| 43 | try {
|
| 44 | Files.createDirectories(PROFILING_RESULTS_DIR);
|
| 45 | } catch (IOException e) {
|
| 46 | throw new UncheckedIOException(e);
|
| 47 | }
|
| 48 |
|
| 49 | try {
|
| 50 | Path tempDir = Files.createTempDirectory("minecraft-profiling");
|
| 51 | tempDir.toFile().deleteOnExit();
|
| 52 | Files.createDirectories(PROFILING_RESULTS_DIR);
|
| 53 | Path workingDir = tempDir.resolve(this.rootFolderName);
|
| 54 | Path metricsDir = workingDir.resolve("metrics");
|
| 55 | this.saveMetrics(samplers, metricsDir);
|
| 56 | if (!deviationsBySampler.isEmpty()) {
|
| 57 | this.saveDeviations(deviationsBySampler, workingDir.resolve("deviations"));
|
| 58 | }
|
| 59 |
|
| 60 | this.saveProfilingTaskExecutionResult(profilerResults, workingDir);
|
| 61 | return tempDir;
|
| 62 | } catch (IOException e) {
|
| 63 | throw new UncheckedIOException(e);
|
| 64 | }
|
| 65 | }
|
| 66 |
|
| 67 | private void saveMetrics(final Set<MetricSampler> samplers, final Path dir) {
|
| 68 | if (samplers.isEmpty()) {
|
| 69 | throw new IllegalArgumentException("Expected at least one sampler to persist");
|
| 70 | }
|
| 71 |
|
| 72 | Map<MetricCategory, List<MetricSampler>> samplersByCategory = samplers.stream().collect(Collectors.groupingBy(MetricSampler::getCategory));
|
| 73 | samplersByCategory.forEach((category, samplersInCategory) -> this.saveCategory(category, (List<MetricSampler>)samplersInCategory, dir));
|
| 74 | }
|
| 75 |
|
| 76 | private void saveCategory(final MetricCategory category, final List<MetricSampler> samplers, final Path dir) {
|
| 77 | Path file = dir.resolve(Util.sanitizeName(category.getDescription(), Identifier::validPathChar) + ".csv");
|
| 78 | Writer writer = null;
|
| 79 |
|
| 80 | try {
|
| 81 | Files.createDirectories(file.getParent());
|
| 82 | writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8);
|
| 83 | CsvOutput.Builder csvBuilder = CsvOutput.builder();
|
| 84 | csvBuilder.addColumn("@tick");
|
| 85 |
|
| 86 | for (MetricSampler sampler : samplers) {
|
| 87 | csvBuilder.addColumn(sampler.getName());
|
| 88 | }
|
| 89 |
|
| 90 | CsvOutput csvOutput = csvBuilder.build(writer);
|
| 91 | List<MetricSampler.SamplerResult> results = samplers.stream().map(MetricSampler::result).collect(Collectors.toList());
|
| 92 | int firstTick = results.stream().mapToInt(MetricSampler.SamplerResult::getFirstTick).summaryStatistics().getMin();
|
| 93 | int lastTick = results.stream().mapToInt(MetricSampler.SamplerResult::getLastTick).summaryStatistics().getMax();
|
| 94 |
|
| 95 | for (int tick = firstTick; tick <= lastTick; tick++) {
|
| 96 | int finalTick = tick;
|
| 97 | Stream<String> valuesStream = results.stream().map(it -> String.valueOf(it.valueAtTick(finalTick)));
|
| 98 | Object[] row = Stream.concat(Stream.of(String.valueOf(tick)), valuesStream).toArray(String[]::new);
|
| 99 | csvOutput.writeRow(row);
|
| 100 | }
|
| 101 |
|
| 102 | LOGGER.info("Flushed metrics to {}", file);
|
| 103 | } catch (Exception e) {
|
| 104 | LOGGER.error("Could not save profiler results to {}", file, e);
|
| 105 | } finally {
|
| 106 | IOUtils.closeQuietly(writer);
|
| 107 | }
|
| 108 | }
|
| 109 |
|
| 110 | private void saveDeviations(final Map<MetricSampler, List<RecordedDeviation>> deviationsBySampler, final Path directory) {
|
| 111 | DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH.mm.ss.SSS", Locale.UK).withZone(ZoneId.systemDefault());
|
| 112 | deviationsBySampler.forEach(
|
| 113 | (sampler, deviations) -> deviations.forEach(
|
| 114 | deviation -> {
|
| 115 | String timestamp = formatter.format(deviation.timestamp);
|
| 116 | Path deviationLogFile = directory.resolve(Util.sanitizeName(sampler.getName(), Identifier::validPathChar))
|
| 117 | .resolve(String.format(Locale.ROOT, "%d@%s.txt", deviation.tick, timestamp));
|
| 118 | deviation.profilerResultAtTick.saveResults(deviationLogFile);
|
| 119 | }
|
| 120 | )
|
| 121 | );
|
| 122 | }
|
| 123 |
|
| 124 | private void saveProfilingTaskExecutionResult(final ProfileResults results, final Path directory) {
|
| 125 | results.saveResults(directory.resolve("profiling.txt"));
|
| 126 | }
|
| 127 | }
|
| 128 |
|