Bug 4105: Add dynamic module/shard config for entity-owners shard
[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, DatastoreContext datastoreContext) {
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(datastoreContext, "datastoreContext should not be null");
75
76         this.type = datastoreContext.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                 datastoreContext, shardDispatcher, shardManagerId, primaryShardInfoCache), cluster,
88                 configuration, datastoreContext, 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(datastoreContext.getDataStoreMXBeanType());
96         datastoreConfigMXBean.setContext(datastoreContext);
97         datastoreConfigMXBean.registerMBean();
98
99         datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContext.getDataStoreMXBeanType(), actorContext);
100         datastoreInfoMXBean.registerMBean();
101     }
102
103     @VisibleForTesting
104     DistributedDataStore(ActorContext actorContext) {
105         this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
106         this.txContextFactory = TransactionContextFactory.create(actorContext);
107         this.type = UNKNOWN_TYPE;
108         this.waitTillReadyTimeInMillis =
109                 actorContext.getDatastoreContext().getShardLeaderElectionTimeout().duration().toMillis() * READY_WAIT_FACTOR;
110     }
111
112     public void setCloseable(AutoCloseable closeable) {
113         this.closeable = closeable;
114     }
115
116     @SuppressWarnings("unchecked")
117     @Override
118     public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
119                                               ListenerRegistration<L> registerChangeListener(
120         final YangInstanceIdentifier path, L listener,
121         AsyncDataBroker.DataChangeScope scope) {
122
123         Preconditions.checkNotNull(path, "path should not be null");
124         Preconditions.checkNotNull(listener, "listener should not be null");
125
126         LOG.debug("Registering listener: {} for path: {} scope: {}", listener, path, scope);
127
128         String shardName = actorContext.getShardStrategyFactory().getStrategy(path).findShard(path);
129
130         final DataChangeListenerRegistrationProxy listenerRegistrationProxy =
131                 new DataChangeListenerRegistrationProxy(shardName, actorContext, listener);
132         listenerRegistrationProxy.init(path, scope);
133
134         return listenerRegistrationProxy;
135     }
136
137     @Override
138     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(YangInstanceIdentifier treeId, L listener) {
139         Preconditions.checkNotNull(treeId, "treeId should not be null");
140         Preconditions.checkNotNull(listener, "listener should not be null");
141
142         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
143         LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
144
145         final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
146                 new DataTreeChangeListenerProxy<L>(actorContext, listener);
147         listenerRegistrationProxy.init(shardName, treeId);
148
149         return listenerRegistrationProxy;
150     }
151
152     @Override
153     public DOMStoreTransactionChain createTransactionChain() {
154         return txContextFactory.createTransactionChain();
155     }
156
157     @Override
158     public DOMStoreReadTransaction newReadOnlyTransaction() {
159        return new TransactionProxy(txContextFactory, TransactionType.READ_ONLY);
160     }
161
162     @Override
163     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
164         actorContext.acquireTxCreationPermit();
165         return new TransactionProxy(txContextFactory, TransactionType.WRITE_ONLY);
166     }
167
168     @Override
169     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
170         actorContext.acquireTxCreationPermit();
171         return new TransactionProxy(txContextFactory, TransactionType.READ_WRITE);
172     }
173
174     @Override
175     public void onGlobalContextUpdated(SchemaContext schemaContext) {
176         actorContext.setSchemaContext(schemaContext);
177     }
178
179     @Override
180     public void onDatastoreContextUpdated(DatastoreContext context) {
181         LOG.info("DatastoreContext updated for data store {}", actorContext.getDataStoreType());
182
183         actorContext.setDatastoreContext(context);
184         datastoreConfigMXBean.setContext(context);
185     }
186
187     @Override
188     public void close() {
189         datastoreConfigMXBean.unregisterMBean();
190         datastoreInfoMXBean.unregisterMBean();
191
192         if (closeable != null) {
193             try {
194                 closeable.close();
195             } catch (Exception e) {
196                 LOG.debug("Error closing instance", e);
197             }
198         }
199
200         txContextFactory.close();
201         actorContext.shutdown();
202         DistributedDataStoreFactory.destroyInstance(this);
203     }
204
205     public ActorContext getActorContext() {
206         return actorContext;
207     }
208
209     public void waitTillReady(){
210         LOG.info("Beginning to wait for data store to become ready : {}", type);
211
212         try {
213             if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
214                 LOG.debug("Data store {} is now ready", type);
215             } else {
216                 LOG.error("Shared leaders failed to settle in {} seconds, giving up", TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
217             }
218         } catch (InterruptedException e) {
219             LOG.error("Interrupted while waiting for shards to settle", e);
220         }
221     }
222
223     private ActorRef createShardManager(ActorSystem actorSystem, ClusterWrapper cluster, Configuration configuration,
224                                         DatastoreContext datastoreContext, String shardDispatcher, String shardManagerId,
225                                         PrimaryShardInfoFutureCache primaryShardInfoCache){
226         Exception lastException = null;
227
228         for(int i=0;i<100;i++) {
229             try {
230                 return actorSystem.actorOf(
231                         ShardManager.props(cluster, configuration, datastoreContext, waitTillReadyCountDownLatch,
232                                 primaryShardInfoCache).withDispatcher(shardDispatcher).withMailbox(
233                                         ActorContext.MAILBOX), shardManagerId);
234             } catch (Exception e){
235                 lastException = e;
236                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
237                 LOG.debug(String.format("Could not create actor %s because of %s - waiting for sometime before retrying (retry count = %d)", shardManagerId, e.getMessage(), i));
238             }
239         }
240
241         throw new IllegalStateException("Failed to create Shard Manager", lastException);
242     }
243
244     @VisibleForTesting
245     public CountDownLatch getWaitTillReadyCountDownLatch() {
246         return waitTillReadyCountDownLatch;
247     }
248 }