blob: dbdbabeef7a199af877657c9b43f4221453bafe4 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.store.cluster.impl;
tom2d7c65f2014-09-23 01:09:35 -070017
Jonathan Hart4a4d18f2015-03-26 12:16:16 -070018import com.google.common.collect.ImmutableSet;
19import com.google.common.collect.Maps;
Madan Jampanie3375062016-04-19 16:32:10 -070020
tom2d7c65f2014-09-23 01:09:35 -070021import org.apache.felix.scr.annotations.Activate;
22import org.apache.felix.scr.annotations.Component;
23import org.apache.felix.scr.annotations.Deactivate;
sangyun-hanf98df542016-03-24 20:28:03 +090024import org.apache.felix.scr.annotations.Modified;
25import org.apache.felix.scr.annotations.Property;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070026import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
Deepa Vaddireddy6690f592017-03-12 03:31:48 +053028import org.apache.felix.scr.annotations.ReferencePolicy;
tom2d7c65f2014-09-23 01:09:35 -070029import org.apache.felix.scr.annotations.Service;
Ayaka Koshibedd91b842015-03-02 14:48:47 -080030import org.onlab.packet.IpAddress;
31import org.onlab.util.KryoNamespace;
Deepa Vaddireddy6690f592017-03-12 03:31:48 +053032import org.onosproject.cfg.ConfigProperty;
sangyun-han9f0af2d2016-08-04 13:04:59 +090033import org.onosproject.cfg.ComponentConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.cluster.ClusterEvent;
Madan Jampaniec1df022015-10-13 21:23:03 -070035import org.onosproject.cluster.ClusterMetadataService;
Brian O'Connorabafb502014-12-02 22:26:20 -080036import org.onosproject.cluster.ClusterStore;
37import org.onosproject.cluster.ClusterStoreDelegate;
38import org.onosproject.cluster.ControllerNode;
Ayaka Koshibedd91b842015-03-02 14:48:47 -080039import org.onosproject.cluster.ControllerNode.State;
Jonathan Hart4a4d18f2015-03-26 12:16:16 -070040import org.onosproject.cluster.DefaultControllerNode;
Brian O'Connorabafb502014-12-02 22:26:20 -080041import org.onosproject.cluster.NodeId;
Jordan Haltermanf70bf462017-07-29 13:12:00 -070042import org.onosproject.core.Version;
43import org.onosproject.core.VersionService;
Ayaka Koshibedd91b842015-03-02 14:48:47 -080044import org.onosproject.store.AbstractStore;
Madan Jampanic26eede2015-04-16 11:42:16 -070045import org.onosproject.store.cluster.messaging.Endpoint;
Madan Jampaniafeebbd2015-05-19 15:26:01 -070046import org.onosproject.store.cluster.messaging.MessagingService;
Ayaka Koshibedd91b842015-03-02 14:48:47 -080047import org.onosproject.store.serializers.KryoNamespaces;
Jordan Halterman2c83a102017-08-20 17:11:41 -070048import org.onosproject.store.service.Serializer;
sangyun-hanf98df542016-03-24 20:28:03 +090049import org.osgi.service.component.ComponentContext;
Ayaka Koshibedd91b842015-03-02 14:48:47 -080050import org.slf4j.Logger;
tom2d7c65f2014-09-23 01:09:35 -070051
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070052import java.time.Instant;
Jonathan Hart4a4d18f2015-03-26 12:16:16 -070053import java.util.Map;
Thomas Vachuskafba7f3d2016-03-23 15:46:25 -070054import java.util.Objects;
Jonathan Hart4a4d18f2015-03-26 12:16:16 -070055import java.util.Set;
56import java.util.concurrent.ExecutorService;
57import java.util.concurrent.Executors;
58import java.util.concurrent.ScheduledExecutorService;
59import java.util.concurrent.TimeUnit;
Madan Jampanid36def02016-01-13 11:21:56 -080060import java.util.function.BiConsumer;
Jonathan Hart4a4d18f2015-03-26 12:16:16 -070061import java.util.stream.Collectors;
62
Jordan Haltermanf70bf462017-07-29 13:12:00 -070063import static com.google.common.base.MoreObjects.firstNonNull;
sangyun-hanf98df542016-03-24 20:28:03 +090064import static com.google.common.base.Preconditions.checkArgument;
Jonathan Hart4a4d18f2015-03-26 12:16:16 -070065import static com.google.common.base.Preconditions.checkNotNull;
Deepa Vaddireddy6690f592017-03-12 03:31:48 +053066import static com.google.common.base.Strings.isNullOrEmpty;
Jonathan Hart4a4d18f2015-03-26 12:16:16 -070067import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuskafba7f3d2016-03-23 15:46:25 -070068import static org.onosproject.cluster.ClusterEvent.Type.INSTANCE_ACTIVATED;
69import static org.onosproject.cluster.ClusterEvent.Type.INSTANCE_DEACTIVATED;
70import static org.onosproject.cluster.ClusterEvent.Type.INSTANCE_READY;
Jonathan Hart4a4d18f2015-03-26 12:16:16 -070071import static org.slf4j.LoggerFactory.getLogger;
tom2d7c65f2014-09-23 01:09:35 -070072
tom2d7c65f2014-09-23 01:09:35 -070073@Component(immediate = true)
74@Service
Ayaka Koshibedd91b842015-03-02 14:48:47 -080075/**
76 * Distributed cluster nodes store that employs an accrual failure
77 * detector to identify cluster member up/down status.
78 */
tom0755a362014-09-24 11:54:43 -070079public class DistributedClusterStore
Ayaka Koshibedd91b842015-03-02 14:48:47 -080080 extends AbstractStore<ClusterEvent, ClusterStoreDelegate>
tomb41d1ac2014-09-24 01:51:24 -070081 implements ClusterStore {
tom2d7c65f2014-09-23 01:09:35 -070082
Thomas Vachuska8dc1a692015-03-31 01:01:37 -070083 private static final Logger log = getLogger(DistributedClusterStore.class);
tom2d7c65f2014-09-23 01:09:35 -070084
Thomas Vachuskade563cf2015-04-01 00:28:50 -070085 public static final String HEARTBEAT_MESSAGE = "onos-cluster-heartbeat";
86
sangyun-hanf98df542016-03-24 20:28:03 +090087 private static final int DEFAULT_HEARTBEAT_INTERVAL = 100;
88 @Property(name = "heartbeatInterval", intValue = DEFAULT_HEARTBEAT_INTERVAL,
89 label = "Interval time to send heartbeat to other controller nodes (millisecond)")
90 private int heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL;
91
92 private static final int DEFAULT_PHI_FAILURE_THRESHOLD = 10;
93 @Property(name = "phiFailureThreshold", intValue = DEFAULT_PHI_FAILURE_THRESHOLD,
94 label = "the value of Phi threshold to detect accrual failure")
95 private int phiFailureThreshold = DEFAULT_PHI_FAILURE_THRESHOLD;
tom2d7c65f2014-09-23 01:09:35 -070096
Jordan Haltermanb75aa082018-05-14 15:00:42 -070097 private static final long DEFAULT_MIN_STANDARD_DEVIATION_MILLIS = 50;
98 @Property(name = "minStandardDeviationMillis", longValue = DEFAULT_MIN_STANDARD_DEVIATION_MILLIS,
99 label = "The minimum standard deviation to take into account when computing the Phi value")
100 private long minStandardDeviationMillis = DEFAULT_MIN_STANDARD_DEVIATION_MILLIS;
101
Jordan Halterman2c83a102017-08-20 17:11:41 -0700102 private static final Serializer SERIALIZER = Serializer.using(
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700103 KryoNamespace.newBuilder()
Thomas Vachuska8dc1a692015-03-31 01:01:37 -0700104 .register(KryoNamespaces.API)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700105 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
Thomas Vachuska8dc1a692015-03-31 01:01:37 -0700106 .register(HeartbeatMessage.class)
HIGUCHI Yutae7290652016-05-18 11:29:01 -0700107 .build("ClusterStore"));
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800108
109 private static final String INSTANCE_ID_NULL = "Instance ID cannot be null";
110
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800111 private final Map<NodeId, ControllerNode> allNodes = Maps.newConcurrentMap();
112 private final Map<NodeId, State> nodeStates = Maps.newConcurrentMap();
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700113 private final Map<NodeId, Version> nodeVersions = Maps.newConcurrentMap();
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700114 private final Map<NodeId, Instant> nodeLastUpdatedTimes = Maps.newConcurrentMap();
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800115
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800116 private ScheduledExecutorService heartBeatSender = Executors.newSingleThreadScheduledExecutor(
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700117 groupedThreads("onos/cluster/membership", "heartbeat-sender", log));
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800118 private ExecutorService heartBeatMessageHandler = Executors.newSingleThreadExecutor(
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700119 groupedThreads("onos/cluster/membership", "heartbeat-receiver", log));
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800120
121 private PhiAccrualFailureDetector failureDetector;
122
123 private ControllerNode localNode;
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700124 private Version localVersion;
125
126 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
127 protected VersionService versionService;
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800128
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Madan Jampaniec1df022015-10-13 21:23:03 -0700130 protected ClusterMetadataService clusterMetadataService;
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700131
132 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
133 protected MessagingService messagingService;
134
Thomas Vachuska1ca7e9f2016-08-05 10:21:41 -0700135 // This must be optional to avoid a cyclic dependency
Deepa Vaddireddy6690f592017-03-12 03:31:48 +0530136 @Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY,
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700137 bind = "bindComponentConfigService",
138 unbind = "unbindComponentConfigService",
139 policy = ReferencePolicy.DYNAMIC)
sangyun-han9f0af2d2016-08-04 13:04:59 +0900140 protected ComponentConfigService cfgService;
141
Thomas Vachuska1ca7e9f2016-08-05 10:21:41 -0700142 /**
143 * Hook for wiring up optional reference to a service.
144 *
145 * @param service service being announced
146 */
147 protected void bindComponentConfigService(ComponentConfigService service) {
148 if (cfgService == null) {
149 cfgService = service;
150 cfgService.registerProperties(getClass());
Deepa Vaddireddy6690f592017-03-12 03:31:48 +0530151 readComponentConfiguration();
Thomas Vachuska1ca7e9f2016-08-05 10:21:41 -0700152 }
153 }
154
155 /**
156 * Hook for unwiring optional reference to a service.
157 *
158 * @param service service being withdrawn
159 */
160 protected void unbindComponentConfigService(ComponentConfigService service) {
161 if (cfgService == service) {
162 cfgService.unregisterProperties(getClass(), false);
163 cfgService = null;
164 }
165 }
166
tom2d7c65f2014-09-23 01:09:35 -0700167 @Activate
Thomas Vachuska1ca7e9f2016-08-05 10:21:41 -0700168 public void activate() {
Madan Jampaniec1df022015-10-13 21:23:03 -0700169 localNode = clusterMetadataService.getLocalNode();
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700170 localVersion = versionService.version();
171 nodeVersions.put(localNode.id(), localVersion);
Thomas Vachuska8dc1a692015-03-31 01:01:37 -0700172
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800173 messagingService.registerHandler(HEARTBEAT_MESSAGE,
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700174 new HeartbeatMessageHandler(), heartBeatMessageHandler);
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800175
Jordan Haltermanb75aa082018-05-14 15:00:42 -0700176 failureDetector = new PhiAccrualFailureDetector(minStandardDeviationMillis);
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800177
178 heartBeatSender.scheduleWithFixedDelay(this::heartbeat, 0,
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700179 heartbeatInterval, TimeUnit.MILLISECONDS);
tomb41d1ac2014-09-24 01:51:24 -0700180
181 log.info("Started");
182 }
183
tom2d7c65f2014-09-23 01:09:35 -0700184 @Deactivate
185 public void deactivate() {
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700186 messagingService.unregisterHandler(HEARTBEAT_MESSAGE);
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800187 heartBeatSender.shutdownNow();
188 heartBeatMessageHandler.shutdownNow();
189
tom2d7c65f2014-09-23 01:09:35 -0700190 log.info("Stopped");
191 }
192
sangyun-hanf98df542016-03-24 20:28:03 +0900193 @Modified
194 public void modified(ComponentContext context) {
Deepa Vaddireddy6690f592017-03-12 03:31:48 +0530195 readComponentConfiguration();
sangyun-hanf98df542016-03-24 20:28:03 +0900196 }
197
tom2d7c65f2014-09-23 01:09:35 -0700198 @Override
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800199 public void setDelegate(ClusterStoreDelegate delegate) {
200 checkNotNull(delegate, "Delegate cannot be null");
201 this.delegate = delegate;
202 }
203
204 @Override
205 public void unsetDelegate(ClusterStoreDelegate delegate) {
206 this.delegate = null;
207 }
208
209 @Override
210 public boolean hasDelegate() {
211 return this.delegate != null;
212 }
213
214 @Override
tom2d7c65f2014-09-23 01:09:35 -0700215 public ControllerNode getLocalNode() {
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800216 return localNode;
tom2d7c65f2014-09-23 01:09:35 -0700217 }
218
219 @Override
220 public Set<ControllerNode> getNodes() {
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800221 return ImmutableSet.copyOf(allNodes.values());
tom2d7c65f2014-09-23 01:09:35 -0700222 }
223
224 @Override
225 public ControllerNode getNode(NodeId nodeId) {
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800226 checkNotNull(nodeId, INSTANCE_ID_NULL);
227 return allNodes.get(nodeId);
tom2d7c65f2014-09-23 01:09:35 -0700228 }
229
230 @Override
tomb41d1ac2014-09-24 01:51:24 -0700231 public State getState(NodeId nodeId) {
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800232 checkNotNull(nodeId, INSTANCE_ID_NULL);
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700233 return firstNonNull(nodeStates.get(nodeId), State.INACTIVE);
234 }
235
236 @Override
237 public Version getVersion(NodeId nodeId) {
238 checkNotNull(nodeId, INSTANCE_ID_NULL);
239 return nodeVersions.get(nodeId);
tomb41d1ac2014-09-24 01:51:24 -0700240 }
241
242 @Override
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800243 public void markFullyStarted(boolean started) {
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700244 updateNode(localNode.id(), started ? State.READY : State.ACTIVE, null);
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800245 }
246
247 @Override
Pavlin Radoslavov444b5192014-10-28 10:45:19 -0700248 public ControllerNode addNode(NodeId nodeId, IpAddress ip, int tcpPort) {
sangyun-hanf98df542016-03-24 20:28:03 +0900249 checkNotNull(nodeId, INSTANCE_ID_NULL);
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800250 ControllerNode node = new DefaultControllerNode(nodeId, ip, tcpPort);
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700251 addNode(node);
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800252 return node;
tomee49c372014-09-26 15:14:50 -0700253 }
254
255 @Override
tomb41d1ac2014-09-24 01:51:24 -0700256 public void removeNode(NodeId nodeId) {
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800257 checkNotNull(nodeId, INSTANCE_ID_NULL);
258 ControllerNode node = allNodes.remove(nodeId);
259 if (node != null) {
260 nodeStates.remove(nodeId);
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700261 nodeVersions.remove(nodeId);
Jonathan Hartf1141262015-04-23 11:27:07 -0700262 notifyDelegate(new ClusterEvent(ClusterEvent.Type.INSTANCE_REMOVED, node));
tomb41d1ac2014-09-24 01:51:24 -0700263 }
264 }
265
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700266 private void addNode(ControllerNode node) {
267 allNodes.put(node.id(), node);
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700268 updateNode(node.id(), node.equals(localNode) ? State.ACTIVE : State.INACTIVE, null);
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700269 notifyDelegate(new ClusterEvent(ClusterEvent.Type.INSTANCE_ADDED, node));
Thomas Vachuskade563cf2015-04-01 00:28:50 -0700270 }
271
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700272 private void updateNode(NodeId nodeId, State newState, Version newVersion) {
Thomas Vachuskafba7f3d2016-03-23 15:46:25 -0700273 State currentState = nodeStates.get(nodeId);
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700274 Version currentVersion = nodeVersions.get(nodeId);
Jordan Haltermaneabae962017-08-01 17:29:36 -0700275 if (!Objects.equals(currentState, newState)
276 || (newVersion != null && !Objects.equals(currentVersion, newVersion))) {
Thomas Vachuskafba7f3d2016-03-23 15:46:25 -0700277 nodeStates.put(nodeId, newState);
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700278 if (newVersion != null) {
279 nodeVersions.put(nodeId, newVersion);
280 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700281 nodeLastUpdatedTimes.put(nodeId, Instant.now());
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700282 notifyChange(nodeId, currentState, newState, currentVersion, newVersion);
Thomas Vachuskafba7f3d2016-03-23 15:46:25 -0700283 }
Madan Jampani7d2fab22015-03-18 17:21:57 -0700284 }
285
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800286 private void heartbeat() {
287 try {
288 Set<ControllerNode> peers = allNodes.values()
289 .stream()
290 .filter(node -> !(node.id().equals(localNode.id())))
291 .collect(Collectors.toSet());
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800292 State state = nodeStates.get(localNode.id());
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700293 byte[] hbMessagePayload = SERIALIZER.encode(new HeartbeatMessage(localNode, state, localVersion));
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800294 peers.forEach((node) -> {
295 heartbeatToPeer(hbMessagePayload, node);
296 State currentState = nodeStates.get(node.id());
297 double phi = failureDetector.phi(node.id());
sangyun-hanf98df542016-03-24 20:28:03 +0900298 if (phi >= phiFailureThreshold) {
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800299 if (currentState.isActive()) {
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700300 updateNode(node.id(), State.INACTIVE, null);
Jordan Haltermane7062532018-01-22 11:22:46 -0800301 failureDetector.reset(node.id());
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800302 }
303 } else {
304 if (currentState == State.INACTIVE) {
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700305 updateNode(node.id(), State.ACTIVE, null);
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800306 }
307 }
308 });
309 } catch (Exception e) {
310 log.debug("Failed to send heartbeat", e);
311 }
tomb41d1ac2014-09-24 01:51:24 -0700312 }
313
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700314 private void notifyChange(NodeId nodeId, State oldState, State newState, Version oldVersion, Version newVersion) {
315 if (oldState != newState || !Objects.equals(oldVersion, newVersion)) {
Thomas Vachuskafba7f3d2016-03-23 15:46:25 -0700316 ControllerNode node = allNodes.get(nodeId);
Jon Hall1f13d642016-05-13 17:53:01 -0700317 // Either this node or that node is no longer part of the same cluster
318 if (node == null) {
Jon Hall66870baa2016-06-20 12:12:10 -0700319 log.debug("Could not find node {} in the cluster, ignoring state change", nodeId);
Jon Hall1f13d642016-05-13 17:53:01 -0700320 return;
321 }
Thomas Vachuskafba7f3d2016-03-23 15:46:25 -0700322 ClusterEvent.Type type = newState == State.READY ? INSTANCE_READY :
323 newState == State.ACTIVE ? INSTANCE_ACTIVATED :
324 INSTANCE_DEACTIVATED;
325 notifyDelegate(new ClusterEvent(type, node));
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800326 }
tomb41d1ac2014-09-24 01:51:24 -0700327 }
328
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800329 private void heartbeatToPeer(byte[] messagePayload, ControllerNode peer) {
Madan Jampaniafeebbd2015-05-19 15:26:01 -0700330 Endpoint remoteEp = new Endpoint(peer.ip(), peer.tcpPort());
Madan Jampani175e8fd2015-05-20 14:10:45 -0700331 messagingService.sendAsync(remoteEp, HEARTBEAT_MESSAGE, messagePayload).whenComplete((result, error) -> {
332 if (error != null) {
333 log.trace("Sending heartbeat to {} failed", remoteEp, error);
334 }
335 });
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800336 }
337
Madan Jampanid36def02016-01-13 11:21:56 -0800338 private class HeartbeatMessageHandler implements BiConsumer<Endpoint, byte[]> {
tomb41d1ac2014-09-24 01:51:24 -0700339 @Override
Madan Jampanid36def02016-01-13 11:21:56 -0800340 public void accept(Endpoint sender, byte[] message) {
Madan Jampanic26eede2015-04-16 11:42:16 -0700341 HeartbeatMessage hb = SERIALIZER.decode(message);
Madan Jampanie3375062016-04-19 16:32:10 -0700342 if (clusterMetadataService.getClusterMetadata().getNodes().contains(hb.source())) {
Jordan Haltermane7062532018-01-22 11:22:46 -0800343 // Avoid reporting heartbeats that have been enqueued by setting a minimum interval.
344 long heartbeatTime = System.currentTimeMillis();
Jordan Haltermana8993622018-07-29 00:22:37 -0700345 Long lastHeartbeatTime = failureDetector.getLastHeartbeatTime(hb.source().id());
346 if (lastHeartbeatTime == null || heartbeatTime - lastHeartbeatTime > heartbeatInterval / 2) {
Jordan Haltermane7062532018-01-22 11:22:46 -0800347 failureDetector.report(hb.source().id(), heartbeatTime);
Jordan Halterman1315d3e2018-01-16 19:41:31 -0800348 }
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700349 updateNode(hb.source().id(), hb.state, hb.version);
Madan Jampanie3375062016-04-19 16:32:10 -0700350 }
tomb41d1ac2014-09-24 01:51:24 -0700351 }
tom2d7c65f2014-09-23 01:09:35 -0700352 }
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800353
354 private static class HeartbeatMessage {
355 private ControllerNode source;
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800356 private State state;
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700357 private Version version;
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800358
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700359 public HeartbeatMessage(ControllerNode source, State state, Version version) {
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800360 this.source = source;
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800361 this.state = state != null ? state : State.ACTIVE;
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700362 this.version = version;
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800363 }
364
365 public ControllerNode source() {
366 return source;
367 }
Ayaka Koshibedd91b842015-03-02 14:48:47 -0800368 }
369
Madan Jampani7d2fab22015-03-18 17:21:57 -0700370 @Override
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700371 public Instant getLastUpdatedInstant(NodeId nodeId) {
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700372 return nodeLastUpdatedTimes.get(nodeId);
Madan Jampani7d2fab22015-03-18 17:21:57 -0700373 }
Thomas Vachuskade563cf2015-04-01 00:28:50 -0700374
sangyun-hanf98df542016-03-24 20:28:03 +0900375 /**
Deepa Vaddireddy6690f592017-03-12 03:31:48 +0530376 * Extracts properties from the component configuration.
sangyun-hanf98df542016-03-24 20:28:03 +0900377 *
sangyun-hanf98df542016-03-24 20:28:03 +0900378 */
Deepa Vaddireddy6690f592017-03-12 03:31:48 +0530379 private void readComponentConfiguration() {
380 Set<ConfigProperty> configProperties = cfgService.getProperties(getClass().getName());
381 for (ConfigProperty property : configProperties) {
Jon Halla3fcf672017-03-28 16:53:22 -0700382 if ("heartbeatInterval".equals(property.name())) {
Deepa Vaddireddy6690f592017-03-12 03:31:48 +0530383 String s = property.value();
384 if (s == null) {
385 setHeartbeatInterval(DEFAULT_HEARTBEAT_INTERVAL);
386 log.info("Heartbeat interval time is not configured, default value is {}",
387 DEFAULT_HEARTBEAT_INTERVAL);
388 } else {
389 int newHeartbeatInterval = isNullOrEmpty(s) ? DEFAULT_HEARTBEAT_INTERVAL
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700390 : Integer.parseInt(s.trim());
Deepa Vaddireddy6690f592017-03-12 03:31:48 +0530391 if (newHeartbeatInterval > 0 && heartbeatInterval != newHeartbeatInterval) {
392 heartbeatInterval = newHeartbeatInterval;
393 restartHeartbeatSender();
394 }
395 log.info("Configured. Heartbeat interval time is configured to {}",
396 heartbeatInterval);
397 }
398 }
Jon Halla3fcf672017-03-28 16:53:22 -0700399 if ("phiFailureThreshold".equals(property.name())) {
Deepa Vaddireddy6690f592017-03-12 03:31:48 +0530400 String s = property.value();
401 if (s == null) {
402 setPhiFailureThreshold(DEFAULT_PHI_FAILURE_THRESHOLD);
403 log.info("Phi failure threshold is not configured, default value is {}",
404 DEFAULT_PHI_FAILURE_THRESHOLD);
405 } else {
406 int newPhiFailureThreshold = isNullOrEmpty(s) ? DEFAULT_HEARTBEAT_INTERVAL
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700407 : Integer.parseInt(s.trim());
Deepa Vaddireddy6690f592017-03-12 03:31:48 +0530408 setPhiFailureThreshold(newPhiFailureThreshold);
409 log.info("Configured. Phi failure threshold is configured to {}",
410 phiFailureThreshold);
411 }
412 }
Jordan Haltermanb75aa082018-05-14 15:00:42 -0700413 if ("minStandardDeviationMillis".equals(property.name())) {
414 String s = property.value();
415 if (s == null) {
416 setMinStandardDeviationMillis(DEFAULT_MIN_STANDARD_DEVIATION_MILLIS);
417 log.info("Minimum standard deviation is not configured, default value is {}",
418 DEFAULT_MIN_STANDARD_DEVIATION_MILLIS);
419 } else {
420 long newMinStandardDeviationMillis = isNullOrEmpty(s)
421 ? DEFAULT_MIN_STANDARD_DEVIATION_MILLIS
422 : Long.parseLong(s.trim());
423 setMinStandardDeviationMillis(newMinStandardDeviationMillis);
424 log.info("Configured. Minimum standard deviation is configured to {}",
425 newMinStandardDeviationMillis);
426 }
427 }
sangyun-hanf98df542016-03-24 20:28:03 +0900428 }
429 }
430
431 /**
432 * Sets heartbeat interval between the termination of one execution of heartbeat
433 * and the commencement of the next.
434 *
435 * @param interval term between each heartbeat
436 */
437 private void setHeartbeatInterval(int interval) {
438 try {
439 checkArgument(interval > 0, "Interval must be greater than zero");
440 heartbeatInterval = interval;
441 } catch (IllegalArgumentException e) {
442 log.warn(e.getMessage());
443 heartbeatInterval = DEFAULT_HEARTBEAT_INTERVAL;
444 }
445 }
446
447 /**
448 * Sets Phi failure threshold.
449 * Phi is based on a paper titled: "The φ Accrual Failure Detector" by Hayashibara, et al.
450 *
451 * @param threshold
452 */
453 private void setPhiFailureThreshold(int threshold) {
454 phiFailureThreshold = threshold;
455 }
456
457 /**
Jordan Haltermanb75aa082018-05-14 15:00:42 -0700458 * Sets the minimum standard deviation milliseconds.
459 *
460 * @param minStandardDeviationMillis the updated minimum standard deviation
461 */
462 private void setMinStandardDeviationMillis(long minStandardDeviationMillis) {
463 this.minStandardDeviationMillis = minStandardDeviationMillis;
464 try {
465 failureDetector = new PhiAccrualFailureDetector(minStandardDeviationMillis);
466 } catch (IllegalArgumentException e) {
467 log.warn(e.getMessage());
468 this.minStandardDeviationMillis = DEFAULT_MIN_STANDARD_DEVIATION_MILLIS;
469 failureDetector = new PhiAccrualFailureDetector(this.minStandardDeviationMillis);
470 }
471 }
472
473 /**
sangyun-hanf98df542016-03-24 20:28:03 +0900474 * Restarts heartbeatSender executor.
sangyun-hanf98df542016-03-24 20:28:03 +0900475 */
476 private void restartHeartbeatSender() {
477 try {
478 ScheduledExecutorService prevSender = heartBeatSender;
479 heartBeatSender = Executors.newSingleThreadScheduledExecutor(
HIGUCHI Yutad9e01052016-04-14 09:31:42 -0700480 groupedThreads("onos/cluster/membership", "heartbeat-sender-%d", log));
sangyun-hanf98df542016-03-24 20:28:03 +0900481 heartBeatSender.scheduleWithFixedDelay(this::heartbeat, 0,
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700482 heartbeatInterval, TimeUnit.MILLISECONDS);
sangyun-hanf98df542016-03-24 20:28:03 +0900483 prevSender.shutdown();
484 } catch (Exception e) {
485 log.warn(e.getMessage());
486 }
487 }
Jordan Haltermanf70bf462017-07-29 13:12:00 -0700488}