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.Nullable;
28 import javax.annotation.concurrent.Immutable;
29 import javax.management.MBeanServerConnection;
30 import org.opendaylight.controller.config.api.ConflictingVersionException;
31 import org.opendaylight.controller.config.api.ModuleFactoryNotFoundException;
32 import org.opendaylight.controller.config.api.ValidationException;
33 import org.opendaylight.controller.config.facade.xml.ConfigExecution;
34 import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacade;
35 import org.opendaylight.controller.config.facade.xml.ConfigSubsystemFacadeFactory;
36 import org.opendaylight.controller.config.facade.xml.mapping.config.Config;
37 import org.opendaylight.controller.config.facade.xml.osgi.YangStoreService;
38 import org.opendaylight.controller.config.facade.xml.util.Util;
39 import org.opendaylight.controller.config.persist.api.ConfigPusher;
40 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
41 import org.opendaylight.controller.config.persist.api.Persister;
42 import org.opendaylight.controller.config.util.capability.Capability;
43 import org.opendaylight.controller.config.util.xml.DocumentedException;
44 import org.opendaylight.controller.config.util.xml.XmlUtil;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.w3c.dom.Element;
49 import org.xml.sax.SAXException;
52 public class ConfigPusherImpl implements ConfigPusher {
53 private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherImpl.class);
55 private static final Date NO_REVISION = new Date(0);
56 private static final int QUEUE_SIZE = 100;
58 private final long maxWaitForCapabilitiesMillis;
59 private final long conflictingVersionTimeoutMillis;
60 private final BlockingQueue<List<? extends ConfigSnapshotHolder>> queue = new LinkedBlockingQueue<>(QUEUE_SIZE);
62 private final ConfigSubsystemFacadeFactory facade;
63 private ConfigPersisterNotificationHandler jmxNotificationHandler;
65 public ConfigPusherImpl(ConfigSubsystemFacadeFactory facade, long maxWaitForCapabilitiesMillis,
66 long conflictingVersionTimeoutMillis) {
67 this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
68 this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
72 public void process(List<AutoCloseable> autoCloseables, MBeanServerConnection platformMBeanServer,
73 Persister persisterAggregator, boolean propagateExceptions) throws InterruptedException {
74 while(processSingle(autoCloseables, platformMBeanServer, persisterAggregator, propagateExceptions)) {
78 boolean processSingle(final List<AutoCloseable> autoCloseables, final MBeanServerConnection platformMBeanServer,
79 final Persister persisterAggregator, boolean propagateExceptions) throws InterruptedException {
80 final List<? extends ConfigSnapshotHolder> configs = queue.take();
82 internalPushConfigs(configs);
84 // Do not register multiple notification handlers
85 if(jmxNotificationHandler == null) {
86 jmxNotificationHandler =
87 new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator, facade);
88 synchronized (autoCloseables) {
89 autoCloseables.add(jmxNotificationHandler);
93 LOG.debug("ConfigPusher has pushed configs {}", configs);
94 } catch (Exception e) {
95 // Exceptions are logged to error downstream
96 LOG.debug("Failed to push some of configs: {}", configs, e);
98 if(propagateExceptions) {
99 if(e instanceof RuntimeException) {
100 throw (RuntimeException)e;
102 throw new IllegalStateException(e);
113 public void pushConfigs(List<? extends ConfigSnapshotHolder> configs) throws InterruptedException {
114 LOG.debug("Requested to push configs {}", configs);
115 this.queue.put(configs);
118 private LinkedHashMap<? extends ConfigSnapshotHolder, Boolean> internalPushConfigs(List<? extends ConfigSnapshotHolder> configs)
119 throws DocumentedException {
120 LOG.debug("Last config snapshots to be pushed to netconf: {}", configs);
121 LinkedHashMap<ConfigSnapshotHolder, Boolean> result = new LinkedHashMap<>();
122 // start pushing snapshots
123 for (ConfigSnapshotHolder configSnapshotHolder : configs) {
124 if (configSnapshotHolder != null) {
125 LOG.info("Pushing configuration snapshot {}", configSnapshotHolder);
126 boolean pushResult = false;
128 pushResult = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
129 } catch (ConfigSnapshotFailureException e) {
130 LOG.error("Failed to apply configuration snapshot: {}. Config snapshot is not semantically correct and will be IGNORED. " +
131 "for detailed information see enclosed exception.", e.getConfigIdForReporting(), e);
132 throw new IllegalStateException("Failed to apply configuration snapshot " + e.getConfigIdForReporting(), e);
133 } catch (Exception e) {
134 String msg = String.format("Failed to apply configuration snapshot: %s", configSnapshotHolder);
136 throw new IllegalStateException(msg, e);
139 LOG.info("Successfully pushed configuration snapshot {}", configSnapshotHolder);
140 result.put(configSnapshotHolder, pushResult);
143 LOG.debug("All configuration snapshots have been pushed successfully.");
147 private synchronized boolean pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException {
148 ConflictingVersionException lastException;
149 Stopwatch stopwatch = Stopwatch.createUnstarted();
151 //TODO wait untill all expected modules are in yangStoreService, do we even need to with yangStoreService instead on netconfOperationService?
152 String idForReporting = configSnapshotHolder.toString();
153 SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
154 "Expected capabilities must not be null - %s, check %s", idForReporting,
155 configSnapshotHolder.getClass().getName());
157 // wait max time for required capabilities to appear
158 waitForCapabilities(expectedCapabilities, idForReporting);
160 if(!stopwatch.isRunning()) {
163 return pushConfig(configSnapshotHolder);
164 } catch (ConflictingVersionException e) {
166 LOG.info("Conflicting version detected, will retry after timeout");
169 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
170 throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
174 private void waitForCapabilities(Set<String> expectedCapabilities, String idForReporting) {
175 Stopwatch stopwatch = Stopwatch.createStarted();
176 ConfigPusherException lastException;
179 final Set<Capability> currentCaps = facade.getCurrentCapabilities();
180 final Set<String> notFoundCapabilities = computeNotFoundCapabilities(expectedCapabilities, currentCaps);
181 if (notFoundCapabilities.isEmpty()) {
184 LOG.debug("Netconf server did not provide required capabilities for {} ", idForReporting,
185 "Expected but not found: {}, all expected {}, current {}",
186 notFoundCapabilities, expectedCapabilities, currentCaps
188 throw new NotEnoughCapabilitiesException(
189 "Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundCapabilities, notFoundCapabilities);
191 } catch (ConfigPusherException e) {
192 LOG.debug("Not enough capabilities: {}", e.toString());
196 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
198 LOG.error("Unable to push configuration due to missing yang models." +
199 " Yang models that are missing, but required by the configuration: {}." +
200 " For each mentioned model check: " +
201 " 1. that the mentioned yang model namespace/name/revision is identical to those in the yang model itself" +
202 " 2. the yang file is present in the system" +
203 " 3. the bundle with that yang file is present in the system and active" +
204 " 4. the yang parser did not fail while attempting to parse that model",
205 ((NotEnoughCapabilitiesException) lastException).getMissingCaps());
206 throw new IllegalStateException("Unable to push configuration due to missing yang models." +
207 " Required yang models that are missing: "
208 + ((NotEnoughCapabilitiesException) lastException).getMissingCaps(), lastException);
211 private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, Set<Capability> currentCapabilities) {
212 Collection<String> actual = transformCapabilities(currentCapabilities);
213 Set<String> allNotFound = new HashSet<>(expectedCapabilities);
214 allNotFound.removeAll(actual);
218 static Set<String> transformCapabilities(final Set<Capability> currentCapabilities) {
219 return new HashSet<>(Collections2.transform(currentCapabilities, new Function<Capability, String>() {
221 public String apply(@Nonnull final Capability input) {
222 return input.getCapabilityUri();
227 static class ConfigPusherException extends Exception {
229 public ConfigPusherException(final String message) {
233 public ConfigPusherException(final String message, final Throwable cause) {
234 super(message, cause);
238 static class NotEnoughCapabilitiesException extends ConfigPusherException {
239 private static final long serialVersionUID = 1L;
240 private final Set<String> missingCaps;
242 NotEnoughCapabilitiesException(String message, Set<String> missingCaps) {
244 this.missingCaps = missingCaps;
247 public Set<String> getMissingCaps() {
252 private static final class ConfigSnapshotFailureException extends ConfigPusherException {
254 private final String configIdForReporting;
256 public ConfigSnapshotFailureException(final String configIdForReporting, final String operationNameForReporting, final Exception e) {
257 super(String.format("Failed to apply config snapshot: %s during phase: %s", configIdForReporting, operationNameForReporting), e);
258 this.configIdForReporting = configIdForReporting;
261 public String getConfigIdForReporting() {
262 return configIdForReporting;
266 private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, YangStoreService yangStoreService) {
268 Collection<String> actual = Collections2.transform(yangStoreService.getModules(), new Function<Module, String>() {
271 public String apply(Module input) {
272 final String withoutRevision = input.getNamespace().toString() + "?module=" + input.getName();
273 return !input.getRevision().equals(NO_REVISION) ? withoutRevision + "&revision=" + Util.writeDate(input.getRevision()) : withoutRevision;
277 Set<String> allNotFound = new HashSet<>(expectedCapabilities);
278 allNotFound.removeAll(actual);
282 private void sleep() {
285 } catch (InterruptedException e) {
286 Thread.currentThread().interrupt();
287 throw new IllegalStateException(e);
291 private synchronized boolean pushConfig(ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException, ConflictingVersionException {
292 Element xmlToBePersisted;
294 xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
295 } catch (SAXException | IOException e) {
296 throw new IllegalStateException("Cannot parse " + configSnapshotHolder, e);
298 LOG.trace("Pushing last configuration to config mapping: {}", configSnapshotHolder);
300 Stopwatch stopwatch = Stopwatch.createStarted();
301 final ConfigSubsystemFacade currentFacade = this.facade.createFacade("config-push");
303 ConfigExecution configExecution = createConfigExecution(xmlToBePersisted, currentFacade);
304 executeWithMissingModuleFactoryRetries(currentFacade, configExecution);
305 } catch (ValidationException | DocumentedException | ModuleFactoryNotFoundException e) {
306 LOG.trace("Validation for config: {} failed", configSnapshotHolder, e);
307 throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "edit", e);
311 currentFacade.commitSilentTransaction();
312 } catch (ValidationException | DocumentedException e) {
313 throw new ConfigSnapshotFailureException(configSnapshotHolder.toString(), "commit", e);
316 LOG.trace("Last configuration loaded successfully");
317 LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
322 private void executeWithMissingModuleFactoryRetries(ConfigSubsystemFacade facade, ConfigExecution configExecution)
323 throws DocumentedException, ValidationException, ModuleFactoryNotFoundException {
324 Stopwatch stopwatch = Stopwatch.createStarted();
325 ModuleFactoryNotFoundException lastException = null;
328 facade.executeConfigExecution(configExecution);
330 } catch (ModuleFactoryNotFoundException e) {
331 LOG.debug("{} - will retry after timeout", e.toString());
335 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
340 private ConfigExecution createConfigExecution(Element xmlToBePersisted, final ConfigSubsystemFacade currentFacade) throws DocumentedException {
341 final Config configMapping = currentFacade.getConfigMapping();
342 return currentFacade.getConfigExecution(configMapping, xmlToBePersisted);