Search in sources :

Example 6 with RedisException

use of org.redisson.client.RedisException in project redisson by redisson.

the class ConnectionWatchdog method tryReconnect.

private void tryReconnect(final RedisConnection connection, final int nextAttempt) {
    if (connection.isClosed() || bootstrap.group().isShuttingDown()) {
        return;
    }
    log.debug("reconnecting {} to {} ", connection, connection.getRedisClient().getAddr(), connection);
    bootstrap.connect().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (connection.isClosed() || bootstrap.group().isShuttingDown()) {
                return;
            }
            try {
                if (future.isSuccess()) {
                    log.debug("{} connected to {}", connection, connection.getRedisClient().getAddr());
                    reconnect(connection, future.channel());
                    return;
                }
            } catch (RedisException e) {
                log.warn("Can't connect " + connection + " to " + connection.getRedisClient().getAddr(), e);
            }
            reconnect(connection, nextAttempt);
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) RedisException(org.redisson.client.RedisException) ChannelFutureListener(io.netty.channel.ChannelFutureListener) RedisException(org.redisson.client.RedisException)

Example 7 with RedisException

use of org.redisson.client.RedisException in project redisson by redisson.

the class ClusterConnectionManager method connect.

private RFuture<RedisConnection> connect(ClusterServersConfig cfg, final URL addr) {
    RedisConnection connection = nodeConnections.get(addr);
    if (connection != null) {
        return newSucceededFuture(connection);
    }
    RedisClient client = createClient(addr.getHost(), addr.getPort(), cfg.getConnectTimeout(), cfg.getRetryInterval() * cfg.getRetryAttempts());
    final RPromise<RedisConnection> result = newPromise();
    RFuture<RedisConnection> future = client.connectAsync();
    future.addListener(new FutureListener<RedisConnection>() {

        @Override
        public void operationComplete(Future<RedisConnection> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }
            RedisConnection connection = future.getNow();
            RPromise<RedisConnection> promise = newPromise();
            connectListener.onConnect(promise, connection, null, config);
            promise.addListener(new FutureListener<RedisConnection>() {

                @Override
                public void operationComplete(Future<RedisConnection> future) throws Exception {
                    if (!future.isSuccess()) {
                        result.tryFailure(future.cause());
                        return;
                    }
                    RedisConnection connection = future.getNow();
                    if (connection.isActive()) {
                        nodeConnections.put(addr, connection);
                        result.trySuccess(connection);
                    } else {
                        connection.closeAsync();
                        result.tryFailure(new RedisException("Connection to " + connection.getRedisClient().getAddr() + " is not active!"));
                    }
                }
            });
        }
    });
    return result;
}
Also used : RedisClient(org.redisson.client.RedisClient) FutureListener(io.netty.util.concurrent.FutureListener) RPromise(org.redisson.misc.RPromise) ScheduledFuture(io.netty.util.concurrent.ScheduledFuture) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future) RedisException(org.redisson.client.RedisException) RedisException(org.redisson.client.RedisException) RedisConnectionException(org.redisson.client.RedisConnectionException) RedisConnection(org.redisson.client.RedisConnection)

Example 8 with RedisException

use of org.redisson.client.RedisException in project redisson by redisson.

the class ReplicatedConnectionManager method connect.

