blob: b3e193e8f420f72442d2c1c2e90da242998e2b2d [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;
Jonathan Hartf2fda812015-02-17 15:21:03 -080024import org.onosproject.cluster.ClusterEvent;
25import org.onosproject.cluster.ClusterEventListener;
Jonathan Hart74c83132015-02-02 18:37:57 -080026import org.onosproject.cluster.ClusterService;
Jonathan Hartf2fda812015-02-17 15:21:03 -080027import org.onosproject.cluster.ControllerNode;
Jonathan Hart74c83132015-02-02 18:37:57 -080028import org.onosproject.cluster.Leadership;
29import org.onosproject.cluster.LeadershipEvent;
30import org.onosproject.cluster.LeadershipEventListener;
31import org.onosproject.cluster.LeadershipService;
Jonathan Hart5ec32ba2015-02-05 13:33:58 -080032import org.onosproject.net.intent.Key;
Jonathan Hart74c83132015-02-02 18:37:57 -080033import org.slf4j.Logger;
34import org.slf4j.LoggerFactory;
35
36import java.util.Collections;
Jonathan Hartf2fda812015-02-17 15:21:03 -080037import java.util.Iterator;
Jonathan Hart74c83132015-02-02 18:37:57 -080038import java.util.Set;
39import java.util.concurrent.ConcurrentHashMap;
Jonathan Hartf2fda812015-02-17 15:21:03 -080040import java.util.concurrent.Executors;
41import java.util.concurrent.ScheduledExecutorService;
42import java.util.concurrent.TimeUnit;
Jonathan Hart74c83132015-02-02 18:37:57 -080043
Jonathan Hart74c83132015-02-02 18:37:57 -080044/**
45 * Manages the assignment of intent keyspace partitions to instances.
46 */
47@Component(immediate = true)
48@Service
49public class PartitionManager implements PartitionService {
50
51 private static final Logger log = LoggerFactory.getLogger(PartitionManager.class);
52
53 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
54 protected LeadershipService leadershipService;
55
56 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
57 protected ClusterService clusterService;
58
Brian O'Connor71503cd2015-02-20 22:05:48 -080059 private static final int NUM_PARTITIONS = 14;
Jonathan Hartf2fda812015-02-17 15:21:03 -080060 private static final int BACKOFF_TIME = 2;
61 private static final int CHECK_PERIOD = 10;
Jonathan Hart74c83132015-02-02 18:37:57 -080062
63 private static final String ELECTION_PREFIX = "intent-partition-";
64
65 private LeadershipEventListener leaderListener = new InternalLeadershipListener();
Jonathan Hartf2fda812015-02-17 15:21:03 -080066 private ClusterEventListener clusterListener = new InternalClusterEventListener();
Jonathan Hart74c83132015-02-02 18:37:57 -080067
Jonathan Hartf2fda812015-02-17 15:21:03 -080068 private final Set<PartitionId> myPartitions
69 = Collections.newSetFromMap(new ConcurrentHashMap<>());
70
71 private ScheduledExecutorService executor = Executors
72 .newScheduledThreadPool(1);
Jonathan Hart74c83132015-02-02 18:37:57 -080073
74 @Activate
75 public void activate() {
Jonathan Hart74c83132015-02-02 18:37:57 -080076 leadershipService.addListener(leaderListener);
Jonathan Hartf2fda812015-02-17 15:21:03 -080077 clusterService.addListener(clusterListener);
Jonathan Hart74c83132015-02-02 18:37:57 -080078
79 for (int i = 0; i < NUM_PARTITIONS; i++) {
Jonathan Hartf2fda812015-02-17 15:21:03 -080080 leadershipService.runForLeadership(getPartitionPath(i));
Jonathan Hart74c83132015-02-02 18:37:57 -080081 }
Jonathan Hartf2fda812015-02-17 15:21:03 -080082
83 executor.scheduleAtFixedRate(this::doRelinquish, 0,
84 CHECK_PERIOD, TimeUnit.SECONDS);
Jonathan Hart74c83132015-02-02 18:37:57 -080085 }
86
87 @Deactivate
88 public void deactivate() {
Jonathan Hartac48a952015-02-25 14:11:55 -080089 executor.shutdownNow();
90
Jonathan Hart74c83132015-02-02 18:37:57 -080091 leadershipService.removeListener(leaderListener);
Jonathan Hartf2fda812015-02-17 15:21:03 -080092 clusterService.removeListener(clusterListener);
93 }
94
95 private String getPartitionPath(int i) {
96 return ELECTION_PREFIX + i;
Jonathan Hart74c83132015-02-02 18:37:57 -080097 }
98
Jonathan Hart5ec32ba2015-02-05 13:33:58 -080099 private PartitionId getPartitionForKey(Key intentKey) {
Brian O'Connor1fdfacd2015-02-18 20:52:06 -0800100 int partition = Math.abs((int) intentKey.hash()) % NUM_PARTITIONS;
101 //TODO investigate Guava consistent hash method
102 // ... does it add significant computational complexity? is it worth it?
103 //int partition = consistentHash(intentKey.hash(), NUM_PARTITIONS);
104 PartitionId id = new PartitionId(partition);
105 log.debug("Getting partition for {}: {}", intentKey, id); //FIXME debug
106 return id;
Jonathan Hart74c83132015-02-02 18:37:57 -0800107 }
108
109 @Override
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800110 public boolean isMine(Key intentKey) {
111 return myPartitions.contains(getPartitionForKey(intentKey));
Jonathan Hart74c83132015-02-02 18:37:57 -0800112 }
113
Jonathan Hartf2fda812015-02-17 15:21:03 -0800114 private void doRelinquish() {
115 try {
116 relinquish();
117 } catch (Exception e) {
118 log.warn("Exception caught during relinquish task", e);
119 }
120 }
121
122
123 /**
124 * Determine whether we have more than our fair share of partitions, and if
125 * so, relinquish leadership of some of them for a little while to let
126 * other instances take over.
127 */
128 private void relinquish() {
129 int activeNodes = (int) clusterService.getNodes()
130 .stream()
131 .filter(n -> clusterService.getState(n.id())
132 == ControllerNode.State.ACTIVE)
133 .count();
134
135 int myShare = (int) Math.ceil((double) NUM_PARTITIONS / activeNodes);
136
137 synchronized (myPartitions) {
138 int relinquish = myPartitions.size() - myShare;
139
140 if (relinquish <= 0) {
141 return;
142 }
143
144 Iterator<PartitionId> it = myPartitions.iterator();
145 for (int i = 0; i < relinquish; i++) {
146 PartitionId id = it.next();
147 it.remove();
148
149 leadershipService.withdraw(getPartitionPath(id.value()));
150
151 executor.schedule(() -> recontest(getPartitionPath(id.value())),
152 BACKOFF_TIME, TimeUnit.SECONDS);
153 }
154 }
155 }
156
157 /**
158 * Try and recontest for leadership of a partition.
159 *
160 * @param path topic name to recontest
161 */
162 private void recontest(String path) {
163 leadershipService.runForLeadership(path);
164 }
165
Jonathan Hart74c83132015-02-02 18:37:57 -0800166 private final class InternalLeadershipListener implements LeadershipEventListener {
167
168 @Override
169 public void event(LeadershipEvent event) {
170 Leadership leadership = event.subject();
171 // update internal state about which partitions I'm leader of
172 if (leadership.leader().equals(clusterService.getLocalNode().id()) &&
173 leadership.topic().startsWith(ELECTION_PREFIX)) {
174
175 // Parse out the partition ID
176 String[] splitted = leadership.topic().split("-");
177 if (splitted.length != 3) {
178 log.warn("Couldn't parse leader election topic {}", leadership.topic());
179 return;
180 }
181
182 int partitionId;
183 try {
184 partitionId = Integer.parseInt(splitted[2]);
185 } catch (NumberFormatException e) {
186 log.warn("Couldn't parse partition ID {}", splitted[2]);
187 return;
188 }
189
Jonathan Hartf2fda812015-02-17 15:21:03 -0800190 synchronized (myPartitions) {
191 if (event.type() == LeadershipEvent.Type.LEADER_ELECTED) {
192 myPartitions.add(new PartitionId(partitionId));
193 } else if (event.type() == LeadershipEvent.Type.LEADER_BOOTED) {
194 myPartitions.remove(new PartitionId(partitionId));
195 }
Jonathan Hart74c83132015-02-02 18:37:57 -0800196 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800197
198 // See if we need to let some partitions go
199 relinquish();
Jonathan Hart74c83132015-02-02 18:37:57 -0800200 }
Jonathan Hart74c83132015-02-02 18:37:57 -0800201 }
202 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800203
204 private final class InternalClusterEventListener implements
205 ClusterEventListener {
206
207 @Override
208 public void event(ClusterEvent event) {
209 relinquish();
210 }
211 }
Jonathan Hart74c83132015-02-02 18:37:57 -0800212}