Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ public class BrokerLiveInfo implements Serializable {
private static final long serialVersionUID = 3612173344946510993L;
private final String brokerName;

private String brokerAddr;
private long heartbeatTimeoutMillis;
private Channel channel;
private long brokerId;
private long lastUpdateTimestamp;
private int epoch;
private long maxOffset;
private long confirmOffset;
private Integer electionPriority;
private volatile String brokerAddr;
private volatile long heartbeatTimeoutMillis;
private volatile Channel channel;
private volatile long brokerId;
private volatile long lastUpdateTimestamp;
private volatile int epoch;
private volatile long maxOffset;
private volatile long confirmOffset;
private volatile Integer electionPriority;

public BrokerLiveInfo(String brokerName, String brokerAddr, long brokerId, long lastUpdateTimestamp,
long heartbeatTimeoutMillis, Channel channel, int epoch, long maxOffset, Integer electionPriority) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,24 @@
package org.apache.rocketmq.controller.impl.heartbeat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.rocketmq.common.ControllerConfig;
import org.apache.rocketmq.common.ThreadFactoryImpl;
import org.apache.rocketmq.common.constant.LoggerName;
Expand All @@ -47,6 +54,8 @@ public class DefaultBrokerHeartbeatManager implements BrokerHeartbeatManager {
private final ControllerConfig controllerConfig;
private final Map<BrokerIdentityInfo/* brokerIdentity*/, BrokerLiveInfo> brokerLiveTable;
private final List<BrokerLifecycleListener> brokerLifecycleListeners;
private final ConcurrentMap<Channel, Object> closingChannels = new ConcurrentHashMap<>();
private final ReadWriteLock channelLifecycleLock = new ReentrantReadWriteLock();

public DefaultBrokerHeartbeatManager(final ControllerConfig controllerConfig) {
this.controllerConfig = controllerConfig;
Expand All @@ -63,6 +72,7 @@ public void start() {
public void shutdown() {
this.scheduledService.shutdown();
this.executor.shutdown();
this.closingChannels.clear();
}

@Override
Expand All @@ -74,27 +84,104 @@ public void initialize() {
public void scanNotActiveBroker() {
try {
log.info("start scanNotActiveBroker");
final Iterator<Map.Entry<BrokerIdentityInfo, BrokerLiveInfo>> iterator = this.brokerLiveTable.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry<BrokerIdentityInfo, BrokerLiveInfo> next = iterator.next();
long last = next.getValue().getLastUpdateTimestamp();
long timeoutMillis = next.getValue().getHeartbeatTimeoutMillis();
if (System.currentTimeMillis() - last > timeoutMillis) {
final Channel channel = next.getValue().getChannel();
iterator.remove();
if (channel != null) {
RemotingHelper.closeChannel(channel);
for (Map.Entry<BrokerIdentityInfo, BrokerLiveInfo> entry : this.brokerLiveTable.entrySet()) {
final BrokerIdentityInfo identity = entry.getKey();
final BrokerLiveInfo info = entry.getValue();
long last = info.getLastUpdateTimestamp();
long timeoutMillis = info.getHeartbeatTimeoutMillis();
if (System.currentTimeMillis() - last <= timeoutMillis) {
continue;
}
final AtomicReference<BrokerLiveInfo> expiredRef = new AtomicReference<>();
final AtomicReference<Channel> expiredChannelRef = new AtomicReference<>();
final AtomicLong expiredTimeoutRef = new AtomicLong();
this.brokerLiveTable.computeIfPresent(identity, (key, current) -> {
long currentLast = current.getLastUpdateTimestamp();
long currentTimeout = current.getHeartbeatTimeoutMillis();
if (System.currentTimeMillis() - currentLast > currentTimeout) {
expiredRef.set(current);
expiredChannelRef.set(current.getChannel());
expiredTimeoutRef.set(currentTimeout);
return null;
}
return current;
});
final BrokerLiveInfo expired = expiredRef.get();
if (expired != null) {
final Channel channel = expiredChannelRef.get();
final String brokerName = expired.getBrokerName();
final long brokerId = expired.getBrokerId();
closeChannelIfUnused(channel);
this.executor.submit(() ->
notifyBrokerInActive(next.getKey().getClusterName(), next.getValue().getBrokerName(), next.getValue().getBrokerId()));
log.warn("The broker channel {} expired, brokerInfo {}, expired {}ms", next.getValue().getChannel(), next.getKey(), timeoutMillis);
notifyBrokerInActive(identity.getClusterName(), brokerName, brokerId));
log.warn("The broker channel {} expired, brokerInfo {}, expired {}ms",
channel, identity, expiredTimeoutRef.get());
}
}
} catch (Exception e) {
log.error("scanNotActiveBroker exception", e);
}
}

private void closeChannelIfUnused(Channel channel) {
if (channel == null || isChannelInUse(channel)) {
return;
}
this.channelLifecycleLock.writeLock().lock();
try {
if (!isChannelInUse(channel)) {
final Object closeToken = new Object();
this.closingChannels.put(channel, closeToken);
final ChannelFuture closeFuture = channel.closeFuture();
if (closeFuture != null) {
closeFuture.addListener(future -> this.closingChannels.remove(channel, closeToken));
}
boolean closeListenerAttached = false;
try {
final ChannelFuture opFuture = closeChannel(channel);
if (opFuture != null) {
closeListenerAttached = true;
opFuture.addListener((ChannelFutureListener) future -> {
if (!future.isSuccess() || closeFuture == null || !channel.isActive()) {
this.closingChannels.remove(channel, closeToken);
}
});
}
} finally {
if (!closeListenerAttached || !channel.isActive()) {
this.closingChannels.remove(channel, closeToken);
}
}
}
} finally {
this.channelLifecycleLock.writeLock().unlock();
}
}

private ChannelFuture closeChannel(Channel channel) {
final String addrRemote = RemotingHelper.parseChannelRemoteAddr(channel);
final ChannelFuture closeFuture = channel.close();
if (closeFuture != null && addrRemote != null && !addrRemote.isEmpty()) {
closeFuture.addListener((ChannelFutureListener) future ->
log.info("closeChannel: close the connection to remote address[{}] result: {}", addrRemote,
future.isSuccess()));
}
return closeFuture;
}

private boolean isChannelInUse(Channel channel) {
for (BrokerLiveInfo liveInfo : this.brokerLiveTable.values()) {
if (liveInfo.getChannel() == channel) {
return true;
}
}
return false;
}

private boolean isChannelClosingOrInactive(Channel channel) {
return this.closingChannels.containsKey(channel) || !channel.isActive();
}

private void notifyBrokerInActive(String clusterName, String brokerName, Long brokerId) {
for (BrokerLifecycleListener listener : this.brokerLifecycleListeners) {
listener.onBrokerInactive(clusterName, brokerName, brokerId);
Expand All @@ -111,55 +198,98 @@ public void onBrokerHeartbeat(String clusterName, String brokerName, String brok
Long timeoutMillis, Channel channel, Integer epoch, Long maxOffset, Long confirmOffset,
Integer electionPriority) {
BrokerIdentityInfo brokerIdentityInfo = new BrokerIdentityInfo(clusterName, brokerName, brokerId);
BrokerLiveInfo prev = this.brokerLiveTable.get(brokerIdentityInfo);
int realEpoch = Optional.ofNullable(epoch).orElse(-1);
long realBrokerId = Optional.ofNullable(brokerId).orElse(-1L);
long realMaxOffset = Optional.ofNullable(maxOffset).orElse(-1L);
long realConfirmOffset = Optional.ofNullable(confirmOffset).orElse(-1L);
long realTimeoutMillis = Optional.ofNullable(timeoutMillis).orElse(DEFAULT_BROKER_CHANNEL_EXPIRED_TIME);
int realElectionPriority = Optional.ofNullable(electionPriority).orElse(Integer.MAX_VALUE);
if (null == prev) {
this.brokerLiveTable.put(brokerIdentityInfo,
new BrokerLiveInfo(brokerName,
brokerAddr,
realBrokerId,
System.currentTimeMillis(),
realTimeoutMillis,
channel,
realEpoch,
realMaxOffset,
realElectionPriority));
log.info("new broker registered, {}, brokerId:{}", brokerIdentityInfo, realBrokerId);
} else {
prev.setLastUpdateTimestamp(System.currentTimeMillis());
prev.setHeartbeatTimeoutMillis(realTimeoutMillis);
prev.setElectionPriority(realElectionPriority);
if (realEpoch > prev.getEpoch() || realEpoch == prev.getEpoch() && realMaxOffset > prev.getMaxOffset()) {
prev.setEpoch(realEpoch);
prev.setMaxOffset(realMaxOffset);
prev.setConfirmOffset(realConfirmOffset);
final AtomicBoolean acceptedChannel = new AtomicBoolean(false);
if (channel != null) {
this.channelLifecycleLock.readLock().lock();
}
try {
// Serialize creation, timestamp refresh, and channel rebinding per broker identity, while
// rejecting already-closed or expiry-condemned channels so late heartbeats cannot resurrect
// or rebind stale connections. Holding readLock coordinates non-blocking heartbeats with
// writeLock in closeChannelIfUnused() so a shared BrokerContainer channel cannot be closed
// concurrently with a sibling broker rebinding onto it.
this.brokerLiveTable.compute(brokerIdentityInfo, (key, prev) -> {
if (channel != null && isChannelClosingOrInactive(channel)) {
log.warn("Ignore heartbeat from inactive channel {}, brokerInfo:{}", channel, brokerIdentityInfo);
return prev;
}
if (channel != null) {
acceptedChannel.set(true);
}
long now = System.currentTimeMillis();
if (prev == null) {
log.info("new broker registered, {}, brokerId:{}", brokerIdentityInfo, realBrokerId);
return new BrokerLiveInfo(brokerName,
brokerAddr,
realBrokerId,
now,
realTimeoutMillis,
channel,
realEpoch,
realMaxOffset,
realElectionPriority);
}
prev.setLastUpdateTimestamp(now);
prev.setHeartbeatTimeoutMillis(realTimeoutMillis);
prev.setElectionPriority(realElectionPriority);
if (channel != null && channel != prev.getChannel()) {
prev.setChannel(channel);
}
if (realEpoch > prev.getEpoch() || realEpoch == prev.getEpoch() && realMaxOffset > prev.getMaxOffset()) {
prev.setEpoch(realEpoch);
prev.setMaxOffset(realMaxOffset);
prev.setConfirmOffset(realConfirmOffset);
}
return prev;
});
} finally {
if (channel != null) {
this.channelLifecycleLock.readLock().unlock();
}
}

if (acceptedChannel.get() && isChannelClosingOrInactive(channel)) {
evictBrokerIfChannelMatches(brokerIdentityInfo, channel);
}
}

@Override
public void onBrokerChannelClose(Channel channel) {
BrokerIdentityInfo addrInfo = null;
for (Map.Entry<BrokerIdentityInfo, BrokerLiveInfo> entry : this.brokerLiveTable.entrySet()) {
if (entry.getValue().getChannel() == channel) {
log.info("Channel {} inactive, broker {}, addr:{}, id:{}", entry.getValue().getChannel(), entry.getValue().getBrokerName(), entry.getValue().getBrokerAddr(), entry.getValue().getBrokerId());
addrInfo = entry.getKey();
this.executor.submit(() ->
notifyBrokerInActive(entry.getKey().getClusterName(), entry.getValue().getBrokerName(), entry.getValue().getBrokerId()));
break;
}
if (channel == null) {
return;
}
if (addrInfo != null) {
this.brokerLiveTable.remove(addrInfo);
for (BrokerIdentityInfo brokerIdentity : this.brokerLiveTable.keySet()) {
evictBrokerIfChannelMatches(brokerIdentity, channel);
}
}

private boolean evictBrokerIfChannelMatches(BrokerIdentityInfo brokerIdentity, Channel channel) {
final AtomicReference<BrokerLiveInfo> closedRef = new AtomicReference<>();
this.brokerLiveTable.computeIfPresent(brokerIdentity, (key, live) -> {
if (live.getChannel() != channel) {
return live;
}
closedRef.set(live);
return null;
});
final BrokerLiveInfo closed = closedRef.get();
if (closed != null) {
final String brokerName = closed.getBrokerName();
final String brokerAddr = closed.getBrokerAddr();
final long brokerId = closed.getBrokerId();
log.info("Channel {} inactive, broker {}, addr:{}, id:{}", channel, brokerName, brokerAddr, brokerId);
this.executor.submit(() -> notifyBrokerInActive(brokerIdentity.getClusterName(),
brokerName, brokerId));
return true;
}
return false;
}

@Override
public BrokerLiveInfo getBrokerLiveInfo(String clusterName, String brokerName, Long brokerId) {
return this.brokerLiveTable.get(new BrokerIdentityInfo(clusterName, brokerName, brokerId));
Expand Down
Loading
Loading