Initial commit.

master
kalle 2021-04-12 23:42:07 +02:00
commit 1f0b81347c
24 changed files with 1131 additions and 0 deletions

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
.gradle/
.idea/
gradle/
*.iml
build/

32
build.gradle Normal file
View File

@ -0,0 +1,32 @@
apply plugin: 'java'
group = pluginGroup
version = pluginVersion
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
maven {
name = 'spigotmc-repo'
url = 'https://hub.spigotmc.org/nexus/content/groups/public/'
}
maven {
name = 'sonatype'
url = 'https://oss.sonatype.org/content/groups/public/'
}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'org.spigotmc:spigot-api:1.14.1-R0.1-SNAPSHOT'
}
import org.apache.tools.ant.filters.ReplaceTokens
processResources {
from(sourceSets.main.resources.srcDirs) {
filter ReplaceTokens, tokens: [version: version]
}
}

2
gradle.properties Normal file
View File

@ -0,0 +1,2 @@
pluginGroup=nl.dragontamerfred
pluginVersion=1.0

172
gradlew vendored Executable file
View File

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored Normal file
View File

@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,66 @@
package nl.dragontamerfred.lagmon;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
public class Config {
public static String BROADCAST_FORMAT;
public static long BROADCAST_INTERVAL;
public static boolean CPU_DISCARD_NEGATIVE;
public static int CPU_SAMPLE_TIME;
public static String MEMORY_PROVIDER;
public static int MEMORY_PTERODACTYL_POLLING_RATE;
public static String MEMORY_PTERODACTYL_BASE_URL;
public static String MEMORY_PTERODACTYL_SERVER_ID;
public static String MEMORY_PTERODACTYL_API_TOKEN;
public static int RESTART_PERCENTAGE;
public static String RESTART_MESSAGE_NO_PERM;
public static String RESTART_MESSAGE_VOTE_STARTED;
public static String RESTART_MESSAGE_VOTE_UPDATE;
public static String RESTART_MESSAGE_VOTE_CANCELED;
public static String RESTART_MESSAGE_VOTE_PASSED;
public static String RESTART_MESSAGE_VOTE_RESTARTING;
public static String RESART_MESSAGE_RESTART_IN;
public static void load(File file) {
try {
if (!file.getParentFile().exists())
file.getParentFile().mkdirs();
if (!file.exists())
Util.ExportResource("/config.yml", file);
YamlConfiguration config = new YamlConfiguration();
config.load(file);
BROADCAST_FORMAT = config.getString("broadcast.format");
BROADCAST_INTERVAL = config.getLong("broadcast.interval");
CPU_DISCARD_NEGATIVE = config.getBoolean("cpu.discard-negative");
CPU_SAMPLE_TIME = config.getInt("cpu.sample-time");
MEMORY_PROVIDER = config.getString("memory.provider");
MEMORY_PTERODACTYL_POLLING_RATE = config.getInt("memory.pterodactyl.polling-rate");
MEMORY_PTERODACTYL_BASE_URL = config.getString("memory.pterodactyl.base-url");
MEMORY_PTERODACTYL_SERVER_ID = config.getString("memory.pterodactyl.server-id");
MEMORY_PTERODACTYL_API_TOKEN = config.getString("memory.pterodactyl.api-token");
RESTART_PERCENTAGE = config.getInt("restart.percentage");
RESTART_MESSAGE_NO_PERM = config.getString("restart.messages.no-perm");
RESTART_MESSAGE_VOTE_STARTED = config.getString("restart.messages.vote-started");
RESTART_MESSAGE_VOTE_UPDATE = config.getString("restart.messages.vote-update");
RESTART_MESSAGE_VOTE_CANCELED = config.getString("restart.messages.vote-canceled");
RESTART_MESSAGE_VOTE_PASSED = config.getString("restart.messages.vote-passed");
RESTART_MESSAGE_VOTE_RESTARTING = config.getString("restart.messages.vote-restarting");
RESART_MESSAGE_RESTART_IN = config.getString("restart.messages.resarting-in");
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,43 @@
package nl.dragontamerfred.lagmon;
import nl.dragontamerfred.lagmon.commands.CommandLmrestart;
import nl.dragontamerfred.lagmon.components.ComponentBroadcast;
import nl.dragontamerfred.lagmon.components.ComponentCPU;
import nl.dragontamerfred.lagmon.components.ComponentMemory;
import nl.dragontamerfred.lagmon.components.ComponentTPS;
import nl.dragontamerfred.lagmon.components.memory.ProviderRuntime;
import nl.dragontamerfred.lagmon.components.memory.ProviderPterodactyl;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
public final class LagMon extends JavaPlugin {
public static LagMon plugin;
@Override
public void onEnable() {
plugin = this;
Config.load(new File(getDataFolder(), "config.yml"));
ComponentTPS.startScheduler(this);
ComponentCPU.startScheduler(this);
if ("pterodactyl".equals(Config.MEMORY_PROVIDER))
ComponentMemory.setup(new ProviderPterodactyl());
else
ComponentMemory.setup(new ProviderRuntime());
ComponentBroadcast.startScheduler(this);
// Register commands
CommandLmrestart commandLmrestart = new CommandLmrestart();
getCommand("lmrestart").setExecutor(commandLmrestart);
getCommand("lmrestart").setTabCompleter(commandLmrestart);
}
@Override
public void onDisable() {
// Plugin shutdown logic
}
}

View File

@ -0,0 +1,46 @@
package nl.dragontamerfred.lagmon;
import org.bukkit.ChatColor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class Util {
public static final long BYTES_PER_MB = 1048576;
/**
* Convert the amount of memory in bytes to the correct amount in MegaBytes as string.
* @param mem The amount of memory in bytes (as long)
* @return The amount of memory in MegaBytes (as String)
*/
public static String formatMemory(long mem) {
return Long.toString(mem / BYTES_PER_MB);
}
public static String color(String str) {
return ChatColor.translateAlternateColorCodes('&', str);
}
/*
Method to export a file from the jar to the plugin folder.
*/
public static void ExportResource(String resourceName, File output) {
try (InputStream stream = LagMon.class.getResourceAsStream(resourceName); OutputStream resStreamOut = new FileOutputStream(output)) {
if (stream == null) {
throw new Exception("Cannot get resource \"" + resourceName + "\" from Jar file.");
}
int readBytes;
byte[] buffer = new byte[4096];
while ((readBytes = stream.read(buffer)) > 0) {
resStreamOut.write(buffer, 0, readBytes);
}
} catch (Exception ex) {
//Fail silently
}
}
}

View File

@ -0,0 +1,62 @@
package nl.dragontamerfred.lagmon.commands;
import nl.dragontamerfred.lagmon.Config;
import nl.dragontamerfred.lagmon.commands.lmrestart.Help;
import nl.dragontamerfred.lagmon.commands.lmrestart.Now;
import nl.dragontamerfred.lagmon.commands.lmrestart.Vote;
import nl.dragontamerfred.lagmon.types.ICommand;
import nl.dragontamerfred.lagmon.types.ISubCommand;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class CommandLmrestart implements CommandExecutor, TabCompleter, ICommand {
private static HashMap<String, ISubCommand> subCommands = new HashMap<>();
public CommandLmrestart() {
subCommands.put("help", new Help());
subCommands.put("now", new Now());
subCommands.put("vote", new Vote());
}
// {PLAYER} {VOTE_AMOUNT} {VOTE_PERCENTAGE} {TIME}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!sender.hasPermission("lagmon.restart.vote")) {
sender.sendMessage(Config.RESTART_MESSAGE_NO_PERM);
return true;
}
if (args.length <= 0)
return subCommands.get("help").execute(this, sender, args);
if (subCommands.containsKey(args[0])) {
return subCommands.get(args[0]).execute(this, sender, args);
} else {
return subCommands.get("help").execute(this, sender, args);
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
List<String> tabComplete = new ArrayList<>();
for (String subCommand : subCommands.keySet()) {
if (subCommand.startsWith(args[0]))
tabComplete.add(subCommand);
}
return tabComplete;
}
@Override
public HashMap<String, ISubCommand> getSubCommands() {
return subCommands;
}
}

View File

@ -0,0 +1,32 @@
package nl.dragontamerfred.lagmon.commands.lmrestart;
import nl.dragontamerfred.lagmon.Util;
import nl.dragontamerfred.lagmon.types.ICommand;
import nl.dragontamerfred.lagmon.types.ISubCommand;
import org.bukkit.command.CommandSender;
public class Help implements ISubCommand {
@Override
public String getName() {
return "help";
}
@Override
public String getDescription() {
return "Display this help message.";
}
@Override
public String getPermission() {
return "lagmon.restart.help";
}
@Override
public boolean execute(ICommand command, CommandSender sender, String[] args) {
for (ISubCommand subCommand : command.getSubCommands().values()) {
sender.sendMessage(Util.color("&6&l/lmrestart " + subCommand.getName() + "&f - &6" + subCommand.getDescription()));
}
return true;
}
}

View File

@ -0,0 +1,30 @@
package nl.dragontamerfred.lagmon.commands.lmrestart;
import nl.dragontamerfred.lagmon.components.ComponentRestart;
import nl.dragontamerfred.lagmon.types.ICommand;
import nl.dragontamerfred.lagmon.types.ISubCommand;
import org.bukkit.command.CommandSender;
public class Now implements ISubCommand {
@Override
public String getName() {
return "now";
}
@Override
public String getDescription() {
return "Force a server restart.";
}
@Override
public String getPermission() {
return "lagmon.restart.now";
}
@Override
public boolean execute(ICommand command, CommandSender sender, String[] args) {
ComponentRestart.restart();
return false;
}
}

View File

@ -0,0 +1,42 @@
package nl.dragontamerfred.lagmon.commands.lmrestart;
import nl.dragontamerfred.lagmon.Config;
import nl.dragontamerfred.lagmon.Util;
import nl.dragontamerfred.lagmon.components.ComponentRestart;
import nl.dragontamerfred.lagmon.types.ICommand;
import nl.dragontamerfred.lagmon.types.ISubCommand;
import org.bukkit.command.CommandSender;
public class Vote implements ISubCommand {
@Override
public String getName() {
return "vote";
}
@Override
public String getDescription() {
return "Vote for a server restart.";
}
@Override
public String getPermission() {
return "lagmon.restart.vote";
}
@Override
public boolean execute(ICommand command, CommandSender sender, String[] args) {
switch (ComponentRestart.getStatus()) {
case ENDED:
sender.sendMessage(Util.color(Config.RESTART_MESSAGE_VOTE_RESTARTING));
break;
case STARTED:
ComponentRestart.addVote(sender.getName());
break;
case STOPPED:
ComponentRestart.startVote(sender.getName());
break;
}
return true;
}
}

View File

@ -0,0 +1,34 @@
package nl.dragontamerfred.lagmon.components;
import nl.dragontamerfred.lagmon.Config;
import nl.dragontamerfred.lagmon.Util;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
public class ComponentBroadcast {
public static void startScheduler(JavaPlugin plugin) {
Bukkit.getScheduler().runTaskTimer(plugin, new Timer(), Config.BROADCAST_INTERVAL * 20, Config.BROADCAST_INTERVAL * 20);
}
private static class Timer implements Runnable {
@Override
public void run() {
String message = Util.color(Config.BROADCAST_FORMAT
.replaceAll("\\{RAM_USED}", ComponentMemory.getUsed())
.replaceAll("\\{RAM_USED_COLOR}", ComponentMemory.getUsedColored())
.replaceAll("\\{RAM_FREE}", ComponentMemory.getFree())
.replaceAll("\\{RAM_FREE_COLOR}", ComponentMemory.getFreeColored())
.replaceAll("\\{RAM_TOTAL}", ComponentMemory.getMax())
.replaceAll("\\{TPS}", ComponentTPS.getTPS())
.replaceAll("\\{TPS_COLOR}", ComponentTPS.getTPSColored())
.replaceAll("\\{CPU_USAGE}", ComponentCPU.getCPU())
.replaceAll("\\{CPU_USAGE_COLOR}", ComponentCPU.getCPUColored()));
Bukkit.broadcast(message, "lagmon.broadcast.receive");
}
}
}

View File

@ -0,0 +1,58 @@
package nl.dragontamerfred.lagmon.components;
import nl.dragontamerfred.lagmon.Config;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.Plugin;
import java.lang.management.ManagementFactory;
public class ComponentCPU {
private static float cpu;
public static void startScheduler(Plugin plugin) {
Bukkit.getScheduler().runTaskTimer(plugin, new Timer(), 0, Config.CPU_SAMPLE_TIME);
}
public static float getCpuRaw() {
return cpu;
}
public static String getCPU() {
return String.format("%.2f", cpu);
}
public static String getCPUColored() {
if (cpu <= 25) {
return ChatColor.GREEN + getCPU();
} else if (cpu <= 75) {
return ChatColor.YELLOW + getCPU();
} else {
return ChatColor.RED + getCPU();
}
}
private static class Timer implements Runnable {
long lastTotal = 0;
long lastTime = 0;
@Override
public void run() {
long totalCPUTime = 0;
for (long id : ManagementFactory.getThreadMXBean().getAllThreadIds()) {
totalCPUTime += ManagementFactory.getThreadMXBean().getThreadCpuTime(id);
}
float correctedTotal = (totalCPUTime - lastTotal) / 1000000.0f;
long correctedTime = System.currentTimeMillis() - lastTime;
float percentage = 100.0f * correctedTotal / correctedTime;
if (!Config.CPU_DISCARD_NEGATIVE || percentage >= 0)
cpu = percentage;
lastTotal = totalCPUTime;
lastTime = System.currentTimeMillis();
}
}
}

View File

@ -0,0 +1,56 @@
package nl.dragontamerfred.lagmon.components;
import nl.dragontamerfred.lagmon.Util;
import nl.dragontamerfred.lagmon.components.memory.IMemoryProvider;
import org.bukkit.ChatColor;
public class ComponentMemory {
private static IMemoryProvider provider;
public static void setup(IMemoryProvider mprovider) {
provider = mprovider;
}
public static String getFree() {
return Util.formatMemory(provider.getFreeRaw());
}
public static String getMax() {
return Util.formatMemory(provider.getMaxRaw());
}
public static String getUsed() {
return Util.formatMemory(provider.getUsedRaw());
}
public static String getFreeColored() {
long free = provider.getFreeRaw();
long total = provider.getMaxRaw();
double percentage = 100.0 * free / total;
if (percentage >= 50) {
return ChatColor.GREEN + getFree();
} else if (percentage >= 10) {
return ChatColor.YELLOW + getFree();
} else {
return ChatColor.RED + getFree();
}
}
public static String getUsedColored() {
long used = provider.getUsedRaw();
long total = provider.getMaxRaw();
double percentage = 100.0 * used / total;
if (percentage >= 90) {
return ChatColor.RED + getUsed();
} else if (percentage >= 50) {
return ChatColor.YELLOW + getUsed();
} else {
return ChatColor.GREEN + getUsed();
}
}
}

View File

@ -0,0 +1,115 @@
package nl.dragontamerfred.lagmon.components;
import nl.dragontamerfred.lagmon.Config;
import nl.dragontamerfred.lagmon.LagMon;
import nl.dragontamerfred.lagmon.Util;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask;
import java.util.HashSet;
public class ComponentRestart {
private static VoteStatus status = VoteStatus.STOPPED;
private static BukkitTask voteTask;
private static HashSet<String> votes = new HashSet<>();
public static boolean startVote(String name) {
if (status != VoteStatus.STOPPED)
return false;
votes = new HashSet<>();
votes.add(name);
status = VoteStatus.STARTED;
Bukkit.broadcast(Config.RESTART_MESSAGE_VOTE_STARTED.replaceAll("\\{PLAYER}", name), "lagmon.restart.vote");
voteTask = Bukkit.getScheduler().runTaskLater(LagMon.plugin, new VoteTask(), 60 * 20);
if (checkVotes()) {
restartVoted();
}
return true;
}
public static boolean addVote(String name) {
if (status != VoteStatus.STARTED)
return false;
if (votes.contains(name))
return false;
votes.add(name);
if (checkVotes()) {
restartVoted();
}
return true;
}
public static VoteStatus getStatus() {
return status;
}
private static boolean checkVotes() {
int playerCount = Bukkit.getOnlinePlayers().size();
int voteCount = votes.size();
System.out.println("playerCount: " + playerCount);
System.out.println("voteCount: " + voteCount);
System.out.println("Percentage: " + Config.RESTART_PERCENTAGE);
System.out.println("Needed: " + playerCount * (Config.RESTART_PERCENTAGE * 0.01));
return voteCount >= playerCount * (Config.RESTART_PERCENTAGE * 0.01);
}
private static void restartVoted() {
Bukkit.broadcastMessage(Util.color(Config.RESTART_MESSAGE_VOTE_PASSED));
status = VoteStatus.ENDED;
restart();
}
public static void restart() {
if (voteTask != null)
voteTask.cancel();
if (status != VoteStatus.ENDED)
status = VoteStatus.ENDED;
Bukkit.getScheduler().runTaskAsynchronously(LagMon.plugin, new RestartTask());
}
public enum VoteStatus {
STOPPED, // There is no vote currently going on.
STARTED, // There is currently a vote going on.
ENDED // A vote has just successfully finished.
}
private static class VoteTask implements Runnable {
@Override
public void run() {
status = VoteStatus.STOPPED;
Bukkit.broadcast(Config.RESTART_MESSAGE_VOTE_CANCELED, "lagmon.restart.vote");
}
}
private static class RestartTask implements Runnable {
@Override
public void run() {
Bukkit.broadcastMessage(Util.color(Config.RESART_MESSAGE_RESTART_IN.replaceAll("\\{TIME}", "10")));
try {
Thread.sleep(5000);
Bukkit.broadcastMessage(Util.color(Config.RESART_MESSAGE_RESTART_IN.replaceAll("\\{TIME}", "5")));
Thread.sleep(1000);
Bukkit.broadcastMessage(Util.color(Config.RESART_MESSAGE_RESTART_IN.replaceAll("\\{TIME}", "4")));
Thread.sleep(1000);
Bukkit.broadcastMessage(Util.color(Config.RESART_MESSAGE_RESTART_IN.replaceAll("\\{TIME}", "3")));
Thread.sleep(1000);
Bukkit.broadcastMessage(Util.color(Config.RESART_MESSAGE_RESTART_IN.replaceAll("\\{TIME}", "2")));
Thread.sleep(1000);
Bukkit.broadcastMessage(Util.color(Config.RESART_MESSAGE_RESTART_IN.replaceAll("\\{TIME}", "1")));
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Bukkit.getServer().shutdown();
}
}
}

View File

@ -0,0 +1,54 @@
package nl.dragontamerfred.lagmon.components;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.plugin.Plugin;
public class ComponentTPS {
private static double tps;
public static void startScheduler(Plugin plugin) {
Bukkit.getScheduler().runTaskTimer(plugin, new Timer(), 0, 1);
}
public static double getTPSRaw() {
return tps;
}
public static String getTPS() {
return String.format("%.1f", tps);
}
public static String getTPSColored() {
if (tps >= 18) {
return ChatColor.GREEN + getTPS();
} else if (tps >= 12) {
return ChatColor.YELLOW + getTPS();
} else if (tps >= 8) {
return ChatColor.RED + getTPS();
} else {
return ChatColor.DARK_RED + getTPS();
}
}
private static class Timer implements Runnable {
long secstart;
long secend;
int ticks;
@Override
public void run() {
secstart = (System.currentTimeMillis() / 1000);
if(secstart == secend) {
ticks++;
} else {
secend = secstart;
tps = (tps == 0) ? ticks : ((tps + ticks) / 2);
ticks = 1;
}
}
}
}

View File

@ -0,0 +1,10 @@
package nl.dragontamerfred.lagmon.components.memory;
public interface IMemoryProvider {
long getFreeRaw();
long getUsedRaw();
long getMaxRaw();
}

View File

@ -0,0 +1,91 @@
package nl.dragontamerfred.lagmon.components.memory;
import com.google.gson.GsonBuilder;
import nl.dragontamerfred.lagmon.Config;
import nl.dragontamerfred.lagmon.LagMon;
import nl.dragontamerfred.lagmon.Util;
import org.bukkit.Bukkit;
import javax.net.ssl.HttpsURLConnection;
import java.io.InputStreamReader;
import java.net.URL;
public class ProviderPterodactyl implements IMemoryProvider {
private Response response = null;
public ProviderPterodactyl() {
Bukkit.getScheduler().runTaskTimerAsynchronously(LagMon.plugin, new task(), 0, Config.MEMORY_PTERODACTYL_POLLING_RATE * 20);
}
@Override
public long getFreeRaw() {
return (response.attributes.memory.limit - response.attributes.memory.current) * Util.BYTES_PER_MB;
}
@Override
public long getUsedRaw() {
return response.attributes.memory.current * Util.BYTES_PER_MB;
}
@Override
public long getMaxRaw() {
return response.attributes.memory.limit * Util.BYTES_PER_MB;
}
private class task implements Runnable {
@Override
public void run() {
HttpsURLConnection connection = null;
try {
URL url = new URL(Config.MEMORY_PTERODACTYL_BASE_URL + "/api/client/servers/" + Config.MEMORY_PTERODACTYL_SERVER_ID + "/utilization");
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Bearer " + Config.MEMORY_PTERODACTYL_API_TOKEN);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
// TODO maybe connection.connect() is needed
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
response = new GsonBuilder().create().fromJson(isr, Response.class);
isr.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
}
}
}
private static class Response {
public String object;
public Attributes attributes;
}
private static class Attributes {
public String state;
public Memory memory;
public Cpu cpu;
public Disk disk;
}
private static class Memory {
public int current;
public int limit;
}
private static class Cpu {
public double current;
public double[] cores;
public double limit;
}
private static class Disk {
public int current;
public int limit;
}
}

View File

@ -0,0 +1,19 @@
package nl.dragontamerfred.lagmon.components.memory;
public class ProviderRuntime implements IMemoryProvider {
@Override
public long getFreeRaw() {
return Runtime.getRuntime().freeMemory();
}
@Override
public long getUsedRaw() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
@Override
public long getMaxRaw() {
return Runtime.getRuntime().maxMemory();
}
}

View File

@ -0,0 +1,8 @@
package nl.dragontamerfred.lagmon.types;
import java.util.HashMap;
public interface ICommand {
HashMap<String, ISubCommand> getSubCommands();
}

View File

@ -0,0 +1,15 @@
package nl.dragontamerfred.lagmon.types;
import org.bukkit.command.CommandSender;
public interface ISubCommand {
String getName();
String getDescription();
String getPermission();
boolean execute(ICommand command, CommandSender sender, String[] args);
}

View File

@ -0,0 +1,39 @@
broadcast:
# Placeholders:
# {RAM_USED} - The current RAM usage (in MB)
# {RAM_USED_COLOR} - The current RAM usage (in MB) (colored)
# {RAM_FREE} - The current RAM available (in MB)
# {RAM_FREE_COLOR} - The current RAM available (in MB) (colored)
# {RAM_TOTAL} - The total amount of RAM (in MB)
# {TPS} - The server tps
# {TPS_COLOR} - The server tps (colored)
# {CPU_USAGE} - The current CPU usage
# {CPU_USAGE_COLOR} - The current CPU usage (colored)
format: '&8[&7LAG&8]&f &lTPS: &7{TPS_COLOR}&f &lMemory: {RAM_USED_COLOR}MB&f/&8{RAM_TOTAL}MB&f &lCPU: {CPU_USAGE_COLOR}%'
interval: 300 # In seconds
cpu:
discard-negative: true
sample-time: 100 # In ticks
memory:
# Availible providers:
# runtime - The default provider. Uses java runtime to request memory usage.
# pterodactyl - For use with server hosts running a (modified) version of pterodactyl panel. Uses the pterodactyl panel api to request data on the server.
provider: "runtime"
pterodactyl:
polling-rate: 10 # In seconds
base-url: ""
server-id: ""
api-token: ""
restart:
percentage: 75 # Percentage of players that need to agree to a restart.
messages:
no-perm: "&cYou do not have permission to use this command!"
vote-started: "&8[&7LAG&8]&f A restart vote has been started by &6&l{PLAYER}&f! (/lmrestart)"
vote-update: "&8[&7LAG&8]&f Currently &6&l{VOTE_AMOUNT} ({VOTE_PERCENTAGE}%)&f players want a restart! (/lmrestart)"
vote-canceled: "&8[&7LAG&8]&f Not enough players voted for a restart!"
vote-passed: "&8[&7LAG&8]&f Enough players voted for a restart."
vote-restarting: "&cThe server is already restarting. No need to vote!"
resarting-in: "&8[&7LAG&8]&f Restarting in {TIME} seconds!"

View File

@ -0,0 +1,16 @@
name: LagMon
version: @version@
main: nl.dragontamerfred.lagmon.LagMon
api-version: 1.13
commands:
lmrestart:
permissions:
"lagmon.broadcast.receive":
default: true
"lagmon.restart.help":
default: true
"lagmon.restart.vote":
default: true
"lagmon.restart.now":
default: op