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