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