Fix (and suppress) some static code analysis warnings in blueprint
[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.CheckedFuture;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.Futures;
14 import java.io.File;
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;
44
45 /**
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.
50  *
51  * @author Thomas Pantelis
52  */
53 public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactoryMetadata {
54     private static final Logger LOG = LoggerFactory.getLogger(DataStoreAppConfigMetadata.class);
55
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";
60
61     private static final String DEFAULT_APP_CONFIG_FILE_PATH = "etc" + File.separator + "opendaylight" + File.separator
62             + "datastore" + File.separator + "initial" + File.separator + "config";
63
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);
70
71     private volatile BindingContext bindingContext;
72     private volatile ListenerRegistration<?> appConfigChangeListenerReg;
73     private volatile DataObject currentAppConfig;
74
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;
79
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) {
83         super(id);
84         this.defaultAppConfigElement = defaultAppConfigElement;
85         this.defaultAppConfigFileName = defaultAppConfigFileName;
86         this.appConfigBindingClassName = appConfigBindingClassName;
87         this.appConfigListKeyValue = appConfigListKeyValue;
88         this.appConfigUpdateStrategy = updateStrategyValue;
89     }
90
91     @Override
92     @SuppressWarnings("unchecked")
93     public void init(final ExtendedBlueprintContainer container) {
94         super.init(container);
95
96         Class<DataObject> appConfigBindingClass;
97         try {
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()));
103             }
104
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);
109         }
110
111         bindingContext = BindingContext.create(logName(), appConfigBindingClass, appConfigListKeyValue);
112     }
113
114     @Override
115     public Object create() throws ComponentDefinitionException {
116         LOG.debug("{}: In create - currentAppConfig: {}", logName(), currentAppConfig);
117
118         super.onCreate();
119
120         return currentAppConfig;
121     }
122
123     @Override
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.
127
128         retrieveService("binding-codec", BindingNormalizedNodeSerializer.class, service -> {
129             bindingSerializer = (BindingNormalizedNodeSerializer)service;
130             retrieveDataBrokerService();
131         });
132     }
133
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));
138     }
139
140     private void retrieveInitialAppConfig(final DataBroker dataBroker) {
141         LOG.debug("{}: Got DataBroker instance - reading app config {}", logName(), bindingContext.appConfigPath);
142
143         setDependencyDesc("Initial app config " + bindingContext.appConfigBindingClass.getSimpleName());
144
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
148         // isn't present.
149
150         DataTreeIdentifier<DataObject> dataTreeId = new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
151                 bindingContext.appConfigPath);
152         appConfigChangeListenerReg = dataBroker.registerDataTreeChangeListener(dataTreeId,
153                 (ClusteredDataTreeChangeListener<DataObject>) this::onAppConfigChanged);
154
155         readInitialAppConfig(dataBroker);
156     }
157
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>>() {
164             @Override
165             public void onSuccess(final Optional<DataObject> possibleAppConfig) {
166                 LOG.debug("{}: Read of app config {} succeeded: {}", logName(), bindingContext
167                         .appConfigBindingClass.getName(), possibleAppConfig);
168
169                 readOnlyTx.close();
170                 setInitialAppConfig(possibleAppConfig);
171             }
172
173             @Override
174             public void onFailure(final Throwable failure) {
175                 readOnlyTx.close();
176
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);
181
182                     readInitialAppConfig(dataBroker);
183                 }
184             }
185         });
186     }
187
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();
192
193             LOG.debug("{}: onAppConfigChanged: {}, {}", logName(), type, change.getRootPath());
194
195             if (type == ModificationType.SUBTREE_MODIFIED || type == ModificationType.WRITE) {
196                 DataObject newAppConfig = changeRoot.getDataAfter();
197
198                 LOG.debug("New app config instance: {}, previous: {}", newAppConfig, currentAppConfig);
199
200                 if (!setInitialAppConfig(Optional.of(newAppConfig))
201                         && !Objects.equals(currentAppConfig, newAppConfig)) {
202                     LOG.debug("App config was updated");
203
204                     if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
205                         restartContainer();
206                     }
207                 }
208             } else if (type == ModificationType.DELETE) {
209                 LOG.debug("App config was deleted");
210
211                 if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) {
212                     restartContainer();
213                 }
214             }
215         }
216     }
217
218     private boolean setInitialAppConfig(final Optional<DataObject> possibleAppConfig) {
219         boolean result = readingInitialAppConfig.compareAndSet(true, false);
220         if (result) {
221             DataObject localAppConfig;
222             if (possibleAppConfig.isPresent()) {
223                 localAppConfig = possibleAppConfig.get();
224             } else {
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();
228             }
229
230             LOG.debug("{}: Setting currentAppConfig instance: {}", logName(), localAppConfig);
231
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;
235             setSatisfied();
236         }
237
238         return result;
239     }
240
241     private DataObject createDefaultInstance() {
242         try {
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());
248
249                 if (!appConfigFile.exists()) {
250                     return Optional.absent();
251                 }
252
253                 LOG.debug("{}: Found file {}", logName(), appConfigFile.getAbsolutePath());
254
255                 return Optional.of(appConfigFile.toURI().toURL());
256             };
257
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);
267                 } else {
268                     return dataNode;
269                 }
270             });
271
272         } catch (ConfigXMLReaderException e) {
273             if (e.getCause() == null) {
274                 setFailureMessage(e.getMessage());
275             } else {
276                 setFailure(e.getMessage(), e);
277             }
278             return null;
279         }
280     }
281
282     @Nullable
283     private NormalizedNode<?, ?> parsePossibleDefaultAppConfigElement(final SchemaContext schemaContext,
284             final DataSchemaNode dataSchema) {
285         if (defaultAppConfigElement == null) {
286             return null;
287         }
288
289         LOG.debug("{}: parsePossibleDefaultAppConfigElement for {}", logName(), bindingContext.bindingQName);
290
291         DomToNormalizedNodeParserFactory parserFactory = DomToNormalizedNodeParserFactory.getInstance(
292                 XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext);
293
294
295         LOG.debug("{}: Got app config schema: {}", logName(), dataSchema);
296
297         NormalizedNode<?, ?> dataNode = bindingContext.parseDataElement(defaultAppConfigElement, dataSchema,
298                 parserFactory);
299
300         LOG.debug("{}: Parsed data node: {}", logName(), dataNode);
301
302         return dataNode;
303     }
304
305     @Override
306     public void destroy(final Object instance) {
307         super.destroy(instance);
308
309         if (appConfigChangeListenerReg != null) {
310             appConfigChangeListenerReg.close();
311             appConfigChangeListenerReg = null;
312         }
313     }
314
315 }