Cleanup all migration commands - closes #63

This commit is contained in:
Luck 2017-02-01 18:41:15 +00:00
parent f7b281f655
commit 9cee319ed9
No known key found for this signature in database
GPG Key ID: EFA9B3EC5FD90F8B
11 changed files with 576 additions and 830 deletions

View File

@ -33,15 +33,12 @@ import me.lucko.luckperms.api.MetaUtils;
import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.SubCommand;
import me.lucko.luckperms.common.commands.migration.MigrationLogger;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Constants;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@ -50,7 +47,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.concurrent.atomic.AtomicInteger;
import static me.lucko.luckperms.common.constants.Permission.MIGRATION;
@ -68,6 +65,101 @@ public class MigrationBPermissions extends SubCommand<Object> {
}
}
public MigrationBPermissions() {
super("bpermissions", "Migration from bPermissions", MIGRATION, Predicates.alwaysFalse(), null);
}
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) throws CommandException {
MigrationLogger log = new MigrationLogger("bPermissions");
log.addListener(plugin.getConsoleSender());
log.addListener(sender);
log.log("Starting.");
WorldManager worldManager = WorldManager.getInstance();
if (worldManager == null) {
log.logErr("Plugin not loaded.");
return CommandResult.STATE_ERROR;
}
log.log("Forcing the plugin to load all data. This could take a while.");
for (World world : worldManager.getAllWorlds()) {
log.log("Loading users in world " + world.getName());
Set<String> users = getUsers(world);
if (users == null) {
log.logErr("Couldn't get a list of users.");
return CommandResult.FAILURE;
}
AtomicInteger userLoadCount = new AtomicInteger(0);
users.forEach(s -> {
world.loadOne(s, CalculableType.USER);
log.logProgress("Forcefully loaded {} users so far.", userLoadCount.incrementAndGet());
});
}
log.log("Forcefully loaded all users.");
// Migrate one world at a time.
log.log("Starting world migration.");
for (World world : worldManager.getAllWorlds()) {
log.log("Migrating world: " + world.getName());
// Migrate all groups
log.log("Starting group migration in world " + world.getName() + ".");
AtomicInteger groupCount = new AtomicInteger(0);
for (Calculable group : world.getAll(CalculableType.GROUP)) {
String groupName = group.getName().toLowerCase();
if (group.getName().equalsIgnoreCase(world.getDefaultGroup())) {
groupName = "default";
}
// Make a LuckPerms group for the one being migrated.
plugin.getStorage().createAndLoadGroup(groupName).join();
me.lucko.luckperms.common.core.model.Group lpGroup = plugin.getGroupManager().getIfLoaded(groupName);
migrateHolder(log, world, group, lpGroup);
plugin.getStorage().saveGroup(lpGroup);
log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
}
log.log("Migrated " + groupCount.get() + " groups in world " + world.getName() + ".");
// Migrate all users
log.log("Starting user migration in world " + world.getName() + ".");
AtomicInteger userCount = new AtomicInteger(0);
for (Calculable user : world.getAll(CalculableType.USER)) {
// There is no mention of UUIDs in the API. I assume that name = uuid. idk?
UUID uuid;
try {
uuid = UUID.fromString(user.getName());
} catch (IllegalArgumentException e) {
uuid = plugin.getUuidFromUsername(user.getName());
}
if (uuid == null) {
log.logErr("Unable to migrate user " + user.getName() + ". Cannot to get UUID.");
continue;
}
// Make a LuckPerms user for the one being migrated.
plugin.getStorage().loadUser(uuid, "null").join();
User lpUser = plugin.getUserManager().get(uuid);
migrateHolder(log, world, user, lpUser);
plugin.getStorage().saveUser(lpUser);
plugin.getUserManager().cleanup(lpUser);
log.logProgress("Migrated {} users so far.", userCount.incrementAndGet());
}
log.log("Migrated " + userCount.get() + " users in world " + world.getName() + ".");
}
log.log("Success! Migration complete.");
return CommandResult.SUCCESS;
}
@SuppressWarnings("unchecked")
private static Set<String> getUsers(World world) {
try {
@ -94,33 +186,21 @@ public class MigrationBPermissions extends SubCommand<Object> {
}
}
private static void migrateHolder(LuckPermsPlugin plugin, World world, Calculable c, PermissionHolder holder) {
private static void migrateHolder(MigrationLogger log, World world, Calculable c, PermissionHolder holder) {
// Migrate the groups permissions in this world
for (Permission p : c.getPermissions()) {
try {
holder.setPermission(p.name(), p.isTrue(), "global", world.getName());
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("set " + p.name() + " " + p.isTrue() + " global " + world.getName())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
// Include any child permissions
for (Map.Entry<String, Boolean> child : p.getChildren().entrySet()) {
try {
holder.setPermission(child.getKey(), child.getValue(), "global", world.getName());
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("set " + child.getKey() + " " + child.getValue() + " global " + world.getName())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
}
@ -129,14 +209,8 @@ public class MigrationBPermissions extends SubCommand<Object> {
for (Group parent : c.getGroups()) {
try {
holder.setPermission("group." + parent.getName(), true, "global", world.getName());
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("setinherit " + parent.getName() + " global " + world.getName())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -146,127 +220,18 @@ public class MigrationBPermissions extends SubCommand<Object> {
String chatMeta = MetaUtils.escapeCharacters(meta.getValue());
try {
holder.setPermission(meta.getKey().toLowerCase() + "." + c.getPriority() + "." + chatMeta, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("set " + meta.getKey().toLowerCase() + "." + c.getPriority() + "." + chatMeta + " true")
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
continue;
}
try {
holder.setPermission("meta." + meta.getKey() + "." + meta.getValue(), true, "global", world.getName());
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("set meta." + meta.getKey() + "." + meta.getValue() + " true global " + world.getName())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
}
public MigrationBPermissions() {
super("bpermissions", "Migration from bPermissions", MIGRATION, Predicates.alwaysFalse(), null);
}
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) throws CommandException {
Consumer<String> log = s -> {
Message.MIGRATION_LOG.send(sender, s);
if (!sender.isConsole()) {
Message.MIGRATION_LOG.send(plugin.getConsoleSender(), s);
}
};
log.accept("Starting bPermissions migration.");
WorldManager worldManager = WorldManager.getInstance();
if (worldManager == null) {
log.accept("Error -> bPermissions is not loaded.");
return CommandResult.STATE_ERROR;
}
log.accept("Forcing the plugin to load all data. This could take a while.");
for (World world : worldManager.getAllWorlds()) {
Set<String> users = getUsers(world);
if (users == null) {
log.accept("Couldn't get a list of users.");
return CommandResult.FAILURE;
}
users.forEach(s -> world.loadOne(s, CalculableType.USER));
}
// Migrate one world at a time.
log.accept("Starting world migration.");
for (World world : worldManager.getAllWorlds()) {
log.accept("Migrating world: " + world.getName());
// Migrate all groups
log.accept("Starting group migration in world " + world.getName() + ".");
int groupCount = 0;
for (Calculable group : world.getAll(CalculableType.GROUP)) {
groupCount++;
String groupName = group.getName().toLowerCase();
if (group.getName().equalsIgnoreCase(world.getDefaultGroup())) {
groupName = "default";
}
// Make a LuckPerms group for the one being migrated.
plugin.getStorage().createAndLoadGroup(groupName).join();
me.lucko.luckperms.common.core.model.Group lpGroup = plugin.getGroupManager().getIfLoaded(groupName);
try {
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpGroup).action("create")
.build().submit(plugin);
} catch (Exception ex) {
ex.printStackTrace();
}
migrateHolder(plugin, world, group, lpGroup);
plugin.getStorage().saveGroup(lpGroup);
}
log.accept("Migrated " + groupCount + " groups in world " + world.getName() + ".");
// Migrate all users
log.accept("Starting user migration in world " + world.getName() + ".");
int userCount = 0;
for (Calculable user : world.getAll(CalculableType.USER)) {
userCount++;
// There is no mention of UUIDs in the API. I assume that name = uuid. idk?
UUID uuid;
try {
uuid = UUID.fromString(user.getName());
} catch (IllegalArgumentException e) {
uuid = plugin.getUuidFromUsername(user.getName());
}
if (uuid == null) {
log.accept("Unable to migrate user " + user.getName() + ". Unable to get UUID.");
continue;
}
// Make a LuckPerms user for the one being migrated.
plugin.getStorage().loadUser(uuid, "null").join();
User lpUser = plugin.getUserManager().get(uuid);
migrateHolder(plugin, world, user, lpUser);
plugin.getStorage().saveUser(lpUser);
plugin.getUserManager().cleanup(lpUser);
}
log.accept("Migrated " + userCount + " users in world " + world.getName() + ".");
}
log.accept("Success! Completed without any errors.");
return CommandResult.SUCCESS;
}
}

View File

@ -22,16 +22,15 @@
package me.lucko.luckperms.bukkit.migration;
import com.google.common.collect.Maps;
import me.lucko.luckperms.common.commands.Arg;
import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.SubCommand;
import me.lucko.luckperms.common.commands.migration.MigrationLogger;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Constants;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.NodeFactory;
import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
@ -44,58 +43,55 @@ import org.anjocaido.groupmanager.data.User;
import org.anjocaido.groupmanager.dataholder.WorldDataHolder;
import org.anjocaido.groupmanager.dataholder.worlds.WorldsHolder;
import org.bukkit.Bukkit;
import org.bukkit.World;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
public class MigrationGroupManager extends SubCommand<Object> {
public MigrationGroupManager() {
super("groupmanager", "Migration from GroupManager", Permission.MIGRATION, Predicates.is(0),
Arg.list(Arg.create("world names...", false, "a list of worlds to migrate permissions from"))
Arg.list(Arg.create("migrate as global", true, "if world permissions should be ignored, and just migrated as global"))
);
}
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) throws CommandException {
Consumer<String> log = s -> {
Message.MIGRATION_LOG.send(sender, s);
if (!sender.isConsole()) {
Message.MIGRATION_LOG.send(plugin.getConsoleSender(), s);
}
};
log.accept("Starting GroupManager migration.");
MigrationLogger log = new MigrationLogger("GroupManager");
log.addListener(plugin.getConsoleSender());
log.addListener(sender);
log.log("Starting.");
if (!args.get(0).equalsIgnoreCase("true") && !args.get(0).equalsIgnoreCase("false")) {
log.logErr("Was expecting true/false, but got " + args.get(0) + " instead.");
return CommandResult.STATE_ERROR;
}
boolean migrateAsGlobal = Boolean.parseBoolean(args.get(0));
final Function<String, String> worldMappingFunc = s -> migrateAsGlobal ? "" : s;
if (!Bukkit.getPluginManager().isPluginEnabled("GroupManager")) {
log.accept("Error -> GroupManager is not loaded.");
log.logErr("Plugin not loaded.");
return CommandResult.STATE_ERROR;
}
final List<String> worlds = args.stream()
.map(String::toLowerCase)
.collect(Collectors.toList());
List<String> worlds = Bukkit.getWorlds().stream().map(World::getName).map(String::toLowerCase).collect(Collectors.toList());
GroupManager gm = (GroupManager) Bukkit.getPluginManager().getPlugin("GroupManager");
// Migrate Global Groups
log.accept("Starting Global Group migration.");
log.log("Starting global group migration.");
GlobalGroups gg = GroupManager.getGlobalGroups();
AtomicInteger globalGroupCount = new AtomicInteger(0);
for (Group g : gg.getGroupList()) {
plugin.getStorage().createAndLoadGroup(g.getName().toLowerCase()).join();
me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(g.getName().toLowerCase());
try {
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("create")
.build().submit(plugin);
} catch (Exception ex) {
ex.printStackTrace();
}
for (String node : g.getPermissionList()) {
boolean value = true;
@ -109,47 +105,45 @@ public class MigrationGroupManager extends SubCommand<Object> {
try {
group.setPermission(node, value);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("set " + node + " " + value)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
for (String s : g.getInherits()) {
try {
group.setPermission("group." + s.toLowerCase(), true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("setinherit " + s.toLowerCase())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
plugin.getStorage().saveGroup(group);
log.logAllProgress("Migrated {} groups so far.", globalGroupCount.incrementAndGet());
}
log.log("Migrated " + globalGroupCount.get() + " global groups");
// Collect data
// UUID --> Map<Entry<String, String>, Boolean> where k=world, v = node
Map<UUID, Map<Map.Entry<String, String>, Boolean>> users = new HashMap<>();
// UUID --> primary group name
Map<UUID, String> primaryGroups = new HashMap<>();
// String --> Map<Entry<String, String>, Boolean> where k=world, v = node
Map<String, Map<Map.Entry<String, String>, Boolean>> groups = new HashMap<>();
WorldsHolder wh = gm.getWorldsHolder();
// Collect data for all users and groups.
log.accept("Starting user and group migration.");
log.log("Collecting user and group data.");
for (String world : worlds) {
world = world.toLowerCase();
log.log("Querying world " + world);
WorldDataHolder wdh = wh.getWorldData(world);
AtomicInteger groupWorldCount = new AtomicInteger(0);
for (Group g : wdh.getGroupList()) {
groups.putIfAbsent(g.getName().toLowerCase(), new HashMap<>());
@ -163,19 +157,23 @@ public class MigrationGroupManager extends SubCommand<Object> {
value = true;
}
groups.get(g.getName().toLowerCase()).put(new AbstractMap.SimpleEntry<>(world, node), value);
groups.get(g.getName().toLowerCase()).put(Maps.immutableEntry(worldMappingFunc.apply(world), node), value);
}
for (String s : g.getInherits()) {
groups.get(g.getName().toLowerCase()).put(new AbstractMap.SimpleEntry<>(world, "group." + s.toLowerCase()), true);
groups.get(g.getName().toLowerCase()).put(Maps.immutableEntry(worldMappingFunc.apply(world), "group." + s.toLowerCase()), true);
}
log.logAllProgress("Migrated {} groups so far in world " + world, groupWorldCount.incrementAndGet());
}
log.log("Migrated " + groupWorldCount.get() + " groups in world " + world);
AtomicInteger userWorldCount = new AtomicInteger(0);
for (User user : wdh.getUserList()) {
UUID uuid;
try {
uuid = UUID.fromString(user.getUUID());
} catch (IllegalArgumentException e) {
log.logErr("Could not parse UUID for user: " + user.getUUID());
continue;
}
@ -191,66 +189,56 @@ public class MigrationGroupManager extends SubCommand<Object> {
value = true;
}
users.get(uuid).put(new AbstractMap.SimpleEntry<>(world, node), value);
users.get(uuid).put(Maps.immutableEntry(worldMappingFunc.apply(world), node), value);
}
String finalWorld = world;
String finalWorld = worldMappingFunc.apply(world);
// Collect sub groups
users.get(uuid).putAll(user.subGroupListStringCopy().stream()
.map(n -> "group." + n)
.map(n -> new AbstractMap.SimpleEntry<>(finalWorld, n))
.map(n -> Maps.immutableEntry(finalWorld, n))
.collect(Collectors.toMap(n -> n, n -> true))
);
primaryGroups.put(uuid, user.getGroupName());
log.logProgress("Migrated {} users so far in world " + world, userWorldCount.incrementAndGet());
}
log.log("Migrated " + userWorldCount.get() + " users in world " + world);
}
log.accept("All existing GroupManager data has been processed. Now beginning the import process.");
log.accept("Found a total of " + users.size() + " users and " + groups.size() + " groups.");
log.log("All data has now been processed, now starting the import process.");
log.log("Found a total of " + users.size() + " users and " + groups.size() + " groups.");
log.log("Starting group migration.");
AtomicInteger groupCount = new AtomicInteger(0);
for (Map.Entry<String, Map<Map.Entry<String, String>, Boolean>> e : groups.entrySet()) {
plugin.getStorage().createAndLoadGroup(e.getKey()).join();
me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(e.getKey());
try {
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("create")
.build().submit(plugin);
} catch (Exception ex) {
ex.printStackTrace();
}
for (Map.Entry<Map.Entry<String, String>, Boolean> n : e.getValue().entrySet()) {
// n.key.key = world
// n.key.value = node
// n.value = true/false
try {
group.setPermission(NodeFactory.fromSerialisedNode("global-" + n.getKey().getKey() + "/" + n.getKey().getValue(), n.getValue()));
if (n.getKey().getValue().startsWith("group.")) {
String groupName = n.getKey().getValue().substring(6);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("setinherit " + groupName + " global " + n.getKey().getKey())
.build().submit(plugin);
if (n.getKey().getKey().equals("")) {
group.setPermission(n.getKey().getValue(), n.getValue());
} else {
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("set " + n.getKey().getValue() + " " + n.getValue() + " global " + n.getKey().getKey())
.build().submit(plugin);
group.setPermission(n.getKey().getValue(), n.getValue(), "global", n.getKey().getKey());
}
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
plugin.getStorage().saveGroup(group);
log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
}
log.log("Migrated " + groupCount.get() + " groups");
log.log("Starting user migration.");
AtomicInteger userCount = new AtomicInteger(0);
for (Map.Entry<UUID, Map<Map.Entry<String, String>, Boolean>> e : users.entrySet()) {
plugin.getStorage().loadUser(e.getKey(), "null").join();
me.lucko.luckperms.common.core.model.User user = plugin.getUserManager().get(e.getKey());
@ -260,25 +248,13 @@ public class MigrationGroupManager extends SubCommand<Object> {
// n.key.value = node
// n.value = true/false
try {
user.setPermission(NodeFactory.fromSerialisedNode("global-" + n.getKey().getKey() + "/" + n.getKey().getValue(), n.getValue()));
if (n.getKey().getValue().startsWith("group.")) {
String group = n.getKey().getValue().substring(6);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("addgroup " + group + " global " + n.getKey().getKey())
.build().submit(plugin);
if (n.getKey().getKey().equals("")) {
user.setPermission(n.getKey().getValue(), n.getValue());
} else {
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("set " + n.getKey().getValue() + " " + n.getValue() + " global " + n.getKey().getKey())
.build().submit(plugin);
user.setPermission(n.getKey().getValue(), n.getValue(), "global", n.getKey().getKey());
}
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -286,20 +262,20 @@ public class MigrationGroupManager extends SubCommand<Object> {
if (primaryGroup != null) {
try {
user.setPermission("group." + primaryGroup, true);
} catch (ObjectAlreadyHasException ignored) {
}
} catch (ObjectAlreadyHasException ignored) {}
user.setPrimaryGroup(primaryGroup);
try {
user.unsetPermission("group.default");
} catch (ObjectLacksException ignored) {
}
} catch (ObjectLacksException ignored) {}
}
plugin.getStorage().saveUser(user);
plugin.getUserManager().cleanup(user);
log.logProgress("Migrated {} users so far.", userCount.incrementAndGet());
}
log.accept("Success! Completed without any errors.");
log.log("Migrated " + userCount.get() + " users.");
log.log("Success! Migration complete.");
return CommandResult.SUCCESS;
}
}

View File

@ -23,23 +23,21 @@
package me.lucko.luckperms.bukkit.migration;
import me.lucko.luckperms.api.MetaUtils;
import me.lucko.luckperms.api.PlatformType;
import me.lucko.luckperms.common.commands.Arg;
import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.SubCommand;
import me.lucko.luckperms.common.commands.migration.MigrationLogger;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Constants;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.model.Group;
import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import org.bukkit.Bukkit;
import org.bukkit.World;
import ru.tehkode.permissions.NativeInterface;
import ru.tehkode.permissions.PermissionGroup;
@ -50,41 +48,29 @@ import ru.tehkode.permissions.bukkit.PermissionsEx;
import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class MigrationPermissionsEx extends SubCommand<Object> {
public MigrationPermissionsEx() {
super("permissionsex", "Migration from PermissionsEx", Permission.MIGRATION, Predicates.alwaysFalse(),
Arg.list(Arg.create("world names...", false, "a list of worlds to migrate permissions from"))
);
super("permissionsex", "Migration from PermissionsEx", Permission.MIGRATION, Predicates.alwaysFalse(), null);
}
@SuppressWarnings("deprecation")
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) throws CommandException {
Consumer<String> log = s -> {
Message.MIGRATION_LOG.send(sender, s);
if (!sender.isConsole()) {
Message.MIGRATION_LOG.send(plugin.getConsoleSender(), s);
}
};
log.accept("Starting PermissionsEx migration.");
MigrationLogger log = new MigrationLogger("PermissionsEx");
log.addListener(plugin.getConsoleSender());
log.addListener(sender);
log.log("Starting.");
if (!Bukkit.getPluginManager().isPluginEnabled("PermissionsEx")) {
log.accept("Error -> PermissionsEx is not loaded.");
log.logErr("Plugin not loaded.");
return CommandResult.STATE_ERROR;
}
if (plugin.getServerType() != PlatformType.BUKKIT) {
// Sponge uses a completely different version of PEX.
log.accept("PEX import is not supported on this platform.");
return CommandResult.STATE_ERROR;
}
final List<String> worlds = args.stream()
.map(String::toLowerCase)
.collect(Collectors.toList());
List<String> worlds = Bukkit.getWorlds().stream().map(World::getName).map(String::toLowerCase).collect(Collectors.toList());
PermissionsEx pex = (PermissionsEx) Bukkit.getPluginManager().getPlugin("PermissionsEx");
PermissionManager manager = pex.getPermissionsManager();
@ -99,28 +85,22 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
return CommandResult.FAILURE;
}
// Migrate all groups.
log.accept("Starting group migration.");
int maxGroupWeight = 0;
int groupCount = 0;
log.log("Calculating group weightings.");
int maxWeight = 0;
for (PermissionGroup group : manager.getGroupList()) {
int groupWeight = group.getWeight() * -1;
groupCount++;
maxGroupWeight = Math.max(maxGroupWeight, groupWeight);
maxWeight = Math.max(maxWeight, group.getRank());
}
maxWeight += 5;
// Migrate all groups.
log.log("Starting group migration.");
AtomicInteger groupCount = new AtomicInteger(0);
for (PermissionGroup group : manager.getGroupList()) {
int groupWeight = maxWeight - group.getRank();
final String name = group.getName().toLowerCase();
plugin.getStorage().createAndLoadGroup(name).join();
Group lpGroup = plugin.getGroupManager().getIfLoaded(name);
try {
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpGroup).action("create")
.build().submit(plugin);
} catch (Exception ex) {
ex.printStackTrace();
}
try {
for (String node : group.getOwnPermissions(null)) {
@ -132,40 +112,26 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
try {
lpGroup.setPermission(node, value);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpGroup).action("set " + node + " " + value)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
} catch (NullPointerException ignored) {
// Probably won't happen. I have no API docs on getOwnPermissions#null though.
// No docs on if #getOwnPermissions(null) is ok. Should be fine though.
}
if (worlds != null && !worlds.isEmpty()) {
for (String world : worlds) {
for (String node : group.getOwnPermissions(world)) {
boolean value = true;
if (node.startsWith("-")) {
node = node.substring(1);
value = false;
}
for (String world : worlds) {
for (String node : group.getOwnPermissions(world)) {
boolean value = true;
if (node.startsWith("-")) {
node = node.substring(1);
value = false;
}
try {
lpGroup.setPermission(node, value, "global", world);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpGroup).action("set " + node + " " + value + " global " + world)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
}
try {
lpGroup.setPermission(node, value, "global", world.toLowerCase());
} catch (Exception ex) {
log.handleException(ex);
}
}
}
@ -173,31 +139,17 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
for (PermissionGroup g : group.getParents()) {
try {
lpGroup.setPermission("group." + g.getName().toLowerCase(), true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpGroup).action("setinherit " + g.getName().toLowerCase())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
if (worlds != null && !worlds.isEmpty()) {
for (String world : worlds) {
for (PermissionGroup g : group.getParents(world)) {
try {
lpGroup.setPermission("group." + g.getName().toLowerCase(), true, "global", world);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpGroup).action("setinherit " + g.getName().toLowerCase() + " global " + world)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
}
for (String world : worlds) {
for (PermissionGroup g : group.getParents(world)) {
try {
lpGroup.setPermission("group." + g.getName().toLowerCase(), true, "global", world.toLowerCase());
} catch (Exception ex) {
log.handleException(ex);
}
}
}
@ -209,14 +161,8 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
prefix = MetaUtils.escapeCharacters(prefix);
try {
lpGroup.setPermission("prefix." + groupWeight + "." + prefix, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpGroup).action("set prefix." + groupWeight + "." + prefix + " true")
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -224,30 +170,25 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
suffix = MetaUtils.escapeCharacters(suffix);
try {
lpGroup.setPermission("suffix." + groupWeight + "." + suffix, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpGroup).action("set suffix." + groupWeight + "." + suffix + " true")
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
plugin.getStorage().saveGroup(lpGroup);
log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
}
log.accept("Migrated " + groupCount + " groups");
log.log("Migrated " + groupCount.get() + " groups");
// Migrate all users
log.accept("Starting user migration.");
int userCount = 0;
maxGroupWeight++;
for (PermissionUser user : manager.getUsers()) {
UUID u = null;
log.log("Starting user migration.");
AtomicInteger userCount = new AtomicInteger(0);
// Increment the max weight from the group migrations. All user meta should override.
maxWeight += 5;
for (PermissionUser user : manager.getUsers()) {
UUID u;
try {
u = UUID.fromString(user.getIdentifier());
} catch (IllegalArgumentException e) {
@ -258,11 +199,10 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
}
if (u == null) {
log.accept("Unable to get a UUID for user identifier: " + user.getIdentifier());
log.logErr("Unable to get a UUID for user identifier: " + user.getIdentifier());
continue;
}
userCount++;
plugin.getStorage().loadUser(u, user.getName()).join();
User lpUser = plugin.getUserManager().get(u);
@ -276,40 +216,26 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
try {
lpUser.setPermission(node, value);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpUser).action("set " + node + " " + value)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
} catch (NullPointerException ignored) {
// Probably won't happen. I have no API docs on getOwnPermissions#null though.
// No docs on if #getOwnPermissions(null) is ok. Should be fine though.
}
if (worlds != null && !worlds.isEmpty()) {
for (String world : worlds) {
for (String node : user.getOwnPermissions(world)) {
boolean value = true;
if (node.startsWith("-")) {
node = node.substring(1);
value = false;
}
for (String world : worlds) {
for (String node : user.getOwnPermissions(world)) {
boolean value = true;
if (node.startsWith("-")) {
node = node.substring(1);
value = false;
}
try {
lpUser.setPermission(node, value, "global", world);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpUser).action("set " + node + " " + value + " global " + world)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
}
try {
lpUser.setPermission(node, value, "global", world.toLowerCase());
} catch (Exception ex) {
log.handleException(ex);
}
}
}
@ -317,31 +243,17 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
for (String s : user.getGroupNames()) {
try {
lpUser.setPermission("group." + s.toLowerCase(), true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpUser).action("addgroup " + s.toLowerCase())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
if (worlds != null && !worlds.isEmpty()) {
for (String world : worlds) {
for (String s : user.getGroupNames(world)) {
try {
lpUser.setPermission("group." + s.toLowerCase(), true, "global", world);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpUser).action("addgroup " + s.toLowerCase() + " global " + world)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
}
for (String world : worlds) {
for (String s : user.getGroupNames(world)) {
try {
lpUser.setPermission("group." + s.toLowerCase(), true, "global", world.toLowerCase());
} catch (Exception ex) {
log.handleException(ex);
}
}
}
@ -352,56 +264,48 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
if (prefix != null && !prefix.equals("")) {
prefix = MetaUtils.escapeCharacters(prefix);
try {
lpUser.setPermission("prefix." + maxGroupWeight + "." + prefix, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpUser).action("set prefix." + maxGroupWeight + "." + prefix + " true")
.build().submit(plugin);
lpUser.setPermission("prefix." + maxWeight + "." + prefix, true);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
if (suffix != null && !suffix.equals("")) {
suffix = MetaUtils.escapeCharacters(suffix);
try {
lpUser.setPermission("suffix." + maxGroupWeight + "." + suffix, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(lpUser).action("set suffix." + maxGroupWeight + "." + suffix + " true")
.build().submit(plugin);
lpUser.setPermission("suffix." + maxWeight + "." + suffix, true);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
// Lowest rank is the highest group #logic
String primary = null;
int weight = -100;
int weight = Integer.MAX_VALUE;
for (PermissionGroup group : user.getOwnParents()) {
if (group.getRank() > weight) {
if (group.getRank() < weight) {
primary = group.getName();
weight = group.getWeight();
weight = group.getRank();
}
}
if (primary != null) {
if (primary != null && !primary.equalsIgnoreCase("default")) {
try {
lpUser.setPermission("group." + primary.toLowerCase(), true);
} catch (ObjectAlreadyHasException ignored) {
}
} catch (ObjectAlreadyHasException ignored) {}
lpUser.setPrimaryGroup(primary);
try {
lpUser.unsetPermission("group.default");
} catch (ObjectLacksException ignored) {}
}
plugin.getUserManager().cleanup(lpUser);
plugin.getStorage().saveUser(lpUser);
log.logProgress("Migrated {} users so far.", userCount.incrementAndGet());
}
log.accept("Migrated " + userCount + " users.");
log.accept("Success! Completed without any errors.");
log.log("Migrated " + userCount.get() + " users.");
log.log("Success! Migration complete.");
return CommandResult.SUCCESS;
}
}

View File

@ -22,8 +22,6 @@
package me.lucko.luckperms.bukkit.migration;
import lombok.Cleanup;
import com.github.cheesesoftware.PowerfulPermsAPI.CachedGroup;
import com.github.cheesesoftware.PowerfulPermsAPI.Group;
import com.github.cheesesoftware.PowerfulPermsAPI.Permission;
@ -33,21 +31,17 @@ import com.github.cheesesoftware.PowerfulPermsAPI.ResultRunnable;
import com.google.common.util.concurrent.ListenableFuture;
import com.zaxxer.hikari.HikariDataSource;
import me.lucko.luckperms.api.data.Callback;
import me.lucko.luckperms.bukkit.migration.utils.LPResultRunnable;
import me.lucko.luckperms.common.commands.Arg;
import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.SubCommand;
import me.lucko.luckperms.common.commands.migration.MigrationLogger;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Constants;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.core.model.PermissionHolder;
import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import org.bukkit.Bukkit;
@ -66,26 +60,18 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import static me.lucko.luckperms.common.constants.Permission.MIGRATION;
@SuppressWarnings("unchecked")
public class MigrationPowerfulPerms extends SubCommand<Object> {
/* <sadness>
The PowerfulPerms API is a complete joke. Seriously, it would probably be easier reflecting into the actual plugin.
Methods move about randomly every version...
What kind of API requires reflection to function with multiple versions...
Doesn't that just defeat the whole god damn point of having an API in the first place?
Whatever happened to depreciation?
</sadness> */
private static Method getPlayerPermissionsMethod = null;
private static Method getPlayerGroupsMethod = null;
private static Method getGroupMethod = null;
// lol
// lol, nice "api"
private static boolean superLegacy = false;
private static boolean legacy = false;
@ -93,29 +79,25 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
try {
Class.forName("com.github.cheesesoftware.PowerfulPermsAPI.ResponseRunnable");
legacy = true;
} catch (ClassNotFoundException ignored) {
}
} catch (ClassNotFoundException ignored) {}
if (legacy) {
try {
getPlayerPermissionsMethod = PermissionManager.class.getMethod("getPlayerOwnPermissions", UUID.class, ResultRunnable.class);
getPlayerPermissionsMethod.setAccessible(true);
} catch (NoSuchMethodException ignored) {
}
} catch (NoSuchMethodException ignored) {}
} else {
try {
getPlayerPermissionsMethod = PermissionManager.class.getMethod("getPlayerOwnPermissions", UUID.class);
getPlayerPermissionsMethod.setAccessible(true);
} catch (NoSuchMethodException ignored) {
}
} catch (NoSuchMethodException ignored) {}
}
try {
getGroupMethod = CachedGroup.class.getMethod("getGroup");
getGroupMethod.setAccessible(true);
superLegacy = true;
} catch (NoSuchMethodException ignored) {
}
} catch (NoSuchMethodException ignored) {}
if (!legacy) {
try {
@ -139,42 +121,6 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
}
}
private static void getPlayerPermissions(PermissionManager manager, UUID uuid, Callback<List<Permission>> callback) {
if (legacy) {
try {
getPlayerPermissionsMethod.invoke(manager, uuid, new LPResultRunnable<List<Permission>>() {
@Override
public void run() {
callback.onComplete(getResult());
}
});
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
} else {
try {
ListenableFuture<List<Permission>> lf = (ListenableFuture<List<Permission>>) getPlayerPermissionsMethod.invoke(manager, uuid);
try {
if (lf.isDone()) {
callback.onComplete(lf.get());
} else {
lf.addListener(() -> {
try {
callback.onComplete(lf.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}, Runnable::run);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
public MigrationPowerfulPerms() {
super("powerfulperms", "Migration from PowerfulPerms", MIGRATION, Predicates.not(5),
Arg.list(
@ -198,16 +144,14 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
}
private CommandResult run(LuckPermsPlugin plugin, Sender sender, List<String> args) {
Consumer<String> log = s -> {
Message.MIGRATION_LOG.send(sender, s);
if (!sender.isConsole()) {
Message.MIGRATION_LOG.send(plugin.getConsoleSender(), s);
}
};
log.accept("Starting PowerfulPerms migration.");
MigrationLogger log = new MigrationLogger("PowerfulPerms");
log.addListener(plugin.getConsoleSender());
log.addListener(sender);
log.log("Starting.");
if (!Bukkit.getPluginManager().isPluginEnabled("PowerfulPerms")) {
log.accept("Error -> PowerfulPerms is not loaded.");
log.logErr("PowerfulPerms is not loaded.");
return CommandResult.STATE_ERROR;
}
@ -218,100 +162,90 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
final String dbTable = args.get(4);
// Find a list of UUIDs
log.accept("Getting a list of UUIDs to migrate.");
@Cleanup HikariDataSource hikari = new HikariDataSource();
hikari.setMaximumPoolSize(2);
hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
hikari.addDataSourceProperty("serverName", address.split(":")[0]);
hikari.addDataSourceProperty("port", address.split(":")[1]);
hikari.addDataSourceProperty("databaseName", database);
hikari.addDataSourceProperty("user", username);
hikari.addDataSourceProperty("password", password);
log.log("Getting a list of UUIDs to migrate.");
Set<UUID> uuids = new HashSet<>();
try {
@Cleanup Connection connection = hikari.getConnection();
DatabaseMetaData meta = connection.getMetaData();
try (HikariDataSource hikari = new HikariDataSource()) {
hikari.setMaximumPoolSize(2);
hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
hikari.addDataSourceProperty("serverName", address.split(":")[0]);
hikari.addDataSourceProperty("port", address.split(":")[1]);
hikari.addDataSourceProperty("databaseName", database);
hikari.addDataSourceProperty("user", username);
hikari.addDataSourceProperty("password", password);
@Cleanup ResultSet tables = meta.getTables(null, null, dbTable, null);
if (!tables.next()) {
log.accept("Error - Couldn't find table.");
return CommandResult.FAILURE;
try (Connection c = hikari.getConnection()) {
DatabaseMetaData meta = c.getMetaData();
} else {
@Cleanup PreparedStatement columnPs = connection.prepareStatement("SELECT COLUMN_NAME, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=?");
columnPs.setString(1, dbTable);
@Cleanup ResultSet columnRs = columnPs.executeQuery();
log.accept("Found table: " + dbTable);
while (columnRs.next()) {
log.accept("" + columnRs.getString("COLUMN_NAME") + " - " + columnRs.getString("COLUMN_TYPE"));
}
@Cleanup PreparedStatement preparedStatement = connection.prepareStatement("SELECT `uuid` FROM " + dbTable);
@Cleanup ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
uuids.add(UUID.fromString(resultSet.getString("uuid")));
try (ResultSet rs = meta.getTables(null, null, dbTable, null)) {
if (!rs.next()) {
log.log("Error - Couldn't find table.");
return CommandResult.FAILURE;
}
}
}
try (Connection c = hikari.getConnection()) {
try (PreparedStatement ps = c.prepareStatement("SELECT COLUMN_NAME, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=?")) {
ps.setString(1, dbTable);
try (ResultSet rs = ps.executeQuery()) {
log.log("Found table: " + dbTable);
while (rs.next()) {
log.log("" + rs.getString("COLUMN_NAME") + " - " + rs.getString("COLUMN_TYPE"));
}
}
}
try (PreparedStatement ps = c.prepareStatement("SELECT `uuid` FROM " + dbTable)) {
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
uuids.add(UUID.fromString(rs.getString("uuid")));
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
return CommandResult.FAILURE;
}
if (uuids.isEmpty()) {
log.accept("Error - Unable to find any UUIDs to migrate.");
log.logErr("Unable to find any UUIDs to migrate.");
return CommandResult.FAILURE;
}
log.accept("Found " + uuids.size() + " uuids. Starting migration.");
log.log("Found " + uuids.size() + " uuids. Starting migration.");
PowerfulPermsPlugin ppPlugin = (PowerfulPermsPlugin) Bukkit.getPluginManager().getPlugin("PowerfulPerms");
PermissionManager pm = ppPlugin.getPermissionManager();
// Groups first.
log.accept("Starting group migration.");
log.log("Starting group migration.");
AtomicInteger groupCount = new AtomicInteger(0);
Map<Integer, Group> groups = pm.getGroups(); // All versions
for (Group g : groups.values()) {
plugin.getStorage().createAndLoadGroup(g.getName().toLowerCase()).join();
final me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(g.getName().toLowerCase());
try {
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("create")
.build().submit(plugin);
} catch (Exception ex) {
ex.printStackTrace();
}
for (Permission p : g.getOwnPermissions()) { // All versions
applyPerm(group, p, plugin);
applyPerm(group, p, log);
}
for (Group parent : g.getParents()) { // All versions
try {
group.setPermission("group." + parent.getName().toLowerCase(), true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("setinherit " + parent.getName().toLowerCase()) // All versions
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
plugin.getStorage().saveGroup(group);
log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
}
log.accept("Group migration complete.");
log.log("Migrated " + groupCount.get() + " groups");
// Now users.
log.accept("Starting user migration.");
log.log("Starting user migration.");
final Map<UUID, CountDownLatch> progress = new HashMap<>();
// Migrate all users and their groups
@ -324,7 +258,7 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
// Get a list of Permissions held by the user from the PP API.
getPlayerPermissions(pm, uuid, perms -> { // Changes each version
perms.forEach(p -> applyPerm(user, p, plugin));
perms.forEach(p -> applyPerm(user, p, log));
// Update the progress so the user can be saved and unloaded.
synchronized (progress) {
@ -337,7 +271,7 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
});
// Migrate the user's groups to LuckPerms from PP.
Callback<Map<String, List<CachedGroup>>> callback = groups1 -> {
Consumer<Map<String, List<CachedGroup>>> callback = groups1 -> {
for (Map.Entry<String, List<CachedGroup>> e : groups1.entrySet()) {
final String server;
if (e.getKey() != null && (e.getKey().equals("") || e.getKey().equalsIgnoreCase("all"))) {
@ -362,26 +296,14 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
if (server == null) {
try {
user.setPermission("group." + g.getName().toLowerCase(), true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("addgroup " + g.getName().toLowerCase())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
} else {
try {
user.setPermission("group." + g.getName().toLowerCase(), true, server);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("addgroup " + g.getName().toLowerCase() + " " + server)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
}
@ -395,26 +317,14 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
if (server == null) {
try {
user.setPermission("group." + group.getName().toLowerCase(), true, g.getExpirationDate().getTime() / 1000L);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("addtempgroup " + group.getName().toLowerCase() + " " + g.getExpirationDate().getTime() / 1000L)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
} else {
try {
user.setPermission("group." + group.getName().toLowerCase(), true, server, g.getExpirationDate().getTime() / 1000L);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("addtempgroup " + group.getName().toLowerCase() + " " + g.getExpirationDate().getTime() / 1000L + " " + server)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -422,26 +332,14 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
if (server == null) {
try {
user.setPermission("group." + group.getName().toLowerCase(), true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("addgroup " + group.getName().toLowerCase())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
} else {
try {
user.setPermission("group." + group.getName().toLowerCase(), true, server);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("addgroup " + group.getName().toLowerCase() + " " + server)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
}
@ -464,11 +362,11 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
ListenableFuture<LinkedHashMap<String, List<CachedGroup>>> future = (ListenableFuture<LinkedHashMap<String, List<CachedGroup>>>) getPlayerGroupsMethod.invoke(pm, uuid);
try {
if (future.isDone()) {
callback.onComplete(future.get());
callback.accept(future.get());
} else {
future.addListener(() -> {
try {
callback.onComplete(future.get());
callback.accept(future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
@ -478,7 +376,6 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
e.printStackTrace();
}
} catch (IllegalAccessException | InvocationTargetException e) {
log.accept("Error");
e.printStackTrace();
}
} else {
@ -486,11 +383,10 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
getPlayerGroupsMethod.invoke(pm, uuid, new LPResultRunnable<LinkedHashMap<String, List<CachedGroup>>>() {
@Override
public void run() {
callback.onComplete(getResult());
callback.accept(getResult());
}
});
} catch (IllegalAccessException | InvocationTargetException e) {
log.accept("Error");
e.printStackTrace();
}
}
@ -498,7 +394,7 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
// All groups are migrated, but there may still be some users being migrated.
// This block will wait for all users to be completed.
log.accept("Waiting for user migration to complete. This may take some time");
log.log("Waiting for user migration to complete. This may take some time");
boolean sleep = true;
while (sleep) {
sleep = false;
@ -521,11 +417,11 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
}
// We done.
log.accept("Success! Completed without any errors.");
log.log("Success! Migration complete.");
return CommandResult.SUCCESS;
}
private void applyPerm(PermissionHolder holder, Permission p, LuckPermsPlugin plugin) {
private void applyPerm(PermissionHolder holder, Permission p, MigrationLogger log) {
String node = p.getPermissionString();
boolean value = true;
if (node.startsWith("!")) {
@ -558,26 +454,14 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
if (expireAt == 0L) {
try {
holder.setPermission(node, value, server, world);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("set " + node + " " + value + " " + server + " " + world)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
} else {
try {
holder.setPermission(node, value, server, world, expireAt);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("settemp " + node + " " + value + " " + expireAt + " " + server + " " + world)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -585,54 +469,66 @@ public class MigrationPowerfulPerms extends SubCommand<Object> {
if (expireAt == 0L) {
try {
holder.setPermission(node, value, server);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("set " + node + " " + value + " " + server)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
} else {
try {
holder.setPermission(node, value, server, expireAt);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("settemp " + node + " " + value + " " + expireAt + " " + server)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
} else {
if (expireAt == 0L) {
try {
holder.setPermission(node, value);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("set " + node + " " + value)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
} else {
try {
holder.setPermission(node, value, expireAt);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(holder).action("settemp " + node + " " + value + " " + expireAt)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
}
}
private static void getPlayerPermissions(PermissionManager manager, UUID uuid, Consumer<List<Permission>> callback) {
if (legacy) {
try {
getPlayerPermissionsMethod.invoke(manager, uuid, new LPResultRunnable<List<Permission>>() {
@Override
public void run() {
callback.accept(getResult());
}
});
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
} else {
try {
ListenableFuture<List<Permission>> lf = (ListenableFuture<List<Permission>>) getPlayerPermissionsMethod.invoke(manager, uuid);
try {
if (lf.isDone()) {
callback.accept(lf.get());
} else {
lf.addListener(() -> {
try {
callback.accept(lf.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}, Runnable::run);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}

View File

@ -25,8 +25,8 @@ package me.lucko.luckperms.bukkit.migration;
import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.SubCommand;
import me.lucko.luckperms.common.commands.migration.MigrationLogger;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.NodeFactory;
import me.lucko.luckperms.common.core.model.Group;
@ -49,7 +49,7 @@ import org.tyrannyofheaven.bukkit.zPermissions.model.PermissionEntity;
import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.concurrent.atomic.AtomicInteger;
public class MigrationZPermissions extends SubCommand<Object> {
public MigrationZPermissions() {
@ -58,21 +58,19 @@ public class MigrationZPermissions extends SubCommand<Object> {
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) throws CommandException {
Consumer<String> log = s -> {
Message.MIGRATION_LOG.send(sender, s);
if (!sender.isConsole()) {
Message.MIGRATION_LOG.send(plugin.getConsoleSender(), s);
}
};
log.accept("Starting zPermissions migration.");
MigrationLogger log = new MigrationLogger("PermissionManager");
log.addListener(plugin.getConsoleSender());
log.addListener(sender);
log.log("Starting.");
if (!Bukkit.getPluginManager().isPluginEnabled("zPermissions")) {
log.accept("Error -> zPermissions is not loaded.");
log.logErr("zPermissions is not loaded.");
return CommandResult.STATE_ERROR;
}
if (!Bukkit.getServicesManager().isProvidedFor(ZPermissionsService.class)) {
log.accept("Error -> zPermissions is not loaded.");
log.logErr("zPermissions is not loaded.");
return CommandResult.STATE_ERROR;
}
@ -89,7 +87,8 @@ public class MigrationZPermissions extends SubCommand<Object> {
}
// Migrate all groups
log.accept("Starting group migration.");
log.log("Starting group migration.");
AtomicInteger groupCount = new AtomicInteger(0);
for (String g : service.getAllGroups()) {
plugin.getStorage().createAndLoadGroup(g.toLowerCase()).join();
Group group = plugin.getGroupManager().getIfLoaded(g.toLowerCase());
@ -98,19 +97,25 @@ public class MigrationZPermissions extends SubCommand<Object> {
migrateEntity(group, entity, null);
plugin.getStorage().saveGroup(group);
log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
}
log.log("Migrated " + groupCount.get() + " groups");
// Migrate all tracks
log.accept("Starting track migration.");
log.log("Starting track migration.");
AtomicInteger trackCount = new AtomicInteger(0);
for (String t : service.getAllTracks()) {
plugin.getStorage().createAndLoadTrack(t.toLowerCase()).join();
Track track = plugin.getTrackManager().getIfLoaded(t.toLowerCase());
track.setGroups(service.getTrackGroups(t));
plugin.getStorage().saveTrack(track);
log.logAllProgress("Migrated {} tracks so far.", trackCount.incrementAndGet());
}
log.log("Migrated " + trackCount.get() + " tracks");
// Migrate all users.
log.accept("Starting user migration.");
log.log("Starting user migration.");
AtomicInteger userCount = new AtomicInteger(0);
for (UUID u : service.getAllPlayersUUID()) {
plugin.getStorage().loadUser(u, "null").join();
User user = plugin.getUserManager().get(u);
@ -126,9 +131,11 @@ public class MigrationZPermissions extends SubCommand<Object> {
plugin.getUserManager().cleanup(user);
plugin.getStorage().saveUser(user);
log.logProgress("Migrated {} users so far.", userCount.incrementAndGet());
}
log.accept("Success! Completed without any errors.");
log.log("Migrated " + userCount.get() + " users.");
log.log("Success! Migration complete.");
return CommandResult.SUCCESS;
}
@ -137,13 +144,11 @@ public class MigrationZPermissions extends SubCommand<Object> {
if (e.getWorld() != null) {
try {
group.setPermission(e.getPermission(), true, "global", e.getWorld().getName());
} catch (ObjectAlreadyHasException ignored) {
}
} catch (ObjectAlreadyHasException ignored) {}
} else {
try {
group.setPermission(e.getPermission(), true); // TODO handle negated.
} catch (ObjectAlreadyHasException ignored) {
}
} catch (ObjectAlreadyHasException ignored) {}
}
}
@ -153,16 +158,14 @@ public class MigrationZPermissions extends SubCommand<Object> {
if (!inheritance.getParent().getName().equals(group.getObjectName())) {
group.setPermission("group." + inheritance.getParent().getName(), true);
}
} catch (ObjectAlreadyHasException ignored) {
}
} catch (ObjectAlreadyHasException ignored) {}
}
} else {
// entity.getMemberships() doesn't work (always returns 0 records)
for (Membership membership : memberships) {
try {
group.setPermission("group." + membership.getGroup().getDisplayName(), true);
} catch (ObjectAlreadyHasException ignored) {
}
} catch (ObjectAlreadyHasException ignored) {}
}
}

View File

@ -26,14 +26,11 @@ import me.lucko.luckperms.api.MetaUtils;
import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.SubCommand;
import me.lucko.luckperms.common.commands.migration.MigrationLogger;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Constants;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.data.LogEntry;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import net.alpenblock.bungeeperms.BungeePerms;
import net.alpenblock.bungeeperms.Group;
@ -43,11 +40,8 @@ import net.alpenblock.bungeeperms.World;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.concurrent.atomic.AtomicInteger;
/**
* BungeePerms is actually pretty nice. huh.
*/
public class MigrationBungeePerms extends SubCommand<Object> {
public MigrationBungeePerms() {
super("bungeeperms", "Migration from BungeePerms", Permission.MIGRATION, Predicates.alwaysFalse(), null);
@ -55,51 +49,34 @@ public class MigrationBungeePerms extends SubCommand<Object> {
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) throws CommandException {
Consumer<String> log = s -> {
Message.MIGRATION_LOG.send(sender, s);
if (!sender.isConsole()) {
Message.MIGRATION_LOG.send(plugin.getConsoleSender(), s);
}
};
log.accept("Starting BungeePerms migration.");
MigrationLogger log = new MigrationLogger("BungeePerms");
log.addListener(plugin.getConsoleSender());
log.addListener(sender);
log.log("Starting.");
// Get BungeePerms instance
BungeePerms bp = BungeePerms.getInstance();
if (bp == null) {
log.accept("Error -> BungeePerms is not loaded.");
log.logErr("Plugin not loaded.");
return CommandResult.STATE_ERROR;
}
// Migrate all groups.
log.accept("Starting group migration.");
int groupCount = 0;
log.log("Starting group migration.");
AtomicInteger groupCount = new AtomicInteger(0);
for (Group g : bp.getPermissionsManager().getBackEnd().loadGroups()) {
groupCount++;
// Make a LuckPerms group for the one being migrated
plugin.getStorage().createAndLoadGroup(g.getName().toLowerCase()).join();
me.lucko.luckperms.common.core.model.Group group = plugin.getGroupManager().getIfLoaded(g.getName().toLowerCase());
try {
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("create")
.build().submit(plugin);
} catch (Exception ex) {
ex.printStackTrace();
}
// Migrate global perms
for (String perm : g.getPerms()) {
try {
group.setPermission(perm, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("set " + perm + " true")
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -108,14 +85,8 @@ public class MigrationBungeePerms extends SubCommand<Object> {
for (String perm : e.getValue().getPerms()) {
try {
group.setPermission(perm, true, e.getKey());
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("set " + perm + " true " + e.getKey())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -124,14 +95,8 @@ public class MigrationBungeePerms extends SubCommand<Object> {
for (String perm : we.getValue().getPerms()) {
try {
group.setPermission(perm, true, e.getKey(), we.getKey());
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("set " + perm + " true " + e.getKey() + " " + we.getKey())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
}
@ -141,14 +106,8 @@ public class MigrationBungeePerms extends SubCommand<Object> {
for (String inherit : g.getInheritances()) {
try {
group.setPermission("group." + inherit, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("setinherit " + group)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -160,14 +119,8 @@ public class MigrationBungeePerms extends SubCommand<Object> {
prefix = MetaUtils.escapeCharacters(prefix);
try {
group.setPermission("prefix.50." + prefix, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("set prefix.50." + prefix + " true")
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -175,29 +128,25 @@ public class MigrationBungeePerms extends SubCommand<Object> {
suffix = MetaUtils.escapeCharacters(suffix);
try {
group.setPermission("suffix.50." + suffix, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(group).action("set suffix.50." + suffix + " true")
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
plugin.getStorage().saveGroup(group);
}
log.accept("Migrated " + groupCount + " groups");
log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
}
log.log("Migrated " + groupCount.get() + " groups");
// Migrate all users.
log.accept("Starting user migration.");
int userCount = 0;
log.log("Starting user migration.");
AtomicInteger userCount = new AtomicInteger(0);
for (User u : bp.getPermissionsManager().getBackEnd().loadUsers()) {
if (u.getUUID() == null) continue;
userCount++;
if (u.getUUID() == null) {
log.logErr("Could not parse UUID for user: " + u.getName());
continue;
}
// Make a LuckPerms user for the one being migrated.
plugin.getStorage().loadUser(u.getUUID(), "null").join();
@ -207,14 +156,8 @@ public class MigrationBungeePerms extends SubCommand<Object> {
for (String perm : u.getPerms()) {
try {
user.setPermission(perm, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("set " + perm + " true")
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -223,14 +166,8 @@ public class MigrationBungeePerms extends SubCommand<Object> {
for (String perm : e.getValue().getPerms()) {
try {
user.setPermission(perm, true, e.getKey());
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("set " + perm + " true " + e.getKey())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -239,14 +176,8 @@ public class MigrationBungeePerms extends SubCommand<Object> {
for (String perm : we.getValue().getPerms()) {
try {
user.setPermission(perm, true, e.getKey(), we.getKey());
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("set " + perm + " true " + e.getKey() + " " + we.getKey())
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
}
@ -256,14 +187,8 @@ public class MigrationBungeePerms extends SubCommand<Object> {
for (String group : u.getGroupsString()) {
try {
user.setPermission("group." + group, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("addgroup " + group)
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -275,14 +200,8 @@ public class MigrationBungeePerms extends SubCommand<Object> {
prefix = MetaUtils.escapeCharacters(prefix);
try {
user.setPermission("prefix.100." + prefix, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("set prefix.100." + prefix + " true")
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
@ -290,23 +209,19 @@ public class MigrationBungeePerms extends SubCommand<Object> {
suffix = MetaUtils.escapeCharacters(suffix);
try {
user.setPermission("suffix.100." + suffix, true);
LogEntry.build()
.actor(Constants.CONSOLE_UUID).actorName(Constants.CONSOLE_NAME)
.acted(user).action("set suffix.100." + suffix + " true")
.build().submit(plugin);
} catch (Exception ex) {
if (!(ex instanceof ObjectAlreadyHasException)) {
ex.printStackTrace();
}
log.handleException(ex);
}
}
plugin.getStorage().saveUser(user);
plugin.getUserManager().cleanup(user);
log.logProgress("Migrated {} users so far.", userCount.incrementAndGet());
}
log.accept("Migrated " + userCount + " users.");
log.accept("Success! Completed without any errors.");
log.log("Migrated " + userCount.get() + " users.");
log.log("Success! Migration complete.");
return CommandResult.SUCCESS;
}
}

View File

@ -0,0 +1,72 @@
/*
* Copyright (c) 2016 Lucko (Luck) <luck@lucko.me>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.lucko.luckperms.common.commands.migration;
import lombok.RequiredArgsConstructor;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.exceptions.ObjectAlreadyHasException;
import me.lucko.luckperms.exceptions.ObjectLacksException;
import java.util.HashSet;
import java.util.Set;
@RequiredArgsConstructor
public class MigrationLogger {
private static final int NOTIFY_FREQUENCY = 100;
private final String pluginName;
private final Set<Sender> listeners = new HashSet<>();
public void addListener(Sender sender) {
listeners.add(sender);
}
public void log(String msg) {
listeners.forEach(s -> Message.MIGRATION_LOG.send(s, pluginName, msg));
}
public void logErr(String msg) {
listeners.forEach(s -> Message.MIGRATION_LOG.send(s, pluginName, "Error -> " + msg));
}
public void logAllProgress(String msg, int amount) {
listeners.forEach(s -> Message.MIGRATION_LOG_PROGRESS.send(s, pluginName, msg.replace("{}", "" + amount)));
}
public void logProgress(String msg, int amount) {
if (amount % NOTIFY_FREQUENCY == 0) {
// migrated {} groups so far.
logAllProgress(msg, amount);
}
}
public void handleException(Exception ex) {
if (ex instanceof ObjectAlreadyHasException || ex instanceof ObjectLacksException) {
return;
}
ex.printStackTrace();
}
}

View File

@ -22,6 +22,7 @@
package me.lucko.luckperms.common.commands.sender;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import me.lucko.luckperms.common.constants.Constants;
@ -39,6 +40,7 @@ import java.util.UUID;
* @param <T> the command sender type
*/
@Getter
@EqualsAndHashCode(of = "uuid")
public class AbstractSender<T> implements Sender {
private final LuckPermsPlugin platform;
private final SenderFactory<T> factory;

View File

@ -49,7 +49,8 @@ public enum Message {
OP_DISABLED_SPONGE("&2Server Operator status has no effect when a permission plugin is installed. Please edit user data directly.", true),
LOG("&3LOG &3&l> {0}", true),
EXPORT_LOG("&3EXPORT &3&l> &f{0}", true),
MIGRATION_LOG("&3MIGRATION &3&l> &f{0}", true),
MIGRATION_LOG("&3MIGRATION &7[&3{0}&7] &3&l> &f{1}", true),
MIGRATION_LOG_PROGRESS("&3MIGRATION &7[&3{0}&7] &3&l> &7{1}", true),
COMMAND_NOT_RECOGNISED("Command not recognised.", true),
COMMAND_NO_PERMISSION("You do not have permission to use this command!", true),

View File

@ -25,26 +25,29 @@ package me.lucko.luckperms.sponge.migration;
import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.SubCommand;
import me.lucko.luckperms.common.commands.migration.MigrationLogger;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.Util;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.model.Group;
import me.lucko.luckperms.common.core.model.User;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.utils.Predicates;
import me.lucko.luckperms.sponge.LPSpongePlugin;
import me.lucko.luckperms.sponge.service.LuckPermsService;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.service.permission.PermissionService;
import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.service.permission.SubjectCollection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.concurrent.atomic.AtomicInteger;
import static me.lucko.luckperms.sponge.migration.MigrationUtils.migrateSubject;
@ -55,17 +58,17 @@ public class MigrationPermissionManager extends SubCommand<Object> {
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) throws CommandException {
Consumer<String> log = s -> {
Message.MIGRATION_LOG.send(sender, s);
if (!sender.isConsole()) {
Message.MIGRATION_LOG.send(plugin.getConsoleSender(), s);
}
};
log.accept("Starting PermissionManager migration.");
MigrationLogger log = new MigrationLogger("PermissionManager");
log.addListener(plugin.getConsoleSender());
log.addListener(sender);
log.log("Starting.");
final LuckPermsService lpService = ((LPSpongePlugin) plugin).getService();
Optional<PluginContainer> pm = Sponge.getPluginManager().getPlugin("permissionmanager");
if (!pm.isPresent()) {
log.accept("Error -> PermissionManager is not loaded.");
log.logErr("Plugin not loaded.");
return CommandResult.STATE_ERROR;
}
@ -81,8 +84,18 @@ public class MigrationPermissionManager extends SubCommand<Object> {
return CommandResult.FAILURE;
}
// Migrate defaults
log.log("Migrating default subjects.");
for (SubjectCollection collection : pmService.getKnownSubjects().values()) {
MigrationUtils.migrateSubjectData(
collection.getDefaults().getSubjectData(),
lpService.getSubjects("defaults").get(collection.getIdentifier()).getSubjectData()
);
}
MigrationUtils.migrateSubjectData(pmService.getDefaults().getSubjectData(), lpService.getDefaults().getSubjectData());
// Migrate groups
log.accept("Starting group migration.");
log.log("Starting group migration.");
// Forcefully load all groups.
try {
@ -92,10 +105,8 @@ public class MigrationPermissionManager extends SubCommand<Object> {
t.printStackTrace();
}
int groupCount = 0;
AtomicInteger groupCount = new AtomicInteger(0);
for (Subject pmGroup : pmService.getGroupSubjects().getAllSubjects()) {
groupCount++;
String pmName = MigrationUtils.convertGroupName(pmGroup.getIdentifier().toLowerCase());
// Make a LuckPerms group for the one being migrated
@ -103,11 +114,13 @@ public class MigrationPermissionManager extends SubCommand<Object> {
Group group = plugin.getGroupManager().getIfLoaded(pmName);
migrateSubject(pmGroup, group);
plugin.getStorage().saveGroup(group);
log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
}
log.accept("Migrated " + groupCount + " groups");
log.log("Migrated " + groupCount.get() + " groups");
// Migrate users
log.accept("Starting user migration.");
log.log("Starting user migration.");
// Forcefully load all users.
try {
@ -117,12 +130,11 @@ public class MigrationPermissionManager extends SubCommand<Object> {
t.printStackTrace();
}
int userCount = 0;
AtomicInteger userCount = new AtomicInteger(0);
for (Subject pmUser : pmService.getUserSubjects().getAllSubjects()) {
userCount++;
UUID uuid = Util.parseUuid(pmUser.getIdentifier());
if (uuid == null) {
log.accept("Error -> Could not parse UUID for user: " + pmUser.getIdentifier());
log.logErr("Could not parse UUID for user: " + pmUser.getIdentifier());
continue;
}
@ -135,10 +147,12 @@ public class MigrationPermissionManager extends SubCommand<Object> {
migrateSubject(pmUser, user);
plugin.getStorage().saveUser(user);
plugin.getUserManager().cleanup(user);
log.logProgress("Migrated {} users so far.", userCount.incrementAndGet());
}
log.accept("Migrated " + userCount + " users.");
log.accept("Success! Completed without any errors.");
log.log("Migrated " + userCount.get() + " users.");
log.log("Success! Migration complete.");
return CommandResult.SUCCESS;
}
}

View File

@ -25,9 +25,9 @@ package me.lucko.luckperms.sponge.migration;
import me.lucko.luckperms.common.commands.CommandException;
import me.lucko.luckperms.common.commands.CommandResult;
import me.lucko.luckperms.common.commands.SubCommand;
import me.lucko.luckperms.common.commands.migration.MigrationLogger;
import me.lucko.luckperms.common.commands.sender.Sender;
import me.lucko.luckperms.common.commands.utils.Util;
import me.lucko.luckperms.common.constants.Message;
import me.lucko.luckperms.common.constants.Permission;
import me.lucko.luckperms.common.core.model.Group;
import me.lucko.luckperms.common.core.model.Track;
@ -51,7 +51,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.concurrent.atomic.AtomicInteger;
import static me.lucko.luckperms.sponge.migration.MigrationUtils.migrateSubject;
@ -62,19 +62,17 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, Object o, List<String> args, String label) throws CommandException {
Consumer<String> log = s -> {
Message.MIGRATION_LOG.send(sender, s);
if (!sender.isConsole()) {
Message.MIGRATION_LOG.send(plugin.getConsoleSender(), s);
}
};
log.accept("Starting PermissionsEx migration.");
MigrationLogger log = new MigrationLogger("PermissionsEx");
log.addListener(plugin.getConsoleSender());
log.addListener(sender);
log.log("Starting.");
final LuckPermsService lpService = ((LPSpongePlugin) plugin).getService();
Optional<PluginContainer> pex = Sponge.getPluginManager().getPlugin("permissionsex");
if (!pex.isPresent()) {
log.accept("Error -> PermissionsEx is not loaded.");
log.logErr("Plugin not loaded.");
return CommandResult.STATE_ERROR;
}
@ -82,23 +80,21 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
PermissionService pexService = (PermissionService) pex.get().getInstance().get();
// Migrate defaults
log.log("Migrating default subjects.");
for (SubjectCollection collection : pexService.getKnownSubjects().values()) {
MigrationUtils.migrateSubjectData(
collection.getDefaults().getSubjectData(),
lpService.getSubjects("defaults").get(collection.getIdentifier()).getSubjectData()
);
}
MigrationUtils.migrateSubjectData(pexService.getDefaults().getSubjectData(), lpService.getDefaults().getSubjectData());
Map<String, TreeMap<Integer, String>> tracks = new HashMap<>();
// Migrate groups
log.accept("Starting group migration.");
int groupCount = 0;
log.log("Starting group migration.");
AtomicInteger groupCount = new AtomicInteger(0);
for (Subject pexGroup : pexService.getGroupSubjects().getAllSubjects()) {
groupCount++;
String pexName = MigrationUtils.convertGroupName(pexGroup.getIdentifier().toLowerCase());
// Make a LuckPerms group for the one being migrated
@ -122,11 +118,12 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
} catch (NumberFormatException ignored) {}
}
log.logAllProgress("Migrated {} groups so far.", groupCount.incrementAndGet());
}
log.accept("Migrated " + groupCount + " groups");
log.log("Migrated " + groupCount.get() + " groups");
// Migrate tracks
log.accept("Starting track migration.");
log.log("Starting track migration.");
for (Map.Entry<String, TreeMap<Integer, String>> e : tracks.entrySet()) {
plugin.getStorage().createAndLoadTrack(e.getKey()).join();
Track track = plugin.getTrackManager().getIfLoaded(e.getKey());
@ -139,16 +136,15 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
}
}
}
log.accept("Migrated " + tracks.size() + " tracks");
log.log("Migrated " + tracks.size() + " tracks");
// Migrate users
log.accept("Starting user migration.");
int userCount = 0;
log.log("Starting user migration.");
AtomicInteger userCount = new AtomicInteger(0);
for (Subject pexUser : pexService.getUserSubjects().getAllSubjects()) {
userCount++;
UUID uuid = Util.parseUuid(pexUser.getIdentifier());
if (uuid == null) {
log.accept("Error -> Could not parse UUID for user: " + pexUser.getIdentifier());
log.logErr("Could not parse UUID for user: " + pexUser.getIdentifier());
continue;
}
@ -161,10 +157,12 @@ public class MigrationPermissionsEx extends SubCommand<Object> {
migrateSubject(pexUser, user);
plugin.getStorage().saveUser(user);
plugin.getUserManager().cleanup(user);
log.logProgress("Migrated {} users so far.", userCount.incrementAndGet());
}
log.accept("Migrated " + userCount + " users.");
log.accept("Success! Completed without any errors.");
log.log("Migrated " + userCount.get() + " users.");
log.log("Success! Migration complete.");
return CommandResult.SUCCESS;
}
}