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