|
| 1 | +package com.javadiscord.bot.commands.slash; |
| 2 | + |
| 3 | +import java.awt.*; |
| 4 | +import java.io.OutputStream; |
| 5 | +import java.time.Instant; |
| 6 | +import java.util.Optional; |
| 7 | +import java.util.concurrent.Executors; |
| 8 | +import java.util.concurrent.ScheduledExecutorService; |
| 9 | +import java.util.concurrent.ThreadLocalRandom; |
| 10 | +import java.util.concurrent.TimeUnit; |
| 11 | + |
| 12 | +import com.javadiscord.bot.utils.docker.*; |
| 13 | +import com.javadiscord.jdi.core.CommandOptionType; |
| 14 | +import com.javadiscord.jdi.core.annotations.CommandOption; |
| 15 | +import com.javadiscord.jdi.core.annotations.SlashCommand; |
| 16 | +import com.javadiscord.jdi.core.interaction.SlashCommandEvent; |
| 17 | +import com.javadiscord.jdi.core.models.application.ApplicationCommandOption; |
| 18 | +import com.javadiscord.jdi.core.models.message.embed.Embed; |
| 19 | +import com.javadiscord.jdi.core.models.message.embed.EmbedAuthor; |
| 20 | +import com.javadiscord.jdi.core.models.user.User; |
| 21 | + |
| 22 | +import com.github.dockerjava.api.DockerClient; |
| 23 | +import com.github.dockerjava.api.command.CreateContainerResponse; |
| 24 | +import org.apache.logging.log4j.LogManager; |
| 25 | +import org.apache.logging.log4j.Logger; |
| 26 | + |
| 27 | +public class LinuxCommand { |
| 28 | + private static final Logger LOGGER = LogManager.getLogger(LinuxCommand.class); |
| 29 | + private static final ScheduledExecutorService EXECUTOR_SERVICE = |
| 30 | + Executors.newSingleThreadScheduledExecutor(); |
| 31 | + |
| 32 | + private final DockerClient dockerClient; |
| 33 | + public final DockerSessions dockerSessions; |
| 34 | + private final DockerCommandRunner commandRunner; |
| 35 | + |
| 36 | + public LinuxCommand( |
| 37 | + DockerClient dockerClient, |
| 38 | + DockerSessions dockerSessions, |
| 39 | + DockerCommandRunner commandRunner |
| 40 | + ) { |
| 41 | + this.dockerClient = dockerClient; |
| 42 | + this.dockerSessions = dockerSessions; |
| 43 | + this.commandRunner = commandRunner; |
| 44 | + |
| 45 | + Runtime.getRuntime() |
| 46 | + .addShutdownHook( |
| 47 | + new Thread( |
| 48 | + () -> dockerSessions |
| 49 | + .getSessions() |
| 50 | + .forEach(dockerSessions::stopContainer) |
| 51 | + ) |
| 52 | + ); |
| 53 | + |
| 54 | + EXECUTOR_SERVICE.scheduleAtFixedRate( |
| 55 | + new ContainerCleanupTask(dockerSessions), 0, 5, TimeUnit.MINUTES |
| 56 | + ); |
| 57 | + } |
| 58 | + |
| 59 | + @SlashCommand( |
| 60 | + name = "linux", description = "Run commands in your very own Linux session", options = { |
| 61 | + @CommandOption( |
| 62 | + name = "code", description = "The command you would like to run", type = CommandOptionType.STRING |
| 63 | + ) |
| 64 | + } |
| 65 | + ) |
| 66 | + public void handle(SlashCommandEvent event) { |
| 67 | + event.deferReply(); |
| 68 | + |
| 69 | + Optional<ApplicationCommandOption> codeOption = event.option("code"); |
| 70 | + User user = event.user(); |
| 71 | + |
| 72 | + codeOption.ifPresent(option -> { |
| 73 | + LOGGER.info("Running command {}", option.valueAsString()); |
| 74 | + |
| 75 | + Thread.ofVirtual().start(() -> handleLinuxCommand(event, option.valueAsString(), user)); |
| 76 | + }); |
| 77 | + } |
| 78 | + |
| 79 | + private void handleLinuxCommand(SlashCommandEvent event, String command, User member) { |
| 80 | + String memberId = String.valueOf(member.id()); |
| 81 | + Session session = getSessionForUser(memberId); |
| 82 | + try (OutputStream output = commandRunner.sendCommand(session, command)) { |
| 83 | + String reply = |
| 84 | + """ |
| 85 | + Ran command: |
| 86 | + ``` |
| 87 | + $ %s |
| 88 | + ``` |
| 89 | +
|
| 90 | + ```java |
| 91 | + %s |
| 92 | + ``` |
| 93 | +
|
| 94 | + Session expires in %s |
| 95 | + """ |
| 96 | + .formatted(command, output, getSessionExpiry(session)); |
| 97 | + |
| 98 | + Embed embed = |
| 99 | + new Embed.Builder() |
| 100 | + .author(new EmbedAuthor(member.asMention(), null, null, null)) |
| 101 | + .description(shortenOutput(reply)) |
| 102 | + .color(Color.RED) |
| 103 | + .build(); |
| 104 | + |
| 105 | + event.reply(embed); |
| 106 | + } catch (Exception e) { |
| 107 | + LOGGER.error(e); |
| 108 | + event.reply("An error occurred: " + e.getMessage()); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + private String getSessionExpiry(Session session) { |
| 113 | + Instant expiry = session.getStartTime().plusSeconds(TimeUnit.MINUTES.toSeconds(5)); |
| 114 | + long epochSeconds = expiry.getEpochSecond(); |
| 115 | + return "<t:" + epochSeconds + ":R>"; |
| 116 | + } |
| 117 | + |
| 118 | + private String shortenOutput(String input) { |
| 119 | + String concatMessage = "\n**Rest of the output as been removed as it was too long**\n"; |
| 120 | + if (input.length() > 4096) { |
| 121 | + input = input.substring(0, 4096 - concatMessage.length()) + concatMessage; |
| 122 | + } |
| 123 | + StringBuilder sb = new StringBuilder(); |
| 124 | + String[] parts = input.split("\n"); |
| 125 | + if (parts.length > 50) { |
| 126 | + for (int i = 50; i > 0; i--) { |
| 127 | + sb.append(parts[i]).append("\n"); |
| 128 | + } |
| 129 | + sb.append(concatMessage); |
| 130 | + } else { |
| 131 | + sb.append(input); |
| 132 | + } |
| 133 | + return sb.toString(); |
| 134 | + } |
| 135 | + |
| 136 | + private Session getSessionForUser(String name) { |
| 137 | + if (!dockerSessions.hasSession(name)) { |
| 138 | + |
| 139 | + LOGGER.info("Creating new session for {}", name); |
| 140 | + |
| 141 | + DockerContainerCreator containerCreator = new DockerContainerCreator(dockerClient); |
| 142 | + |
| 143 | + CreateContainerResponse createContainerResponse = |
| 144 | + containerCreator.createContainerStarted( |
| 145 | + "session-" + ThreadLocalRandom.current().nextInt(), |
| 146 | + "ubuntu:latest", |
| 147 | + mb(256), |
| 148 | + mb(256), |
| 149 | + 512, |
| 150 | + 100000, |
| 151 | + cpuQuota(100000, 0.5) |
| 152 | + ); |
| 153 | + |
| 154 | + return dockerSessions.createSession(name, createContainerResponse.getId()); |
| 155 | + } |
| 156 | + |
| 157 | + LOGGER.info("Found existing session for {}", name); |
| 158 | + |
| 159 | + return dockerSessions.getSessionForUser(name); |
| 160 | + } |
| 161 | + |
| 162 | + public static long mb(long megabytes) { |
| 163 | + return megabytes * 1024 * 1024; |
| 164 | + } |
| 165 | + |
| 166 | + public static long cpuQuota(int cpuPeriod, double percentage) { |
| 167 | + return (long) (cpuPeriod * (percentage / 10.0)); |
| 168 | + } |
| 169 | +} |
0 commit comments