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