Merge "Bug 6745 Do not ignore syncup return value"
[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         try {
245             result.stream()
246                     .map(MultipartReply::getMultipartReplyBody)
247                     .forEach(multipartReplyBody -> {
248                         if (!(writeDesc(type, multipartReplyBody, dContext, nodeII)
249                                 || writeTableFeatures(type, multipartReplyBody, dContext, nodeII, convertorExecutor)
250                                 || writeMeterFeatures(type, multipartReplyBody, dContext, nodeII)
251                                 || writeGroupFeatures(type, multipartReplyBody, dContext, nodeII)
252                                 || writePortDesc(type, multipartReplyBody, dContext, nodeII))) {
253                             throw new IllegalArgumentException("Unexpected MultipartType " + type);
254                         }
255                     });
256         } catch (final Exception e) {
257             LOG.debug("translateAndWriteReply: Failed to write node {} to DS ", dContext.getDeviceInfo().getNodeId().toString(), e);
258         }
259     }
260
261     private static boolean writeDesc(final MultipartType type,
262                                      final MultipartReplyBody body,
263                                      final DeviceContext dContext,
264                                      final InstanceIdentifier<Node> nodeII) {
265         if (!MultipartType.OFPMPDESC.equals(type)) {
266             return false;
267         }
268
269         Preconditions.checkArgument(body instanceof MultipartReplyDescCase);
270         final MultipartReplyDesc replyDesc = ((MultipartReplyDescCase) body).getMultipartReplyDesc();
271         final FlowCapableNode fcNode = NodeStaticReplyTranslatorUtil
272                 .nodeDescTranslator(replyDesc, getIpAddressOf(dContext))
273                 .setSwitchFeatures(SwitchFeaturesUtil.getInstance().buildSwitchFeatures(
274                         new GetFeaturesOutputBuilder(dContext.getPrimaryConnectionContext().getFeatures()).build()))
275                 .build();
276
277         final InstanceIdentifier<FlowCapableNode> fNodeII = nodeII.augmentation(FlowCapableNode.class);
278         dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, fNodeII, fcNode);
279         return true;
280     }
281
282     private static boolean writeTableFeatures(final MultipartType type,
283                                               final MultipartReplyBody body,
284                                               final DeviceContext dContext,
285                                               final InstanceIdentifier<Node> nodeII,
286                                               final ConvertorExecutor convertorExecutor) {
287         if (!MultipartType.OFPMPTABLEFEATURES.equals(type)) {
288             return false;
289         }
290
291         Preconditions.checkArgument(body instanceof MultipartReplyTableFeaturesCase);
292         final MultipartReplyTableFeatures tableFeaturesMP = ((MultipartReplyTableFeaturesCase) body)
293                 .getMultipartReplyTableFeatures();
294         final List<TableFeatures> tableFeatures = NodeStaticReplyTranslatorUtil
295                 .nodeTableFeatureTranslator(tableFeaturesMP, dContext.getDeviceInfo().getVersion(), convertorExecutor);
296         for (final TableFeatures tableFeature : tableFeatures) {
297             final Short tableId = tableFeature.getTableId();
298             final KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII =
299                     nodeII.augmentation(FlowCapableNode.class)
300                             .child(TableFeatures.class, new TableFeaturesKey(tableId));
301             dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableFeaturesII, tableFeature);
302
303             // write parent for table statistics
304             final KeyedInstanceIdentifier<Table, TableKey> tableII =
305                     nodeII.augmentation(FlowCapableNode.class)
306                             .child(Table.class, new TableKey(tableId));
307             final TableBuilder tableBld = new TableBuilder().setId(tableId)
308                     .addAugmentation(FlowTableStatisticsData.class,
309                             new FlowTableStatisticsDataBuilder().build());
310
311             dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, tableBld.build());
312         }
313
314         return true;
315     }
316
317     private static boolean writeMeterFeatures(final MultipartType type,
318                                               final MultipartReplyBody body,
319                                               final DeviceContext dContext,
320                                               final InstanceIdentifier<Node> nodeII) {
321         if (!MultipartType.OFPMPMETERFEATURES.equals(type)) {
322             return false;
323         }
324
325         Preconditions.checkArgument(body instanceof MultipartReplyMeterFeaturesCase);
326         final MultipartReplyMeterFeatures meterFeatures = ((MultipartReplyMeterFeaturesCase) body)
327                 .getMultipartReplyMeterFeatures();
328         final NodeMeterFeatures mFeature = NodeStaticReplyTranslatorUtil
329                 .nodeMeterFeatureTranslator(meterFeatures);
330         final InstanceIdentifier<NodeMeterFeatures> mFeatureII = nodeII
331                 .augmentation(NodeMeterFeatures.class);
332         dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, mFeatureII, mFeature);
333         if (0L < mFeature.getMeterFeatures().getMaxMeter().getValue()) {
334             dContext.getDeviceState().setMeterAvailable(true);
335         }
336
337         return true;
338     }
339
340     private static boolean writeGroupFeatures(final MultipartType type,
341                                               final MultipartReplyBody body,
342                                               final DeviceContext dContext,
343                                               final InstanceIdentifier<Node> nodeII) {
344         if (!MultipartType.OFPMPGROUPFEATURES.equals(type)) {
345             return false;
346         }
347
348         Preconditions.checkArgument(body instanceof MultipartReplyGroupFeaturesCase);
349         final MultipartReplyGroupFeatures groupFeatures = ((MultipartReplyGroupFeaturesCase) body)
350                 .getMultipartReplyGroupFeatures();
351         final NodeGroupFeatures gFeature = NodeStaticReplyTranslatorUtil
352                 .nodeGroupFeatureTranslator(groupFeatures);
353         final InstanceIdentifier<NodeGroupFeatures> gFeatureII = nodeII
354                 .augmentation(NodeGroupFeatures.class);
355         dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, gFeatureII, gFeature);
356
357         return true;
358     }
359
360     private static boolean writePortDesc(final MultipartType type,
361                                          final MultipartReplyBody body,
362                                          final DeviceContext dContext,
363                                          final InstanceIdentifier<Node> nodeII) {
364         if (!MultipartType.OFPMPPORTDESC.equals(type)) {
365             return false;
366         }
367
368         Preconditions.checkArgument(body instanceof MultipartReplyPortDescCase);
369         final MultipartReplyPortDesc portDesc = ((MultipartReplyPortDescCase) body)
370                 .getMultipartReplyPortDesc();
371         for (final PortGrouping port : portDesc.getPorts()) {
372             final short ofVersion = dContext.getDeviceInfo().getVersion();
373             final TranslatorKey translatorKey = new TranslatorKey(ofVersion, PortGrouping.class.getName());
374             final MessageTranslator<PortGrouping, FlowCapableNodeConnector> translator = dContext.oook()
375                     .lookupTranslator(translatorKey);
376             final FlowCapableNodeConnector fcNodeConnector = translator.translate(port, dContext.getDeviceInfo(), null);
377
378             final BigInteger dataPathId = dContext.getPrimaryConnectionContext().getFeatures()
379                     .getDatapathId();
380             final NodeConnectorId nodeConnectorId = NodeStaticReplyTranslatorUtil.nodeConnectorId(
381                     dataPathId.toString(), port.getPortNo(), ofVersion);
382             final NodeConnectorBuilder ncBuilder = new NodeConnectorBuilder().setId(nodeConnectorId);
383             ncBuilder.addAugmentation(FlowCapableNodeConnector.class, fcNodeConnector);
384
385             ncBuilder.addAugmentation(FlowCapableNodeConnectorStatisticsData.class,
386                     new FlowCapableNodeConnectorStatisticsDataBuilder().build());
387             final NodeConnector connector = ncBuilder.build();
388
389             final InstanceIdentifier<NodeConnector> connectorII = nodeII.child(NodeConnector.class,
390                     connector.getKey());
391             dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, connectorII, connector);
392         }
393
394         return true;
395     }
396
397     private static void createEmptyFlowCapableNodeInDs(final DeviceContext deviceContext) {
398         final FlowCapableNodeBuilder flowCapableNodeBuilder = new FlowCapableNodeBuilder();
399         final InstanceIdentifier<FlowCapableNode> fNodeII = deviceContext.getDeviceInfo().getNodeInstanceIdentifier()
400                 .augmentation(FlowCapableNode.class);
401         try {
402             deviceContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, fNodeII, flowCapableNodeBuilder.build());
403         } catch (final Exception e) {
404             LOG.debug("createEmptyFlowCapableNodeInDs: Failed to write node {} to DS ", deviceContext.getDeviceInfo().getNodeId().toString(), e);
405         }
406     }
407
408     private static IpAddress getIpAddressOf(final DeviceContext deviceContext) {
409
410         final InetSocketAddress remoteAddress = deviceContext.getPrimaryConnectionContext().getConnectionAdapter()
411                 .getRemoteAddress();
412
413         if (remoteAddress == null) {
414             LOG.warn("IP address of the node {} cannot be obtained. No connection with switch.", deviceContext
415                     .getDeviceInfo().getNodeId());
416             return null;
417         }
418         LOG.info("IP address of switch is: {}", remoteAddress);
419
420         return IetfInetUtil.INSTANCE.ipAddressFor(remoteAddress.getAddress());
421     }
422
423     // FIXME : remove after ovs tableFeatures fix
424     private static void makeEmptyTables(final DeviceContext dContext, final InstanceIdentifier<Node> nodeII,
425                                         final Short nrOfTables) {
426         if (LOG.isDebugEnabled()) {
427             LOG.debug("About to create {} empty tables.", nrOfTables);
428         }
429         for (int i = 0; i < nrOfTables; i++) {
430             final short tId = (short) i;
431             final InstanceIdentifier<Table> tableII = nodeII.augmentation(FlowCapableNode.class).child(Table.class,
432                     new TableKey(tId));
433             final TableBuilder tableBuilder = new TableBuilder().setId(tId).addAugmentation(
434                     FlowTableStatisticsData.class, new FlowTableStatisticsDataBuilder().build());
435
436             try {
437                 dContext.writeToTransaction(LogicalDatastoreType.OPERATIONAL, tableII, tableBuilder.build());
438             } catch (final Exception e) {
439                 LOG.debug("makeEmptyTables: Failed to write node {} to DS ", dContext.getDeviceInfo().getNodeId().toString(), e);
440             }
441
442         }
443     }
444
445     static void createSuccessProcessingCallback(final MultipartType type, final DeviceContext deviceContext,
446                                                 final InstanceIdentifier<Node> nodeII,
447                                                 final ListenableFuture<RpcResult<List<MultipartReply>>> requestContextFuture,
448                                                 final ConvertorExecutor convertorExecutor) {
449         Futures.addCallback(requestContextFuture, new FutureCallback<RpcResult<List<MultipartReply>>>() {
450             @Override
451             public void onSuccess(final RpcResult<List<MultipartReply>> rpcResult) {
452                 final List<MultipartReply> result = rpcResult.getResult();
453                 if (result != null) {
454                     LOG.info("Static node {} info: {} collected", deviceContext.getDeviceInfo().getNodeId(), type);
455                     translateAndWriteReply(type, deviceContext, nodeII, result, convertorExecutor);
456                 } else {
457                     for (RpcError rpcError : rpcResult.getErrors()) {
458                         LOG.info("Failed to retrieve static node {} info: {}", type, rpcError.getMessage());
459                         if (LOG.isTraceEnabled() && Objects.nonNull(rpcError.getCause())) {
460                             LOG.trace("Detailed error:", rpcError.getCause());
461                         }
462                     }
463                     if (MultipartType.OFPMPTABLEFEATURES.equals(type)) {
464                         makeEmptyTables(deviceContext, nodeII, deviceContext.getPrimaryConnectionContext()
465                                 .getFeatures().getTables());
466                     }
467                 }
468             }
469
470             @Override
471             public void onFailure(final Throwable throwable) {
472                 LOG.info("Request of type {} for static info of node {} failed.", type, nodeII);
473             }
474         });
475     }
476
477     private static ListenableFuture<RpcResult<List<MultipartReply>>> getNodeStaticInfo(final MultipartType type,
478                                                                                        final DeviceContext deviceContext,
479                                                                                        final InstanceIdentifier<Node> nodeII,
480                                                                                        final short version) {
481
482         final OutboundQueue queue = deviceContext.getPrimaryConnectionContext().getOutboundQueueProvider();
483
484         final Long reserved = deviceContext.getDeviceInfo().reserveXidForDeviceMessage();
485         final RequestContext<List<MultipartReply>> requestContext = new AbstractRequestContext<List<MultipartReply>>(
486                 reserved) {
487             @Override
488             public void close() {
489                 //NOOP
490             }
491         };
492
493         final Xid xid = requestContext.getXid();
494
495         LOG.trace("Hooking xid {} to device context - precaution.", reserved);
496
497         final MultiMsgCollector multiMsgCollector = deviceContext.getMultiMsgCollector(requestContext);
498         queue.commitEntry(xid.getValue(),
499                 MultipartRequestInputFactory.makeMultipartRequestInput(xid.getValue(), version, type),
500                 new FutureCallback<OfHeader>() {
501                     @Override
502                     public void onSuccess(final OfHeader ofHeader) {
503                         if (ofHeader instanceof MultipartReply) {
504                             final MultipartReply multipartReply = (MultipartReply) ofHeader;
505                             multiMsgCollector.addMultipartMsg(multipartReply);
506                         } else if (null != ofHeader) {
507                             LOG.info("Unexpected response type received {}.", ofHeader.getClass());
508                         } else {
509                             multiMsgCollector.endCollecting();
510                             LOG.info("Response received is null.");
511                         }
512                     }
513
514                     @Override
515                     public void onFailure(final Throwable t) {
516                         LOG.info("Fail response from OutboundQueue for multipart type {}.", type);
517                         final RpcResult<List<MultipartReply>> rpcResult = RpcResultBuilder
518                                 .<List<MultipartReply>>failed().build();
519                         requestContext.setResult(rpcResult);
520                         if (MultipartType.OFPMPTABLEFEATURES.equals(type)) {
521                             makeEmptyTables(deviceContext, nodeII, deviceContext.getPrimaryConnectionContext()
522                                     .getFeatures().getTables());
523                         }
524                         requestContext.close();
525                     }
526                 });
527
528         return requestContext.getFuture();
529     }
530
531     static void chainTableTrunkWriteOF10(final DeviceContext deviceContext,
532                                          final ListenableFuture<List<RpcResult<List<MultipartReply>>>> deviceFeaturesFuture) {
533
534         try {
535             if (LOG.isTraceEnabled()) {
536                 LOG.trace("Waiting for protocol version 1.0");
537             }
538             List<RpcResult<List<MultipartReply>>> results = deviceFeaturesFuture.get();
539             boolean allSucceeded = true;
540             for (final RpcResult<List<MultipartReply>> rpcResult : results) {
541                 allSucceeded &= rpcResult.isSuccessful();
542             }
543             if (allSucceeded) {
544                 if (LOG.isDebugEnabled()) {
545                     LOG.debug("Creating empty flow capable node: {}", deviceContext.getDeviceInfo().getLOGValue());
546                 }
547                 createEmptyFlowCapableNodeInDs(deviceContext);
548                 if (LOG.isDebugEnabled()) {
549                     LOG.debug("Creating empty tables for {}", deviceContext.getDeviceInfo().getLOGValue());
550                 }
551                 makeEmptyTables(deviceContext, deviceContext.getDeviceInfo().getNodeInstanceIdentifier(),
552                         deviceContext.getPrimaryConnectionContext().getFeatures().getTables());
553             }
554         } catch (InterruptedException | ExecutionException e) {
555             LOG.warn("Error occurred in preparation node {} for protocol 1.0", deviceContext.getDeviceInfo().getLOGValue());
556             if (LOG.isTraceEnabled()) {
557                 LOG.trace("Error for node {} : ", deviceContext.getDeviceInfo().getLOGValue(), e);
558             }
559         }
560     }
561 }