Mechanical code cleanup (sal-distributed-datastore)
[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 akka.actor.PoisonPill;
14 import akka.actor.Props;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Preconditions;
17 import com.google.common.base.Throwables;
18 import com.google.common.util.concurrent.Uninterruptibles;
19 import java.util.concurrent.CountDownLatch;
20 import java.util.concurrent.TimeUnit;
21 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
22 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClient;
23 import org.opendaylight.controller.cluster.databroker.actors.dds.DistributedDataStoreClientActor;
24 import org.opendaylight.controller.cluster.datastore.config.Configuration;
25 import org.opendaylight.controller.cluster.datastore.identifiers.ShardManagerIdentifier;
26 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreConfigurationMXBeanImpl;
27 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.DatastoreInfoMXBeanImpl;
28 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
29 import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
30 import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
31 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
32 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
33 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
34 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
35 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
36 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
37 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
38 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
39 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTreeChangePublisher;
40 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
43 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
44 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
45 import org.opendaylight.yangtools.concepts.ListenerRegistration;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 /**
54  *
55  */
56 public class DistributedDataStore implements DistributedDataStoreInterface, SchemaContextListener,
57         DatastoreContextConfigAdminOverlay.Listener, DOMStoreTreeChangePublisher, DOMDataTreeCommitCohortRegistry, AutoCloseable {
58
59     private static final Logger LOG = LoggerFactory.getLogger(DistributedDataStore.class);
60
61     private static final long READY_WAIT_FACTOR = 3;
62
63     private final ActorContext actorContext;
64     private final long waitTillReadyTimeInMillis;
65
66     private AutoCloseable closeable;
67
68     private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
69
70     private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
71
72     private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
73
74     private final ClientIdentifier identifier;
75     private final DistributedDataStoreClient client;
76
77     private final TransactionContextFactory txContextFactory;
78
79     public DistributedDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
80             final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
81             final DatastoreSnapshot restoreFromSnapshot) {
82         Preconditions.checkNotNull(actorSystem, "actorSystem should not be null");
83         Preconditions.checkNotNull(cluster, "cluster should not be null");
84         Preconditions.checkNotNull(configuration, "configuration should not be null");
85         Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
86
87         String shardManagerId = ShardManagerIdentifier.builder()
88                 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
89
90         LOG.info("Creating ShardManager : {}", shardManagerId);
91
92         String shardDispatcher =
93                 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
94
95         PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
96
97         ShardManagerCreator creator = new ShardManagerCreator().cluster(cluster).configuration(configuration).
98                 datastoreContextFactory(datastoreContextFactory).waitTillReadyCountdownLatch(waitTillReadyCountDownLatch).
99                 primaryShardInfoCache(primaryShardInfoCache).restoreFromSnapshot(restoreFromSnapshot);
100
101         actorContext = new ActorContext(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
102                 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(), primaryShardInfoCache);
103
104         final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
105             datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorContext);
106         final ActorRef clientActor = actorSystem.actorOf(clientProps);
107         try {
108             client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
109         } catch (Exception e) {
110             LOG.error("Failed to get actor for {}", clientProps, e);
111             clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
112             throw Throwables.propagate(e);
113         }
114
115         identifier = client.getIdentifier();
116         LOG.debug("Distributed data store client {} started", identifier);
117
118         this.waitTillReadyTimeInMillis =
119                 actorContext.getDatastoreContext().getShardLeaderElectionTimeout().duration().toMillis() * READY_WAIT_FACTOR;
120
121         this.txContextFactory = new TransactionContextFactory(actorContext, identifier);
122
123         datastoreConfigMXBean = new DatastoreConfigurationMXBeanImpl(
124                 datastoreContextFactory.getBaseDatastoreContext().getDataStoreMXBeanType());
125         datastoreConfigMXBean.setContext(datastoreContextFactory.getBaseDatastoreContext());
126         datastoreConfigMXBean.registerMBean();
127
128         datastoreInfoMXBean = new DatastoreInfoMXBeanImpl(datastoreContextFactory.getBaseDatastoreContext().
129                 getDataStoreMXBeanType(), actorContext);
130         datastoreInfoMXBean.registerMBean();
131     }
132
133     @VisibleForTesting
134     DistributedDataStore(final ActorContext actorContext, final ClientIdentifier identifier) {
135         this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
136         this.client = null;
137         this.identifier = Preconditions.checkNotNull(identifier);
138         this.txContextFactory = new TransactionContextFactory(actorContext, identifier);
139         this.waitTillReadyTimeInMillis =
140                 actorContext.getDatastoreContext().getShardLeaderElectionTimeout().duration().toMillis() * READY_WAIT_FACTOR;
141     }
142
143     public void setCloseable(final AutoCloseable closeable) {
144         this.closeable = closeable;
145     }
146
147     @SuppressWarnings("unchecked")
148     @Override
149     public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
150                                               ListenerRegistration<L> registerChangeListener(
151         final YangInstanceIdentifier path, final L listener,
152         final AsyncDataBroker.DataChangeScope scope) {
153
154         Preconditions.checkNotNull(path, "path should not be null");
155         Preconditions.checkNotNull(listener, "listener should not be null");
156
157         LOG.debug("Registering listener: {} for path: {} scope: {}", listener, path, scope);
158
159         String shardName = actorContext.getShardStrategyFactory().getStrategy(path).findShard(path);
160
161         final DataChangeListenerRegistrationProxy listenerRegistrationProxy =
162                 new DataChangeListenerRegistrationProxy(shardName, actorContext, listener);
163         listenerRegistrationProxy.init(path, scope);
164
165         return listenerRegistrationProxy;
166     }
167
168     @Override
169     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(final YangInstanceIdentifier treeId, final L listener) {
170         Preconditions.checkNotNull(treeId, "treeId should not be null");
171         Preconditions.checkNotNull(listener, "listener should not be null");
172
173         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
174         LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
175
176         final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
177                 new DataTreeChangeListenerProxy<>(actorContext, listener);
178         listenerRegistrationProxy.init(shardName, treeId);
179
180         return listenerRegistrationProxy;
181     }
182
183
184     @Override
185     public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
186             final DOMDataTreeIdentifier subtree, final C cohort) {
187         YangInstanceIdentifier treeId =
188                 Preconditions.checkNotNull(subtree, "subtree should not be null").getRootIdentifier();
189         Preconditions.checkNotNull(cohort, "listener should not be null");
190
191
192         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
193         LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
194
195         DataTreeCohortRegistrationProxy<C> cohortProxy =
196                 new DataTreeCohortRegistrationProxy<>(actorContext, subtree, cohort);
197         cohortProxy.init(shardName);
198         return cohortProxy;
199     }
200
201     @Override
202     public DOMStoreTransactionChain createTransactionChain() {
203         return txContextFactory.createTransactionChain();
204     }
205
206     @Override
207     public DOMStoreReadTransaction newReadOnlyTransaction() {
208        return new TransactionProxy(txContextFactory, TransactionType.READ_ONLY);
209     }
210
211     @Override
212     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
213         actorContext.acquireTxCreationPermit();
214         return new TransactionProxy(txContextFactory, TransactionType.WRITE_ONLY);
215     }
216
217     @Override
218     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
219         actorContext.acquireTxCreationPermit();
220         return new TransactionProxy(txContextFactory, TransactionType.READ_WRITE);
221     }
222
223     @Override
224     public void onGlobalContextUpdated(final SchemaContext schemaContext) {
225         actorContext.setSchemaContext(schemaContext);
226     }
227
228     @Override
229     public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
230         LOG.info("DatastoreContext updated for data store {}", actorContext.getDataStoreName());
231
232         actorContext.setDatastoreContext(contextFactory);
233         datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
234     }
235
236     @Override
237     public void close() {
238         LOG.info("Closing data store {}", identifier);
239
240         if (datastoreConfigMXBean != null) {
241             datastoreConfigMXBean.unregisterMBean();
242         }
243         if (datastoreInfoMXBean != null) {
244             datastoreInfoMXBean.unregisterMBean();
245         }
246
247         if (closeable != null) {
248             try {
249                 closeable.close();
250             } catch (Exception e) {
251                 LOG.debug("Error closing instance", e);
252             }
253         }
254
255         txContextFactory.close();
256         actorContext.shutdown();
257
258         if (client != null) {
259             client.close();
260         }
261     }
262
263     @Override
264     public ActorContext getActorContext() {
265         return actorContext;
266     }
267
268     public void waitTillReady(){
269         LOG.info("Beginning to wait for data store to become ready : {}", identifier);
270
271         try {
272             if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
273                 LOG.debug("Data store {} is now ready", identifier);
274             } else {
275                 LOG.error("Shared leaders failed to settle in {} seconds, giving up", TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
276             }
277         } catch (InterruptedException e) {
278             LOG.error("Interrupted while waiting for shards to settle", e);
279         }
280     }
281
282     private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
283             final String shardDispatcher, final String shardManagerId) {
284         Exception lastException = null;
285
286         for(int i=0;i<100;i++) {
287             try {
288                 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher).withMailbox(
289                         ActorContext.BOUNDED_MAILBOX), shardManagerId);
290             } catch (Exception e){
291                 lastException = e;
292                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
293                 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying (retry count = {})",
294                     shardManagerId, e.getMessage(), i);
295             }
296         }
297
298         throw new IllegalStateException("Failed to create Shard Manager", lastException);
299     }
300
301     @VisibleForTesting
302     public CountDownLatch getWaitTillReadyCountDownLatch() {
303         return waitTillReadyCountDownLatch;
304     }
305 }