Choose owner when all candidate registrations received.
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / 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
9 package org.opendaylight.controller.cluster.datastore.entityownership.selectionstrategy;
10
11 import com.google.common.base.MoreObjects;
12 import java.util.Collection;
13 import java.util.HashMap;
14 import java.util.Map;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17
18 /**
19  * The LeastLoadedCandidateSelectionStrategy assigns ownership for an entity to the candidate which owns the least
20  * number of entities.
21  */
22 public class LeastLoadedCandidateSelectionStrategy extends AbstractEntityOwnerSelectionStrategy {
23     private static final Logger LOG = LoggerFactory.getLogger(LeastLoadedCandidateSelectionStrategy.class);
24
25     private Map<String, Long> localStatistics = new HashMap<>();
26
27     protected LeastLoadedCandidateSelectionStrategy(long selectionDelayInMillis) {
28         super(selectionDelayInMillis);
29     }
30
31     @Override
32     public String newOwner(Collection<String> viableCandidates, Map<String, Long> statistics) {
33         String leastLoadedCandidate = null;
34         long leastLoadedCount = Long.MAX_VALUE;
35
36         for(String candidateName : viableCandidates){
37             long val = MoreObjects.firstNonNull(statistics.get(candidateName), 0L);
38             long localVal = MoreObjects.firstNonNull(localStatistics.get(candidateName), 0L);
39             if(val < localVal){
40                 LOG.debug("Local statistic higher - Candidate : {}, local statistic : {}, provided statistic : {}",
41                         candidateName, localVal, val);
42                 val = localVal;
43             } else {
44                 LOG.debug("Provided statistic higher - Candidate : {}, local statistic : {}, provided statistic : {}",
45                         candidateName, localVal, val);
46                 localStatistics.put(candidateName, val);
47             }
48             if(val < leastLoadedCount){
49                 leastLoadedCount = val;
50                 leastLoadedCandidate = candidateName;
51             }
52         }
53
54         if(leastLoadedCandidate == null){
55             leastLoadedCandidate = viableCandidates.iterator().next();
56         }
57
58         localStatistics.put(leastLoadedCandidate, leastLoadedCount + 1);
59         return leastLoadedCandidate;
60     }
61 }