问题复盘:一个Redisson驱动源码BUG

今天来看一个之前遇到的问题。

前段时间,生产环境的一个模块偶发性出现不工作的情况,最后定位到是模块中使用的Redisson源码中的一个BUG。

还顺便给Redisson增加了一个测试用例:

https://github.com/redisson/redisson/commit/fdde5d8bcb3259d7b558993fc2e449ef5cc0385a

Redisson是Redis官方推荐的Java版的Redis客户端,是一个在Redis的基础上实现的Java驻内存数据网格(In-Memory Data Grid),在GitHub上有16.3K的star。

Redisson 提供了许多 Features ,这次出问题的是业务模块中使用到的分布式调度任务服务(Scheduler Service),使用的Redisson 版本是3.14.1 。

本文主要是问题的一个复盘,更重要的是记录下处理过程中的思路。如果有更好的定位手段欢迎交流一下。

01、拿到问题后积极收集相关数据,合理分析,大胆假设

接到问题反馈后,先去查看了线上的业务日志情况,发现已经没有处理业务线程输出日志,正常情况下只要服务正常运行都是会有相关记录的,所以初步怀疑是某个方法将线程池的所有线程都阻塞了。

因为已经让运维的同学开了新的服务机器保证用户使用,将这台问题机器暂时保留作为定位用,所以 可以在当前机器上使用 arthas 查看当前服务的一个线程情况。

Arthas 是 Alibaba 开源的Java诊断工具,可以比较方便在生产环境机器上进行问题的定位和诊断。

更多介绍可以查看官方介绍:

https://arthas.aliyun.com/doc/

[arthas@1440]$ thread -allThreads Total: 332, NEW: 0, RUNNABLE: 149, BLOCKED: 0, WAITING: 146, TIMED_WAITING: 25, TERMINATED: 0, Internal threads: 12                                            ID     NAME                                      GROUP                PRIORITY      STATE        %CPU          DELTA_TIME    TIME          INTERRUPTED   DAEMON          ...           143485 pool-4-thread-112353                      main                 5             WAITING      0.0           0.000         0:41.813      false         false         144056 pool-4-thread-112725                      main                 5             WAITING      0.0           0.000         0:0.655       false         false         144064 pool-4-thread-112731                      main                 5             WAITING      0.0           0.000         0:6.117       false         false         144314 pool-4-thread-112875                      main                 5             WAITING      0.0           0.000         0:15.230      false         false         144345 pool-4-thread-112885                      main                 5             WAITING      0.0           0.000         5:11.817      false         false         144506 pool-4-thread-112905                      main                 5             WAITING      0.0           0.000         17:3.553      false         false         144529 pool-4-thread-112914                      main                 5             WAITING      0.0           0.000         115:34.837    false         false         144534 pool-4-thread-112915                      main                 5             WAITING      0.0           0.000         167:40.361    false         false         144536 pool-4-thread-112916                      main                 5             WAITING      0.0           0.000         13:45.058     false         false         144539 pool-4-thread-112917                      main                 5             WAITING      0.0           0.000         101:58.574    false         false         144545 pool-4-thread-112918                      main                 5             WAITING      0.0           0.000         22:18.870     false         false         ...[arthas@1440]$ thread 143485"pool-4-thread-112353" Id=143485 WAITING on io.netty.util.concurrent.ImmediateEventExecutor$ImmediatePromise@efc8da9    at java.lang.Object.wait(Native Method)    -  waiting on io.netty.util.concurrent.ImmediateEventExecutor$ImmediatePromise@efc8da9    at java.lang.Object.wait(Object.java:502)    at io.netty.util.concurrent.DefaultPromise.await(DefaultPromise.java:252)    at org.redisson.misc.RedissonPromise.await(RedissonPromise.java:110)    at org.redisson.misc.RedissonPromise.await(RedissonPromise.java:35)    at org.redisson.command.CommandAsyncService.get(CommandAsyncService.java:139)    at org.redisson.RedissonExecutorService.cancelTask(RedissonExecutorService.java:1036)    ...    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)    at java.lang.Thread.run(Thread.java:748)

查看对应源码可以看到其实这里实际调用的是一个异步方法,但根据堆栈信息反推不出问题根本原因。

public boolean cancelTask(String taskId) {    return commandExecutor.get(cancelTaskAsync(taskId));}

