Host updates for Topology
[controller.git] / opendaylight / hosttracker_new / implementation / src / main / java / org / opendaylight / controller / hosttracker / internal / DeviceManagerImpl.java
index bda13723113aac7ade179a6804a7b1f655b7d59d..0a6c2713dde0a2e6a0087f7d7c889e5d77668765 100755 (executable)
@@ -38,6 +38,7 @@ import static org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl
 import static org.opendaylight.controller.hosttracker.internal.DeviceManagerImpl.DeviceUpdate.Change.DELETE;
 
 import java.net.InetAddress;
+import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Collection;
@@ -67,11 +68,17 @@ import org.opendaylight.controller.hosttracker.IEntityClass;
 import org.opendaylight.controller.hosttracker.IEntityClassListener;
 import org.opendaylight.controller.hosttracker.IEntityClassifierService;
 import org.opendaylight.controller.hosttracker.IfIptoHost;
+import org.opendaylight.controller.hosttracker.IfNewHostNotify;
 import org.opendaylight.controller.hosttracker.SwitchPort;
 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
+import org.opendaylight.controller.sal.core.ConstructionException;
 import org.opendaylight.controller.sal.core.Edge;
+import org.opendaylight.controller.sal.core.Host;
+import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
+import org.opendaylight.controller.sal.core.Tier;
+import org.opendaylight.controller.sal.core.UpdateType;
 import org.opendaylight.controller.sal.packet.ARP;
 import org.opendaylight.controller.sal.packet.Ethernet;
 import org.opendaylight.controller.sal.packet.IDataPacketService;
@@ -79,11 +86,16 @@ import org.opendaylight.controller.sal.packet.IListenDataPacket;
 import org.opendaylight.controller.sal.packet.Packet;
 import org.opendaylight.controller.sal.packet.PacketResult;
 import org.opendaylight.controller.sal.packet.RawPacket;
+import org.opendaylight.controller.sal.packet.address.DataLinkAddress;
+import org.opendaylight.controller.sal.packet.address.EthernetAddress;
 import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
+import org.opendaylight.controller.sal.utils.HexEncode;
 import org.opendaylight.controller.sal.utils.ListenerDispatcher;
 import org.opendaylight.controller.sal.utils.MultiIterator;
+import org.opendaylight.controller.sal.utils.NetUtils;
 import org.opendaylight.controller.sal.utils.SingletonTask;
 import org.opendaylight.controller.sal.utils.Status;
+import org.opendaylight.controller.sal.utils.StatusCode;
 import org.opendaylight.controller.switchmanager.ISwitchManager;
 import org.opendaylight.controller.topologymanager.ITopologyManager;
 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
@@ -290,6 +302,10 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
      */
     protected ListenerDispatcher<String, IDeviceListener> deviceListeners;
 
+    /**
+     * Using the IfNewHostNotify to notify listeners of host changes.
+     */
+    private Set<IfNewHostNotify> newHostNotify = Collections.synchronizedSet(new HashSet<IfNewHostNotify>());
     /**
      * A device update event to be dispatched
      */
@@ -429,6 +445,14 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
     // Dependency injection
     // ********************
 
+    void setNewHostNotify(IfNewHostNotify obj){
+        this.newHostNotify.add(obj);
+    }
+
+    void unsetNewHostNotify(IfNewHostNotify obj){
+        this.newHostNotify.remove(obj);
+    }
+
     void setDataPacketService(IDataPacketService s) {
         this.dataPacketService = s;
     }
@@ -780,11 +804,11 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
         if (inPkt == null) {
             return PacketResult.IGNORED;
         }
-        try {
-            throw new Exception("Sample");
-        } catch (Exception e) {
-            logger.error("Sample stack trace", e);
-        }
+//        try {
+//            throw new Exception("Sample");
+//        } catch (Exception e) {
+//            logger.error("Sample stack trace", e);
+//        }
 
         Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt);
         Ethernet eth;
@@ -1166,6 +1190,7 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
         logger.info("Primary index {}", primaryIndex);
         ArrayList<Long> deleteQueue = null;
         LinkedList<DeviceUpdate> deviceUpdates = null;
+        Device oldDevice = null;
         Device device = null;
 
         // we may need to restart the learning process if we detect
@@ -1321,7 +1346,7 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
                 // modified this Device).
                 if (!res)
                     continue;
