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