1
#include "source/common/network/connection_balancer_impl.h"
2

            
3
#include <limits>
4

            
5
namespace Envoy {
6
namespace Network {
7

            
8
14
void ExactConnectionBalancerImpl::registerHandler(BalancedConnectionHandler& handler) {
9
14
  absl::MutexLock lock(lock_);
10
14
  handlers_.push_back(&handler);
11
14
}
12

            
13
14
void ExactConnectionBalancerImpl::unregisterHandler(BalancedConnectionHandler& handler) {
14
14
  absl::MutexLock lock(lock_);
15
  // This could be made more efficient in various ways, but the number of listeners is generally
16
  // small and this is a rare operation so we can start with this and optimize later if this
17
  // becomes a perf bottleneck.
18
14
  handlers_.erase(std::find(handlers_.begin(), handlers_.end(), &handler));
19
14
}
20

            
21
BalancedConnectionHandler&
22
46
ExactConnectionBalancerImpl::pickTargetHandler(BalancedConnectionHandler&) {
23
46
  BalancedConnectionHandler* min_connection_handler = nullptr;
24
46
  {
25
46
    absl::MutexLock lock(lock_);
26
46
    uint64_t min_connections = std::numeric_limits<uint64_t>::max();
27
70
    for (BalancedConnectionHandler* handler : handlers_) {
28
70
      const uint64_t connections = handler->numConnections();
29
70
      if (connections < min_connections) {
30
58
        min_connections = connections;
31
58
        min_connection_handler = handler;
32
58
      }
33
70
    }
34

            
35
46
    min_connection_handler->incNumConnections(); // NOLINT(clang-analyzer-core.CallAndMessage)
36
46
  }
37

            
38
46
  return *min_connection_handler;
39
46
}
40

            
41
} // namespace Network
42
} // namespace Envoy