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