Merge "BUG-2673: make CDS implement DOMDataTreeChangeListener"
[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.ActorSystem;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Preconditions;
14 import java.util.concurrent.CountDownLatch;
15 import java.util.concurrent.TimeUnit;
16 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
17 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreConfigurationMXBeanImpl;
18 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreInfoMXBeanImpl;
19 import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
20 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
21 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
22 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
23 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
25 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
26 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
27 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
28 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
29 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTreeChangePublisher;
30 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
31 import org.opendaylight.yangtools.concepts.ListenerRegistration;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 /**
40  *
41  */
42 public class DistributedDataStore implements DOMStore, SchemaContextListener,
43         DatastoreContextConfigAdminOverlay.Listener, DOMStoreTreeChangePublisher, AutoCloseable {
44
45     private static final Logger LOG = LoggerFactory.getLogger(DistributedDataStore.class);
46     private static final String UNKNOWN_TYPE = "unknown";
47
48     private static final long READY_WAIT_FACTOR = 3;
49
50     private final ActorContext actorContext;
51     private final long waitTillReadyTimeInMillis;
52
53
54     private AutoCloseable closeable;
55
56     private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
57
58     private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
59
60     private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
61
62     private final String type;
63
64     public DistributedDataStore(ActorSystem actorSystem, ClusterWrapper cluster,
65             Configuration configuration, DatastoreContext datastoreContext) {
66         Preconditions.checkNotNull(actorSystem, "actorSystem should not be null");
67         Preconditions.checkNotNull(cluster, "cluster should not be null");
68         Preconditions.checkNotNull(configuration, "configuration should not be null");
69         Preconditions.checkNotNull(datastoreContext, "datastoreContext should not be null");
70
71         this.type = datastoreContext.getDataStoreType();
72
73         String shardManagerId = ShardManagerIdentifier.builder().type(type).build().toString();
74
75         LOG.info("Creating ShardManager : {}", shardManagerId);
76
77         String shardDispatcher =
78                 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
79
80         actorContext = new ActorContext(actorSystem, actorSystem.actorOf(
81                 ShardManager.props(cluster, configuration, datastoreContext, waitTillReadyCountDownLatch)
82                         .withDispatcher(shardDispatcher).withMailbox(ActorContext.MAILBOX), shardManagerId ),
83                 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, TransactionProxy.TransactionType.READ_ONLY);
153     }
154
155     @Override
156     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
157         actorContext.acquireTxCreationPermit();
158         return new TransactionProxy(actorContext, TransactionProxy.TransactionType.WRITE_ONLY);
159     }
160
161     @Override
162     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
163         actorContext.acquireTxCreationPermit();
164         return new TransactionProxy(actorContext, TransactionProxy.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 insance", e);
190             }
191         }
192
193         actorContext.shutdown();
194     }
195
196     @VisibleForTesting
197     ActorContext getActorContext() {
198         return actorContext;
199     }
200
201     public void waitTillReady(){
202         LOG.info("Beginning to wait for data store to become ready : {}", type);
203
204         try {
205             if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
206                 LOG.debug("Data store {} is now ready", type);
207             } else {
208                 LOG.error("Shared leaders failed to settle in {} seconds, giving up", TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
209             }
210         } catch (InterruptedException e) {
211             LOG.error("Interrupted while waiting for shards to settle", e);
212         }
213     }
214
215     @VisibleForTesting
216     public CountDownLatch getWaitTillReadyCountDownLatch() {
217         return waitTillReadyCountDownLatch;
218     }
219 }