2 * Copyright (c) 2015 Cisco 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
9 package org.opendaylight.controller.config.persist.impl;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import com.google.common.base.Function;
13 import com.google.common.base.Stopwatch;
14 import com.google.common.collect.Collections2;
15 import java.io.IOException;
16 import java.util.Collection;
17 import java.util.Date;
18 import java.util.HashSet;
19 import java.util.LinkedHashMap;
20 import java.util.List;
22 import java.util.SortedSet;
23 import java.util.concurrent.BlockingQueue;
24 import java.util.concurrent.LinkedBlockingQueue;
25 import java.util.concurrent.TimeUnit;
26 import javax.annotation.Nonnull;
27 import javax.annotation.concurrent.Immutable;
28 import javax.management.MBeanServerConnection;
29 import org.opendaylight.controller.config.api.ConflictingVersionException;
30 import org.opendaylight.controller.config.api.ModuleFactoryNotFoundException;
31 import org.opendaylight.controller.config.api.ValidationException;
32 import org.opendaylight.controller.config.facade.xml.ConfigExecution;
33 import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
34 import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
35 import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
36 import org.opendaylight.controller.config.persist.api.ConfigPusher;
37 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
38 import org.opendaylight.controller.config.persist.api.Persister;
39 import org.opendaylight.controller.config.util.capability.Capability;
40 import org.opendaylight.controller.config.util.xml.DocumentedException;
41 import org.opendaylight.controller.config.util.xml.XmlUtil;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Element;
45 import org.xml.sax.SAXException;
48 public class ConfigPusherImpl implements ConfigPusher {
49 private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherImpl.class);
51 private static final Date NO_REVISION = new Date(0);
52 private static final int QUEUE_SIZE = 100;
54 private final long maxWaitForCapabilitiesMillis;
55 private final long conflictingVersionTimeoutMillis;
56 private final BlockingQueue<List<? extends ConfigSnapshotHolder>> queue = new LinkedBlockingQueue<>(QUEUE_SIZE);
58 private final ConfigSubsystemFacadeFactory facade;
59 private ConfigPersisterNotificationHandler jmxNotificationHandler;
61 public ConfigPusherImpl(final ConfigSubsystemFacadeFactory facade, final long maxWaitForCapabilitiesMillis,
62 final long conflictingVersionTimeoutMillis) {
63 this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
64 this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
68 public void process(final List<AutoCloseable> autoCloseables, final MBeanServerConnection platformMBeanServer,
69 final Persister persisterAggregator, final boolean propagateExceptions) throws InterruptedException {
70 while(processSingle(autoCloseables, platformMBeanServer, persisterAggregator, propagateExceptions)) {
74 boolean processSingle(final List<AutoCloseable> autoCloseables, final MBeanServerConnection platformMBeanServer,
75 final Persister persisterAggregator, final boolean propagateExceptions) throws InterruptedException {
76 final List<? extends ConfigSnapshotHolder> configs = queue.take();
78 internalPushConfigs(configs);
80 // Do not register multiple notification handlers
81 if(jmxNotificationHandler == null) {
82 jmxNotificationHandler =
83 new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator, facade);
84 synchronized (autoCloseables) {
85 autoCloseables.add(jmxNotificationHandler);
89 LOG.debug("ConfigPusher has pushed configs {}", configs);
90 } catch (final Exception e) {
91 // Exceptions are logged to error downstream
92 LOG.debug("Failed to push some of configs: {}", configs, e);
94 if(propagateExceptions) {
95 if(e instanceof RuntimeException) {
96 throw (RuntimeException)e;
98 throw new IllegalStateException(e);
109 public void pushConfigs(final List<? extends ConfigSnapshotHolder> configs) throws InterruptedException {
110 LOG.debug("Requested to push configs {}", configs);
111 this.queue.put(configs);
114 private LinkedHashMap<? extends ConfigSnapshotHolder, Boolean> internalPushConfigs(final List<? extends ConfigSnapshotHolder> configs)
115 throws DocumentedException {
116 LOG.debug("Last config snapshots to be pushed to netconf: {}", configs);
117 LinkedHashMap<ConfigSnapshotHolder, Boolean> result = new LinkedHashMap<>();
118 // start pushing snapshots
119 for (ConfigSnapshotHolder configSnapshotHolder : configs) {
120 if (configSnapshotHolder != null) {
121 LOG.info("Pushing configuration snapshot {}", configSnapshotHolder);
122 boolean pushResult = false;
124 pushResult = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
125 } catch (final ConfigSnapshotFailureException e) {
126 LOG.error("Failed to apply configuration snapshot: {}. Config snapshot is not semantically correct and will be IGNORED. " +
127 "for detailed information see enclosed exception.", e.getConfigIdForReporting(), e);
128 throw new IllegalStateException("Failed to apply configuration snapshot " + e.getConfigIdForReporting(), e);
129 } catch (final Exception e) {
130 String msg = String.format("Failed to apply configuration snapshot: %s", configSnapshotHolder);
132 throw new IllegalStateException(msg, e);
135 LOG.info("Successfully pushed configuration snapshot {}", configSnapshotHolder);
136 result.put(configSnapshotHolder, pushResult);
139 LOG.debug("All configuration snapshots have been pushed successfully.");
143 private synchronized boolean pushConfigWithConflictingVersionRetries(final ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException {
144 ConflictingVersionException lastException;
145 Stopwatch stopwatch = Stopwatch.createUnstarted();
147 //TODO wait untill all expected modules are in yangStoreService, do we even need to with yangStoreService instead on netconfOperationService?
148 String idForReporting = configSnapshotHolder.toString();
149 SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
150 "Expected capabilities must not be null - %s, check %s", idForReporting,
151 configSnapshotHolder.getClass().getName());
153 // wait max time for required capabilities to appear
154 waitForCapabilities(expectedCapabilities, idForReporting);
156 if(!stopwatch.isRunning()) {
159 return pushConfig(configSnapshotHolder);
160 } catch (final ConflictingVersionException e) {
162 LOG.info("Conflicting version detected, will retry after timeout");
165 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
166 throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
170 private void waitForCapabilities(final Set<String> expectedCapabilities, final String idForReporting) {
171 Stopwatch stopwatch = Stopwatch.createStarted();
172 ConfigPusherException lastException;
175 final Set<Capability> currentCaps = facade.getCurrentCapabilities();
176 final Set<String> notFoundCapabilities = computeNotFoundCapabilities(expectedCapabilities, currentCaps);
177 if (notFoundCapabilities.isEmpty()) {
180 LOG.debug("Netconf server did not provide required capabilities for {} ", idForReporting,
181 "Expected but not found: {}, all expected {}, current {}",
182 notFoundCapabilities, expectedCapabilities, currentCaps
184 throw new NotEnoughCapabilitiesException(
185 "Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundCapabilities, notFoundCapabilities);
187 } catch (final ConfigPusherException e) {
188 LOG.debug("Not enough capabilities: {}", e.toString());
192 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
194 LOG.error("Unable to push configuration due to missing yang models." +
195 " Yang models that are missing, but required by the configuration: {}." +
196 " For each mentioned model check: " +
197 " 1. that the mentioned yang model namespace/name/revision is identical to those in the yang model itself" +
198 " 2. the yang file is present in the system" +
199 " 3. the bundle with that yang file is present in the system and active" +
200 " 4. the yang parser did not fail while attempting to parse that model",
201 ((NotEnoughCapabilitiesException) lastException).getMissingCaps());
202 throw new IllegalStateException("Unable to push configuration due to missing yang models." +
203 " Required yang models that are missing: "
204 + ((NotEnoughCapabilitiesException) lastException).getMissingCaps(), lastException);
207 private static Set<String> computeNotFoundCapabilities(final Set<String> expectedCapabilities, final Set<Capability> currentCapabilities) {
208 Collection<String> actual = transformCapabilities(currentCapabilities);
209 Set<String> allNotFound = new HashSet<>(expectedCapabilities);
210 allNotFound.removeAll(actual);
214 static Set<String> transformCapabilities(final Set<Capability> currentCapabilities) {
215 return new HashSet<>(Collections2.transform(currentCapabilities, new Function<Capability, String>() {
217 public String apply(@Nonnull final Capability input) {
218 return input.getCapabilityUri();
223 static class ConfigPusherException extends Exception {
225 public ConfigPusherException(final String message) {
229 public ConfigPusherException(final String message, final Throwable cause) {
230 super(message, cause);
234 static class NotEnoughCapabilitiesException extends ConfigPusherException {
235 private static final long serialVersionUID = 1L;
236 private final Set<String> missingCaps;
238 NotEnoughCapabilitiesException(final String message, final Set<String> missingCaps) {
240 this.missingCaps = missingCaps;
243 public Set<String> getMissingCaps() {
248 private static final class ConfigSnapshotFailureException extends ConfigPusherException {
250 private final String configIdForReporting;
252 public ConfigSnapshotFailureException(final String configIdForReporting, final String operationNameForReporting, final Exception e) {
253 super(String.format("Failed to apply config snapshot: %s during phase: %s", configIdForReporting, operationNameForReporting), e);
254 this.configIdForReporting = configIdForReporting;
257 public String getConfigIdForReporting() {
258 return configIdForReporting;
262 private void sleep() {
265 } catch (final InterruptedException e) {
266 Thread.currentThread().interrupt();
267 throw new IllegalStateException(e);
271 private synchronized boolean pushConfig(final ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException, ConflictingVersionException {
272 Element xmlToBePersisted;
274 xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
275 } catch (SAXException | IOException e) {
276 throw new IllegalStateException("Cannot parse " + configSnapshotHolder, e);
278 LOG.trace("Pushing last configuration to config mapping: {}", configSnapshotHolder);
280 Stopwatch stopwatch = Stopwatch.createStarted();
281 final ConfigSubsystemFacade currentFacade = this.facade.createFacade("config-push");
283 ConfigExecution configExecution = createConfigExecution(xmlToBePersisted, currentFacade);
284 executeWithMissingModuleFactoryRetries(currentFacade, configExecution);
285 } catch (ValidationException | DocumentedException | ModuleFactoryNotFoundException e) {
286 LOG.trace("Validation for config: {} failed", configSnapshotHolder, e);
287 throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "edit", e);
291 currentFacade.commitSilentTransaction();
292 } catch (ValidationException | DocumentedException e) {
293 throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "commit", e);
296 LOG.trace("Last configuration loaded successfully");
297 LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
302 private void executeWithMissingModuleFactoryRetries(final ConfigSubsystemFacade facade, final ConfigExecution configExecution)
303 throws DocumentedException, ValidationException, ModuleFactoryNotFoundException {
304 Stopwatch stopwatch = Stopwatch.createStarted();
305 ModuleFactoryNotFoundException lastException = null;
308 facade.executeConfigExecution(configExecution);
310 } catch (final ModuleFactoryNotFoundException e) {
311 LOG.debug("{} - will retry after timeout", e.toString());
315 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
320 private ConfigExecution createConfigExecution(final Element xmlToBePersisted, final ConfigSubsystemFacade currentFacade) throws DocumentedException {
321 final Config configMapping = currentFacade.getConfigMapping();
322 return currentFacade.getConfigExecution(configMapping, xmlToBePersisted);