2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
3 * This program and the accompanying materials are made available under the
4 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
5 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.sal.connector.remoterpc;
10 import com.google.common.base.Optional;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13 import org.zeromq.ZMQ;
14 import java.net.UnknownHostException;
15 import java.util.Collection;
16 import java.util.concurrent.ConcurrentHashMap;
20 * Manages creation of {@link RpcSocket} and their registration with {@link ZMQ.Poller}
22 public class SocketManager implements AutoCloseable{
23 private static final Logger log = LoggerFactory.getLogger(SocketManager.class);
26 * RpcSockets mapped by network address its connected to
28 private ConcurrentHashMap<String, RpcSocket> managedSockets = new ConcurrentHashMap<String, RpcSocket>();
30 private ZMQ.Poller _poller = new ZMQ.Poller(2); //randomly selected size. Poller grows automatically
33 * Returns a {@link RpcSocket} for the given address
34 * @param address network address with port eg: 10.199.199.20:5554
37 public RpcSocket getManagedSocket(String address) throws IllegalArgumentException {
39 if (!address.matches("(tcp://)(.*)(:)(\\d*)")) {
40 throw new IllegalArgumentException("Address must of format 'tcp://<ip address>:<port>' but is " + address);
43 if (!managedSockets.containsKey(address)) {
44 log.debug("{} Creating new socket for {}", Thread.currentThread().getName());
45 RpcSocket socket = new RpcSocket(address, _poller);
46 managedSockets.put(address, socket);
49 return managedSockets.get(address);
53 * Returns a {@link RpcSocket} for the given {@link ZMQ.Socket}
57 public Optional<RpcSocket> getManagedSocketFor(ZMQ.Socket socket) {
58 for (RpcSocket rpcSocket : managedSockets.values()) {
59 if (rpcSocket.getSocket().equals(socket)) {
60 return Optional.of(rpcSocket);
63 return Optional.absent();
67 * Return a collection of all managed sockets
70 public Collection<RpcSocket> getManagedSockets() {
71 return managedSockets.values();
75 * Returns the {@link ZMQ.Poller}
78 public ZMQ.Poller getPoller() {
83 * This should be called when stopping the server to close all the sockets
87 public void close() throws Exception {
88 log.debug("Stopping...");
89 for (RpcSocket socket : managedSockets.values()) {
92 managedSockets.clear();