Further refactoring, move away from using future thread pool

This commit is contained in:
William278 committed 2023-03-04 21:38:53 +00:00
1 parent 4c90e5498c
commit 39e0b25d46
56 files changed
+737 -1713

No files matched your search

@@ -8,7 +8,7 @@ import net.william278.huskhomes.command.BukkitCommand;
import net.william278.huskhomes.command.BukkitCommandType;
import net.william278.huskhomes.command.CommandBase;
import net.william278.huskhomes.command.DisabledCommand;
import net.william278.huskhomes.config.CachedSpawn;
import net.william278.huskhomes.config.Spawn;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.database.Database;
@@ -23,8 +23,6 @@ import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.PluginMessageBroker;
import net.william278.huskhomes.network.RedisBroker;
import net.william278.huskhomes.migrator.LegacyMigrator;
import net.william278.huskhomes.migrator.Migrator;
import net.william278.huskhomes.user.BukkitUser;
import net.william278.huskhomes.user.OnlineUser;
import net.william278.huskhomes.position.Location;
@@ -32,7 +30,6 @@ import net.william278.huskhomes.position.Server;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.NormalDistributionEngine;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.request.RequestManager;
import net.william278.huskhomes.util.*;
import org.bstats.bukkit.Metrics;
import org.bstats.charts.SimplePie;
@@ -71,17 +68,15 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
private BukkitLogger logger;
private Database database;
private Cache cache;
private RequestManager requestManager;
private Validator validator;
private Manager manager;
private EventListener eventListener;
private RandomTeleportEngine randomTeleportEngine;
private CachedSpawn serverSpawn;
private Spawn serverSpawn;
private UnsafeBlocks unsafeBlocks;
private EventDispatcher eventDispatcher;
private Set<PluginHook> pluginHooks;
private List<CommandBase> registeredCommands;
private List<Migrator> migrators;
private Server server;
@Nullable
@@ -114,17 +109,11 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
// Create adventure audience
this.audiences = BukkitAudiences.create(this);
// Detect if an upgrade is needed
final BukkitUpgradeUtil upgradeData = BukkitUpgradeUtil.detect(this);
// Load settings and locales
getLoggingAdapter().log(Level.INFO, "Loading plugin configuration settings & locales...");
initialized.set(reload());
if (initialized.get()) {
logger.showDebugLogs(settings.doDebugLogging());
if (upgradeData != null) {
upgradeData.upgradeSettings(settings);
}
getLoggingAdapter().log(Level.INFO, "Successfully loaded plugin configuration settings & locales");
} else {
throw new IllegalStateException("Failed to load plugin configuration settings and/or locales");
@@ -158,9 +147,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
// Prepare the validator
this.validator = new Validator(this);
// Prepare the request manager
this.requestManager = new RequestManager(this);
// Prepare the event dispatcher
this.eventDispatcher = new BukkitEventDispatcher(this);
@@ -175,14 +161,14 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
// Register plugin hooks (Economy, Maps, Plan)
this.pluginHooks = new HashSet<>();
if (settings.isEconomy()) {
if (settings.doEconomy()) {
if (Bukkit.getPluginManager().getPlugin("RedisEconomy") != null) {
pluginHooks.add(new RedisEconomyHook(this));
} else if (Bukkit.getPluginManager().getPlugin("Vault") != null) {
pluginHooks.add(new VaultEconomyHook(this));
}
}
if (settings.isDoMapHook()) {
if (settings.doMapHook()) {
switch (settings.getMappingPlugin()) {
case DYNMAP -> {
final Plugin dynmapPlugin = Bukkit.getPluginManager().getPlugin("Dynmap");
@@ -243,10 +229,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
});
getLoggingAdapter().log(Level.INFO, "Successfully registered permissions & commands.");
// Prepare migrators
this.migrators = new ArrayList<>();
this.migrators.add(new LegacyMigrator(this));
// Hook into bStats metrics
registerMetrics(METRICS_ID);
@@ -255,18 +237,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
getLoggingAdapter().log(Level.INFO, "Checking for updates...");
getLatestVersionIfOutdated().thenAccept(newestVersion -> newestVersion.ifPresent(newVersion -> getLoggingAdapter().log(Level.WARNING, "An update is available for HuskHomes, v" + newVersion + " (Currently running v" + getVersion() + ")")));
}
// Perform automatic upgrade if detected
if (upgradeData != null) {
getLoggingAdapter().log(Level.INFO, "Performing automatic upgrade...");
new LegacyMigrator(this, upgradeData).start().thenAccept(result -> {
if (result) {
getLoggingAdapter().log(Level.INFO, "Successfully performed automatic upgrade.");
} else {
getLoggingAdapter().log(Level.WARNING, "Failed to perform automatic upgrade.");
}
});
}
} catch (IllegalStateException exception) {
getLoggingAdapter().log(Level.SEVERE, exception.getMessage());
initialized.set(false);
@@ -346,12 +316,6 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
return cache;
}
@Override
@NotNull
public RequestManager getRequestManager() {
return requestManager;
}
@Override
@NotNull
public Validator getValidator() {
@@ -391,18 +355,13 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
}
@Override
public List<Migrator> getMigrators() {
return migrators;
}
@Override
public Optional<CachedSpawn> getLocalCachedSpawn() {
public Optional<Spawn> getLocalCachedSpawn() {
return Optional.ofNullable(serverSpawn);
}
@Override
public void setServerSpawn(@NotNull Location location) {
final CachedSpawn newSpawn = new CachedSpawn(location);
final Spawn newSpawn = new Spawn(location);
this.serverSpawn = newSpawn;
try {
Annotaml.create(new File(getDataFolder(), "spawn.yml"), newSpawn);
@@ -502,7 +461,7 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
// Load spawn location from file
final File spawnFile = new File(getDataFolder(), "spawn.yml");
if (spawnFile.exists()) {
this.serverSpawn = Annotaml.create(spawnFile, CachedSpawn.class).get();
this.serverSpawn = Annotaml.create(spawnFile, Spawn.class).get();
}
// Load unsafe blocks from resources
@@ -531,9 +490,9 @@ public class BukkitHuskHomes extends JavaPlugin implements HuskHomes, PluginMess
}
metrics.addCustomChart(new SimplePie("language", () -> getSettings().getLanguage().toLowerCase()));
metrics.addCustomChart(new SimplePie("database_type", () -> getSettings().getDatabaseType().displayName));
metrics.addCustomChart(new SimplePie("using_economy", () -> Boolean.toString(getSettings().isEconomy())));
metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().isDoMapHook())));
if (getSettings().isDoMapHook()) {
metrics.addCustomChart(new SimplePie("using_economy", () -> Boolean.toString(getSettings().doEconomy())));
metrics.addCustomChart(new SimplePie("using_map", () -> Boolean.toString(getSettings().doMapHook())));
if (getSettings().doMapHook()) {
metrics.addCustomChart(new SimplePie("map_type", () -> getSettings().getMappingPlugin().displayName));
}
} catch (Exception e) {
@@ -98,14 +98,25 @@ public class HuskHomesAPI extends BaseHuskHomesAPI {
* @param location the bukkit location to get the {@link Position} instance for
* @param server the {@link Server} the position is on
* @return the {@link Position} instance for the given bukkit {@link Location} on the given {@link Server}
* @see Position#server
* @since 3.0
* @see Position#getServer() to get the server the position is on
* @since 4.0
*/
@Nullable
@NotNull
public Position adaptPosition(@NotNull org.bukkit.Location location, @NotNull String server) {
return new Position(Objects.requireNonNull(adaptLocation(location)), server);
}
/**
* Returns a {@link Position} instance for the given bukkit {@link Location} on the server the plugin is running on.
* @param location the bukkit location to get the {@link Position} instance for
* @return the {@link Position} instance for the given bukkit {@link Location} on the server the plugin is running on
* @since 4.0
*/
@NotNull
public Position adaptPosition(@NotNull org.bukkit.Location location) {
return new Position(Objects.requireNonNull(adaptLocation(location)), getServer());
}
/**
* Get the {@link Server}, containing the ID of the server the plugin is running on
*
@@ -1,212 +0,0 @@
package net.william278.huskhomes.migrator;
import net.william278.huskhomes.HuskHomes;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.util.BukkitUpgradeUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
public class LegacyMigrator extends Migrator {
public Database.DatabaseType sourceDatabaseType;
public String sourceMySqlHost;
public int sourceMySqlPort;
public String sourceMySqlDatabase;
public String sourceMySqlUsername;
public String sourceMySqlPassword;
public String sourcePlayerDataTable = "huskhomes_player_data";
public String sourceLocationsDataTable = "huskhomes_location_data";
public String sourceHomesDataTable = "huskhomes_home_data";
public String sourceWarpsDataTable = "huskhomes_warp_data";
public LegacyMigrator(@NotNull HuskHomes implementor) {
super(implementor);
this.sourceDatabaseType = implementor.getSettings().getDatabaseType();
this.sourceMySqlHost = implementor.getSettings().getMySqlHost();
this.sourceMySqlPort = implementor.getSettings().getMySqlPort();
this.sourceMySqlDatabase = implementor.getSettings().getMySqlDatabase();
this.sourceMySqlUsername = implementor.getSettings().getMySqlUsername();
this.sourceMySqlPassword = implementor.getSettings().getMySqlPassword();
}
public LegacyMigrator(@NotNull HuskHomes implementor, @NotNull BukkitUpgradeUtil bukkitUpgradeUtil) {
super(implementor);
this.sourceDatabaseType = bukkitUpgradeUtil.databaseType;
this.sourceMySqlHost = bukkitUpgradeUtil.mySqlHost;
this.sourceMySqlPort = bukkitUpgradeUtil.mySqlPort;
this.sourceMySqlDatabase = bukkitUpgradeUtil.mySqlDatabase;
this.sourceMySqlUsername = bukkitUpgradeUtil.mySqlUsername;
this.sourceMySqlPassword = bukkitUpgradeUtil.mySqlPassword;
this.sourcePlayerDataTable = bukkitUpgradeUtil.sourcePlayerDataTable;
this.sourceLocationsDataTable = bukkitUpgradeUtil.sourceLocationsDataTable;
this.sourceHomesDataTable = bukkitUpgradeUtil.sourceHomesDataTable;
this.sourceWarpsDataTable = bukkitUpgradeUtil.sourceWarpsDataTable;
}
@Override
public CompletableFuture<Boolean> start() {
return CompletableFuture.supplyAsync(() -> {
if (sourceDatabaseType == Database.DatabaseType.SQLITE) {
migrateSqLiteDatabase();
return true;
}
if (sourceDatabaseType == plugin.getSettings().getDatabaseType()
&& sourceMySqlHost.equals(plugin.getSettings().getMySqlHost())
&& sourceMySqlPort == plugin.getSettings().getMySqlPort()) {
migrateMySqlDatabase();
return true;
}
plugin.getLoggingAdapter().log(Level.SEVERE, "Migration failed! Different source and target databases/types." +
"Please dump your data from your source database manually and then" +
" import it to your new database, then attempt migration again.");
return false;
});
}
private void migrateSqLiteDatabase() {
plugin.getLoggingAdapter().log(Level.INFO, "Migrating SQLite database, please wait... This may take a while!");
// Execute the migration script
try {
plugin.getDatabase().runScript(Objects.requireNonNull(plugin.getResource("database/migrator/sqlite_migrator.sql")),
Map.of("%target_positions_table%", plugin.getSettings().getTableName(Database.TableName.POSITION_DATA),
"%source_positions_table%", sourceLocationsDataTable,
"%target_users_table%", plugin.getSettings().getTableName(Database.TableName.PLAYER_DATA),
"%source_users_table%", sourcePlayerDataTable,
"%target_saved_positions%", plugin.getSettings().getTableName(Database.TableName.SAVED_POSITION_DATA),
"%source_homes_table%", sourceHomesDataTable,
"%target_homes_table%", plugin.getSettings().getTableName(Database.TableName.HOME_DATA),
"%source_warps_table%", sourceWarpsDataTable,
"%target_warps_table%", plugin.getSettings().getTableName(Database.TableName.WARP_DATA)));
plugin.getLoggingAdapter().log(Level.INFO, "SQLite Migration complete!");
} catch (Exception e) {
plugin.getLoggingAdapter().log(Level.SEVERE, "Migration of SQLite database failed!" +
" Perhaps the target tables was not clean?", e);
}
}
private void migrateMySqlDatabase() {
plugin.getLoggingAdapter().log(Level.INFO, "Migrating MySQL database, please wait... This may take a while!");
// Execute the migration script
try {
plugin.getDatabase().runScript(Objects.requireNonNull(plugin.getResource("database/migrator/mysql_migrator.sql")),
Map.of("%target_positions_table%", plugin.getSettings().getTableName(Database.TableName.POSITION_DATA),
"%source_positions_table%", sourceLocationsDataTable,
"%target_users_table%", plugin.getSettings().getTableName(Database.TableName.PLAYER_DATA),
"%source_users_table%", sourcePlayerDataTable,
"%target_saved_positions%", plugin.getSettings().getTableName(Database.TableName.SAVED_POSITION_DATA),
"%source_homes_table%", sourceHomesDataTable,
"%target_homes_table%", plugin.getSettings().getTableName(Database.TableName.HOME_DATA),
"%source_warps_table%", sourceWarpsDataTable,
"%target_warps_table%", plugin.getSettings().getTableName(Database.TableName.WARP_DATA),
"%source_database%", sourceMySqlDatabase));
plugin.getLoggingAdapter().log(Level.INFO, "MySQL Migration complete!");
} catch (Exception e){
plugin.getLoggingAdapter().log(Level.SEVERE, "Migration of MySQL database failed!" +
" Perhaps the target tables was not clean?", e);
}
}
@Override
public void handleConfigurationCommand(@NotNull String[] args) {
if (args.length == 2) {
if (switch (args[0].toLowerCase()) {
case "database" -> {
this.sourceMySqlDatabase = args[1];
yield true;
}
case "player_data_table" -> {
this.sourcePlayerDataTable = args[1];
yield true;
}
case "locations_data_table" -> {
this.sourceLocationsDataTable = args[1];
yield true;
}
case "homes_data_table" -> {
this.sourceHomesDataTable = args[1];
yield true;
}
case "warps_data_table" -> {
this.sourceWarpsDataTable = args[1];
yield true;
}
default -> false;
}) {
plugin.getLoggingAdapter().log(Level.INFO, getHelpMenu());
plugin.getLoggingAdapter().log(Level.INFO, "Successfully set " + args[0] + " to " +
obfuscateDataString(args[1]));
} else {
plugin.getLoggingAdapter().log(Level.INFO, "Invalid operation, could not set " + args[0] + " to " +
obfuscateDataString(args[1]) + " (is it a valid option?)");
}
} else {
plugin.getLoggingAdapter().log(Level.INFO, getHelpMenu());
}
}
@Override
public @NotNull String getIdentifier() {
return "legacy";
}
@Override
public @NotNull String getName() {
return "HuskHomes Legacy (v2.x)";
}
@NotNull
@Override
public String getHelpMenu() {
return """
=== HuskHomes v2.x --> v3.x Migration Wizard =========
This will migrate all user data from HuskHomes v2.x
to HuskHomes v3.x. The source and target databases
must be the same, please note.
[!] Existing data in the database will be wiped. [!]
STEP 1] Please ensure no players are on any servers
running HuskHomes. If you're running MySQL, you only
need to do this once - it's best to only have one
server running.
STEP 2] Ensure the following settings are correct:
Source table names:
- player_data: %source_players_table%
- locations_data: %source_locations_table%
- homes_data: %source_homes_table%
- warps_data: %source_warps_table%
Source MySQL database name (ignore if using SQLite):
- database: %source_mysql_database%
If any of these are not correct, please correct them
using the command:
"huskhomes migrate legacy set <parameter> <value>"
(e.g.: "huskhomes migrate legacy set database foo")
STEP 3] HuskHomes will migrate data into the database
tables configured in the config.yml file of this
server. Please make sure you're happy with this
before proceeding.
STEP 4] To start the migration, please run:
"huskhomes migrate legacy start"
""".replaceAll("%source_players_table%", sourcePlayerDataTable)
.replaceAll("%source_locations_table%", sourceLocationsDataTable)
.replaceAll("%source_homes_table%", sourceHomesDataTable)
.replaceAll("%source_warps_table%", sourceWarpsDataTable)
.replaceAll("%source_mysql_database%", sourceMySqlDatabase);
}
}
@@ -1,17 +1,17 @@
package net.william278.huskhomes.util;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.HuskHomes;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
public interface BukkitTaskRunner extends TaskRunner {
@Override
default void runAsync(@NotNull Runnable runnable) {
Bukkit.getScheduler().runTaskAsynchronously((BukkitHuskHomes) getPlugin(), runnable);
default int runAsync(@NotNull Runnable runnable) {
return Bukkit.getScheduler().runTaskAsynchronously((BukkitHuskHomes) getPlugin(), runnable).getTaskId();
}
@Override
@@ -23,8 +23,21 @@ public interface BukkitTaskRunner extends TaskRunner {
}
@Override
default void runSync(@NotNull Runnable runnable) {
Bukkit.getScheduler().runTask((BukkitHuskHomes) getPlugin(), runnable);
default int runSync(@NotNull Runnable runnable) {
return Bukkit.getScheduler().runTask((BukkitHuskHomes) getPlugin(), runnable).getTaskId();
}
@Override
default int runAsyncRepeating(@NotNull Runnable runnable, long period) {
AtomicInteger taskId = new AtomicInteger();
taskId.set(Bukkit.getScheduler().runTaskTimerAsynchronously((BukkitHuskHomes) getPlugin(),
runnable, 0, period).getTaskId());
return taskId.get();
}
@Override
default void cancelTask(int taskId) {
Bukkit.getScheduler().cancelTask(taskId);
}
}
@@ -1,88 +0,0 @@
package net.william278.huskhomes.util;
import net.william278.annotaml.Annotaml;
import net.william278.huskhomes.BukkitHuskHomes;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.database.Database;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
/**
* Utility class for upgrading important stuff from HuskHomes v2.x config files to v3.x.
*/
public class BukkitUpgradeUtil {
private final BukkitHuskHomes plugin;
public Database.DatabaseType databaseType;
public String mySqlHost;
public int mySqlPort;
public String mySqlDatabase;
public String mySqlUsername;
public String mySqlPassword;
public String mySqlParams;
public String sourcePlayerDataTable;
public String sourceLocationsDataTable;
public String sourceHomesDataTable;
public String sourceWarpsDataTable;
private BukkitUpgradeUtil(@NotNull BukkitHuskHomes plugin) {
this.plugin = plugin;
}
/**
* Reads old settings from the config and writes them to the new config.
*/
private void readOldSettings() {
this.databaseType = Database.DatabaseType.valueOf(plugin.getConfig()
.getString("data_storage_options.storage_type", "SQLITE").toUpperCase());
this.mySqlHost = plugin.getConfig().getString("data_storage_options.mysql_credentials.host", "localhost");
this.mySqlPort = plugin.getConfig().getInt("data_storage_options.mysql_credentials.port", 3306);
this.mySqlDatabase = plugin.getConfig().getString("data_storage_options.mysql_credentials.database", "HuskHomes");
this.mySqlUsername = plugin.getConfig().getString("data_storage_options.mysql_credentials.username", "root");
this.mySqlPassword = plugin.getConfig().getString("data_storage_options.mysql_credentials.password", "pa55w0rd");
this.mySqlParams = plugin.getConfig().getString("data_storage_options.mysql_credentials.params", "?autoReconnect=true&useSSL=false");
this.sourcePlayerDataTable = plugin.getConfig().getString("data_storage_options.table_names.player_data", "huskhomes_player_data");
this.sourceLocationsDataTable = plugin.getConfig().getString("data_storage_options.table_names.locations_data", "huskhomes_location_data");
this.sourceHomesDataTable = plugin.getConfig().getString("data_storage_options.table_names.homes_data", "huskhomes_home_data");
this.sourceWarpsDataTable = plugin.getConfig().getString("data_storage_options.table_names.warps_data", "huskhomes_warp_data");
}
/**
* Upgrade the config from an older version to the current version.
*
* @param settings The settings to upgrade
*/
public void upgradeSettings(@NotNull Settings settings) {
plugin.getLoggingAdapter().log(Level.WARNING, "Upgrading critical HuskHomes v2.x settings to v3.x.");
settings.databaseType = databaseType;
settings.mySqlHost = mySqlHost;
settings.mySqlPort = mySqlPort;
settings.mySqlDatabase = mySqlDatabase;
settings.mySqlUsername = mySqlUsername;
settings.mySqlPassword = mySqlPassword;
settings.mySqlConnectionParameters = mySqlParams;
try {
Annotaml.create(new File(plugin.getDataFolder(), "config.yml"), settings);
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, "Failed to upgrade HuskHomes settings from a legacy version", e);
}
}
@Nullable
public static BukkitUpgradeUtil detect(@NotNull BukkitHuskHomes plugin) {
if (!plugin.getConfig().contains("config_file_version")) {
return null;
}
final BukkitUpgradeUtil upgrade = new BukkitUpgradeUtil(plugin);
upgrade.readOldSettings();
return upgrade;
}
}