Improve cleanup after device disconnected event
[openflowplugin.git] / openflowplugin-impl / src / main / java / org / opendaylight / openflowplugin / impl / util / DeviceInitializationUtils.java
1 /*
2  * Copyright (c) 2016 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
9 package org.opendaylight.openflowplugin.impl.util;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.AsyncFunction;
13 import com.google.common.util.concurrent.FutureCallback;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import com.google.common.util.concurrent.SettableFuture;
17 import java.math.BigInteger;
18 import java.net.InetSocketAddress;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.Objects;
24 import java.util.concurrent.ExecutionException;
25 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
26 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
27 import org.opendaylight.openflowplugin.api.ConnectionException;
28 import org.opendaylight.openflowplugin.api.OFConstants;
29 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
30 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
31 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
32 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
33 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
34 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
35 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
36 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
37 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
38 import org.opendaylight.openflowplugin.impl.common.MultipartRequestInputFactory;
39 import org.opendaylight.openflowplugin.impl.common.NodeStaticReplyTranslatorUtil;
40 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
41 import org.opendaylight.openflowplugin.openflow.md.core.sal.SwitchFeaturesUtil;
42 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorExecutor;
43 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IetfInetUtil;
44 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.IpAddress;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsData;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.table.statistics.rev131215.FlowTableStatisticsDataBuilder;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupFeatures;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorBuilder;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterFeatures;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.CapabilitiesV10;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutputBuilder;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.MultipartReplyBody;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyDescCase;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyGroupFeaturesCase;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyMeterFeaturesCase;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyPortDescCase;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyTableFeaturesCase;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.desc._case.MultipartReplyDesc;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.group.features._case.MultipartReplyGroupFeatures;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.meter.features._case.MultipartReplyMeterFeatures;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.port.desc._case.MultipartReplyPortDesc;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.table.features._case.MultipartReplyTableFeatures;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsData;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.FlowCapableNodeConnectorStatisticsDataBuilder;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
82 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
83 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
84 import org.opendaylight.yangtools.yang.common.RpcError;
85 import org.opendaylight.yangtools.yang.common.RpcResult;
86 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89
90 public class DeviceInitializationUtils {
91
92     private static final Logger LOG = LoggerFactory.getLogger(DeviceInitializationUtils.class);
93
94     private DeviceInitializationUtils() {
95         // Hiding implicit constructor
96     }
97
98     /**
99      * InitializationNodeInformation is good to call only for MASTER otherwise we will have not empty transaction
100      * for every Cluster Node (SLAVE too) and we will get race-condition by closing Connection.
101      *
102      * @param deviceContext
103      * @param switchFeaturesMandatory
104      * @param convertorExecutor
105      */
106     public static void initializeNodeInformation(final DeviceContext deviceContext, final boolean switchFeaturesMandatory, final ConvertorExecutor convertorExecutor) throws ExecutionException, InterruptedException {
107         Preconditions.checkArgument(deviceContext != null);
108         final DeviceState deviceState = Preconditions.checkNotNull(deviceContext.getDeviceState());
109         final DeviceInfo deviceInfo = deviceContext.getDeviceInfo();
110         final ConnectionContext connectionContext = Preconditions.checkNotNull(deviceContext.getPrimaryConnectionContext());
111         final short version = deviceInfo.getVersion();
112         LOG.trace("initalizeNodeInformation for node {}", deviceInfo.getNodeId());
113         final SettableFuture<Void> returnFuture = SettableFuture.create();
114         addNodeToOperDS(deviceContext, returnFuture);
115         final ListenableFuture<List<RpcResult<List<MultipartReply>>>> deviceFeaturesFuture;
116         if (OFConstants.OFP_VERSION_1_0 == version) {
117             final CapabilitiesV10 capabilitiesV10 = connectionContext.getFeatures().getCapabilitiesV10();
118
119             DeviceStateUtil.setDeviceStateBasedOnV10Capabilities(deviceState, capabilitiesV10);
120
121             deviceFeaturesFuture = createDeviceFeaturesForOF10(deviceContext);
122             // create empty tables after device description is processed
123             chainTableTrunkWriteOF10(deviceContext, deviceFeaturesFuture);
124
125             final short ofVersion = deviceInfo.getVersion();
126             final TranslatorKey translatorKey = new TranslatorKey(ofVersion, PortGrouping.class.getName());
127             final MessageTranslator<PortGrouping, FlowCapableNodeConnector> translator = deviceContext.oook()
128                     .lookupTranslator(translatorKey);
129             final BigInteger dataPathId = deviceContext.getDeviceInfo().getDatapathId();
130
131             for (final PortGrouping port : connectionContext.getFeatures().getPhyPort()) {
132                 final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, deviceContext.getDeviceInfo(), null);
133
134                 final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil.nodeConnectorId(
135                         dataPathId.toString(), port.getPortNo(), ofVersion);
136                 final NodeConnectorBuilder ncBuilder = new NodeConnectorBuilder().setId(nodeConnectorId);
137                 ncBuilder.addAugmentation(FlowCapableNodeConnector.class, fcNodeConnector);
138                 ncBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class,
139                         new FlowCapableNodeConnectorStatisticsDataBuilder().build());
140                 final NodeConnector connector = ncBuilder.build();
141                 final InstanceIdentifier<NodeConnector> connectorII = deviceInfo.getNodeInstanceIdentifier().child(
142                         NodeConnector.class, connector.getKey());
143                 try {
144                     deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, connectorII, connector);
145                 } catch (final Exception e) {
146                     LOG.debug("initializeNodeInformation: Failed to write node {} to DS ", deviceInfo.getNodeId().toString(),
147                             e);
148                 }
149
150             }
151         } else if (OFConstants.OFP_VERSION_1_3 == version) {
152             final Capabilities capabilities = connectionContext.getFeatures().getCapabilities();
153             LOG.debug("Setting capabilities for device {}", deviceInfo.getNodeId());
154             DeviceStateUtil.setDeviceStateBasedOnV13Capabilities(deviceState, capabilities);
155             createDeviceFeaturesForOF13(deviceContext, switchFeaturesMandatory, convertorExecutor).get();
156         } else {
157             throw new ExecutionException(new ConnectionException("Unsupported version " + version));
158         }
159
160     }
161
162     private static void addNodeToOperDS(final DeviceContext deviceContext, final SettableFuture<Void> future) {
163         Preconditions.checkArgument(deviceContext != null);
164         final NodeBuilder nodeBuilder = new NodeBuilder().setId(deviceContext.getDeviceInfo().getNodeId()).setNodeConnector(
165                 Collections.emptyList());
166         try {
167             deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(),
168                     nodeBuilder.build());
169         } catch (final Exception e) {
170             LOG.warn("addNodeToOperDS: Failed to write node {} to DS ", deviceContext.getDeviceInfo().getNodeId(), e);
171             future.cancel(true);
172         }
173     }
174
175     private static ListenableFuture<List<RpcResult<List<MultipartReply>>>> createDeviceFeaturesForOF10(
176             final DeviceContext deviceContext) {
177         final ListenableFuture<RpcResult<List<MultipartReply>>> replyDesc = getNodeStaticInfo(MultipartType.OFPMPDESC,
178                 deviceContext, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
179
180         return Futures.allAsList(Arrays.asList(replyDesc));
181     }
182
183     private static ListenableFuture<List<RpcResult<List<MultipartReply>>>> createDeviceFeaturesForOF13(
184             final DeviceContext deviceContext, final boolean switchFeaturesMandatory, final ConvertorExecutor convertorExecutor) {
185
186         final ListenableFuture<RpcResult<List<MultipartReply>>> replyDesc = getNodeStaticInfo(MultipartType.OFPMPDESC,
187                 deviceContext, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
188
189         //first process description reply, write data to DS and write consequent data if successful
190         return Futures.transform(replyDesc,
191                 new AsyncFunction<RpcResult<List<MultipartReply>>, List<RpcResult<List<MultipartReply>>>>() {
192                     @Override
193                     public ListenableFuture<List<RpcResult<List<MultipartReply>>>> apply(
194                             final RpcResult<List<MultipartReply>> rpcResult) throws Exception {
195
196                         translateAndWriteReply(MultipartType.OFPMPDESC, deviceContext,
197                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), rpcResult.getResult(), convertorExecutor);
198
199                         final ListenableFuture<RpcResult<List<MultipartReply>>> replyMeterFeature = getNodeStaticInfo(
200                                 MultipartType.OFPMPMETERFEATURES, deviceContext,
201                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
202
203                         createSuccessProcessingCallback(MultipartType.OFPMPMETERFEATURES, deviceContext,
204                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), replyMeterFeature, convertorExecutor);
205
206                         final ListenableFuture<RpcResult<List<MultipartReply>>> replyGroupFeatures = getNodeStaticInfo(
207                                 MultipartType.OFPMPGROUPFEATURES, deviceContext,
208                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
209                         createSuccessProcessingCallback(MultipartType.OFPMPGROUPFEATURES, deviceContext,
210                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), replyGroupFeatures, convertorExecutor);
211
212                         final ListenableFuture<RpcResult<List<MultipartReply>>> replyTableFeatures;
213
214                         if (deviceContext.isSkipTableFeatures()) {
215                             replyTableFeatures = RpcResultBuilder.<List<MultipartReply>>success().buildFuture();
216                         } else {
217                             replyTableFeatures = getNodeStaticInfo(
218                                     MultipartType.OFPMPTABLEFEATURES, deviceContext,
219                                     deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), deviceContext.getDeviceInfo().getVersion());
220                         }
221                         createSuccessProcessingCallback(MultipartType.OFPMPTABLEFEATURES, deviceContext,
222                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), replyTableFeatures, convertorExecutor);
223
224                         final ListenableFuture<RpcResult<List<MultipartReply>>> replyPortDescription = getNodeStaticInfo(
225                                 MultipartType.OFPMPPORTDESC, deviceContext, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(),
226                                 deviceContext.getDeviceInfo().getVersion());
227                         createSuccessProcessingCallback(MultipartType.OFPMPPORTDESC, deviceContext,
228                                 deviceContext.getDeviceInfo().getNodeInstanceIdentifier(), replyPortDescription, convertorExecutor);
229                         if (switchFeaturesMandatory) {
230                             return Futures.allAsList(Arrays.asList(replyMeterFeature, replyGroupFeatures,
231                                     replyTableFeatures, replyPortDescription));
232                         } else {
233                             return Futures.successfulAsList(Arrays.asList(replyMeterFeature, replyGroupFeatures,
234                                     replyTableFeatures, replyPortDescription));
235                         }
236                     }
237                 });
238
239     }
240
241     static void translateAndWriteReply(final MultipartType type, final DeviceContext dContext,
242                                        final InstanceIdentifier<Node> nodeII, final Collection<MultipartReply> result,
243                                        final ConvertorExecutor convertorExecutor) {
244         if (Objects.nonNull(result)) {
245             try {
246                 result.stream()
247                         .map(MultipartReply::getMultipartReplyBody)
248                         .forEach(multipartReplyBody -> {
249                             if (!(writeDesc(type, multipartReplyBody, dContext, nodeII)
250                                     || writeTableFeatures(type, multipartReplyBody, dContext, nodeII, convertorExecutor)
251                                     || writeMeterFeatures(type, multipartReplyBody, dContext, nodeII)
252                                     || writeGroupFeatures(type, multipartReplyBody, dContext, nodeII)
253                                     || writePortDesc(type, multipartReplyBody, dContext, nodeII))) {
254                                 throw new IllegalArgumentException("Unexpected MultipartType " + type);
255                             }
256                         });
257             } catch (final Exception e) {
258                 LOG.debug("translateAndWriteReply: Failed to write node {} to DS ", dContext.getDeviceInfo().getNodeId().toString(), e);
259             }
260         } else {
261             LOG.debug("translateAndWriteReply: Failed to write node {} to DS because we failed to gather device" +
262                             "info.",
263                     dContext.getDeviceInfo().getNodeId().toString());
264         }
265     }
266
267     private static boolean writeDesc(final MultipartType type,
268                                      final MultipartReplyBody body,
269                                      final DeviceContext dContext,
270                                      final InstanceIdentifier<Node> nodeII) {
271         if (!MultipartType.OFPMPDESC.equals(type)) {
272             return false;
273         }
274
275         Preconditions.checkArgument(body instanceof MultipartReplyDescCase);
276         final MultipartReplyDesc replyDesc = ((MultipartReplyDescCase) body).getMultipartReplyDesc();
277         final FlowCapableNode fcNode = NodeStaticReplyTranslatorUtil
278                 .nodeDescTranslator(replyDesc, getIpAddressOf(dContext))
279                 .setSwitchFeatures(SwitchFeaturesUtil.getInstance().buildSwitchFeatures(
280                         new GetFeaturesOutputBuilder(dContext.getPrimaryConnectionContext().getFeatures()).build()))
281                 .build();
282
283         final InstanceIdentifier<FlowCapableNode> fNodeII = nodeII.augmentation(FlowCapableNode.class);
284         dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, fNodeII, fcNode);
285         return true;
286     }
287
288     private static boolean writeTableFeatures(final MultipartType type,
289                                               final MultipartReplyBody body,
290                                               final DeviceContext dContext,
291                                               final InstanceIdentifier<Node> nodeII,
292                                               final ConvertorExecutor convertorExecutor) {
293         if (!MultipartType.OFPMPTABLEFEATURES.equals(type)) {
294             return false;
295         }
296
297         Preconditions.checkArgument(body instanceof MultipartReplyTableFeaturesCase);
298         final MultipartReplyTableFeatures tableFeaturesMP = ((MultipartReplyTableFeaturesCase) body)
299                 .getMultipartReplyTableFeatures();
300         final List<TableFeatures> tableFeatures = NodeStaticReplyTranslatorUtil
301                 .nodeTableFeatureTranslator(tableFeaturesMP, dContext.getDeviceInfo().getVersion(), convertorExecutor);
302         for (final TableFeatures tableFeature : tableFeatures) {
303             final Short tableId = tableFeature.getTableId();
304             final KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII =
305                     nodeII.augmentation(FlowCapableNode.class)
306                             .child(TableFeatures.class, new TableFeaturesKey(tableId));
307             dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableFeaturesII, tableFeature);
308
309             // write parent for table statistics
310             final KeyedInstanceIdentifier<Table, TableKey> tableII =
311                     nodeII.augmentation(FlowCapableNode.class)
312                             .child(Table.class, new TableKey(tableId));
313             final TableBuilder tableBld = new TableBuilder().setId(tableId)
314                     .addAugmentation(FlowTableStatisticsData.class,
315                             new FlowTableStatisticsDataBuilder().build());
316
317             dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, tableBld.build());
318         }
319
320         return true;
321     }
322
323     private static boolean writeMeterFeatures(final MultipartType type,
324                                               final MultipartReplyBody body,
325                                               final DeviceContext dContext,
326                                               final InstanceIdentifier<Node> nodeII) {
327         if (!MultipartType.OFPMPMETERFEATURES.equals(type)) {
328             return false;
329         }
330
331         Preconditions.checkArgument(body instanceof MultipartReplyMeterFeaturesCase);
332         final MultipartReplyMeterFeatures meterFeatures = ((MultipartReplyMeterFeaturesCase) body)
333                 .getMultipartReplyMeterFeatures();
334         final NodeMeterFeatures mFeature = NodeStaticReplyTranslatorUtil
335                 .nodeMeterFeatureTranslator(meterFeatures);
336         final InstanceIdentifier<NodeMeterFeatures> mFeatureII = nodeII
337                 .augmentation(NodeMeterFeatures.class);
338         dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, mFeatureII, mFeature);
339         if (0L < mFeature.getMeterFeatures().getMaxMeter().getValue()) {
340             dContext.getDeviceState().setMeterAvailable(true);
341         }
342
343         return true;
344     }
345
346     private static boolean writeGroupFeatures(final MultipartType type,
347                                               final MultipartReplyBody body,
348                                               final DeviceContext dContext,
349                                               final InstanceIdentifier<Node> nodeII) {
350         if (!MultipartType.OFPMPGROUPFEATURES.equals(type)) {
351             return false;
352         }
353
354         Preconditions.checkArgument(body instanceof MultipartReplyGroupFeaturesCase);
355         final MultipartReplyGroupFeatures groupFeatures = ((MultipartReplyGroupFeaturesCase) body)
356                 .getMultipartReplyGroupFeatures();
357         final NodeGroupFeatures gFeature = NodeStaticReplyTranslatorUtil
358                 .nodeGroupFeatureTranslator(groupFeatures);
359         final InstanceIdentifier<NodeGroupFeatures> gFeatureII = nodeII
360                 .augmentation(NodeGroupFeatures.class);
361         dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, gFeatureII, gFeature);
362
363         return true;
364     }
365
366     private static boolean writePortDesc(final MultipartType type,
367                                          final MultipartReplyBody body,
368                                          final DeviceContext dContext,
369                                          final InstanceIdentifier<Node> nodeII) {
370         if (!MultipartType.OFPMPPORTDESC.equals(type)) {
371             return false;
372         }
373
374         Preconditions.checkArgument(body instanceof MultipartReplyPortDescCase);
375         final MultipartReplyPortDesc portDesc = ((MultipartReplyPortDescCase) body)
376                 .getMultipartReplyPortDesc();
377         for (final PortGrouping port : portDesc.getPorts()) {
378             final short ofVersion = dContext.getDeviceInfo().getVersion();
379             final TranslatorKey translatorKey = new TranslatorKey(ofVersion, PortGrouping.class.getName());
380             final MessageTranslator<PortGrouping, FlowCapableNodeConnector> translator = dContext.oook()
381                     .lookupTranslator(translatorKey);
382             final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, dContext.getDeviceInfo(), null);
383
384             final BigInteger dataPathId = dContext.getPrimaryConnectionContext().getFeatures()
385                     .getDatapathId();
386             final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil.nodeConnectorId(
387                     dataPathId.toString(), port.getPortNo(), ofVersion);
388             final NodeConnectorBuilder ncBuilder = new NodeConnectorBuilder().setId(nodeConnectorId);
389             ncBuilder.addAugmentation(FlowCapableNodeConnector.class, fcNodeConnector);
390
391             ncBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class,
392                     new FlowCapableNodeConnectorStatisticsDataBuilder().build());
393             final NodeConnector connector = ncBuilder.build();
394
395             final InstanceIdentifier<NodeConnector> connectorII = nodeII.child(NodeConnector.class,
396                     connector.getKey());
397             dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, connectorII, connector);
398         }
399
400         return true;
401     }
402
403     private static void createEmptyFlowCapableNodeInDs(final DeviceContext deviceContext) {
404         final FlowCapableNodeBuilder flowCapableNodeBuilder = new FlowCapableNodeBuilder();
405         final InstanceIdentifier<FlowCapableNode> fNodeII = deviceContext.getDeviceInfo().getNodeInstanceIdentifier()
406                 .augmentation(FlowCapableNode.class);
407         try {
408             deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, fNodeII, flowCapableNodeBuilder.build());
409         } catch (final Exception e) {
410             LOG.debug("createEmptyFlowCapableNodeInDs: Failed to write node {} to DS ", deviceContext.getDeviceInfo().getNodeId().toString(), e);
411         }
412     }
413
414     private static IpAddress getIpAddressOf(final DeviceContext deviceContext) {
415
416         final InetSocketAddress remoteAddress = deviceContext.getPrimaryConnectionContext().getConnectionAdapter()
417                 .getRemoteAddress();
418
419         if (remoteAddress == null) {
420             LOG.warn("IP address of the node {} cannot be obtained. No connection with switch.", deviceContext
421                     .getDeviceInfo().getNodeId());
422             return null;
423         }
424         LOG.info("IP address of switch is: {}", remoteAddress);
425
426         return IetfInetUtil.INSTANCE.ipAddressFor(remoteAddress.getAddress());
427     }
428
429     // FIXME : remove after ovs tableFeatures fix
430     private static void makeEmptyTables(final DeviceContext dContext, final InstanceIdentifier<Node> nodeII,
431                                         final Short nrOfTables) {
432         if (LOG.isDebugEnabled()) {
433             LOG.debug("About to create {} empty tables.", nrOfTables);
434         }
435         for (int i = 0; i < nrOfTables; i++) {
436             final short tId = (short) i;
437             final InstanceIdentifier<Table> tableII = nodeII.augmentation(FlowCapableNode.class).child(Table.class,
438                     new TableKey(tId));
439             final TableBuilder tableBuilder = new TableBuilder().setId(tId).addAugmentation(
440                     FlowTableStatisticsData.class, new FlowTableStatisticsDataBuilder().build());
441
442             try {
443                 dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, tableBuilder.build());
444             } catch (final Exception e) {
445                 LOG.debug("makeEmptyTables: Failed to write node {} to DS ", dContext.getDeviceInfo().getNodeId().toString(), e);
446             }
447
448         }
449     }
450
451     static void createSuccessProcessingCallback(final MultipartType type, final DeviceContext deviceContext,
452                                                 final InstanceIdentifier<Node> nodeII,
453                                                 final ListenableFuture<RpcResult<List<MultipartReply>>> requestContextFuture,
454                                                 final ConvertorExecutor convertorExecutor) {
455         Futures.addCallback(requestContextFuture, new FutureCallback<RpcResult<List<MultipartReply>>>() {
456             @Override
457             public void onSuccess(final RpcResult<List<MultipartReply>> rpcResult) {
458                 final List<MultipartReply> result = rpcResult.getResult();
459                 if (result != null) {
460                     LOG.info("Static node {} info: {} collected", deviceContext.getDeviceInfo().getNodeId(), type);
461                     translateAndWriteReply(type, deviceContext, nodeII, result, convertorExecutor);
462                 } else {
463                     for (RpcError rpcError : rpcResult.getErrors()) {
464                         LOG.info("Failed to retrieve static node {} info: {}", type, rpcError.getMessage());
465                         if (LOG.isTraceEnabled() && Objects.nonNull(rpcError.getCause())) {
466                             LOG.trace("Detailed error:", rpcError.getCause());
467                         }
468                     }
469                     if (MultipartType.OFPMPTABLEFEATURES.equals(type)) {
470                         makeEmptyTables(deviceContext, nodeII, deviceContext.getPrimaryConnectionContext()
471                                 .getFeatures().getTables());
472                     }
473                 }
474             }
475
476             @Override
477             public void onFailure(final Throwable throwable) {
478                 LOG.info("Request of type {} for static info of node {} failed.", type, nodeII);
479             }
480         });
481     }
482
483     private static ListenableFuture<RpcResult<List<MultipartReply>>> getNodeStaticInfo(final MultipartType type,
484                                                                                        final DeviceContext deviceContext,
485                                                                                        final InstanceIdentifier<Node> nodeII,
486                                                                                        final short version) {
487
488         final OutboundQueue queue = deviceContext.getPrimaryConnectionContext().getOutboundQueueProvider();
489
490         final Long reserved = deviceContext.getDeviceInfo().reserveXidForDeviceMessage();
491         final RequestContext<List<MultipartReply>> requestContext = new AbstractRequestContext<List<MultipartReply>>(
492                 reserved) {
493             @Override
494             public void close() {
495                 //NOOP
496             }
497         };
498
499         final Xid xid = requestContext.getXid();
500
501         if (Objects.isNull(xid)) {
502             LOG.debug("Xid is not present, so cancelling node static info gathering.");
503             return Futures.immediateCancelledFuture();
504         }
505
506         LOG.trace("Hooking xid {} to device context - precaution.", reserved);
507
508         final MultiMsgCollector multiMsgCollector = deviceContext.getMultiMsgCollector(requestContext);
509         queue.commitEntry(xid.getValue(),
510                 MultipartRequestInputFactory.makeMultipartRequestInput(xid.getValue(), version, type),
511                 new FutureCallback<OfHeader>() {
512                     @Override
513                     public void onSuccess(final OfHeader ofHeader) {
514                         if (ofHeader instanceof MultipartReply) {
515                             final MultipartReply multipartReply = (MultipartReply) ofHeader;
516                             multiMsgCollector.addMultipartMsg(multipartReply);
517                         } else if (null != ofHeader) {
518                             LOG.info("Unexpected response type received {}.", ofHeader.getClass());
519                         } else {
520                             multiMsgCollector.endCollecting();
521                             LOG.info("Response received is null.");
522                         }
523                     }
524
525                     @Override
526                     public void onFailure(final Throwable t) {
527                         LOG.info("Fail response from OutboundQueue for multipart type {}.", type);
528                         final RpcResult<List<MultipartReply>> rpcResult = RpcResultBuilder
529                                 .<List<MultipartReply>>failed().build();
530                         requestContext.setResult(rpcResult);
531                         if (MultipartType.OFPMPTABLEFEATURES.equals(type)) {
532                             makeEmptyTables(deviceContext, nodeII, deviceContext.getPrimaryConnectionContext()
533                                     .getFeatures().getTables());
534                         }
535                         requestContext.close();
536                     }
537                 });
538
539         return requestContext.getFuture();
540     }
541
542     static void chainTableTrunkWriteOF10(final DeviceContext deviceContext,
543                                          final ListenableFuture<List<RpcResult<List<MultipartReply>>>> deviceFeaturesFuture) {
544
545         try {
546             if (LOG.isTraceEnabled()) {
547                 LOG.trace("Waiting for protocol version 1.0");
548             }
549             List<RpcResult<List<MultipartReply>>> results = deviceFeaturesFuture.get();
550             boolean allSucceeded = true;
551             for (final RpcResult<List<MultipartReply>> rpcResult : results) {
552                 allSucceeded &= rpcResult.isSuccessful();
553             }
554             if (allSucceeded) {
555                 if (LOG.isDebugEnabled()) {
556                     LOG.debug("Creating empty flow capable node: {}", deviceContext.getDeviceInfo().getLOGValue());
557                 }
558                 createEmptyFlowCapableNodeInDs(deviceContext);
559                 if (LOG.isDebugEnabled()) {
560                     LOG.debug("Creating empty tables for {}", deviceContext.getDeviceInfo().getLOGValue());
561                 }
562                 makeEmptyTables(deviceContext, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(),
563                         deviceContext.getPrimaryConnectionContext().getFeatures().getTables());
564             }
565         } catch (InterruptedException | ExecutionException e) {
566             LOG.warn("Error occurred in preparation node {} for protocol 1.0", deviceContext.getDeviceInfo().getLOGValue());
567             if (LOG.isTraceEnabled()) {
568                 LOG.trace("Error for node {} : ", deviceContext.getDeviceInfo().getLOGValue(), e);
569             }
570         }
571     }
572 }