2 * Copyright (c) 2011,2012 Big Switch Networks, Inc.
4 * Licensed under the Eclipse Public License, Version 1.0 (the
5 * "License"); you may not use this file except in compliance with the
6 * License. You may obtain a copy of the License at
8 * http://www.eclipse.org/legal/epl-v10.html
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 * implied. See the License for the specific language governing
14 * permissions and limitations under the License.
16 * This file incorporates work covered by the following copyright and
19 * Originally created by David Erickson, Stanford University
21 * Licensed under the Apache License, Version 2.0 (the "License");
22 * you may not use this file except in compliance with the
23 * License. You may obtain a copy of the License at
25 * http://www.apache.org/licenses/LICENSE-2.0
27 * Unless required by applicable law or agreed to in writing,
28 * software distributed under the License is distributed on an "AS
29 * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
30 * express or implied. See the License for the specific language
31 * governing permissions and limitations under the License.
34 package org.opendaylight.controller.hosttracker.internal;
36 import java.net.InetAddress;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.Date;
42 import java.util.EnumSet;
43 import java.util.HashMap;
44 import java.util.Iterator;
45 import java.util.List;
47 import java.util.TreeSet;
49 import org.opendaylight.controller.hosttracker.Entity;
50 import org.opendaylight.controller.hosttracker.IDevice;
51 import org.opendaylight.controller.hosttracker.IDeviceService.DeviceField;
52 import org.opendaylight.controller.hosttracker.IEntityClass;
53 import org.opendaylight.controller.hosttracker.SwitchPort;
54 import org.opendaylight.controller.hosttracker.SwitchPort.ErrorStatus;
55 import org.opendaylight.controller.hosttracker.hostAware.HostNodeConnector;
56 import org.opendaylight.controller.sal.core.NodeConnector;
57 import org.opendaylight.controller.sal.utils.HexEncode;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
62 * Concrete implementation of {@link IDevice}
66 public class Device implements IDevice {
67 protected static Logger log = LoggerFactory.getLogger(Device.class);
68 public static final short VLAN_UNTAGGED = (short) 0xffff;
70 private final Long deviceKey;
71 protected final DeviceManagerImpl deviceManager;
73 protected final Entity[] entities;
74 private final IEntityClass entityClass;
76 protected final String macAddressString;
77 // the vlan Ids from the entities of this device
78 protected final Short[] vlanIds;
79 protected volatile String dhcpClientName;
81 private boolean staticHost;
84 * These are the old attachment points for the device that were valid no
85 * more than INACTIVITY_TIME ago.
87 protected volatile List<AttachmentPoint> oldAPs;
89 * The current attachment points for the device.
91 protected volatile List<AttachmentPoint> attachmentPoints;
98 * Create a device from an entities
100 * @param deviceManager
101 * the device manager for this device
103 * the unique identifier for this device object
105 * the initial entity for the device
107 * the entity classes associated with the entity
109 public Device(DeviceManagerImpl deviceManager, Long deviceKey,
110 Entity entity, IEntityClass entityClass) {
111 this.deviceManager = deviceManager;
112 this.deviceKey = deviceKey;
113 this.entities = new Entity[] { entity };
114 this.macAddressString = HexEncode.longToHexString(entity
116 this.entityClass = entityClass;
117 Arrays.sort(this.entities);
119 this.dhcpClientName = null;
121 this.attachmentPoints = null;
123 if (entity.getPort() != null) {
124 NodeConnector port = entity.getPort();
126 if (deviceManager.isValidAttachmentPoint(port)) {
128 ap = new AttachmentPoint(port, entity.getLastSeenTimestamp()
131 this.attachmentPoints = new ArrayList<AttachmentPoint>();
132 this.attachmentPoints.add(ap);
135 vlanIds = computeVlandIds();
139 * Create a device from a set of entities
141 * @param deviceManager
142 * the device manager for this device
144 * the unique identifier for this device object
146 * the initial entities for the device
148 * the entity class associated with the entities
150 public Device(DeviceManagerImpl deviceManager, Long deviceKey,
151 String dhcpClientName, Collection<AttachmentPoint> oldAPs,
152 Collection<AttachmentPoint> attachmentPoints,
153 Collection<Entity> entities, IEntityClass entityClass) {
154 this.deviceManager = deviceManager;
155 this.deviceKey = deviceKey;
156 this.dhcpClientName = dhcpClientName;
157 this.entities = entities.toArray(new Entity[entities.size()]);
159 this.attachmentPoints = null;
160 if (oldAPs != null) {
161 this.oldAPs = new ArrayList<AttachmentPoint>(oldAPs);
163 if (attachmentPoints != null) {
164 this.attachmentPoints = new ArrayList<AttachmentPoint>(
167 this.macAddressString = HexEncode.longToHexString(this.entities[0]
169 this.entityClass = entityClass;
170 Arrays.sort(this.entities);
171 vlanIds = computeVlandIds();
175 * Construct a new device consisting of the entities from the old device
176 * plus an additional entity. The caller needs to ensure that the additional
177 * entity is not already present in the array
180 * the old device object
182 * the entity to add. newEntity must be have the same entity
184 * @param if positive indicates the index in the entities array were the new
185 * entity should be inserted. If negative we will compute the correct
188 public Device(Device device, Entity newEntity, int insertionpoint) {
189 this.deviceManager = device.deviceManager;
190 this.deviceKey = device.deviceKey;
191 this.dhcpClientName = device.dhcpClientName;
193 this.entities = new Entity[device.entities.length + 1];
194 if (insertionpoint < 0) {
195 insertionpoint = -(Arrays.binarySearch(device.entities, newEntity) + 1);
197 if (insertionpoint > 0) {
198 // insertion point is not the beginning:
199 // copy up to insertion point
200 System.arraycopy(device.entities, 0, this.entities, 0,
203 if (insertionpoint < device.entities.length) {
204 // insertion point is not the end
205 // copy from insertion point
206 System.arraycopy(device.entities, insertionpoint, this.entities,
207 insertionpoint + 1, device.entities.length - insertionpoint);
209 this.entities[insertionpoint] = newEntity;
211 * this.entities = Arrays.<Entity>copyOf(device.entities,
212 * device.entities.length + 1); this.entities[this.entities.length - 1]
213 * = newEntity; Arrays.sort(this.entities);
216 if (device.oldAPs != null) {
217 this.oldAPs = new ArrayList<AttachmentPoint>(device.oldAPs);
219 this.attachmentPoints = null;
220 if (device.attachmentPoints != null) {
221 this.attachmentPoints = new ArrayList<AttachmentPoint>(
222 device.attachmentPoints);
225 this.macAddressString = HexEncode.longToHexString(this.entities[0]
228 this.entityClass = device.entityClass;
229 vlanIds = computeVlandIds();
232 private Short[] computeVlandIds() {
233 if (entities.length == 1) {
234 if (entities[0].getVlan() != null) {
235 return new Short[] { entities[0].getVlan() };
237 return new Short[] { Short.valueOf((short) -1) };
241 TreeSet<Short> vals = new TreeSet<Short>();
242 for (Entity e : entities) {
243 if (e.getVlan() == null)
244 vals.add((short) -1);
246 vals.add(e.getVlan());
248 return vals.toArray(new Short[vals.size()]);
252 * Given a list of attachment points (apList), the procedure would return a
253 * map of attachment points for each L2 domain. L2 domain id is the key.
258 private Map<Long, AttachmentPoint> getAPMap(List<AttachmentPoint> apList) {
262 // ITopologyService topology = deviceManager.topology;
264 // Get the old attachment points and sort them.
265 List<AttachmentPoint> oldAP = new ArrayList<AttachmentPoint>();
267 oldAP.addAll(apList);
269 // Remove invalid attachment points before sorting.
270 List<AttachmentPoint> tempAP = new ArrayList<AttachmentPoint>();
271 for (AttachmentPoint ap : oldAP) {
272 if (deviceManager.isValidAttachmentPoint(ap.getPort())) {
278 Collections.sort(oldAP, deviceManager.apComparator);
280 // Map of attachment point by L2 domain Id.
281 Map<Long, AttachmentPoint> apMap = new HashMap<Long, AttachmentPoint>();
283 for (int i = 0; i < oldAP.size(); ++i) {
284 AttachmentPoint ap = oldAP.get(i);
285 // if this is not a valid attachment point, continue
286 if (!deviceManager.isValidAttachmentPoint(ap.getPort()))
289 // long id = topology.getL2DomainId(ap.getSw());
290 // XXX - Missing functionality
302 * Remove all attachment points that are older than INACTIVITY_INTERVAL from
308 private boolean removeExpiredAttachmentPoints(List<AttachmentPoint> apList) {
310 List<AttachmentPoint> expiredAPs = new ArrayList<AttachmentPoint>();
315 for (AttachmentPoint ap : apList) {
316 if (ap.getLastSeen() + AttachmentPoint.INACTIVITY_INTERVAL < System
317 .currentTimeMillis())
320 if (expiredAPs.size() > 0) {
321 apList.removeAll(expiredAPs);
328 * Get a list of duplicate attachment points, given a list of old attachment
329 * points and one attachment point per L2 domain. Given a true attachment
330 * point in the L2 domain, say trueAP, another attachment point in the same
331 * L2 domain, say ap, is duplicate if: 1. ap is inconsistent with trueAP,
332 * and 2. active time of ap is after that of trueAP; and 3. last seen time
333 * of ap is within the last INACTIVITY_INTERVAL
339 List<AttachmentPoint> getDuplicateAttachmentPoints(
340 List<AttachmentPoint> oldAPList, Map<Long, AttachmentPoint> apMap) {
341 // ITopologyService topology = deviceManager.topology;
342 List<AttachmentPoint> dupAPs = new ArrayList<AttachmentPoint>();
343 long timeThreshold = System.currentTimeMillis()
344 - AttachmentPoint.INACTIVITY_INTERVAL;
346 if (oldAPList == null || apMap == null)
349 for (AttachmentPoint ap : oldAPList) {
350 // XXX - Missing functionality
351 // long id = topology.getL2DomainId(ap.getSw());
353 AttachmentPoint trueAP = apMap.get(id);
357 // XXX - Missing functionality
358 // boolean c = (topology.isConsistent(trueAP.getSw(),
360 // ap.getSw(), ap.getPort()));
362 boolean active = (ap.getActiveSince() > trueAP.getActiveSince());
363 boolean last = ap.getLastSeen() > timeThreshold;
364 if (!c && active && last) {
373 * Update the known attachment points. This method is called whenever
374 * topology changes. The method returns true if there's any change to the
375 * list of attachment points -- which indicates a possible device move.
379 protected boolean updateAttachmentPoint() {
380 boolean moved = false;
381 this.oldAPs = attachmentPoints;
382 if (attachmentPoints == null || attachmentPoints.isEmpty())
385 List<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
386 if (attachmentPoints != null)
387 apList.addAll(attachmentPoints);
388 Map<Long, AttachmentPoint> newMap = getAPMap(apList);
389 if (newMap == null || newMap.size() != apList.size()) {
393 // Prepare the new attachment point list.
395 log.info("updateAttachmentPoint: ap {} newmap {} ",
396 attachmentPoints, newMap);
397 List<AttachmentPoint> newAPList = new ArrayList<AttachmentPoint>();
399 newAPList.addAll(newMap.values());
400 this.attachmentPoints = newAPList;
403 // Set the oldAPs to null.
408 * Update the list of attachment points given that a new packet-in was seen
409 * from (sw, port) at time (lastSeen). The return value is true if there was
410 * any change to the list of attachment points for the device -- which
411 * indicates a device move.
418 protected boolean updateAttachmentPoint(NodeConnector port, long lastSeen) {
419 // ITopologyService topology = deviceManager.topology;
420 List<AttachmentPoint> oldAPList;
421 List<AttachmentPoint> apList;
422 boolean oldAPFlag = false;
424 if (!deviceManager.isValidAttachmentPoint(port))
426 AttachmentPoint newAP = new AttachmentPoint(port, lastSeen);
427 // Copy the oldAP and ap list.
428 apList = new ArrayList<AttachmentPoint>();
429 if (attachmentPoints != null)
430 apList.addAll(attachmentPoints);
431 oldAPList = new ArrayList<AttachmentPoint>();
433 oldAPList.addAll(oldAPs);
435 // if the sw, port is in old AP, remove it from there
436 // and update the lastSeen in that object.
437 if (oldAPList.contains(newAP)) {
438 int index = oldAPList.indexOf(newAP);
439 newAP = oldAPList.remove(index);
440 newAP.setLastSeen(lastSeen);
441 this.oldAPs = oldAPList;
445 // newAP now contains the new attachment point.
447 // Get the APMap is null or empty.
448 Map<Long, AttachmentPoint> apMap = getAPMap(apList);
449 if (apMap == null || apMap.isEmpty()) {
451 attachmentPoints = apList;
452 // there are no old attachment points - since the device exists,
454 // may be because the host really moved (so the old AP port went
456 // or it may be because the switch restarted (so old APs were
458 // For now we will treat both cases as host moved.
462 // XXX - Missing functionality
463 // long id = topology.getL2DomainId(sw);
465 AttachmentPoint oldAP = apMap.get(id);
467 if (oldAP == null) // No attachment on this L2 domain.
469 apList = new ArrayList<AttachmentPoint>();
470 apList.addAll(apMap.values());
472 this.attachmentPoints = apList;
473 return true; // new AP found on an L2 island.
476 // There is already a known attachment point on the same L2 island.
477 // we need to compare oldAP and newAP.
478 if (oldAP.equals(newAP)) {
479 // nothing to do here. just the last seen has to be changed.
480 if (newAP.lastSeen > oldAP.lastSeen) {
481 oldAP.setLastSeen(newAP.lastSeen);
483 this.attachmentPoints = new ArrayList<AttachmentPoint>(
485 return false; // nothing to do here.
488 int x = deviceManager.apComparator.compare(oldAP, newAP);
490 // newAP replaces oldAP.
491 apMap.put(id, newAP);
492 this.attachmentPoints = new ArrayList<AttachmentPoint>(
495 oldAPList = new ArrayList<AttachmentPoint>();
497 oldAPList.addAll(oldAPs);
498 oldAPList.add(oldAP);
499 this.oldAPs = oldAPList;
500 // XXX - Missing functionality
501 // if (!topology.isInSameBroadcastDomain(oldAP.getSw(),
503 // newAP.getSw(), newAP.getPort()))
504 // return true; // attachment point changed.
506 } else if (oldAPFlag) {
507 // retain oldAP as is. Put the newAP in oldAPs for flagging
508 // possible duplicates.
509 oldAPList = new ArrayList<AttachmentPoint>();
511 oldAPList.addAll(oldAPs);
512 // Add to oldAPList only if it was picked up from the oldAPList
513 oldAPList.add(newAP);
514 this.oldAPs = oldAPList;
515 // XXX - Missing functionality
516 // if (!topology.isInSameBroadcastDomain(oldAP.getSw(),
518 // newAP.getSw(), newAP.getPort()))
519 // return true; // attachment point changed.
526 * Delete (sw,port) from the list of list of attachment points and oldAPs.
532 public boolean deleteAttachmentPoint(NodeConnector port) {
533 AttachmentPoint ap = new AttachmentPoint(port, 0);
535 if (this.oldAPs != null) {
536 ArrayList<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
537 apList.addAll(this.oldAPs);
538 int index = apList.indexOf(ap);
540 apList.remove(index);
541 this.oldAPs = apList;
545 if (this.attachmentPoints != null) {
546 ArrayList<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
547 apList.addAll(this.attachmentPoints);
548 int index = apList.indexOf(ap);
550 apList.remove(index);
551 this.attachmentPoints = apList;
563 public SwitchPort[] getOldAP() {
564 List<SwitchPort> sp = new ArrayList<SwitchPort>();
565 SwitchPort[] returnSwitchPorts = new SwitchPort[] {};
567 return returnSwitchPorts;
568 if (oldAPs.isEmpty())
569 return returnSwitchPorts;
572 List<AttachmentPoint> oldAPList;
573 oldAPList = new ArrayList<AttachmentPoint>();
576 oldAPList.addAll(oldAPs);
577 removeExpiredAttachmentPoints(oldAPList);
579 if (oldAPList != null) {
580 for (AttachmentPoint ap : oldAPList) {
581 SwitchPort swport = new SwitchPort(ap.getPort());
585 return sp.toArray(new SwitchPort[sp.size()]);
589 public SwitchPort[] getAttachmentPoints() {
590 return getAttachmentPoints(false);
594 public SwitchPort[] getAttachmentPoints(boolean includeError) {
595 List<SwitchPort> sp = new ArrayList<SwitchPort>();
596 SwitchPort[] returnSwitchPorts = new SwitchPort[] {};
597 if (attachmentPoints == null)
598 return returnSwitchPorts;
599 if (attachmentPoints.isEmpty())
600 return returnSwitchPorts;
603 List<AttachmentPoint> apList = attachmentPoints;
605 if (apList != null) {
606 for (AttachmentPoint ap : apList) {
607 SwitchPort swport = new SwitchPort(ap.getPort());
613 return sp.toArray(new SwitchPort[sp.size()]);
615 List<AttachmentPoint> oldAPList;
616 oldAPList = new ArrayList<AttachmentPoint>();
619 oldAPList.addAll(oldAPs);
621 if (removeExpiredAttachmentPoints(oldAPList))
622 this.oldAPs = oldAPList;
624 List<AttachmentPoint> dupList;
626 Map<Long, AttachmentPoint> apMap = getAPMap(apList);
627 dupList = this.getDuplicateAttachmentPoints(oldAPList, apMap);
628 if (dupList != null) {
629 for (AttachmentPoint ap : dupList) {
630 SwitchPort swport = new SwitchPort(ap.getPort(),
631 ErrorStatus.DUPLICATE_DEVICE);
635 return sp.toArray(new SwitchPort[sp.size()]);
639 public Long getDeviceKey() {
644 public long getMACAddress() {
645 // we assume only one MAC per device for now.
646 return entities[0].getMacAddress();
650 public String getMACAddressString() {
651 return macAddressString;
655 public Short[] getVlanId() {
656 return Arrays.copyOf(vlanIds, vlanIds.length);
659 static final EnumSet<DeviceField> ipv4Fields = EnumSet.of(DeviceField.IPV4);
662 public Integer[] getIPv4Addresses() {
663 // XXX - TODO we can cache this result. Let's find out if this
664 // is really a performance bottleneck first though.
666 TreeSet<Integer> vals = new TreeSet<Integer>();
667 for (Entity e : entities) {
668 if (e.getIpv4Address() == null)
671 // We have an IP address only if among the devices within the class
672 // we have the most recent entity with that IP.
673 boolean validIP = true;
674 Iterator<Device> devices = deviceManager.queryClassByEntity(
675 entityClass, ipv4Fields, e);
676 while (devices.hasNext()) {
677 Device d = devices.next();
678 if (deviceKey.equals(d.getDeviceKey()))
680 for (Entity se : d.entities) {
681 if (se.getIpv4Address() != null
682 && se.getIpv4Address().equals(e.getIpv4Address())
683 && se.getLastSeenTimestamp() != null
684 && 0 < se.getLastSeenTimestamp().compareTo(
685 e.getLastSeenTimestamp())) {
695 vals.add(e.getIpv4Address());
698 return vals.toArray(new Integer[vals.size()]);
702 public Short[] getSwitchPortVlanIds(SwitchPort swp) {
703 TreeSet<Short> vals = new TreeSet<Short>();
704 for (Entity e : entities) {
705 if (e.getPort().equals(swp.getPort())) {
706 if (e.getVlan() == null)
707 vals.add(VLAN_UNTAGGED);
709 vals.add(e.getVlan());
712 return vals.toArray(new Short[vals.size()]);
716 public Date getLastSeen() {
718 for (int i = 0; i < entities.length; i++) {
720 || entities[i].getLastSeenTimestamp().compareTo(d) > 0)
721 d = entities[i].getLastSeenTimestamp();
731 public IEntityClass getEntityClass() {
735 public Entity[] getEntities() {
739 public String getDHCPClientName() {
740 return dhcpClientName;
748 * Check whether the device contains the specified entity
751 * the entity to search for
752 * @return the index of the entity, or <0 if not found
754 protected int entityIndex(Entity entity) {
755 return Arrays.binarySearch(entities, entity);
763 public int hashCode() {
764 final int prime = 31;
766 result = prime * result + Arrays.hashCode(entities);
771 public boolean equals(Object obj) {
776 if (getClass() != obj.getClass())
778 Device other = (Device) obj;
779 if (!deviceKey.equals(other.deviceKey))
781 if (!Arrays.equals(entities, other.entities))
786 public HostNodeConnector toHostNodeConnector() {
787 Integer[] ipv4s = this.getIPv4Addresses();
789 Entity e = this.entities[this.entities.length-1];
790 NodeConnector n = null;
793 InetAddress ip = InetAddress.getByName(ipv4s[ipv4s.length - 1]
795 byte[] macAddr = macLongToByte(this.getMACAddress());
796 HostNodeConnector nc = new HostNodeConnector(macAddr, ip, n,
798 nc.setStaticHost(this.isStaticHost());
800 } catch (Exception e) {
805 private byte[] macLongToByte(long mac) {
806 byte[] macAddr = new byte[6];
807 for (int i = 0; i < 6; i++) {
808 macAddr[5 - i] = (byte) (mac >> (8 * i));
813 public boolean isStaticHost(){
814 return this.staticHost;
817 public void setStaticHost(boolean isStatic){
818 this.staticHost = isStatic;
822 public String toString() {
823 StringBuilder builder = new StringBuilder();
824 builder.append("Device [deviceKey=");
825 builder.append(deviceKey);
826 builder.append(", entityClass=");
827 builder.append(entityClass.getName());
828 builder.append(", MAC=");
829 builder.append(macAddressString);
830 builder.append(", IPs=[");
831 boolean isFirst = true;
832 for (Integer ip : getIPv4Addresses()) {
834 builder.append(", ");
836 // builder.append(IPv4.fromIPv4Address(ip));
839 builder.append("], APs=");
840 builder.append(Arrays.toString(getAttachmentPoints(true)));
842 return builder.toString();