4fa961f81b3d928b4f783a67e9621257206a4e30
[onosfw.git] /
1 /*
2  * Copyright 2014-2015 Open Networking Laboratory
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
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 implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onosproject.provider.of.device.impl;
17
18 import static com.google.common.base.Preconditions.checkArgument;
19 import static com.google.common.base.Strings.isNullOrEmpty;
20 import static org.onlab.util.Tools.get;
21 import static org.onosproject.net.DeviceId.deviceId;
22 import static org.onosproject.net.Port.Type.COPPER;
23 import static org.onosproject.net.Port.Type.FIBER;
24 import static org.onosproject.openflow.controller.Dpid.dpid;
25 import static org.onosproject.openflow.controller.Dpid.uri;
26 import static org.slf4j.LoggerFactory.getLogger;
27
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Dictionary;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
35
36 import org.apache.felix.scr.annotations.Activate;
37 import org.apache.felix.scr.annotations.Component;
38 import org.apache.felix.scr.annotations.Deactivate;
39 import org.apache.felix.scr.annotations.Modified;
40 import org.apache.felix.scr.annotations.Property;
41 import org.apache.felix.scr.annotations.Reference;
42 import org.apache.felix.scr.annotations.ReferenceCardinality;
43 import org.onlab.packet.ChassisId;
44 import org.onlab.util.Frequency;
45 import org.onlab.util.Spectrum;
46 import org.onosproject.cfg.ComponentConfigService;
47 import org.onosproject.net.AnnotationKeys;
48 import org.onosproject.net.ChannelSpacing;
49 import org.onosproject.net.DefaultAnnotations;
50 import org.onosproject.net.Device;
51 import org.onosproject.net.DeviceId;
52 import org.onosproject.net.GridType;
53 import org.onosproject.net.MastershipRole;
54 import org.onosproject.net.OchSignal;
55 import org.onosproject.net.OduCltPort;
56 import org.onosproject.net.OduSignalType;
57 import org.onosproject.net.Port;
58 import org.onosproject.net.PortNumber;
59 import org.onosproject.net.SparseAnnotations;
60 import org.onosproject.net.device.DefaultDeviceDescription;
61 import org.onosproject.net.device.DefaultPortDescription;
62 import org.onosproject.net.device.DefaultPortStatistics;
63 import org.onosproject.net.device.DeviceDescription;
64 import org.onosproject.net.device.DeviceProvider;
65 import org.onosproject.net.device.DeviceProviderRegistry;
66 import org.onosproject.net.device.DeviceProviderService;
67 import org.onosproject.net.device.OchPortDescription;
68 import org.onosproject.net.device.OduCltPortDescription;
69 import org.onosproject.net.device.OmsPortDescription;
70 import org.onosproject.net.device.PortDescription;
71 import org.onosproject.net.device.PortStatistics;
72 import org.onosproject.net.provider.AbstractProvider;
73 import org.onosproject.net.provider.ProviderId;
74 import org.onosproject.openflow.controller.Dpid;
75 import org.onosproject.openflow.controller.OpenFlowController;
76 import org.onosproject.openflow.controller.OpenFlowEventListener;
77 import org.onosproject.openflow.controller.OpenFlowOpticalSwitch;
78 import org.onosproject.openflow.controller.OpenFlowSwitch;
79 import org.onosproject.openflow.controller.OpenFlowSwitchListener;
80 import org.onosproject.openflow.controller.PortDescPropertyType;
81 import org.onosproject.openflow.controller.RoleState;
82 import org.osgi.service.component.ComponentContext;
83 import org.projectfloodlight.openflow.protocol.OFCalientPortDescStatsEntry;
84 import org.projectfloodlight.openflow.protocol.OFExpPort;
85 import org.projectfloodlight.openflow.protocol.OFExpPortDescPropOpticalTransport;
86 import org.projectfloodlight.openflow.protocol.OFExpPortOpticalTransportLayerEntry;
87 import org.projectfloodlight.openflow.protocol.OFFactory;
88 import org.projectfloodlight.openflow.protocol.OFMessage;
89 import org.projectfloodlight.openflow.protocol.OFObject;
90 import org.projectfloodlight.openflow.protocol.OFPortConfig;
91 import org.projectfloodlight.openflow.protocol.OFPortDesc;
92 import org.projectfloodlight.openflow.protocol.OFPortDescPropOpticalTransport;
93 import org.projectfloodlight.openflow.protocol.OFPortFeatures;
94 import org.projectfloodlight.openflow.protocol.OFPortOptical;
95 import org.projectfloodlight.openflow.protocol.OFPortOpticalTransportLayerClass;
96 import org.projectfloodlight.openflow.protocol.OFPortOpticalTransportSignalType;
97 import org.projectfloodlight.openflow.protocol.OFPortReason;
98 import org.projectfloodlight.openflow.protocol.OFPortState;
99 import org.projectfloodlight.openflow.protocol.OFPortStatsEntry;
100 import org.projectfloodlight.openflow.protocol.OFPortStatsReply;
101 import org.projectfloodlight.openflow.protocol.OFPortStatus;
102 import org.projectfloodlight.openflow.protocol.OFStatsReply;
103 import org.projectfloodlight.openflow.protocol.OFStatsReplyFlags;
104 import org.projectfloodlight.openflow.protocol.OFStatsType;
105 import org.projectfloodlight.openflow.protocol.OFVersion;
106 import org.projectfloodlight.openflow.types.PortSpeed;
107 import org.slf4j.Logger;
108
109 import com.google.common.base.Strings;
110 import com.google.common.collect.Lists;
111 import com.google.common.collect.Maps;
112 import com.google.common.collect.Sets;
113
114 /**
115  * Provider which uses an OpenFlow controller to detect network
116  * infrastructure devices.
117  */
118 @Component(immediate = true)
119 public class OpenFlowDeviceProvider extends AbstractProvider implements DeviceProvider {
120
121     private static final Logger LOG = getLogger(OpenFlowDeviceProvider.class);
122
123     private static final long MBPS = 1_000 * 1_000;
124     private static final Frequency FREQ100 = Frequency.ofGHz(100);
125     private static final Frequency FREQ193_1 = Frequency.ofTHz(193.1);
126     private static final Frequency FREQ4_4 = Frequency.ofTHz(4.4);
127
128     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
129     protected DeviceProviderRegistry providerRegistry;
130
131     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
132     protected OpenFlowController controller;
133
134     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
135     protected ComponentConfigService cfgService;
136
137     private DeviceProviderService providerService;
138
139     private final InternalDeviceProvider listener = new InternalDeviceProvider();
140
141     // TODO: We need to make the poll interval configurable.
142     static final int POLL_INTERVAL = 5;
143     @Property(name = "PortStatsPollFrequency", intValue = POLL_INTERVAL,
144     label = "Frequency (in seconds) for polling switch Port statistics")
145     private int portStatsPollFrequency = POLL_INTERVAL;
146
147     private HashMap<Dpid, PortStatsCollector> collectors = Maps.newHashMap();
148
149     /**
150      * Creates an OpenFlow device provider.
151      */
152     public OpenFlowDeviceProvider() {
153         super(new ProviderId("of", "org.onosproject.provider.openflow"));
154     }
155
156     @Activate
157     public void activate(ComponentContext context) {
158         cfgService.registerProperties(getClass());
159         providerService = providerRegistry.register(this);
160         controller.addListener(listener);
161         controller.addEventListener(listener);
162         connectInitialDevices();
163         LOG.info("Started");
164     }
165
166     @Deactivate
167     public void deactivate(ComponentContext context) {
168         cfgService.unregisterProperties(getClass(), false);
169         controller.removeListener(listener);
170         disconnectDevices();
171         providerRegistry.unregister(this);
172         collectors.values().forEach(PortStatsCollector::stop);
173         providerService = null;
174         LOG.info("Stopped");
175     }
176
177     @Modified
178     public void modified(ComponentContext context) {
179         Dictionary<?, ?> properties = context.getProperties();
180         int newPortStatsPollFrequency;
181         try {
182             String s = get(properties, "PortStatsPollFrequency");
183             newPortStatsPollFrequency = isNullOrEmpty(s) ? portStatsPollFrequency : Integer.parseInt(s.trim());
184
185         } catch (NumberFormatException | ClassCastException e) {
186             newPortStatsPollFrequency = portStatsPollFrequency;
187         }
188
189         if (newPortStatsPollFrequency != portStatsPollFrequency) {
190             portStatsPollFrequency = newPortStatsPollFrequency;
191             collectors.values().forEach(psc -> psc.adjustPollInterval(portStatsPollFrequency));
192         }
193
194         LOG.info("Settings: portStatsPollFrequency={}", portStatsPollFrequency);
195     }
196
197     private void connectInitialDevices() {
198         for (OpenFlowSwitch sw : controller.getSwitches()) {
199             try {
200                 listener.switchAdded(new Dpid(sw.getId()));
201             } catch (Exception e) {
202                 LOG.warn("Failed initially adding {} : {}", sw.getStringId(), e.getMessage());
203                 LOG.debug("Error details:", e);
204                 // disconnect to trigger switch-add later
205                 sw.disconnectSwitch();
206             }
207             PortStatsCollector psc = new PortStatsCollector(sw, portStatsPollFrequency);
208             psc.start();
209             collectors.put(new Dpid(sw.getId()), psc);
210         }
211     }
212
213     private void disconnectDevices() {
214         // Only disconnect the devices for which we are currently master.
215         controller.getMasterSwitches().forEach(sw -> listener.switchRemoved(new Dpid(sw.getId())));
216     }
217
218     @Override
219     public boolean isReachable(DeviceId deviceId) {
220         OpenFlowSwitch sw = controller.getSwitch(dpid(deviceId.uri()));
221         return sw != null && sw.isConnected();
222     }
223
224     @Override
225     public void triggerProbe(DeviceId deviceId) {
226         LOG.debug("Triggering probe on device {}", deviceId);
227
228         final Dpid dpid = dpid(deviceId.uri());
229         OpenFlowSwitch sw = controller.getSwitch(dpid);
230         if (sw == null || !sw.isConnected()) {
231             LOG.error("Failed to probe device {} on sw={}", deviceId, sw);
232             providerService.deviceDisconnected(deviceId);
233             return;
234         } else {
235             LOG.trace("Confirmed device {} connection", deviceId);
236         }
237
238         // Prompt an update of port information. We can use any XID for this.
239         OFFactory fact = sw.factory();
240         switch (fact.getVersion()) {
241             case OF_10:
242                 sw.sendMsg(fact.buildFeaturesRequest().setXid(0).build());
243                 break;
244             case OF_13:
245                 sw.sendMsg(fact.buildPortDescStatsRequest().setXid(0).build());
246                 break;
247             default:
248                 LOG.warn("Unhandled protocol version");
249         }
250     }
251
252     @Override
253     public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
254         switch (newRole) {
255             case MASTER:
256                 controller.setRole(dpid(deviceId.uri()), RoleState.MASTER);
257                 break;
258             case STANDBY:
259                 controller.setRole(dpid(deviceId.uri()), RoleState.EQUAL);
260                 break;
261             case NONE:
262                 controller.setRole(dpid(deviceId.uri()), RoleState.SLAVE);
263                 break;
264             default:
265                 LOG.error("Unknown Mastership state : {}", newRole);
266
267         }
268         LOG.debug("Accepting mastership role change for device {}", deviceId);
269     }
270
271     private void pushPortMetrics(Dpid dpid, List<OFPortStatsEntry> portStatsEntries) {
272         DeviceId deviceId = DeviceId.deviceId(dpid.uri(dpid));
273         Collection<PortStatistics> stats = buildPortStatistics(deviceId, portStatsEntries);
274         providerService.updatePortStatistics(deviceId, stats);
275     }
276
277     private Collection<PortStatistics> buildPortStatistics(DeviceId deviceId,
278                                                            List<OFPortStatsEntry> entries) {
279         HashSet<PortStatistics> stats = Sets.newHashSet();
280
281         for (OFPortStatsEntry entry : entries) {
282             try {
283                 if (entry == null || entry.getPortNo() == null || entry.getPortNo().getPortNumber() < 0) {
284                     continue;
285                 }
286                 DefaultPortStatistics.Builder builder = DefaultPortStatistics.builder();
287                 DefaultPortStatistics stat = builder.setDeviceId(deviceId)
288                         .setPort(entry.getPortNo().getPortNumber())
289                         .setPacketsReceived(entry.getRxPackets().getValue())
290                         .setPacketsSent(entry.getTxPackets().getValue())
291                         .setBytesReceived(entry.getRxBytes().getValue())
292                         .setBytesSent(entry.getTxBytes().getValue())
293                         .setPacketsRxDropped(entry.getRxDropped().getValue())
294                         .setPacketsTxDropped(entry.getTxDropped().getValue())
295                         .setPacketsRxErrors(entry.getRxErrors().getValue())
296                         .setPacketsTxErrors(entry.getTxErrors().getValue())
297                         .setDurationSec(entry.getVersion() == OFVersion.OF_10 ? 0 : entry.getDurationSec())
298                         .setDurationNano(entry.getVersion() == OFVersion.OF_10 ? 0 : entry.getDurationNsec())
299                         .build();
300
301                 stats.add(stat);
302             } catch (Exception e) {
303                 LOG.warn("Unable to process port stats", e);
304             }
305         }
306
307         return Collections.unmodifiableSet(stats);
308
309     }
310
311     private class InternalDeviceProvider implements OpenFlowSwitchListener, OpenFlowEventListener {
312
313         private HashMap<Dpid, List<OFPortStatsEntry>> portStatsReplies = new HashMap<>();
314
315         @Override
316         public void switchAdded(Dpid dpid) {
317             if (providerService == null) {
318                 return;
319             }
320             DeviceId did = deviceId(uri(dpid));
321             OpenFlowSwitch sw = controller.getSwitch(dpid);
322
323             ChassisId cId = new ChassisId(dpid.value());
324
325             SparseAnnotations annotations = DefaultAnnotations.builder()
326                     .set(AnnotationKeys.PROTOCOL, sw.factory().getVersion().toString())
327                     .set(AnnotationKeys.CHANNEL_ID, sw.channelId())
328                     .set(AnnotationKeys.MANAGEMENT_ADDRESS, sw.channelId().split(":")[0])
329                     .build();
330
331             DeviceDescription description =
332                     new DefaultDeviceDescription(did.uri(), sw.deviceType(),
333                                                  sw.manufacturerDescription(),
334                                                  sw.hardwareDescription(),
335                                                  sw.softwareDescription(),
336                                                  sw.serialNumber(),
337                                                  cId, annotations);
338             providerService.deviceConnected(did, description);
339             providerService.updatePorts(did, buildPortDescriptions(sw));
340
341             PortStatsCollector psc =
342                     new PortStatsCollector(controller.getSwitch(dpid), portStatsPollFrequency);
343             psc.start();
344             collectors.put(dpid, psc);
345         }
346
347         @Override
348         public void switchRemoved(Dpid dpid) {
349             if (providerService == null) {
350                 return;
351             }
352             providerService.deviceDisconnected(deviceId(uri(dpid)));
353
354             PortStatsCollector collector = collectors.remove(dpid);
355             if (collector != null) {
356                 collector.stop();
357             }
358         }
359
360         @Override
361         public void switchChanged(Dpid dpid) {
362             if (providerService == null) {
363                 return;
364             }
365             DeviceId did = deviceId(uri(dpid));
366             OpenFlowSwitch sw = controller.getSwitch(dpid);
367             providerService.updatePorts(did, buildPortDescriptions(sw));
368         }
369
370         @Override
371         public void portChanged(Dpid dpid, OFPortStatus status) {
372             PortDescription portDescription = buildPortDescription(status);
373             providerService.portStatusChanged(deviceId(uri(dpid)), portDescription);
374         }
375
376         @Override
377         public void receivedRoleReply(Dpid dpid, RoleState requested, RoleState response) {
378             MastershipRole request = roleOf(requested);
379             MastershipRole reply = roleOf(response);
380
381             providerService.receivedRoleReply(deviceId(uri(dpid)), request, reply);
382         }
383
384         /**
385          * Translates a RoleState to the corresponding MastershipRole.
386          *
387          * @param response role state
388          * @return a MastershipRole
389          */
390         private MastershipRole roleOf(RoleState response) {
391             switch (response) {
392                 case MASTER:
393                     return MastershipRole.MASTER;
394                 case EQUAL:
395                     return MastershipRole.STANDBY;
396                 case SLAVE:
397                     return MastershipRole.NONE;
398                 default:
399                     LOG.warn("unknown role {}", response);
400                     return null;
401             }
402         }
403
404         /**
405          * Builds a list of port descriptions for a given list of ports.
406          *
407          * @return list of portdescriptions
408          */
409         private List<PortDescription> buildPortDescriptions(OpenFlowSwitch sw) {
410             final List<PortDescription> portDescs = new ArrayList<>(sw.getPorts().size());
411             if (!(Device.Type.ROADM.equals(sw.deviceType()))) {
412                   sw.getPorts().forEach(port -> portDescs.add(buildPortDescription(port)));
413             }
414
415             OpenFlowOpticalSwitch opsw;
416             switch (sw.deviceType()) {
417                 case ROADM:
418                     opsw = (OpenFlowOpticalSwitch) sw;
419                     List<OFPortDesc> ports = opsw.getPorts();
420                     LOG.debug("SW ID {} , ETH- ODU CLT Ports {}", opsw.getId(), ports);
421                     // ODU client ports are reported as ETH
422                     ports.forEach(port -> portDescs.add(buildOduCltPortDescription(port)));
423
424                     opsw.getPortTypes().forEach(type -> {
425                     List<? extends OFObject> portsOf = opsw.getPortsOf(type);
426                     LOG.debug("Ports Of{}", portsOf);
427                     portsOf.forEach(
428                         op -> {
429                             portDescs.add(buildPortDescription(type, (OFObject) op));
430                         }
431                      );
432                     });
433                     break;
434                 case FIBER_SWITCH:
435                     opsw = (OpenFlowOpticalSwitch) sw;
436                     opsw.getPortTypes().forEach(type -> {
437                         opsw.getPortsOf(type).forEach(
438                                 op -> {
439                                     portDescs.add(buildPortDescription((OFCalientPortDescStatsEntry) op));
440                                 }
441                         );
442                     });
443                     break;
444                 default:
445                     break;
446             }
447
448             return portDescs;
449         }
450
451         private PortDescription buildOduCltPortDescription(OFPortDesc port) {
452             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
453             boolean enabled = !port.getState().contains(OFPortState.LINK_DOWN) &&
454                               !port.getConfig().contains(OFPortConfig.PORT_DOWN);
455             Long portSpeed = portSpeed(port);
456             OduCltPort.SignalType sigType = null;
457
458             switch (portSpeed.toString()) {
459                 case "1":
460                     sigType = OduCltPort.SignalType.CLT_1GBE;
461                     break;
462                 case "10":
463                     sigType = OduCltPort.SignalType.CLT_10GBE;
464                     break;
465                 case "40":
466                     sigType = OduCltPort.SignalType.CLT_40GBE;
467                     break;
468                 case "100":
469                     sigType = OduCltPort.SignalType.CLT_100GBE;
470                     break;
471                 default:
472                     throw new RuntimeException("Un recognize OduClt speed: " + portSpeed.toString());
473             }
474
475             SparseAnnotations annotations = buildOduCltAnnotation(port);
476             return new OduCltPortDescription(portNo, enabled, sigType, annotations);
477         }
478
479         private SparseAnnotations buildOduCltAnnotation(OFPortDesc port) {
480             SparseAnnotations annotations = null;
481             String portName = Strings.emptyToNull(port.getName());
482             if (portName != null) {
483                  annotations = DefaultAnnotations.builder()
484                         .set(AnnotationKeys.PORT_NAME, portName)
485                         .set(AnnotationKeys.STATIC_PORT, Boolean.TRUE.toString()).build();
486             }
487             return annotations;
488         }
489
490         private PortDescription buildPortDescription(PortDescPropertyType ptype, OFObject port) {
491             if (port instanceof  OFPortOptical) {
492                return buildPortDescription(ptype, (OFPortOptical) port);
493             }
494             return buildPortDescription(ptype, (OFExpPort) port);
495         }
496
497         /**
498          * Build a portDescription from a given a port description describing some
499          * Optical port.
500          *
501          * @param ptype description property type.
502          * @param port the port to build from.
503          * @return portDescription for the port.
504          */
505         private PortDescription buildPortDescription(PortDescPropertyType ptype, OFExpPort port) {
506             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
507             boolean enabled = !port.getState().contains(OFPortState.LINK_DOWN)
508                     && !port.getConfig().contains(OFPortConfig.PORT_DOWN);
509             SparseAnnotations annotations = makePortNameAnnotation(port.getName());
510
511             OFExpPortDescPropOpticalTransport firstProp = port.getProperties().get(0);
512             OFPortOpticalTransportSignalType sigType = firstProp.getPortSignalType();
513
514             DefaultPortDescription portDes = null;
515             switch (sigType) {
516             case OMSN:
517                 portDes =  new OmsPortDescription(portNo, enabled, FREQ193_1, FREQ193_1.add(FREQ4_4),
518                        FREQ100, annotations);
519                 break;
520             case OCH:
521                 OFExpPortOpticalTransportLayerEntry entry = firstProp.getFeatures().get(0).getValue().get(0);
522                 OFPortOpticalTransportLayerClass layerClass =  entry.getLayerClass();
523                 if (!OFPortOpticalTransportLayerClass.ODU.equals(layerClass)) {
524                     LOG.error("Unsupported layer Class {} ", layerClass);
525                     return null;
526                 }
527
528                 // convert to ONOS OduSignalType
529                 OduSignalType oduSignalType = OpenFlowDeviceValueMapper.
530                         lookupOduSignalType((byte) entry.getSignalType());
531                 //OchSignal is needed for OchPortDescription constructor,
532                 //yet not relevant for tunable OCH port, creating with default parameters
533                 OchSignal signalId = new OchSignal(GridType.DWDM, ChannelSpacing.CHL_50GHZ, 1, 1);
534
535                 portDes = new OchPortDescription(portNo, enabled,
536                         oduSignalType, true, signalId, annotations);
537
538                 break;
539             case OTU2:
540             case OTU4:
541                   LOG.error("Signal tpye OTU2/4 not supported yet ", port.toString());
542                   break;
543             default:
544                 break;
545             }
546
547             return portDes;
548         }
549
550         /**
551          * Creates an annotation for the port name if one is available.
552          *
553          * @param port description of the port
554          * @return annotation containing the port name if one is found,
555          *         null otherwise
556          */
557         private SparseAnnotations makePortNameAnnotation(String port) {
558             SparseAnnotations annotations = null;
559             String portName = Strings.emptyToNull(port);
560             if (portName != null) {
561                 annotations = DefaultAnnotations.builder()
562                         .set(AnnotationKeys.PORT_NAME, portName).build();
563             }
564             return annotations;
565         }
566
567         /**
568          * Build a portDescription from a given Ethernet port description.
569          *
570          * @param port the port to build from.
571          * @return portDescription for the port.
572          */
573         private PortDescription buildPortDescription(OFPortDesc port) {
574             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
575             boolean enabled =
576                     !port.getState().contains(OFPortState.LINK_DOWN) &&
577                             !port.getConfig().contains(OFPortConfig.PORT_DOWN);
578             Port.Type type = port.getCurr().contains(OFPortFeatures.PF_FIBER) ? FIBER : COPPER;
579             SparseAnnotations annotations = makePortNameAnnotation(port.getName());
580             return new DefaultPortDescription(portNo, enabled, type,
581                                               portSpeed(port), annotations);
582         }
583
584         /**
585          * Build a portDescription from a given a port description describing some
586          * Optical port.
587          *
588          * @param port description property type.
589          * @param port the port to build from.
590          * @return portDescription for the port.
591          */
592         private PortDescription buildPortDescription(PortDescPropertyType ptype, OFPortOptical port) {
593             checkArgument(port.getDesc().size() >= 1);
594
595             // Minimally functional fixture. This needs to be fixed as we add better support.
596             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
597
598             boolean enabled = !port.getState().contains(OFPortState.LINK_DOWN)
599                     && !port.getConfig().contains(OFPortConfig.PORT_DOWN);
600             SparseAnnotations annotations = makePortNameAnnotation(port.getName());
601
602             if (port.getVersion() == OFVersion.OF_13
603                     && ptype == PortDescPropertyType.OPTICAL_TRANSPORT) {
604                 // At this point, not much is carried in the optical port message.
605                 LOG.debug("Optical transport port message {}", port.toString());
606             } else {
607                 // removable once 1.4+ support complete.
608                 LOG.debug("Unsupported optical port properties");
609             }
610
611             OFPortDescPropOpticalTransport desc = port.getDesc().get(0);
612             switch (desc.getPortSignalType()) {
613                 // FIXME: use constants once loxi has full optical extensions
614                 case 2:     // OMS port
615                     // Assume complete optical spectrum and 50 GHz grid
616                     // LINC-OE is only supported optical OF device for now
617                     return new OmsPortDescription(portNo, enabled,
618                             Spectrum.U_BAND_MIN, Spectrum.O_BAND_MAX, Frequency.ofGHz(50), annotations);
619                 case 5:     // OCH port
620                     OchSignal signal = new OchSignal(GridType.DWDM, ChannelSpacing.CHL_50GHZ, 0, 4);
621                     return new OchPortDescription(portNo, enabled, OduSignalType.ODU4,
622                             true, signal, annotations);
623                 default:
624                     break;
625             }
626
627             return new DefaultPortDescription(portNo, enabled, FIBER, 0, annotations);
628         }
629
630         /**
631          * Build a portDescription from a given port description describing a fiber switch optical port.
632          *
633          * @param port description property type.
634          * @param port the port to build from.
635          * @return portDescription for the port.
636          */
637         private PortDescription buildPortDescription(OFCalientPortDescStatsEntry port) {
638             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
639
640             // FIXME when Calient OF agent reports port status
641             boolean enabled = true;
642             SparseAnnotations annotations = makePortNameAnnotation(port.getName());
643
644             // S160 data sheet
645             // Wavelength range: 1260 - 1630 nm, grid is irrelevant for this type of switch
646             return new OmsPortDescription(portNo, enabled,
647                     Spectrum.U_BAND_MIN, Spectrum.O_BAND_MAX, Frequency.ofGHz(100), annotations);
648         }
649
650         private PortDescription buildPortDescription(OFPortStatus status) {
651             OFPortDesc port = status.getDesc();
652             if (status.getReason() != OFPortReason.DELETE) {
653                 return buildPortDescription(port);
654             } else {
655                 PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
656                 Port.Type type = port.getCurr().contains(OFPortFeatures.PF_FIBER) ? FIBER : COPPER;
657                 SparseAnnotations annotations = makePortNameAnnotation(port.getName());
658                 return new DefaultPortDescription(portNo, false, type,
659                                                   portSpeed(port), annotations);
660             }
661         }
662
663         private long portSpeed(OFPortDesc port) {
664             if (port.getVersion() == OFVersion.OF_13) {
665                 return port.getCurrSpeed() / MBPS;
666             }
667
668             PortSpeed portSpeed = PortSpeed.SPEED_NONE;
669             for (OFPortFeatures feat : port.getCurr()) {
670                 portSpeed = PortSpeed.max(portSpeed, feat.getPortSpeed());
671             }
672             return portSpeed.getSpeedBps() / MBPS;
673         }
674
675         @Override
676         public void handleMessage(Dpid dpid, OFMessage msg) {
677             switch (msg.getType()) {
678                 case STATS_REPLY:
679                     if (((OFStatsReply) msg).getStatsType() == OFStatsType.PORT) {
680                         OFPortStatsReply portStatsReply = (OFPortStatsReply) msg;
681                         List<OFPortStatsEntry> portStatsReplyList = portStatsReplies.get(dpid);
682                         if (portStatsReplyList == null) {
683                             portStatsReplyList = Lists.newArrayList();
684                         }
685                         portStatsReplyList.addAll(portStatsReply.getEntries());
686                         portStatsReplies.put(dpid, portStatsReplyList);
687                         if (!portStatsReply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
688                             pushPortMetrics(dpid, portStatsReplies.get(dpid));
689                             portStatsReplies.get(dpid).clear();
690                         }
691                     }
692                     break;
693                 default:
694                     break;
695             }
696         }
697     }
698 }