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