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