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

©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.