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