可以看出,是在取消定时任务的地方阻塞了。该业务模块使用了定时模块,比如说60s后执行某个动作,但是这个定时是能被取消的,一个特定的请求会触发取消掉这个定时任务,这时候就需要调用 cancelTask方法,但是在业务上线之前肯定都是经过测试的,并且已经在线上跑了快一年了,也没有出现过问题。

通过对问题时间点附近的业务日志进行分析,发现一个异常的点,在调用cancelTask发生阻塞线程的上下文中,都是在60s定时时间到,开始执行定时任务的时候触发了取消定时任务。通过往前查找相似的业务日志, 发现这个特殊情况下阻塞线程也是概率出现的。

02、在测试环境根据推测简化代码,提高复现概率,确认问题出现步骤

根据生产环境中收集到的信息和对问题的推测,在测试环境下 去模拟复现问题,确认问题复现步骤。但是在之前, 可以对测试环境做一些精简处理,比如说将模块的业务线程池总线程数量减少,提高复现效率。

在测试环境验证的过程中,发现了几个有意思的点:

1、取消定时任务的时机非常重要. 必须是该定时任务正在执行中,可以是已经由Redisson开始反序列化任务对象,也可以是已经在执行定时的业务代码,但是不能是任务已经执行完毕

2、通过延长定时任务处理时间可以提高问题复现概率

3、定时任务的业务代码中添加了延时后,取消任务后若定时任务还有超过3s的时间,就会抛出InterruptedException异常,取消任务也是成功的,不会阻塞线程

因为能在测试环境直接必现问题,所以是可以在测试环境的跑服务的机器上打开调试端口,通过ssh的反向代理让本机进入远程调试模式,进一步确认异步方法的阻塞位置。

03、在本地环境提炼出问题的测试用例,进一步分析

通过以上操作,基本已经能确定问题的复现步骤了,可以将问题部分摘出来写成测试用例,一方面能反馈给官方,另一方面也能在本地进一步确认问题的原因。

代码如下:

