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