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