public class SchedulerServiceExamples {    private static final Logger LOG = LoggerFactory.getLogger(SchedulerServiceExamples.class);    public static void main(String[] args) throws InterruptedException {        Config config = new Config();        config.useSingleServer().setAddress("redis://127.0.0.1:6379");        RedissonClient redisson = Redisson.create(config);        RedissonNodeConfig nodeConfig = new RedissonNodeConfig(config);        nodeConfig.setExecutorServiceWorkers(Collections.singletonMap("myExecutor", 5));        RedissonNode node = RedissonNode.create(nodeConfig);        node.start();        RScheduledExecutorService e = redisson.getExecutorService("myExecutor");        String taskId = redisson.getExecutorService("myExecutor").schedule(new RunnableTask(), 2000, TimeUnit.MILLISECONDS).getTaskId();        Thread.sleep(5500);        LOG.info("xxxx start cancel task {}", taskId);        e.cancelTask(taskId);        LOG.info("yyyy end cancel task {}", taskId);    }    public static class RunnableTask implements Runnable, Serializable {        private static final Logger LOG = LoggerFactory.getLogger(RunnableTask.class);        @Override        public void run() {            LOG.info("Task start...");            try {                Thread.sleep(1000);                LOG.info("Task running 1 ...");                Thread.sleep(1000);                LOG.info("Task running 2 ...");                Thread.sleep(1000);                LOG.info("Task running 3 ...");                Thread.sleep(1000);                LOG.info("Task running 4 ...");            } catch (InterruptedException interruptedException) {                LOG.info("Task interruptedException");            }        }    }

可以在执行完取消任务的下一行日志设置断点,可以看到并不会执行到36行。

继续往下定位, 能确认是在 scheduleCheck 中死循环了,因为当前进入了异常分支

继续看下removeAsync方法

removeOperationAsync 做了做了什么事情呢?其实就是去获取hash 里面的序列化任务。

protected RFuture removeOperationAsync(K key) {    String name = getName(key);    return commandExecutor.evalWriteAsync(name, codec, RedisCommands.EVAL_MAP_VALUE,            "local v = redis.call('hget', KEYS[1], ARGV[1]); "            + "redis.call('hdel', KEYS[1], ARGV[1]); "            + "return v",            Collections.singletonList(name), encodeMapKey(key));}

但是在此时任务对应的 hashmap key 已经被删除了,可以从输出的日志中查看到相应输出

19:55:10.852 [redisson-netty-5-17] DEBUG org.redisson.command.RedisExecutor - connection released for command (EVAL) and params [local value = redis.call('zscore', KEYS[2], ARGV[1]); if (value ~= false and tonumber(value) < tonum..., 7, {myExecutor:org.redisson.executor.RemoteExecutorService}:tasks, {myExecutor:org.redisson.executor.RemoteExecutorService}:expiration, {myExecutor:org.redisson.executor.RemoteExecutorService}:counter, {myExecutor:org.redisson.executor.RemoteExecutorService}:status, {myExecutor:org.redisson.executor.RemoteExecutorService}:retry-interval, {myExecutor:org.redisson.executor.RemoteExecutorService}:termination-topic, {myExecutor:org.redisson.executor.RemoteExecutorService}:scheduler, 0185996c68c89d47cc0da91d38ebc87d02, ...] from slot NodeSource [slot=0, addr=null, redisClient=null, redirect=null, entry=null] using connection RedisConnection@334656297 [redisClient=[addr=redis://127.0.0.1:6379], channel=[id: 0x86bb7257, L:/127.0.0.1:60572 - R:/127.0.0.1:6379], currentCommand=CommandData [promise=RedissonPromise [promise=ImmediateEventExecutor$ImmediatePromise@710d6403(success: RemoteServiceRequest [requestId=0185996c68c89d47cc0da91d38ebc87d02, methodName=scheduleRunnable, signature=[J@538349a2, args=[org.redisson.executor.params.ScheduledParameters@5333e8cd], options=RemoteInvocationOptions[ackTimeoutInMillis=null, executionTimeoutInMillis=3600000], date=1619956508690])], command=(EVAL), params=[local value = redis.call('zscore', KEYS[2], ARGV[1]); if (value ~= false and tonumber(value) < tonum..., 7, {myExecutor:org.redisson.executor.RemoteExecutorService}:tasks, {myExecutor:org.redisson.executor.RemoteExecutorService}:expiration, {myExecutor:org.redisson.executor.RemoteExecutorService}:counter, {myExecutor:org.redisson.executor.RemoteExecutorService}:status, {myExecutor:org.redisson.executor.RemoteExecutorService}:retry-interval, {myExecutor:org.redisson.executor.RemoteExecutorService}:termination-topic, {myExecutor:org.redisson.executor.RemoteExecutorService}:scheduler, 0185996c68c89d47cc0da91d38ebc87d02, ...], codec=org.redisson.codec.MarshallingCodec]]19:55:10.861 [redisson-6-6] INFO com.neo.web.SchedulerServiceExamples$RunnableTask - Task start...19:55:11.861 [redisson-6-6] INFO com.neo.web.SchedulerServiceExamples$RunnableTask - Task running 1 ...19:55:12.862 [redisson-6-6] INFO com.neo.web.SchedulerServiceExamples$RunnableTask - Task running 2 ...19:55:13.426 [redisson-netty-2-21] DEBUG org.redisson.connection.DNSMonitor - Request sent to resolve ip address for master host: 127.0.0.119:55:13.429 [redisson-netty-2-20] DEBUG org.redisson.connection.DNSMonitor - Resolved ip: /127.0.0.1 for master host: 127.0.0.119:55:13.575 [redisson-netty-5-21] DEBUG org.redisson.connection.DNSMonitor - Request sent to resolve ip address for master host: 127.0.0.119:55:13.576 [redisson-netty-5-20] DEBUG org.redisson.connection.DNSMonitor - Resolved ip: /127.0.0.1 for master host: 127.0.0.119:55:13.862 [redisson-6-6] INFO com.neo.web.SchedulerServiceExamples$RunnableTask - Task running 3 ...19:55:13.886 [redisson-timer-7-1] DEBUG org.redisson.command.RedisExecutor - acquired connection for command (EVAL) and params [local v = redis.call('hget', KEYS[1], ARGV[1]); redis.call('hdel', KEYS[1], ARGV[1]); return v, 1, {myExecutor:remote}:cancel-request, PooledUnsafeDirectByteBuf(ridx: 0, widx: 34, cap: 256)] from slot NodeSource [slot=0, addr=null, redisClient=null, redirect=null, entry=null] using node /127.0.0.1:6379... RedisConnection@956171700 [redisClient=[addr=redis://127.0.0.1:6379], channel=[id: 0xc1cbe7cf, L:/127.0.0.1:60568 - R:/127.0.0.1:6379], currentCommand=null]19:55:13.888 [redisson-netty-5-14] DEBUG org.redisson.command.RedisExecutor - connection released for command (EVAL) and params [local v = redis.call('hget', KEYS[1], ARGV[1]); redis.call('hdel', KEYS[1], ARGV[1]); return v, 1, {myExecutor:remote}:cancel-request, PooledUnsafeDirectByteBuf(ridx: 0, widx: 34, cap: 256)] from slot NodeSource [slot=0, addr=null, redisClient=null, redirect=null, entry=null] using connection RedisConnection@956171700 [redisClient=[addr=redis://127.0.0.1:6379], channel=[id: 0xc1cbe7cf, L:/127.0.0.1:60568 - R:/127.0.0.1:6379], currentCommand=CommandData [promise=RedissonPromise [promise=ImmediateEventExecutor$ImmediatePromise@954380a(success)], command=(EVAL), params=[local v = redis.call('hget', KEYS[1], ARGV[1]); redis.call('hdel', KEYS[1], ARGV[1]); return v, 1, {myExecutor:remote}:cancel-request, PooledUnsafeDirectByteBuf(ridx: 0, widx: 34, cap: 256)], codec=org.redisson.codec.CompositeCodec@85fd4fb7]]19:55:14.208 [main] INFO com.neo.web.SchedulerServiceExamples - xxxx start cancel task 0185996c68c89d47cc0da91d38ebc87d02

所以导致每3s进入一次 scheduleCheck 检查

将问题和测试用例反馈给redisson官方后,在3.15.1版本已经将该问题修复,可以看下官方的解决办法

合入记录:

https://github.com/redisson/redisson/commit/fdde5d8bcb3259d7b558993fc2e449ef5cc0385a

// 3.15.1private void scheduleCancelResponseCheck(String mapName, RequestId requestId, RPromise cancelResponse) {        commandExecutor.getConnectionManager().newTimeout(timeout -> {            if (cancelResponse.isDone()) {                return;            }            RMap canceledResponses = getMap(mapName);            RFuture future = canceledResponses.removeAsync(requestId.toString());            future.onComplete((response, ex) -> {                if (ex != null) {                    scheduleCancelResponseCheck(mapName, requestId, cancelResponse);                    return;                }                if (response == null) {                    RFuture f = hasTaskAsync(requestId.toString());                    f.onComplete((r, e) -> {                        if (e != null || r) {                            scheduleCancelResponseCheck(mapName, requestId, cancelResponse);                            return;                        }                        RemoteServiceCancelResponse resp = new RemoteServiceCancelResponse(requestId.toString(), false);                        cancelResponse.trySuccess(resp);                    });                } else {                    cancelResponse.trySuccess(response);                }            });        }, 3000, TimeUnit.MILLISECONDS);    }// 3.14.1protected  void scheduleCheck(String mapName, RequestId requestId, RPromise cancelRequest) {        commandExecutor.getConnectionManager().newTimeout(new TimerTask() {            @Override            public void run(Timeout timeout) throws Exception {                if (cancelRequest.isDone()) {                    return;                }                RMap canceledRequests = getMap(mapName);                RFuture future = canceledRequests.removeAsync(requestId.toString());                future.onComplete((request, ex) -> {                    if (cancelRequest.isDone()) {                        return;                    }                    if (ex != null) {                        scheduleCheck(mapName, requestId, cancelRequest);                        return;                    }                                        if (request == null) {                        scheduleCheck(mapName, requestId, cancelRequest);                    } else {                        cancelRequest.trySuccess(request);                    }                });            }        }, 3000, TimeUnit.MILLISECONDS);    }

解决问题的过程就是层层抽丝剥茧,硬着头皮干就完事了!

下班了下班了~

End


【推荐阅读】

1、京东云无线宝怎么设置收益高?一个不需要光猫后台超级账号密码的方法

2、两台主机、多台主机怎么共用键鼠?Windows、Mac OS、Linux 多系统怎么共用键鼠?

3、记录一下小米6解BL锁,获取ROOT权限

你可能感兴趣的:(问题复盘:一个Redisson驱动源码BUG)