Do not keep per-switch state in DeviceManagerImpl
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / device / DeviceManagerImpl.java
1 /**
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.openflowplugin.impl.device;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import io.netty.util.HashedWheelTimer;
15 import java.math.BigInteger;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.concurrent.ScheduledThreadPoolExecutor;
23 import java.util.concurrent.TimeUnit;
24 import javax.annotation.CheckForNull;
25 import javax.annotation.Nonnull;
26 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
27 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
28 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
29 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
30 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
31 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
32 import org.opendaylight.openflowplugin.api.ConnectionException;
33 import org.opendaylight.openflowplugin.api.OFConstants;
34 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
35 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
36 import org.opendaylight.openflowplugin.api.openflow.connection.ThrottledNotificationsOfferer;
37 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
38 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
39 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
40 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
41 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
42 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
43 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
44 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
45 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
46 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
47 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
48 import org.opendaylight.openflowplugin.impl.common.MultipartRequestInputFactory;
49 import org.opendaylight.openflowplugin.impl.common.NodeStaticReplyTranslatorUtil;
50 import org.opendaylight.openflowplugin.impl.connection.OutboundQueueProviderImpl;
51 import org.opendaylight.openflowplugin.impl.connection.ThrottledNotificationsOffererImpl;
52 import org.opendaylight.openflowplugin.impl.device.listener.OpenflowProtocolListenerFullImpl;
53 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
54 import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsData;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsDataBuilder;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupFeatures;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterFeatures;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.CapabilitiesV10;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.MultipartReplyBody;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyDescCase;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupFeaturesCase;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterFeaturesCase;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortDescCase;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCase;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.desc._case.MultipartReplyDesc;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.features._case.MultipartReplyGroupFeatures;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.features._case.MultipartReplyMeterFeatures;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.MultipartReplyPortDesc;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeatures;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsDataBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
92 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
93 import org.opendaylight.yangtools.yang.common.RpcError;
94 import org.opendaylight.yangtools.yang.common.RpcResult;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
97
98 /**
99  *
100  */
101 public class DeviceManagerImpl implements DeviceManager, AutoCloseable {
102
103     private static final Logger LOG = LoggerFactory.getLogger(DeviceManagerImpl.class);
104
105     private static final long TICK_DURATION = 10; // 0.5 sec.
106     private ScheduledThreadPoolExecutor spyPool;
107     private final int spyRate = 10;
108
109     private final DataBroker dataBroker;
110     private final HashedWheelTimer hashedWheelTimer;
111     private TranslatorLibrary translatorLibrary;
112     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
113     private NotificationService notificationService;
114     private NotificationPublishService notificationPublishService;
115     private ThrottledNotificationsOfferer throttledNotificationsOfferer;
116
117     private final List<DeviceContext> deviceContexts = new ArrayList<DeviceContext>();
118     private final MessageIntelligenceAgency messageIntelligenceAgency;
119
120     private final long barrierNanos = TimeUnit.MILLISECONDS.toNanos(500);
121     private final int maxQueueDepth = 25600;
122
123     public DeviceManagerImpl(@Nonnull final DataBroker dataBroker,
124                              @Nonnull final MessageIntelligenceAgency messageIntelligenceAgency) {
125         this.dataBroker = Preconditions.checkNotNull(dataBroker);
126         hashedWheelTimer = new HashedWheelTimer(TICK_DURATION, TimeUnit.MILLISECONDS, 500);
127         /* merge empty nodes to oper DS to predict any problems with missing parent for Node */
128         final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
129
130         final NodesBuilder nodesBuilder = new NodesBuilder();
131         nodesBuilder.setNode(Collections.<Node>emptyList());
132         tx.merge(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(Nodes.class), nodesBuilder.build());
133         tx.submit();
134
135         this.messageIntelligenceAgency = messageIntelligenceAgency;
136     }
137
138     @Override
139     public void setDeviceInitializationPhaseHandler(final DeviceInitializationPhaseHandler handler) {
140         deviceInitPhaseHandler = handler;
141     }
142
143     @Override
144     public void onDeviceContextLevelUp(final DeviceContext deviceContext) {
145         // final phase - we have to add new Device to MD-SAL DataStore
146         Preconditions.checkNotNull(deviceContext);
147         ((DeviceContextImpl) deviceContext).submitTransaction();
148     }
149
150     @Override
151     public void deviceConnected(@CheckForNull final ConnectionContext connectionContext) {
152         Preconditions.checkArgument(connectionContext != null);
153
154         final Short version = connectionContext.getFeatures().getVersion();
155         OutboundQueueProvider outboundQueueProvider = new OutboundQueueProviderImpl(version);
156         connectionContext.getConnectionAdapter().registerOutboundQueueHandler(outboundQueueProvider, maxQueueDepth, barrierNanos);
157         connectionContext.setOutboundQueueProvider(outboundQueueProvider);
158
159         final DeviceState deviceState = new DeviceStateImpl(connectionContext.getFeatures(), connectionContext.getNodeId());
160
161         final DeviceContext deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker, hashedWheelTimer, messageIntelligenceAgency, throttledNotificationsOfferer);
162
163         deviceContext.setNotificationService(notificationService);
164         deviceContext.setNotificationPublishService(notificationPublishService);
165         deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, deviceState.getNodeInstanceIdentifier(), new NodeBuilder().setId(deviceState.getNodeId()).build());
166
167         connectionContext.setDeviceDisconnectedHandler(deviceContext);
168         deviceContext.setTranslatorLibrary(translatorLibrary);
169         deviceContext.addDeviceContextClosedHandler(this);
170
171         final OpenflowProtocolListenerFullImpl messageListener = new OpenflowProtocolListenerFullImpl(
172                 connectionContext.getConnectionAdapter(), deviceContext);
173
174         final ListenableFuture<List<RpcResult<List<MultipartReply>>>> deviceFeaturesFuture;
175
176
177         if (OFConstants.OFP_VERSION_1_0 == version) {
178             final CapabilitiesV10 capabilitiesV10 = connectionContext.getFeatures().getCapabilitiesV10();
179
180             DeviceStateUtil.setDeviceStateBasedOnV10Capabilities(deviceState, capabilitiesV10);
181
182             deviceFeaturesFuture = createDeviceFeaturesForOF10(deviceContext, deviceState);
183             // create empty tables after device description is processed
184             chainTableTrunkWriteOF10(deviceContext, deviceFeaturesFuture);
185
186             for (final PortGrouping port : connectionContext.getFeatures().getPhyPort()) {
187                 final short ofVersion = deviceContext.getDeviceState().getVersion();
188                 final TranslatorKey translatorKey = new TranslatorKey(ofVersion, PortGrouping.class.getName());
189                 final MessageTranslator<PortGrouping, FlowCapableNodeConnector> translator = deviceContext.oook().lookupTranslator(translatorKey);
190                 final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, deviceContext, null);
191
192                 final BigInteger dataPathId = deviceContext.getPrimaryConnectionContext().getFeatures().getDatapathId();
193                 final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil.nodeConnectorId(dataPathId.toString(), port.getPortNo(), ofVersion);
194                 final NodeConnectorBuilder ncBuilder = new NodeConnectorBuilder().setId(nodeConnectorId);
195                 ncBuilder.addAugmentation(FlowCapableNodeConnector.class, fcNodeConnector);
196                 ncBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class, new FlowCapableNodeConnectorStatisticsDataBuilder().build());
197                 final NodeConnector connector = ncBuilder.build();
198                 final InstanceIdentifier<NodeConnector> connectorII = deviceState.getNodeInstanceIdentifier().child(NodeConnector.class, connector.getKey());
199                 deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, connectorII, connector);
200             }
201         } else if (OFConstants.OFP_VERSION_1_3 == version) {
202             final Capabilities capabilities = connectionContext.getFeatures().getCapabilities();
203             LOG.debug("Setting capabilities for device {}", deviceContext.getDeviceState().getNodeId());
204             DeviceStateUtil.setDeviceStateBasedOnV13Capabilities(deviceState, capabilities);
205             deviceFeaturesFuture = createDeviceFeaturesForOF13(deviceContext, deviceState);
206         } else {
207             deviceFeaturesFuture = Futures.immediateFailedFuture(new ConnectionException("Unsupported version " + version));
208         }
209
210         Futures.addCallback(deviceFeaturesFuture, new FutureCallback<List<RpcResult<List<MultipartReply>>>>() {
211             @Override
212             public void onSuccess(final List<RpcResult<List<MultipartReply>>> result) {
213                 deviceContext.getDeviceState().setValid(true);
214                 deviceInitPhaseHandler.onDeviceContextLevelUp(deviceContext);
215             }
216
217             @Override
218             public void onFailure(final Throwable t) {
219                 // FIXME : remove session
220                 LOG.trace("Device capabilities gathering future failed.");
221                 LOG.trace("more info in exploration failure..", t);
222             }
223         });
224     }
225
226     private static void chainTableTrunkWriteOF10(final DeviceContext deviceContext, final ListenableFuture<List<RpcResult<List<MultipartReply>>>> deviceFeaturesFuture) {
227         Futures.addCallback(deviceFeaturesFuture, new FutureCallback<List<RpcResult<List<MultipartReply>>>>() {
228             @Override
229             public void onSuccess(final List<RpcResult<List<MultipartReply>>> results) {
230                 boolean allSucceeded = true;
231                 for (final RpcResult<List<MultipartReply>> rpcResult : results) {
232                     allSucceeded &= rpcResult.isSuccessful();
233                 }
234                 if (allSucceeded) {
235                     createEmptyFlowCapableNodeInDs(deviceContext);
236                     makeEmptyTables(deviceContext, deviceContext.getDeviceState().getNodeInstanceIdentifier(),
237                             deviceContext.getDeviceState().getFeatures().getTables());
238                 }
239             }
240
241             @Override
242             public void onFailure(final Throwable t) {
243                 //NOOP
244             }
245         });
246     }
247
248     private ListenableFuture<RpcResult<List<MultipartReply>>> processReplyDesc(final DeviceContext deviceContext,
249                                                                                final DeviceState deviceState) {
250
251         final ListenableFuture<RpcResult<List<MultipartReply>>> replyDesc = getNodeStaticInfo(MultipartType.OFPMPDESC,
252                 deviceContext,
253                 deviceState.getNodeInstanceIdentifier(),
254                 deviceState.getVersion());
255         return replyDesc;
256     }
257
258     private ListenableFuture<List<RpcResult<List<MultipartReply>>>> createDeviceFeaturesForOF10(final DeviceContext deviceContext,
259                                                                                                 final DeviceState deviceState) {
260         return Futures.allAsList(Arrays.asList(processReplyDesc(deviceContext, deviceState)));
261     }
262
263     private ListenableFuture<List<RpcResult<List<MultipartReply>>>> createDeviceFeaturesForOF13(final DeviceContext deviceContext,
264                                                                                                 final DeviceState deviceState) {
265         final ListenableFuture<RpcResult<List<MultipartReply>>> replyDesc = processReplyDesc(deviceContext, deviceState);
266
267         final ListenableFuture<RpcResult<List<MultipartReply>>> replyMeterFeature = getNodeStaticInfo(MultipartType.OFPMPMETERFEATURES,
268                 deviceContext,
269                 deviceState.getNodeInstanceIdentifier(),
270                 deviceState.getVersion());
271
272         final ListenableFuture<RpcResult<List<MultipartReply>>> replyGroupFeatures = getNodeStaticInfo(MultipartType.OFPMPGROUPFEATURES,
273                 deviceContext,
274                 deviceState.getNodeInstanceIdentifier(),
275                 deviceState.getVersion());
276
277         final ListenableFuture<RpcResult<List<MultipartReply>>> replyTableFeatures = getNodeStaticInfo(MultipartType.OFPMPTABLEFEATURES,
278                 deviceContext,
279                 deviceState.getNodeInstanceIdentifier(),
280                 deviceState.getVersion());
281
282         final ListenableFuture<RpcResult<List<MultipartReply>>> replyPortDescription = getNodeStaticInfo(MultipartType.OFPMPPORTDESC,
283                 deviceContext,
284                 deviceState.getNodeInstanceIdentifier(),
285                 deviceState.getVersion());
286
287         return Futures.allAsList(Arrays.asList(replyDesc,
288                 replyMeterFeature,
289                 replyGroupFeatures,
290 //                        replyTableFeatures,
291                 replyPortDescription));
292
293     }
294
295     @Override
296     public TranslatorLibrary oook() {
297         return translatorLibrary;
298     }
299
300     @Override
301     public void setTranslatorLibrary(final TranslatorLibrary translatorLibrary) {
302         this.translatorLibrary = translatorLibrary;
303     }
304
305     private static ListenableFuture<RpcResult<List<MultipartReply>>> getNodeStaticInfo(final MultipartType type, final DeviceContext deviceContext,
306                                                                                 final InstanceIdentifier<Node> nodeII, final short version) {
307
308         final OutboundQueue queue = deviceContext.getPrimaryConnectionContext().getOutboundQueueProvider();
309
310         final Long reserved = deviceContext.getReservedXid();
311         final RequestContext<List<MultipartReply>> requestContext = new AbstractRequestContext<List<MultipartReply>>(reserved) {
312             @Override
313             public void close() {
314                 //NOOP
315             }
316         };
317
318         final Xid xid = requestContext.getXid();
319
320         LOG.trace("Hooking xid {} to device context - precaution.", reserved);
321
322         final ListenableFuture<RpcResult<List<MultipartReply>>> requestContextFuture = requestContext.getFuture();
323
324         final MultiMsgCollector multiMsgCollector = deviceContext.getMultiMsgCollector();
325         multiMsgCollector.registerMultipartRequestContext(requestContext);
326
327         createSuccessProcessingCallback(type, deviceContext, nodeII, requestContextFuture);
328
329         queue.commitEntry(xid.getValue(), MultipartRequestInputFactory.makeMultipartRequestInput(xid.getValue(), version, type), new FutureCallback<OfHeader>() {
330             @Override
331             public void onSuccess(final OfHeader ofHeader) {
332                 if (ofHeader instanceof MultipartReply) {
333                     MultipartReply multipartReply = (MultipartReply) ofHeader;
334                     multiMsgCollector.addMultipartMsg(multipartReply);
335                 } else {
336                     if (null != ofHeader) {
337                         LOG.info("Unexpected response type received {}.", ofHeader.getClass());
338                     } else {
339                         LOG.info("Response received is null.");
340                     }
341                 }
342
343             }
344
345             @Override
346             public void onFailure(final Throwable t) {
347                 LOG.info("Fail response from OutboundQueue.");
348             }
349         });
350
351
352         return requestContext.getFuture();
353     }
354
355     private static void createSuccessProcessingCallback(final MultipartType type, final DeviceContext deviceContext, final InstanceIdentifier<Node> nodeII, final ListenableFuture<RpcResult<List<MultipartReply>>> requestContextFuture) {
356         Futures.addCallback(requestContextFuture, new FutureCallback<RpcResult<List<MultipartReply>>>() {
357             @Override
358             public void onSuccess(final RpcResult<List<MultipartReply>> rpcResult) {
359                 final List<MultipartReply> result = rpcResult.getResult();
360                 if (result != null) {
361                     LOG.info("Static node {} info: {} collected", nodeII.toString(), type);
362                     translateAndWriteReply(type, deviceContext, nodeII, result);
363                 } else {
364                     final Iterator<RpcError> rpcErrorIterator = rpcResult.getErrors().iterator();
365                     while (rpcErrorIterator.hasNext()) {
366                         final RpcError rpcError = rpcErrorIterator.next();
367                         LOG.info("Failed to retrieve static node {} info: {}", type, rpcError.getMessage());
368                         if (null != rpcError.getCause()) {
369                             LOG.trace("Detailed error:", rpcError.getCause());
370                         }
371                     }
372                     if (MultipartType.OFPMPTABLEFEATURES.equals(type)) {
373                         makeEmptyTables(deviceContext, nodeII, deviceContext.getPrimaryConnectionContext().getFeatures().getTables());
374                     }
375                 }
376             }
377
378             @Override
379             public void onFailure(final Throwable throwable) {
380                 LOG.info("Request of type {} for static info of node {} failed.", type, nodeII);
381             }
382         });
383     }
384
385     // FIXME : remove after ovs tableFeatures fix
386     private static void makeEmptyTables(final DeviceContext dContext, final InstanceIdentifier<Node> nodeII, final Short nrOfTables) {
387         LOG.debug("About to create {} empty tables.", nrOfTables);
388         for (int i = 0; i < nrOfTables; i++) {
389             final short tId = (short) i;
390             final InstanceIdentifier<Table> tableII = nodeII.augmentation(FlowCapableNode.class).child(Table.class, new TableKey(tId));
391             final TableBuilder tableBuilder = new TableBuilder().setId(tId).addAugmentation(FlowTableStatisticsData.class, new FlowTableStatisticsDataBuilder().build());
392             dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, tableBuilder.build());
393         }
394     }
395
396     private static void translateAndWriteReply(final MultipartType type, final DeviceContext dContext,
397                                                final InstanceIdentifier<Node> nodeII, final Collection<MultipartReply> result) {
398         for (final MultipartReply reply : result) {
399             final MultipartReplyBody body = reply.getMultipartReplyBody();
400             switch (type) {
401                 case OFPMPDESC:
402                     Preconditions.checkArgument(body instanceof MultipartReplyDescCase);
403                     final MultipartReplyDesc replyDesc = ((MultipartReplyDescCase) body).getMultipartReplyDesc();
404                     final FlowCapableNode fcNode = NodeStaticReplyTranslatorUtil.nodeDescTranslator(replyDesc);
405                     final InstanceIdentifier<FlowCapableNode> fNodeII = nodeII.augmentation(FlowCapableNode.class);
406                     dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, fNodeII, fcNode);
407                     break;
408
409                 case OFPMPTABLEFEATURES:
410                     Preconditions.checkArgument(body instanceof MultipartReplyTableFeaturesCase);
411                     final MultipartReplyTableFeatures tableFeatures = ((MultipartReplyTableFeaturesCase) body).getMultipartReplyTableFeatures();
412                     final List<TableFeatures> tables = NodeStaticReplyTranslatorUtil.nodeTableFeatureTranslator(tableFeatures);
413                     for (final TableFeatures table : tables) {
414                         final Short tableId = table.getTableId();
415                         final InstanceIdentifier<Table> tableII = nodeII.augmentation(FlowCapableNode.class).child(Table.class, new TableKey(tableId));
416                         final TableBuilder tableBuilder = new TableBuilder().setId(tableId).setTableFeatures(Collections.singletonList(table));
417                         tableBuilder.addAugmentation(FlowTableStatisticsData.class, new FlowTableStatisticsDataBuilder().build());
418                         dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, tableBuilder.build());
419                     }
420                     break;
421
422                 case OFPMPMETERFEATURES:
423                     Preconditions.checkArgument(body instanceof MultipartReplyMeterFeaturesCase);
424                     final MultipartReplyMeterFeatures meterFeatures = ((MultipartReplyMeterFeaturesCase) body).getMultipartReplyMeterFeatures();
425                     final NodeMeterFeatures mFeature = NodeStaticReplyTranslatorUtil.nodeMeterFeatureTranslator(meterFeatures);
426                     final InstanceIdentifier<NodeMeterFeatures> mFeatureII = nodeII.augmentation(NodeMeterFeatures.class);
427                     dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, mFeatureII, mFeature);
428                     if (0L < mFeature.getMeterFeatures().getMaxMeter().getValue()) {
429                         dContext.getDeviceState().setMeterAvailable(true);
430                     }
431                     break;
432
433                 case OFPMPGROUPFEATURES:
434                     Preconditions.checkArgument(body instanceof MultipartReplyGroupFeaturesCase);
435                     final MultipartReplyGroupFeatures groupFeatures = ((MultipartReplyGroupFeaturesCase) body).getMultipartReplyGroupFeatures();
436                     final NodeGroupFeatures gFeature = NodeStaticReplyTranslatorUtil.nodeGroupFeatureTranslator(groupFeatures);
437                     final InstanceIdentifier<NodeGroupFeatures> gFeatureII = nodeII.augmentation(NodeGroupFeatures.class);
438                     dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, gFeatureII, gFeature);
439                     break;
440
441                 case OFPMPPORTDESC:
442                     Preconditions.checkArgument(body instanceof MultipartReplyPortDescCase);
443                     final MultipartReplyPortDesc portDesc = ((MultipartReplyPortDescCase) body).getMultipartReplyPortDesc();
444                     for (final PortGrouping port : portDesc.getPorts()) {
445                         final short ofVersion = dContext.getDeviceState().getVersion();
446                         final TranslatorKey translatorKey = new TranslatorKey(ofVersion, PortGrouping.class.getName());
447                         final MessageTranslator<PortGrouping, FlowCapableNodeConnector> translator = dContext.oook().lookupTranslator(translatorKey);
448                         final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, dContext, null);
449
450                         final BigInteger dataPathId = dContext.getPrimaryConnectionContext().getFeatures().getDatapathId();
451                         final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil.nodeConnectorId(dataPathId.toString(), port.getPortNo(), ofVersion);
452                         final NodeConnectorBuilder ncBuilder = new NodeConnectorBuilder().setId(nodeConnectorId);
453                         ncBuilder.addAugmentation(FlowCapableNodeConnector.class, fcNodeConnector);
454                         ncBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class, new FlowCapableNodeConnectorStatisticsDataBuilder().build());
455                         final NodeConnector connector = ncBuilder.build();
456
457                         final InstanceIdentifier<NodeConnector> connectorII = nodeII.child(NodeConnector.class, connector.getKey());
458                         dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, connectorII, connector);
459                     }
460
461                     break;
462
463                 default:
464                     throw new IllegalArgumentException("Unnexpected MultipartType " + type);
465             }
466         }
467     }
468
469     @Override
470     public void setNotificationService(final NotificationService notificationServiceParam) {
471         notificationService = notificationServiceParam;
472     }
473
474     @Override
475     public void setNotificationPublishService(final NotificationPublishService notificationService) {
476         this.notificationPublishService = notificationService;
477     }
478
479     @Override
480     public void close() throws Exception {
481         for (final DeviceContext deviceContext : deviceContexts) {
482             deviceContext.close();
483         }
484         if (throttledNotificationsOfferer != null) {
485             throttledNotificationsOfferer.close();
486         }
487     }
488
489     private static void createEmptyFlowCapableNodeInDs(final DeviceContext deviceContext) {
490         final FlowCapableNodeBuilder flowCapableNodeBuilder = new FlowCapableNodeBuilder();
491         final InstanceIdentifier<FlowCapableNode> fNodeII = deviceContext.getDeviceState().getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
492         deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, fNodeII, flowCapableNodeBuilder.build());
493     }
494
495     @Override
496     public void onDeviceContextClosed(final DeviceContext deviceContext) {
497         deviceContexts.remove(deviceContext);
498     }
499
500     @Override
501     public void initialize() {
502         spyPool = new ScheduledThreadPoolExecutor(1);
503         spyPool.scheduleAtFixedRate(messageIntelligenceAgency, spyRate, spyRate, TimeUnit.SECONDS);
504
505         throttledNotificationsOfferer = new ThrottledNotificationsOffererImpl(notificationPublishService, messageIntelligenceAgency);
506     }
507 }