03b403a13c9f446d0b915d76e1eb46957a85ccfb
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / AbstractDataStore.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.DataStoreClient;
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.persisted.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.ClusterUtils;
32 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
33 import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
34 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
35 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
36 import org.opendaylight.controller.md.sal.dom.api.ClusteredDOMDataTreeChangeListener;
37 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
38 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTreeChangePublisher;
39 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
40 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
41 import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
42 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
43 import org.opendaylight.yangtools.concepts.ListenerRegistration;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Base implementation of a distributed DOMStore.
53  */
54 public abstract class AbstractDataStore implements DistributedDataStoreInterface, SchemaContextListener,
55         DatastoreContextConfigAdminOverlay.Listener, DOMStoreTreeChangePublisher,
56         DOMDataTreeCommitCohortRegistry, AutoCloseable {
57
58     private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
59
60     private static final long READY_WAIT_FACTOR = 3;
61
62     private final ActorContext actorContext;
63     private final long waitTillReadyTimeInMillis;
64
65     private AutoCloseable closeable;
66
67     private DatastoreConfigurationMXBeanImpl datastoreConfigMXBean;
68
69     private DatastoreInfoMXBeanImpl datastoreInfoMXBean;
70
71     private final CountDownLatch waitTillReadyCountDownLatch = new CountDownLatch(1);
72
73     private final ClientIdentifier identifier;
74     private final DataStoreClient client;
75
76     @SuppressWarnings("checkstyle:IllegalCatch")
77     protected AbstractDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
78             final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
79             final DatastoreSnapshot restoreFromSnapshot) {
80         Preconditions.checkNotNull(actorSystem, "actorSystem should not be null");
81         Preconditions.checkNotNull(cluster, "cluster should not be null");
82         Preconditions.checkNotNull(configuration, "configuration should not be null");
83         Preconditions.checkNotNull(datastoreContextFactory, "datastoreContextFactory should not be null");
84
85         String shardManagerId = ShardManagerIdentifier.builder()
86                 .type(datastoreContextFactory.getBaseDatastoreContext().getDataStoreName()).build().toString();
87
88         LOG.info("Creating ShardManager : {}", shardManagerId);
89
90         String shardDispatcher =
91                 new Dispatchers(actorSystem.dispatchers()).getDispatcherPath(Dispatchers.DispatcherType.Shard);
92
93         PrimaryShardInfoFutureCache primaryShardInfoCache = new PrimaryShardInfoFutureCache();
94
95         ShardManagerCreator creator = new ShardManagerCreator().cluster(cluster).configuration(configuration)
96                 .datastoreContextFactory(datastoreContextFactory)
97                 .waitTillReadyCountDownLatch(waitTillReadyCountDownLatch)
98                 .primaryShardInfoCache(primaryShardInfoCache)
99                 .restoreFromSnapshot(restoreFromSnapshot)
100                 .distributedDataStore(this);
101
102         actorContext = new ActorContext(actorSystem, createShardManager(actorSystem, creator, shardDispatcher,
103                 shardManagerId), cluster, configuration, datastoreContextFactory.getBaseDatastoreContext(),
104                 primaryShardInfoCache);
105
106         final Props clientProps = DistributedDataStoreClientActor.props(cluster.getCurrentMemberName(),
107             datastoreContextFactory.getBaseDatastoreContext().getDataStoreName(), actorContext);
108         final ActorRef clientActor = actorSystem.actorOf(clientProps);
109         try {
110             client = DistributedDataStoreClientActor.getDistributedDataStoreClient(clientActor, 30, TimeUnit.SECONDS);
111         } catch (Exception e) {
112             LOG.error("Failed to get actor for {}", clientProps, e);
113             clientActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
114             throw Throwables.propagate(e);
115         }
116
117         identifier = client.getIdentifier();
118         LOG.debug("Distributed data store client {} started", identifier);
119
120         this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
121                 .duration().toMillis() * READY_WAIT_FACTOR;
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     protected AbstractDataStore(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.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
139                 .duration().toMillis() * READY_WAIT_FACTOR;
140     }
141
142     @VisibleForTesting
143     protected AbstractDataStore(final ActorContext actorContext, final ClientIdentifier identifier,
144                                 final DataStoreClient clientActor) {
145         this.actorContext = Preconditions.checkNotNull(actorContext, "actorContext should not be null");
146         this.client = clientActor;
147         this.identifier = Preconditions.checkNotNull(identifier);
148         this.waitTillReadyTimeInMillis = actorContext.getDatastoreContext().getShardLeaderElectionTimeout()
149                 .duration().toMillis() * READY_WAIT_FACTOR;
150     }
151
152     protected final DataStoreClient getClient() {
153         return client;
154     }
155
156     final ClientIdentifier getIdentifier() {
157         return identifier;
158     }
159
160     public void setCloseable(final AutoCloseable closeable) {
161         this.closeable = closeable;
162     }
163
164     @SuppressWarnings("unchecked")
165     @Override
166     public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
167                                               ListenerRegistration<L> registerChangeListener(
168         final YangInstanceIdentifier path, final L listener,
169         final AsyncDataBroker.DataChangeScope scope) {
170
171         Preconditions.checkNotNull(path, "path should not be null");
172         Preconditions.checkNotNull(listener, "listener should not be null");
173
174         LOG.debug("Registering listener: {} for path: {} scope: {}", listener, path, scope);
175
176         String shardName = actorContext.getShardStrategyFactory().getStrategy(path).findShard(path);
177
178         final DataChangeListenerRegistrationProxy listenerRegistrationProxy =
179                 new DataChangeListenerRegistrationProxy(shardName, actorContext, listener);
180         listenerRegistrationProxy.init(path, scope);
181
182         return listenerRegistrationProxy;
183     }
184
185     @Override
186     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
187             final YangInstanceIdentifier treeId, final L listener) {
188         Preconditions.checkNotNull(treeId, "treeId should not be null");
189         Preconditions.checkNotNull(listener, "listener should not be null");
190
191         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
192         LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
193
194         final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
195                 new DataTreeChangeListenerProxy<>(actorContext, listener, treeId);
196         listenerRegistrationProxy.init(shardName);
197
198         return listenerRegistrationProxy;
199     }
200
201
202     @Override
203     public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
204             final DOMDataTreeIdentifier subtree, final C cohort) {
205         YangInstanceIdentifier treeId =
206                 Preconditions.checkNotNull(subtree, "subtree should not be null").getRootIdentifier();
207         Preconditions.checkNotNull(cohort, "listener should not be null");
208
209
210         final String shardName = actorContext.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
211         LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
212
213         DataTreeCohortRegistrationProxy<C> cohortProxy =
214                 new DataTreeCohortRegistrationProxy<>(actorContext, subtree, cohort);
215         cohortProxy.init(shardName);
216         return cohortProxy;
217     }
218
219     @Override
220     public void onGlobalContextUpdated(final SchemaContext schemaContext) {
221         actorContext.setSchemaContext(schemaContext);
222     }
223
224     @Override
225     public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
226         LOG.info("DatastoreContext updated for data store {}", actorContext.getDataStoreName());
227
228         actorContext.setDatastoreContext(contextFactory);
229         datastoreConfigMXBean.setContext(contextFactory.getBaseDatastoreContext());
230     }
231
232     @Override
233     @SuppressWarnings("checkstyle:IllegalCatch")
234     public void close() {
235         LOG.info("Closing data store {}", identifier);
236
237         if (datastoreConfigMXBean != null) {
238             datastoreConfigMXBean.unregisterMBean();
239         }
240         if (datastoreInfoMXBean != null) {
241             datastoreInfoMXBean.unregisterMBean();
242         }
243
244         if (closeable != null) {
245             try {
246                 closeable.close();
247             } catch (Exception e) {
248                 LOG.debug("Error closing instance", e);
249             }
250         }
251
252         actorContext.shutdown();
253
254         if (client != null) {
255             client.close();
256         }
257     }
258
259     @Override
260     public ActorContext getActorContext() {
261         return actorContext;
262     }
263
264     public void waitTillReady() {
265         LOG.info("Beginning to wait for data store to become ready : {}", identifier);
266
267         try {
268             if (waitTillReadyCountDownLatch.await(waitTillReadyTimeInMillis, TimeUnit.MILLISECONDS)) {
269                 LOG.debug("Data store {} is now ready", identifier);
270             } else {
271                 LOG.error("Shard leaders failed to settle in {} seconds, giving up",
272                         TimeUnit.MILLISECONDS.toSeconds(waitTillReadyTimeInMillis));
273             }
274         } catch (InterruptedException e) {
275             LOG.error("Interrupted while waiting for shards to settle", e);
276         }
277     }
278
279     @SuppressWarnings("checkstyle:IllegalCatch")
280     private static ActorRef createShardManager(final ActorSystem actorSystem, final ShardManagerCreator creator,
281             final String shardDispatcher, final String shardManagerId) {
282         Exception lastException = null;
283
284         for (int i = 0; i < 100; i++) {
285             try {
286                 return actorSystem.actorOf(creator.props().withDispatcher(shardDispatcher).withMailbox(
287                         ActorContext.BOUNDED_MAILBOX), shardManagerId);
288             } catch (Exception e) {
289                 lastException = e;
290                 Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
291                 LOG.debug("Could not create actor {} because of {} - waiting for sometime before retrying "
292                         + "(retry count = {})", shardManagerId, e.getMessage(), i);
293             }
294         }
295
296         throw new IllegalStateException("Failed to create Shard Manager", lastException);
297     }
298
299     @VisibleForTesting
300     public CountDownLatch getWaitTillReadyCountDownLatch() {
301         return waitTillReadyCountDownLatch;
302     }
303
304     @SuppressWarnings("unchecked")
305     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
306             final YangInstanceIdentifier shardLookup,
307             final YangInstanceIdentifier insideShard,
308             final org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener delegate) {
309
310         Preconditions.checkNotNull(shardLookup, "shardLookup should not be null");
311         Preconditions.checkNotNull(insideShard, "insideShard should not be null");
312         Preconditions.checkNotNull(delegate, "delegate should not be null");
313
314         final String shardName = actorContext.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
315         LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
316                 delegate,shardLookup, shardName, insideShard);
317
318         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
319                 new DataTreeChangeListenerProxy<>(actorContext,
320                         // wrap this in the ClusteredDOMDataTreeChangeLister interface
321                         // since we always want clustered registration
322                         (ClusteredDOMDataTreeChangeListener) delegate::onDataTreeChanged, insideShard);
323         listenerRegistrationProxy.init(shardName);
324
325         return (ListenerRegistration<L>) listenerRegistrationProxy;
326     }
327
328     @SuppressWarnings("unchecked")
329     public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerShardConfigListener(
330             final YangInstanceIdentifier internalPath,
331             final DOMDataTreeChangeListener delegate) {
332         Preconditions.checkNotNull(delegate, "delegate should not be null");
333
334         LOG.debug("Registering a listener for the configuration shard: {}", internalPath);
335
336         final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy =
337                 new DataTreeChangeListenerProxy<>(actorContext, delegate, internalPath);
338         proxy.init(ClusterUtils.PREFIX_CONFIG_SHARD_ID);
339
340         return (ListenerRegistration<L>) proxy;
341     }
342
343 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.