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.FutureCallback;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.MoreExecutors;
16 import java.io.IOException;
17 import java.net.URISyntaxException;
18 import java.util.Collection;
19 import java.util.Objects;
20 import java.util.concurrent.atomic.AtomicBoolean;
21 import javax.annotation.Nonnull;
22 import javax.annotation.Nullable;
23 import javax.xml.parsers.ParserConfigurationException;
24 import javax.xml.stream.XMLStreamException;
25 import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
26 import org.opendaylight.controller.blueprint.ext.DataStoreAppConfigDefaultXMLReader.ConfigURLProvider;
27 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
28 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
29 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
30 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType;
31 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
32 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
33 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
34 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
35 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
36 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
37 import org.opendaylight.yangtools.concepts.ListenerRegistration;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.osgi.service.blueprint.container.ComponentDefinitionException;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Element;
46 import org.xml.sax.SAXException;
49 * Factory metadata corresponding to the "clustered-app-config" element that obtains an application's
50 * config data from the data store and provides the binding DataObject instance to the Blueprint container
51 * as a bean. In addition registers a DataTreeChangeListener to restart the Blueprint container when the
52 * config data is changed.
54 * @author Thomas Pantelis
56 public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactoryMetadata {
57 private static final Logger LOG = LoggerFactory.getLogger(DataStoreAppConfigMetadata.class);
59 static final String BINDING_CLASS = "binding-class";
60 static final String DEFAULT_CONFIG = "default-config";
61 static final String DEFAULT_CONFIG_FILE_NAME = "default-config-file-name";
62 static final String LIST_KEY_VALUE = "list-key-value";
64 private static final String DEFAULT_APP_CONFIG_FILE_PATH = "etc" + File.separator + "opendaylight" + File.separator
65 + "datastore" + File.separator + "initial" + File.separator + "config";
67 private final Element defaultAppConfigElement;
68 private final String defaultAppConfigFileName;
69 private final String appConfigBindingClassName;
70 private final String appConfigListKeyValue;
71 private final UpdateStrategy appConfigUpdateStrategy;
72 private final AtomicBoolean readingInitialAppConfig = new AtomicBoolean(true);
74 private volatile BindingContext bindingContext;
75 private volatile ListenerRegistration<?> appConfigChangeListenerReg;
76 private volatile DataObject currentAppConfig;
78 // Note: the BindingNormalizedNodeSerializer interface is annotated as deprecated because there's an
79 // equivalent interface in the mdsal project but the corresponding binding classes in the controller
80 // project are still used - conversion to the mdsal binding classes hasn't occurred yet.
81 private volatile BindingNormalizedNodeSerializer bindingSerializer;
83 public DataStoreAppConfigMetadata(@Nonnull final String id, @Nonnull final String appConfigBindingClassName,
84 @Nullable final String appConfigListKeyValue, @Nullable final String defaultAppConfigFileName,
85 @Nonnull final UpdateStrategy updateStrategyValue, @Nullable final Element defaultAppConfigElement) {
87 this.defaultAppConfigElement = defaultAppConfigElement;
88 this.defaultAppConfigFileName = defaultAppConfigFileName;
89 this.appConfigBindingClassName = appConfigBindingClassName;
90 this.appConfigListKeyValue = appConfigListKeyValue;
91 this.appConfigUpdateStrategy = updateStrategyValue;
95 @SuppressWarnings("unchecked")
96 public void init(final ExtendedBlueprintContainer container) {
97 super.init(container);
99 Class<DataObject> appConfigBindingClass;
101 Class<?> bindingClass = container.getBundleContext().getBundle().loadClass(appConfigBindingClassName);
102 if (!DataObject.class.isAssignableFrom(bindingClass)) {
103 throw new ComponentDefinitionException(String.format(
104 "%s: Specified app config binding class %s does not extend %s",
105 logName(), appConfigBindingClassName, DataObject.class.getName()));
108 appConfigBindingClass = (Class<DataObject>) bindingClass;
109 } catch (final ClassNotFoundException e) {
110 throw new ComponentDefinitionException(String.format("%s: Error loading app config binding class %s",
111 logName(), appConfigBindingClassName), e);
114 bindingContext = BindingContext.create(logName(), appConfigBindingClass, appConfigListKeyValue);
118 public Object create() throws ComponentDefinitionException {
119 LOG.debug("{}: In create - currentAppConfig: {}", logName(), currentAppConfig);
123 return currentAppConfig;
127 protected void startTracking() {
128 // First get the BindingNormalizedNodeSerializer OSGi service. This will be used to create a default
129 // instance of the app config binding class, if necessary.
131 retrieveService("binding-codec", BindingNormalizedNodeSerializer.class, service -> {
132 bindingSerializer = (BindingNormalizedNodeSerializer)service;
133 retrieveDataBrokerService();
137 private void retrieveDataBrokerService() {
138 LOG.debug("{}: In retrieveDataBrokerService", logName());
139 // Get the binding DataBroker OSGi service.
140 retrieveService("data-broker", DataBroker.class, service -> retrieveInitialAppConfig((DataBroker)service));
143 private void retrieveInitialAppConfig(final DataBroker dataBroker) {
144 LOG.debug("{}: Got DataBroker instance - reading app config {}", logName(), bindingContext.appConfigPath);
146 setDependencyDesc("Initial app config " + bindingContext.appConfigBindingClass.getSimpleName());
148 // We register a DTCL to get updates and also read the app config data from the data store. If
149 // the app config data is present then both the read and initial DTCN update will return it. If the
150 // the data isn't present, we won't get an initial DTCN update so the read will indicate the data
153 DataTreeIdentifier<DataObject> dataTreeId = new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
154 bindingContext.appConfigPath);
155 appConfigChangeListenerReg = dataBroker.registerDataTreeChangeListener(dataTreeId,
156 (ClusteredDataTreeChangeListener<DataObject>) this::onAppConfigChanged);
158 readInitialAppConfig(dataBroker);
161 private void readInitialAppConfig(final DataBroker dataBroker) {
162 final ReadOnlyTransaction readOnlyTx = dataBroker.newReadOnlyTransaction();
163 ListenableFuture<Optional<DataObject>> future = readOnlyTx.read(
164 LogicalDatastoreType.CONFIGURATION, bindingContext.appConfigPath);
165 Futures.addCallback(future, new FutureCallback<Optional<DataObject>>() {
167 public void onSuccess(final Optional<DataObject> possibleAppConfig) {
168 LOG.debug("{}: Read of app config {} succeeded: {}", logName(), bindingContext
169 .appConfigBindingClass.getName(), possibleAppConfig);
172 setInitialAppConfig(possibleAppConfig);
176 public void onFailure(final Throwable failure) {
179 // We may have gotten the app config via the data tree change listener so only retry if not.
180 if (readingInitialAppConfig.get()) {
181 LOG.warn("{}: Read of app config {} failed - retrying", logName(),
182 bindingContext.appConfigBindingClass.getName(), failure);
184 readInitialAppConfig(dataBroker);
187 }, MoreExecutors.directExecutor());
190 private void onAppConfigChanged(final Collection<DataTreeModification<DataObject>> changes) {
191 for (DataTreeModification<DataObject> change: changes) {
192 DataObjectModification<DataObject> changeRoot = change.getRootNode();
193 ModificationType type = changeRoot.getModificationType();
195 LOG.debug("{}: onAppConfigChanged: {}, {}", logName(), type, change.getRootPath());
197 if (type == ModificationType.SUBTREE_MODIFIED || type == ModificationType.WRITE) {
198 DataObject newAppConfig = changeRoot.getDataAfter();
200 LOG.debug("New app config instance: {}, previous: {}", newAppConfig, currentAppConfig);
202 if (!setInitialAppConfig(Optional.of(newAppConfig))
203 && !Objects.equals(currentAppConfig, newAppConfig)) {
204 LOG.debug("App config was updated");
206 if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
210 } else if (type == ModificationType.DELETE) {
211 LOG.debug("App config was deleted");
213 if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
220 private boolean setInitialAppConfig(final Optional<DataObject> possibleAppConfig) {
221 boolean result = readingInitialAppConfig.compareAndSet(true, false);
223 DataObject localAppConfig;
224 if (possibleAppConfig.isPresent()) {
225 localAppConfig = possibleAppConfig.get();
227 // No app config data is present so create an empty instance via the bindingSerializer service.
228 // This will also return default values for leafs that haven't been explicitly set.
229 localAppConfig = createDefaultInstance();
232 LOG.debug("{}: Setting currentAppConfig instance: {}", logName(), localAppConfig);
234 // Now publish the app config instance to the volatile field and notify the callback to let the
235 // container know our dependency is now satisfied.
236 currentAppConfig = localAppConfig;
243 private DataObject createDefaultInstance() {
245 ConfigURLProvider inputStreamProvider = appConfigFileName -> {
246 File appConfigFile = new File(DEFAULT_APP_CONFIG_FILE_PATH, appConfigFileName);
247 LOG.debug("{}: parsePossibleDefaultAppConfigXMLFile looking for file {}", logName(),
248 appConfigFile.getAbsolutePath());
250 if (!appConfigFile.exists()) {
251 return Optional.absent();
254 LOG.debug("{}: Found file {}", logName(), appConfigFile.getAbsolutePath());
256 return Optional.of(appConfigFile.toURI().toURL());
259 DataStoreAppConfigDefaultXMLReader<?> reader = new DataStoreAppConfigDefaultXMLReader<>(logName(),
260 defaultAppConfigFileName, getOSGiService(DOMSchemaService.class), bindingSerializer, bindingContext,
261 inputStreamProvider);
262 return reader.createDefaultInstance((schemaContext, dataSchema) -> {
263 // Fallback if file cannot be read, try XML from Config
264 NormalizedNode<?, ?> dataNode = parsePossibleDefaultAppConfigElement(schemaContext, dataSchema);
265 if (dataNode == null) {
266 // or, as last resort, defaults from the model
267 return bindingContext.newDefaultNode(dataSchema);
273 } catch (final ConfigXMLReaderException | IOException | SAXException | XMLStreamException
274 | ParserConfigurationException | URISyntaxException e) {
275 if (e.getCause() == null) {
276 setFailureMessage(e.getMessage());
278 setFailure(e.getMessage(), e);
285 private NormalizedNode<?, ?> parsePossibleDefaultAppConfigElement(final SchemaContext schemaContext,
286 final DataSchemaNode dataSchema) throws URISyntaxException, IOException, ParserConfigurationException,
287 SAXException, XMLStreamException {
288 if (defaultAppConfigElement == null) {
292 LOG.debug("{}: parsePossibleDefaultAppConfigElement for {}", logName(), bindingContext.bindingQName);
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;