blob: 2d09bcfdf28a848842d8c6b8089233747f94d2a1 [file] [log] [blame]
Jonathan Hart74c83132015-02-02 18:37:57 -08001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2016-present Open Networking Laboratory
Jonathan Hart74c83132015-02-02 18:37:57 -08003 *
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 */
16package org.onosproject.store.intent.impl;
17
18import org.apache.felix.scr.annotations.Activate;
19import org.apache.felix.scr.annotations.Component;
20import org.apache.felix.scr.annotations.Deactivate;
21import org.apache.felix.scr.annotations.Reference;
22import org.apache.felix.scr.annotations.ReferenceCardinality;
23import org.apache.felix.scr.annotations.Service;
24import org.onosproject.cluster.ClusterService;
25import org.onosproject.cluster.Leadership;
26import org.onosproject.cluster.LeadershipEvent;
27import org.onosproject.cluster.LeadershipEventListener;
28import org.onosproject.cluster.LeadershipService;
Brian O'Connor5eb77c82015-03-02 18:09:39 -080029import org.onosproject.cluster.NodeId;
Brian O'Connor69d6ac72015-05-29 16:24:06 -070030import org.onosproject.event.EventDeliveryService;
31import org.onosproject.event.ListenerRegistry;
Madan Jampani1c965102016-01-13 14:34:16 -080032import org.onosproject.net.intent.IntentPartitionEvent;
33import org.onosproject.net.intent.IntentPartitionEventListener;
34import org.onosproject.net.intent.IntentPartitionService;
Thomas Vachuska7a8de842016-03-07 20:56:35 -080035import org.onosproject.net.intent.Key;
Jonathan Hart74c83132015-02-02 18:37:57 -080036import org.slf4j.Logger;
37import org.slf4j.LoggerFactory;
38
Jonathan Hartdc9d7b82015-02-22 17:59:50 -080039import java.util.List;
Brian O'Connor5eb77c82015-03-02 18:09:39 -080040import java.util.Objects;
Jonathan Hartf2fda812015-02-17 15:21:03 -080041import java.util.concurrent.Executors;
42import java.util.concurrent.ScheduledExecutorService;
43import java.util.concurrent.TimeUnit;
Madan Jampani4732c1b2015-05-19 17:11:50 -070044import java.util.concurrent.atomic.AtomicBoolean;
Jonathan Hartdc9d7b82015-02-22 17:59:50 -080045import java.util.stream.Collectors;
Madan Jampania4a59942016-05-02 11:25:34 -070046import java.util.stream.IntStream;
Jonathan Hart74c83132015-02-02 18:37:57 -080047
Jonathan Hart74c83132015-02-02 18:37:57 -080048/**
49 * Manages the assignment of intent keyspace partitions to instances.
50 */
51@Component(immediate = true)
52@Service
Madan Jampani1c965102016-01-13 14:34:16 -080053public class IntentPartitionManager implements IntentPartitionService {
Jonathan Hart74c83132015-02-02 18:37:57 -080054
Madan Jampani1c965102016-01-13 14:34:16 -080055 private static final Logger log = LoggerFactory.getLogger(IntentPartitionManager.class);
Jonathan Hart74c83132015-02-02 18:37:57 -080056
57 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
58 protected LeadershipService leadershipService;
59
60 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
61 protected ClusterService clusterService;
62
Brian O'Connor69d6ac72015-05-29 16:24:06 -070063 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
64 protected EventDeliveryService eventDispatcher;
65
Madan Jampani4732c1b2015-05-19 17:11:50 -070066 protected final AtomicBoolean rebalanceScheduled = new AtomicBoolean(false);
67
Jonathan Hart7061acd2015-03-04 13:15:32 -080068 static final int NUM_PARTITIONS = 14;
Jonathan Hartf2fda812015-02-17 15:21:03 -080069 private static final int BACKOFF_TIME = 2;
Madan Jampani4732c1b2015-05-19 17:11:50 -070070 private static final int CHECK_PARTITION_BALANCE_PERIOD_SEC = 10;
71 private static final int RETRY_AFTER_DELAY_SEC = 5;
Jonathan Hart74c83132015-02-02 18:37:57 -080072
73 private static final String ELECTION_PREFIX = "intent-partition-";
74
Madan Jampania9673fd2016-02-02 13:01:29 -080075 protected NodeId localNodeId;
Madan Jampani1c965102016-01-13 14:34:16 -080076 private ListenerRegistry<IntentPartitionEvent, IntentPartitionEventListener> listenerRegistry;
Jonathan Hart74c83132015-02-02 18:37:57 -080077 private LeadershipEventListener leaderListener = new InternalLeadershipListener();
78
Jonathan Hartf2fda812015-02-17 15:21:03 -080079 private ScheduledExecutorService executor = Executors
80 .newScheduledThreadPool(1);
Jonathan Hart74c83132015-02-02 18:37:57 -080081
82 @Activate
83 public void activate() {
Madan Jampania9673fd2016-02-02 13:01:29 -080084 localNodeId = clusterService.getLocalNode().id();
Jonathan Hart74c83132015-02-02 18:37:57 -080085 leadershipService.addListener(leaderListener);
86
Brian O'Connor69d6ac72015-05-29 16:24:06 -070087 listenerRegistry = new ListenerRegistry<>();
Madan Jampani1c965102016-01-13 14:34:16 -080088 eventDispatcher.addSink(IntentPartitionEvent.class, listenerRegistry);
Brian O'Connor69d6ac72015-05-29 16:24:06 -070089
Jonathan Hart74c83132015-02-02 18:37:57 -080090 for (int i = 0; i < NUM_PARTITIONS; i++) {
Jonathan Hartf2fda812015-02-17 15:21:03 -080091 leadershipService.runForLeadership(getPartitionPath(i));
Madan Jampania9673fd2016-02-02 13:01:29 -080092 log.debug("Registered to run for {}", getPartitionPath(i));
Jonathan Hart74c83132015-02-02 18:37:57 -080093 }
Jonathan Hartf2fda812015-02-17 15:21:03 -080094
Madan Jampani4732c1b2015-05-19 17:11:50 -070095 executor.scheduleAtFixedRate(() -> scheduleRebalance(0), 0,
96 CHECK_PARTITION_BALANCE_PERIOD_SEC, TimeUnit.SECONDS);
Madan Jampania9673fd2016-02-02 13:01:29 -080097 log.info("Started");
Jonathan Hart74c83132015-02-02 18:37:57 -080098 }
99
100 @Deactivate
101 public void deactivate() {
Jonathan Hartac48a952015-02-25 14:11:55 -0800102 executor.shutdownNow();
103
Madan Jampani1c965102016-01-13 14:34:16 -0800104 eventDispatcher.removeSink(IntentPartitionEvent.class);
Jonathan Hart74c83132015-02-02 18:37:57 -0800105 leadershipService.removeListener(leaderListener);
Madan Jampania9673fd2016-02-02 13:01:29 -0800106 log.info("Stopped");
Jonathan Hartf2fda812015-02-17 15:21:03 -0800107 }
108
Jonathan Hart7061acd2015-03-04 13:15:32 -0800109 /**
110 * Sets the specified executor to be used for scheduling background tasks.
111 *
112 * @param executor scheduled executor service for background tasks
113 * @return this PartitionManager
114 */
Sho SHIMIZUb8147732016-01-15 13:13:31 -0800115 IntentPartitionManager withScheduledExecutor(ScheduledExecutorService executor) {
Jonathan Hart7061acd2015-03-04 13:15:32 -0800116 this.executor = executor;
117 return this;
118 }
119
Jonathan Hartf2fda812015-02-17 15:21:03 -0800120 private String getPartitionPath(int i) {
121 return ELECTION_PREFIX + i;
Jonathan Hart74c83132015-02-02 18:37:57 -0800122 }
123
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800124 private String getPartitionPath(PartitionId id) {
125 return getPartitionPath(id.value());
126 }
127
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800128 private PartitionId getPartitionForKey(Key intentKey) {
Brian O'Connor1fdfacd2015-02-18 20:52:06 -0800129 int partition = Math.abs((int) intentKey.hash()) % NUM_PARTITIONS;
130 //TODO investigate Guava consistent hash method
131 // ... does it add significant computational complexity? is it worth it?
132 //int partition = consistentHash(intentKey.hash(), NUM_PARTITIONS);
133 PartitionId id = new PartitionId(partition);
Brian O'Connor1fdfacd2015-02-18 20:52:06 -0800134 return id;
Jonathan Hart74c83132015-02-02 18:37:57 -0800135 }
136
137 @Override
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800138 public boolean isMine(Key intentKey) {
Madan Jampania4a59942016-05-02 11:25:34 -0700139 return Objects.equals(leadershipService.getLeadership(getPartitionPath(getPartitionForKey(intentKey)))
140 .leaderNodeId(),
Madan Jampania9673fd2016-02-02 13:01:29 -0800141 localNodeId);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800142 }
143
144 @Override
145 public NodeId getLeader(Key intentKey) {
146 return leadershipService.getLeader(getPartitionPath(getPartitionForKey(intentKey)));
Jonathan Hart74c83132015-02-02 18:37:57 -0800147 }
148
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700149 @Override
Madan Jampani1c965102016-01-13 14:34:16 -0800150 public void addListener(IntentPartitionEventListener listener) {
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700151 listenerRegistry.addListener(listener);
152 }
153
154 @Override
Madan Jampani1c965102016-01-13 14:34:16 -0800155 public void removeListener(IntentPartitionEventListener listener) {
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700156 listenerRegistry.removeListener(listener);
157 }
158
Sho SHIMIZUb8147732016-01-15 13:13:31 -0800159 void doRebalance() {
Madan Jampani4732c1b2015-05-19 17:11:50 -0700160 rebalanceScheduled.set(false);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800161 try {
Madan Jampani4732c1b2015-05-19 17:11:50 -0700162 rebalance();
Jonathan Hartf2fda812015-02-17 15:21:03 -0800163 } catch (Exception e) {
Madan Jampani4732c1b2015-05-19 17:11:50 -0700164 log.warn("Exception caught during rebalance task. Will retry in " + RETRY_AFTER_DELAY_SEC + " seconds", e);
165 scheduleRebalance(RETRY_AFTER_DELAY_SEC);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800166 }
167 }
168
Jonathan Hartf2fda812015-02-17 15:21:03 -0800169 /**
170 * Determine whether we have more than our fair share of partitions, and if
171 * so, relinquish leadership of some of them for a little while to let
172 * other instances take over.
173 */
Madan Jampani4732c1b2015-05-19 17:11:50 -0700174 private void rebalance() {
Jonathan Hartf2fda812015-02-17 15:21:03 -0800175 int activeNodes = (int) clusterService.getNodes()
176 .stream()
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800177 .filter(node -> clusterService.getState(node.id()).isActive())
Jonathan Hartf2fda812015-02-17 15:21:03 -0800178 .count();
179
180 int myShare = (int) Math.ceil((double) NUM_PARTITIONS / activeNodes);
181
Madan Jampania4d2c722016-06-06 16:39:06 -0700182 // First make sure this node is a candidate for all partitions.
183 IntStream.range(0, NUM_PARTITIONS)
184 .mapToObj(this::getPartitionPath)
185 .map(leadershipService::getLeadership)
186 .filter(leadership -> !leadership.candidates().contains(localNodeId))
187 .map(Leadership::topic)
188 .forEach(leadershipService::runForLeadership);
189
Madan Jampania4a59942016-05-02 11:25:34 -0700190 List<String> myPartitions = IntStream.range(0, NUM_PARTITIONS)
191 .mapToObj(this::getPartitionPath)
192 .map(leadershipService::getLeadership)
193 .filter(Objects::nonNull)
194 .filter(leadership -> localNodeId.equals(leadership.leaderNodeId()))
195 .map(Leadership::topic)
196 .collect(Collectors.toList());
Jonathan Hartf2fda812015-02-17 15:21:03 -0800197
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800198 int relinquish = myPartitions.size() - myShare;
Jonathan Hartf2fda812015-02-17 15:21:03 -0800199
Madan Jampania4d2c722016-06-06 16:39:06 -0700200
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800201 for (int i = 0; i < relinquish; i++) {
Madan Jampania4a59942016-05-02 11:25:34 -0700202 String topic = myPartitions.get(i);
Madan Jampani783d3d22016-06-13 17:40:02 -0700203 // Wait till all active nodes are in contention for partition ownership.
204 // This avoids too many relinquish/reclaim cycles.
205 if (leadershipService.getCandidates(topic).size() == activeNodes) {
206 leadershipService.withdraw(topic);
207 executor.schedule(() -> recontest(topic), BACKOFF_TIME, TimeUnit.SECONDS);
208 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800209 }
210 }
211
Madan Jampani4732c1b2015-05-19 17:11:50 -0700212 private void scheduleRebalance(int afterDelaySec) {
213 if (rebalanceScheduled.compareAndSet(false, true)) {
214 executor.schedule(this::doRebalance, afterDelaySec, TimeUnit.SECONDS);
215 }
216 }
217
Jonathan Hartf2fda812015-02-17 15:21:03 -0800218 /**
219 * Try and recontest for leadership of a partition.
220 *
221 * @param path topic name to recontest
222 */
223 private void recontest(String path) {
224 leadershipService.runForLeadership(path);
225 }
226
Jonathan Hart74c83132015-02-02 18:37:57 -0800227 private final class InternalLeadershipListener implements LeadershipEventListener {
228
229 @Override
230 public void event(LeadershipEvent event) {
231 Leadership leadership = event.subject();
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800232
Madan Jampania9673fd2016-02-02 13:01:29 -0800233 if (Objects.equals(leadership.leaderNodeId(), localNodeId) &&
Jonathan Hart74c83132015-02-02 18:37:57 -0800234 leadership.topic().startsWith(ELECTION_PREFIX)) {
235
Madan Jampani1c965102016-01-13 14:34:16 -0800236 eventDispatcher.post(new IntentPartitionEvent(IntentPartitionEvent.Type.LEADER_CHANGED,
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700237 leadership.topic()));
Jonathan Hart74c83132015-02-02 18:37:57 -0800238 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800239
Madan Jampani620f70d2016-01-30 22:22:47 -0800240 if (event.type() == LeadershipEvent.Type.CANDIDATES_CHANGED) {
241 scheduleRebalance(0);
242 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800243 }
244 }
Jonathan Hart74c83132015-02-02 18:37:57 -0800245}