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