dce5368218f30685f30fcc2894a5be73c08cab5a
[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.persisted.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     @VisibleForTesting
140     protected AbstractDataStore(final ActorContext actorContext, final ClientIdentifier identifier,
141                                 final DataStoreClient clientActor) {
142         this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
143         this.client = clientActor;
144         this.identifier = Preconditions.checkNotNull(identifier);
145         this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
146                 .duration().toMillis() * READY_WAIT_FACTOR;
147     }
148
149     protected final DataStoreClient getClient() {
150         return client;
151     }
152
153     final ClientIdentifier getIdentifier() {
154         return identifier;
155     }
156
157     public void setCloseable(final AutoCloseable closeable) {
158         this.closeable = closeable;
159     }
160
161     @SuppressWarnings("unchecked")
162     @Override
163     public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
164                                               ListenerRegistration<L> registerChangeListener(
165         final YangInstanceIdentifier path, final L listener,
166         final AsyncDataBroker.DataChangeScope scope) {
167
168         Preconditions.checkNotNull(path, "path should not be null");
169         Preconditions.checkNotNull(listener, "listener should not be null");
170
171         LOG.debug("Registering listener: {} for path: {} scope: {}", listener, path, scope);
172
173         String shardName = actorContext.getShardStrategyFactory().getStrategy(path).findShard(path);
174
175         final DataChangeListenerRegistrationProxy listenerRegistrationProxy =
176                 new DataChangeListenerRegistrationProxy(shardName, actorContext, listener);
177         listenerRegistrationProxy.init(path, scope);
178
179         return listenerRegistrationProxy;
180     }
181
182     @Override
183     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
184             final YangInstanceIdentifier treeId, final L listener) {
185         Preconditions.checkNotNull(treeId, "treeId should not be null");
186         Preconditions.checkNotNull(listener, "listener should not be null");
187
188         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
189         LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
190
191         final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
192                 new DataTreeChangeListenerProxy<>(actorContext, listener, treeId);
193         listenerRegistrationProxy.init(shardName);
194
195         return listenerRegistrationProxy;
196     }
197
198
199     @Override
200     public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
201             final DOMDataTreeIdentifier subtree, final C cohort) {
202         YangInstanceIdentifier treeId =
203                 Preconditions.checkNotNull(subtree, "subtree should not be null").getRootIdentifier();
204         Preconditions.checkNotNull(cohort, "listener should not be null");
205
206
207         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
208         LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
209
210         DataTreeCohortRegistrationProxy<C> cohortProxy =
211                 new DataTreeCohortRegistrationProxy<>(actorContext, subtree, cohort);
212         cohortProxy.init(shardName);
213         return cohortProxy;
214     }
215
216     @Override
217     public void onGlobalContextUpdated(final SchemaContext schemaContext) {
218         actorContext.setSchemaContext(schemaContext);
219     }
220
221     @Override
222     public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
223         LOG.info("DatastoreContext updated for data store {}", actorContext.getDataStoreName());
224
225         actorContext.setDatastoreContext(contextFactory);
226         datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
227     }
228
229     @Override
230     @SuppressWarnings("checkstyle:IllegalCatch")
231     public void close() {
232         LOG.info("Closing data store {}", identifier);
233
234         if (datastoreConfigMXBean != null) {
235             datastoreConfigMXBean.unregisterMBean();
236         }
237         if (datastoreInfoMXBean != null) {
238             datastoreInfoMXBean.unregisterMBean();
239         }
240
241         if (closeable != null) {
242             try {
243                 closeable.close();
244             } catch (Exception e) {
245                 LOG.debug("Error closing instance", e);
246             }
247         }
248
249         actorContext.shutdown();
250
251         if (client != null) {
252             client.close();
253         }
254     }
255
256     @Override
257     public ActorContext getActorContext() {
258         return actorContext;
259     }
260
261     public void waitTillReady() {
262         LOG.info("Beginning to wait for data store to become ready : {}", identifier);
263
264         try {
265             if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
266                 LOG.debug("Data store {} is now ready", identifier);
267             } else {
268                 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
269                         TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
270             }
271         } catch (InterruptedException e) {
272             LOG.error("Interrupted while waiting for shards to settle", e);
273         }
274     }
275
276     @SuppressWarnings("checkstyle:IllegalCatch")
277     private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
278             final String shardDispatcher, final String shardManagerId) {
279         Exception lastException = null;
280
281         for (int i = 0; i < 100; i++) {
282             try {
283                 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher).withMailbox(
284                         ActorContext.BOUNDED_MAILBOX), shardManagerId);
285             } catch (Exception e) {
286                 lastException = e;
287                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
288                 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
289                         + "(retry count = {})", shardManagerId, e.getMessage(), i);
290             }
291         }
292
293         throw new IllegalStateException("Failed to create Shard Manager", lastException);
294     }
295
296     @VisibleForTesting
297     public CountDownLatch getWaitTillReadyCountDownLatch() {
298         return waitTillReadyCountDownLatch;
299     }
300
301     @SuppressWarnings("unchecked")
302     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
303             final YangInstanceIdentifier shardLookup,
304             final YangInstanceIdentifier insideShard,
305             final org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener delegate) {
306
307         Preconditions.checkNotNull(shardLookup, "shardLookup should not be null");
308         Preconditions.checkNotNull(insideShard, "insideShard should not be null");
309         Preconditions.checkNotNull(delegate, "delegate should not be null");
310
311         final String shardName = actorContext.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
312         LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
313                 delegate,shardLookup, shardName, insideShard);
314
315         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
316                 new DataTreeChangeListenerProxy<>(actorContext, delegate::onDataTreeChanged, insideShard);
317         listenerRegistrationProxy.init(shardName);
318
319         return (ListenerRegistration<L>) listenerRegistrationProxy;
320     }
321
322 }