blob: 2a9096a8c451424437315685d7e6a2acda52d0ba [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07003 *
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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.cluster.impl;
Ayaka Koshibe16609692014-09-23 12:46:15 -070017
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -080018import com.codahale.metrics.Timer;
19import com.codahale.metrics.Timer.Context;
Madan Jampanide003d92015-05-11 17:14:20 -070020import com.google.common.collect.Lists;
Claudine Chiudce08152016-03-09 18:19:28 +000021import com.google.common.collect.Sets;
Madan Jampanide003d92015-05-11 17:14:20 -070022import com.google.common.util.concurrent.Futures;
Yuta HIGUCHI6a462832014-11-23 23:56:03 -080023import org.onlab.metrics.MetricsService;
Victor Silvaf2b9d032016-09-19 19:43:20 -030024import org.onosproject.cfg.ComponentConfigService;
25import org.onosproject.cfg.ConfigProperty;
Brian O'Connorabafb502014-12-02 22:26:20 -080026import org.onosproject.cluster.ClusterService;
27import org.onosproject.cluster.ControllerNode;
28import org.onosproject.cluster.NodeId;
29import org.onosproject.cluster.RoleInfo;
30import org.onosproject.core.MetricsHelper;
Thomas Vachuska7a8de842016-03-07 20:56:35 -080031import org.onosproject.event.AbstractListenerManager;
Brian O'Connorabafb502014-12-02 22:26:20 -080032import org.onosproject.mastership.MastershipAdminService;
33import org.onosproject.mastership.MastershipEvent;
Jordan Halterman0a2bd452018-06-13 17:24:58 -070034import org.onosproject.mastership.MastershipInfo;
Brian O'Connorabafb502014-12-02 22:26:20 -080035import org.onosproject.mastership.MastershipListener;
36import org.onosproject.mastership.MastershipService;
37import org.onosproject.mastership.MastershipStore;
38import org.onosproject.mastership.MastershipStoreDelegate;
39import org.onosproject.mastership.MastershipTerm;
40import org.onosproject.mastership.MastershipTermService;
41import org.onosproject.net.DeviceId;
42import org.onosproject.net.MastershipRole;
Claudine Chiudce08152016-03-09 18:19:28 +000043import org.onosproject.net.region.Region;
44import org.onosproject.net.region.RegionService;
Jordan Halterman713830d2017-10-07 13:40:44 -070045import org.onosproject.upgrade.UpgradeEvent;
46import org.onosproject.upgrade.UpgradeEventListener;
47import org.onosproject.upgrade.UpgradeService;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070048import org.osgi.service.component.annotations.Activate;
49import org.osgi.service.component.annotations.Component;
50import org.osgi.service.component.annotations.Deactivate;
51import org.osgi.service.component.annotations.Modified;
52import org.osgi.service.component.annotations.Reference;
53import org.osgi.service.component.annotations.ReferenceCardinality;
Ayaka Koshibe16609692014-09-23 12:46:15 -070054import org.slf4j.Logger;
55
Claudine Chiudce08152016-03-09 18:19:28 +000056import java.util.ArrayList;
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -080057import java.util.Collection;
Claudine Chiudce08152016-03-09 18:19:28 +000058import java.util.Collections;
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -080059import java.util.Comparator;
Thomas Vachuska12dfdc32014-11-29 16:03:12 -080060import java.util.HashMap;
61import java.util.HashSet;
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -080062import java.util.Iterator;
63import java.util.List;
Thomas Vachuska12dfdc32014-11-29 16:03:12 -080064import java.util.Map;
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -080065import java.util.Set;
Madan Jampanif7536ab2015-05-07 23:23:23 -070066import java.util.concurrent.CompletableFuture;
67
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -080068import static com.google.common.base.Preconditions.checkNotNull;
69import static com.google.common.collect.Lists.newArrayList;
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -080070import static java.util.concurrent.CompletableFuture.allOf;
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -080071import static org.onlab.metrics.MetricsUtil.startTimer;
72import static org.onlab.metrics.MetricsUtil.stopTimer;
Brian O'Connorabafb502014-12-02 22:26:20 -080073import static org.onosproject.net.MastershipRole.MASTER;
Changhoon Yoon541ef712015-05-23 17:18:34 +090074import static org.onosproject.security.AppGuard.checkPermission;
Thomas Vachuska7a8de842016-03-07 20:56:35 -080075import static org.onosproject.security.AppPermission.Type.CLUSTER_READ;
76import static org.onosproject.security.AppPermission.Type.CLUSTER_WRITE;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070077import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoonb856b812015-08-10 03:47:19 +090078
Changhoon Yoon541ef712015-05-23 17:18:34 +090079
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -080080/**
81 * Component providing the node-device mastership service.
82 */
Ray Milkey86ad7bb2018-09-27 12:32:28 -070083@Component(immediate = true,
84 service = {MastershipService.class, MastershipAdminService.class, MastershipTermService.class,
85 MetricsHelper.class})
Ayaka Koshibe3eed2b02014-09-23 13:28:05 -070086public class MastershipManager
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -080087 extends AbstractListenerManager<MastershipEvent, MastershipListener>
88 implements MastershipService, MastershipAdminService, MastershipTermService,
89 MetricsHelper {
Ayaka Koshibe16609692014-09-23 12:46:15 -070090
91 private static final String NODE_ID_NULL = "Node ID cannot be null";
92 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
93 private static final String ROLE_NULL = "Mastership role cannot be null";
94
95 private final Logger log = getLogger(getClass());
96
alshabib339a3d92014-09-26 17:54:32 -070097 private final MastershipStoreDelegate delegate = new InternalDelegate();
Jordan Halterman713830d2017-10-07 13:40:44 -070098 private final UpgradeEventListener upgradeEventListener = new InternalUpgradeEventListener();
Ayaka Koshibe16609692014-09-23 12:46:15 -070099
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700100 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibe16609692014-09-23 12:46:15 -0700101 protected MastershipStore store;
102
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700103 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tom4a5d1712014-09-23 17:49:39 -0700104 protected ClusterService clusterService;
Ayaka Koshibe16609692014-09-23 12:46:15 -0700105
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700106 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yuta HIGUCHI6a462832014-11-23 23:56:03 -0800107 protected MetricsService metricsService;
108
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700109 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Claudine Chiudce08152016-03-09 18:19:28 +0000110 protected RegionService regionService;
111
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700112 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Victor Silvaf2b9d032016-09-19 19:43:20 -0300113 protected ComponentConfigService cfgService;
114
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700115 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jordan Halterman713830d2017-10-07 13:40:44 -0700116 protected UpgradeService upgradeService;
117
Madan Jampanic6e574f2015-05-29 13:41:52 -0700118 private NodeId localNodeId;
Yuta HIGUCHI6a462832014-11-23 23:56:03 -0800119 private Timer requestRoleTimer;
Victor Silvaf2b9d032016-09-19 19:43:20 -0300120
121 static final boolean DEFAULT_USE_REGION_FOR_BALANCE_ROLES = false;
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700122 //@Property(name = "useRegionForBalanceRoles", boolValue = DEFAULT_USE_REGION_FOR_BALANCE_ROLES,
123 // label = "Use Regions for balancing roles")
Jordan Halterman713830d2017-10-07 13:40:44 -0700124 protected boolean useRegionForBalanceRoles;
125
126 private static final boolean DEFAULT_REBALANCE_ROLES_ON_UPGRADE = true;
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700127 //@Property(name = "rebalanceRolesOnUpgrade",
128 // boolValue = DEFAULT_REBALANCE_ROLES_ON_UPGRADE,
129 // label = "Automatically rebalance roles following an upgrade")
Jordan Halterman0676c972017-11-05 11:49:23 -0800130 protected boolean rebalanceRolesOnUpgrade = DEFAULT_REBALANCE_ROLES_ON_UPGRADE;
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700131
Ayaka Koshibe16609692014-09-23 12:46:15 -0700132 @Activate
133 public void activate() {
Victor Silvaf2b9d032016-09-19 19:43:20 -0300134 cfgService.registerProperties(getClass());
135 modified();
136
Yuta HIGUCHI6a462832014-11-23 23:56:03 -0800137 requestRoleTimer = createTimer("Mastership", "requestRole", "responseTime");
Madan Jampanic6e574f2015-05-29 13:41:52 -0700138 localNodeId = clusterService.getLocalNode().id();
Jordan Halterman61aeb352017-10-18 16:22:17 -0700139 upgradeService.addListener(upgradeEventListener);
Ayaka Koshibe16609692014-09-23 12:46:15 -0700140 eventDispatcher.addSink(MastershipEvent.class, listenerRegistry);
alshabib339a3d92014-09-26 17:54:32 -0700141 store.setDelegate(delegate);
Ayaka Koshibe16609692014-09-23 12:46:15 -0700142 log.info("Started");
143 }
144
Victor Silvaf2b9d032016-09-19 19:43:20 -0300145 @Modified
146 public void modified() {
147 Set<ConfigProperty> configProperties = cfgService.getProperties(getClass().getCanonicalName());
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700148 if (configProperties != null) {
149 for (ConfigProperty property : configProperties) {
150 if ("useRegionForBalanceRoles".equals(property.name())) {
151 useRegionForBalanceRoles = property.asBoolean();
152 }
Victor Silvaf2b9d032016-09-19 19:43:20 -0300153 }
154 }
155 }
156
Ayaka Koshibe16609692014-09-23 12:46:15 -0700157 @Deactivate
158 public void deactivate() {
159 eventDispatcher.removeSink(MastershipEvent.class);
Jordan Halterman61aeb352017-10-18 16:22:17 -0700160 upgradeService.removeListener(upgradeEventListener);
alshabib339a3d92014-09-26 17:54:32 -0700161 store.unsetDelegate(delegate);
Ayaka Koshibe16609692014-09-23 12:46:15 -0700162 log.info("Stopped");
Victor Silvaf2b9d032016-09-19 19:43:20 -0300163 cfgService.unregisterProperties(getClass(), false);
Ayaka Koshibe16609692014-09-23 12:46:15 -0700164 }
165
Ayaka Koshibe16609692014-09-23 12:46:15 -0700166 @Override
Madan Jampanide003d92015-05-11 17:14:20 -0700167 public CompletableFuture<Void> setRole(NodeId nodeId, DeviceId deviceId, MastershipRole role) {
Ayaka Koshibe16609692014-09-23 12:46:15 -0700168 checkNotNull(nodeId, NODE_ID_NULL);
169 checkNotNull(deviceId, DEVICE_ID_NULL);
170 checkNotNull(role, ROLE_NULL);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700171
Madan Jampanif7536ab2015-05-07 23:23:23 -0700172 CompletableFuture<MastershipEvent> eventFuture = null;
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700173
174 switch (role) {
175 case MASTER:
Madan Jampanif7536ab2015-05-07 23:23:23 -0700176 eventFuture = store.setMaster(nodeId, deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700177 break;
178 case STANDBY:
Madan Jampanif7536ab2015-05-07 23:23:23 -0700179 eventFuture = store.setStandby(nodeId, deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700180 break;
181 case NONE:
Madan Jampanif7536ab2015-05-07 23:23:23 -0700182 eventFuture = store.relinquishRole(nodeId, deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700183 break;
184 default:
185 log.info("Unknown role; ignoring");
Madan Jampanide003d92015-05-11 17:14:20 -0700186 return CompletableFuture.completedFuture(null);
Ayaka Koshibe971a38a2014-09-30 11:56:23 -0700187 }
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700188
Madan Jampanic6e574f2015-05-29 13:41:52 -0700189 return eventFuture.thenAccept(this::post)
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800190 .thenApply(v -> null);
Ayaka Koshibe16609692014-09-23 12:46:15 -0700191 }
192
193 @Override
tomb41d1ac2014-09-24 01:51:24 -0700194 public MastershipRole getLocalRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900195 checkPermission(CLUSTER_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900196
tomb41d1ac2014-09-24 01:51:24 -0700197 checkNotNull(deviceId, DEVICE_ID_NULL);
198 return store.getRole(clusterService.getLocalNode().id(), deviceId);
199 }
200
201 @Override
Madan Jampanic6e574f2015-05-29 13:41:52 -0700202 public CompletableFuture<Void> relinquishMastership(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900203 checkPermission(CLUSTER_WRITE);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700204 return store.relinquishRole(localNodeId, deviceId)
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800205 .thenAccept(this::post)
206 .thenApply(v -> null);
tomb41d1ac2014-09-24 01:51:24 -0700207 }
208
209 @Override
Madan Jampanide003d92015-05-11 17:14:20 -0700210 public CompletableFuture<MastershipRole> requestRoleFor(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900211 checkPermission(CLUSTER_WRITE);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900212
tomb41d1ac2014-09-24 01:51:24 -0700213 checkNotNull(deviceId, DEVICE_ID_NULL);
Yuta HIGUCHI6a462832014-11-23 23:56:03 -0800214 final Context timer = startTimer(requestRoleTimer);
Madan Jampanide003d92015-05-11 17:14:20 -0700215 return store.requestRole(deviceId).whenComplete((result, error) -> stopTimer(timer));
216
tomb41d1ac2014-09-24 01:51:24 -0700217 }
218
219 @Override
Ayaka Koshibe16609692014-09-23 12:46:15 -0700220 public NodeId getMasterFor(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900221 checkPermission(CLUSTER_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900222
Ayaka Koshibe16609692014-09-23 12:46:15 -0700223 checkNotNull(deviceId, DEVICE_ID_NULL);
224 return store.getMaster(deviceId);
225 }
226
227 @Override
228 public Set<DeviceId> getDevicesOf(NodeId nodeId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900229 checkPermission(CLUSTER_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900230
Ayaka Koshibe16609692014-09-23 12:46:15 -0700231 checkNotNull(nodeId, NODE_ID_NULL);
232 return store.getDevices(nodeId);
233 }
234
Ayaka Koshibe45503ce2014-10-14 11:26:45 -0700235 @Override
Ayaka Koshibeabedb092014-10-20 17:01:31 -0700236 public RoleInfo getNodesFor(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900237 checkPermission(CLUSTER_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900238
Ayaka Koshibe45503ce2014-10-14 11:26:45 -0700239 checkNotNull(deviceId, DEVICE_ID_NULL);
240 return store.getNodes(deviceId);
241 }
Ayaka Koshibeb70d34b2014-09-25 15:43:01 -0700242
243 @Override
Jordan Halterman0a2bd452018-06-13 17:24:58 -0700244 public MastershipInfo getMastershipFor(DeviceId deviceId) {
245 checkPermission(CLUSTER_READ);
246 checkNotNull(deviceId, DEVICE_ID_NULL);
247 return store.getMastership(deviceId);
248 }
249
250 @Override
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800251 public MastershipTerm getMastershipTerm(DeviceId deviceId) {
Heedo Kang4a47a302016-02-29 17:40:23 +0900252 checkPermission(CLUSTER_READ);
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800253 return store.getTermFor(deviceId);
Ayaka Koshibeb70d34b2014-09-25 15:43:01 -0700254 }
255
Ayaka Koshibe16609692014-09-23 12:46:15 -0700256 @Override
Yuta HIGUCHIa22f69f2014-11-24 22:25:17 -0800257 public MetricsService metricsService() {
258 return metricsService;
259 }
Ayaka Koshibe16609692014-09-23 12:46:15 -0700260
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800261 @Override
262 public void balanceRoles() {
263 List<ControllerNode> nodes = newArrayList(clusterService.getNodes());
Thomas Vachuska12dfdc32014-11-29 16:03:12 -0800264 Map<ControllerNode, Set<DeviceId>> controllerDevices = new HashMap<>();
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800265 Set<DeviceId> orphanedDevices = Sets.newHashSet();
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800266 int deviceCount = 0;
267
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800268 // Create buckets reflecting current ownership; do this irrespective of
269 // whether the node is active.
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800270 for (ControllerNode node : nodes) {
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800271 Set<DeviceId> devicesOf = new HashSet<>(getDevicesOf(node.id()));
Thomas Vachuska7a8de842016-03-07 20:56:35 -0800272 if (clusterService.getState(node.id()).isActive()) {
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800273 log.info("Node {} has {} devices.", node.id(), devicesOf.size());
Thomas Vachuska12dfdc32014-11-29 16:03:12 -0800274 deviceCount += devicesOf.size();
275 controllerDevices.put(node, devicesOf);
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800276 } else if (!devicesOf.isEmpty()) {
277 log.warn("Inactive node {} has {} orphaned devices.", node.id(), devicesOf.size());
278 orphanedDevices.addAll(getDevicesOf(node.id()));
Thomas Vachuska12dfdc32014-11-29 16:03:12 -0800279 }
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800280 }
281
Claudine Chiudce08152016-03-09 18:19:28 +0000282 if (useRegionForBalanceRoles && balanceRolesUsingRegions(controllerDevices)) {
283 return;
284 }
285
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800286 List<CompletableFuture<Void>> balanceBucketsFutures = Lists.newLinkedList();
Claudine Chiudce08152016-03-09 18:19:28 +0000287
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800288 // First re-balance the buckets until they are roughly even.
289 balanceControllerNodes(controllerDevices, deviceCount, balanceBucketsFutures);
290
291 // Then attempt to distribute any orphaned devices among the buckets.
292 distributeOrphanedDevices(controllerDevices, orphanedDevices, balanceBucketsFutures);
293
294 CompletableFuture<Void> balanceRolesFuture =
295 allOf(balanceBucketsFutures.toArray(new CompletableFuture[balanceBucketsFutures.size()]));
Claudine Chiudce08152016-03-09 18:19:28 +0000296
297 Futures.getUnchecked(balanceRolesFuture);
298 }
299
300 /**
301 * Balances the nodes specified in controllerDevices.
302 *
303 * @param controllerDevices controller nodes to devices map
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800304 * @param deviceCount number of devices mastered by controller nodes
305 * @param futures list of setRole futures for "moved" devices
Claudine Chiudce08152016-03-09 18:19:28 +0000306 */
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800307 private void balanceControllerNodes(Map<ControllerNode, Set<DeviceId>> controllerDevices,
308 int deviceCount,
309 List<CompletableFuture<Void>> futures) {
Thomas Vachuska12dfdc32014-11-29 16:03:12 -0800310 // Now re-balance the buckets until they are roughly even.
311 int rounds = controllerDevices.keySet().size();
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800312 for (int i = 0; i < rounds; i++) {
313 // Iterate over the buckets and find the smallest and the largest.
Thomas Vachuska12dfdc32014-11-29 16:03:12 -0800314 ControllerNode smallest = findBucket(true, controllerDevices);
315 ControllerNode largest = findBucket(false, controllerDevices);
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800316 futures.add(balanceBuckets(smallest, largest, controllerDevices, deviceCount));
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800317 }
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800318 }
319
320 /**
321 * Uses the set of orphaned devices to even out the load among the controllers.
322 *
323 * @param controllerDevices controller nodes to devices map
324 * @param orphanedDevices set of orphaned devices without an active master
325 * @param futures list of completable future to track the progress of the balancing operation
326 */
327 private void distributeOrphanedDevices(Map<ControllerNode, Set<DeviceId>> controllerDevices,
328 Set<DeviceId> orphanedDevices,
329 List<CompletableFuture<Void>> futures) {
330 // Now re-distribute the orphaned devices into buckets until they are roughly even.
331 while (!orphanedDevices.isEmpty()) {
332 // Iterate over the buckets and find the smallest bucket.
333 ControllerNode smallest = findBucket(true, controllerDevices);
334 changeMastership(smallest, controllerDevices.get(smallest),
335 orphanedDevices, 1, futures);
336 }
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800337 }
338
Claudine Chiudce08152016-03-09 18:19:28 +0000339 /**
340 * Finds node with the minimum/maximum devices from a list of nodes.
341 *
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800342 * @param min true: minimum, false: maximum
Claudine Chiudce08152016-03-09 18:19:28 +0000343 * @param controllerDevices controller nodes to devices map
344 * @return controller node with minimum/maximum devices
345 */
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800346
Thomas Vachuska12dfdc32014-11-29 16:03:12 -0800347 private ControllerNode findBucket(boolean min,
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800348 Map<ControllerNode, Set<DeviceId>> controllerDevices) {
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800349 int xSize = min ? Integer.MAX_VALUE : -1;
350 ControllerNode xNode = null;
Thomas Vachuska12dfdc32014-11-29 16:03:12 -0800351 for (ControllerNode node : controllerDevices.keySet()) {
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800352 int size = controllerDevices.get(node).size();
353 if ((min && size < xSize) || (!min && size > xSize)) {
354 xSize = size;
355 xNode = node;
356 }
357 }
358 return xNode;
359 }
360
Claudine Chiudce08152016-03-09 18:19:28 +0000361 /**
362 * Balance the node buckets by moving devices from largest to smallest node.
363 *
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800364 * @param smallest node that is master of the smallest number of devices
365 * @param largest node that is master of the largest number of devices
Claudine Chiudce08152016-03-09 18:19:28 +0000366 * @param controllerDevices controller nodes to devices map
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800367 * @param deviceCount number of devices mastered by controller nodes
Claudine Chiudce08152016-03-09 18:19:28 +0000368 * @return list of setRole futures for "moved" devices
369 */
Madan Jampanide003d92015-05-11 17:14:20 -0700370 private CompletableFuture<Void> balanceBuckets(ControllerNode smallest, ControllerNode largest,
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800371 Map<ControllerNode, Set<DeviceId>> controllerDevices,
372 int deviceCount) {
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800373 Collection<DeviceId> minBucket = controllerDevices.get(smallest);
374 Collection<DeviceId> maxBucket = controllerDevices.get(largest);
375 int bucketCount = controllerDevices.keySet().size();
376
377 int delta = (maxBucket.size() - minBucket.size()) / 2;
378 delta = Math.min(deviceCount / bucketCount, delta);
379
Madan Jampanide003d92015-05-11 17:14:20 -0700380 List<CompletableFuture<Void>> setRoleFutures = Lists.newLinkedList();
381
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800382 if (delta > 0) {
383 log.info("Attempting to move {} nodes from {} to {}...", delta,
384 largest.id(), smallest.id());
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800385 changeMastership(smallest, minBucket, maxBucket, delta, setRoleFutures);
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800386 }
Madan Jampanide003d92015-05-11 17:14:20 -0700387
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800388 return allOf(setRoleFutures.toArray(new CompletableFuture[setRoleFutures.size()]));
389 }
390
391 /**
392 * Changes mastership for the specified number of devices in the given source
393 * bucket to the specified node and ads those devices to the given target
394 * bucket. Also adds the futures for tracking the role reassignment progress.
395 *
396 * @param toNode target controller node
397 * @param toBucket target bucket
398 * @param fromBucket source bucket
399 * @param count number of devices
400 * @param futures futures for tracking operation progress
401 */
402 private void changeMastership(ControllerNode toNode, Collection<DeviceId> toBucket,
403 Collection<DeviceId> fromBucket, int count,
404 List<CompletableFuture<Void>> futures) {
405 int i = 0;
406 Iterator<DeviceId> it = fromBucket.iterator();
407 while (it.hasNext() && i < count) {
408 DeviceId deviceId = it.next();
409 log.info("Setting {} as the master for {}", toNode.id(), deviceId);
410 futures.add(setRole(toNode.id(), deviceId, MASTER));
411 toBucket.add(deviceId);
412 it.remove();
413 i++;
414 }
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800415 }
416
Claudine Chiudce08152016-03-09 18:19:28 +0000417 /**
418 * Balances the nodes considering Region information.
419 *
420 * @param allControllerDevices controller nodes to devices map
421 * @return true: nodes balanced; false: nodes not balanced
422 */
423 private boolean balanceRolesUsingRegions(Map<ControllerNode, Set<DeviceId>> allControllerDevices) {
424 Set<Region> regions = regionService.getRegions();
425 if (regions.isEmpty()) {
426 return false; // no balancing was done using regions.
427 }
428
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800429 // Handle nodes belonging to regions
Claudine Chiudce08152016-03-09 18:19:28 +0000430 Set<ControllerNode> nodesInRegions = Sets.newHashSet();
431 for (Region region : regions) {
432 Map<ControllerNode, Set<DeviceId>> activeRegionControllers =
433 balanceRolesInRegion(region, allControllerDevices);
434 nodesInRegions.addAll(activeRegionControllers.keySet());
435 }
436
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800437 // Handle nodes not belonging to any region
Claudine Chiudce08152016-03-09 18:19:28 +0000438 Set<ControllerNode> nodesNotInRegions = Sets.difference(allControllerDevices.keySet(), nodesInRegions);
439 if (!nodesNotInRegions.isEmpty()) {
440 int deviceCount = 0;
441 Map<ControllerNode, Set<DeviceId>> controllerDevicesNotInRegions = new HashMap<>();
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800442 for (ControllerNode controllerNode : nodesNotInRegions) {
Claudine Chiudce08152016-03-09 18:19:28 +0000443 controllerDevicesNotInRegions.put(controllerNode, allControllerDevices.get(controllerNode));
444 deviceCount += allControllerDevices.get(controllerNode).size();
445 }
446 // Now re-balance the buckets until they are roughly even.
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800447 List<CompletableFuture<Void>> balanceBucketsFutures = Lists.newArrayList();
448 balanceControllerNodes(controllerDevicesNotInRegions, deviceCount, balanceBucketsFutures);
Claudine Chiudce08152016-03-09 18:19:28 +0000449
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800450 CompletableFuture<Void> balanceRolesFuture = allOf(
Claudine Chiudce08152016-03-09 18:19:28 +0000451 balanceBucketsFutures.toArray(new CompletableFuture[balanceBucketsFutures.size()]));
452
453 Futures.getUnchecked(balanceRolesFuture);
454 }
455 return true; // balancing was done using regions.
456 }
457
458 /**
459 * Balances the nodes in specified region.
460 *
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800461 * @param region region in which nodes are to be balanced
Claudine Chiudce08152016-03-09 18:19:28 +0000462 * @param allControllerDevices controller nodes to devices map
463 * @return controller nodes that were balanced
464 */
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800465 private Map<ControllerNode, Set<DeviceId>>
466 balanceRolesInRegion(Region region,
467 Map<ControllerNode, Set<DeviceId>> allControllerDevices) {
Claudine Chiudce08152016-03-09 18:19:28 +0000468
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800469 // Retrieve all devices associated with specified region
Claudine Chiudce08152016-03-09 18:19:28 +0000470 Set<DeviceId> devicesInRegion = regionService.getRegionDevices(region.id());
471 log.info("Region {} has {} devices.", region.id(), devicesInRegion.size());
472 if (devicesInRegion.isEmpty()) {
473 return new HashMap<>(); // no devices in this region, so nothing to balance.
474 }
475
476 List<Set<NodeId>> mastersList = region.masters();
477 log.info("Region {} has {} sets of masters.", region.id(), mastersList.size());
478 if (mastersList.isEmpty()) {
479 // TODO handle devices that belong to a region, which has no masters defined
480 return new HashMap<>(); // for now just leave devices alone
481 }
482
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800483 // Get the region's preferred set of masters
Claudine Chiudce08152016-03-09 18:19:28 +0000484 Set<DeviceId> devicesInMasters = Sets.newHashSet();
485 Map<ControllerNode, Set<DeviceId>> regionalControllerDevices =
486 getRegionsPreferredMasters(region, devicesInMasters, allControllerDevices);
487
488 // Now re-balance the buckets until they are roughly even.
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800489 List<CompletableFuture<Void>> balanceBucketsFutures = Lists.newArrayList();
490 balanceControllerNodes(regionalControllerDevices, devicesInMasters.size(), balanceBucketsFutures);
Claudine Chiudce08152016-03-09 18:19:28 +0000491
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800492 // Handle devices that are not currently mastered by the master node set
Claudine Chiudce08152016-03-09 18:19:28 +0000493 Set<DeviceId> devicesNotMasteredWithControllers = Sets.difference(devicesInRegion, devicesInMasters);
494 if (!devicesNotMasteredWithControllers.isEmpty()) {
495 // active controllers in master node set are already balanced, just
496 // assign device mastership in sequence
497 List<ControllerNode> sorted = new ArrayList<>(regionalControllerDevices.keySet());
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800498 Collections.sort(sorted, Comparator.comparingInt(o -> (regionalControllerDevices.get(o)).size()));
Claudine Chiudce08152016-03-09 18:19:28 +0000499 int deviceIndex = 0;
500 for (DeviceId deviceId : devicesNotMasteredWithControllers) {
501 ControllerNode cnode = sorted.get(deviceIndex % sorted.size());
502 balanceBucketsFutures.add(setRole(cnode.id(), deviceId, MASTER));
503 regionalControllerDevices.get(cnode).add(deviceId);
504 deviceIndex++;
505 }
506 }
507
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800508 CompletableFuture<Void> balanceRolesFuture =
509 allOf(balanceBucketsFutures.toArray(new CompletableFuture[balanceBucketsFutures.size()]));
Claudine Chiudce08152016-03-09 18:19:28 +0000510
511 Futures.getUnchecked(balanceRolesFuture);
512
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800513 // Update the map before returning
Claudine Chiudce08152016-03-09 18:19:28 +0000514 regionalControllerDevices.forEach((controllerNode, deviceIds) -> {
515 regionalControllerDevices.put(controllerNode, new HashSet<>(getDevicesOf(controllerNode.id())));
516 });
517
518 return regionalControllerDevices;
519 }
520
521 /**
522 * Get region's preferred set of master nodes - the first master node set that has at
523 * least one active node.
524 *
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800525 * @param region region for which preferred set of master nodes is requested
526 * @param devicesInMasters device set to track devices in preferred set of master nodes
Claudine Chiudce08152016-03-09 18:19:28 +0000527 * @param allControllerDevices controller nodes to devices map
528 * @return region's preferred master nodes (and devices that use them as masters)
529 */
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800530 private Map<ControllerNode, Set<DeviceId>>
531 getRegionsPreferredMasters(Region region,
532 Set<DeviceId> devicesInMasters,
533 Map<ControllerNode, Set<DeviceId>> allControllerDevices) {
Claudine Chiudce08152016-03-09 18:19:28 +0000534 Map<ControllerNode, Set<DeviceId>> regionalControllerDevices = new HashMap<>();
535 int listIndex = 0;
Thomas Vachuskaf2e09cb2017-11-06 15:17:06 -0800536 for (Set<NodeId> masterSet : region.masters()) {
Claudine Chiudce08152016-03-09 18:19:28 +0000537 log.info("Region {} masters set {} has {} nodes.",
538 region.id(), listIndex, masterSet.size());
539 if (masterSet.isEmpty()) { // nothing on this level
540 listIndex++;
541 continue;
542 }
543 // Create buckets reflecting current ownership.
544 for (NodeId nodeId : masterSet) {
Michele Santuari6ebb36e2016-03-28 10:12:04 -0700545 if (clusterService.getState(nodeId).isActive()) {
Claudine Chiudce08152016-03-09 18:19:28 +0000546 ControllerNode controllerNode = clusterService.getNode(nodeId);
547 Set<DeviceId> devicesOf = new HashSet<>(allControllerDevices.get(controllerNode));
548 regionalControllerDevices.put(controllerNode, devicesOf);
549 devicesInMasters.addAll(devicesOf);
550 log.info("Active Node {} has {} devices.", nodeId, devicesOf.size());
551 }
552 }
553 if (!regionalControllerDevices.isEmpty()) {
554 break; // now have a set of >0 active controllers
555 }
556 listIndex++; // keep on looking
557 }
558 return regionalControllerDevices;
559 }
Thomas Vachuska1e68bdd2014-11-29 13:53:10 -0800560
alshabib339a3d92014-09-26 17:54:32 -0700561 public class InternalDelegate implements MastershipStoreDelegate {
alshabib339a3d92014-09-26 17:54:32 -0700562 @Override
563 public void notify(MastershipEvent event) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700564 post(event);
alshabib339a3d92014-09-26 17:54:32 -0700565 }
alshabib339a3d92014-09-26 17:54:32 -0700566 }
567
Jordan Halterman713830d2017-10-07 13:40:44 -0700568 private class InternalUpgradeEventListener implements UpgradeEventListener {
569 @Override
570 public void event(UpgradeEvent event) {
571 if (rebalanceRolesOnUpgrade &&
572 (event.type() == UpgradeEvent.Type.COMMITTED || event.type() == UpgradeEvent.Type.RESET)) {
573 balanceRoles();
574 }
575 }
576 }
577
Ayaka Koshibe16609692014-09-23 12:46:15 -0700578}