RedisBungee/src/main/java/com/imaginarycode/minecraft/redisbungee/RedisBungee.java

520 lines
23 KiB
Java
Raw Normal View History

2013-09-29 20:16:47 +00:00
package com.imaginarycode.minecraft.redisbungee;
import com.google.common.collect.*;
import com.google.common.io.ByteStreams;
import com.google.gson.Gson;
import com.imaginarycode.minecraft.redisbungee.events.PubSubMessageEvent;
import com.imaginarycode.minecraft.redisbungee.util.*;
2015-03-28 20:46:08 +00:00
import com.squareup.okhttp.Dispatcher;
2015-01-25 05:17:52 +00:00
import com.squareup.okhttp.OkHttpClient;
import lombok.AccessLevel;
2014-04-19 20:08:49 +00:00
import lombok.Getter;
2015-06-24 09:54:19 +00:00
import lombok.NoArgsConstructor;
import lombok.NonNull;
import net.md_5.bungee.api.ProxyServer;
2013-09-29 20:16:47 +00:00
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.scheduler.ScheduledTask;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import redis.clients.jedis.*;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException;
2013-09-29 20:16:47 +00:00
import java.io.*;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
2013-09-29 20:16:47 +00:00
2014-02-21 23:49:26 +00:00
import static com.google.common.base.Preconditions.checkArgument;
/**
* The RedisBungee plugin.
* <p>
* The only function of interest is {@link #getApi()}, which exposes some functions in this class.
*/
2014-04-19 20:08:49 +00:00
public final class RedisBungee extends Plugin {
@Getter
2014-09-21 17:56:46 +00:00
private static Gson gson = new Gson();
private static RedisBungeeAPI api;
@Getter(AccessLevel.PACKAGE)
2014-09-21 17:56:46 +00:00
private static PubSubListener psl = null;
@Getter
2014-04-19 20:08:49 +00:00
private JedisPool pool;
@Getter
private UUIDTranslator uuidTranslator;
@Getter(AccessLevel.PACKAGE)
private static RedisBungeeConfiguration configuration;
@Getter
private DataManager dataManager;
@Getter
2015-01-25 05:17:52 +00:00
private static OkHttpClient httpClient;
2014-04-19 19:54:30 +00:00
private List<String> serverIds;
private final AtomicInteger nagAboutServers = new AtomicInteger();
private ScheduledTask integrityCheck;
private ScheduledTask heartbeatTask;
private boolean usingLua;
private LuaManager.Script serverToPlayersScript;
2013-10-13 19:44:20 +00:00
/**
* Fetch the {@link RedisBungeeAPI} object created on plugin start.
2013-10-13 19:44:20 +00:00
*
* @return the {@link RedisBungeeAPI} object
2013-10-13 19:44:20 +00:00
*/
public static RedisBungeeAPI getApi() {
return api;
}
2014-09-21 17:56:46 +00:00
static PubSubListener getPubSubListener() {
return psl;
}
2014-04-04 03:03:27 +00:00
final List<String> getServerIds() {
2014-04-19 19:54:30 +00:00
return serverIds;
}
private List<String> getCurrentServerIds() {
try (Jedis jedis = pool.getResource()) {
int nag = nagAboutServers.decrementAndGet();
if (nag <= 0) {
nagAboutServers.set(10);
}
2014-04-19 19:52:15 +00:00
ImmutableList.Builder<String> servers = ImmutableList.builder();
Map<String, String> heartbeats = jedis.hgetAll("heartbeats");
for (Map.Entry<String, String> entry : heartbeats.entrySet()) {
try {
2015-01-25 05:04:34 +00:00
long stamp = Long.parseLong(entry.getValue());
if (System.currentTimeMillis() < stamp + 30000)
2014-04-19 19:52:15 +00:00
servers.add(entry.getKey());
else if (nag <= 0) {
getLogger().severe(entry.getKey() + " is " + (System.currentTimeMillis() - stamp) + "ms behind! (Time not synchronized or server down?)");
}
2014-04-19 19:52:15 +00:00
} catch (NumberFormatException ignored) {
}
}
return servers.build();
2014-04-04 03:03:27 +00:00
} catch (JedisConnectionException e) {
getLogger().log(Level.SEVERE, "Unable to fetch all server IDs", e);
return Collections.singletonList(configuration.getServerId());
2014-04-04 03:03:27 +00:00
}
2014-01-26 00:06:33 +00:00
}
public Set<UUID> getPlayersOnProxy(String server) {
checkArgument(getServerIds().contains(server), server + " is not a valid proxy ID");
try (Jedis jedis = pool.getResource()) {
Set<String> users = jedis.smembers("proxy:" + server + ":usersOnline");
ImmutableSet.Builder<UUID> builder = ImmutableSet.builder();
for (String user : users) {
builder.add(UUID.fromString(user));
}
return builder.build();
}
}
final Multimap<String, UUID> serversToPlayers() {
if (usingLua) {
Collection<String> data = (Collection<String>) serverToPlayersScript.eval(ImmutableList.<String>of(), getServerIds());
ImmutableMultimap.Builder<String, UUID> builder = ImmutableMultimap.builder();
// TODO: This seems pretty slow, but execution times over the long term seem to stay below that of the
// Java implementation, at least. If you have a better idea, I want to see it!
String key = null;
for (String s : data) {
if (key == null) {
key = s;
continue;
}
builder.put(key, UUID.fromString(s));
key = null;
}
return builder.build();
} else {
ImmutableMultimap.Builder<String, UUID> multimapBuilder = ImmutableMultimap.builder();
for (UUID p : getPlayers()) {
String name = dataManager.getServer(p);
if (name != null)
multimapBuilder.put(name, p);
}
return multimapBuilder.build();
2013-12-27 20:40:58 +00:00
}
}
final int getCount() {
int c = 0;
if (pool != null) {
try (Jedis rsc = pool.getResource()) {
for (String i : getServerIds()) {
c += rsc.scard("proxy:" + i + ":usersOnline");
}
} catch (JedisConnectionException e) {
// Redis server has disappeared!
getLogger().log(Level.SEVERE, "Unable to get connection from pool - did your Redis server go away?", e);
throw new RuntimeException("Unable to get total player count", e);
}
}
return c;
}
private Set<String> getLocalPlayersAsUuidStrings() {
ImmutableSet.Builder<String> builder = ImmutableSet.builder();
for (ProxiedPlayer player : getProxy().getPlayers()) {
builder.add(player.getUniqueId().toString());
}
return builder.build();
2014-01-20 15:34:40 +00:00
}
final Set<UUID> getPlayers() {
ImmutableSet.Builder<UUID> setBuilder = ImmutableSet.builder();
2013-09-29 20:16:47 +00:00
if (pool != null) {
try (Jedis rsc = pool.getResource()) {
2014-04-26 23:43:09 +00:00
List<String> keys = new ArrayList<>();
2014-04-19 19:54:30 +00:00
for (String i : getServerIds()) {
keys.add("proxy:" + i + ":usersOnline");
2014-04-26 23:43:09 +00:00
}
if (!keys.isEmpty()) {
Set<String> users = rsc.sunion(keys.toArray(new String[keys.size()]));
if (users != null && !users.isEmpty()) {
for (String user : users) {
try {
setBuilder = setBuilder.add(UUID.fromString(user));
} catch (IllegalArgumentException ignored) {
}
}
}
2013-09-29 20:16:47 +00:00
}
} catch (JedisConnectionException e) {
// Redis server has disappeared!
getLogger().log(Level.SEVERE, "Unable to get connection from pool - did your Redis server go away?", e);
throw new RuntimeException("Unable to get all players online", e);
2013-09-29 20:16:47 +00:00
}
}
2014-01-26 00:06:33 +00:00
return setBuilder.build();
2013-09-29 20:16:47 +00:00
}
final Set<UUID> getPlayersOnServer(@NonNull String server) {
checkArgument(getProxy().getServers().containsKey(server), "server does not exist");
return ImmutableSet.copyOf(serversToPlayers().get(server));
2013-12-27 20:40:58 +00:00
}
final void sendProxyCommand(@NonNull String proxyId, @NonNull String command) {
2014-04-04 03:03:27 +00:00
checkArgument(getServerIds().contains(proxyId) || proxyId.equals("allservers"), "proxyId is invalid");
sendChannelMessage("redisbungee-" + proxyId, command);
2014-01-02 00:05:55 +00:00
}
2014-09-21 17:56:46 +00:00
final void sendChannelMessage(String channel, String message) {
try (Jedis jedis = pool.getResource()) {
jedis.publish(channel, message);
} catch (JedisConnectionException e) {
// Redis server has disappeared!
getLogger().log(Level.SEVERE, "Unable to get connection from pool - did your Redis server go away?", e);
throw new RuntimeException("Unable to publish channel message", e);
}
}
2014-01-02 00:05:55 +00:00
2013-09-29 20:16:47 +00:00
@Override
public void onEnable() {
try {
loadConfig();
} catch (IOException e) {
throw new RuntimeException("Unable to load/save config", e);
} catch (JedisConnectionException e) {
throw new RuntimeException("Unable to connect to your Redis server!", e);
2013-09-29 20:16:47 +00:00
}
if (pool != null) {
try (Jedis tmpRsc = pool.getResource()) {
tmpRsc.hset("heartbeats", configuration.getServerId(), String.valueOf(System.currentTimeMillis()));
// This is more portable than INFO <section>
String info = tmpRsc.info();
for (String s : info.split("\r\n")) {
if (s.startsWith("redis_version:")) {
String version = s.split(":")[1];
if (!(usingLua = RedisUtil.canUseLua(version))) {
getLogger().warning("Your version of Redis (" + version + ") is below 2.6. RedisBungee will disable optimizations using Lua.");
getLogger().warning("Support for versions of Redis below version 2.6 will be removed in the future.");
} else {
getLogger().info("Using Redis >= 2.6, enabling Lua optimizations.");
LuaManager manager = new LuaManager(this);
serverToPlayersScript = manager.createScript(IOUtil.readInputStreamAsString(getResourceAsStream("lua/server_to_players.lua")));
}
break;
}
}
long uuidCacheSize = tmpRsc.hlen("uuid-cache");
if (uuidCacheSize > 750000) {
getLogger().info("Looks like you have a really big UUID cache! Run https://www.spigotmc.org/resources/redisbungeecleaner.8505/ as soon as possible.");
}
2013-09-29 20:16:47 +00:00
}
2014-04-19 19:54:30 +00:00
serverIds = getCurrentServerIds();
uuidTranslator = new UUIDTranslator(this);
heartbeatTask = getProxy().getScheduler().schedule(this, new Runnable() {
2013-10-31 23:07:37 +00:00
@Override
public void run() {
try (Jedis rsc = pool.getResource()) {
rsc.hset("heartbeats", configuration.getServerId(), String.valueOf(System.currentTimeMillis()));
} catch (JedisConnectionException e) {
// Redis server has disappeared!
getLogger().log(Level.SEVERE, "Unable to update heartbeat - did your Redis server go away?", e);
2013-10-31 23:07:37 +00:00
}
2014-04-19 19:54:30 +00:00
serverIds = getCurrentServerIds();
2013-10-31 23:07:37 +00:00
}
}, 0, 3, TimeUnit.SECONDS);
dataManager = new DataManager(this);
if (configuration.isRegisterBungeeCommands()) {
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.GlistCommand(this));
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.FindCommand(this));
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.LastSeenCommand(this));
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.IpCommand(this));
}
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.SendToAll(this));
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.ServerId(this));
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.ServerIds());
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.PlayerProxyCommand(this));
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.PlistCommand(this));
getProxy().getPluginManager().registerCommand(this, new RedisBungeeCommands.DebugCommand(this));
api = new RedisBungeeAPI(this);
getProxy().getPluginManager().registerListener(this, new RedisBungeeListener(this, configuration.getExemptAddresses()));
getProxy().getPluginManager().registerListener(this, dataManager);
psl = new PubSubListener();
getProxy().getScheduler().runAsync(this, psl);
integrityCheck = getProxy().getScheduler().schedule(this, new Runnable() {
2014-01-20 15:34:40 +00:00
@Override
public void run() {
try (Jedis tmpRsc = pool.getResource()) {
Set<String> players = getLocalPlayersAsUuidStrings();
Set<String> playersInRedis = tmpRsc.smembers("proxy:" + configuration.getServerId() + ":usersOnline");
for (Iterator<String> it = playersInRedis.iterator(); it.hasNext(); ) {
String member = it.next();
2014-01-20 23:42:56 +00:00
if (!players.contains(member)) {
// Are they simply on a different proxy?
String found = null;
2014-04-04 03:03:27 +00:00
for (String proxyId : getServerIds()) {
if (proxyId.equals(configuration.getServerId())) continue;
if (tmpRsc.sismember("proxy:" + proxyId + ":usersOnline", member)) {
2014-01-20 23:42:56 +00:00
// Just clean up the set.
found = proxyId;
2014-01-20 23:42:56 +00:00
break;
}
}
if (found == null) {
2014-04-19 20:08:49 +00:00
RedisUtil.cleanUpPlayer(member, tmpRsc);
2014-01-20 23:42:56 +00:00
getLogger().warning("Player found in set that was not found locally and globally: " + member);
} else {
tmpRsc.srem("proxy:" + configuration.getServerId() + ":usersOnline", member);
2014-01-20 23:42:56 +00:00
getLogger().warning("Player found in set that was not found locally, but is on another proxy: " + member);
}
it.remove();
2014-01-20 23:42:56 +00:00
}
}
Pipeline pipeline = tmpRsc.pipelined();
for (String player : players) {
if (playersInRedis.contains(player))
continue;
// Player not online according to Redis but not BungeeCord.
getLogger().warning("Player " + player + " is on the proxy but not in Redis.");
ProxiedPlayer proxiedPlayer = ProxyServer.getInstance().getPlayer(UUID.fromString(player));
if (proxiedPlayer == null)
continue; // We'll deal with it later.
RedisUtil.createPlayer(proxiedPlayer, pipeline, true);
}
pipeline.sync();
2014-01-20 15:34:40 +00:00
}
}
}, 0, 1, TimeUnit.MINUTES);
2013-09-29 20:16:47 +00:00
}
2014-01-22 20:32:49 +00:00
getProxy().registerChannel("RedisBungee");
2013-09-29 20:16:47 +00:00
}
@Override
public void onDisable() {
2013-10-18 21:14:58 +00:00
if (pool != null) {
// Poison the PubSub listener
psl.poison();
getProxy().getScheduler().cancel(this);
integrityCheck.cancel();
heartbeatTask.cancel();
getProxy().getPluginManager().unregisterListeners(this);
try (Jedis tmpRsc = pool.getResource()) {
tmpRsc.hdel("heartbeats", configuration.getServerId());
if (tmpRsc.scard("proxy:" + configuration.getServerId() + ":usersOnline") > 0) {
Set<String> players = tmpRsc.smembers("proxy:" + configuration.getServerId() + ":usersOnline");
for (String member : players)
2014-09-11 20:38:40 +00:00
RedisUtil.cleanUpPlayer(member, tmpRsc);
2013-12-03 21:01:27 +00:00
}
2013-10-18 21:14:58 +00:00
}
pool.destroy();
2013-10-18 21:14:58 +00:00
}
2013-09-29 20:16:47 +00:00
}
private void loadConfig() throws IOException, JedisConnectionException {
2013-09-29 20:16:47 +00:00
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
File file = new File(getDataFolder(), "config.yml");
if (!file.exists()) {
file.createNewFile();
try (InputStream in = getResourceAsStream("example_config.yml");
OutputStream out = new FileOutputStream(file)) {
ByteStreams.copy(in, out);
2013-09-29 20:16:47 +00:00
}
}
final Configuration configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file);
final String redisServer = configuration.getString("redis-server", "localhost");
final int redisPort = configuration.getInt("redis-port", 6379);
String redisPassword = configuration.getString("redis-password");
String serverId = configuration.getString("server-id");
2013-09-29 20:16:47 +00:00
2014-06-17 19:47:52 +00:00
if (redisPassword != null && (redisPassword.isEmpty() || redisPassword.equals("none"))) {
redisPassword = null;
}
2013-09-29 20:16:47 +00:00
// Configuration sanity checks.
2014-06-17 19:47:52 +00:00
if (serverId == null || serverId.isEmpty()) {
throw new RuntimeException("server-id is not specified in the configuration or is empty");
}
2013-11-15 22:55:57 +00:00
2014-06-17 19:47:52 +00:00
if (redisServer != null && !redisServer.isEmpty()) {
final String finalRedisPassword = redisPassword;
FutureTask<JedisPool> task = new FutureTask<>(new Callable<JedisPool>() {
@Override
public JedisPool call() throws Exception {
// With recent versions of Jedis, we must set the classloader to the one BungeeCord used
// to load RedisBungee with.
ClassLoader previous = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(RedisBungee.class.getClassLoader());
// Create the pool...
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(configuration.getInt("max-redis-connections", 8));
config.setJmxEnabled(false);
JedisPool pool = new JedisPool(config, redisServer, redisPort, 0, finalRedisPassword);
// Reset classloader and return the pool
Thread.currentThread().setContextClassLoader(previous);
return pool;
}
});
getProxy().getScheduler().runAsync(this, task);
try {
pool = task.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Unable to create Redis pool", e);
}
2014-06-17 19:47:52 +00:00
// Test the connection
2015-05-17 18:46:44 +00:00
try (Jedis rsc = pool.getResource()) {
rsc.ping();
2014-06-17 19:47:52 +00:00
// If that worked, now we can check for an existing, alive Bungee:
File crashFile = new File(getDataFolder(), "restarted_from_crash.txt");
if (crashFile.exists()) {
2014-06-17 19:47:52 +00:00
crashFile.delete();
} else if (rsc.hexists("heartbeats", serverId)) {
2014-06-17 19:47:52 +00:00
try {
long value = Long.parseLong(rsc.hget("heartbeats", serverId));
if (System.currentTimeMillis() < value + 20000) {
getLogger().severe("You have launched a possible impostor BungeeCord instance. Another instance is already running.");
2014-06-17 19:47:52 +00:00
getLogger().severe("For data consistency reasons, RedisBungee will now disable itself.");
getLogger().severe("If this instance is coming up from a crash, create a file in your RedisBungee plugins directory with the name 'restarted_from_crash.txt' and RedisBungee will not perform this check.");
throw new RuntimeException("Possible impostor instance!");
}
2014-06-17 19:47:52 +00:00
} catch (NumberFormatException ignored) {
}
2014-06-17 19:47:52 +00:00
}
FutureTask<Void> task2 = new FutureTask<>(new Callable<Void>() {
@Override
public Void call() throws Exception {
2015-01-25 05:17:52 +00:00
httpClient = new OkHttpClient();
Dispatcher dispatcher = new Dispatcher(getExecutorService());
2015-03-28 20:46:08 +00:00
httpClient.setDispatcher(dispatcher);
2015-02-04 15:02:30 +00:00
NameFetcher.setHttpClient(httpClient);
2015-02-10 15:04:03 +00:00
UUIDFetcher.setHttpClient(httpClient);
RedisBungee.configuration = new RedisBungeeConfiguration(RedisBungee.this.getPool(), configuration);
return null;
}
});
getProxy().getScheduler().runAsync(this, task2);
try {
task2.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Unable to create HTTP client", e);
}
2014-06-17 19:47:52 +00:00
getLogger().log(Level.INFO, "Successfully connected to Redis.");
} catch (JedisConnectionException e) {
pool.destroy();
pool = null;
throw e;
2013-09-29 20:16:47 +00:00
}
} else {
throw new RuntimeException("No redis server specified!");
2013-09-29 20:16:47 +00:00
}
}
2015-06-24 09:54:19 +00:00
@NoArgsConstructor(access = AccessLevel.PRIVATE)
class PubSubListener implements Runnable {
private JedisPubSubHandler jpsh;
@Override
public void run() {
2015-06-24 09:54:19 +00:00
try (Jedis rsc = pool.getResource()) {
jpsh = new JedisPubSubHandler();
rsc.subscribe(jpsh, "redisbungee-" + configuration.getServerId(), "redisbungee-allservers", "redisbungee-data");
} catch (JedisException | ClassCastException ignored) {
}
}
public void addChannel(String... channel) {
jpsh.subscribe(channel);
}
public void removeChannel(String... channel) {
jpsh.unsubscribe(channel);
}
public void poison() {
jpsh.unsubscribe();
}
}
private class JedisPubSubHandler extends JedisPubSub {
@Override
public void onMessage(final String s, final String s2) {
2014-01-26 00:06:33 +00:00
if (s2.trim().length() == 0) return;
getProxy().getScheduler().runAsync(RedisBungee.this, new Runnable() {
2014-03-31 14:23:10 +00:00
@Override
public void run() {
getProxy().getPluginManager().callEvent(new PubSubMessageEvent(s, s2));
2014-03-31 14:23:10 +00:00
}
});
}
}
2013-09-29 20:16:47 +00:00
}