Bump MRI 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.Collection;
17 import org.eclipse.jdt.annotation.Nullable;
18 import org.opendaylight.mdsal.binding.api.DataBroker;
19 import org.opendaylight.mdsal.binding.api.DataObjectModification;
20 import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
21 import org.opendaylight.mdsal.binding.api.DataTreeModification;
22 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
23 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesCommiter;
24 import org.opendaylight.openflowplugin.applications.frm.ForwardingRulesManager;
25 import org.opendaylight.openflowplugin.applications.frm.NodeConfigurator;
26 import org.opendaylight.serviceutils.srm.RecoverableListener;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
28 import org.opendaylight.yangtools.concepts.ListenerRegistration;
29 import org.opendaylight.yangtools.yang.binding.DataObject;
30 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * AbstractChangeListner implemented basic {@link org.opendaylight.mdsal.binding.api.DataTreeModification}
36  * processing for flow node subDataObject (flows, groups and meters).
37  */
38 public abstract class AbstractListeningCommiter<T extends DataObject>
39         implements ForwardingRulesCommiter<T>, RecoverableListener {
40
41     private static final Logger LOG = LoggerFactory.getLogger(AbstractListeningCommiter.class);
42     final ForwardingRulesManager provider;
43     NodeConfigurator nodeConfigurator;
44     protected final DataBroker dataBroker;
45     protected final ListenerRegistrationHelper registrationHelper;
46     protected ListenerRegistration<AbstractListeningCommiter> 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         this.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 Collection<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
89                                     IllegalArgumentException("Unhandled modification type "
90                                     + mod.getModificationType());
91                     }
92                 } else {
93                     if (provider.isStaleMarkingEnabled()) {
94                         LOG.info("Stale-Marking ENABLED and switch {} is NOT connected, storing stale entities",
95                                 nodeIdent.toString());
96                         // Switch is NOT connected
97                         switch (mod.getModificationType()) {
98                             case DELETE:
99                                 createStaleMarkEntity(key, mod.getDataBefore(), nodeIdent);
100                                 break;
101                             case SUBTREE_MODIFIED:
102                                 break;
103                             case WRITE:
104                                 break;
105                             default:
106                                 throw new
107                                         IllegalArgumentException("Unhandled modification type "
108                                         + mod.getModificationType());
109                         }
110                     }
111                 }
112             } catch (RuntimeException e) {
113                 LOG.error("Failed to handle event {} key {} due to error ", mod.getModificationType(), key, e);
114             }
115         }
116     }
117
118     @Override
119     public final void registerListener() {
120         final DataTreeIdentifier<T> treeId =
121                 DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, getWildCardPath());
122         Futures.addCallback(registrationHelper.checkedRegisterListener(treeId, this),
123                 new FutureCallback<ListenerRegistration<AbstractListeningCommiter>>() {
124                     @Override
125                     public void onSuccess(
126                             @Nullable final ListenerRegistration<AbstractListeningCommiter> flowListenerRegistration) {
127                         LOG.info("{} registered successfully", flowListenerRegistration.getInstance());
128                         listenerRegistration = flowListenerRegistration;
129                     }
130
131                     @Override
132                     public void onFailure(final Throwable throwable) {
133                         LOG.error("Registration failed ", throwable);
134                     }
135                 }, MoreExecutors.directExecutor());
136     }
137
138     /**
139      * Method return wildCardPath for Listener registration
140      * and for identify the correct KeyInstanceIdentifier from data.
141      */
142     protected abstract InstanceIdentifier<T> getWildCardPath();
143
144     private boolean preConfigurationCheck(final InstanceIdentifier<FlowCapableNode> nodeIdent) {
145         requireNonNull(nodeIdent, "FlowCapableNode identifier can not be null!");
146         // In single node cluster, node should be in local cache before we get any flow/group/meter
147         // data change event from data store. So first check should pass.
148         // In case of 3-node cluster, when shard leader changes, clustering will send blob of data
149         // present in operational data store and config data store. So ideally local node cache
150         // should get populated. But to handle a scenario where flow request comes before the blob
151         // of config/operational data gets processes, it won't find node in local cache and it will
152         // skip the flow/group/meter operational. This requires an addition check, where it reads
153         // node from operational data store and if it's present it calls flowNodeConnected to explicitly
154         // trigger the event of new node connected.
155         return provider.isNodeOwner(nodeIdent);
156     }
157 }