cf60b089d832a8b0c2bf6a9f1c1d76443c119204
[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 com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import akka.actor.ActorRef;
14 import akka.actor.ActorSystem;
15 import akka.actor.PoisonPill;
16 import akka.actor.Props;
17 import com.google.common.annotations.Beta;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Throwables;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import com.google.common.util.concurrent.SettableFuture;
22 import com.google.common.util.concurrent.Uninterruptibles;
23 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
24 import java.util.List;
25 import java.util.Set;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.TimeoutException;
29 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
30 import org.opendaylight.controller.cluster.common.actor.Dispatchers;
31 import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
32 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClientActor;
33 import org.opendaylight.controller.cluster.datastore.config.Configuration;
34 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
35 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
36 import org.opendaylight.controller.cluster.datastore.shardmanager.AbstractShardManagerCreator;
37 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
38 import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
39 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
40 import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
45 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
46 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
47 import org.opendaylight.yangtools.concepts.ListenerRegistration;
48 import org.opendaylight.yangtools.yang.common.Empty;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
51 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
52 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import scala.concurrent.duration.Duration;
56
57 /**
58  * Base implementation of a distributed DOMStore.
59  */
60 public abstract class AbstractDataStore implements DistributedDataStoreInterface, EffectiveModelContextListener,
61         DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
62         DOMDataTreeCommitCohortRegistry, AutoCloseable {
63
64     private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
65
66     private final SettableFuture<Empty> readinessFuture = SettableFuture.create();
67     private final ClientIdentifier identifier;
68     private final DataStoreClient client;
69     private final ActorUtils actorUtils;
70
71     private AutoCloseable closeable;
72     private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
73     private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
74
75     @SuppressWarnings("checkstyle:IllegalCatch")
76     @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "Testing overrides")
77     protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
78             final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
79             final DatastoreSnapshot restoreFromSnapshot) {
80         requireNonNull(actorSystem, "actorSystem should not be null");
81         requireNonNull(cluster, "cluster should not be null");
82         requireNonNull(configuration, "configuration should not be null");
83         requireNonNull(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         AbstractShardManagerCreator<?> creator = getShardManagerCreator().cluster(cluster).configuration(configuration)
96                 .datastoreContextFactory(datastoreContextFactory)
97                 .readinessFuture(readinessFuture)
98                 .primaryShardInfoCache(primaryShardInfoCache)
99                 .restoreFromSnapshot(restoreFromSnapshot)
100                 .distributedDataStore(this);
101
102         actorUtils = new ActorUtils(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(), actorUtils);
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         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         client = null;
135         this.identifier = requireNonNull(identifier);
136     }
137
138     @VisibleForTesting
139     protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
140                                 final DataStoreClient clientActor) {
141         this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
142         client = clientActor;
143         this.identifier = requireNonNull(identifier);
144     }
145
146     protected AbstractShardManagerCreator<?> getShardManagerCreator() {
147         return new ShardManagerCreator();
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         /*
169          * We need to potentially deal with multi-shard composition for registration targeting the root of the data
170          * store. If that is the case, we delegate to a more complicated setup invol
171          */
172         if (treeId.isEmpty()) {
173             // User is targeting root of the datastore. If there is more than one shard, we have to register with them
174             // all and perform data composition.
175             final Set<String> shardNames = actorUtils.getConfiguration().getAllShardNames();
176             if (shardNames.size() > 1) {
177                 checkArgument(listener instanceof ClusteredDOMDataTreeChangeListener,
178                     "Cannot listen on root without non-clustered listener %s", listener);
179                 return new RootDataTreeChangeListenerProxy<>(actorUtils, listener, shardNames);
180             }
181         }
182
183         final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
184         LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
185
186         final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
187                 new DataTreeChangeListenerProxy<>(actorUtils, listener, treeId);
188         listenerRegistrationProxy.init(shardName);
189
190         return listenerRegistrationProxy;
191     }
192
193     @Override
194     public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
195             final DOMDataTreeIdentifier subtree, final C cohort) {
196         YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
197         requireNonNull(cohort, "listener should not be null");
198
199
200         final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
201         LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
202
203         DataTreeCohortRegistrationProxy<C> cohortProxy =
204                 new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
205         cohortProxy.init(shardName);
206         return cohortProxy;
207     }
208
209     @Override
210     public void onModelContextUpdated(final EffectiveModelContext newModelContext) {
211         actorUtils.setSchemaContext(newModelContext);
212     }
213
214     @Override
215     public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
216         LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
217
218         actorUtils.setDatastoreContext(contextFactory);
219         datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
220     }
221
222     @Override
223     @SuppressWarnings("checkstyle:IllegalCatch")
224     public void close() {
225         LOG.info("Closing data store {}", identifier);
226
227         if (datastoreConfigMXBean != null) {
228             datastoreConfigMXBean.unregisterMBean();
229         }
230         if (datastoreInfoMXBean != null) {
231             datastoreInfoMXBean.unregisterMBean();
232         }
233
234         if (closeable != null) {
235             try {
236                 closeable.close();
237             } catch (Exception e) {
238                 LOG.debug("Error closing instance", e);
239             }
240         }
241
242         actorUtils.shutdown();
243
244         if (client != null) {
245             client.close();
246         }
247     }
248
249     @Override
250     public final ActorUtils getActorUtils() {
251         return actorUtils;
252     }
253
254     // TODO: consider removing this in favor of awaitReadiness()
255     @Deprecated
256     public void waitTillReady() {
257         LOG.info("Beginning to wait for data store to become ready : {}", identifier);
258
259         final Duration toWait = initialSettleTime();
260         try {
261             if (!awaitReadiness(toWait)) {
262                 LOG.error("Shard leaders failed to settle in {}, giving up", toWait);
263                 return;
264             }
265         } catch (InterruptedException e) {
266             LOG.error("Interrupted while waiting for shards to settle", e);
267             return;
268         }
269
270         LOG.debug("Data store {} is now ready", identifier);
271     }
272
273     @Beta
274     @Deprecated
275     public boolean awaitReadiness() throws InterruptedException {
276         return awaitReadiness(initialSettleTime());
277     }
278
279     @Beta
280     @Deprecated
281     public boolean awaitReadiness(final Duration toWait) throws InterruptedException {
282         try {
283             if (toWait.isFinite()) {
284                 try {
285                     readinessFuture.get(toWait.toNanos(), TimeUnit.NANOSECONDS);
286                 } catch (TimeoutException e) {
287                     LOG.debug("Timed out waiting for shards to settle", e);
288                     return false;
289                 }
290             } else {
291                 readinessFuture.get();
292             }
293         } catch (ExecutionException e) {
294             LOG.warn("Unexpected readiness failure, assuming convergence", e);
295         }
296
297         return true;
298     }
299
300     @Beta
301     @Deprecated
302     public void awaitReadiness(final long timeout, final TimeUnit unit) throws InterruptedException, TimeoutException {
303         if (!awaitReadiness(Duration.create(timeout, unit))) {
304             throw new TimeoutException("Shard leaders failed to settle");
305         }
306     }
307
308     @SuppressWarnings("checkstyle:IllegalCatch")
309     private static ActorRef createShardManager(final ActorSystem actorSystem,
310             final AbstractShardManagerCreator<?> creator, final String shardDispatcher,
311             final String shardManagerId) {
312         Exception lastException = null;
313
314         for (int i = 0; i < 100; i++) {
315             try {
316                 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher), shardManagerId);
317             } catch (Exception e) {
318                 lastException = e;
319                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
320                 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
321                         + "(retry count = {})", shardManagerId, e.getMessage(), i);
322             }
323         }
324
325         throw new IllegalStateException("Failed to create Shard Manager", lastException);
326     }
327
328     /**
329      * Future which completes when all shards settle for the first time.
330      *
331      * @return A Listenable future.
332      */
333     public final ListenableFuture<?> initialSettleFuture() {
334         return readinessFuture;
335     }
336
337     @VisibleForTesting
338     SettableFuture<Empty> readinessFuture() {
339         return readinessFuture;
340     }
341
342     @Override
343     @SuppressWarnings("unchecked")
344     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
345             final YangInstanceIdentifier shardLookup, final YangInstanceIdentifier insideShard,
346             final DOMDataTreeChangeListener delegate) {
347
348         requireNonNull(shardLookup, "shardLookup should not be null");
349         requireNonNull(insideShard, "insideShard should not be null");
350         requireNonNull(delegate, "delegate should not be null");
351
352         final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
353         LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
354                 delegate,shardLookup, shardName, insideShard);
355
356         // wrap this in the ClusteredDOMDataTreeChangeLister interface
357         // since we always want clustered registration
358         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
359                 new DataTreeChangeListenerProxy<>(actorUtils, new ClusteredDOMDataTreeChangeListener() {
360                     @Override
361                     public void onDataTreeChanged(final List<DataTreeCandidate> changes) {
362                         delegate.onDataTreeChanged(changes);
363                     }
364
365                     @Override
366                     public void onInitialData() {
367                         delegate.onInitialData();
368                     }
369                 }, insideShard);
370         listenerRegistrationProxy.init(shardName);
371
372         return (ListenerRegistration<L>) listenerRegistrationProxy;
373     }
374
375     private Duration initialSettleTime() {
376         final DatastoreContext context = actorUtils.getDatastoreContext();
377         final int multiplier = context.getInitialSettleTimeoutMultiplier();
378         return multiplier == 0 ? Duration.Inf() : context.getShardLeaderElectionTimeout().duration().$times(multiplier);
379     }
380 }