blob: d2c63f3febcf2facd668b648fb6d36c39c605711 [file] [log] [blame]
Jonathan Hart74c83132015-02-02 18:37:57 -08001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
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;
Jonathan Hartf2fda812015-02-17 15:21:03 -080025import org.onosproject.cluster.ControllerNode;
Jonathan Hart74c83132015-02-02 18:37:57 -080026import org.onosproject.cluster.Leadership;
27import org.onosproject.cluster.LeadershipEvent;
28import org.onosproject.cluster.LeadershipEventListener;
29import org.onosproject.cluster.LeadershipService;
Brian O'Connor5eb77c82015-03-02 18:09:39 -080030import org.onosproject.cluster.NodeId;
Brian O'Connor69d6ac72015-05-29 16:24:06 -070031import org.onosproject.event.EventDeliveryService;
32import org.onosproject.event.ListenerRegistry;
Jonathan Hart5ec32ba2015-02-05 13:33:58 -080033import org.onosproject.net.intent.Key;
Madan Jampani1c965102016-01-13 14:34:16 -080034import org.onosproject.net.intent.IntentPartitionEvent;
35import org.onosproject.net.intent.IntentPartitionEventListener;
36import org.onosproject.net.intent.IntentPartitionService;
Jonathan Hart74c83132015-02-02 18:37:57 -080037import org.slf4j.Logger;
38import org.slf4j.LoggerFactory;
39
Jonathan Hartdc9d7b82015-02-22 17:59:50 -080040import java.util.List;
Brian O'Connor5eb77c82015-03-02 18:09:39 -080041import java.util.Objects;
Jonathan Hartf2fda812015-02-17 15:21:03 -080042import java.util.concurrent.Executors;
43import java.util.concurrent.ScheduledExecutorService;
44import java.util.concurrent.TimeUnit;
Madan Jampani4732c1b2015-05-19 17:11:50 -070045import java.util.concurrent.atomic.AtomicBoolean;
Jonathan Hartdc9d7b82015-02-22 17:59:50 -080046import java.util.stream.Collectors;
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 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() {
Jonathan Hart74c83132015-02-02 18:37:57 -080083 leadershipService.addListener(leaderListener);
84
Brian O'Connor69d6ac72015-05-29 16:24:06 -070085 listenerRegistry = new ListenerRegistry<>();
Madan Jampani1c965102016-01-13 14:34:16 -080086 eventDispatcher.addSink(IntentPartitionEvent.class, listenerRegistry);
Brian O'Connor69d6ac72015-05-29 16:24:06 -070087
Jonathan Hart74c83132015-02-02 18:37:57 -080088 for (int i = 0; i < NUM_PARTITIONS; i++) {
Jonathan Hartf2fda812015-02-17 15:21:03 -080089 leadershipService.runForLeadership(getPartitionPath(i));
Jonathan Hart74c83132015-02-02 18:37:57 -080090 }
Jonathan Hartf2fda812015-02-17 15:21:03 -080091
Madan Jampani4732c1b2015-05-19 17:11:50 -070092 executor.scheduleAtFixedRate(() -> scheduleRebalance(0), 0,
93 CHECK_PARTITION_BALANCE_PERIOD_SEC, TimeUnit.SECONDS);
Jonathan Hart74c83132015-02-02 18:37:57 -080094 }
95
96 @Deactivate
97 public void deactivate() {
Jonathan Hartac48a952015-02-25 14:11:55 -080098 executor.shutdownNow();
99
Madan Jampani1c965102016-01-13 14:34:16 -0800100 eventDispatcher.removeSink(IntentPartitionEvent.class);
Jonathan Hart74c83132015-02-02 18:37:57 -0800101 leadershipService.removeListener(leaderListener);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800102 }
103
Jonathan Hart7061acd2015-03-04 13:15:32 -0800104 /**
105 * Sets the specified executor to be used for scheduling background tasks.
106 *
107 * @param executor scheduled executor service for background tasks
108 * @return this PartitionManager
109 */
Sho SHIMIZUb8147732016-01-15 13:13:31 -0800110 IntentPartitionManager withScheduledExecutor(ScheduledExecutorService executor) {
Jonathan Hart7061acd2015-03-04 13:15:32 -0800111 this.executor = executor;
112 return this;
113 }
114
Jonathan Hartf2fda812015-02-17 15:21:03 -0800115 private String getPartitionPath(int i) {
116 return ELECTION_PREFIX + i;
Jonathan Hart74c83132015-02-02 18:37:57 -0800117 }
118
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800119 private String getPartitionPath(PartitionId id) {
120 return getPartitionPath(id.value());
121 }
122
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800123 private PartitionId getPartitionForKey(Key intentKey) {
Brian O'Connor1fdfacd2015-02-18 20:52:06 -0800124 int partition = Math.abs((int) intentKey.hash()) % NUM_PARTITIONS;
125 //TODO investigate Guava consistent hash method
126 // ... does it add significant computational complexity? is it worth it?
127 //int partition = consistentHash(intentKey.hash(), NUM_PARTITIONS);
128 PartitionId id = new PartitionId(partition);
Brian O'Connor1fdfacd2015-02-18 20:52:06 -0800129 return id;
Jonathan Hart74c83132015-02-02 18:37:57 -0800130 }
131
132 @Override
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800133 public boolean isMine(Key intentKey) {
Brian O'Connor5eb77c82015-03-02 18:09:39 -0800134 return Objects.equals(leadershipService.getLeader(getPartitionPath(getPartitionForKey(intentKey))),
135 clusterService.getLocalNode().id());
136 }
137
138 @Override
139 public NodeId getLeader(Key intentKey) {
140 return leadershipService.getLeader(getPartitionPath(getPartitionForKey(intentKey)));
Jonathan Hart74c83132015-02-02 18:37:57 -0800141 }
142
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700143 @Override
Madan Jampani1c965102016-01-13 14:34:16 -0800144 public void addListener(IntentPartitionEventListener listener) {
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700145 listenerRegistry.addListener(listener);
146 }
147
148 @Override
Madan Jampani1c965102016-01-13 14:34:16 -0800149 public void removeListener(IntentPartitionEventListener listener) {
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700150 listenerRegistry.removeListener(listener);
151 }
152
Sho SHIMIZUb8147732016-01-15 13:13:31 -0800153 void doRebalance() {
Madan Jampani4732c1b2015-05-19 17:11:50 -0700154 rebalanceScheduled.set(false);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800155 try {
Madan Jampani4732c1b2015-05-19 17:11:50 -0700156 rebalance();
Jonathan Hartf2fda812015-02-17 15:21:03 -0800157 } catch (Exception e) {
Madan Jampani4732c1b2015-05-19 17:11:50 -0700158 log.warn("Exception caught during rebalance task. Will retry in " + RETRY_AFTER_DELAY_SEC + " seconds", e);
159 scheduleRebalance(RETRY_AFTER_DELAY_SEC);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800160 }
161 }
162
Jonathan Hartf2fda812015-02-17 15:21:03 -0800163 /**
164 * Determine whether we have more than our fair share of partitions, and if
165 * so, relinquish leadership of some of them for a little while to let
166 * other instances take over.
167 */
Madan Jampani4732c1b2015-05-19 17:11:50 -0700168 private void rebalance() {
Jonathan Hartf2fda812015-02-17 15:21:03 -0800169 int activeNodes = (int) clusterService.getNodes()
170 .stream()
Madan Jampani4732c1b2015-05-19 17:11:50 -0700171 .filter(node -> ControllerNode.State.ACTIVE == clusterService.getState(node.id()))
Jonathan Hartf2fda812015-02-17 15:21:03 -0800172 .count();
173
174 int myShare = (int) Math.ceil((double) NUM_PARTITIONS / activeNodes);
175
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800176 List<Leadership> myPartitions = leadershipService.getLeaderBoard().values()
177 .stream()
Madan Jampani620f70d2016-01-30 22:22:47 -0800178 .filter(l -> clusterService.getLocalNode().id().equals(l.leaderNodeId()))
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800179 .filter(l -> l.topic().startsWith(ELECTION_PREFIX))
180 .collect(Collectors.toList());
Jonathan Hartf2fda812015-02-17 15:21:03 -0800181
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800182 int relinquish = myPartitions.size() - myShare;
Jonathan Hartf2fda812015-02-17 15:21:03 -0800183
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800184 if (relinquish <= 0) {
185 return;
186 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800187
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800188 for (int i = 0; i < relinquish; i++) {
189 String topic = myPartitions.get(i).topic();
190 leadershipService.withdraw(topic);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800191
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800192 executor.schedule(() -> recontest(topic),
193 BACKOFF_TIME, TimeUnit.SECONDS);
Jonathan Hartf2fda812015-02-17 15:21:03 -0800194 }
195 }
196
Madan Jampani4732c1b2015-05-19 17:11:50 -0700197 private void scheduleRebalance(int afterDelaySec) {
198 if (rebalanceScheduled.compareAndSet(false, true)) {
199 executor.schedule(this::doRebalance, afterDelaySec, TimeUnit.SECONDS);
200 }
201 }
202
Jonathan Hartf2fda812015-02-17 15:21:03 -0800203 /**
204 * Try and recontest for leadership of a partition.
205 *
206 * @param path topic name to recontest
207 */
208 private void recontest(String path) {
209 leadershipService.runForLeadership(path);
210 }
211
Jonathan Hart74c83132015-02-02 18:37:57 -0800212 private final class InternalLeadershipListener implements LeadershipEventListener {
213
214 @Override
215 public void event(LeadershipEvent event) {
216 Leadership leadership = event.subject();
Jonathan Hartdc9d7b82015-02-22 17:59:50 -0800217
Madan Jampani620f70d2016-01-30 22:22:47 -0800218 if (Objects.equals(leadership.leaderNodeId(), clusterService.getLocalNode().id()) &&
Jonathan Hart74c83132015-02-02 18:37:57 -0800219 leadership.topic().startsWith(ELECTION_PREFIX)) {
220
Madan Jampani1c965102016-01-13 14:34:16 -0800221 eventDispatcher.post(new IntentPartitionEvent(IntentPartitionEvent.Type.LEADER_CHANGED,
Brian O'Connor69d6ac72015-05-29 16:24:06 -0700222 leadership.topic()));
Jonathan Hart74c83132015-02-02 18:37:57 -0800223 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800224
Madan Jampani620f70d2016-01-30 22:22:47 -0800225 if (event.type() == LeadershipEvent.Type.CANDIDATES_CHANGED) {
226 scheduleRebalance(0);
227 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800228 }
229 }
Jonathan Hart74c83132015-02-02 18:37:57 -0800230}