|
| 1 | +package org.tron.core.net.service.effective; |
| 2 | + |
| 3 | +import com.google.common.cache.Cache; |
| 4 | +import com.google.common.cache.CacheBuilder; |
| 5 | +import com.google.common.util.concurrent.ThreadFactoryBuilder; |
| 6 | +import java.net.InetSocketAddress; |
| 7 | +import java.util.Comparator; |
| 8 | +import java.util.HashSet; |
| 9 | +import java.util.List; |
| 10 | +import java.util.Optional; |
| 11 | +import java.util.Set; |
| 12 | +import java.util.concurrent.Executors; |
| 13 | +import java.util.concurrent.ScheduledExecutorService; |
| 14 | +import java.util.concurrent.TimeUnit; |
| 15 | +import java.util.concurrent.atomic.AtomicInteger; |
| 16 | +import lombok.Getter; |
| 17 | +import lombok.Setter; |
| 18 | +import lombok.extern.slf4j.Slf4j; |
| 19 | +import org.springframework.beans.factory.annotation.Autowired; |
| 20 | +import org.springframework.stereotype.Component; |
| 21 | +import org.tron.core.config.args.Args; |
| 22 | +import org.tron.core.net.TronNetDelegate; |
| 23 | +import org.tron.core.net.TronNetService; |
| 24 | +import org.tron.core.net.peer.PeerConnection; |
| 25 | +import org.tron.p2p.discover.Node; |
| 26 | +import org.tron.protos.Protocol.ReasonCode; |
| 27 | + |
| 28 | +@Slf4j(topic = "net") |
| 29 | +@Component |
| 30 | +public class EffectiveCheckService { |
| 31 | + |
| 32 | + @Getter |
| 33 | + private final boolean isEffectiveCheck = Args.getInstance().isNodeEffectiveCheckEnable(); |
| 34 | + @Autowired |
| 35 | + private TronNetDelegate tronNetDelegate; |
| 36 | + |
| 37 | + private final Cache<InetSocketAddress, Boolean> nodesCache = CacheBuilder.newBuilder() |
| 38 | + .initialCapacity(100) |
| 39 | + .maximumSize(10000) |
| 40 | + .expireAfterWrite(20, TimeUnit.MINUTES).build(); |
| 41 | + @Getter |
| 42 | + @Setter |
| 43 | + private volatile InetSocketAddress cur; |
| 44 | + private final AtomicInteger count = new AtomicInteger(0); |
| 45 | + private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor( |
| 46 | + new ThreadFactoryBuilder().setNameFormat("effective-thread-%d").build()); |
| 47 | + private long MAX_HANDSHAKE_TIME = 60_000; |
| 48 | + |
| 49 | + public void init() { |
| 50 | + if (isEffectiveCheck) { |
| 51 | + executor.scheduleWithFixedDelay(() -> { |
| 52 | + try { |
| 53 | + findEffectiveNode(); |
| 54 | + } catch (Exception e) { |
| 55 | + logger.error("Check effective connection processing failed", e); |
| 56 | + } |
| 57 | + }, 60, 5, TimeUnit.SECONDS); |
| 58 | + } else { |
| 59 | + logger.info("EffectiveCheckService is disabled"); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public void triggerNext() { |
| 64 | + try { |
| 65 | + executor.submit(this::findEffectiveNode); |
| 66 | + } catch (Exception e) { |
| 67 | + logger.warn("Submit effective service task failed, message:{}", e.getMessage()); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + public void close() { |
| 72 | + if (executor != null) { |
| 73 | + try { |
| 74 | + executor.shutdown(); |
| 75 | + } catch (Exception e) { |
| 76 | + logger.error("Exception in shutdown effective service worker, {}", e.getMessage()); |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + public boolean isIsolateLand() { |
| 82 | + return (int) tronNetDelegate.getActivePeer().stream() |
| 83 | + .filter(PeerConnection::isNeedSyncFromUs) |
| 84 | + .count() == tronNetDelegate.getActivePeer().size(); |
| 85 | + } |
| 86 | + |
| 87 | + //try to find node which we can sync from |
| 88 | + private void findEffectiveNode() { |
| 89 | + if (!isIsolateLand()) { |
| 90 | + if (count.get() > 0) { |
| 91 | + logger.info("Success to verify effective node {}", cur); |
| 92 | + resetCount(); |
| 93 | + } |
| 94 | + return; |
| 95 | + } |
| 96 | + |
| 97 | + if (cur != null) { |
| 98 | + tronNetDelegate.getActivePeer().forEach(p -> { |
| 99 | + if (p.getInetSocketAddress().equals(cur) |
| 100 | + && System.currentTimeMillis() - p.getChannel().getStartTime() >= MAX_HANDSHAKE_TIME) { |
| 101 | + // we encounter no effective connection again, so we disconnect with last used node |
| 102 | + logger.info("Disconnect with {}", cur); |
| 103 | + p.disconnect(ReasonCode.BELOW_THAN_ME); |
| 104 | + } |
| 105 | + }); |
| 106 | + logger.info("Thread is running"); |
| 107 | + return; |
| 108 | + } |
| 109 | + |
| 110 | + List<Node> tableNodes = TronNetService.getP2pService().getConnectableNodes(); |
| 111 | + tableNodes.sort(Comparator.comparingLong(node -> -node.getUpdateTime())); |
| 112 | + Set<InetSocketAddress> usedAddressSet = new HashSet<>(); |
| 113 | + tronNetDelegate.getActivePeer().forEach(p -> usedAddressSet.add(p.getInetSocketAddress())); |
| 114 | + Optional<Node> chosenNode = tableNodes.stream() |
| 115 | + .filter(node -> nodesCache.getIfPresent(node.getPreferInetSocketAddress()) == null) |
| 116 | + .filter(node -> !usedAddressSet.contains(node.getPreferInetSocketAddress())) |
| 117 | + .filter(node -> !TronNetService.getP2pConfig().getActiveNodes() |
| 118 | + .contains(node.getPreferInetSocketAddress())) |
| 119 | + .findFirst(); |
| 120 | + if (!chosenNode.isPresent()) { |
| 121 | + logger.warn("No available node to choose"); |
| 122 | + return; |
| 123 | + } |
| 124 | + |
| 125 | + count.incrementAndGet(); |
| 126 | + nodesCache.put(chosenNode.get().getPreferInetSocketAddress(), true); |
| 127 | + cur = new InetSocketAddress(chosenNode.get().getPreferInetSocketAddress().getAddress(), |
| 128 | + chosenNode.get().getPreferInetSocketAddress().getPort()); |
| 129 | + |
| 130 | + logger.info("Try to get effective connection by using {} at seq {}", cur, count.get()); |
| 131 | + TronNetService.getP2pService().connect(chosenNode.get(), future -> { |
| 132 | + if (future.isCancelled()) { |
| 133 | + // Connection attempt cancelled by user |
| 134 | + cur = null; |
| 135 | + } else if (!future.isSuccess()) { |
| 136 | + // You might get a NullPointerException here because the future might not be completed yet. |
| 137 | + logger.warn("Connect to chosen peer {} fail, cause:{}", cur, future.cause().getMessage()); |
| 138 | + future.channel().close(); |
| 139 | + cur = null; |
| 140 | + triggerNext(); |
| 141 | + } else { |
| 142 | + // Connection established successfully |
| 143 | + } |
| 144 | + }); |
| 145 | + } |
| 146 | + |
| 147 | + private void resetCount() { |
| 148 | + count.set(0); |
| 149 | + } |
| 150 | + |
| 151 | + public void onDisconnect(InetSocketAddress inetSocketAddress) { |
| 152 | + if (inetSocketAddress.equals(cur)) { |
| 153 | + logger.warn("Close chosen peer: {}", cur); |
| 154 | + cur = null; |
| 155 | + triggerNext(); |
| 156 | + } |
| 157 | + } |
| 158 | +} |
0 commit comments