Remove DataChangeListener and friends
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / AbstractDataStore.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
9 package org.opendaylight.controller.cluster.datastore;
10
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSystem;
13 import akka.actor.PoisonPill;
14 import akka.actor.Props;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Preconditions;
17 import com.google.common.base.Throwables;
18 import com.google.common.util.concurrent.Uninterruptibles;
19 import java.util.concurrent.CountDownLatch;
20 import java.util.concurrent.TimeUnit;
21 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
22 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
23 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
24 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClientActor;
25 import org.opendaylight.controller.cluster.datastore.config.Configuration;
26 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
27 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreConfigurationMXBeanImpl;
28 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreInfoMXBeanImpl;
29 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
30 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
31 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
32 import org.opendaylight.controller.cluster.datastore.utils.ClusterUtils;
33 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
34 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
36 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
37 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
38 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
39 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
40 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
41 import org.opendaylight.yangtools.concepts.ListenerRegistration;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * Base implementation of a distributed DOMStore.
50  */
51 public abstract class AbstractDataStore implements DistributedDataStoreInterface, SchemaContextListener,
52         DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
53         DOMDataTreeCommitCohortRegistry, AutoCloseable {
54
55     private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
56
57     private static final long READY_WAIT_FACTOR = 3;
58
59     private final ActorContext actorContext;
60     private final long waitTillReadyTimeInMillis;
61
62     private AutoCloseable closeable;
63
64     private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
65
66     private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
67
68     private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
69
70     private final ClientIdentifier identifier;
71     private final DataStoreClient client;
72
73     @SuppressWarnings("checkstyle:IllegalCatch")
74     protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
75             final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
76             final DatastoreSnapshot restoreFromSnapshot) {
77         Preconditions.checkNotNull(actorSystem, "actorSystem should not be null");
78         Preconditions.checkNotNull(cluster, "cluster should not be null");
79         Preconditions.checkNotNull(configuration, "configuration should not be null");
80         Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
81
82         String shardManagerId = ShardManagerIdentifier.builder()
83                 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
84
85         LOG.info("Creating ShardManager : {}", shardManagerId);
86
87         String shardDispatcher =
88                 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
89
90         PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
91
92         ShardManagerCreator creator = new ShardManagerCreator().cluster(cluster).configuration(configuration)
93                 .datastoreContextFactory(datastoreContextFactory)
94                 .waitTillReadyCountDownLatch(waitTillReadyCountDownLatch)
95                 .primaryShardInfoCache(primaryShardInfoCache)
96                 .restoreFromSnapshot(restoreFromSnapshot)
97                 .distributedDataStore(this);
98
99         actorContext = new ActorContext(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
100                 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
101                 primaryShardInfoCache);
102
103         final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
104             datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorContext);
105         final ActorRef clientActor = actorSystem.actorOf(clientProps);
106         try {
107             client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
108         } catch (Exception e) {
109             LOG.error("Failed to get actor for {}", clientProps, e);
110             clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
111             Throwables.throwIfUnchecked(e);
112             throw new RuntimeException(e);
113         }
114
115         identifier = client.getIdentifier();
116         LOG.debug("Distributed data store client {} started", identifier);
117
118         this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
119                 .duration().toMillis() * READY_WAIT_FACTOR;
120
121         datastoreConfigMXBean = new DatastoreConfigurationMXBeanImpl(
122                 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
123         datastoreConfigMXBean.setContext(datastoreContextFactory.getBaseDatastoreContext());
124         datastoreConfigMXBean.registerMBean();
125
126         datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContextFactory.getBaseDatastoreContext()
127                 .getDataStoreMXBeanType(), actorContext);
128         datastoreInfoMXBean.registerMBean();
129     }
130
131     @VisibleForTesting
132     protected AbstractDataStore(final ActorContext actorContext, final ClientIdentifier identifier) {
133         this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
134         this.client = null;
135         this.identifier = Preconditions.checkNotNull(identifier);
136         this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
137                 .duration().toMillis() * READY_WAIT_FACTOR;
138     }
139
140     @VisibleForTesting
141     protected AbstractDataStore(final ActorContext actorContext, final ClientIdentifier identifier,
142                                 final DataStoreClient clientActor) {
143         this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
144         this.client = clientActor;
145         this.identifier = Preconditions.checkNotNull(identifier);
146         this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
147                 .duration().toMillis() * READY_WAIT_FACTOR;
148     }
149
150     protected final DataStoreClient getClient() {
151         return client;
152     }
153
154     final ClientIdentifier getIdentifier() {
155         return identifier;
156     }
157
158     public void setCloseable(final AutoCloseable closeable) {
159         this.closeable = closeable;
160     }
161
162     @Override
163     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
164             final YangInstanceIdentifier treeId, final L listener) {
165         Preconditions.checkNotNull(treeId, "treeId should not be null");
166         Preconditions.checkNotNull(listener, "listener should not be null");
167
168         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
169         LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
170
171         final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
172                 new DataTreeChangeListenerProxy<>(actorContext, listener, treeId);
173         listenerRegistrationProxy.init(shardName);
174
175         return listenerRegistrationProxy;
176     }
177
178
179     @Override
180     public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
181             final DOMDataTreeIdentifier subtree, final C cohort) {
182         YangInstanceIdentifier treeId =
183                 Preconditions.checkNotNull(subtree, "subtree should not be null").getRootIdentifier();
184         Preconditions.checkNotNull(cohort, "listener should not be null");
185
186
187         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
188         LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
189
190         DataTreeCohortRegistrationProxy<C> cohortProxy =
191                 new DataTreeCohortRegistrationProxy<>(actorContext, subtree, cohort);
192         cohortProxy.init(shardName);
193         return cohortProxy;
194     }
195
196     @Override
197     public void onGlobalContextUpdated(final SchemaContext schemaContext) {
198         actorContext.setSchemaContext(schemaContext);
199     }
200
201     @Override
202     public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
203         LOG.info("DatastoreContext updated for data store {}", actorContext.getDataStoreName());
204
205         actorContext.setDatastoreContext(contextFactory);
206         datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
207     }
208
209     @Override
210     @SuppressWarnings("checkstyle:IllegalCatch")
211     public void close() {
212         LOG.info("Closing data store {}", identifier);
213
214         if (datastoreConfigMXBean != null) {
215             datastoreConfigMXBean.unregisterMBean();
216         }
217         if (datastoreInfoMXBean != null) {
218             datastoreInfoMXBean.unregisterMBean();
219         }
220
221         if (closeable != null) {
222             try {
223                 closeable.close();
224             } catch (Exception e) {
225                 LOG.debug("Error closing instance", e);
226             }
227         }
228
229         actorContext.shutdown();
230
231         if (client != null) {
232             client.close();
233         }
234     }
235
236     @Override
237     public ActorContext getActorContext() {
238         return actorContext;
239     }
240
241     public void waitTillReady() {
242         LOG.info("Beginning to wait for data store to become ready : {}", identifier);
243
244         try {
245             if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
246                 LOG.debug("Data store {} is now ready", identifier);
247             } else {
248                 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
249                         TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
250             }
251         } catch (InterruptedException e) {
252             LOG.error("Interrupted while waiting for shards to settle", e);
253         }
254     }
255
256     @SuppressWarnings("checkstyle:IllegalCatch")
257     private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
258             final String shardDispatcher, final String shardManagerId) {
259         Exception lastException = null;
260
261         for (int i = 0; i < 100; i++) {
262             try {
263                 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
264             } catch (Exception e) {
265                 lastException = e;
266                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
267                 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
268                         + "(retry count = {})", shardManagerId, e.getMessage(), i);
269             }
270         }
271
272         throw new IllegalStateException("Failed to create Shard Manager", lastException);
273     }
274
275     @VisibleForTesting
276     public CountDownLatch getWaitTillReadyCountDownLatch() {
277         return waitTillReadyCountDownLatch;
278     }
279
280     @SuppressWarnings("unchecked")
281     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
282             final YangInstanceIdentifier shardLookup,
283             final YangInstanceIdentifier insideShard,
284             final org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener delegate) {
285
286         Preconditions.checkNotNull(shardLookup, "shardLookup should not be null");
287         Preconditions.checkNotNull(insideShard, "insideShard should not be null");
288         Preconditions.checkNotNull(delegate, "delegate should not be null");
289
290         final String shardName = actorContext.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
291         LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
292                 delegate,shardLookup, shardName, insideShard);
293
294         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
295                 new DataTreeChangeListenerProxy<>(actorContext,
296                         // wrap this in the ClusteredDOMDataTreeChangeLister interface
297                         // since we always want clustered registration
298                         (ClusteredDOMDataTreeChangeListener) delegate::onDataTreeChanged, insideShard);
299         listenerRegistrationProxy.init(shardName);
300
301         return (ListenerRegistration<L>) listenerRegistrationProxy;
302     }
303
304     @SuppressWarnings("unchecked")
305     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
306             final YangInstanceIdentifier internalPath,
307             final DOMDataTreeChangeListener delegate) {
308         Preconditions.checkNotNull(delegate, "delegate should not be null");
309
310         LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
311
312         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
313                 new DataTreeChangeListenerProxy<>(actorContext, delegate, internalPath);
314         proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
315
316         return (ListenerRegistration<L>) proxy;
317     }
318
319 }