2 * Copyright (c) 2013 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.netconf.persist.impl;
11 import static com.google.common.base.Preconditions.checkNotNull;
13 import com.google.common.base.Function;
14 import com.google.common.base.Stopwatch;
15 import com.google.common.collect.Collections2;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.util.Collection;
19 import java.util.HashSet;
20 import java.util.LinkedHashMap;
21 import java.util.List;
22 import java.util.Map.Entry;
24 import java.util.SortedSet;
25 import java.util.TreeMap;
26 import java.util.concurrent.BlockingQueue;
27 import java.util.concurrent.LinkedBlockingQueue;
28 import java.util.concurrent.TimeUnit;
29 import javax.annotation.Nonnull;
30 import javax.annotation.concurrent.Immutable;
31 import javax.management.MBeanServerConnection;
32 import org.opendaylight.controller.config.api.ConflictingVersionException;
33 import org.opendaylight.controller.config.persist.api.ConfigPusher;
34 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
35 import org.opendaylight.controller.config.persist.api.Persister;
36 import org.opendaylight.controller.netconf.api.Capability;
37 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
38 import org.opendaylight.controller.netconf.api.NetconfMessage;
39 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
40 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
41 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
42 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
43 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
44 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
45 import org.opendaylight.controller.netconf.util.NetconfUtil;
46 import org.opendaylight.controller.netconf.util.xml.XmlElement;
47 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.w3c.dom.Document;
51 import org.w3c.dom.Element;
52 import org.xml.sax.SAXException;
55 public class ConfigPusherImpl implements ConfigPusher {
56 private static final Logger LOG = LoggerFactory.getLogger(ConfigPusherImpl.class);
58 private final long maxWaitForCapabilitiesMillis;
59 private final long conflictingVersionTimeoutMillis;
60 private final NetconfOperationServiceFactory configNetconfConnector;
61 private static final int QUEUE_SIZE = 100;
62 private BlockingQueue<List<? extends ConfigSnapshotHolder>> queue = new LinkedBlockingQueue<List<? extends ConfigSnapshotHolder>>(QUEUE_SIZE);
64 public ConfigPusherImpl(NetconfOperationServiceFactory configNetconfConnector, long maxWaitForCapabilitiesMillis,
65 long conflictingVersionTimeoutMillis) {
66 this.configNetconfConnector = configNetconfConnector;
67 this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
68 this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
71 public void process(List<AutoCloseable> autoCloseables, MBeanServerConnection platformMBeanServer, Persister persisterAggregator) throws InterruptedException {
72 List<? extends ConfigSnapshotHolder> configs;
74 configs = queue.take();
76 internalPushConfigs(configs);
77 ConfigPersisterNotificationHandler jmxNotificationHandler = new ConfigPersisterNotificationHandler(platformMBeanServer, persisterAggregator);
78 synchronized (autoCloseables) {
79 autoCloseables.add(jmxNotificationHandler);
82 LOG.debug("ConfigPusher has pushed configs {}", configs);
83 } catch (NetconfDocumentedException e) {
84 LOG.error("Error pushing configs {}",configs);
85 throw new IllegalStateException(e);
90 public void pushConfigs(List<? extends ConfigSnapshotHolder> configs) throws InterruptedException {
91 LOG.debug("Requested to push configs {}", configs);
92 this.queue.put(configs);
95 private LinkedHashMap<? extends ConfigSnapshotHolder, EditAndCommitResponse> internalPushConfigs(List<? extends ConfigSnapshotHolder> configs) throws NetconfDocumentedException {
96 LOG.debug("Last config snapshots to be pushed to netconf: {}", configs);
97 LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponse> result = new LinkedHashMap<>();
98 // start pushing snapshots:
99 for (ConfigSnapshotHolder configSnapshotHolder : configs) {
100 if(configSnapshotHolder != null) {
101 EditAndCommitResponse editAndCommitResponseWithRetries = null;
103 editAndCommitResponseWithRetries = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
104 } catch (ConfigSnapshotFailureException e) {
105 LOG.warn("Failed to apply configuration snapshot: {}. Config snapshot is not semantically correct and will be IGNORED. " +
106 "for detailed information see enclosed exception.", e.getConfigIdForReporting(), e);
107 throw new IllegalStateException("Failed to apply configuration snapshot " + e.getConfigIdForReporting(), e);
109 LOG.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
110 result.put(configSnapshotHolder, editAndCommitResponseWithRetries);
113 LOG.debug("All configuration snapshots have been pushed successfully.");
118 * First calls {@link #getOperationServiceWithRetries(java.util.Set, String)} in order to wait until
119 * expected capabilities are present, then tries to push configuration. If {@link ConflictingVersionException}
120 * is caught, whole process is retried - new service instance need to be obtained from the factory. Closes
121 * {@link NetconfOperationService} after each use.
123 private synchronized EditAndCommitResponse pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws ConfigSnapshotFailureException {
124 ConflictingVersionException lastException;
125 Stopwatch stopwatch = Stopwatch.createUnstarted();
127 String idForReporting = configSnapshotHolder.toString();
128 SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
129 "Expected capabilities must not be null - %s, check %s", idForReporting,
130 configSnapshotHolder.getClass().getName());
131 try (NetconfOperationService operationService = getOperationServiceWithRetries(expectedCapabilities, idForReporting)) {
132 if(!stopwatch.isRunning()) {
135 return pushConfig(configSnapshotHolder, operationService);
136 } catch (ConflictingVersionException e) {
138 LOG.info("Conflicting version detected, will retry after timeout");
141 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
142 throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
146 private NetconfOperationService getOperationServiceWithRetries(Set<String> expectedCapabilities, String idForReporting) {
147 Stopwatch stopwatch = Stopwatch.createStarted();
148 ConfigPusherException lastException;
151 return getOperationService(expectedCapabilities, idForReporting);
152 } catch (ConfigPusherException e) {
153 LOG.debug("Not enough capabilities: {}", e.toString());
157 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
159 if(lastException instanceof NotEnoughCapabilitiesException) {
160 LOG.error("Unable to push configuration due to missing yang models." +
161 " Yang models that are missing, but required by the configuration: {}." +
162 " For each mentioned model check: " +
163 " 1. that the mentioned yang model namespace/name/revision is identical to those in the yang model itself" +
164 " 2. the yang file is present in the system" +
165 " 3. the bundle with that yang file is present in the system and active" +
166 " 4. the yang parser did not fail while attempting to parse that model",
167 ((NotEnoughCapabilitiesException) lastException).getMissingCaps());
168 throw new IllegalStateException("Unable to push configuration due to missing yang models." +
169 " Required yang models that are missing: "
170 + ((NotEnoughCapabilitiesException) lastException).getMissingCaps(), lastException);
172 final String msg = "Unable to push configuration due to missing netconf service";
173 LOG.error(msg, lastException);
174 throw new IllegalStateException(msg, lastException);
178 private static class ConfigPusherException extends Exception {
180 public ConfigPusherException(final String message) {
184 public ConfigPusherException(final String message, final Throwable cause) {
185 super(message, cause);
189 private static class NotEnoughCapabilitiesException extends ConfigPusherException {
190 private static final long serialVersionUID = 1L;
191 private Set<String> missingCaps;
193 private NotEnoughCapabilitiesException(String message, Set<String> missingCaps) {
195 this.missingCaps = missingCaps;
198 public Set<String> getMissingCaps() {
203 private static final class NetconfServiceNotAvailableException extends ConfigPusherException {
205 public NetconfServiceNotAvailableException(final String s, final RuntimeException e) {
210 private static final class ConfigSnapshotFailureException extends ConfigPusherException {
212 private final String configIdForReporting;
214 public ConfigSnapshotFailureException(final String configIdForReporting, final String operationNameForReporting, final Exception e) {
215 super(String.format("Failed to apply config snapshot: %s during phase: %s", configIdForReporting, operationNameForReporting), e);
216 this.configIdForReporting = configIdForReporting;
219 public String getConfigIdForReporting() {
220 return configIdForReporting;
225 * Get NetconfOperationService iif all required capabilities are present.
227 * @param expectedCapabilities that must be provided by configNetconfConnector
228 * @param idForReporting
229 * @return service if capabilities are present, otherwise absent value
231 private NetconfOperationService getOperationService(Set<String> expectedCapabilities, String idForReporting) throws ConfigPusherException {
232 NetconfOperationService serviceCandidate;
234 serviceCandidate = configNetconfConnector.createService(idForReporting);
235 } catch(RuntimeException e) {
236 throw new NetconfServiceNotAvailableException("Netconf service not stable for config pusher." +
237 " Cannot push any configuration", e);
239 Set<String> notFoundDiff = computeNotFoundCapabilities(expectedCapabilities, configNetconfConnector);
240 if (notFoundDiff.isEmpty()) {
241 return serviceCandidate;
243 serviceCandidate.close();
244 LOG.debug("Netconf server did not provide required capabilities for {} ", idForReporting,
245 "Expected but not found: {}, all expected {}, current {}",
246 notFoundDiff, expectedCapabilities, configNetconfConnector.getCapabilities()
248 throw new NotEnoughCapabilitiesException("Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundDiff, notFoundDiff);
252 private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, NetconfOperationServiceFactory serviceCandidate) {
253 Collection<String> actual = Collections2.transform(serviceCandidate.getCapabilities(), new Function<Capability, String>() {
255 public String apply(@Nonnull final Capability input) {
256 return input.getCapabilityUri();
259 Set<String> allNotFound = new HashSet<>(expectedCapabilities);
260 allNotFound.removeAll(actual);
264 private void sleep() {
267 } catch (InterruptedException e) {
268 Thread.currentThread().interrupt();
269 throw new IllegalStateException(e);
274 * Sends two RPCs to the netconf server: edit-config and commit.
276 * @param configSnapshotHolder
277 * @throws ConflictingVersionException if commit fails on optimistic lock failure inside of config-manager
278 * @throws java.lang.RuntimeException if edit-config or commit fails otherwise
280 private synchronized EditAndCommitResponse pushConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfOperationService operationService)
281 throws ConflictingVersionException, ConfigSnapshotFailureException {
283 Element xmlToBePersisted;
285 xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
286 } catch (SAXException | IOException e) {
287 throw new IllegalStateException("Cannot parse " + configSnapshotHolder);
289 LOG.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
290 Stopwatch stopwatch = Stopwatch.createStarted();
291 NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted);
293 Document editResponseMessage = sendRequestGetResponseCheckIsOK(editConfigMessage, operationService,
294 "edit-config", configSnapshotHolder.toString());
296 Document commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), operationService,
297 "commit", configSnapshotHolder.toString());
299 if (LOG.isTraceEnabled()) {
300 StringBuilder response = new StringBuilder("editConfig response = {");
301 response.append(XmlUtil.toString(editResponseMessage));
302 response.append("}");
303 response.append("commit response = {");
304 response.append(XmlUtil.toString(commitResponseMessage));
305 response.append("}");
306 LOG.trace("Last configuration loaded successfully");
307 LOG.trace("Detailed message {}", response);
308 LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
310 return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
313 private NetconfOperation findOperation(NetconfMessage request, NetconfOperationService operationService) {
314 TreeMap<HandlingPriority, NetconfOperation> allOperations = new TreeMap<>();
315 Set<NetconfOperation> netconfOperations = operationService.getNetconfOperations();
316 if (netconfOperations.isEmpty()) {
317 throw new IllegalStateException("Possible code error: no config operations");
319 for (NetconfOperation netconfOperation : netconfOperations) {
320 HandlingPriority handlingPriority = null;
322 handlingPriority = netconfOperation.canHandle(request.getDocument());
323 } catch (NetconfDocumentedException e) {
324 throw new IllegalStateException("Possible code error: canHandle threw exception", e);
326 allOperations.put(handlingPriority, netconfOperation);
328 Entry<HandlingPriority, NetconfOperation> highestEntry = allOperations.lastEntry();
329 if (highestEntry.getKey().isCannotHandle()) {
330 throw new IllegalStateException("Possible code error: operation with highest priority is CANNOT_HANDLE");
332 return highestEntry.getValue();
335 private Document sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfOperationService operationService,
336 String operationNameForReporting, String configIdForReporting)
337 throws ConflictingVersionException, ConfigSnapshotFailureException {
339 NetconfOperation operation = findOperation(request, operationService);
342 response = operation.handle(request.getDocument(), NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
343 return NetconfUtil.checkIsMessageOk(response);
344 } catch (NetconfDocumentedException e) {
345 if (e.getCause() instanceof ConflictingVersionException) {
346 throw (ConflictingVersionException) e.getCause();
348 throw new ConfigSnapshotFailureException(configIdForReporting, operationNameForReporting, e);
352 // load editConfig.xml template, populate /rpc/edit-config/config with parameter
353 private static NetconfMessage createEditConfigMessage(Element dataElement) {
354 String editConfigResourcePath = "/netconfOp/editConfig.xml";
355 try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
356 checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
358 Document doc = XmlUtil.readXmlToDocument(stream);
360 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
361 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
362 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
363 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
365 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), deep));
367 editConfigElement.appendChild(configWrapper.getDomElement());
368 return new NetconfMessage(doc);
369 } catch (IOException | SAXException | NetconfDocumentedException e) {
370 // error reading the xml file bundled into the jar
371 throw new IllegalStateException("Error while opening local resource " + editConfigResourcePath, e);
375 private static NetconfMessage getCommitMessage() {
376 String resource = "/netconfOp/commit.xml";
377 try (InputStream stream = ConfigPusherImpl.class.getResourceAsStream(resource)) {
378 checkNotNull(stream, "Unable to load resource " + resource);
379 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
380 } catch (SAXException | IOException e) {
381 // error reading the xml file bundled into the jar
382 throw new IllegalStateException("Error while opening local resource " + resource, e);
386 static class EditAndCommitResponse {
387 private final Document editResponse, commitResponse;
389 EditAndCommitResponse(Document editResponse, Document commitResponse) {
390 this.editResponse = editResponse;
391 this.commitResponse = commitResponse;
394 public Document getEditResponse() {
398 public Document getCommitResponse() {
399 return commitResponse;
403 public String toString() {
404 return "EditAndCommitResponse{" +
405 "editResponse=" + editResponse +
406 ", commitResponse=" + commitResponse +