|
| 1 | +package org.apache.hugegraph.util; |
| 2 | + |
| 3 | +import com.alipay.sofa.jraft.Node; |
| 4 | +import com.alipay.sofa.jraft.ReplicatorGroup; |
| 5 | +import com.alipay.sofa.jraft.core.Replicator; |
| 6 | +import com.alipay.sofa.jraft.entity.PeerId; |
| 7 | +import com.alipay.sofa.jraft.util.ThreadId; |
| 8 | + |
| 9 | +import lombok.extern.slf4j.Slf4j; |
| 10 | +import lombok.var; |
| 11 | + |
| 12 | +@Slf4j |
| 13 | +public class RaftReflectionUtil { |
| 14 | + |
| 15 | + public static Replicator.State getReplicatorState(Node node, PeerId peerId) { |
| 16 | + if (node == null || peerId == null) { |
| 17 | + return null; |
| 18 | + } |
| 19 | + |
| 20 | + // Get ReplicatorGroup from Node |
| 21 | + var clz = node.getClass(); |
| 22 | + ReplicatorGroup replicateGroup = null; |
| 23 | + try { |
| 24 | + var f = clz.getDeclaredField("replicatorGroup"); |
| 25 | + f.setAccessible(true); |
| 26 | + try { |
| 27 | + replicateGroup = (ReplicatorGroup) f.get(node); |
| 28 | + } finally { |
| 29 | + f.setAccessible(false); |
| 30 | + } |
| 31 | + } catch (NoSuchFieldException | IllegalAccessException e) { |
| 32 | + log.info("getReplicatorGroup: error {}", e.getMessage()); |
| 33 | + return null; |
| 34 | + } |
| 35 | + |
| 36 | + if (replicateGroup == null) { |
| 37 | + return null; |
| 38 | + } |
| 39 | + |
| 40 | + ThreadId threadId = replicateGroup.getReplicator(peerId); |
| 41 | + if (threadId == null) { |
| 42 | + return null; |
| 43 | + } else { |
| 44 | + Replicator r = (Replicator) threadId.lock(); |
| 45 | + if (r == null) { |
| 46 | + return Replicator.State.Probe; |
| 47 | + } |
| 48 | + Replicator.State result = null; |
| 49 | + |
| 50 | + // Get state from Replicator |
| 51 | + try { |
| 52 | + var replicatorClz = r.getClass(); |
| 53 | + try { |
| 54 | + var f = replicatorClz.getDeclaredField("state"); |
| 55 | + f.setAccessible(true); |
| 56 | + try { |
| 57 | + result = (Replicator.State) f.get(r); |
| 58 | + } finally { |
| 59 | + f.setAccessible(false); |
| 60 | + } |
| 61 | + } catch (NoSuchFieldException | IllegalAccessException e) { |
| 62 | + log.info("getReplicatorState: error {}", e.getMessage()); |
| 63 | + result = null; |
| 64 | + } |
| 65 | + } |
| 66 | + finally { |
| 67 | + threadId.unlock(); |
| 68 | + } |
| 69 | + return result; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments