fc53f9545e2bf1b42c3073d82a1b93c402136686
[controller.git] / opendaylight / md-sal / sal-distributed-eos / src / main / java / org / opendaylight / controller / cluster / entityownership / selectionstrategy / LeastLoadedCandidateSelectionStrategy.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.entityownership.selectionstrategy;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNullElse;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Strings;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.Map;
18
19 /**
20  * The LeastLoadedCandidateSelectionStrategy assigns ownership for an entity to the candidate which owns the least
21  * number of entities.
22  */
23 public class LeastLoadedCandidateSelectionStrategy extends AbstractEntityOwnerSelectionStrategy {
24     private final Map<String, Long> localStatistics = new HashMap<>();
25
26     protected LeastLoadedCandidateSelectionStrategy(final long selectionDelayInMillis,
27             final Map<String, Long> initialStatistics) {
28         super(selectionDelayInMillis, initialStatistics);
29
30         localStatistics.putAll(initialStatistics);
31     }
32
33     @Override
34     public String newOwner(final String currentOwner, final Collection<String> viableCandidates) {
35         checkArgument(viableCandidates.size() > 0);
36         String leastLoadedCandidate = null;
37         long leastLoadedCount = Long.MAX_VALUE;
38
39         if (!Strings.isNullOrEmpty(currentOwner)) {
40             long localVal = requireNonNullElse(localStatistics.get(currentOwner), 0L);
41             localStatistics.put(currentOwner, localVal - 1);
42         }
43
44         for (String candidateName : viableCandidates) {
45             long val = requireNonNullElse(localStatistics.get(candidateName), 0L);
46             if (val < leastLoadedCount) {
47                 leastLoadedCount = val;
48                 leastLoadedCandidate = candidateName;
49             }
50         }
51
52         if (leastLoadedCandidate == null) {
53             leastLoadedCandidate = viableCandidates.iterator().next();
54         }
55
56         localStatistics.put(leastLoadedCandidate, leastLoadedCount + 1);
57         return leastLoadedCandidate;
58     }
59
60     @VisibleForTesting
61     Map<String, Long> getLocalStatistics() {
62         return localStatistics;
63     }
64 }