private RFuture<RedisConnection> connect(BaseMasterSlaveServersConfig<?> cfg, final URL addr) {
    RedisConnection connection = nodeConnections.get(addr);
    if (connection != null) {
        return newSucceededFuture(connection);
    }
    RedisClient client = createClient(addr.getHost(), addr.getPort(), cfg.getConnectTimeout(), cfg.getRetryInterval() * cfg.getRetryAttempts());
    final RPromise<RedisConnection> result = newPromise();
    RFuture<RedisConnection> future = client.connectAsync();
    future.addListener(new FutureListener<RedisConnection>() {

        @Override
        public void operationComplete(Future<RedisConnection> future) throws Exception {
            if (!future.isSuccess()) {
                result.tryFailure(future.cause());
                return;
            }
            RedisConnection connection = future.getNow();
            RPromise<RedisConnection> promise = newPromise();
            connectListener.onConnect(promise, connection, null, config);
            promise.addListener(new FutureListener<RedisConnection>() {

                @Override
                public void operationComplete(Future<RedisConnection> future) throws Exception {
                    if (!future.isSuccess()) {
                        result.tryFailure(future.cause());
                        return;
                    }
                    RedisConnection connection = future.getNow();
                    if (connection.isActive()) {
                        nodeConnections.put(addr, connection);
                        result.trySuccess(connection);
                    } else {
                        connection.closeAsync();
                        result.tryFailure(new RedisException("Connection to " + connection.getRedisClient().getAddr() + " is not active!"));
                    }
                }
            });
        }
    });
    return result;
}
Also used : RedisClient(org.redisson.client.RedisClient) FutureListener(io.netty.util.concurrent.FutureListener) RPromise(org.redisson.misc.RPromise) ScheduledFuture(io.netty.util.concurrent.ScheduledFuture) RFuture(org.redisson.api.RFuture) Future(io.netty.util.concurrent.Future) RedisException(org.redisson.client.RedisException) RedisException(org.redisson.client.RedisException) RedisConnectionException(org.redisson.client.RedisConnectionException) RedisConnection(org.redisson.client.RedisConnection)

Example 9 with RedisException

use of org.redisson.client.RedisException in project redisson by redisson.

the class CommandDecoder method decode.

private void decode(ByteBuf in, CommandData<Object, Object> data, List<Object> parts, Channel channel) throws IOException {
    int code = in.readByte();
    if (code == '+') {
        ByteBuf rb = in.readBytes(in.bytesBefore((byte) '\r'));
        try {
            String result = rb.toString(CharsetUtil.UTF_8);
            in.skipBytes(2);
            handleResult(data, parts, result, false, channel);
        } finally {
            rb.release();
        }
    } else if (code == '-') {
        ByteBuf rb = in.readBytes(in.bytesBefore((byte) '\r'));
        try {
            String error = rb.toString(CharsetUtil.UTF_8);
            in.skipBytes(2);
            if (error.startsWith("MOVED")) {
                String[] errorParts = error.split(" ");
                int slot = Integer.valueOf(errorParts[1]);
                String addr = errorParts[2];
                data.tryFailure(new RedisMovedException(slot, addr));
            } else if (error.startsWith("ASK")) {
                String[] errorParts = error.split(" ");
                int slot = Integer.valueOf(errorParts[1]);
                String addr = errorParts[2];
                data.tryFailure(new RedisAskException(slot, addr));
            } else if (error.startsWith("TRYAGAIN")) {
                data.tryFailure(new RedisTryAgainException(error + ". channel: " + channel + " data: " + data));
            } else if (error.startsWith("LOADING")) {
                data.tryFailure(new RedisLoadingException(error + ". channel: " + channel + " data: " + data));
            } else if (error.startsWith("OOM")) {
                data.tryFailure(new RedisOutOfMemoryException(error.split("OOM ")[1] + ". channel: " + channel + " data: " + data));
            } else if (error.contains("-OOM ")) {
                data.tryFailure(new RedisOutOfMemoryException(error.split("-OOM ")[1] + ". channel: " + channel + " data: " + data));
            } else {
                if (data != null) {
                    data.tryFailure(new RedisException(error + ". channel: " + channel + " command: " + data));
                } else {
                    log.error("Error: {} channel: {} data: {}", error, channel, data);
                }
            }
        } finally {
            rb.release();
        }
    } else if (code == ':') {
        Long result = readLong(in);
        handleResult(data, parts, result, false, channel);
    } else if (code == '$') {
        ByteBuf buf = readBytes(in);
        Object result = null;
        if (buf != null) {
            Decoder<Object> decoder = selectDecoder(data, parts);
            result = decoder.decode(buf, state());
        }
        handleResult(data, parts, result, false, channel);
    } else if (code == '*') {
        int level = state().incLevel();
        long size = readLong(in);
        List<Object> respParts;
        if (state().getLevels().size() - 1 >= level) {
            StateLevel stateLevel = state().getLevels().get(level);
            respParts = stateLevel.getParts();
            size = stateLevel.getSize();
        } else {
            respParts = new ArrayList<Object>();
            if (state().isMakeCheckpoint()) {
                state().addLevel(new StateLevel(size, respParts));
            }
        }
        decodeList(in, data, parts, channel, size, respParts);
    } else {
        String dataStr = in.toString(0, in.writerIndex(), CharsetUtil.UTF_8);
        throw new IllegalStateException("Can't decode replay: " + dataStr);
    }
}
Also used : RedisMovedException(org.redisson.client.RedisMovedException) RedisTryAgainException(org.redisson.client.RedisTryAgainException) ByteBuf(io.netty.buffer.ByteBuf) ReplayingDecoder(io.netty.handler.codec.ReplayingDecoder) Decoder(org.redisson.client.protocol.Decoder) ListMultiDecoder(org.redisson.client.protocol.decoder.ListMultiDecoder) SlotsDecoder(org.redisson.client.protocol.decoder.SlotsDecoder) NestedMultiDecoder(org.redisson.client.protocol.decoder.NestedMultiDecoder) MultiDecoder(org.redisson.client.protocol.decoder.MultiDecoder) RedisLoadingException(org.redisson.client.RedisLoadingException) RedisException(org.redisson.client.RedisException) RedisAskException(org.redisson.client.RedisAskException) RedisOutOfMemoryException(org.redisson.client.RedisOutOfMemoryException)

