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