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 (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 final ReadOnlyTransaction readOnlyTx = dataBroker.newReadOnlyTransaction();
160 CheckedFuture<Optional<DataObject>, ReadFailedException> future = readOnlyTx.read(
161 LogicalDatastoreType.CONFIGURATION, bindingContext.appConfigPath);
162 Futures.addCallback(future, new FutureCallback<Optional<DataObject>>() {
164 public void onSuccess(final Optional<DataObject> possibleAppConfig) {
165 LOG.debug("{}: Read of app config {} succeeded: {}", logName(), bindingContext
166 .appConfigBindingClass.getName(), possibleAppConfig);
169 setInitialAppConfig(possibleAppConfig);
173 public void onFailure(final Throwable failure) {
176 // We may have gotten the app config via the data tree change listener so only retry if not.
177 if (readingInitialAppConfig.get()) {
178 LOG.warn("{}: Read of app config {} failed - retrying", logName(),
179 bindingContext.appConfigBindingClass.getName(), failure);
181 readInitialAppConfig(dataBroker);
187 private void onAppConfigChanged(final Collection<DataTreeModification<DataObject>> changes) {
188 for (DataTreeModification<DataObject> change: changes) {
189 DataObjectModification<DataObject> changeRoot = change.getRootNode();
190 ModificationType type = changeRoot.getModificationType();
192 LOG.debug("{}: onAppConfigChanged: {}, {}", logName(), type, change.getRootPath());
194 if (type == ModificationType.SUBTREE_MODIFIED || type == ModificationType.WRITE) {
195 DataObject newAppConfig = changeRoot.getDataAfter();
197 LOG.debug("New app config instance: {}, previous: {}", newAppConfig, currentAppConfig);
199 if (!setInitialAppConfig(Optional.of(newAppConfig))
200 && !Objects.equals(currentAppConfig, newAppConfig)) {
201 LOG.debug("App config was updated");
203 if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
207 } else if (type == ModificationType.DELETE) {
208 LOG.debug("App config was deleted");
210 if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
217 private boolean setInitialAppConfig(final Optional<DataObject> possibleAppConfig) {
218 boolean result = readingInitialAppConfig.compareAndSet(true, false);
220 DataObject localAppConfig;
221 if (possibleAppConfig.isPresent()) {
222 localAppConfig = possibleAppConfig.get();
224 // No app config data is present so create an empty instance via the bindingSerializer service.
225 // This will also return default values for leafs that haven't been explicitly set.
226 localAppConfig = createDefaultInstance();
229 LOG.debug("{}: Setting currentAppConfig instance: {}", logName(), localAppConfig);
231 // Now publish the app config instance to the volatile field and notify the callback to let the
232 // container know our dependency is now satisfied.
233 currentAppConfig = localAppConfig;
240 private DataObject createDefaultInstance() {
242 @SuppressWarnings("resource")
243 ConfigURLProvider inputStreamProvider = appConfigFileName -> {
244 File appConfigFile = new File(DEFAULT_APP_CONFIG_FILE_PATH, appConfigFileName);
245 LOG.debug("{}: parsePossibleDefaultAppConfigXMLFile looking for file {}", logName(),
246 appConfigFile.getAbsolutePath());
248 if (!appConfigFile.exists()) {
249 return Optional.absent();
252 LOG.debug("{}: Found file {}", logName(), appConfigFile.getAbsolutePath());
254 return Optional.of(appConfigFile.toURI().toURL());
257 DataStoreAppConfigDefaultXMLReader<?> reader = new DataStoreAppConfigDefaultXMLReader(logName(),
258 defaultAppConfigFileName, getOSGiService(SchemaService.class), bindingSerializer, bindingContext,
259 inputStreamProvider);
260 return reader.createDefaultInstance((schemaContext, dataSchema) -> {
261 // Fallback if file cannot be read, try XML from Config
262 NormalizedNode<?, ?> dataNode = parsePossibleDefaultAppConfigElement(schemaContext, dataSchema);
263 if (dataNode == null) {
264 // or, as last resort, defaults from the model
265 return bindingContext.newDefaultNode(dataSchema);
271 } catch (ConfigXMLReaderException e) {
272 if (e.getCause() == null) {
273 setFailureMessage(e.getMessage());
275 setFailure(e.getMessage(), e);
282 private NormalizedNode<?, ?> parsePossibleDefaultAppConfigElement(final SchemaContext schemaContext,
283 final DataSchemaNode dataSchema) {
284 if (defaultAppConfigElement == null) {
288 LOG.debug("{}: parsePossibleDefaultAppConfigElement for {}", logName(), bindingContext.bindingQName);
290 DomToNormalizedNodeParserFactory parserFactory = DomToNormalizedNodeParserFactory.getInstance(
291 XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext);
294 LOG.debug("{}: Got app config schema: {}", logName(), dataSchema);
296 NormalizedNode<?, ?> dataNode = bindingContext.parseDataElement(defaultAppConfigElement, dataSchema,
299 LOG.debug("{}: Parsed data node: {}", logName(), dataNode);
305 public void destroy(final Object instance) {
306 super.destroy(instance);
308 if (appConfigChangeListenerReg != null) {
309 appConfigChangeListenerReg.close();
310 appConfigChangeListenerReg = null;