Fix findbugs violations in applications
[openflowplugin.git] / applications / forwardingrules-manager / src / main / java / org / opendaylight / openflowplugin / applications / frm / impl / FlowForwarder.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.util.concurrent.CheckedFuture;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import com.google.common.util.concurrent.MoreExecutors;
15 import com.google.common.util.concurrent.SettableFuture;
16 import java.util.concurrent.Future;
17 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
18 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
19 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
22 import org.opendaylight.infrautils.utils.concurrent.JdkFutures;
23 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
24 import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowBuilder;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlowKey;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowOutput;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowTableRef;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowOutput;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInputBuilder;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowOutput;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlowBuilder;
42 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlowBuilder;
43 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
44 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
45 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
46 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
47 import org.opendaylight.yangtools.concepts.ListenerRegistration;
48 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
49 import org.opendaylight.yangtools.yang.common.RpcResult;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * FlowForwarder It implements
55  * {@link org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener}
56  * for WildCardedPath to {@link Flow} and ForwardingRulesCommiter interface for
57  * methods: add, update and remove {@link Flow} processing for
58  * {@link org.opendaylight.controller.md.sal.binding.api.DataTreeModification}.
59  */
60 public class FlowForwarder extends AbstractListeningCommiter<Flow> {
61
62     private static final Logger LOG = LoggerFactory.getLogger(FlowForwarder.class);
63     private final DataBroker dataBroker;
64     private ListenerRegistration<FlowForwarder> listenerRegistration;
65
66     public FlowForwarder(final ForwardingRulesManager manager, final DataBroker db) {
67         super(manager);
68         dataBroker = Preconditions.checkNotNull(db, "DataBroker can not be null!");
69         registrationListener(db);
70     }
71
72     @SuppressWarnings("IllegalCatch")
73     private void registrationListener(final DataBroker db) {
74         final DataTreeIdentifier<Flow> treeId = new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
75                 getWildCardPath());
76         try {
77             SimpleTaskRetryLooper looper = new SimpleTaskRetryLooper(ForwardingRulesManagerImpl.STARTUP_LOOP_TICK,
78                     ForwardingRulesManagerImpl.STARTUP_LOOP_MAX_RETRIES);
79             listenerRegistration = looper
80                     .loopUntilNoException(() -> db.registerDataTreeChangeListener(treeId, FlowForwarder.this));
81         } catch (final Exception e) {
82             LOG.warn("FRM Flow DataTreeChange listener registration fail!");
83             LOG.debug("FRM Flow DataTreeChange listener registration fail ..", e);
84             throw new IllegalStateException("FlowForwarder startup fail! System needs restart.", e);
85         }
86     }
87
88     @Override
89     public void close() {
90         if (listenerRegistration != null) {
91             listenerRegistration.close();
92             listenerRegistration = null;
93         }
94     }
95
96     @Override
97     public void remove(final InstanceIdentifier<Flow> identifier, final Flow removeDataObj,
98             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
99
100         final TableKey tableKey = identifier.firstKeyOf(Table.class, TableKey.class);
101         if (tableIdValidationPrecondition(tableKey, removeDataObj)) {
102             final RemoveFlowInputBuilder builder = new RemoveFlowInputBuilder(removeDataObj);
103             builder.setFlowRef(new FlowRef(identifier));
104             builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
105             builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
106
107             // This method is called only when a given flow object has been
108             // removed from datastore. So FRM always needs to set strict flag
109             // into remove-flow input so that only a flow entry associated with
110             // a given flow object is removed.
111             builder.setTransactionUri(new Uri(provider.getNewTransactionId())).setStrict(Boolean.TRUE);
112             final Future<RpcResult<RemoveFlowOutput>> resultFuture =
113                     provider.getSalFlowService().removeFlow(builder.build());
114             JdkFutures.addErrorLogging(resultFuture, LOG, "removeFlow");
115         }
116     }
117
118     // TODO: Pull this into ForwardingRulesCommiter and override it here
119
120     @Override
121     public Future<RpcResult<RemoveFlowOutput>> removeWithResult(final InstanceIdentifier<Flow> identifier,
122             final Flow removeDataObj, final InstanceIdentifier<FlowCapableNode> nodeIdent) {
123
124         Future<RpcResult<RemoveFlowOutput>> resultFuture = SettableFuture.create();
125         final TableKey tableKey = identifier.firstKeyOf(Table.class, TableKey.class);
126         if (tableIdValidationPrecondition(tableKey, removeDataObj)) {
127             final RemoveFlowInputBuilder builder = new RemoveFlowInputBuilder(removeDataObj);
128             builder.setFlowRef(new FlowRef(identifier));
129             builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
130             builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
131
132             // This method is called only when a given flow object has been
133             // removed from datastore. So FRM always needs to set strict flag
134             // into remove-flow input so that only a flow entry associated with
135             // a given flow object is removed.
136             builder.setTransactionUri(new Uri(provider.getNewTransactionId())).setStrict(Boolean.TRUE);
137             resultFuture = provider.getSalFlowService().removeFlow(builder.build());
138         }
139
140         return resultFuture;
141     }
142
143     @Override
144     public void update(final InstanceIdentifier<Flow> identifier, final Flow original, final Flow update,
145             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
146
147         final TableKey tableKey = identifier.firstKeyOf(Table.class, TableKey.class);
148         if (tableIdValidationPrecondition(tableKey, update)) {
149             final UpdateFlowInputBuilder builder = new UpdateFlowInputBuilder();
150
151             builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
152             builder.setFlowRef(new FlowRef(identifier));
153             builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
154
155             // This method is called only when a given flow object in datastore
156             // has been updated. So FRM always needs to set strict flag into
157             // update-flow input so that only a flow entry associated with
158             // a given flow object is updated.
159             builder.setUpdatedFlow(new UpdatedFlowBuilder(update).setStrict(Boolean.TRUE).build());
160             builder.setOriginalFlow(new OriginalFlowBuilder(original).setStrict(Boolean.TRUE).build());
161
162             final Future<RpcResult<UpdateFlowOutput>> resultFuture =
163                     provider.getSalFlowService().updateFlow(builder.build());
164             JdkFutures.addErrorLogging(resultFuture, LOG, "updateFlow");
165         }
166     }
167
168     @Override
169     public Future<RpcResult<AddFlowOutput>> add(final InstanceIdentifier<Flow> identifier, final Flow addDataObj,
170             final InstanceIdentifier<FlowCapableNode> nodeIdent) {
171
172         Future<RpcResult<AddFlowOutput>> future;
173         final TableKey tableKey = identifier.firstKeyOf(Table.class, TableKey.class);
174         if (tableIdValidationPrecondition(tableKey, addDataObj)) {
175             final AddFlowInputBuilder builder = new AddFlowInputBuilder(addDataObj);
176
177             builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
178             builder.setFlowRef(new FlowRef(identifier));
179             builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
180             builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
181             future = provider.getSalFlowService().addFlow(builder.build());
182         } else {
183             future = Futures.<RpcResult<AddFlowOutput>>immediateFuture(null);
184         }
185
186         return future;
187     }
188
189     @Override
190     public void createStaleMarkEntity(InstanceIdentifier<Flow> identifier, Flow del,
191             InstanceIdentifier<FlowCapableNode> nodeIdent) {
192         LOG.debug("Creating Stale-Mark entry for the switch {} for flow {} ", nodeIdent.toString(), del.toString());
193
194         StaleFlow staleFlow = makeStaleFlow(identifier, del, nodeIdent);
195         persistStaleFlow(staleFlow, nodeIdent);
196
197     }
198
199     @Override
200     protected InstanceIdentifier<Flow> getWildCardPath() {
201         return InstanceIdentifier.create(Nodes.class).child(Node.class).augmentation(FlowCapableNode.class)
202                 .child(Table.class).child(Flow.class);
203     }
204
205     private static boolean tableIdValidationPrecondition(final TableKey tableKey, final Flow flow) {
206         Preconditions.checkNotNull(tableKey, "TableKey can not be null or empty!");
207         Preconditions.checkNotNull(flow, "Flow can not be null or empty!");
208         if (!tableKey.getId().equals(flow.getTableId())) {
209             LOG.warn("TableID in URI tableId={} and in palyload tableId={} is not same.", flow.getTableId(),
210                     tableKey.getId());
211             return false;
212         }
213         return true;
214     }
215
216     private StaleFlow makeStaleFlow(InstanceIdentifier<Flow> identifier, Flow del,
217             InstanceIdentifier<FlowCapableNode> nodeIdent) {
218         StaleFlowBuilder staleFlowBuilder = new StaleFlowBuilder(del);
219         return staleFlowBuilder.setId(del.getId()).build();
220     }
221
222     private void persistStaleFlow(StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
223         WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
224         writeTransaction.put(LogicalDatastoreType.CONFIGURATION, getStaleFlowInstanceIdentifier(staleFlow, nodeIdent),
225                 staleFlow, false);
226
227         CheckedFuture<Void, TransactionCommitFailedException> submitFuture = writeTransaction.submit();
228         handleStaleFlowResultFuture(submitFuture);
229     }
230
231     private void handleStaleFlowResultFuture(CheckedFuture<Void, TransactionCommitFailedException> submitFuture) {
232         Futures.addCallback(submitFuture, new FutureCallback<Void>() {
233             @Override
234             public void onSuccess(Void result) {
235                 LOG.debug("Stale Flow creation success");
236             }
237
238             @Override
239             public void onFailure(Throwable throwable) {
240                 LOG.error("Stale Flow creation failed {}", throwable);
241             }
242         }, MoreExecutors.directExecutor());
243
244     }
245
246     private InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight
247         .flow.inventory.rev130819.tables.table.StaleFlow> getStaleFlowInstanceIdentifier(
248             StaleFlow staleFlow, InstanceIdentifier<FlowCapableNode> nodeIdent) {
249         return nodeIdent.child(Table.class, new TableKey(staleFlow.getTableId())).child(
250                 org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.StaleFlow.class,
251                 new StaleFlowKey(new FlowId(staleFlow.getId())));
252     }
253 }