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