Example 10 with RedisException

use of org.redisson.client.RedisException in project MantaroBot by Mantaro.

the class CommandListener method onCommand.

private void onCommand(GuildMessageReceivedEvent event) {
    try {
        Member self = event.getGuild().getSelfMember();
        if (!self.getPermissions(event.getChannel()).contains(Permission.MESSAGE_WRITE) && !self.hasPermission(Permission.ADMINISTRATOR))
            return;
        if (commandProcessor.run(event)) {
            commandTotal++;
        } else {
            // Only run experience if no command has been executed, avoids weird race conditions when saving player status.
            try {
                // Only run experience if the user is not rate limited (clears every 30 seconds)
                if (random.nextInt(15) > 7 && !event.getAuthor().isBot() && experienceRatelimiter.process(event.getAuthor())) {
                    if (event.getMember() == null)
                        return;
                    // some nasty race conditions involving player save.
                    if (InteractiveOperations.get(event.getChannel()) != null)
                        return;
                    Player player = MantaroData.db().getPlayer(event.getAuthor());
                    PlayerData data = player.getData();
                    DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
                    GuildData guildData = dbGuild.getData();
                    if (player.isLocked())
                        return;
                    // Set level to 1 if level is zero.
                    if (player.getLevel() == 0)
                        player.setLevel(1);
                    // Set player experience to a random number between 1 and 5.
                    data.setExperience(data.getExperience() + Math.round(random.nextInt(5)));
                    // Apply some black magic.
                    if (data.getExperience() > (player.getLevel() * Math.log10(player.getLevel()) * 1000) + (50 * player.getLevel() / 2)) {
                        player.setLevel(player.getLevel() + 1);
                        // Check if the member is not null, just to be sure it happened in-between.
                        if (player.getLevel() > 1 && event.getGuild().getMemberById(player.getUserId()) != null) {
                            if (guildData.isEnabledLevelUpMessages()) {
                                String levelUpChannel = guildData.getLevelUpChannel();
                                String levelUpMessage = guildData.getLevelUpMessage();
                                // Player has leveled up!
                                if (levelUpMessage != null && levelUpChannel != null) {
                                    processMessage(String.valueOf(player.getLevel()), levelUpMessage, levelUpChannel, event);
                                }
                            }
                        }
                    }
                    // This time, actually remember to save the player so you don't have to restart 102 shards to fix it.
                    player.saveAsync();
                }
            } catch (Exception ignored) {
            }
        }
    } catch (IndexOutOfBoundsException e) {
        event.getChannel().sendMessage(EmoteReference.ERROR + "Your query returned no results or you used the incorrect arguments, seemingly. Just in case, check command help!").queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            event.getChannel().sendMessage(String.format("%sI don't have permission to do this :<, I need the permission: **%s**%s", EmoteReference.ERROR, e.getPermission().getName(), e.getMessage() != null ? String.format(" | Message: %s", e.getMessage()) : "")).queue();
        } else {
            event.getChannel().sendMessage(EmoteReference.ERROR + "I cannot perform this action due to the lack of permission! Is the role I might be trying to assign" + " higher than my role? Do I have the correct permissions/hierarchy to perform this action?").queue();
        }
    } catch (IllegalArgumentException e) {
        // NumberFormatException == IllegalArgumentException
        String id = Snow64.toSnow64(event.getMessage().getIdLong());
        event.getChannel().sendMessage(String.format("%sI think you forgot something on the floor. (Maybe we threw it there? [Error ID: %s]... I hope we didn't)\n" + "- Incorrect type arguments or the message I'm trying to send exceeds 2048 characters, Just in case, check command help!", EmoteReference.ERROR, id)).queue();
        log.warn("Exception caught and alternate message sent. We should look into this, anyway (ID: {})", id, e);
    } catch (ReqlError e) {
        // So much just went wrong...
        e.printStackTrace();
        SentryHelper.captureExceptionContext("Something seems to have broken in the db! Check this out!", e, this.getClass(), "Database");
    } catch (RedisException e) {
        // So much just went wrong but on another side of the db...
        e.printStackTrace();
        SentryHelper.captureExceptionContext("Something seems to have broken in the db! Check this out!", e, this.getClass(), "Redis Database");
    } catch (Exception e) {
        String id = Snow64.toSnow64(event.getMessage().getIdLong());
        Player player = MantaroData.db().getPlayer(event.getAuthor());
        event.getChannel().sendMessage(String.format("%s%s\n(Error ID: `%s`)\n" + "If you want, join our **support guild** (Link on `~>about`), or check out our GitHub page (/Mantaro/MantaroBot). " + "Please tell them to quit exploding me and please don't forget the Error ID when reporting!", EmoteReference.ERROR, boomQuotes[rand.nextInt(boomQuotes.length)], id)).queue();
        if (player.getData().addBadgeIfAbsent(Badge.FIRE))
            player.saveAsync();
        SentryHelper.captureException(String.format("Unexpected Exception on Command: %s | (Error ID: ``%s``)", event.getMessage().getContentRaw(), id), e, this.getClass());
        log.error("Error happened with id: {} (Error ID: {})", event.getMessage().getContentRaw(), id, e);
    }
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Player(net.kodehawa.mantarobot.db.entities.Player) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) ReqlError(com.rethinkdb.gen.exc.ReqlError) RedisException(org.redisson.client.RedisException) Member(net.dv8tion.jda.core.entities.Member) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) RedisException(org.redisson.client.RedisException) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException)

Aggregations

RedisException (org.redisson.client.RedisException)13 CommandBatchService (org.redisson.command.CommandBatchService)5 RFuture (org.redisson.api.RFuture)3 RedisClient (org.redisson.client.RedisClient)3 Future (io.netty.util.concurrent.Future)2 FutureListener (io.netty.util.concurrent.FutureListener)2 ScheduledFuture (io.netty.util.concurrent.ScheduledFuture)2 InvocationHandler (java.lang.reflect.InvocationHandler)2 Method (java.lang.reflect.Method)2 List (java.util.List)2 RBitSetAsync (org.redisson.api.RBitSetAsync)2 RemoteInvocationOptions (org.redisson.api.RemoteInvocationOptions)2 RedisConnection (org.redisson.client.RedisConnection)2 RedisConnectionException (org.redisson.client.RedisConnectionException)2 RPromise (org.redisson.misc.RPromise)2 ReqlError (com.rethinkdb.gen.exc.ReqlError)1 ByteBuf (io.netty.buffer.ByteBuf)1 ChannelFuture (io.netty.channel.ChannelFuture)1 ChannelFutureListener (io.netty.channel.ChannelFutureListener)1 ReplayingDecoder (io.netty.handler.codec.ReplayingDecoder)1