329df20b393db04bb21950e7941dd80a0d3384d5
[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             providerService.receivedRoleReply(deviceId(uri(dpid)), request, reply);
381         }
382
383         /**
384          * Translates a RoleState to the corresponding MastershipRole.
385          *
386          * @param response role state
387          * @return a MastershipRole
388          */
389         private MastershipRole roleOf(RoleState response) {
390             switch (response) {
391                 case MASTER:
392                     return MastershipRole.MASTER;
393                 case EQUAL:
394                     return MastershipRole.STANDBY;
395                 case SLAVE:
396                     return MastershipRole.NONE;
397                 default:
398                     LOG.warn("unknown role {}", response);
399                     return null;
400             }
401         }
402
403         /**
404          * Builds a list of port descriptions for a given list of ports.
405          *
406          * @return list of portdescriptions
407          */
408         private List<PortDescription> buildPortDescriptions(OpenFlowSwitch sw) {
409             final List<PortDescription> portDescs = new ArrayList<>(sw.getPorts().size());
410             if (!(Device.Type.ROADM.equals(sw.deviceType()))) {
411                   sw.getPorts().forEach(port -> portDescs.add(buildPortDescription(port)));
412             }
413
414             OpenFlowOpticalSwitch opsw;
415             switch (sw.deviceType()) {
416                 case ROADM:
417                     opsw = (OpenFlowOpticalSwitch) sw;
418                     List<OFPortDesc> ports = opsw.getPorts();
419                     LOG.debug("SW ID {} , ETH- ODU CLT Ports {}", opsw.getId(), ports);
420                     // ODU client ports are reported as ETH
421                     ports.forEach(port -> portDescs.add(buildOduCltPortDescription(port)));
422
423                     opsw.getPortTypes().forEach(type -> {
424                     List<? extends OFObject> portsOf = opsw.getPortsOf(type);
425                     LOG.debug("Ports Of{}", portsOf);
426                     portsOf.forEach(
427                         op -> {
428                             portDescs.add(buildPortDescription(type, (OFObject) op));
429                         }
430                      );
431                     });
432                     break;
433                 case FIBER_SWITCH:
434                     opsw = (OpenFlowOpticalSwitch) sw;
435                     opsw.getPortTypes().forEach(type -> {
436                         opsw.getPortsOf(type).forEach(
437                                 op -> {
438                                     portDescs.add(buildPortDescription((OFCalientPortDescStatsEntry) op));
439                                 }
440                         );
441                     });
442                     break;
443                 default:
444                     break;
445             }
446
447             return portDescs;
448         }
449
450         private PortDescription buildOduCltPortDescription(OFPortDesc port) {
451             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
452             boolean enabled = !port.getState().contains(OFPortState.LINK_DOWN) &&
453                               !port.getConfig().contains(OFPortConfig.PORT_DOWN);
454             Long portSpeed = portSpeed(port);
455             OduCltPort.SignalType sigType = null;
456
457             switch (portSpeed.toString()) {
458                 case "1":
459                     sigType = OduCltPort.SignalType.CLT_1GBE;
460                     break;
461                 case "10":
462                     sigType = OduCltPort.SignalType.CLT_10GBE;
463                     break;
464                 case "40":
465                     sigType = OduCltPort.SignalType.CLT_40GBE;
466                     break;
467                 case "100":
468                     sigType = OduCltPort.SignalType.CLT_100GBE;
469                     break;
470                 default:
471                     throw new RuntimeException("Un recognize OduClt speed: " + portSpeed.toString());
472             }
473
474             SparseAnnotations annotations = buildOduCltAnnotation(port);
475             return new OduCltPortDescription(portNo, enabled, sigType, annotations);
476         }
477
478         private SparseAnnotations buildOduCltAnnotation(OFPortDesc port) {
479             SparseAnnotations annotations = null;
480             String portName = Strings.emptyToNull(port.getName());
481             if (portName != null) {
482                  annotations = DefaultAnnotations.builder()
483                         .set(AnnotationKeys.PORT_NAME, portName)
484                         .set(AnnotationKeys.STATIC_PORT, Boolean.TRUE.toString()).build();
485             }
486             return annotations;
487         }
488
489         private PortDescription buildPortDescription(PortDescPropertyType ptype, OFObject port) {
490             if (port instanceof  OFPortOptical) {
491                return buildPortDescription(ptype, (OFPortOptical) port);
492             }
493             return buildPortDescription(ptype, (OFExpPort) port);
494         }
495
496         /**
497          * Build a portDescription from a given a port description describing some
498          * Optical port.
499          *
500          * @param ptype description property type.
501          * @param port the port to build from.
502          * @return portDescription for the port.
503          */
504         private PortDescription buildPortDescription(PortDescPropertyType ptype, OFExpPort port) {
505             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
506             boolean enabled = !port.getState().contains(OFPortState.LINK_DOWN)
507                     && !port.getConfig().contains(OFPortConfig.PORT_DOWN);
508             SparseAnnotations annotations = makePortNameAnnotation(port.getName());
509
510             OFExpPortDescPropOpticalTransport firstProp = port.getProperties().get(0);
511             OFPortOpticalTransportSignalType sigType = firstProp.getPortSignalType();
512
513             DefaultPortDescription portDes = null;
514             switch (sigType) {
515             case OMSN:
516                 portDes =  new OmsPortDescription(portNo, enabled, FREQ193_1, FREQ193_1.add(FREQ4_4),
517                        FREQ100, annotations);
518                 break;
519             case OCH:
520                 OFExpPortOpticalTransportLayerEntry entry = firstProp.getFeatures().get(0).getValue().get(0);
521                 OFPortOpticalTransportLayerClass layerClass =  entry.getLayerClass();
522                 if (!OFPortOpticalTransportLayerClass.ODU.equals(layerClass)) {
523                     LOG.error("Unsupported layer Class {} ", layerClass);
524                     return null;
525                 }
526
527                 // convert to ONOS OduSignalType
528                 OduSignalType oduSignalType = OpenFlowDeviceValueMapper.
529                         lookupOduSignalType((byte) entry.getSignalType());
530                 //OchSignal is needed for OchPortDescription constructor,
531                 //yet not relevant for tunable OCH port, creating with default parameters
532                 OchSignal signalId = new OchSignal(GridType.DWDM, ChannelSpacing.CHL_50GHZ, 1, 1);
533
534                 portDes = new OchPortDescription(portNo, enabled,
535                         oduSignalType, true, signalId, annotations);
536
537                 break;
538             case OTU2:
539             case OTU4:
540                   LOG.error("Signal tpye OTU2/4 not supported yet ", port.toString());
541                   break;
542             default:
543                 break;
544             }
545
546             return portDes;
547         }
548
549         /**
550          * Creates an annotation for the port name if one is available.
551          *
552          * @param port description of the port
553          * @return annotation containing the port name if one is found,
554          *         null otherwise
555          */
556         private SparseAnnotations makePortNameAnnotation(String port) {
557             SparseAnnotations annotations = null;
558             String portName = Strings.emptyToNull(port);
559             if (portName != null) {
560                 annotations = DefaultAnnotations.builder()
561                         .set(AnnotationKeys.PORT_NAME, portName).build();
562             }
563             return annotations;
564         }
565
566         /**
567          * Build a portDescription from a given Ethernet port description.
568          *
569          * @param port the port to build from.
570          * @return portDescription for the port.
571          */
572         private PortDescription buildPortDescription(OFPortDesc port) {
573             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
574             boolean enabled =
575                     !port.getState().contains(OFPortState.LINK_DOWN) &&
576                             !port.getConfig().contains(OFPortConfig.PORT_DOWN);
577             Port.Type type = port.getCurr().contains(OFPortFeatures.PF_FIBER) ? FIBER : COPPER;
578             SparseAnnotations annotations = makePortNameAnnotation(port.getName());
579             return new DefaultPortDescription(portNo, enabled, type,
580                                               portSpeed(port), annotations);
581         }
582
583         /**
584          * Build a portDescription from a given a port description describing some
585          * Optical port.
586          *
587          * @param port description property type.
588          * @param port the port to build from.
589          * @return portDescription for the port.
590          */
591         private PortDescription buildPortDescription(PortDescPropertyType ptype, OFPortOptical port) {
592             checkArgument(port.getDesc().size() >= 1);
593
594             // Minimally functional fixture. This needs to be fixed as we add better support.
595             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
596
597             boolean enabled = !port.getState().contains(OFPortState.LINK_DOWN)
598                     && !port.getConfig().contains(OFPortConfig.PORT_DOWN);
599             SparseAnnotations annotations = makePortNameAnnotation(port.getName());
600
601             if (port.getVersion() == OFVersion.OF_13
602                     && ptype == PortDescPropertyType.OPTICAL_TRANSPORT) {
603                 // At this point, not much is carried in the optical port message.
604                 LOG.debug("Optical transport port message {}", port.toString());
605             } else {
606                 // removable once 1.4+ support complete.
607                 LOG.debug("Unsupported optical port properties");
608             }
609
610             OFPortDescPropOpticalTransport desc = port.getDesc().get(0);
611             switch (desc.getPortSignalType()) {
612                 // FIXME: use constants once loxi has full optical extensions
613                 case 2:     // OMS port
614                     // Assume complete optical spectrum and 50 GHz grid
615                     // LINC-OE is only supported optical OF device for now
616                     return new OmsPortDescription(portNo, enabled,
617                             Spectrum.U_BAND_MIN, Spectrum.O_BAND_MAX, Frequency.ofGHz(50), annotations);
618                 case 5:     // OCH port
619                     OchSignal signal = new OchSignal(GridType.DWDM, ChannelSpacing.CHL_50GHZ, 0, 4);
620                     return new OchPortDescription(portNo, enabled, OduSignalType.ODU4,
621                             true, signal, annotations);
622                 default:
623                     break;
624             }
625
626             return new DefaultPortDescription(portNo, enabled, FIBER, 0, annotations);
627         }
628
629         /**
630          * Build a portDescription from a given port description describing a fiber switch optical port.
631          *
632          * @param port description property type.
633          * @param port the port to build from.
634          * @return portDescription for the port.
635          */
636         private PortDescription buildPortDescription(OFCalientPortDescStatsEntry port) {
637             PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
638
639             // FIXME when Calient OF agent reports port status
640             boolean enabled = true;
641             SparseAnnotations annotations = makePortNameAnnotation(port.getName());
642
643             // S160 data sheet
644             // Wavelength range: 1260 - 1630 nm, grid is irrelevant for this type of switch
645             return new OmsPortDescription(portNo, enabled,
646                     Spectrum.U_BAND_MIN, Spectrum.O_BAND_MAX, Frequency.ofGHz(100), annotations);
647         }
648
649         private PortDescription buildPortDescription(OFPortStatus status) {
650             OFPortDesc port = status.getDesc();
651             if (status.getReason() != OFPortReason.DELETE) {
652                 return buildPortDescription(port);
653             } else {
654                 PortNumber portNo = PortNumber.portNumber(port.getPortNo().getPortNumber());
655                 Port.Type type = port.getCurr().contains(OFPortFeatures.PF_FIBER) ? FIBER : COPPER;
656                 SparseAnnotations annotations = makePortNameAnnotation(port.getName());
657                 return new DefaultPortDescription(portNo, false, type,
658                                                   portSpeed(port), annotations);
659             }
660         }
661
662         private long portSpeed(OFPortDesc port) {
663             if (port.getVersion() == OFVersion.OF_13) {
664                 return port.getCurrSpeed() / MBPS;
665             }
666
667             PortSpeed portSpeed = PortSpeed.SPEED_NONE;
668             for (OFPortFeatures feat : port.getCurr()) {
669                 portSpeed = PortSpeed.max(portSpeed, feat.getPortSpeed());
670             }
671             return portSpeed.getSpeedBps() / MBPS;
672         }
673
674         @Override
675         public void handleMessage(Dpid dpid, OFMessage msg) {
676             switch (msg.getType()) {
677                 case STATS_REPLY:
678                     if (((OFStatsReply) msg).getStatsType() == OFStatsType.PORT) {
679                         OFPortStatsReply portStatsReply = (OFPortStatsReply) msg;
680                         List<OFPortStatsEntry> portStatsReplyList = portStatsReplies.get(dpid);
681                         if (portStatsReplyList == null) {
682                             portStatsReplyList = Lists.newArrayList();
683                         }
684                         portStatsReplyList.addAll(portStatsReply.getEntries());
685                         portStatsReplies.put(dpid, portStatsReplyList);
686                         if (!portStatsReply.getFlags().contains(OFStatsReplyFlags.REPLY_MORE)) {
687                             pushPortMetrics(dpid, portStatsReplies.get(dpid));
688                             portStatsReplies.get(dpid).clear();
689                         }
690                     }
691                     break;
692                 default:
693                     break;
694             }
695         }
696     }
697 }