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