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