55108e0ef9cd720895b04d560145022b3cdae703
[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 package org.opendaylight.controller.cluster.datastore;
9
10 import static java.util.Objects.requireNonNull;
11
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSystem;
14 import akka.actor.PoisonPill;
15 import akka.actor.Props;
16 import com.google.common.annotations.VisibleForTesting;
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.ActorUtils;
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 ActorUtils actorUtils;
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         requireNonNull(actorSystem, "actorSystem should not be null");
78         requireNonNull(cluster, "cluster should not be null");
79         requireNonNull(configuration, "configuration should not be null");
80         requireNonNull(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         actorUtils = new ActorUtils(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(), actorUtils);
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 = actorUtils.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(), actorUtils);
128         datastoreInfoMXBean.registerMBean();
129     }
130
131     @VisibleForTesting
132     protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier) {
133         this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
134         this.client = null;
135         this.identifier = requireNonNull(identifier);
136         this.waitTillReadyTimeInMillis = actorUtils.getDatastoreContext().getShardLeaderElectionTimeout()
137                 .duration().toMillis() * READY_WAIT_FACTOR;
138     }
139
140     @VisibleForTesting
141     protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
142                                 final DataStoreClient clientActor) {
143         this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
144         this.client = clientActor;
145         this.identifier = requireNonNull(identifier);
146         this.waitTillReadyTimeInMillis = actorUtils.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         requireNonNull(treeId, "treeId should not be null");
166         requireNonNull(listener, "listener should not be null");
167
168         final String shardName = actorUtils.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<>(actorUtils, 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 = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
183         requireNonNull(cohort, "listener should not be null");
184
185
186         final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
187         LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
188
189         DataTreeCohortRegistrationProxy<C> cohortProxy =
190                 new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
191         cohortProxy.init(shardName);
192         return cohortProxy;
193     }
194
195     @Override
196     public void onGlobalContextUpdated(final SchemaContext schemaContext) {
197         actorUtils.setSchemaContext(schemaContext);
198     }
199
200     @Override
201     public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
202         LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
203
204         actorUtils.setDatastoreContext(contextFactory);
205         datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
206     }
207
208     @Override
209     @SuppressWarnings("checkstyle:IllegalCatch")
210     public void close() {
211         LOG.info("Closing data store {}", identifier);
212
213         if (datastoreConfigMXBean != null) {
214             datastoreConfigMXBean.unregisterMBean();
215         }
216         if (datastoreInfoMXBean != null) {
217             datastoreInfoMXBean.unregisterMBean();
218         }
219
220         if (closeable != null) {
221             try {
222                 closeable.close();
223             } catch (Exception e) {
224                 LOG.debug("Error closing instance", e);
225             }
226         }
227
228         actorUtils.shutdown();
229
230         if (client != null) {
231             client.close();
232         }
233     }
234
235     @Override
236     public ActorUtils getActorUtils() {
237         return actorUtils;
238     }
239
240     public void waitTillReady() {
241         LOG.info("Beginning to wait for data store to become ready : {}", identifier);
242
243         try {
244             if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
245                 LOG.debug("Data store {} is now ready", identifier);
246             } else {
247                 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
248                         TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
249             }
250         } catch (InterruptedException e) {
251             LOG.error("Interrupted while waiting for shards to settle", e);
252         }
253     }
254
255     @SuppressWarnings("checkstyle:IllegalCatch")
256     private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
257             final String shardDispatcher, final String shardManagerId) {
258         Exception lastException = null;
259
260         for (int i = 0; i < 100; i++) {
261             try {
262                 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
263             } catch (Exception e) {
264                 lastException = e;
265                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
266                 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
267                         + "(retry count = {})", shardManagerId, e.getMessage(), i);
268             }
269         }
270
271         throw new IllegalStateException("Failed to create Shard Manager", lastException);
272     }
273
274     @VisibleForTesting
275     public CountDownLatch getWaitTillReadyCountDownLatch() {
276         return waitTillReadyCountDownLatch;
277     }
278
279     @SuppressWarnings("unchecked")
280     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
281             final YangInstanceIdentifier shardLookup,
282             final YangInstanceIdentifier insideShard,
283             final org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener delegate) {
284
285         requireNonNull(shardLookup, "shardLookup should not be null");
286         requireNonNull(insideShard, "insideShard should not be null");
287         requireNonNull(delegate, "delegate should not be null");
288
289         final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
290         LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
291                 delegate,shardLookup, shardName, insideShard);
292
293         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
294                 new DataTreeChangeListenerProxy<>(actorUtils,
295                         // wrap this in the ClusteredDOMDataTreeChangeLister interface
296                         // since we always want clustered registration
297                         (ClusteredDOMDataTreeChangeListener) delegate::onDataTreeChanged, insideShard);
298         listenerRegistrationProxy.init(shardName);
299
300         return (ListenerRegistration<L>) listenerRegistrationProxy;
301     }
302
303     @SuppressWarnings("unchecked")
304     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
305             final YangInstanceIdentifier internalPath,
306             final DOMDataTreeChangeListener delegate) {
307         requireNonNull(delegate, "delegate should not be null");
308
309         LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
310
311         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
312                 new DataTreeChangeListenerProxy<>(actorUtils, delegate, internalPath);
313         proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
314
315         return (ListenerRegistration<L>) proxy;
316     }
317
318 }