BUG-5280: add SimpleDataStoreClientBehavior
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / DistributedDataStore.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.messages.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.DOMStoreReadTransaction;
37 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
38 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
39 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTreeChangePublisher;
40 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
45 import org.opendaylight.yangtools.concepts.ListenerRegistration;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  * Implements a distributed DOMStore.
55  */
56 public class DistributedDataStore implements DistributedDataStoreInterface, SchemaContextListener,
57         DatastoreContextConfigAdminOverlay.Listener, DOMStoreTreeChangePublisher,
58         DOMDataTreeCommitCohortRegistry, AutoCloseable {
59
60     private static final Logger LOG = LoggerFactory.getLogger(DistributedDataStore.class);
61
62     private static final long READY_WAIT_FACTOR = 3;
63
64     private final ActorContext actorContext;
65     private final long waitTillReadyTimeInMillis;
66
67     private AutoCloseable closeable;
68
69     private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
70
71     private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
72
73     private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
74
75     private final ClientIdentifier identifier;
76     private final DataStoreClient client;
77
78     private final TransactionContextFactory txContextFactory;
79
80     @SuppressWarnings("checkstyle:IllegalCatch")
81     public DistributedDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
82             final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
83             final DatastoreSnapshot restoreFromSnapshot) {
84         Preconditions.checkNotNull(actorSystem, "actorSystem should not be null");
85         Preconditions.checkNotNull(cluster, "cluster should not be null");
86         Preconditions.checkNotNull(configuration, "configuration should not be null");
87         Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
88
89         String shardManagerId = ShardManagerIdentifier.builder()
90                 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
91
92         LOG.info("Creating ShardManager : {}", shardManagerId);
93
94         String shardDispatcher =
95                 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
96
97         PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
98
99         ShardManagerCreator creator = new ShardManagerCreator().cluster(cluster).configuration(configuration)
100                 .datastoreContextFactory(datastoreContextFactory)
101                 .waitTillReadyCountDownLatch(waitTillReadyCountDownLatch)
102                 .primaryShardInfoCache(primaryShardInfoCache)
103                 .restoreFromSnapshot(restoreFromSnapshot);
104
105         actorContext = new ActorContext(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
106                 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
107                 primaryShardInfoCache);
108
109         final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
110             datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorContext);
111         final ActorRef clientActor = actorSystem.actorOf(clientProps);
112         try {
113             client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
114         } catch (Exception e) {
115             LOG.error("Failed to get actor for {}", clientProps, e);
116             clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
117             throw Throwables.propagate(e);
118         }
119
120         identifier = client.getIdentifier();
121         LOG.debug("Distributed data store client {} started", identifier);
122
123         this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
124                 .duration().toMillis() * READY_WAIT_FACTOR;
125
126         this.txContextFactory = new TransactionContextFactory(actorContext, identifier);
127
128         datastoreConfigMXBean = new DatastoreConfigurationMXBeanImpl(
129                 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
130         datastoreConfigMXBean.setContext(datastoreContextFactory.getBaseDatastoreContext());
131         datastoreConfigMXBean.registerMBean();
132
133         datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContextFactory.getBaseDatastoreContext()
134                 .getDataStoreMXBeanType(), actorContext);
135         datastoreInfoMXBean.registerMBean();
136     }
137
138     @VisibleForTesting
139     DistributedDataStore(final ActorContext actorContext, final ClientIdentifier identifier) {
140         this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
141         this.client = null;
142         this.identifier = Preconditions.checkNotNull(identifier);
143         this.txContextFactory = new TransactionContextFactory(actorContext, identifier);
144         this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
145                 .duration().toMillis() * READY_WAIT_FACTOR;
146     }
147
148     public void setCloseable(final AutoCloseable closeable) {
149         this.closeable = closeable;
150     }
151
152     @SuppressWarnings("unchecked")
153     @Override
154     public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
155                                               ListenerRegistration<L> registerChangeListener(
156         final YangInstanceIdentifier path, final L listener,
157         final AsyncDataBroker.DataChangeScope scope) {
158
159         Preconditions.checkNotNull(path, "path should not be null");
160         Preconditions.checkNotNull(listener, "listener should not be null");
161
162         LOG.debug("Registering listener: {} for path: {} scope: {}", listener, path, scope);
163
164         String shardName = actorContext.getShardStrategyFactory().getStrategy(path).findShard(path);
165
166         final DataChangeListenerRegistrationProxy listenerRegistrationProxy =
167                 new DataChangeListenerRegistrationProxy(shardName, actorContext, listener);
168         listenerRegistrationProxy.init(path, scope);
169
170         return listenerRegistrationProxy;
171     }
172
173     @Override
174     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
175             final YangInstanceIdentifier treeId, final L listener) {
176         Preconditions.checkNotNull(treeId, "treeId should not be null");
177         Preconditions.checkNotNull(listener, "listener should not be null");
178
179         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
180         LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
181
182         final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
183                 new DataTreeChangeListenerProxy<>(actorContext, listener);
184         listenerRegistrationProxy.init(shardName, treeId);
185
186         return listenerRegistrationProxy;
187     }
188
189
190     @Override
191     public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
192             final DOMDataTreeIdentifier subtree, final C cohort) {
193         YangInstanceIdentifier treeId =
194                 Preconditions.checkNotNull(subtree, "subtree should not be null").getRootIdentifier();
195         Preconditions.checkNotNull(cohort, "listener should not be null");
196
197
198         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
199         LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
200
201         DataTreeCohortRegistrationProxy<C> cohortProxy =
202                 new DataTreeCohortRegistrationProxy<>(actorContext, subtree, cohort);
203         cohortProxy.init(shardName);
204         return cohortProxy;
205     }
206
207     @Override
208     public DOMStoreTransactionChain createTransactionChain() {
209         return txContextFactory.createTransactionChain();
210     }
211
212     @Override
213     public DOMStoreReadTransaction newReadOnlyTransaction() {
214         return new TransactionProxy(txContextFactory, TransactionType.READ_ONLY);
215     }
216
217     @Override
218     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
219         actorContext.acquireTxCreationPermit();
220         return new TransactionProxy(txContextFactory, TransactionType.WRITE_ONLY);
221     }
222
223     @Override
224     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
225         actorContext.acquireTxCreationPermit();
226         return new TransactionProxy(txContextFactory, TransactionType.READ_WRITE);
227     }
228
229     @Override
230     public void onGlobalContextUpdated(final SchemaContext schemaContext) {
231         actorContext.setSchemaContext(schemaContext);
232     }
233
234     @Override
235     public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
236         LOG.info("DatastoreContext updated for data store {}", actorContext.getDataStoreName());
237
238         actorContext.setDatastoreContext(contextFactory);
239         datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
240     }
241
242     @Override
243     @SuppressWarnings("checkstyle:IllegalCatch")
244     public void close() {
245         LOG.info("Closing data store {}", identifier);
246
247         if (datastoreConfigMXBean != null) {
248             datastoreConfigMXBean.unregisterMBean();
249         }
250         if (datastoreInfoMXBean != null) {
251             datastoreInfoMXBean.unregisterMBean();
252         }
253
254         if (closeable != null) {
255             try {
256                 closeable.close();
257             } catch (Exception e) {
258                 LOG.debug("Error closing instance", e);
259             }
260         }
261
262         txContextFactory.close();
263         actorContext.shutdown();
264
265         if (client != null) {
266             client.close();
267         }
268     }
269
270     @Override
271     public ActorContext getActorContext() {
272         return actorContext;
273     }
274
275     public void waitTillReady() {
276         LOG.info("Beginning to wait for data store to become ready : {}", identifier);
277
278         try {
279             if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
280                 LOG.debug("Data store {} is now ready", identifier);
281             } else {
282                 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
283                         TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
284             }
285         } catch (InterruptedException e) {
286             LOG.error("Interrupted while waiting for shards to settle", e);
287         }
288     }
289
290     @SuppressWarnings("checkstyle:IllegalCatch")
291     private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
292             final String shardDispatcher, final String shardManagerId) {
293         Exception lastException = null;
294
295         for (int i = 0; i < 100; i++) {
296             try {
297                 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher).withMailbox(
298                         ActorContext.BOUNDED_MAILBOX), shardManagerId);
299             } catch (Exception e) {
300                 lastException = e;
301                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
302                 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
303                         + "(retry count = {})", shardManagerId, e.getMessage(), i);
304             }
305         }
306
307         throw new IllegalStateException("Failed to create Shard Manager", lastException);
308     }
309
310     @VisibleForTesting
311     public CountDownLatch getWaitTillReadyCountDownLatch() {
312         return waitTillReadyCountDownLatch;
313     }
314 }