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