0d6585bda2f026ae25b921951bcac8ec22be333e
[controller.git] / opendaylight / blueprint / src / main / java / org / opendaylight / controller / blueprint / ext / DataStoreAppConfigMetadata.java
1 /*
2  * Copyright (c) 2016 Brocade Communications 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.blueprint.ext;
9
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;
15 import java.io.File;
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;
47
48 /**
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.
53  *
54  * @author Thomas Pantelis
55  */
56 public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactoryMetadata {
57     private static final Logger LOG = LoggerFactory.getLogger(DataStoreAppConfigMetadata.class);
58
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";
63
64     private static final String DEFAULT_APP_CONFIG_FILE_PATH = "etc" + File.separator + "opendaylight" + File.separator
65             + "datastore" + File.separator + "initial" + File.separator + "config";
66
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);
73
74     private volatile BindingContext bindingContext;
75     private volatile ListenerRegistration<?> appConfigChangeListenerReg;
76     private volatile DataObject currentAppConfig;
77
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;
82
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) {
86         super(id);
87         this.defaultAppConfigElement = defaultAppConfigElement;
88         this.defaultAppConfigFileName = defaultAppConfigFileName;
89         this.appConfigBindingClassName = appConfigBindingClassName;
90         this.appConfigListKeyValue = appConfigListKeyValue;
91         this.appConfigUpdateStrategy = updateStrategyValue;
92     }
93
94     @Override
95     @SuppressWarnings("unchecked")
96     public void init(final ExtendedBlueprintContainer container) {
97         super.init(container);
98
99         Class<DataObject> appConfigBindingClass;
100         try {
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()));
106             }
107
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);
112         }
113
114         bindingContext = BindingContext.create(logName(), appConfigBindingClass, appConfigListKeyValue);
115     }
116
117     @Override
118     public Object create() throws ComponentDefinitionException {
119         LOG.debug("{}: In create - currentAppConfig: {}", logName(), currentAppConfig);
120
121         super.onCreate();
122
123         return currentAppConfig;
124     }
125
126     @Override
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.
130
131         retrieveService("binding-codec", BindingNormalizedNodeSerializer.class, service -> {
132             bindingSerializer = (BindingNormalizedNodeSerializer)service;
133             retrieveDataBrokerService();
134         });
135     }
136
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));
141     }
142
143     private void retrieveInitialAppConfig(final DataBroker dataBroker) {
144         LOG.debug("{}: Got DataBroker instance - reading app config {}", logName(), bindingContext.appConfigPath);
145
146         setDependencyDesc("Initial app config " + bindingContext.appConfigBindingClass.getSimpleName());
147
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
151         // isn't present.
152
153         DataTreeIdentifier<DataObject> dataTreeId = new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
154                 bindingContext.appConfigPath);
155         appConfigChangeListenerReg = dataBroker.registerDataTreeChangeListener(dataTreeId,
156                 (ClusteredDataTreeChangeListener<DataObject>) this::onAppConfigChanged);
157
158         readInitialAppConfig(dataBroker);
159     }
160
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>>() {
166             @Override
167             public void onSuccess(final Optional<DataObject> possibleAppConfig) {
168                 LOG.debug("{}: Read of app config {} succeeded: {}", logName(), bindingContext
169                         .appConfigBindingClass.getName(), possibleAppConfig);
170
171                 readOnlyTx.close();
172                 setInitialAppConfig(possibleAppConfig);
173             }
174
175             @Override
176             public void onFailure(final Throwable failure) {
177                 readOnlyTx.close();
178
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);
183
184                     readInitialAppConfig(dataBroker);
185                 }
186             }
187         }, MoreExecutors.directExecutor());
188     }
189
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();
194
195             LOG.debug("{}: onAppConfigChanged: {}, {}", logName(), type, change.getRootPath());
196
197             if (type == ModificationType.SUBTREE_MODIFIED || type == ModificationType.WRITE) {
198                 DataObject newAppConfig = changeRoot.getDataAfter();
199
200                 LOG.debug("New app config instance: {}, previous: {}", newAppConfig, currentAppConfig);
201
202                 if (!setInitialAppConfig(Optional.of(newAppConfig))
203                         && !Objects.equals(currentAppConfig, newAppConfig)) {
204                     LOG.debug("App config was updated");
205
206                     if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
207                         restartContainer();
208                     }
209                 }
210             } else if (type == ModificationType.DELETE) {
211                 LOG.debug("App config was deleted");
212
213                 if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
214                     restartContainer();
215                 }
216             }
217         }
218     }
219
220     private boolean setInitialAppConfig(final Optional<DataObject> possibleAppConfig) {
221         boolean result = readingInitialAppConfig.compareAndSet(true, false);
222         if (result) {
223             DataObject localAppConfig;
224             if (possibleAppConfig.isPresent()) {
225                 localAppConfig = possibleAppConfig.get();
226             } else {
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();
230             }
231
232             LOG.debug("{}: Setting currentAppConfig instance: {}", logName(), localAppConfig);
233
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;
237             setSatisfied();
238         }
239
240         return result;
241     }
242
243     private DataObject createDefaultInstance() {
244         try {
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());
249
250                 if (!appConfigFile.exists()) {
251                     return Optional.absent();
252                 }
253
254                 LOG.debug("{}: Found file {}", logName(), appConfigFile.getAbsolutePath());
255
256                 return Optional.of(appConfigFile.toURI().toURL());
257             };
258
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);
268                 } else {
269                     return dataNode;
270                 }
271             });
272
273         } catch (final ConfigXMLReaderException | IOException | SAXException | XMLStreamException
274                 | ParserConfigurationException | URISyntaxException e) {
275             if (e.getCause() == null) {
276                 setFailureMessage(e.getMessage());
277             } else {
278                 setFailure(e.getMessage(), e);
279             }
280             return null;
281         }
282     }
283
284     @Nullable
285     private NormalizedNode<?, ?> parsePossibleDefaultAppConfigElement(final SchemaContext schemaContext,
286             final DataSchemaNode dataSchema) throws URISyntaxException, IOException, ParserConfigurationException,
287             SAXException, XMLStreamException {
288         if (defaultAppConfigElement == null) {
289             return null;
290         }
291
292         LOG.debug("{}: parsePossibleDefaultAppConfigElement for {}", logName(), bindingContext.bindingQName);
293
294         LOG.debug("{}: Got app config schema: {}", logName(), dataSchema);
295
296         NormalizedNode<?, ?> dataNode = bindingContext.parseDataElement(defaultAppConfigElement, dataSchema,
297                 schemaContext);
298
299         LOG.debug("{}: Parsed data node: {}", logName(), dataNode);
300
301         return dataNode;
302     }
303
304     @Override
305     public void destroy(final Object instance) {
306         super.destroy(instance);
307
308         if (appConfigChangeListenerReg != null) {
309             appConfigChangeListenerReg.close();
310             appConfigChangeListenerReg = null;
311         }
312     }
313
314 }