-
+                oldDevice = device;
                 device = newDevice;
                 // update indices
                 if (!updateIndices(device, deviceKey)) {
@@ -1350,7 +1375,7 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
                 if (moved) {
                     // we count device moved events in
                     // sendDeviceMovedNotification()
-                    sendDeviceMovedNotification(device);
+                    sendDeviceMovedNotification(device, oldDevice);
                     if (logger.isTraceEnabled()) {
                         logger.trace("Device moved: attachment points {},"
                                 + "entities {}", device.attachmentPoints,
@@ -1444,9 +1469,71 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
 
     protected void notifyListeners(List<IDeviceListener> listeners,
             DeviceUpdate update) {
-        if (listeners == null) {
+       // Topology update is for some reason outside of listeners registry
+       // logic
+        Entity[] ents = update.device.getEntities();
+        Entity e = ents[ents.length-1];
+        NodeConnector p = e.getPort();
+        Node node = p.getNode();
+        Host h = null;
+        try {
+            byte[] mac = NetUtils.longToByteArray6(e.getMacAddress());
+            DataLinkAddress dla = new EthernetAddress(
+                    mac);
+            e.getIpv4Address();
+            InetAddress.getAllByName(e.getIpv4Address().toString());
+            h = new org.opendaylight.controller.sal.core.Host(dla,
+                    InetAddress.getByName(e.getIpv4Address().toString()));
+        } catch (ConstructionException ce) {
+            p = null;
+            h = null;
+        } catch (UnknownHostException ue){
+            p = null;
+            h = null;
+        }
+
+        if (topology != null && p != null && h != null) {
+            if (update.change.equals(DeviceUpdate.Change.ADD)) {
+                Tier tier = new Tier(1);
+                switchManager.setNodeProp(node, tier);
+                topology.updateHostLink(p, h, UpdateType.ADDED, null);
+            } else {
+                // No need to reset the tiering if no other hosts are currently
+                // connected
+                // If this switch was discovered to be an access switch, it
+                // still is even if the host is down
+                Tier tier = new Tier(0);
+                switchManager.setNodeProp(node, tier);
+                topology.updateHostLink(p, h, UpdateType.REMOVED, null);
+            }
+        }
+
+        if (listeners == null && newHostNotify.isEmpty()) {
             return;
         }
+        /**
+         * TODO: IfNewHostNotify is needed for current controller API.
+         * Adding logic so that existing apps (like SimpleForwardingManager)
+         * work.  IDeviceListener adds additional methods and uses IListener's
+         * callback ordering.  The two interfaces need to be merged.
+         */
+
+        for (IfNewHostNotify notify : newHostNotify){
+            switch (update.change) {
+            case ADD:
+                notify.notifyHTClient(update.device.toHostNodeConnector());
+                break;
+            case DELETE:
+                notify.notifyHTClientHostRemoved(update.device.toHostNodeConnector());
+                break;
+            case CHANGE:
+            }
+        }
+
+        /**
+         * TODO: Remove this section as IDeviceListener functionality gets
+         * merged with IfNewHostNotify
+         */
         for (IDeviceListener listener : listeners) {
             switch (update.change) {
             case ADD:
@@ -1866,6 +1953,19 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
             }
         }
     }
+    /**
+     * Send update notifications to listeners.
+     * IfNewHostNotify listeners need to remove old device and add new device.
+     * @param device
+     * @param oldDevice
+     */
+    protected void sendDeviceMovedNotification(Device device, Device oldDevice){
+        for (IfNewHostNotify notify : newHostNotify){
+                notify.notifyHTClientHostRemoved(oldDevice.toHostNodeConnector());
+                notify.notifyHTClient(device.toHostNodeConnector());
+            }
+        sendDeviceMovedNotification(device);
+        }
 
     /**
      * this method will reclassify and reconcile a device - possibilities are -
@@ -2099,8 +2199,16 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
 
     @Override
     public Set<HostNodeConnector> getActiveStaticHosts() {
-        // TODO Auto-generated method stub
-        return null;
+        Collection<Device> devices = Collections
+                .unmodifiableCollection(deviceMap.values());
+        Iterator<Device> i = devices.iterator();
+        Set<HostNodeConnector> nc = new HashSet<HostNodeConnector>();
+        while (i.hasNext()) {
+            Device device = i.next();
+            if(device.isStaticHost())
+                nc.add(device.toHostNodeConnector());
+        }
+        return nc;
     }
 
     @Override
@@ -2112,14 +2220,41 @@ public class DeviceManagerImpl implements IDeviceService, IEntityClassListener,
     @Override
     public Status addStaticHost(String networkAddress, String dataLayerAddress,
             NodeConnector nc, String vlan) {
-        // TODO Auto-generated method stub
-        return null;
+        Long mac = HexEncode.stringToLong(dataLayerAddress);
+        try{
+            InetAddress addr = InetAddress.getByName(networkAddress);
+            int ip = toIPv4Address(addr.getAddress());
+            Entity e = new Entity(mac, Short.valueOf(vlan), ip, nc, new Date());
+            Device d = this.learnDeviceByEntity(e);
+            d.setStaticHost(true);
+            return new Status(StatusCode.SUCCESS);
+        }catch(UnknownHostException e){
+            return new Status(StatusCode.INTERNALERROR);
+        }
     }
 
     @Override
     public Status removeStaticHost(String networkAddress) {
-        // TODO Auto-generated method stub
-        return null;
+        Integer addr;
+        try {
+            addr = toIPv4Address(InetAddress.getByName(networkAddress).getAddress());
+        } catch (UnknownHostException e) {
+            return new Status(StatusCode.NOTFOUND, "Host does not exist");
+        }
+        Iterator<Device> di = this.getDeviceIteratorForQuery(null, null, addr, null);
+        List<IDeviceListener> listeners = deviceListeners
+                .getOrderedListeners();
+        while(di.hasNext()){
+            Device d = di.next();
+            if(d.isStaticHost()){
+                deleteDevice(d);
+                for (IfNewHostNotify notify : newHostNotify)
+                    notify.notifyHTClientHostRemoved(d.toHostNodeConnector());
+                for (IDeviceListener listener : listeners)
+                        listener.deviceRemoved(d);
+            }
+        }
+        return new Status(StatusCode.SUCCESS);
     }
 
     /**