Merge "Move adsal into its own subdirectory."
[controller.git] / opendaylight / adsal / hosttracker_new / implementation / src / main / java / org / opendaylight / controller / hosttracker / internal / Device.java
1 /*
2  * Copyright (c) 2011,2012 Big Switch Networks, Inc.
3  *
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
7  *
8  *      http://www.eclipse.org/legal/epl-v10.html
9  *
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.
15  *
16  * This file incorporates work covered by the following copyright and
17  * permission notice:
18  *
19  *    Originally created by David Erickson, Stanford University
20  *
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
24  *
25  *         http://www.apache.org/licenses/LICENSE-2.0
26  *
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.
32  */
33
34 package org.opendaylight.controller.hosttracker.internal;
35
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;
46 import java.util.Map;
47 import java.util.TreeSet;
48
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;
60
61 /**
62  * Concrete implementation of {@link IDevice}
63  *
64  * @author readams
65  */
66 public class Device implements IDevice {
67     protected static Logger log = LoggerFactory.getLogger(Device.class);
68     public static final short VLAN_UNTAGGED = (short) 0xffff;
69
70     private final Long deviceKey;
71     protected final DeviceManagerImpl deviceManager;
72
73     protected final Entity[] entities;
74     private final IEntityClass entityClass;
75
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;
80
81     private boolean staticHost;
82
83     /**
84      * These are the old attachment points for the device that were valid no
85      * more than INACTIVITY_TIME ago.
86      */
87     protected volatile List<AttachmentPoint> oldAPs;
88     /**
89      * The current attachment points for the device.
90      */
91     protected volatile List<AttachmentPoint> attachmentPoints;
92
93     // ************
94     // Constructors
95     // ************
96
97     /**
98      * Create a device from an entities
99      *
100      * @param deviceManager
101      *            the device manager for this device
102      * @param deviceKey
103      *            the unique identifier for this device object
104      * @param entity
105      *            the initial entity for the device
106      * @param entityClass
107      *            the entity classes associated with the entity
108      */
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
115                 .getMacAddress());
116         this.entityClass = entityClass;
117         Arrays.sort(this.entities);
118
119         this.dhcpClientName = null;
120         this.oldAPs = null;
121         this.attachmentPoints = null;
122
123         if (entity.getPort() != null) {
124             NodeConnector port = entity.getPort();
125
126             if (deviceManager.isValidAttachmentPoint(port)) {
127                 AttachmentPoint ap;
128                 ap = new AttachmentPoint(port, entity.getLastSeenTimestamp()
129                         .getTime());
130
131                 this.attachmentPoints = new ArrayList<AttachmentPoint>();
132                 this.attachmentPoints.add(ap);
133             }
134         }
135         vlanIds = computeVlandIds();
136     }
137
138     /**
139      * Create a device from a set of entities
140      *
141      * @param deviceManager
142      *            the device manager for this device
143      * @param deviceKey
144      *            the unique identifier for this device object
145      * @param entities
146      *            the initial entities for the device
147      * @param entityClass
148      *            the entity class associated with the entities
149      */
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()]);
158         this.oldAPs = null;
159         this.attachmentPoints = null;
160         if (oldAPs != null) {
161             this.oldAPs = new ArrayList<AttachmentPoint>(oldAPs);
162         }
163         if (attachmentPoints != null) {
164             this.attachmentPoints = new ArrayList<AttachmentPoint>(
165                     attachmentPoints);
166         }
167         this.macAddressString = HexEncode.longToHexString(this.entities[0]
168                 .getMacAddress());
169         this.entityClass = entityClass;
170         Arrays.sort(this.entities);
171         vlanIds = computeVlandIds();
172     }
173
174     /**
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
178      *
179      * @param device
180      *            the old device object
181      * @param newEntity
182      *            the entity to add. newEntity must be have the same entity
183      *            class as device
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
187      *        insertion point
188      */
189     public Device(Device device, Entity newEntity, int insertionpoint) {
190         this.deviceManager = device.deviceManager;
191         this.deviceKey = device.deviceKey;
192         this.dhcpClientName = device.dhcpClientName;
193
194         this.entities = new Entity[device.entities.length + 1];
195         if (insertionpoint < 0) {
196             insertionpoint = -(Arrays.binarySearch(device.entities, newEntity) + 1);
197         }
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,
202                     insertionpoint);
203         }
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);
209         }
210         this.entities[insertionpoint] = newEntity;
211         /*
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);
215          */
216         this.oldAPs = null;
217         if (device.oldAPs != null) {
218             this.oldAPs = new ArrayList<AttachmentPoint>(device.oldAPs);
219         }
220         this.attachmentPoints = null;
221         if (device.attachmentPoints != null) {
222             this.attachmentPoints = new ArrayList<AttachmentPoint>(
223                     device.attachmentPoints);
224         }
225
226         this.macAddressString = HexEncode.longToHexString(this.entities[0]
227                 .getMacAddress());
228
229         this.entityClass = device.entityClass;
230         vlanIds = computeVlandIds();
231     }
232
233     private Short[] computeVlandIds() {
234         if (entities.length == 1) {
235             if (entities[0].getVlan() != null) {
236                 return new Short[] { entities[0].getVlan() };
237             } else {
238                 return new Short[] { Short.valueOf((short) -1) };
239             }
240         }
241
242         TreeSet<Short> vals = new TreeSet<Short>();
243         for (Entity e : entities) {
244             if (e.getVlan() == null) {
245                 vals.add((short) -1);
246             } else {
247                 vals.add(e.getVlan());
248             }
249         }
250         return vals.toArray(new Short[vals.size()]);
251     }
252
253     /**
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.
256      *
257      * @param apList
258      * @return
259      */
260     private Map<Long, AttachmentPoint> getAPMap(List<AttachmentPoint> apList) {
261
262         if (apList == null)
263             return null;
264         // ITopologyService topology = deviceManager.topology;
265
266         // Get the old attachment points and sort them.
267         List<AttachmentPoint> oldAP = new ArrayList<AttachmentPoint>();
268         if (apList != null)
269             oldAP.addAll(apList);
270
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())) {
275                 tempAP.add(ap);
276             }
277         }
278         oldAP = tempAP;
279
280         Collections.sort(oldAP, deviceManager.apComparator);
281
282         // Map of attachment point by L2 domain Id.
283         Map<Long, AttachmentPoint> apMap = new HashMap<Long, AttachmentPoint>();
284
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()))
289                 continue;
290
291             // long id = topology.getL2DomainId(ap.getSw());
292             // XXX - Missing functionality
293             long id = 0;
294
295             apMap.put(id, ap);
296         }
297
298         if (apMap.isEmpty())
299             return null;
300         return apMap;
301     }
302
303     /**
304      * Remove all attachment points that are older than INACTIVITY_INTERVAL from
305      * the list.
306      *
307      * @param apList
308      * @return
309      */
310     private boolean removeExpiredAttachmentPoints(List<AttachmentPoint> apList) {
311
312         List<AttachmentPoint> expiredAPs = new ArrayList<AttachmentPoint>();
313
314         if (apList == null)
315             return false;
316
317         for (AttachmentPoint ap : apList) {
318             if (ap.getLastSeen() + AttachmentPoint.INACTIVITY_INTERVAL < System.currentTimeMillis()) {
319                expiredAPs.add(ap);
320             }
321         }
322         if (expiredAPs.size() > 0) {
323             apList.removeAll(expiredAPs);
324             return true;
325         } else {
326             return false;
327         }
328     }
329
330     /**
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
337      *
338      * @param oldAPList
339      * @param apMap
340      * @return
341      */
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;
347
348         if (oldAPList == null || apMap == null)
349             return dupAPs;
350
351         for (AttachmentPoint ap : oldAPList) {
352             long id = 0;
353             AttachmentPoint trueAP = apMap.get(id);
354
355             if (trueAP == null)
356                 continue;
357             boolean c = true;
358             boolean active = (ap.getActiveSince() > trueAP.getActiveSince());
359             boolean last = ap.getLastSeen() > timeThreshold;
360             if (!c && active && last) {
361                 dupAPs.add(ap);
362             }
363         }
364
365         return dupAPs;
366     }
367
368     /**
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.
372      *
373      * @return
374      */
375     protected boolean updateAttachmentPoint() {
376         boolean moved = false;
377         this.oldAPs = attachmentPoints;
378         if (attachmentPoints == null || attachmentPoints.isEmpty())
379             return false;
380
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()) {
386             moved = true;
387         }
388
389         // Prepare the new attachment point list.
390         if (moved) {
391             log.info("updateAttachmentPoint: ap {}  newmap {} ",
392                     attachmentPoints, newMap);
393             List<AttachmentPoint> newAPList = new ArrayList<AttachmentPoint>();
394             if (newMap != null)
395                 newAPList.addAll(newMap.values());
396             this.attachmentPoints = newAPList;
397         }
398
399         // Set the oldAPs to null.
400         return moved;
401     }
402
403     /**
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.
408      *
409      * @param port
410      * @param lastSeen
411      * @return
412      */
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;
418
419         if (!deviceManager.isValidAttachmentPoint(port))
420             return false;
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>();
427         if (oldAPs != null)
428             oldAPList.addAll(oldAPs);
429
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;
437             oldAPFlag = true;
438         }
439
440         // newAP now contains the new attachment point.
441
442         // Get the APMap is null or empty.
443         Map<Long, AttachmentPoint> apMap = getAPMap(apList);
444         if (apMap == null || apMap.isEmpty()) {
445             apList.add(newAP);
446             attachmentPoints = apList;
447             // there are no old attachment points - since the device exists,
448             // this
449             // may be because the host really moved (so the old AP port went
450             // down);
451             // or it may be because the switch restarted (so old APs were
452             // nullified).
453             // For now we will treat both cases as host moved.
454             return true;
455         }
456
457         // XXX - Missing functionality
458         long id = 0;
459         AttachmentPoint oldAP = apMap.get(id);
460
461         if (oldAP == null) // No attachment on this L2 domain.
462         {
463             apList = new ArrayList<AttachmentPoint>();
464             apList.addAll(apMap.values());
465             apList.add(newAP);
466             this.attachmentPoints = apList;
467             return true; // new AP found on an L2 island.
468         }
469
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);
476             }
477             this.attachmentPoints = new ArrayList<AttachmentPoint>(
478                     apMap.values());
479             return false; // nothing to do here.
480         }
481
482         int x = deviceManager.apComparator.compare(oldAP, newAP);
483         if (x < 0) {
484             // newAP replaces oldAP.
485             apMap.put(id, newAP);
486             this.attachmentPoints = new ArrayList<AttachmentPoint>(
487                     apMap.values());
488
489             oldAPList = new ArrayList<AttachmentPoint>();
490             if (oldAPs != null)
491                 oldAPList.addAll(oldAPs);
492             oldAPList.add(oldAP);
493             this.oldAPs = oldAPList;
494             return true;
495         } else if (oldAPFlag) {
496             // retain oldAP as is. Put the newAP in oldAPs for flagging
497             // possible duplicates.
498             oldAPList = new ArrayList<AttachmentPoint>();
499             if (oldAPs != null)
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;
504             return true;
505         }
506         return false;
507     }
508
509     /**
510      * Delete (sw,port) from the list of list of attachment points and oldAPs.
511      *
512      * @param port
513      * @return
514      */
515     public boolean deleteAttachmentPoint(NodeConnector port) {
516         AttachmentPoint ap = new AttachmentPoint(port, 0);
517
518         if (this.oldAPs != null) {
519             ArrayList<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
520             apList.addAll(this.oldAPs);
521             int index = apList.indexOf(ap);
522             if (index > 0) {
523                 apList.remove(index);
524                 this.oldAPs = apList;
525             }
526         }
527
528         if (this.attachmentPoints != null) {
529             ArrayList<AttachmentPoint> apList = new ArrayList<AttachmentPoint>();
530             apList.addAll(this.attachmentPoints);
531             int index = apList.indexOf(ap);
532             if (index > 0) {
533                 apList.remove(index);
534                 this.attachmentPoints = apList;
535                 return true;
536             }
537         }
538         return false;
539     }
540
541     // *******
542     // IDevice
543     // *******
544
545     @Override
546     public SwitchPort[] getOldAP() {
547         List<SwitchPort> sp = new ArrayList<SwitchPort>();
548         SwitchPort[] returnSwitchPorts = new SwitchPort[] {};
549         if (oldAPs == null)
550             return returnSwitchPorts;
551         if (oldAPs.isEmpty())
552             return returnSwitchPorts;
553
554         // copy ap list.
555         List<AttachmentPoint> oldAPList;
556         oldAPList = new ArrayList<AttachmentPoint>();
557
558         if (oldAPs != null)
559             oldAPList.addAll(oldAPs);
560         removeExpiredAttachmentPoints(oldAPList);
561
562         if (oldAPList != null) {
563             for (AttachmentPoint ap : oldAPList) {
564                 SwitchPort swport = new SwitchPort(ap.getPort());
565                 sp.add(swport);
566             }
567         }
568         return sp.toArray(new SwitchPort[sp.size()]);
569     }
570
571     @Override
572     public SwitchPort[] getAttachmentPoints() {
573         return getAttachmentPoints(false);
574     }
575
576     @Override
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;
584
585         // copy ap list.
586         List<AttachmentPoint> apList = attachmentPoints;
587
588         if (apList != null) {
589             for (AttachmentPoint ap : apList) {
590                 SwitchPort swport = new SwitchPort(ap.getPort());
591                 sp.add(swport);
592             }
593         }
594
595         if (!includeError)
596             return sp.toArray(new SwitchPort[sp.size()]);
597
598         List<AttachmentPoint> oldAPList;
599         oldAPList = new ArrayList<AttachmentPoint>();
600
601         if (oldAPs != null)
602             oldAPList.addAll(oldAPs);
603
604         if (removeExpiredAttachmentPoints(oldAPList))
605             this.oldAPs = oldAPList;
606
607         List<AttachmentPoint> dupList;
608         // get AP map.
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);
615                 sp.add(swport);
616             }
617         }
618         return sp.toArray(new SwitchPort[sp.size()]);
619     }
620
621     @Override
622     public Long getDeviceKey() {
623         return deviceKey;
624     }
625
626     @Override
627     public long getMACAddress() {
628         // we assume only one MAC per device for now.
629         return entities[0].getMacAddress();
630     }
631
632     @Override
633     public String getMACAddressString() {
634         return macAddressString;
635     }
636
637     @Override
638     public Short[] getVlanId() {
639         return Arrays.copyOf(vlanIds, vlanIds.length);
640     }
641
642     static final EnumSet<DeviceField> ipv4Fields = EnumSet.of(DeviceField.IPV4);
643
644     @Override
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.
648
649         TreeSet<Integer> vals = new TreeSet<Integer>();
650         for (Entity e : entities) {
651             if (e.getIpv4Address() == null)
652                 continue;
653
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()))
662                     continue;
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())) {
669                         validIP = false;
670                         break;
671                     }
672                 }
673                 if (!validIP)
674                     break;
675             }
676
677             if (validIP)
678                 vals.add(e.getIpv4Address());
679         }
680
681         return vals.toArray(new Integer[vals.size()]);
682     }
683
684     @Override
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);
691                 }
692                 else  {
693                     vals.add(e.getVlan());
694                 }
695             }
696         }
697         return vals.toArray(new Short[vals.size()]);
698     }
699
700     @Override
701     public Date getLastSeen() {
702         Date d = null;
703         for (int i = 0; i < entities.length; i++) {
704             if (d == null
705                     || entities[i].getLastSeenTimestamp().compareTo(d) > 0)
706                 d = entities[i].getLastSeenTimestamp();
707         }
708         return d;
709     }
710
711     // ***************
712     // Getters/Setters
713     // ***************
714
715     @Override
716     public IEntityClass getEntityClass() {
717         return entityClass;
718     }
719
720     public Entity[] getEntities() {
721         return entities;
722     }
723
724     public String getDHCPClientName() {
725         return dhcpClientName;
726     }
727
728     // ***************
729     // Utility Methods
730     // ***************
731
732     /**
733      * Check whether the device contains the specified entity
734      *
735      * @param entity
736      *            the entity to search for
737      * @return the index of the entity, or <0 if not found
738      */
739     protected int entityIndex(Entity entity) {
740         return Arrays.binarySearch(entities, entity);
741     }
742
743     // ******
744     // Object
745     // ******
746
747     @Override
748     public int hashCode() {
749         final int prime = 31;
750         int result = 1;
751         result = prime * result + Arrays.hashCode(entities);
752         return result;
753     }
754
755     @Override
756     public boolean equals(Object obj) {
757         if (this == obj)
758             return true;
759         if (obj == null)
760             return false;
761         if (getClass() != obj.getClass())
762             return false;
763         Device other = (Device) obj;
764         if (!deviceKey.equals(other.deviceKey))
765             return false;
766         if (!Arrays.equals(entities, other.entities))
767             return false;
768         return true;
769     }
770
771     public HostNodeConnector toHostNodeConnector() {
772         Integer[] ipv4s = this.getIPv4Addresses();
773         try {
774             Entity e = this.entities[this.entities.length-1];
775             NodeConnector n = null;
776             if(e!=null)
777                  n = e.getPort();
778             InetAddress ip = InetAddress.getByName(ipv4s[ipv4s.length - 1]
779                     .toString());
780             byte[] macAddr = macLongToByte(this.getMACAddress());
781             HostNodeConnector nc = new HostNodeConnector(macAddr, ip, n,
782                     (short) 0);
783             nc.setStaticHost(this.isStaticHost());
784             return nc;
785         } catch (Exception e) {
786             return null;
787         }
788     }
789
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));
794         }
795         return macAddr;
796     }
797
798     public boolean isStaticHost(){
799         return this.staticHost;
800     }
801
802     public void setStaticHost(boolean isStatic){
803         this.staticHost = isStatic;
804     }
805
806     @Override
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()) {
818             if (!isFirst)
819                 builder.append(", ");
820             isFirst = false;
821             builder.append(ip);
822         }
823         builder.append("], APs=");
824         builder.append(Arrays.toString(getAttachmentPoints(true)));
825         builder.append("]");
826         return builder.toString();
827     }
828 }