import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
static final String ACTIVE_HOST_CACHE = "hosttracker.ActiveHosts";
static final String INACTIVE_HOST_CACHE = "hosttracker.InactiveHosts";
private static final Logger logger = LoggerFactory.getLogger(HostTracker.class);
- private IHostFinder hostFinder;
- private ConcurrentMap<InetAddress, HostNodeConnector> hostsDB;
+ protected final Set<IHostFinder> hostFinder = new CopyOnWriteArraySet<IHostFinder>();;
+ protected ConcurrentMap<InetAddress, HostNodeConnector> hostsDB;
/*
* Following is a list of hosts which have been requested by NB APIs to be
* added, but either the switch or the port is not sup, so they will be
private final Set<IfNewHostNotify> newHostNotify = Collections.synchronizedSet(new HashSet<IfNewHostNotify>());
private ITopologyManager topologyManager;
- private IClusterContainerServices clusterContainerService = null;
- private ISwitchManager switchManager = null;
+ protected IClusterContainerServices clusterContainerService = null;
+ protected ISwitchManager switchManager = null;
private Timer timer;
private Timer arpRefreshTimer;
private String containerName = null;
private ExecutorService executor;
+ protected boolean stopping;
+ private static boolean hostRefresh = true;
+ private static int hostRetryCount = 5;
private static class ARPPending {
protected InetAddress hostIP;
protected short sent_count;
hostTrackerCallable = callable;
}
}
+
// This list contains the hosts for which ARP requests are being sent
// periodically
ConcurrentMap<InetAddress, ARPPending> ARPPendingList;
nonClusterObjectCreate();
allocateCache();
retrieveCache();
+ stopping = false;
timer = new Timer();
timer.schedule(new OutStandingARPHandler(), 4000, 4000);
logger.debug("startUp: Caches created, timers started");
}
- @SuppressWarnings("deprecation")
private void allocateCache() {
if (this.clusterContainerService == null) {
logger.error("un-initialized clusterContainerService, can't create cache");
logger.debug("Cache successfully created for HostTracker");
}
- @SuppressWarnings({ "unchecked", "deprecation" })
+ @SuppressWarnings({ "unchecked" })
private void retrieveCache() {
if (this.clusterContainerService == null) {
logger.error("un-initialized clusterContainerService, can't retrieve cache");
failedARPReqList = new ConcurrentHashMap<InetAddress, ARPPending>();
}
-
public void shutDown() {
}
}
public void setArpHandler(IHostFinder hostFinder) {
- this.hostFinder = hostFinder;
+ if (this.hostFinder != null) {
+ this.hostFinder.add(hostFinder);
+ }
}
public void unsetArpHandler(IHostFinder hostFinder) {
- if (this.hostFinder == hostFinder) {
+ if (this.hostFinder != null) {
logger.debug("Arp Handler Service removed!");
- this.hostFinder = null;
+ this.hostFinder.remove(hostFinder);
}
}
@Override
public Future<HostNodeConnector> discoverHost(InetAddress networkAddress) {
if (executor == null) {
- logger.error("discoverHost: Null executor");
+ logger.debug("discoverHost: Null executor");
return null;
}
Callable<HostNodeConnector> worker = new HostTrackerCallable(this, networkAddress);
/* Add this host to ARPPending List for any potential retries */
- AddtoARPPendingList(networkAddress);
+ addToARPPendingList(networkAddress);
logger.debug("hostFind(): Host Not Found for IP: {}, Inititated Host Discovery ...",
networkAddress.getHostAddress());
/* host is not found, initiate a discovery */
-
- hostFinder.find(networkAddress);
+ for (IHostFinder hf : hostFinder) {
+ hf.find(networkAddress);
+ }
return null;
}
@Override
public Set<HostNodeConnector> getAllHosts() {
- Set<HostNodeConnector> allHosts = new HashSet<HostNodeConnector>();
- for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
- HostNodeConnector host = entry.getValue();
- allHosts.add(host);
- }
- logger.debug("Exiting getAllHosts, Found {} Hosts", allHosts.size());
+ Set<HostNodeConnector> allHosts = new HashSet<HostNodeConnector>(hostsDB.values());
return allHosts;
}
list.add(host);
}
}
- logger.debug("getActiveStaticHosts(): Found {} Hosts", list.size());
return list;
}
@Override
public Set<HostNodeConnector> getInactiveStaticHosts() {
- Set<HostNodeConnector> list = new HashSet<HostNodeConnector>();
- for (Entry<NodeConnector, HostNodeConnector> entry : inactiveStaticHosts.entrySet()) {
- list.add(entry.getValue());
- }
- logger.debug("getInactiveStaticHosts(): Found {} Hosts", list.size());
+ Set<HostNodeConnector> list = new HashSet<HostNodeConnector>(inactiveStaticHosts.values());
return list;
}
- private void AddtoARPPendingList(InetAddress networkAddr) {
+ private void addToARPPendingList(InetAddress networkAddr) {
ARPPending arphost = new ARPPending();
arphost.setHostIP(networkAddr);
public void setCallableOnPendingARP(InetAddress networkAddr, HostTrackerCallable callable) {
ARPPending arphost;
- for (Entry <InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
+ for (Entry<InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
arphost = entry.getValue();
if (arphost.getHostIP().equals(networkAddr)) {
arphost.setHostTrackerCallable(callable);
// Remove the arphost from ARPPendingList as it has been learned now
logger.debug("Host Removed from ARPPending List, IP: {}", networkAddr);
HostTrackerCallable htCallable = arphost.getHostTrackerCallable();
- if (htCallable != null)
+ if (htCallable != null) {
htCallable.wakeup();
+ }
return;
}
* It could have been a host from the FailedARPReqList
*/
- if (failedARPReqList.containsKey(networkAddr)) {
+ if (failedARPReqList.containsKey(networkAddr)) {
failedARPReqList.remove(networkAddr);
logger.debug("Host Removed from FailedARPReqList List, IP: {}", networkAddr);
}
replaceHost(networkAddr, removedHost, host);
return;
} else {
- logger.error("Host to be removed not found in hostsDB. Host {}", removedHost);
+ logger.error("Host to be removed not found in hostsDB");
}
}
- if (removedHost == null) {
- // It is a new host
- learnNewHost(host);
- }
+ // It is a new host
+ learnNewHost(host);
/* check if there is an outstanding request for this host */
processPendingARPReqs(networkAddr);
@Override
public void hostListener(HostNodeConnector host) {
-
- logger.debug("ARP received for Host: IP {}, MAC {}, {}", host.getNetworkAddress().getHostAddress(),
+ logger.debug("Received for Host: IP {}, MAC {}, {}", host.getNetworkAddress().getHostAddress(),
HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host);
if (hostExists(host)) {
HostNodeConnector existinghost = hostsDB.get(host.getNetworkAddress());
ta.notifyHTClientHostRemoved(host);
}
} catch (Exception e) {
- logger.error("Exception on callback", e);
+ logger.error("Exception on new host notification", e);
}
}
}
* @param currentTier
* The Tier on which n belongs
*/
+ @SuppressWarnings("unused")
private void updateSwitchTiers(Node n, int currentTier) {
Map<Node, Set<Edge>> ndlinks = topologyManager.getNodeEdges();
if (ndlinks == null) {
}
// This is the case where Tier was never set for this node
Tier t = (Tier) switchManager.getNodeProp(n, Tier.TierPropName);
- if (t == null)
+ if (t == null) {
return true;
- if (t.getValue() == 0)
+ }
+ if (t.getValue() == 0) {
return true;
- else if (t.getValue() > tier)
+ } else if (t.getValue() > tier) {
return true;
+ }
return false;
}
* cleanup is performed during cases such as Topology Change where the
* existing Tier values might become incorrect
*/
+ @SuppressWarnings("unused")
private void clearTiers() {
Set<Node> nodes = null;
if (switchManager == null) {
int num = 1;
for (ArrayList<String> hierarchy : hierarchies) {
StringBuffer buf = new StringBuffer();
- buf.append("Hierarchy#" + num + " : ");
+ buf.append("Hierarchy#").append(num).append(" : ");
for (String switchName : hierarchy) {
- buf.append(switchName + "/");
+ buf.append(switchName).append("/");
}
logger.debug("{} -> {}", getContainerName(), buf);
num++;
@Override
public List<List<String>> getHostNetworkHierarchy(InetAddress hostAddress) {
HostNodeConnector host = hostQuery(hostAddress);
- if (host == null)
+ if (host == null) {
return null;
+ }
List<List<String>> hierarchies = new ArrayList<List<String>>();
ArrayList<String> currHierarchy = new ArrayList<String>();
int result = 0;
for (int i = 0; i < hex.length(); i++) {
result = (int) ((dpid >> (i * 8)) & 0xff);
- if (result == 0)
+ if (result == 0) {
continue;
- if (result < 0x30)
+ }
+ if (result < 0x30) {
result += 0x40;
+ }
sb.append(String.format("%c", result));
}
return sb.reverse().toString();
*/
@SuppressWarnings("unchecked")
private void updateCurrentHierarchy(Node node, ArrayList<String> currHierarchy, List<List<String>> fullHierarchy) {
- // currHierarchy.add(String.format("%x", currSw.getId()));
currHierarchy.add(dpidToHostNameHack((Long) node.getID()));
// Shallow copy as required
ArrayList<String> currHierarchyClone = (ArrayList<String>) currHierarchy.clone();
public void subnetNotify(Subnet sub, boolean add) {
logger.debug("Received subnet notification: {} add={}", sub, add);
if (add) {
- for (Entry <InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
+ for (Entry<InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
ARPPending arphost;
arphost = entry.getValue();
if (hostFinder == null) {
logger.warn("ARPHandler Services are not available on subnet addition");
continue;
}
- logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress());
- hostFinder.find(arphost.getHostIP());
+ logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress());
+ for (IHostFinder hf : hostFinder) {
+ hf.find(arphost.getHostIP());
+ }
}
}
}
class OutStandingARPHandler extends TimerTask {
@Override
public void run() {
+ if (stopping) {
+ return;
+ }
ARPPending arphost;
-
/* This routine runs every 4 seconds */
logger.trace("Number of Entries in ARP Pending/Failed Lists: ARPPendingList = {}, failedARPReqList = {}",
ARPPendingList.size(), failedARPReqList.size());
- for (Entry <InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
+ for (Entry<InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
arphost = entry.getValue();
if (hostsDB.containsKey(arphost.getHostIP())) {
- // this host is already learned, shouldn't be in ARPPendingList
+ // this host is already learned, shouldn't be in
+ // ARPPendingList
// Remove it and continue
logger.warn("Learned Host {} found in ARPPendingList", arphost.getHostIP());
ARPPendingList.remove(entry.getKey());
continue;
}
- if (arphost.getSent_count() < switchManager.getHostRetryCount()) {
+ if (arphost.getSent_count() < hostRetryCount) {
/*
* No reply has been received of first ARP Req, send the
- * next one. Before sending the ARP, check if ARPHandler
- * is available or not
+ * next one. Before sending the ARP, check if ARPHandler is
+ * available or not
*/
if (hostFinder == null) {
logger.warn("ARPHandler Services are not available for Outstanding ARPs");
continue;
}
- hostFinder.find(arphost.getHostIP());
+ for (IHostFinder hf : hostFinder) {
+ hf.find(arphost.getHostIP());
+ }
arphost.sent_count++;
logger.debug("ARP Sent from ARPPending List, IP: {}", arphost.getHostIP().getHostAddress());
- } else if (arphost.getSent_count() >= switchManager.getHostRetryCount()) {
+ } else if (arphost.getSent_count() >= hostRetryCount) {
/*
- * ARP requests have been sent without receiving a
- * reply, remove this from the pending list
+ * ARP requests have been sent without receiving a reply,
+ * remove this from the pending list
*/
ARPPendingList.remove(entry.getKey());
logger.debug("ARP reply not received after multiple attempts, removing from Pending List IP: {}",
private class ARPRefreshHandler extends TimerTask {
@Override
- @SuppressWarnings("deprecation")
public void run() {
+ if (stopping) {
+ return;
+ }
if ((clusterContainerService != null) && !clusterContainerService.amICoordinator()) {
return;
}
- if ((switchManager != null) && !switchManager.isHostRefreshEnabled()) {
+ if (!hostRefresh) {
/*
- * The host probe procedure was disabled by CLI
+ * The host probe procedure is turned off
*/
return;
}
short arp_cntdown = host.getArpSendCountDown();
arp_cntdown--;
- if (arp_cntdown > switchManager.getHostRetryCount()) {
+ if (arp_cntdown > hostRetryCount) {
host.setArpSendCountDown(arp_cntdown);
} else if (arp_cntdown <= 0) {
/*
*/
removeKnownHost(entry.getKey());
notifyHostLearnedOrRemoved(host, false);
- } else if (arp_cntdown <= switchManager.getHostRetryCount()) {
+ } else if (arp_cntdown <= hostRetryCount) {
/*
* Use the services of arphandler to check if host is still
* there
* probe. However, continue the age out the hosts since
* we don't know if the host is indeed out there or not.
*/
- logger.warn("ARPHandler is not avaialable, can't send the probe");
+ logger.trace("ARPHandler is not avaialable, can't send the probe");
continue;
}
- hostFinder.probe(host);
+ for (IHostFinder hf : hostFinder) {
+ hf.probe(host);
+ }
}
}
}
* indicating the result of this action.
*/
- public Status addStaticHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) {
+ protected Status addStaticHostReq(InetAddress networkAddr, byte[] dataLayerAddress, NodeConnector nc, short vlan) {
if (dataLayerAddress.length != NetUtils.MACAddrLengthInBytes) {
return new Status(StatusCode.BADREQUEST, "Invalid MAC address");
}
// northbound request
HostNodeConnector transHost = hostsDB.get(networkAddr);
transHost.setStaticHost(true);
- return new Status(StatusCode.SUCCESS, null);
+ return new Status(StatusCode.SUCCESS);
}
if (hostsDB.get(networkAddr) != null) {
// There is already a host with this IP address (but behind
// a different (switch, port, vlan) tuple. Return an error
- return new Status(StatusCode.CONFLICT, "Existing IP, Use PUT to update");
+ return new Status(StatusCode.CONFLICT, "Host with this IP already exists.");
}
host.setStaticHost(true);
/*
logger.debug("Switch or switchport is not up, adding host {} to inactive list",
networkAddr.getHostName());
}
- return new Status(StatusCode.SUCCESS, null);
+ return new Status(StatusCode.SUCCESS);
} catch (ConstructionException e) {
logger.error("", e);
return new Status(StatusCode.INTERNALERROR, "Host could not be created");
@Override
public void notifyNode(Node node, UpdateType type, Map<String, Property> propMap) {
- if (node == null)
+ if (node == null) {
return;
+ }
switch (type) {
case REMOVED:
@Override
public void notifyNodeConnector(NodeConnector nodeConnector, UpdateType type, Map<String, Property> propMap) {
- if (nodeConnector == null)
+ if (nodeConnector == null) {
return;
+ }
boolean up = false;
switch (type) {
public Status addStaticHost(String networkAddress, String dataLayerAddress, NodeConnector nc, String vlan) {
try {
InetAddress ip = InetAddress.getByName(networkAddress);
- if (nc == null) {
- return new Status(StatusCode.BADREQUEST, "Invalid NodeId");
+ short vl = 0;
+ if (vlan != null && !vlan.isEmpty()) {
+ vl = Short.decode(vlan);
+ if (vl < 1 || vl > 4095) {
+ return new Status(StatusCode.BADREQUEST, "Host vlan out of range [1 - 4095]");
+ }
}
- return addStaticHostReq(ip, HexEncode.bytesFromHexString(dataLayerAddress), nc, Short.valueOf(vlan));
+
+ return addStaticHostReq(ip, HexEncode.bytesFromHexString(dataLayerAddress), nc, vl);
+
} catch (UnknownHostException e) {
- logger.error("", e);
- return new Status(StatusCode.BADREQUEST, "Invalid Address");
+ logger.debug("Invalid host IP specified when adding static host", e);
+ return new Status(StatusCode.BADREQUEST, "Invalid Host IP Address");
+ } catch (NumberFormatException nfe) {
+ logger.debug("Invalid host vlan or MAC specified when adding static host", nfe);
+ return new Status(StatusCode.BADREQUEST, "Invalid Host vLan/MAC");
}
}
@Override
public Status removeStaticHost(String networkAddress) {
- InetAddress address;
try {
- address = InetAddress.getByName(networkAddress);
+ InetAddress address = InetAddress.getByName(networkAddress);
return removeStaticHostReq(address);
} catch (UnknownHostException e) {
- logger.error("", e);
- return new Status(StatusCode.BADREQUEST, "Invalid Address");
+ logger.debug("Invalid IP Address when trying to remove host", e);
+ return new Status(StatusCode.BADREQUEST, "Invalid IP Address when trying to remove host");
}
}
ARPPending arphost;
HostNodeConnector host = null;
- logger.debug("handleNodeConnectorStatusUp {}", nodeConnector);
+ logger.trace("handleNodeConnectorStatusUp {}", nodeConnector);
- for (Entry <InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
+ for (Entry<InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
arphost = entry.getValue();
- logger.debug("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress());
+ logger.trace("Sending the ARP from FailedARPReqList fors IP: {}", arphost.getHostIP().getHostAddress());
if (hostFinder == null) {
logger.warn("ARPHandler is not available at interface up");
logger.warn("Since this event is missed, host(s) connected to interface {} may not be discovered",
try {
byte[] dataLayerAddress = NetUtils.getBroadcastMACAddr();
host = new HostNodeConnector(dataLayerAddress, arphost.getHostIP(), nodeConnector, (short) 0);
- hostFinder.probe(host);
+ for (IHostFinder hf : hostFinder) {
+ hf.probe(host);
+ }
} catch (ConstructionException e) {
logger.debug("HostNodeConnector couldn't be created for Host: {}, NodeConnector: {}",
arphost.getHostIP(), nodeConnector);
logger.error("", e);
}
- logger.debug("Done. handleNodeConnectorStatusUp {}", nodeConnector);
}
host = inactiveStaticHosts.get(nodeConnector);
}
private void handleNodeConnectorStatusDown(NodeConnector nodeConnector) {
- logger.debug("handleNodeConnectorStatusDown {}", nodeConnector);
+ logger.trace("handleNodeConnectorStatusDown {}", nodeConnector);
for (Entry<InetAddress, HostNodeConnector> entry : hostsDB.entrySet()) {
HostNodeConnector host = entry.getValue();
}
public String getContainerName() {
- if (containerName == null)
+ if (containerName == null) {
return GlobalConstants.DEFAULT.toString();
+ }
return containerName;
}
* calls
*
*/
- void stop(){
+ void stop() {
}
void stopping() {
+ stopping = true;
arpRefreshTimer.cancel();
timer.cancel();
- executor.shutdown();
+ executor.shutdownNow();
}
@Override
public void edgeOverUtilized(Edge edge) {
- // TODO Auto-generated method stub
}
@Override
public void edgeUtilBackToNormal(Edge edge) {
- // TODO Auto-generated method stub
}
@Override
- public void entryCreated(InetAddress key, String cacheName,
- boolean originLocal) {
- if (originLocal) return;
+ public void entryCreated(InetAddress key, String cacheName, boolean originLocal) {
+ if (originLocal) {
+ return;
+ }
processPendingARPReqs(key);
}
@Override
- public void entryUpdated(InetAddress key, HostNodeConnector new_value,
- String cacheName, boolean originLocal) {
+ public void entryUpdated(InetAddress key, HostNodeConnector new_value, String cacheName, boolean originLocal) {
}
@Override
- public void entryDeleted(InetAddress key, String cacheName,
- boolean originLocal) {
+ public void entryDeleted(InetAddress key, String cacheName, boolean originLocal) {
}
private void registerWithOSGIConsole() {
@Override
public String getHelp() {
- // TODO Auto-generated method stub
return null;
}
public void _dumpPendingARPReqList(CommandInterpreter ci) {
ARPPending arphost;
- for (Entry <InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
+ for (Entry<InetAddress, ARPPending> entry : ARPPendingList.entrySet()) {
arphost = entry.getValue();
ci.println(arphost.getHostIP().toString());
}
public void _dumpFailedARPReqList(CommandInterpreter ci) {
ARPPending arphost;
- for (Entry <InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
+ for (Entry<InetAddress, ARPPending> entry : failedARPReqList.entrySet()) {
arphost = entry.getValue();
ci.println(arphost.getHostIP().toString());
}