2 * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.blueprint.ext;
10 import com.google.common.base.Optional;
11 import com.google.common.util.concurrent.CheckedFuture;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
15 import java.util.Collection;
16 import java.util.Objects;
17 import java.util.concurrent.atomic.AtomicBoolean;
18 import javax.annotation.Nonnull;
19 import javax.annotation.Nullable;
20 import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
21 import org.opendaylight.controller.blueprint.ext.DataStoreAppConfigDefaultXMLReader.ConfigURLProvider;
22 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
23 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
24 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
25 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType;
26 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
27 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
28 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
30 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
31 import org.opendaylight.controller.sal.core.api.model.SchemaService;
32 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
33 import org.opendaylight.yangtools.concepts.ListenerRegistration;
34 import org.opendaylight.yangtools.yang.binding.DataObject;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
37 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
38 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.osgi.service.blueprint.container.ComponentDefinitionException;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Element;
46 * Factory metadata corresponding to the "clustered-app-config" element that obtains an application's
47 * config data from the data store and provides the binding DataObject instance to the Blueprint container
48 * as a bean. In addition registers a DataTreeChangeListener to restart the Blueprint container when the
49 * config data is changed.
51 * @author Thomas Pantelis
53 public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactoryMetadata {
54 private static final Logger LOG = LoggerFactory.getLogger(DataStoreAppConfigMetadata.class);
56 static final String BINDING_CLASS = "binding-class";
57 static final String DEFAULT_CONFIG = "default-config";
58 static final String DEFAULT_CONFIG_FILE_NAME = "default-config-file-name";
59 static final String LIST_KEY_VALUE = "list-key-value";
61 private static final String DEFAULT_APP_CONFIG_FILE_PATH = "etc" + File.separator + "opendaylight" + File.separator
62 + "datastore" + File.separator + "initial" + File.separator + "config";
64 private final Element defaultAppConfigElement;
65 private final String defaultAppConfigFileName;
66 private final String appConfigBindingClassName;
67 private final String appConfigListKeyValue;
68 private final UpdateStrategy appConfigUpdateStrategy;
69 private final AtomicBoolean readingInitialAppConfig = new AtomicBoolean(true);
71 private volatile BindingContext bindingContext;
72 private volatile ListenerRegistration<?> appConfigChangeListenerReg;
73 private volatile DataObject currentAppConfig;
75 // Note: the BindingNormalizedNodeSerializer interface is annotated as deprecated because there's an
76 // equivalent interface in the mdsal project but the corresponding binding classes in the controller
77 // project are still used - conversion to the mdsal binding classes hasn't occurred yet.
78 private volatile BindingNormalizedNodeSerializer bindingSerializer;
80 public DataStoreAppConfigMetadata(@Nonnull final String id, @Nonnull final String appConfigBindingClassName,
81 @Nullable final String appConfigListKeyValue, @Nullable final String defaultAppConfigFileName,
82 @Nonnull final UpdateStrategy updateStrategyValue, @Nullable final Element defaultAppConfigElement) {
84 this.defaultAppConfigElement = defaultAppConfigElement;
85 this.defaultAppConfigFileName = defaultAppConfigFileName;
86 this.appConfigBindingClassName = appConfigBindingClassName;
87 this.appConfigListKeyValue = appConfigListKeyValue;
88 this.appConfigUpdateStrategy = updateStrategyValue;
92 @SuppressWarnings("unchecked")
93 public void init(final ExtendedBlueprintContainer container) {
94 super.init(container);
96 Class<DataObject> appConfigBindingClass;
98 Class<?> bindingClass = container.getBundleContext().getBundle().loadClass(appConfigBindingClassName);
99 if (!DataObject.class.isAssignableFrom(bindingClass)) {
100 throw new ComponentDefinitionException(String.format(
101 "%s: Specified app config binding class %s does not extend %s",
102 logName(), appConfigBindingClassName, DataObject.class.getName()));
105 appConfigBindingClass = (Class<DataObject>) bindingClass;
106 } catch (final ClassNotFoundException e) {
107 throw new ComponentDefinitionException(String.format("%s: Error loading app config binding class %s",
108 logName(), appConfigBindingClassName), e);
111 bindingContext = BindingContext.create(logName(), appConfigBindingClass, appConfigListKeyValue);
115 public Object create() throws ComponentDefinitionException {
116 LOG.debug("{}: In create - currentAppConfig: {}", logName(), currentAppConfig);
120 return currentAppConfig;
124 protected void startTracking() {
125 // First get the BindingNormalizedNodeSerializer OSGi service. This will be used to create a default
126 // instance of the app config binding class, if necessary.
128 retrieveService("binding-codec", BindingNormalizedNodeSerializer.class, service -> {
129 bindingSerializer = (BindingNormalizedNodeSerializer)service;
130 retrieveDataBrokerService();
134 private void retrieveDataBrokerService() {
135 LOG.debug("{}: In retrieveDataBrokerService", logName());
136 // Get the binding DataBroker OSGi service.
137 retrieveService("data-broker", DataBroker.class, service -> retrieveInitialAppConfig((DataBroker)service));
140 private void retrieveInitialAppConfig(final DataBroker dataBroker) {
141 LOG.debug("{}: Got DataBroker instance - reading app config {}", logName(), bindingContext.appConfigPath);
143 setDependencyDesc("Initial app config " + bindingContext.appConfigBindingClass.getSimpleName());
145 // We register a DTCL to get updates and also read the app config data from the data store. If
146 // the app config data is present then both the read and initial DTCN update will return it. If the
147 // the data isn't present, we won't get an initial DTCN update so the read will indicate the data
150 DataTreeIdentifier<DataObject> dataTreeId = new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
151 bindingContext.appConfigPath);
152 appConfigChangeListenerReg = dataBroker.registerDataTreeChangeListener(dataTreeId,
153 (ClusteredDataTreeChangeListener<DataObject>) this::onAppConfigChanged);
155 readInitialAppConfig(dataBroker);
158 private void readInitialAppConfig(final DataBroker dataBroker) {
159 @SuppressWarnings("resource") // it's closed in the callback
160 final ReadOnlyTransaction readOnlyTx = dataBroker.newReadOnlyTransaction();
161 CheckedFuture<Optional<DataObject>, ReadFailedException> future = readOnlyTx.read(
162 LogicalDatastoreType.CONFIGURATION, bindingContext.appConfigPath);
163 Futures.addCallback(future, new FutureCallback<Optional<DataObject>>() {
165 public void onSuccess(final Optional<DataObject> possibleAppConfig) {
166 LOG.debug("{}: Read of app config {} succeeded: {}", logName(), bindingContext
167 .appConfigBindingClass.getName(), possibleAppConfig);
170 setInitialAppConfig(possibleAppConfig);
174 public void onFailure(final Throwable failure) {
177 // We may have gotten the app config via the data tree change listener so only retry if not.
178 if (readingInitialAppConfig.get()) {
179 LOG.warn("{}: Read of app config {} failed - retrying", logName(),
180 bindingContext.appConfigBindingClass.getName(), failure);
182 readInitialAppConfig(dataBroker);
188 private void onAppConfigChanged(final Collection<DataTreeModification<DataObject>> changes) {
189 for (DataTreeModification<DataObject> change: changes) {
190 DataObjectModification<DataObject> changeRoot = change.getRootNode();
191 ModificationType type = changeRoot.getModificationType();
193 LOG.debug("{}: onAppConfigChanged: {}, {}", logName(), type, change.getRootPath());
195 if (type == ModificationType.SUBTREE_MODIFIED || type == ModificationType.WRITE) {
196 DataObject newAppConfig = changeRoot.getDataAfter();
198 LOG.debug("New app config instance: {}, previous: {}", newAppConfig, currentAppConfig);
200 if (!setInitialAppConfig(Optional.of(newAppConfig))
201 && !Objects.equals(currentAppConfig, newAppConfig)) {
202 LOG.debug("App config was updated");
204 if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
208 } else if (type == ModificationType.DELETE) {
209 LOG.debug("App config was deleted");
211 if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
218 private boolean setInitialAppConfig(final Optional<DataObject> possibleAppConfig) {
219 boolean result = readingInitialAppConfig.compareAndSet(true, false);
221 DataObject localAppConfig;
222 if (possibleAppConfig.isPresent()) {
223 localAppConfig = possibleAppConfig.get();
225 // No app config data is present so create an empty instance via the bindingSerializer service.
226 // This will also return default values for leafs that haven't been explicitly set.
227 localAppConfig = createDefaultInstance();
230 LOG.debug("{}: Setting currentAppConfig instance: {}", logName(), localAppConfig);
232 // Now publish the app config instance to the volatile field and notify the callback to let the
233 // container know our dependency is now satisfied.
234 currentAppConfig = localAppConfig;
241 private DataObject createDefaultInstance() {
243 @SuppressWarnings("resource")
244 ConfigURLProvider inputStreamProvider = appConfigFileName -> {
245 File appConfigFile = new File(DEFAULT_APP_CONFIG_FILE_PATH, appConfigFileName);
246 LOG.debug("{}: parsePossibleDefaultAppConfigXMLFile looking for file {}", logName(),
247 appConfigFile.getAbsolutePath());
249 if (!appConfigFile.exists()) {
250 return Optional.absent();
253 LOG.debug("{}: Found file {}", logName(), appConfigFile.getAbsolutePath());
255 return Optional.of(appConfigFile.toURI().toURL());
258 DataStoreAppConfigDefaultXMLReader<?> reader = new DataStoreAppConfigDefaultXMLReader(logName(),
259 defaultAppConfigFileName, getOSGiService(SchemaService.class), bindingSerializer, bindingContext,
260 inputStreamProvider);
261 return reader.createDefaultInstance((schemaContext, dataSchema) -> {
262 // Fallback if file cannot be read, try XML from Config
263 NormalizedNode<?, ?> dataNode = parsePossibleDefaultAppConfigElement(schemaContext, dataSchema);
264 if (dataNode == null) {
265 // or, as last resort, defaults from the model
266 return bindingContext.newDefaultNode(dataSchema);
272 } catch (final ConfigXMLReaderException e) {
273 if (e.getCause() == null) {
274 setFailureMessage(e.getMessage());
276 setFailure(e.getMessage(), e);
283 private NormalizedNode<?, ?> parsePossibleDefaultAppConfigElement(final SchemaContext schemaContext,
284 final DataSchemaNode dataSchema) {
285 if (defaultAppConfigElement == null) {
289 LOG.debug("{}: parsePossibleDefaultAppConfigElement for {}", logName(), bindingContext.bindingQName);
291 DomToNormalizedNodeParserFactory parserFactory = DomToNormalizedNodeParserFactory.getInstance(
292 XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext);
295 LOG.debug("{}: Got app config schema: {}", logName(), dataSchema);
297 NormalizedNode<?, ?> dataNode = bindingContext.parseDataElement(defaultAppConfigElement, dataSchema,
300 LOG.debug("{}: Parsed data node: {}", logName(), dataNode);
306 public void destroy(final Object instance) {
307 super.destroy(instance);
309 if (appConfigChangeListenerReg != null) {
310 appConfigChangeListenerReg.close();
311 appConfigChangeListenerReg = null;