| 1 | package net.minecraft.server.commands;
|
| 2 |
|
| 3 | import com.mojang.brigadier.CommandDispatcher;
|
| 4 | import com.mojang.brigadier.context.CommandContext;
|
| 5 | import com.mojang.brigadier.context.ContextChain;
|
| 6 | import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
| 7 | import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
|
| 8 | import com.mojang.logging.LogUtils;
|
| 9 | import java.io.IOException;
|
| 10 | import java.io.PrintWriter;
|
| 11 | import java.io.UncheckedIOException;
|
| 12 | import java.nio.charset.StandardCharsets;
|
| 13 | import java.nio.file.Files;
|
| 14 | import java.nio.file.Path;
|
| 15 | import java.util.Collection;
|
| 16 | import java.util.Locale;
|
| 17 | import net.minecraft.commands.CommandResultCallback;
|
| 18 | import net.minecraft.commands.CommandSource;
|
| 19 | import net.minecraft.commands.CommandSourceStack;
|
| 20 | import net.minecraft.commands.Commands;
|
| 21 | import net.minecraft.commands.FunctionInstantiationException;
|
| 22 | import net.minecraft.commands.arguments.item.FunctionArgument;
|
| 23 | import net.minecraft.commands.execution.ChainModifiers;
|
| 24 | import net.minecraft.commands.execution.CustomCommandExecutor;
|
| 25 | import net.minecraft.commands.execution.ExecutionContext;
|
| 26 | import net.minecraft.commands.execution.ExecutionControl;
|
| 27 | import net.minecraft.commands.execution.Frame;
|
| 28 | import net.minecraft.commands.execution.TraceCallbacks;
|
| 29 | import net.minecraft.commands.execution.tasks.CallFunction;
|
| 30 | import net.minecraft.commands.functions.CommandFunction;
|
| 31 | import net.minecraft.commands.functions.InstantiatedFunction;
|
| 32 | import net.minecraft.network.chat.Component;
|
| 33 | import net.minecraft.resources.Identifier;
|
| 34 | import net.minecraft.server.MinecraftServer;
|
| 35 | import net.minecraft.server.permissions.LevelBasedPermissionSet;
|
| 36 | import net.minecraft.util.TimeUtil;
|
| 37 | import net.minecraft.util.Util;
|
| 38 | import net.minecraft.util.profiling.ProfileResults;
|
| 39 | import org.apache.commons.io.IOUtils;
|
| 40 | import org.slf4j.Logger;
|
| 41 |
|
| 42 | public class DebugCommand {
|
| 43 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 44 | private static final SimpleCommandExceptionType ERROR_NOT_RUNNING = new SimpleCommandExceptionType(Component.translatable("commands.debug.notRunning"));
|
| 45 | private static final SimpleCommandExceptionType ERROR_ALREADY_RUNNING = new SimpleCommandExceptionType(Component.translatable("commands.debug.alreadyRunning"));
|
| 46 | private static final SimpleCommandExceptionType NO_RECURSIVE_TRACES = new SimpleCommandExceptionType(
|
| 47 | Component.translatable("commands.debug.function.noRecursion")
|
| 48 | );
|
| 49 | private static final SimpleCommandExceptionType NO_RETURN_RUN = new SimpleCommandExceptionType(Component.translatable("commands.debug.function.noReturnRun"));
|
| 50 |
|
| 51 | public static void register(final CommandDispatcher<CommandSourceStack> dispatcher) {
|
| 52 | dispatcher.register(
|
| 53 | Commands.literal("debug")
|
| 54 | .requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
| 55 | .then(Commands.literal("start").executes(c -> start(c.getSource())))
|
| 56 | .then(Commands.literal("stop").executes(c -> stop(c.getSource())))
|
| 57 | .then(
|
| 58 | Commands.literal("function")
|
| 59 | .requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
|
| 60 | .then(Commands.argument("name", FunctionArgument.functions()).suggests(FunctionCommand.SUGGEST_FUNCTION).executes(new DebugCommand.TraceCustomExecutor()))
|
| 61 | )
|
| 62 | );
|
| 63 | }
|
| 64 |
|
| 65 | private static int start(final CommandSourceStack source) throws CommandSyntaxException {
|
| 66 | MinecraftServer server = source.getServer();
|
| 67 | if (server.isTimeProfilerRunning()) {
|
| 68 | throw ERROR_ALREADY_RUNNING.create();
|
| 69 | }
|
| 70 |
|
| 71 | server.startTimeProfiler();
|
| 72 | source.sendSuccess(() -> Component.translatable("commands.debug.started"), true);
|
| 73 | return 0;
|
| 74 | }
|
| 75 |
|
| 76 | private static int stop(final CommandSourceStack source) throws CommandSyntaxException {
|
| 77 | MinecraftServer server = source.getServer();
|
| 78 | if (!server.isTimeProfilerRunning()) {
|
| 79 | throw ERROR_NOT_RUNNING.create();
|
| 80 | }
|
| 81 |
|
| 82 | ProfileResults results = server.stopTimeProfiler();
|
| 83 | double seconds = (double)results.getNanoDuration() / TimeUtil.NANOSECONDS_PER_SECOND;
|
| 84 | double tps = results.getTickDuration() / seconds;
|
| 85 | source.sendSuccess(
|
| 86 | () -> Component.translatable(
|
| 87 | "commands.debug.stopped", String.format(Locale.ROOT, "%.2f", seconds), results.getTickDuration(), String.format(Locale.ROOT, "%.2f", tps)
|
| 88 | ),
|
| 89 | true
|
| 90 | );
|
| 91 | return (int)tps;
|
| 92 | }
|
| 93 |
|
| 94 | private static class TraceCustomExecutor
|
| 95 | extends CustomCommandExecutor.WithErrorHandling<CommandSourceStack>
|
| 96 | implements CustomCommandExecutor.CommandAdapter<CommandSourceStack> {
|
| 97 | private static final CommandResponseTracker.DispatchWithArg<Component, CommandFunction<CommandSourceStack>, String> RESPONSE_TRACE = new CommandResponseTracker.DispatchWithArg<>(
|
| 98 | (function, totalValue, outputName) -> Component.translatable(
|
| 99 | "commands.debug.function.success.single", totalValue, Component.translationArg(function.id()), outputName
|
| 100 | ),
|
| 101 | (functionCount, totalValue, outputName) -> Component.translatable("commands.debug.function.success.multiple", totalValue, functionCount, outputName)
|
| 102 | );
|
| 103 |
|
| 104 | public void runGuarded(
|
| 105 | final CommandSourceStack source,
|
| 106 | final ContextChain<CommandSourceStack> currentStep,
|
| 107 | final ChainModifiers modifiers,
|
| 108 | final ExecutionControl<CommandSourceStack> context
|
| 109 | ) throws CommandSyntaxException {
|
| 110 | if (modifiers.isReturn()) {
|
| 111 | throw DebugCommand.NO_RETURN_RUN.create();
|
| 112 | }
|
| 113 |
|
| 114 | if (context.tracer() != null) {
|
| 115 | throw DebugCommand.NO_RECURSIVE_TRACES.create();
|
| 116 | }
|
| 117 |
|
| 118 | CommandContext<CommandSourceStack> currentContext = currentStep.getTopContext();
|
| 119 | Collection<CommandFunction<CommandSourceStack>> functions = FunctionArgument.getFunctions(currentContext, "name");
|
| 120 | MinecraftServer server = source.getServer();
|
| 121 | String outputName = "debug-trace-" + Util.getFilenameFormattedDateTime() + ".txt";
|
| 122 | CommandDispatcher<CommandSourceStack> dispatcher = source.getServer().getFunctions().getDispatcher();
|
| 123 | CommandResponseTracker<CommandFunction<CommandSourceStack>> tracker = CommandResponseTracker.create();
|
| 124 |
|
| 125 | try {
|
| 126 | Path dirPath = server.getFile("debug");
|
| 127 | Files.createDirectories(dirPath);
|
| 128 | final PrintWriter output = new PrintWriter(Files.newBufferedWriter(dirPath.resolve(outputName), StandardCharsets.UTF_8));
|
| 129 | DebugCommand.Tracer tracer = new DebugCommand.Tracer(output);
|
| 130 | context.tracer(tracer);
|
| 131 |
|
| 132 | for (final CommandFunction<CommandSourceStack> function : functions) {
|
| 133 | try {
|
| 134 | CommandSourceStack functionSource = source.withSource(tracer).withMaximumPermission(LevelBasedPermissionSet.GAMEMASTER);
|
| 135 | InstantiatedFunction<CommandSourceStack> instantiatedFunction = function.instantiate(null, dispatcher);
|
| 136 | context.queueNext((new CallFunction<CommandSourceStack>(instantiatedFunction, CommandResultCallback.EMPTY, false) {
|
| 137 | public void execute(final CommandSourceStack sender, final ExecutionContext<CommandSourceStack> contextx, final Frame frame) {
|
| 138 | output.println(function.id());
|
| 139 | super.execute(sender, contextx, frame);
|
| 140 | }
|
| 141 | }).bind(functionSource));
|
| 142 | tracker.track(function, instantiatedFunction.entries().size());
|
| 143 | } catch (FunctionInstantiationException exception) {
|
| 144 | source.sendFailure(exception.messageComponent());
|
| 145 | }
|
| 146 | }
|
| 147 | } catch (UncheckedIOException | IOException e) {
|
| 148 | DebugCommand.LOGGER.warn("Tracing failed", e);
|
| 149 | source.sendFailure(Component.translatable("commands.debug.function.traceFailed"));
|
| 150 | }
|
| 151 |
|
| 152 | context.queueNext((var3, var4) -> source.sendSuccess(() -> tracker.dispatch(CommandResponseTracker.ElementType.ANY, RESPONSE_TRACE, outputName), true));
|
| 153 | }
|
| 154 | }
|
| 155 |
|
| 156 | private static class Tracer implements CommandSource, TraceCallbacks {
|
| 157 | public static final int INDENT_OFFSET = 1;
|
| 158 | private final PrintWriter output;
|
| 159 | private int lastIndent;
|
| 160 | private boolean waitingForResult;
|
| 161 |
|
| 162 | private Tracer(final PrintWriter output) {
|
| 163 | this.output = output;
|
| 164 | }
|
| 165 |
|
| 166 | private void indentAndSave(final int value) {
|
| 167 | this.printIndent(value);
|
| 168 | this.lastIndent = value;
|
| 169 | }
|
| 170 |
|
| 171 | private void printIndent(final int value) {
|
| 172 | for (int i = 0; i < value + 1; i++) {
|
| 173 | this.output.write(" ");
|
| 174 | }
|
| 175 | }
|
| 176 |
|
| 177 | private void newLine() {
|
| 178 | if (this.waitingForResult) {
|
| 179 | this.output.println();
|
| 180 | this.waitingForResult = false;
|
| 181 | }
|
| 182 | }
|
| 183 |
|
| 184 | @Override
|
| 185 | public void onCommand(final int depth, final String command) {
|
| 186 | this.newLine();
|
| 187 | this.indentAndSave(depth);
|
| 188 | this.output.print("[C] ");
|
| 189 | this.output.print(command);
|
| 190 | this.waitingForResult = true;
|
| 191 | }
|
| 192 |
|
| 193 | @Override
|
| 194 | public void onReturn(final int depth, final String command, final int result) {
|
| 195 | if (this.waitingForResult) {
|
| 196 | this.output.print(" -> ");
|
| 197 | this.output.println(result);
|
| 198 | this.waitingForResult = false;
|
| 199 | } else {
|
| 200 | this.indentAndSave(depth);
|
| 201 | this.output.print("[R = ");
|
| 202 | this.output.print(result);
|
| 203 | this.output.print("] ");
|
| 204 | this.output.println(command);
|
| 205 | }
|
| 206 | }
|
| 207 |
|
| 208 | @Override
|
| 209 | public void onCall(final int depth, final Identifier function, final int size) {
|
| 210 | this.newLine();
|
| 211 | this.indentAndSave(depth);
|
| 212 | this.output.print("[F] ");
|
| 213 | this.output.print(function);
|
| 214 | this.output.print(" size=");
|
| 215 | this.output.println(size);
|
| 216 | }
|
| 217 |
|
| 218 | @Override
|
| 219 | public void onError(final String message) {
|
| 220 | this.newLine();
|
| 221 | this.indentAndSave(this.lastIndent + 1);
|
| 222 | this.output.print("[E] ");
|
| 223 | this.output.print(message);
|
| 224 | }
|
| 225 |
|
| 226 | @Override
|
| 227 | public void sendSystemMessage(final Component message) {
|
| 228 | this.newLine();
|
| 229 | this.printIndent(this.lastIndent + 1);
|
| 230 | this.output.print("[M] ");
|
| 231 | this.output.println(message.getString());
|
| 232 | }
|
| 233 |
|
| 234 | @Override
|
| 235 | public boolean acceptsSuccess() {
|
| 236 | return true;
|
| 237 | }
|
| 238 |
|
| 239 | @Override
|
| 240 | public boolean acceptsFailure() {
|
| 241 | return true;
|
| 242 | }
|
| 243 |
|
| 244 | @Override
|
| 245 | public boolean shouldInformAdmins() {
|
| 246 | return false;
|
| 247 | }
|
| 248 |
|
| 249 | @Override
|
| 250 | public boolean alwaysAccepts() {
|
| 251 | return true;
|
| 252 | }
|
| 253 |
|
| 254 | @Override
|
| 255 | public void close() {
|
| 256 | IOUtils.closeQuietly(this.output);
|
| 257 | }
|
| 258 | }
|
| 259 | }
|
| 260 |
|