+ 附属插件异常捕捉

+ 新增多条插件更新线路(GitHub,Gitee)
This commit is contained in:
坏黑 2018-11-29 15:53:41 +08:00
parent 24a9b586c4
commit 62a11cb53a
14 changed files with 358 additions and 44 deletions

View File

@ -6,7 +6,7 @@
<groupId>me.skymc</groupId>
<artifactId>TabooLib</artifactId>
<version>4.62</version>
<version>4.63</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -4,7 +4,6 @@ import com.ilummc.tlib.annotations.Dependency;
import com.ilummc.tlib.compat.PlaceholderHook;
import com.ilummc.tlib.config.TLibConfig;
import com.ilummc.tlib.db.Pool;
import com.ilummc.tlib.filter.TLoggerFilter;
import com.ilummc.tlib.inject.TConfigWatcher;
import com.ilummc.tlib.inject.TDependencyInjector;
import com.ilummc.tlib.inject.TPluginManager;
@ -62,7 +61,6 @@ public class TLib {
public static void init() {
tLib = new TLib();
TLoggerFilter.init();
TLocaleLoader.init();
PlaceholderHook.init();
TLocaleLoader.load(Main.getInst(), false);

View File

@ -1,10 +1,19 @@
package com.ilummc.tlib.filter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ilummc.tlib.filter.impl.FilterConfiguration;
import com.ilummc.tlib.filter.impl.FilterExceptionMirror;
import com.ilummc.tlib.filter.impl.FilterInvalidPluginLoader;
import me.skymc.taboolib.TabooLib;
import org.bukkit.Bukkit;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Filter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* @author Bkm016
@ -12,22 +21,53 @@ import java.util.logging.LogRecord;
*/
public class TLoggerFilter implements Filter {
public static void init() {
Bukkit.getLogger().setFilter(new TLoggerFilter());
private Filter filter;
private static List<TLoggerFilterHandler> handlers = Lists.newLinkedList();
private static Map<String, TLoggerFilter> pluginFilter = Maps.newHashMap();
private static TLoggerFilter globalFilter;
static {
handlers.add(new FilterConfiguration());
handlers.add(new FilterExceptionMirror());
handlers.add(new FilterInvalidPluginLoader());
}
public static void preInit() {
inject(new TLoggerFilter(), Bukkit.getLogger());
inject(new TLoggerFilter(), TabooLib.instance().getLogger());
}
public static void postInit() {
Arrays.stream(Bukkit.getPluginManager().getPlugins()).filter(TabooLib::isDependTabooLib).forEach(plugin -> inject(new TLoggerFilter(), plugin.getLogger()));
}
public static void inject(TLoggerFilter filter, Logger logger) {
try {
filter.filter = logger.getFilter();
logger.setFilter(filter);
} catch (Exception e) {
e.printStackTrace();
}
}
public Filter getFilter() {
return filter;
}
public static TLoggerFilter getGlobalFilter() {
return globalFilter;
}
public static Map<String, TLoggerFilter> getPluginFilter() {
return pluginFilter;
}
public static List<TLoggerFilterHandler> getHandlers() {
return handlers;
}
@Override
public boolean isLoggable(LogRecord e) {
if (e.getMessage().contains("Cannot load configuration from stream")) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (StackTraceElement element : elements) {
if (element.getClassName().contains("ConfigUtils")) {
System.out.println(Arrays.asList(e.getParameters()));
}
}
return false;
} else {
return !e.getMessage().contains("Enabled plugin with unregistered PluginClassLoader");
}
return handlers.stream().allMatch(filter -> filter.isLoggable(e)) && (filter == null || filter.isLoggable(e));
}
}

View File

@ -0,0 +1,13 @@
package com.ilummc.tlib.filter;
import java.util.logging.LogRecord;
/**
* @Author 坏黑
* @Since 2018-11-29 11:42
*/
public abstract class TLoggerFilterHandler {
abstract public boolean isLoggable(LogRecord e);
}

View File

@ -0,0 +1,28 @@
package com.ilummc.tlib.filter.impl;
import com.ilummc.tlib.filter.TLoggerFilterHandler;
import java.util.Arrays;
import java.util.logging.LogRecord;
/**
* @Author 坏黑
* @Since 2018-11-29 11:47
*/
public class FilterConfiguration extends TLoggerFilterHandler {
@Override
public boolean isLoggable(LogRecord e) {
if (e.getMessage().contains("Cannot load configuration from stream")) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
for (StackTraceElement element : elements) {
if (element.getClassName().contains("ConfigUtils")) {
// Bukkit 拦截异常我再扔一个
System.out.println(Arrays.asList(e.getParameters()));
}
}
return false;
}
return true;
}
}

View File

@ -0,0 +1,117 @@
package com.ilummc.tlib.filter.impl;
import com.google.common.collect.Lists;
import com.ilummc.tlib.filter.TLoggerFilterHandler;
import com.ilummc.tlib.resources.TLocale;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
import org.bukkit.command.CommandException;
import org.bukkit.event.EventException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.LogRecord;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Author 坏黑
* @Since 2018-11-29 11:42
*/
public class FilterExceptionMirror extends TLoggerFilterHandler {
interface ArgumentsCallback {
String[] run();
}
private static Pattern patternEvent = Pattern.compile("Could not pass event (.+?) to (.+?)");
private static Pattern patternCommand = Pattern.compile("Unhandled exception executing command '(.+?)' in plugin (.+?)");
/**
* 判断是否为调度器异常
*/
public boolean isScheduleException(LogRecord log) {
return String.valueOf(log.getMessage()).contains("generated an exception");
}
/**
* 是否为可捕捉异常
*/
public boolean isValidException(Throwable throwable) {
return throwable.getCause() != null && throwable.getCause().getStackTrace() != null && throwable.getCause().getStackTrace().length > 0;
}
/**
* 向控制台打印捕捉到的异常
*
* @param stackTraceElements 堆栈
* @param message 信息类型
* @param args 信息参数
* @return 是否成功捕捉并打印
*/
public boolean printException(AtomicReference<Plugin> plugin, StackTraceElement[] stackTraceElements, String message, ArgumentsCallback args) {
List<StackTraceElement> stackTraces = Lists.newLinkedList();
for (StackTraceElement stack : stackTraceElements) {
try {
plugin.set(JavaPlugin.getProvidingPlugin(Class.forName(stack.getClassName())));
if (TabooLib.isTabooLib(plugin.get()) || TabooLib.isDependTabooLib(plugin.get())) {
stackTraces.add(stack);
}
} catch (Exception ignored) {
}
}
if (plugin.get() != null) {
TLocale.Logger.error("TFILTER.EXCEPTION-MIRROR." + message + ".HEAD", args.run());
for (int i = 0; i < stackTraces.size(); i++) {
StackTraceElement stack = stackTraces.get(i);
TLocale.Logger.error("TFILTER.EXCEPTION-MIRROR." + message + ".STACK-TRACE", String.valueOf(i), stack.toString());
}
return true;
}
return false;
}
@Override
public boolean isLoggable(LogRecord e) {
if (!Main.getInst().getConfig().getBoolean("EXCEPTION-MIRROR", true) || e.getThrown() == null) {
return true;
}
// 是否为调度器异常
if (isScheduleException(e)) {
long time = System.currentTimeMillis();
AtomicReference<Plugin> plugin = new AtomicReference<>();
return !printException(plugin, e.getThrown().getStackTrace(), "SCHEDULE", () -> new String[] {plugin.get().getName(), String.valueOf(System.currentTimeMillis() - time), e.getThrown().getClass().getName(), String.valueOf(e.getThrown().getMessage())});
}
// 是否为其他可捕捉异常
else if (isValidException(e.getThrown())) {
// 事件异常
if (e.getThrown() instanceof EventException) {
Matcher matcher = patternEvent.matcher(e.getMessage());
if (matcher.find()) {
long time = System.currentTimeMillis();
AtomicReference<Plugin> plugin = new AtomicReference<>();
return !printException(plugin, e.getThrown().getCause().getStackTrace(), "EVENT", () -> new String[] {plugin.get().getName(), String.valueOf(System.currentTimeMillis() - time), matcher.group(1), e.getThrown().getCause().getClass().getName(), String.valueOf(e.getThrown().getCause().getMessage())});
}
}
// 命令异常
else if (e.getThrown() instanceof CommandException) {
Matcher matcher = patternCommand.matcher(e.getThrown().getMessage());
if (matcher.find()) {
long time = System.currentTimeMillis();
AtomicReference<Plugin> plugin = new AtomicReference<>();
return !printException(plugin, e.getThrown().getCause().getStackTrace(), "COMMAND", () -> new String[] {plugin.get().getName(), String.valueOf(System.currentTimeMillis() - time), matcher.group(1), e.getThrown().getCause().getClass().getName(), String.valueOf(e.getThrown().getCause().getMessage())});
}
}
// 其他异常
else {
long time = System.currentTimeMillis();
AtomicReference<Plugin> plugin = new AtomicReference<>();
return !printException(plugin, e.getThrown().getCause().getStackTrace(), "OTHER", () -> new String[] {plugin.get().getName(), String.valueOf(System.currentTimeMillis() - time), e.getThrown().getCause().getClass().getName(), String.valueOf(e.getThrown().getCause().getMessage())});
}
}
return true;
}
}

View File

@ -0,0 +1,18 @@
package com.ilummc.tlib.filter.impl;
import com.ilummc.tlib.filter.TLoggerFilterHandler;
import java.util.logging.LogRecord;
/**
* @Author 坏黑
* @Since 2018-11-29 11:47
*/
public class FilterInvalidPluginLoader extends TLoggerFilterHandler {
@Override
public boolean isLoggable(LogRecord e) {
// 屏蔽插件加载器注入导致的警告信息
return !e.getMessage().contains("Enabled plugin with unregistered PluginClassLoader");
}
}

View File

@ -1,6 +1,7 @@
package me.skymc.taboolib;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.filter.TLoggerFilter;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.util.IO;
import com.ilummc.tlib.util.Strings;
@ -8,7 +9,6 @@ import me.skymc.taboolib.database.GlobalDataManager;
import me.skymc.taboolib.database.PlayerDataManager;
import me.skymc.taboolib.fileutils.ConfigUtils;
import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.inventory.speciaitem.SpecialItem;
import me.skymc.taboolib.listener.TListenerHandler;
import me.skymc.taboolib.mysql.hikari.HikariHandler;
import me.skymc.taboolib.mysql.protect.MySQLConnection;
@ -17,9 +17,7 @@ import me.skymc.taboolib.playerdata.DataUtils;
import me.skymc.taboolib.socket.TabooLibClient;
import me.skymc.taboolib.socket.TabooLibServer;
import me.skymc.taboolib.string.language2.Language2;
import me.skymc.taboolib.translateuuid.TranslateUUID;
import me.skymc.taboolib.update.UpdateTask;
import me.skymc.tlm.module.TabooLibraryModule;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
@ -82,6 +80,8 @@ public class Main extends JavaPlugin {
disable = false;
// 载入配置文件
saveDefaultConfig();
// 载入日志过滤
TLoggerFilter.preInit();
// 载入扩展
TabooLibLoader.setupAddons();
// 载入牛逼东西
@ -97,6 +97,8 @@ public class Main extends JavaPlugin {
@Override
public void onEnable() {
// 载入日志过滤
TLoggerFilter.postInit();
// 注册插件配置
TabooLibLoader.register();
// 启动数据库储存方法

View File

@ -1,7 +1,6 @@
package me.skymc.taboolib.commands;
import com.ilummc.tlib.resources.TLocale;
import com.ilummc.tlib.util.Strings;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.commands.internal.BaseMainCommand;
import me.skymc.taboolib.commands.internal.BaseSubCommand;
@ -11,12 +10,9 @@ import me.skymc.taboolib.commands.internal.type.CommandRegister;
import me.skymc.taboolib.commands.internal.type.CommandType;
import me.skymc.taboolib.commands.taboolib.*;
import me.skymc.taboolib.database.GlobalDataManager;
import me.skymc.taboolib.fileutils.FileUtils;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.other.DateUtils;
import me.skymc.taboolib.other.NumberUtils;
import me.skymc.taboolib.player.PlayerUtils;
import me.skymc.taboolib.plugin.PluginUtils;
import me.skymc.taboolib.timecycle.TimeCycle;
import me.skymc.taboolib.timecycle.TimeCycleEvent;
import me.skymc.taboolib.timecycle.TimeCycleInitializeEvent;
@ -27,8 +23,6 @@ import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
@ -774,12 +768,14 @@ public class TabooLibMainCommand extends BaseMainCommand {
@Override
public CommandArgument[] getArguments() {
return new CommandArgument[0];
return new CommandArgument[] {
new CommandArgument(TLocale.asString("COMMANDS.TABOOLIB.UPDATEPLUGIN.ARGUMENTS.0"), false)
};
}
@Override
public void onCommand(CommandSender sender, Command command, String label, String[] args) {
UpdateTask.updatePlugin(true);
UpdateTask.updatePlugin(true, args.length > 0);
}
@Override

View File

@ -3,6 +3,8 @@ package me.skymc.taboolib.listener;
import com.ilummc.tlib.logger.TLogger;
import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.commands.builder.SimpleCommandBuilder;
import me.skymc.taboolib.common.inject.TInject;
import me.skymc.taboolib.database.PlayerDataManager;
import me.skymc.taboolib.inventory.ItemUtils;
import me.skymc.taboolib.itemnbtapi.NBTItem;
@ -22,6 +24,30 @@ import org.bukkit.event.server.ServerCommandEvent;
@TListener
public class ListenerPlayerCommand implements Listener {
private static boolean nextException;
public ListenerPlayerCommand() {
Bukkit.getScheduler().runTaskTimer(TabooLib.instance(), () -> {
if (nextException) {
nextException = false;
throw new IllegalStateException();
}
}, 0, 20);
}
@TInject
static SimpleCommandBuilder tExceptionCommand = SimpleCommandBuilder.create("tExceptionCommand", TabooLib.instance())
.execute((sender, args) -> {
throw new IllegalStateException();
});
@TInject
static SimpleCommandBuilder tExceptionSchedule = SimpleCommandBuilder.create("tExceptionSchedule", TabooLib.instance())
.execute((sender, args) -> {
nextException = true;
return true;
});
@EventHandler
public void cmd(ServerCommandEvent e) {
if (e.getCommand().equalsIgnoreCase("saveFiles")) {
@ -42,6 +68,9 @@ public class ListenerPlayerCommand implements Listener {
TabooLib.setDebug(true);
TLogger.getGlobalLogger().info("&aEnabled.");
}
} else if (e.getCommand().equalsIgnoreCase("tExceptionEvent")) {
e.setCancelled(true);
throw new IllegalStateException();
}
}

View File

@ -1,6 +1,7 @@
package me.skymc.taboolib.listener;
import com.ilummc.tlib.TLib;
import com.ilummc.tlib.filter.TLoggerFilter;
import com.ilummc.tlib.inject.TConfigWatcher;
import com.ilummc.tlib.inject.TDependencyInjector;
import com.ilummc.tlib.resources.TLocale;
@ -8,6 +9,7 @@ import me.skymc.taboolib.Main;
import me.skymc.taboolib.TabooLib;
import me.skymc.taboolib.common.configuration.TConfiguration;
import me.skymc.taboolib.events.TPluginEnableEvent;
import me.skymc.taboolib.events.TPluginLoadEvent;
import me.skymc.taboolib.mysql.MysqlUtils;
import me.skymc.taboolib.mysql.hikari.HikariHandler;
import me.skymc.taboolib.mysql.protect.MySQLConnection;
@ -30,6 +32,12 @@ import java.util.Optional;
@TListener
public class ListenerPlugin implements Listener {
public void load(TPluginLoadEvent e) {
if (TabooLib.isDependTabooLib(e.getPlugin())) {
TLoggerFilter.inject(new TLoggerFilter(), e.getPlugin().getLogger());
}
}
@EventHandler (priority = EventPriority.LOWEST)
public void enable(TPluginEnableEvent e) {
if (!TLib.getTLib().isInjectEnabled() || !TLib.getTLib().isBlackListPluginExists()) {

View File

@ -20,6 +20,17 @@ import java.io.File;
public class UpdateTask {
private static double newVersion = 0;
private static int updateLocationUsing;
private static String[][] updateLocation = {
{
"https://api.github.com/repos/Bkm016/TabooLib/releases",
"https://github.com/Bkm016/TabooLib/releases/download/?/TabooLib-?.jar"
},
{
"https://gitee.com/bkm016/TabooLibCloud/raw/master/release.json",
"https://gitee.com/bkm016/TabooLibCloud/raw/master/core/TabooLib.jar"
}
};
public UpdateTask() {
new BukkitRunnable() {
@ -29,20 +40,28 @@ public class UpdateTask {
if (!Main.getInst().getConfig().getBoolean("UPDATE-CHECK")) {
return;
}
String value = FileUtils.getStringFromURL("https://api.github.com/repos/Bkm016/TabooLib/releases", null);
boolean success = false;
for (int i = 0; i < updateLocation.length; i++) {
String[] location = updateLocation[i];
String value = FileUtils.getStringFromURL(location[0], null);
if (value == null) {
TLocale.Logger.error("UPDATETASK.VERSION-FAIL");
return;
continue;
}
JsonElement json = new JsonParser().parse(value);
if (json.isJsonArray()) {
updateLocationUsing = i;
newVersion = json.getAsJsonArray().get(0).getAsJsonObject().get("tag_name").getAsDouble();
if (TabooLib.getPluginVersion() >= newVersion) {
TLocale.Logger.info("UPDATETASK.VERSION-LATEST");
} else {
TLocale.Logger.info("UPDATETASK.VERSION-OUTDATED", String.valueOf(TabooLib.getPluginVersion()), String.valueOf(newVersion));
Bukkit.getScheduler().runTask(TabooLib.instance(), () -> updatePlugin(true));
Bukkit.getScheduler().runTask(TabooLib.instance(), () -> updatePlugin(true, false));
}
return;
}
}
if (!success) {
TLocale.Logger.error("UPDATETASK.VERSION-FAIL");
}
}
}.runTaskTimerAsynchronously(Main.getInst(), 100, 20 * 60 * 60 * 6);
@ -56,8 +75,16 @@ public class UpdateTask {
return newVersion;
}
public static void updatePlugin(boolean shutdown) {
if (!UpdateTask.isHaveUpdate()) {
public static int getUpdateLocationUsing() {
return updateLocationUsing;
}
public static String[][] getUpdateLocation() {
return updateLocation;
}
public static void updatePlugin(boolean shutdown, boolean force) {
if (!UpdateTask.isHaveUpdate() || (newVersion == 0 || !force)) {
TLocale.Logger.info("COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-NOT-FOUND");
return;
}
@ -71,7 +98,7 @@ public class UpdateTask {
return;
}
Bukkit.getScheduler().runTaskAsynchronously(TabooLib.instance(), () -> {
FileUtils.download("https://github.com/Bkm016/TabooLib/releases/download/" + newVersion + "/TabooLib-" + newVersion + ".jar", pluginFile);
FileUtils.download(updateLocation[updateLocationUsing][1].replace("?", String.valueOf(newVersion)), pluginFile);
TLocale.Logger.info("COMMANDS.TABOOLIB.UPDATEPLUGIN.UPDATE-SUCCESS");
if (shutdown) {
Bukkit.shutdown();

View File

@ -53,6 +53,9 @@ UPDATE-CHECK: true
# 是否启用自动更新
UPDATE-DOWNLOAD: false
# 是否启用附属插件异常拦截
EXCEPTION-z: true
# 是否在关闭服务器时清理玩家数据
# 该配置将在启用数据库储存时失效
DELETE-DATA: false

View File

@ -240,6 +240,8 @@ COMMANDS:
UPDATE-SUCCESS: '&8[&3&lTabooLib&8] &7最新版下载完成, 服务器即将重启!'
FILE-NOT-FOUND: '&8[&3&lTabooLib&8] &4尚未寻找到插件文件'
PLAYER-ONLINE: '&8[&3&lTabooLib&8] &4服务器有玩家在线无法更新插件.'
ARGUMENTS:
0: '-f'
PLAYERTAG:
DESCRIPTION:
DISPLAY: '设置玩家展示名称'
@ -658,3 +660,36 @@ TCLOUD:
LIST-LOAD-FAILED: '载入 &4{0} &c扩展数据失败: &4{1}'
LIST-PARSE-FAILED: '读取 &4TCLOUD &c扩展列表失败: &4{0}'
LIST-CONNECT-FAILED: '获取 &4TCLOUD &c扩展列表失败!'
TFILTER:
EXCEPTION-MIRROR:
EVENT:
HEAD:
- '&c插件 &4{0} &c执行事件时出现异常! &7(处理耗时: {1}ms)'
- '&c异常事件: &4{2}'
- '&c异常类型: &4{3}'
- '&c异常内容: &4{4}'
- '&c异常位置:'
STACK-TRACE: '&7 {0}. &4{1}'
COMMAND:
HEAD:
- '&c插件 &4{0} &c执行命令时出现异常! &7(处理耗时: {1}ms)'
- '&c异常命令: &4{2}'
- '&c异常类型: &4{3}'
- '&c异常内容: &4{4}'
- '&c异常位置:'
STACK-TRACE: '&7 {0}. &4{1}'
SCHEDULE:
HEAD:
- '&c插件 &4{0} &c执行任务时出现异常! &7(处理耗时: {1}ms)'
- '&c异常类型: &4{2}'
- '&c异常内容: &4{3}'
- '&c异常位置:'
STACK-TRACE: '&7 {0}. &4{1}'
OTHER:
HEAD:
- '&c插件 &4{0} &c运行时出现异常! &7(处理耗时: {1}ms)'
- '&c异常类型: &4{2}'
- '&c异常内容: &4{3}'
- '&c异常位置:'
STACK-TRACE: '&7 {0}. &4{1}'