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 insertionpoint
185 * if positive indicates the index in the entities array were the new
186 * entity should be inserted. If negative we will compute the correct
189 public Device(Device device, Entity newEntity, int insertionpoint) {
190 this.deviceManager = device.deviceManager;
191 this.deviceKey = device.deviceKey;
192 this.dhcpClientName = device.dhcpClientName;
194 this.entities = new Entity[device.entities.length + 1];
195 if (insertionpoint < 0) {
196 insertionpoint = -(Arrays.binarySearch(device.entities, newEntity) + 1);
198 if (insertionpoint > 0) {
199 // insertion point is not the beginning:
200 // copy up to insertion point
201 System.arraycopy(device.entities, 0, this.entities, 0,
204 if (insertionpoint < device.entities.length) {
205 // insertion point is not the end
206 // copy from insertion point
207 System.arraycopy(device.entities, insertionpoint, this.entities,
208 insertionpoint + 1, device.entities.length - insertionpoint);
210 this.entities[insertionpoint] = newEntity;
212 * this.entities = Arrays.<Entity>copyOf(device.entities,
213 * device.entities.length + 1); this.entities[this.entities.length - 1]
214 * = newEntity; Arrays.sort(this.entities);
217 if (device.oldAPs != null) {
218 this.oldAPs = new ArrayList<AttachmentPoint>(device.oldAPs);
220 this.attachmentPoints = null;
221 if (device.attachmentPoints != null) {
222 this.attachmentPoints = new ArrayList<AttachmentPoint>(
223 device.attachmentPoints);
226 this.macAddressString = HexEncode.longToHexString(this.entities[0]
229 this.entityClass = device.entityClass;
230 vlanIds = computeVlandIds();
233 private Short[] computeVlandIds() {
234 if (entities.length == 1) {
235 if (entities[0].getVlan() != null) {
236 return new Short[] { entities[0].getVlan() };
238 return new Short[] { Short.valueOf((short) -1) };
242 TreeSet<Short> vals = new TreeSet<Short>();
243 for (Entity e : entities) {
244 if (e.getVlan() == null) {
245 vals.add((short) -1);
247 vals.add(e.getVlan());
250 return vals.toArray(new Short[vals.size()]);
254 * Given a list of attachment points (apList), the procedure would return a
255 * map of attachment points for each L2 domain. L2 domain id is the key.
260 private Map<Long, AttachmentPoint> getAPMap(List<AttachmentPoint> apList) {
264 // ITopologyService topology = deviceManager.topology;
266 // Get the old attachment points and sort them.
267 List<AttachmentPoint> oldAP = new ArrayList<AttachmentPoint>();
269 oldAP.addAll(apList);
271 // Remove invalid attachment points before sorting.
272 List<AttachmentPoint> tempAP = new ArrayList<AttachmentPoint>();
273 for (AttachmentPoint ap : oldAP) {
274 if (deviceManager.isValidAttachmentPoint(ap.getPort())) {
280 Collections.sort(oldAP, deviceManager.apComparator);
282 // Map of attachment point by L2 domain Id.
283 Map<Long, AttachmentPoint> apMap = new HashMap<Long, AttachmentPoint>();
285 for (int i = 0; i < oldAP.size(); ++i) {
286 AttachmentPoint ap = oldAP.get(i);
287 // if this is not a valid attachment point, continue
288 if (!deviceManager.isValidAttachmentPoint(ap.getPort()))
291 // long id = topology.getL2DomainId(ap.getSw());
292 // XXX - Missing functionality
304 * Remove all attachment points that are older than INACTIVITY_INTERVAL from
310 private boolean removeExpiredAttachmentPoints(List<AttachmentPoint> apList) {
312 List<AttachmentPoint> expiredAPs = new ArrayList<AttachmentPoint>();
317 for (AttachmentPoint ap : apList) {
318 if (ap.getLastSeen() + AttachmentPoint.INACTIVITY_INTERVAL < System.currentTimeMillis()) {
322 if (expiredAPs.size() > 0) {
323 apList.removeAll(expiredAPs);
331 * Get a list of duplicate attachment points, given a list of old attachment
332 * points and one attachment point per L2 domain. Given a true attachment
333 * point in the L2 domain, say trueAP, another attachment point in the same
334 * L2 domain, say ap, is duplicate if: 1. ap is inconsistent with trueAP,
335 * and 2. active time of ap is after that of trueAP; and 3. last seen time
336 * of ap is within the last INACTIVITY_INTERVAL
342 List<AttachmentPoint> getDuplicateAttachmentPoints(
343 List<AttachmentPoint> oldAPList, Map<Long, AttachmentPoint> apMap) {
344 List<AttachmentPoint> dupAPs = new ArrayList<AttachmentPoint>();
345 long timeThreshold = System.currentTimeMillis()
346 - AttachmentPoint.INACTIVITY_INTERVAL;
348 if (oldAPList == null || apMap == null)
351 for (AttachmentPoint ap : oldAPList) {
353 AttachmentPoint trueAP = apMap.get(id);
358 boolean active = (ap.getActiveSince() > trueAP.getActiveSince());
359 boolean last = ap.getLastSeen() > timeThreshold;
360 if (!c && active && last) {
369 * Update the known attachment points. This method is called whenever
370 * topology changes. The method returns true if there's any change to the
371 * list of attachment points -- which indicates a possible device move.
375 protected boolean updateAttachmentPoint() {
376 boolean moved = false;
377 this.oldAPs = attachmentPoints;
378 if (attachmentPoints == null || attachmentPoints.isEmpty())
381 List<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
382 if (attachmentPoints != null)
383 apList.addAll(attachmentPoints);
384 Map<Long, AttachmentPoint> newMap = getAPMap(apList);
385 if (newMap == null || newMap.size() != apList.size()) {
389 // Prepare the new attachment point list.
391 log.info("updateAttachmentPoint: ap {} newmap {} ",
392 attachmentPoints, newMap);
393 List<AttachmentPoint> newAPList = new ArrayList<AttachmentPoint>();
395 newAPList.addAll(newMap.values());
396 this.attachmentPoints = newAPList;
399 // Set the oldAPs to null.
404 * Update the list of attachment points given that a new packet-in was seen
405 * from (sw, port) at time (lastSeen). The return value is true if there was
406 * any change to the list of attachment points for the device -- which
407 * indicates a device move.
413 protected boolean updateAttachmentPoint(NodeConnector port, long lastSeen) {
414 // ITopologyService topology = deviceManager.topology;
415 List<AttachmentPoint> oldAPList;
416 List<AttachmentPoint> apList;
417 boolean oldAPFlag = false;
419 if (!deviceManager.isValidAttachmentPoint(port))
421 AttachmentPoint newAP = new AttachmentPoint(port, lastSeen);
422 // Copy the oldAP and ap list.
423 apList = new ArrayList<AttachmentPoint>();
424 if (attachmentPoints != null)
425 apList.addAll(attachmentPoints);
426 oldAPList = new ArrayList<AttachmentPoint>();
428 oldAPList.addAll(oldAPs);
430 // if the sw, port is in old AP, remove it from there
431 // and update the lastSeen in that object.
432 if (oldAPList.contains(newAP)) {
433 int index = oldAPList.indexOf(newAP);
434 newAP = oldAPList.remove(index);
435 newAP.setLastSeen(lastSeen);
436 this.oldAPs = oldAPList;
440 // newAP now contains the new attachment point.
442 // Get the APMap is null or empty.
443 Map<Long, AttachmentPoint> apMap = getAPMap(apList);
444 if (apMap == null || apMap.isEmpty()) {
446 attachmentPoints = apList;
447 // there are no old attachment points - since the device exists,
449 // may be because the host really moved (so the old AP port went
451 // or it may be because the switch restarted (so old APs were
453 // For now we will treat both cases as host moved.
457 // XXX - Missing functionality
459 AttachmentPoint oldAP = apMap.get(id);
461 if (oldAP == null) // No attachment on this L2 domain.
463 apList = new ArrayList<AttachmentPoint>();
464 apList.addAll(apMap.values());
466 this.attachmentPoints = apList;
467 return true; // new AP found on an L2 island.
470 // There is already a known attachment point on the same L2 island.
471 // we need to compare oldAP and newAP.
472 if (oldAP.equals(newAP)) {
473 // nothing to do here. just the last seen has to be changed.
474 if (newAP.lastSeen > oldAP.lastSeen) {
475 oldAP.setLastSeen(newAP.lastSeen);
477 this.attachmentPoints = new ArrayList<AttachmentPoint>(
479 return false; // nothing to do here.
482 int x = deviceManager.apComparator.compare(oldAP, newAP);
484 // newAP replaces oldAP.
485 apMap.put(id, newAP);
486 this.attachmentPoints = new ArrayList<AttachmentPoint>(
489 oldAPList = new ArrayList<AttachmentPoint>();
491 oldAPList.addAll(oldAPs);
492 oldAPList.add(oldAP);
493 this.oldAPs = oldAPList;
495 } else if (oldAPFlag) {
496 // retain oldAP as is. Put the newAP in oldAPs for flagging
497 // possible duplicates.
498 oldAPList = new ArrayList<AttachmentPoint>();
500 oldAPList.addAll(oldAPs);
501 // Add to oldAPList only if it was picked up from the oldAPList
502 oldAPList.add(newAP);
503 this.oldAPs = oldAPList;
510 * Delete (sw,port) from the list of list of attachment points and oldAPs.
515 public boolean deleteAttachmentPoint(NodeConnector port) {
516 AttachmentPoint ap = new AttachmentPoint(port, 0);
518 if (this.oldAPs != null) {
519 ArrayList<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
520 apList.addAll(this.oldAPs);
521 int index = apList.indexOf(ap);
523 apList.remove(index);
524 this.oldAPs = apList;
528 if (this.attachmentPoints != null) {
529 ArrayList<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
530 apList.addAll(this.attachmentPoints);
531 int index = apList.indexOf(ap);
533 apList.remove(index);
534 this.attachmentPoints = apList;
546 public SwitchPort[] getOldAP() {
547 List<SwitchPort> sp = new ArrayList<SwitchPort>();
548 SwitchPort[] returnSwitchPorts = new SwitchPort[] {};
550 return returnSwitchPorts;
551 if (oldAPs.isEmpty())
552 return returnSwitchPorts;
555 List<AttachmentPoint> oldAPList;
556 oldAPList = new ArrayList<AttachmentPoint>();
559 oldAPList.addAll(oldAPs);
560 removeExpiredAttachmentPoints(oldAPList);
562 if (oldAPList != null) {
563 for (AttachmentPoint ap : oldAPList) {
564 SwitchPort swport = new SwitchPort(ap.getPort());
568 return sp.toArray(new SwitchPort[sp.size()]);
572 public SwitchPort[] getAttachmentPoints() {
573 return getAttachmentPoints(false);
577 public SwitchPort[] getAttachmentPoints(boolean includeError) {
578 List<SwitchPort> sp = new ArrayList<SwitchPort>();
579 SwitchPort[] returnSwitchPorts = new SwitchPort[] {};
580 if (attachmentPoints == null)
581 return returnSwitchPorts;
582 if (attachmentPoints.isEmpty())
583 return returnSwitchPorts;
586 List<AttachmentPoint> apList = attachmentPoints;
588 if (apList != null) {
589 for (AttachmentPoint ap : apList) {
590 SwitchPort swport = new SwitchPort(ap.getPort());
596 return sp.toArray(new SwitchPort[sp.size()]);
598 List<AttachmentPoint> oldAPList;
599 oldAPList = new ArrayList<AttachmentPoint>();
602 oldAPList.addAll(oldAPs);
604 if (removeExpiredAttachmentPoints(oldAPList))
605 this.oldAPs = oldAPList;
607 List<AttachmentPoint> dupList;
609 Map<Long, AttachmentPoint> apMap = getAPMap(apList);
610 dupList = this.getDuplicateAttachmentPoints(oldAPList, apMap);
611 if (dupList != null) {
612 for (AttachmentPoint ap : dupList) {
613 SwitchPort swport = new SwitchPort(ap.getPort(),
614 ErrorStatus.DUPLICATE_DEVICE);
618 return sp.toArray(new SwitchPort[sp.size()]);
622 public Long getDeviceKey() {
627 public long getMACAddress() {
628 // we assume only one MAC per device for now.
629 return entities[0].getMacAddress();
633 public String getMACAddressString() {
634 return macAddressString;
638 public Short[] getVlanId() {
639 return Arrays.copyOf(vlanIds, vlanIds.length);
642 static final EnumSet<DeviceField> ipv4Fields = EnumSet.of(DeviceField.IPV4);
645 public Integer[] getIPv4Addresses() {
646 // XXX - TODO we can cache this result. Let's find out if this
647 // is really a performance bottleneck first though.
649 TreeSet<Integer> vals = new TreeSet<Integer>();
650 for (Entity e : entities) {
651 if (e.getIpv4Address() == null)
654 // We have an IP address only if among the devices within the class
655 // we have the most recent entity with that IP.
656 boolean validIP = true;
657 Iterator<Device> devices = deviceManager.queryClassByEntity(
658 entityClass, ipv4Fields, e);
659 while (devices.hasNext()) {
660 Device d = devices.next();
661 if (deviceKey.equals(d.getDeviceKey()))
663 for (Entity se : d.entities) {
664 if (se.getIpv4Address() != null
665 && se.getIpv4Address().equals(e.getIpv4Address())
666 && se.getLastSeenTimestamp() != null
667 && 0 < se.getLastSeenTimestamp().compareTo(
668 e.getLastSeenTimestamp())) {
678 vals.add(e.getIpv4Address());
681 return vals.toArray(new Integer[vals.size()]);
685 public Short[] getSwitchPortVlanIds(SwitchPort swp) {
686 TreeSet<Short> vals = new TreeSet<Short>();
687 for (Entity e : entities) {
688 if (e.getPort().equals(swp.getPort())) {
689 if (e.getVlan() == null) {
690 vals.add(VLAN_UNTAGGED);
693 vals.add(e.getVlan());
697 return vals.toArray(new Short[vals.size()]);
701 public Date getLastSeen() {
703 for (int i = 0; i < entities.length; i++) {
705 || entities[i].getLastSeenTimestamp().compareTo(d) > 0)
706 d = entities[i].getLastSeenTimestamp();
716 public IEntityClass getEntityClass() {
720 public Entity[] getEntities() {
724 public String getDHCPClientName() {
725 return dhcpClientName;
733 * Check whether the device contains the specified entity
736 * the entity to search for
737 * @return the index of the entity, or <0 if not found
739 protected int entityIndex(Entity entity) {
740 return Arrays.binarySearch(entities, entity);
748 public int hashCode() {
749 final int prime = 31;
751 result = prime * result + Arrays.hashCode(entities);
756 public boolean equals(Object obj) {
761 if (getClass() != obj.getClass())
763 Device other = (Device) obj;
764 if (!deviceKey.equals(other.deviceKey))
766 if (!Arrays.equals(entities, other.entities))
771 public HostNodeConnector toHostNodeConnector() {
772 Integer[] ipv4s = this.getIPv4Addresses();
774 Entity e = this.entities[this.entities.length-1];
775 NodeConnector n = null;
778 InetAddress ip = InetAddress.getByName(ipv4s[ipv4s.length - 1]
780 byte[] macAddr = macLongToByte(this.getMACAddress());
781 HostNodeConnector nc = new HostNodeConnector(macAddr, ip, n,
783 nc.setStaticHost(this.isStaticHost());
785 } catch (Exception e) {
790 private byte[] macLongToByte(long mac) {
791 byte[] macAddr = new byte[6];
792 for (int i = 0; i < 6; i++) {
793 macAddr[5 - i] = (byte) (mac >> (8 * i));
798 public boolean isStaticHost(){
799 return this.staticHost;
802 public void setStaticHost(boolean isStatic){
803 this.staticHost = isStatic;
807 public String toString() {
808 StringBuilder builder = new StringBuilder();
809 builder.append("Device [deviceKey=");
810 builder.append(deviceKey);
811 builder.append(", entityClass=");
812 builder.append(entityClass.getName());
813 builder.append(", MAC=");
814 builder.append(macAddressString);
815 builder.append(", IPs=[");
816 boolean isFirst = true;
817 for (Integer ip : getIPv4Addresses()) {
819 builder.append(", ");
823 builder.append("], APs=");
824 builder.append(Arrays.toString(getAttachmentPoints(true)));
826 return builder.toString();