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