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