c55e4b3bf16c5e581fe6e16262d4a3e102597553
[openflowplugin.git] / applications / forwardingrules-manager / src / main / java / org / opendaylight / openflowplugin / applications / frm / impl / FlowNodeReconciliationImpl.java
1 /**
2  * Copyright (c) 2014, 2017 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.applications.frm.impl;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
14 import com.google.common.util.concurrent.CheckedFuture;
15 import com.google.common.util.concurrent.FutureCallback;
16 import com.google.common.util.concurrent.Futures;
17 import com.google.common.util.concurrent.JdkFutureAdapters;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import java.math.BigInteger;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.ListIterator;
27 import java.util.Map;
28 import java.util.concurrent.Callable;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.TimeoutException;
34 import java.util.concurrent.atomic.AtomicLong;
35 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
36 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
37 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
38 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
39 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
40 import org.opendaylight.openflowplugin.api.OFConstants;
41 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
42 import org.opendaylight.openflowplugin.applications.frm.FlowNodeReconciliation;
43 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.GroupActionCase;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.OutputActionCase;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeter;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.StaleMeterKey;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupTypes;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.Buckets;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.Bucket;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroup;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.StaleGroupKey;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.MeterId;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInput;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesInputBuilder;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.AddBundleMessagesOutput;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInput;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleInputBuilder;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.ControlBundleOutput;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.SalBundleService;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.Messages;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.MessagesBuilder;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.Message;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.add.bundle.messages.input.messages.MessageBuilder;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddFlowCaseBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleAddGroupCaseBuilder;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveFlowCaseBuilder;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.BundleRemoveGroupCaseBuilder;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.add.flow._case.AddFlowCaseDataBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.add.group._case.AddGroupCaseDataBuilder;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.remove.flow._case.RemoveFlowCaseDataBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.bundle.service.rev170124.bundle.inner.message.grouping.bundle.inner.message.bundle.remove.group._case.RemoveGroupCaseDataBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleControlType;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleFlags;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.extension.onf.rev170124.BundleId;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.rf.state.rev170713.ResultState;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeatures;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.table.features.TableFeaturesKey;
99 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
100 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
101 import org.opendaylight.yangtools.yang.common.RpcResult;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
104
105 /**
106  * Default implementation of {@link ForwardingRulesManager}.
107  *
108  * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
109  */
110 public class FlowNodeReconciliationImpl implements FlowNodeReconciliation {
111
112     private static final Logger LOG = LoggerFactory.getLogger(FlowNodeReconciliationImpl.class);
113
114     // The number of nanoseconds to wait for a single group to be added.
115     private static final long ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(3);
116
117     // The maximum number of nanoseconds to wait for completion of add-group RPCs.
118     private static final long MAX_ADD_GROUP_TIMEOUT = TimeUnit.SECONDS.toNanos(20);
119     private static final String SEPARATOR = ":";
120     private static final int THREAD_POOL_SIZE = 4;
121
122     private final DataBroker dataBroker;
123     private final ForwardingRulesManager provider;
124     private final String serviceName;
125     private final int priority;
126     private final ResultState resultState;
127     private final Map<DeviceInfo, ListenableFuture<Boolean>> futureMap = new HashMap<>();
128
129     private final ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
130
131     private final SalBundleService salBundleService;
132
133     private static final AtomicLong BUNDLE_ID = new AtomicLong();
134     private static final BundleFlags BUNDLE_FLAGS = new BundleFlags(true, true);
135
136     public FlowNodeReconciliationImpl(final ForwardingRulesManager manager, final DataBroker db,
137             final String serviceName, final int priority, final ResultState resultState) {
138         this.provider = Preconditions.checkNotNull(manager, "ForwardingRulesManager can not be null!");
139         dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
140         this.serviceName = serviceName;
141         this.priority = priority;
142         this.resultState = resultState;
143         salBundleService = Preconditions.checkNotNull(manager.getSalBundleService(),
144                 "salBundleService can not be null!");
145     }
146
147     @Override
148     public void close() {
149         if (executor != null) {
150             executor.shutdownNow();
151         }
152     }
153
154     @Override
155     public ListenableFuture<Boolean> reconcileConfiguration(InstanceIdentifier<FlowCapableNode> connectedNode) {
156         LOG.info("Triggering reconciliation for device {}", connectedNode.firstKeyOf(Node.class));
157         if (provider.isStaleMarkingEnabled()) {
158             LOG.info("Stale-Marking is ENABLED and proceeding with deletion of " + "stale-marked entities on switch {}",
159                     connectedNode.toString());
160             reconciliationPreProcess(connectedNode);
161         }
162         LOG.debug("Bundle based reconciliation status : {}",
163                 provider.isBundleBasedReconciliationEnabled() ? "Enable" : "Disable");
164         if (provider.isBundleBasedReconciliationEnabled()) {
165             BundleBasedReconciliationTask bundleBasedReconTask = new BundleBasedReconciliationTask(connectedNode);
166             return JdkFutureAdapters.listenInPoolThread(executor.submit(bundleBasedReconTask));
167         } else {
168             ReconciliationTask reconciliationTask = new ReconciliationTask(connectedNode);
169             return JdkFutureAdapters.listenInPoolThread(executor.submit(reconciliationTask));
170         }
171     }
172
173     private class BundleBasedReconciliationTask implements Callable<Boolean> {
174         final InstanceIdentifier<FlowCapableNode> nodeIdentity;
175
176         BundleBasedReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
177             nodeIdentity = nodeIdent;
178         }
179
180         @Override
181         public Boolean call() {
182             String node = nodeIdentity.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
183             Optional<FlowCapableNode> flowNode = Optional.absent();
184             BundleId bundleIdValue = new BundleId(BUNDLE_ID.getAndIncrement());
185             BigInteger dpnId = getDpnIdFromNodeName(node);
186             LOG.debug("Triggering bundle based reconciliation for device :{}", dpnId);
187             ReadOnlyTransaction trans = provider.getReadTranaction();
188             try {
189                 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
190             } catch (ExecutionException | InterruptedException e) {
191                 LOG.error("Error occurred while reading the configuration data store for node {}", nodeIdentity, e);
192             }
193
194             if (flowNode.isPresent()) {
195                 LOG.debug("FlowNode present for Datapath ID {}", dpnId);
196                 final NodeRef nodeRef = new NodeRef(nodeIdentity.firstIdentifierOf(Node.class));
197
198                 final ControlBundleInput openBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
199                         .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS).setType(BundleControlType.ONFBCTOPENREQUEST)
200                         .build();
201
202                 final ControlBundleInput commitBundleInput = new ControlBundleInputBuilder().setNode(nodeRef)
203                         .setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
204                         .setType(BundleControlType.ONFBCTCOMMITREQUEST).build();
205
206                 final AddBundleMessagesInput addBundleMessagesInput = new AddBundleMessagesInputBuilder()
207                         .setNode(nodeRef).setBundleId(bundleIdValue).setFlags(BUNDLE_FLAGS)
208                         .setMessages(createMessages(nodeRef, flowNode)).build();
209
210                 ListenableFuture<RpcResult<ControlBundleOutput>> openBundle
211                         = salBundleService.controlBundle(openBundleInput);
212
213                 ListenableFuture<RpcResult<AddBundleMessagesOutput>> addBundleMessagesFuture = Futures
214                         .transformAsync(JdkFutureAdapters.listenInPoolThread(openBundle), rpcResult -> {
215                             if (rpcResult.isSuccessful()) {
216                                 return JdkFutureAdapters
217                                         .listenInPoolThread(salBundleService.addBundleMessages(addBundleMessagesInput));
218                             }
219                             return Futures.immediateFuture(null);
220                         }, MoreExecutors.directExecutor());
221                 ListenableFuture<RpcResult<ControlBundleOutput>> commitBundleFuture
222                         = Futures.transformAsync(addBundleMessagesFuture, rpcResult -> {
223                             if (rpcResult.isSuccessful()) {
224                                 return JdkFutureAdapters
225                                         .listenInPoolThread(salBundleService.controlBundle(commitBundleInput));
226                             }
227                             return Futures.immediateFuture(null);
228                         }, MoreExecutors.directExecutor());
229
230                 /* Bundles not supported for meters */
231                 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
232                         : Collections.emptyList();
233                 Futures.transformAsync(commitBundleFuture,
234                     rpcResult -> {
235                         if (rpcResult.isSuccessful()) {
236                             for (Meter meter : meters) {
237                                 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity
238                                         .child(Meter.class, meter.getKey());
239                                 provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
240                             }
241                         }
242                         return Futures.immediateFuture(null);
243                     }, MoreExecutors.directExecutor());
244
245                 trans.close();
246                 try {
247                     if (commitBundleFuture.get().isSuccessful()) {
248                         LOG.debug("Completing bundle based reconciliation for device ID:{}", dpnId);
249                         return true;
250                     } else {
251                         return false;
252                     }
253                 } catch (InterruptedException | ExecutionException e) {
254                     LOG.error("Error while doing bundle based reconciliation for device ID:{}", nodeIdentity);
255                     return false;
256                 }
257             }
258             LOG.error("FlowNode not present for Datapath ID {}", dpnId);
259             return false;
260         }
261     }
262
263     @Override
264     public ListenableFuture<Boolean> startReconciliation(DeviceInfo node) {
265         InstanceIdentifier<FlowCapableNode> connectedNode = node.getNodeInstanceIdentifier()
266                 .augmentation(FlowCapableNode.class);
267         return futureMap.computeIfAbsent(node, future -> reconcileConfiguration(connectedNode));
268     }
269
270     @Override
271     public ListenableFuture<Boolean> endReconciliation(DeviceInfo node) {
272         futureMap.computeIfPresent(node, (key, future) -> future).cancel(true);
273         futureMap.remove(node);
274         return Futures.immediateFuture(true);
275     }
276
277     @Override
278     public int getPriority() {
279         return priority;
280     }
281
282     @Override
283     public String getName() {
284         return serviceName;
285     }
286
287     @Override
288     public ResultState getResultState() {
289         return resultState;
290     }
291
292     private class ReconciliationTask implements Callable<Boolean> {
293
294         InstanceIdentifier<FlowCapableNode> nodeIdentity;
295
296         ReconciliationTask(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
297             nodeIdentity = nodeIdent;
298         }
299
300         @Override
301         public Boolean call() {
302             String node = nodeIdentity.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
303             BigInteger dpnId = getDpnIdFromNodeName(node);
304
305             ReadOnlyTransaction trans = provider.getReadTranaction();
306             Optional<FlowCapableNode> flowNode;
307             // initialize the counter
308             int counter = 0;
309             try {
310                 flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdentity).get();
311             } catch (ExecutionException | InterruptedException e) {
312                 LOG.warn("Fail with read Config/DS for Node {} !", nodeIdentity, e);
313                 return false;
314             }
315
316             if (flowNode.isPresent()) {
317                 /* Tables - have to be pushed before groups */
318                 // CHECK if while pushing the update, updateTableInput can be null to emulate a
319                 // table add
320                 List<TableFeatures> tableList = flowNode.get().getTableFeatures() != null
321                         ? flowNode.get().getTableFeatures()
322                         : Collections.<TableFeatures>emptyList();
323                 for (TableFeatures tableFeaturesItem : tableList) {
324                     TableFeaturesKey tableKey = tableFeaturesItem.getKey();
325                     KeyedInstanceIdentifier<TableFeatures, TableFeaturesKey> tableFeaturesII = nodeIdentity
326                             .child(TableFeatures.class, new TableFeaturesKey(tableKey.getTableId()));
327                     provider.getTableFeaturesCommiter().update(tableFeaturesII, tableFeaturesItem, null, nodeIdentity);
328                 }
329
330                 /* Groups - have to be first */
331                 List<Group> groups = flowNode.get().getGroup() != null ? flowNode.get().getGroup()
332                         : Collections.<Group>emptyList();
333                 List<Group> toBeInstalledGroups = new ArrayList<>();
334                 toBeInstalledGroups.addAll(groups);
335                 // new list for suspected groups pointing to ports .. when the ports come up
336                 // late
337                 List<Group> suspectedGroups = new ArrayList<>();
338                 Map<Long, ListenableFuture<?>> groupFutures = new HashMap<>();
339
340                 while ((!toBeInstalledGroups.isEmpty() || !suspectedGroups.isEmpty())
341                         && counter <= provider.getReconciliationRetryCount()) { // also check if the counter has not
342                                                                                 // crossed the threshold
343
344                     if (toBeInstalledGroups.isEmpty() && !suspectedGroups.isEmpty()) {
345                         LOG.debug("These Groups are pointing to node-connectors that are not up yet {}",
346                                 suspectedGroups.toString());
347                         toBeInstalledGroups.addAll(suspectedGroups);
348                         break;
349                     }
350
351                     ListIterator<Group> iterator = toBeInstalledGroups.listIterator();
352                     while (iterator.hasNext()) {
353                         Group group = iterator.next();
354                         boolean okToInstall = true;
355                         Buckets buckets = group.getBuckets();
356                         List<Bucket> bucketList = buckets == null ? null : buckets.getBucket();
357                         if (bucketList == null) {
358                             bucketList = Collections.<Bucket>emptyList();
359                         }
360                         for (Bucket bucket : bucketList) {
361                             List<Action> actions = bucket.getAction();
362                             if (actions == null) {
363                                 actions = Collections.<Action>emptyList();
364                             }
365                             for (Action action : actions) {
366                                 // chained-port
367                                 if (action.getAction().getImplementedInterface().getName()
368                                         .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
369                                                 + ".action.types.rev131112.action.action.OutputActionCase")) {
370                                     String nodeConnectorUri = ((OutputActionCase) action.getAction()).getOutputAction()
371                                             .getOutputNodeConnector().getValue();
372
373                                     LOG.debug("Installing the group for node connector {}", nodeConnectorUri);
374
375                                     // check if the nodeconnector is there in the multimap
376                                     boolean isPresent = provider.getFlowNodeConnectorInventoryTranslatorImpl()
377                                             .isNodeConnectorUpdated(dpnId, nodeConnectorUri);
378                                     // if yes set okToInstall = true
379
380                                     if (isPresent) {
381                                         break;
382                                     } else {
383                                         // else put it in a different list and still set okToInstall = true
384                                         suspectedGroups.add(group);
385                                         LOG.debug(
386                                                 "Not yet received the node-connector updated for {} "
387                                                         + "for the group with id {}",
388                                                 nodeConnectorUri, group.getGroupId().toString());
389                                         break;
390                                     }
391                                 } else if (action.getAction().getImplementedInterface().getName()
392                                         .equals("org.opendaylight.yang.gen.v1.urn.opendaylight"
393                                                 + ".action.types.rev131112.action.action.GroupActionCase")) {
394                                     // chained groups
395                                     Long groupId = ((GroupActionCase) action.getAction()).getGroupAction().getGroupId();
396                                     ListenableFuture<?> future = groupFutures.get(groupId);
397                                     if (future == null) {
398                                         okToInstall = false;
399                                         break;
400                                     }
401                                     // Need to ensure that the group specified
402                                     // by group-action is already installed.
403                                     awaitGroup(node, future);
404                                 }
405                             }
406                             if (!okToInstall) {
407                                 // increment retry counter value
408                                 counter++;
409                                 break;
410                             }
411                         }
412                         if (okToInstall) {
413                             addGroup(groupFutures, group);
414                             iterator.remove();
415                             // resetting the counter to zero
416                             counter = 0;
417                         }
418                     }
419                 }
420
421                 /* installation of suspected groups */
422                 if (!toBeInstalledGroups.isEmpty()) {
423                     for (Group group : toBeInstalledGroups) {
424                         LOG.debug(
425                                 "Installing the group {} finally although "
426                                         + "the port is not up after checking for {} times ",
427                                 group.getGroupId().toString(), provider.getReconciliationRetryCount());
428                         addGroup(groupFutures, group);
429                     }
430                 }
431                 /* Meters */
432                 List<Meter> meters = flowNode.get().getMeter() != null ? flowNode.get().getMeter()
433                         : Collections.<Meter>emptyList();
434                 for (Meter meter : meters) {
435                     final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdentity.child(Meter.class,
436                             meter.getKey());
437                     provider.getMeterCommiter().add(meterIdent, meter, nodeIdentity);
438                 }
439
440                 // Need to wait for all groups to be installed before adding
441                 // flows.
442                 awaitGroups(node, groupFutures.values());
443
444                 /* Flows */
445                 List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
446                         : Collections.<Table>emptyList();
447                 for (Table table : tables) {
448                     final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdentity.child(Table.class,
449                             table.getKey());
450                     List<Flow> flows = table.getFlow() != null ? table.getFlow() : Collections.<Flow>emptyList();
451                     for (Flow flow : flows) {
452                         final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
453                                 flow.getKey());
454                         provider.getFlowCommiter().add(flowIdent, flow, nodeIdentity);
455                     }
456                 }
457             }
458             /* clean transaction */
459             trans.close();
460             return true;
461         }
462
463         /**
464          * Invoke add-group RPC, and put listenable future associated with the RPC into
465          * the given map.
466          *
467          * @param map
468          *            The map to store listenable futures associated with add-group RPC.
469          * @param group
470          *            The group to add.
471          */
472         private void addGroup(Map<Long, ListenableFuture<?>> map, Group group) {
473             KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdentity.child(Group.class, group.getKey());
474             final Long groupId = group.getGroupId().getValue();
475             ListenableFuture<?> future = JdkFutureAdapters
476                     .listenInPoolThread(provider.getGroupCommiter().add(groupIdent, group, nodeIdentity));
477
478             Futures.addCallback(future, new FutureCallback<Object>() {
479                 @Override
480                 public void onSuccess(Object result) {
481                     if (LOG.isTraceEnabled()) {
482                         LOG.trace("add-group RPC completed: node={}, id={}",
483                                 nodeIdentity.firstKeyOf(Node.class).getId().getValue(), groupId);
484                     }
485                 }
486
487                 @Override
488                 public void onFailure(Throwable cause) {
489                     String msg = "add-group RPC failed: node=" + nodeIdentity.firstKeyOf(Node.class).getId().getValue()
490                             + ", id=" + groupId;
491                     LOG.debug(msg, cause);
492                 }
493             }, MoreExecutors.directExecutor());
494
495             map.put(groupId, future);
496         }
497
498         /**
499          * Wait for completion of add-group RPC.
500          *
501          * @param nodeId
502          *            The identifier for the target node.
503          * @param future
504          *            Future associated with add-group RPC that installs the target
505          *            group.
506          */
507         private void awaitGroup(String nodeId, ListenableFuture<?> future) {
508             awaitGroups(nodeId, Collections.singleton(future));
509         }
510
511         /**
512          * Wait for completion of add-group RPCs.
513          *
514          * @param nodeId
515          *            The identifier for the target node.
516          * @param futures
517          *            A collection of futures associated with add-group RPCs.
518          */
519         private void awaitGroups(String nodeId, Collection<ListenableFuture<?>> futures) {
520             if (!futures.isEmpty()) {
521                 long timeout = Math.min(ADD_GROUP_TIMEOUT * futures.size(), MAX_ADD_GROUP_TIMEOUT);
522                 try {
523                     Futures.successfulAsList(futures).get(timeout, TimeUnit.NANOSECONDS);
524                     LOG.trace("awaitGroups() completed: node={}", nodeId);
525                 } catch (TimeoutException | InterruptedException | ExecutionException e) {
526                     LOG.debug("add-group RPCs did not complete: node={}", nodeId);
527                 }
528             }
529         }
530     }
531
532     private BigInteger getDpnIdFromNodeName(String nodeName) {
533
534         String dpId = nodeName.substring(nodeName.lastIndexOf(SEPARATOR) + 1);
535         return new BigInteger(dpId);
536     }
537
538     private void reconciliationPreProcess(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
539         List<InstanceIdentifier<StaleFlow>> staleFlowsToBeBulkDeleted = Lists.newArrayList();
540         List<InstanceIdentifier<StaleGroup>> staleGroupsToBeBulkDeleted = Lists.newArrayList();
541         List<InstanceIdentifier<StaleMeter>> staleMetersToBeBulkDeleted = Lists.newArrayList();
542
543         ReadOnlyTransaction trans = provider.getReadTranaction();
544         Optional<FlowCapableNode> flowNode = Optional.absent();
545
546         try {
547             flowNode = trans.read(LogicalDatastoreType.CONFIGURATION, nodeIdent).get();
548         } catch (ExecutionException | InterruptedException e) {
549             LOG.warn("Reconciliation Pre-Processing Fail with read Config/DS for Node {} !", nodeIdent, e);
550         }
551
552         if (flowNode.isPresent()) {
553
554             LOG.debug("Proceeding with deletion of stale-marked Flows on switch {} using Openflow interface",
555                     nodeIdent.toString());
556             /* Stale-Flows - Stale-marked Flows have to be removed first for safety */
557             List<Table> tables = flowNode.get().getTable() != null ? flowNode.get().getTable()
558                     : Collections.<Table>emptyList();
559             for (Table table : tables) {
560                 final KeyedInstanceIdentifier<Table, TableKey> tableIdent = nodeIdent.child(Table.class,
561                         table.getKey());
562                 List<StaleFlow> staleFlows = table.getStaleFlow() != null ? table.getStaleFlow()
563                         : Collections.<StaleFlow>emptyList();
564                 for (StaleFlow staleFlow : staleFlows) {
565
566                     FlowBuilder flowBuilder = new FlowBuilder(staleFlow);
567                     Flow toBeDeletedFlow = flowBuilder.setId(staleFlow.getId()).build();
568
569                     final KeyedInstanceIdentifier<Flow, FlowKey> flowIdent = tableIdent.child(Flow.class,
570                             toBeDeletedFlow.getKey());
571
572                     this.provider.getFlowCommiter().remove(flowIdent, toBeDeletedFlow, nodeIdent);
573
574                     staleFlowsToBeBulkDeleted.add(getStaleFlowInstanceIdentifier(staleFlow, nodeIdent));
575                 }
576             }
577
578             LOG.debug("Proceeding with deletion of stale-marked Groups for switch {} using Openflow interface",
579                     nodeIdent.toString());
580
581             // TODO: Should we collate the futures of RPC-calls to be sure that groups are
582             // Flows are fully deleted
583             // before attempting to delete groups - just in case there are references
584
585             /* Stale-marked Groups - Can be deleted after flows */
586             List<StaleGroup> staleGroups = flowNode.get().getStaleGroup() != null ? flowNode.get().getStaleGroup()
587                     : Collections.<StaleGroup>emptyList();
588             for (StaleGroup staleGroup : staleGroups) {
589
590                 GroupBuilder groupBuilder = new GroupBuilder(staleGroup);
591                 Group toBeDeletedGroup = groupBuilder.setGroupId(staleGroup.getGroupId()).build();
592
593                 final KeyedInstanceIdentifier<Group, GroupKey> groupIdent = nodeIdent.child(Group.class,
594                         toBeDeletedGroup.getKey());
595
596                 this.provider.getGroupCommiter().remove(groupIdent, toBeDeletedGroup, nodeIdent);
597
598                 staleGroupsToBeBulkDeleted.add(getStaleGroupInstanceIdentifier(staleGroup, nodeIdent));
599             }
600
601             LOG.debug("Proceeding with deletion of stale-marked Meters for switch {} using Openflow interface",
602                     nodeIdent.toString());
603             /* Stale-marked Meters - can be deleted anytime - so least priority */
604             List<StaleMeter> staleMeters = flowNode.get().getStaleMeter() != null ? flowNode.get().getStaleMeter()
605                     : Collections.<StaleMeter>emptyList();
606
607             for (StaleMeter staleMeter : staleMeters) {
608
609                 MeterBuilder meterBuilder = new MeterBuilder(staleMeter);
610                 Meter toBeDeletedMeter = meterBuilder.setMeterId(staleMeter.getMeterId()).build();
611
612                 final KeyedInstanceIdentifier<Meter, MeterKey> meterIdent = nodeIdent.child(Meter.class,
613                         toBeDeletedMeter.getKey());
614
615                 this.provider.getMeterCommiter().remove(meterIdent, toBeDeletedMeter, nodeIdent);
616
617                 staleMetersToBeBulkDeleted.add(getStaleMeterInstanceIdentifier(staleMeter, nodeIdent));
618             }
619
620         }
621         /* clean transaction */
622         trans.close();
623
624         LOG.debug("Deleting all stale-marked flows/groups/meters of for switch {} in Configuration DS",
625                 nodeIdent.toString());
626         // Now, do the bulk deletions
627         deleteDSStaleFlows(staleFlowsToBeBulkDeleted);
628         deleteDSStaleGroups(staleGroupsToBeBulkDeleted);
629         deleteDSStaleMeters(staleMetersToBeBulkDeleted);
630     }
631
632     private void deleteDSStaleFlows(List<InstanceIdentifier<StaleFlow>> flowsForBulkDelete) {
633         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
634
635         for (InstanceIdentifier<StaleFlow> staleFlowIId : flowsForBulkDelete) {
636             writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleFlowIId);
637         }
638
639         CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
640         handleStaleEntityDeletionResultFuture(submitFuture);
641     }
642
643     private void deleteDSStaleGroups(List<InstanceIdentifier<StaleGroup>> groupsForBulkDelete) {
644         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
645
646         for (InstanceIdentifier<StaleGroup> staleGroupIId : groupsForBulkDelete) {
647             writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleGroupIId);
648         }
649
650         CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
651         handleStaleEntityDeletionResultFuture(submitFuture);
652     }
653
654     private void deleteDSStaleMeters(List<InstanceIdentifier<StaleMeter>> metersForBulkDelete) {
655         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
656
657         for (InstanceIdentifier<StaleMeter> staleMeterIId : metersForBulkDelete) {
658             writeTransaction.delete(LogicalDatastoreType.CONFIGURATION, staleMeterIId);
659         }
660
661         CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
662         handleStaleEntityDeletionResultFuture(submitFuture);
663     }
664
665     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
666         .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
667             StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
668         return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
669                 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
670                 new StaleFlowKey(new FlowId(staleFlow.getId())));
671     }
672
673     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
674         .group.types.rev131018.groups.StaleGroup> getStaleGroupInstanceIdentifier(
675             StaleGroup staleGroup, InstanceIdentifier<FlowCapableNode> nodeIdent) {
676         return nodeIdent.child(StaleGroup.class, new StaleGroupKey(new GroupId(staleGroup.getGroupId())));
677     }
678
679     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
680         .flow.inventory.rev130819.meters.StaleMeter> getStaleMeterInstanceIdentifier(
681             StaleMeter staleMeter, InstanceIdentifier<FlowCapableNode> nodeIdent) {
682         return nodeIdent.child(StaleMeter.class, new StaleMeterKey(new MeterId(staleMeter.getMeterId())));
683     }
684
685     private void handleStaleEntityDeletionResultFuture(
686             CheckedFuture<Void, TransactionCommitFailedException> submitFuture) {
687         Futures.addCallback(submitFuture, new FutureCallback<Void>() {
688             @Override
689             public void onSuccess(Void result) {
690                 LOG.debug("Stale entity removal success");
691             }
692
693             @Override
694             public void onFailure(Throwable throwable) {
695                 LOG.debug("Stale entity removal failed {}", throwable);
696             }
697         }, MoreExecutors.directExecutor());
698     }
699
700     private Flow getDeleteAllFlow() {
701         final FlowBuilder flowBuilder = new FlowBuilder();
702         flowBuilder.setTableId(OFConstants.OFPTT_ALL);
703         return flowBuilder.build();
704     }
705
706     private Group getDeleteAllGroup() {
707         final GroupBuilder groupBuilder = new GroupBuilder();
708         groupBuilder.setGroupType(GroupTypes.GroupAll);
709         groupBuilder.setGroupId(new GroupId(OFConstants.OFPG_ALL));
710         return groupBuilder.build();
711     }
712
713     private Messages createMessages(final NodeRef nodeRef, final Optional<FlowCapableNode> flowNode) {
714         final List<Message> messages = new ArrayList<>();
715         messages.add(new MessageBuilder().setNode(nodeRef)
716                 .setBundleInnerMessage(new BundleRemoveFlowCaseBuilder()
717                         .setRemoveFlowCaseData(new RemoveFlowCaseDataBuilder(getDeleteAllFlow()).build()).build())
718                 .build());
719
720         messages.add(new MessageBuilder().setNode(nodeRef)
721                 .setBundleInnerMessage(new BundleRemoveGroupCaseBuilder()
722                         .setRemoveGroupCaseData(new RemoveGroupCaseDataBuilder(getDeleteAllGroup()).build()).build())
723                 .build());
724
725         if (flowNode.get().getGroup() != null) {
726             for (Group gr : flowNode.get().getGroup()) {
727                 messages.add(new MessageBuilder().setNode(nodeRef).setBundleInnerMessage(new BundleAddGroupCaseBuilder()
728                         .setAddGroupCaseData(new AddGroupCaseDataBuilder(gr).build()).build()).build());
729             }
730         }
731
732         if (flowNode.get().getTable() != null) {
733             for (Table table : flowNode.get().getTable()) {
734                 for (Flow flow : table.getFlow()) {
735                     messages.add(
736                             new MessageBuilder().setNode(nodeRef)
737                                     .setBundleInnerMessage(new BundleAddFlowCaseBuilder()
738                                             .setAddFlowCaseData(new AddFlowCaseDataBuilder(flow).build()).build())
739                                     .build());
740                 }
741             }
742         }
743
744         LOG.debug("The size of the flows and group messages created in createMessage() {}", messages.size());
745         return new MessagesBuilder().setMessage(messages).build();
746     }
747 }