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