Bump upstreams
[openflowplugin.git] / applications / forwardingrules-manager / src / main / java / org / opendaylight / openflowplugin / applications / frm / impl / AbstractListeningCommiter.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 static java.util.Objects.requireNonNull;
11
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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.util.List;
17 import org.opendaylight.mdsal.binding.api.DataBroker;
18 import org.opendaylight.mdsal.binding.api.DataObjectModification;
19 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
20 import org.opendaylight.mdsal.binding.api.DataTreeModification;
21 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
22 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesCommiter;
23 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
24 import org.opendaylight.openflowplugin.applications.frm.NodeConfigurator;
25 import org.opendaylight.serviceutils.srm.RecoverableListener;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
27 import org.opendaylight.yangtools.concepts.Registration;
28 import org.opendaylight.yangtools.yang.binding.DataObject;
29 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * AbstractChangeListner implemented basic {@link org.opendaylight.mdsal.binding.api.DataTreeModification}
35  * processing for flow node subDataObject (flows, groups and meters).
36  */
37 public abstract class AbstractListeningCommiter<T extends DataObject>
38         implements ForwardingRulesCommiter<T>, RecoverableListener {
39     private static final Logger LOG = LoggerFactory.getLogger(AbstractListeningCommiter.class);
40
41     final ForwardingRulesManager provider;
42     NodeConfigurator nodeConfigurator;
43     protected final DataBroker dataBroker;
44     private final ListenerRegistrationHelper registrationHelper;
45
46     private Registration listenerRegistration;
47
48     @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "See FIXME below")
49     protected AbstractListeningCommiter(final ForwardingRulesManager provider, final DataBroker dataBroker,
50                                      final ListenerRegistrationHelper registrationHelper) {
51         this.provider = requireNonNull(provider, "ForwardingRulesManager can not be null!");
52         nodeConfigurator = requireNonNull(provider.getNodeConfigurator(), "NodeConfigurator can not be null!");
53         this.dataBroker = requireNonNull(dataBroker, "DataBroker can not be null!");
54         this.registrationHelper = requireNonNull(registrationHelper, "registrationHelper can not be null!");
55
56         // FIXME: this may start listening on an uninitialized object: clean up the lifecycle here
57         registerListener();
58         provider.addRecoverableListener(this);
59     }
60
61     @SuppressWarnings("checkstyle:IllegalCatch")
62     @Override
63     public void onDataTreeChanged(final List<DataTreeModification<T>> changes) {
64         LOG.trace("Received data changes :{}", requireNonNull(changes, "Changes may not be null!"));
65
66         for (DataTreeModification<T> change : changes) {
67             final InstanceIdentifier<T> key = change.getRootPath().getRootIdentifier();
68             final DataObjectModification<T> mod = change.getRootNode();
69             final InstanceIdentifier<FlowCapableNode> nodeIdent =
70                     key.firstIdentifierOf(FlowCapableNode.class);
71             try {
72                 if (preConfigurationCheck(nodeIdent)) {
73                     switch (mod.getModificationType()) {
74                         case DELETE:
75                             remove(key, mod.getDataBefore(), nodeIdent);
76                             break;
77                         case SUBTREE_MODIFIED:
78                             update(key, mod.getDataBefore(), mod.getDataAfter(), nodeIdent);
79                             break;
80                         case WRITE:
81                             if (mod.getDataBefore() == null) {
82                                 add(key, mod.getDataAfter(), nodeIdent);
83                             } else {
84                                 update(key, mod.getDataBefore(), mod.getDataAfter(), nodeIdent);
85                             }
86                             break;
87                         default:
88                             throw new IllegalArgumentException(
89                                 "Unhandled modification type " + mod.getModificationType());
90                     }
91                 } else if (provider.isStaleMarkingEnabled()) {
92                     LOG.info("Stale-Marking ENABLED and switch {} is NOT connected, storing stale entities", nodeIdent);
93                     // Switch is NOT connected
94                     switch (mod.getModificationType()) {
95                         case DELETE:
96                             createStaleMarkEntity(key, mod.getDataBefore(), nodeIdent);
97                             break;
98                         case SUBTREE_MODIFIED:
99                         case WRITE:
100                             break;
101                         default:
102                             throw new IllegalArgumentException(
103                                 "Unhandled modification type " + mod.getModificationType());
104                     }
105                 }
106             } catch (RuntimeException e) {
107                 LOG.error("Failed to handle event {} key {} due to error ", mod.getModificationType(), key, e);
108             }
109         }
110     }
111
112     @Override
113     public final void registerListener() {
114         Futures.addCallback(registrationHelper.checkedRegisterListener(
115             DataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION, getWildCardPath()), this),
116             new FutureCallback<Registration>() {
117                 @Override
118                 public void onSuccess(final Registration flowListenerRegistration) {
119                     LOG.info("{} registered successfully", this);
120                     listenerRegistration = flowListenerRegistration;
121                 }
122
123                 @Override
124                 public void onFailure(final Throwable throwable) {
125                     LOG.error("Registration failed ", throwable);
126                 }
127             }, MoreExecutors.directExecutor());
128     }
129
130     @Override
131     public void deregisterListener() {
132         close();
133     }
134
135     @Override
136     public void close() {
137         if (listenerRegistration != null) {
138             listenerRegistration.close();
139             listenerRegistration = null;
140         }
141     }
142
143     /**
144      * Method return wildCardPath for Listener registration
145      * and for identify the correct KeyInstanceIdentifier from data.
146      */
147     protected abstract InstanceIdentifier<T> getWildCardPath();
148
149     private boolean preConfigurationCheck(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
150         requireNonNull(nodeIdent, "FlowCapableNode identifier can not be null!");
151         // In single node cluster, node should be in local cache before we get any flow/group/meter
152         // data change event from data store. So first check should pass.
153         // In case of 3-node cluster, when shard leader changes, clustering will send blob of data
154         // present in operational data store and config data store. So ideally local node cache
155         // should get populated. But to handle a scenario where flow request comes before the blob
156         // of config/operational data gets processes, it won't find node in local cache and it will
157         // skip the flow/group/meter operational. This requires an addition check, where it reads
158         // node from operational data store and if it's present it calls flowNodeConnected to explicitly
159         // trigger the event of new node connected.
160         return provider.isNodeOwner(nodeIdent);
161     }
162 }