Merge "added initial waiting for mdsal in FRM"
[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 java.util.concurrent.Callable;
12 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
13 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
14 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
15 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
16 import org.opendaylight.openflowplugin.common.wait.SimpleTaskRetryLooper;
17 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
19 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInputBuilder;
23 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowTableRef;
24 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.RemoveFlowInputBuilder;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.UpdateFlowInputBuilder;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.OriginalFlowBuilder;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.flow.update.UpdatedFlowBuilder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowRef;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
32 import org.opendaylight.yangtools.concepts.ListenerRegistration;
33 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * GroupForwarder
39  * It implements {@link org.opendaylight.controller.md.sal.binding.api.DataChangeListener}}
40  * for WildCardedPath to {@link Flow} and ForwardingRulesCommiter interface for methods:
41  *  add, update and remove {@link Flow} processing for
42  *  {@link org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent}.
43  *
44  * @author <a href="mailto:vdemcak@cisco.com">Vaclav Demcak</a>
45  *
46  */
47 public class FlowForwarder extends AbstractListeningCommiter<Flow> {
48
49     private static final Logger LOG = LoggerFactory.getLogger(FlowForwarder.class);
50
51     private ListenerRegistration<FlowForwarder> listenerRegistration;
52
53     public FlowForwarder (final ForwardingRulesManager manager, final DataBroker db) {
54         super(manager, Flow.class);
55         Preconditions.checkNotNull(db, "DataBroker can not be null!");
56         registrationListener(db);
57     }
58
59     private void registrationListener(final DataBroker db) {
60         final DataTreeIdentifier<Flow> treeId = new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, getWildCardPath());
61         try {
62             SimpleTaskRetryLooper looper = new SimpleTaskRetryLooper(ForwardingRulesManagerImpl.STARTUP_LOOP_TICK,
63                     ForwardingRulesManagerImpl.STARTUP_LOOP_MAX_RETRIES);
64             listenerRegistration = looper.loopUntilNoException(new Callable<ListenerRegistration<FlowForwarder>>() {
65                 @Override
66                 public ListenerRegistration<FlowForwarder> call() throws Exception {
67                     return db.registerDataTreeChangeListener(treeId, FlowForwarder.this);
68                 }
69             });
70         } catch (final Exception e) {
71             LOG.warn("FRM Flow DataChange listener registration fail!");
72             LOG.debug("FRM Flow DataChange listener registration fail ..", e);
73             throw new IllegalStateException("FlowForwarder startup fail! System needs restart.", e);
74         }
75     }
76
77     @Override
78     public void close() {
79         if (listenerRegistration != null) {
80             try {
81                 listenerRegistration.close();
82             } catch (final Exception e) {
83                 LOG.error("Error by stop FRM FlowChangeListener.", e);
84             }
85             listenerRegistration = null;
86         }
87     }
88
89     @Override
90     public void remove(final InstanceIdentifier<Flow> identifier,
91                        final Flow removeDataObj,
92                        final InstanceIdentifier<FlowCapableNode> nodeIdent) {
93
94         final TableKey tableKey = identifier.firstKeyOf(Table.class, TableKey.class);
95         if (tableIdValidationPrecondition(tableKey, removeDataObj)) {
96             final RemoveFlowInputBuilder builder = new RemoveFlowInputBuilder(removeDataObj);
97             builder.setFlowRef(new FlowRef(identifier));
98             builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
99             builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
100
101             // This method is called only when a given flow object has been
102             // removed from datastore. So FRM always needs to set strict flag
103             // into remove-flow input so that only a flow entry associated with
104             // a given flow object is removed.
105             builder.setTransactionUri(new Uri(provider.getNewTransactionId())).
106                 setStrict(Boolean.TRUE);
107             provider.getSalFlowService().removeFlow(builder.build());
108         }
109     }
110
111     @Override
112     public void update(final InstanceIdentifier<Flow> identifier,
113                        final Flow original, final Flow update,
114                        final InstanceIdentifier<FlowCapableNode> nodeIdent) {
115
116         final TableKey tableKey = identifier.firstKeyOf(Table.class, TableKey.class);
117         if (tableIdValidationPrecondition(tableKey, update)) {
118             final UpdateFlowInputBuilder builder = new UpdateFlowInputBuilder();
119
120             builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
121             builder.setFlowRef(new FlowRef(identifier));
122             builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
123
124             // This method is called only when a given flow object in datastore
125             // has been updated. So FRM always needs to set strict flag into
126             // update-flow input so that only a flow entry associated with
127             // a given flow object is updated.
128             builder.setUpdatedFlow((new UpdatedFlowBuilder(update)).setStrict(Boolean.TRUE).build());
129             builder.setOriginalFlow((new OriginalFlowBuilder(original)).setStrict(Boolean.TRUE).build());
130
131             provider.getSalFlowService().updateFlow(builder.build());
132         }
133     }
134
135     @Override
136     public void add(final InstanceIdentifier<Flow> identifier,
137                     final Flow addDataObj,
138                     final InstanceIdentifier<FlowCapableNode> nodeIdent) {
139
140         final TableKey tableKey = identifier.firstKeyOf(Table.class, TableKey.class);
141         if (tableIdValidationPrecondition(tableKey, addDataObj)) {
142             final AddFlowInputBuilder builder = new AddFlowInputBuilder(addDataObj);
143
144             builder.setNode(new NodeRef(nodeIdent.firstIdentifierOf(Node.class)));
145             builder.setFlowRef(new FlowRef(identifier));
146             builder.setFlowTable(new FlowTableRef(nodeIdent.child(Table.class, tableKey)));
147             builder.setTransactionUri(new Uri(provider.getNewTransactionId()));
148             provider.getSalFlowService().addFlow(builder.build());
149         }
150     }
151
152     @Override
153     protected InstanceIdentifier<Flow> getWildCardPath() {
154         return InstanceIdentifier.create(Nodes.class).child(Node.class)
155                 .augmentation(FlowCapableNode.class).child(Table.class).child(Flow.class);
156     }
157
158     private static boolean tableIdValidationPrecondition (final TableKey tableKey, final Flow flow) {
159         Preconditions.checkNotNull(tableKey, "TableKey can not be null or empty!");
160         Preconditions.checkNotNull(flow, "Flow can not be null or empty!");
161         if (! tableKey.getId().equals(flow.getTableId())) {
162             LOG.error("TableID in URI tableId={} and in palyload tableId={} is not same.",
163                     flow.getTableId(), tableKey.getId());
164             return false;
165         }
166         return true;
167     }
168 }
169