blob: 1db6534979d410b08e3ceb9c25e37306d7ae0575 [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;
Jonathan Hart74c83132015-02-02 18:37:57 -080046
Jonathan Hart74c83132015-02-02 18:37:57 -080047/**
48 * Manages the assignment of intent keyspace partitions to instances.
49 */
50@Component(immediate = true)
51@Service
Madan Jampani1c965102016-01-13 14:34:16 -080052public class IntentPartitionManager implements IntentPartitionService {
Jonathan Hart74c83132015-02-02 18:37:57 -080053
Madan Jampani1c965102016-01-13 14:34:16 -080054 private static final Logger log = LoggerFactory.getLogger(IntentPartitionManager.class);
Jonathan Hart74c83132015-02-02 18:37:57 -080055
56 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
57 protected LeadershipService leadershipService;
58
59 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
60 protected ClusterService clusterService;
61
Brian O'Connor69d6ac72015-05-29 16:24:06 -070062 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
63 protected EventDeliveryService eventDispatcher;
64
Madan Jampani4732c1b2015-05-19 17:11:50 -070065 protected final AtomicBoolean rebalanceScheduled = new AtomicBoolean(false);
66
Jonathan Hart7061acd2015-03-04 13:15:32 -080067 static final int NUM_PARTITIONS = 14;
Jonathan Hartf2fda812015-02-17 15:21:03 -080068 private static final int BACKOFF_TIME = 2;
Madan Jampani4732c1b2015-05-19 17:11:50 -070069 private static final int CHECK_PARTITION_BALANCE_PERIOD_SEC = 10;
70 private static final int RETRY_AFTER_DELAY_SEC = 5;
Jonathan Hart74c83132015-02-02 18:37:57 -080071
72 private static final String ELECTION_PREFIX = "intent-partition-";
73
Madan Jampania9673fd2016-02-02 13:01:29 -080074 protected NodeId localNodeId;
Madan Jampani1c965102016-01-13 14:34:16 -080075 private ListenerRegistry<IntentPartitionEvent, IntentPartitionEventListener> listenerRegistry;
Jonathan Hart74c83132015-02-02 18:37:57 -080076 private LeadershipEventListener leaderListener = new InternalLeadershipListener();
77
Jonathan Hartf2fda812015-02-17 15:21:03 -080078 private ScheduledExecutorService executor = Executors
79 .newScheduledThreadPool(1);
Jonathan Hart74c83132015-02-02 18:37:57 -080080
81 @Activate
82 public void activate() {
Madan Jampania9673fd2016-02-02 13:01:29 -080083 localNodeId = clusterService.getLocalNode().id();
Jonathan Hart74c83132015-02-02 18:37:57 -080084 leadershipService.addListener(leaderListener);
85
Brian O'Connor69d6ac72015-05-29 16:24:06 -070086 listenerRegistry = new ListenerRegistry<>();
Madan Jampani1c965102016-01-13 14:34:16 -080087 eventDispatcher.addSink(IntentPartitionEvent.class, listenerRegistry);
Brian O'Connor69d6ac72015-05-29 16:24:06 -070088
Jonathan Hart74c83132015-02-02 18:37:57 -080089 for (int i = 0; i < NUM_PARTITIONS; i++) {
Jonathan Hartf2fda812015-02-17 15:21:03 -080090 leadershipService.runForLeadership(getPartitionPath(i));
Madan Jampania9673fd2016-02-02 13:01:29 -080091 log.debug("Registered to run for {}", getPartitionPath(i));
Jonathan Hart74c83132015-02-02 18:37:57 -080092 }
Jonathan Hartf2fda812015-02-17 15:21:03 -080093
Madan Jampani4732c1b2015-05-19 17:11:50 -070094 executor.scheduleAtFixedRate(() -> scheduleRebalance(0), 0,
95 CHECK_PARTITION_BALANCE_PERIOD_SEC, TimeUnit.SECONDS);
Madan Jampania9673fd2016-02-02 13:01:29 -080096 log.info("Started");
Jonathan Hart74c83132015-02-02 18:37:57 -080097 }
98
99 @Deactivate
100 public void deactivate() {
Jonathan Hartac48a952015-02-25 14:11:55 -0800101 executor.shutdownNow();
102
Madan Jampani1c965102016-01-13 14:34:16 -0800103 eventDispatcher.removeSink(IntentPartitionEvent.class);
Jonathan Hart74c83132015-02-02 18:37:57 -0800104 leadershipService.removeListener(leaderListener);
Madan Jampania9673fd2016-02-02 13:01:29 -0800105 log.info("Stopped");
Jonathan Hartf2fda812015-02-17 15:21:03 -0800106 }
107
Jonathan Hart7061acd2015-03-04 13:15:32 -0800108 /**
109 * Sets the specified executor to be used for scheduling background tasks.
110 *
111 * @param executor scheduled executor service for background tasks
112 * @return this PartitionManager
113 */
Sho SHIMIZUb8147732016-01-15 13:13:31 -0800114 IntentPartitionManager withScheduledExecutor(ScheduledExecutorService executor) {
Jonathan Hart7061acd2015-03-04 13:15:32 -0800115 this.executor = executor;
116 return this;
117 }
118
Jonathan Hartf2fda812015-02-17 15:21:03 -0800119 private String getPartitionPath(int i) {
120 return ELECTION_PREFIX + i;
Jonathan Hart74c83132015-02-02 18:37:57 -0800121 }
122
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800123 private String getPartitionPath(PartitionId id) {
124 return getPartitionPath(id.value());
125 }
126
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800127 private PartitionId getPartitionForKey(Key intentKey) {
Brian O'Connor1fdfacd2015-02-18 20:52:06 -0800128 int partition = Math.abs((int) intentKey.hash()) % NUM_PARTITIONS;
129 //TODO investigate Guava consistent hash method
130 // ... does it add significant computational complexity? is it worth it?
131 //int partition = consistentHash(intentKey.hash(), NUM_PARTITIONS);
132 PartitionId id = new PartitionId(partition);
Brian O'Connor1fdfacd2015-02-18 20:52:06 -0800133 return id;
Jonathan Hart74c83132015-02-02 18:37:57 -0800134 }
135
136 @Override
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800137 public boolean isMine(Key intentKey) {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800138 return Objects.equals(leadershipService.getLeader(getPartitionPath(getPartitionForKey(intentKey))),
Madan Jampania9673fd2016-02-02 13:01:29 -0800139 localNodeId);
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800140 }
141
142 @Override
143 public NodeId getLeader(Key intentKey) {
144 return leadershipService.getLeader(getPartitionPath(getPartitionForKey(intentKey)));
Jonathan Hart74c83132015-02-02 18:37:57 -0800145 }
146
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700147 @Override
Madan Jampani1c965102016-01-13 14:34:16 -0800148 public void addListener(IntentPartitionEventListener listener) {
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700149 listenerRegistry.addListener(listener);
150 }
151
152 @Override
Madan Jampani1c965102016-01-13 14:34:16 -0800153 public void removeListener(IntentPartitionEventListener listener) {
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700154 listenerRegistry.removeListener(listener);
155 }
156
Sho SHIMIZUb8147732016-01-15 13:13:31 -0800157 void doRebalance() {
Madan Jampani4732c1b2015-05-19 17:11:50 -0700158 rebalanceScheduled.set(false);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800159 try {
Madan Jampani4732c1b2015-05-19 17:11:50 -0700160 rebalance();
Jonathan Hartf2fda812015-02-17 15:21:03 -0800161 } catch (Exception e) {
Madan Jampani4732c1b2015-05-19 17:11:50 -0700162 log.warn("Exception caught during rebalance task. Will retry in " + RETRY_AFTER_DELAY_SEC + " seconds", e);
163 scheduleRebalance(RETRY_AFTER_DELAY_SEC);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800164 }
165 }
166
Jonathan Hartf2fda812015-02-17 15:21:03 -0800167 /**
168 * Determine whether we have more than our fair share of partitions, and if
169 * so, relinquish leadership of some of them for a little while to let
170 * other instances take over.
171 */
Madan Jampani4732c1b2015-05-19 17:11:50 -0700172 private void rebalance() {
Jonathan Hartf2fda812015-02-17 15:21:03 -0800173 int activeNodes = (int) clusterService.getNodes()
174 .stream()
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800175 .filter(node -> clusterService.getState(node.id()).isActive())
Jonathan Hartf2fda812015-02-17 15:21:03 -0800176 .count();
177
178 int myShare = (int) Math.ceil((double) NUM_PARTITIONS / activeNodes);
179
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800180 List<Leadership> myPartitions = leadershipService.getLeaderBoard().values()
181 .stream()
Madan Jampania9673fd2016-02-02 13:01:29 -0800182 .filter(l -> localNodeId.equals(l.leaderNodeId()))
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800183 .filter(l -> l.topic().startsWith(ELECTION_PREFIX))
184 .collect(Collectors.toList());
Jonathan Hartf2fda812015-02-17 15:21:03 -0800185
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800186 int relinquish = myPartitions.size() - myShare;
Jonathan Hartf2fda812015-02-17 15:21:03 -0800187
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800188 if (relinquish <= 0) {
189 return;
190 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800191
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800192 for (int i = 0; i < relinquish; i++) {
193 String topic = myPartitions.get(i).topic();
194 leadershipService.withdraw(topic);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800195
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800196 executor.schedule(() -> recontest(topic),
197 BACKOFF_TIME, TimeUnit.SECONDS);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800198 }
199 }
200
Madan Jampani4732c1b2015-05-19 17:11:50 -0700201 private void scheduleRebalance(int afterDelaySec) {
202 if (rebalanceScheduled.compareAndSet(false, true)) {
203 executor.schedule(this::doRebalance, afterDelaySec, TimeUnit.SECONDS);
204 }
205 }
206
Jonathan Hartf2fda812015-02-17 15:21:03 -0800207 /**
208 * Try and recontest for leadership of a partition.
209 *
210 * @param path topic name to recontest
211 */
212 private void recontest(String path) {
213 leadershipService.runForLeadership(path);
214 }
215
Jonathan Hart74c83132015-02-02 18:37:57 -0800216 private final class InternalLeadershipListener implements LeadershipEventListener {
217
218 @Override
219 public void event(LeadershipEvent event) {
220 Leadership leadership = event.subject();
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800221
Madan Jampania9673fd2016-02-02 13:01:29 -0800222 if (Objects.equals(leadership.leaderNodeId(), localNodeId) &&
Jonathan Hart74c83132015-02-02 18:37:57 -0800223 leadership.topic().startsWith(ELECTION_PREFIX)) {
224
Madan Jampani1c965102016-01-13 14:34:16 -0800225 eventDispatcher.post(new IntentPartitionEvent(IntentPartitionEvent.Type.LEADER_CHANGED,
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700226 leadership.topic()));
Jonathan Hart74c83132015-02-02 18:37:57 -0800227 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800228
Madan Jampani620f70d2016-01-30 22:22:47 -0800229 if (event.type() == LeadershipEvent.Type.CANDIDATES_CHANGED) {
230 scheduleRebalance(0);
231 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800232 }
233 }
Jonathan Hart74c83132015-02-02 18:37:57 -0800234}