blob: 611ed218c67bb5491e25fb66ad8afd38475d5fc6 [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
Jonathan Hartf2fda812015-02-17 15:21:03 -080059 private static final int NUM_PARTITIONS = 32;
60 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() {
89 leadershipService.removeListener(leaderListener);
Jonathan Hartf2fda812015-02-17 15:21:03 -080090 clusterService.removeListener(clusterListener);
91 }
92
93 private String getPartitionPath(int i) {
94 return ELECTION_PREFIX + i;
Jonathan Hart74c83132015-02-02 18:37:57 -080095 }
96
Jonathan Hart5ec32ba2015-02-05 13:33:58 -080097 private PartitionId getPartitionForKey(Key intentKey) {
98 log.debug("Getting partition for {}: {}", intentKey,
Jonathan Hartf2fda812015-02-17 15:21:03 -080099 new PartitionId((int) Math.abs(intentKey.hash()) % NUM_PARTITIONS));
100 return new PartitionId((int) Math.abs(intentKey.hash()) % NUM_PARTITIONS);
Jonathan Hart74c83132015-02-02 18:37:57 -0800101 }
102
103 @Override
Jonathan Hart5ec32ba2015-02-05 13:33:58 -0800104 public boolean isMine(Key intentKey) {
105 return myPartitions.contains(getPartitionForKey(intentKey));
Jonathan Hart74c83132015-02-02 18:37:57 -0800106 }
107
Jonathan Hartf2fda812015-02-17 15:21:03 -0800108 private void doRelinquish() {
109 try {
110 relinquish();
111 } catch (Exception e) {
112 log.warn("Exception caught during relinquish task", e);
113 }
114 }
115
116
117 /**
118 * Determine whether we have more than our fair share of partitions, and if
119 * so, relinquish leadership of some of them for a little while to let
120 * other instances take over.
121 */
122 private void relinquish() {
123 int activeNodes = (int) clusterService.getNodes()
124 .stream()
125 .filter(n -> clusterService.getState(n.id())
126 == ControllerNode.State.ACTIVE)
127 .count();
128
129 int myShare = (int) Math.ceil((double) NUM_PARTITIONS / activeNodes);
130
131 synchronized (myPartitions) {
132 int relinquish = myPartitions.size() - myShare;
133
134 if (relinquish <= 0) {
135 return;
136 }
137
138 Iterator<PartitionId> it = myPartitions.iterator();
139 for (int i = 0; i < relinquish; i++) {
140 PartitionId id = it.next();
141 it.remove();
142
143 leadershipService.withdraw(getPartitionPath(id.value()));
144
145 executor.schedule(() -> recontest(getPartitionPath(id.value())),
146 BACKOFF_TIME, TimeUnit.SECONDS);
147 }
148 }
149 }
150
151 /**
152 * Try and recontest for leadership of a partition.
153 *
154 * @param path topic name to recontest
155 */
156 private void recontest(String path) {
157 leadershipService.runForLeadership(path);
158 }
159
Jonathan Hart74c83132015-02-02 18:37:57 -0800160 private final class InternalLeadershipListener implements LeadershipEventListener {
161
162 @Override
163 public void event(LeadershipEvent event) {
164 Leadership leadership = event.subject();
165 // update internal state about which partitions I'm leader of
166 if (leadership.leader().equals(clusterService.getLocalNode().id()) &&
167 leadership.topic().startsWith(ELECTION_PREFIX)) {
168
169 // Parse out the partition ID
170 String[] splitted = leadership.topic().split("-");
171 if (splitted.length != 3) {
172 log.warn("Couldn't parse leader election topic {}", leadership.topic());
173 return;
174 }
175
176 int partitionId;
177 try {
178 partitionId = Integer.parseInt(splitted[2]);
179 } catch (NumberFormatException e) {
180 log.warn("Couldn't parse partition ID {}", splitted[2]);
181 return;
182 }
183
Jonathan Hartf2fda812015-02-17 15:21:03 -0800184 synchronized (myPartitions) {
185 if (event.type() == LeadershipEvent.Type.LEADER_ELECTED) {
186 myPartitions.add(new PartitionId(partitionId));
187 } else if (event.type() == LeadershipEvent.Type.LEADER_BOOTED) {
188 myPartitions.remove(new PartitionId(partitionId));
189 }
Jonathan Hart74c83132015-02-02 18:37:57 -0800190 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800191
192 // See if we need to let some partitions go
193 relinquish();
Jonathan Hart74c83132015-02-02 18:37:57 -0800194 }
Jonathan Hart74c83132015-02-02 18:37:57 -0800195 }
196 }
Jonathan Hartf2fda812015-02-17 15:21:03 -0800197
198 private final class InternalClusterEventListener implements
199 ClusterEventListener {
200
201 @Override
202 public void event(ClusterEvent event) {
203 relinquish();
204 }
205 }
Jonathan Hart74c83132015-02-02 18:37:57 -0800206}