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