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.NetconfDocumentedException;
37 import org.opendaylight.controller.netconf.api.NetconfMessage;
38 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
39 import org.opendaylight.controller.netconf.mapping.api.Capability;
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 = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
102 LOG.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
103 result.put(configSnapshotHolder, editAndCommitResponseWithRetries);
106 LOG.debug("All configuration snapshots have been pushed successfully.");
111 * First calls {@link #getOperationServiceWithRetries(java.util.Set, String)} in order to wait until
112 * expected capabilities are present, then tries to push configuration. If {@link ConflictingVersionException}
113 * is caught, whole process is retried - new service instance need to be obtained from the factory. Closes
114 * {@link NetconfOperationService} after each use.
116 private synchronized EditAndCommitResponse pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws NetconfDocumentedException {
117 ConflictingVersionException lastException;
118 Stopwatch stopwatch = new Stopwatch().start();
120 String idForReporting = configSnapshotHolder.toString();
121 SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
122 "Expected capabilities must not be null - %s, check %s", idForReporting,
123 configSnapshotHolder.getClass().getName());
124 try (NetconfOperationService operationService = getOperationServiceWithRetries(expectedCapabilities, idForReporting)) {
125 return pushConfig(configSnapshotHolder, operationService);
126 } catch (ConflictingVersionException e) {
128 LOG.debug("Conflicting version detected, will retry after timeout");
131 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
132 throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
136 private NetconfOperationService getOperationServiceWithRetries(Set<String> expectedCapabilities, String idForReporting) {
137 Stopwatch stopwatch = new Stopwatch().start();
138 NotEnoughCapabilitiesException lastException;
141 return getOperationService(expectedCapabilities, idForReporting);
142 } catch (NotEnoughCapabilitiesException e) {
143 LOG.debug("Not enough capabilities: {}", e.toString());
147 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
148 throw new IllegalStateException("Max wait for capabilities reached." + lastException.getMessage(), lastException);
151 private static class NotEnoughCapabilitiesException extends Exception {
152 private static final long serialVersionUID = 1L;
154 private NotEnoughCapabilitiesException(String message, Throwable cause) {
155 super(message, cause);
158 private NotEnoughCapabilitiesException(String message) {
164 * Get NetconfOperationService iif all required capabilities are present.
166 * @param expectedCapabilities that must be provided by configNetconfConnector
167 * @param idForReporting
168 * @return service if capabilities are present, otherwise absent value
170 private NetconfOperationService getOperationService(Set<String> expectedCapabilities, String idForReporting) throws NotEnoughCapabilitiesException {
171 NetconfOperationService serviceCandidate;
173 serviceCandidate = configNetconfConnector.createService(idForReporting);
174 } catch(RuntimeException e) {
175 throw new NotEnoughCapabilitiesException("Netconf service not stable for " + idForReporting, e);
177 Set<String> notFoundDiff = computeNotFoundCapabilities(expectedCapabilities, serviceCandidate);
178 if (notFoundDiff.isEmpty()) {
179 return serviceCandidate;
181 serviceCandidate.close();
182 LOG.trace("Netconf server did not provide required capabilities for {} ", idForReporting,
183 "Expected but not found: {}, all expected {}, current {}",
184 notFoundDiff, expectedCapabilities, serviceCandidate.getCapabilities()
186 throw new NotEnoughCapabilitiesException("Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundDiff);
190 private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, NetconfOperationService serviceCandidate) {
191 Collection<String> actual = Collections2.transform(serviceCandidate.getCapabilities(), new Function<Capability, String>() {
193 public String apply(@Nonnull final Capability input) {
194 return input.getCapabilityUri();
197 Set<String> allNotFound = new HashSet<>(expectedCapabilities);
198 allNotFound.removeAll(actual);
204 private void sleep() {
207 } catch (InterruptedException e) {
208 Thread.currentThread().interrupt();
209 throw new IllegalStateException(e);
214 * Sends two RPCs to the netconf server: edit-config and commit.
216 * @param configSnapshotHolder
217 * @throws ConflictingVersionException if commit fails on optimistic lock failure inside of config-manager
218 * @throws java.lang.RuntimeException if edit-config or commit fails otherwise
220 private synchronized EditAndCommitResponse pushConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfOperationService operationService)
221 throws ConflictingVersionException, NetconfDocumentedException {
223 Element xmlToBePersisted;
225 xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
226 } catch (SAXException | IOException e) {
227 throw new IllegalStateException("Cannot parse " + configSnapshotHolder);
229 LOG.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
230 Stopwatch stopwatch = new Stopwatch().start();
231 NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted);
233 Document editResponseMessage = sendRequestGetResponseCheckIsOK(editConfigMessage, operationService,
234 "edit-config", configSnapshotHolder.toString());
236 Document commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), operationService,
237 "commit", configSnapshotHolder.toString());
239 if (LOG.isTraceEnabled()) {
240 StringBuilder response = new StringBuilder("editConfig response = {");
241 response.append(XmlUtil.toString(editResponseMessage));
242 response.append("}");
243 response.append("commit response = {");
244 response.append(XmlUtil.toString(commitResponseMessage));
245 response.append("}");
246 LOG.trace("Last configuration loaded successfully");
247 LOG.trace("Detailed message {}", response);
248 LOG.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
250 return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
253 private NetconfOperation findOperation(NetconfMessage request, NetconfOperationService operationService) throws NetconfDocumentedException {
254 TreeMap<HandlingPriority, NetconfOperation> allOperations = new TreeMap<>();
255 Set<NetconfOperation> netconfOperations = operationService.getNetconfOperations();
256 if (netconfOperations.isEmpty()) {
257 throw new IllegalStateException("Possible code error: no config operations");
259 for (NetconfOperation netconfOperation : netconfOperations) {
260 HandlingPriority handlingPriority = netconfOperation.canHandle(request.getDocument());
261 allOperations.put(handlingPriority, netconfOperation);
263 Entry<HandlingPriority, NetconfOperation> highestEntry = allOperations.lastEntry();
264 if (highestEntry.getKey().isCannotHandle()) {
265 throw new IllegalStateException("Possible code error: operation with highest priority is CANNOT_HANDLE");
267 return highestEntry.getValue();
270 private Document sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfOperationService operationService,
271 String operationNameForReporting, String configIdForReporting)
272 throws ConflictingVersionException, NetconfDocumentedException {
274 NetconfOperation operation = findOperation(request, operationService);
277 response = operation.handle(request.getDocument(), NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
278 } catch (NetconfDocumentedException | RuntimeException e) {
279 if (e instanceof NetconfDocumentedException && e.getCause() instanceof ConflictingVersionException) {
280 throw (ConflictingVersionException) e.getCause();
282 throw new IllegalStateException("Failed to send " + operationNameForReporting +
283 " for configuration " + configIdForReporting, e);
285 return NetconfUtil.checkIsMessageOk(response);
288 // load editConfig.xml template, populate /rpc/edit-config/config with parameter
289 private static NetconfMessage createEditConfigMessage(Element dataElement) throws NetconfDocumentedException {
290 String editConfigResourcePath = "/netconfOp/editConfig.xml";
291 try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
292 checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
294 Document doc = XmlUtil.readXmlToDocument(stream);
296 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
297 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
298 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
299 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
301 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), deep));
303 editConfigElement.appendChild(configWrapper.getDomElement());
304 return new NetconfMessage(doc);
305 } catch (IOException | SAXException e) {
306 // error reading the xml file bundled into the jar
307 throw new IllegalStateException("Error while opening local resource " + editConfigResourcePath, e);
311 private static NetconfMessage getCommitMessage() {
312 String resource = "/netconfOp/commit.xml";
313 try (InputStream stream = ConfigPusherImpl.class.getResourceAsStream(resource)) {
314 checkNotNull(stream, "Unable to load resource " + resource);
315 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
316 } catch (SAXException | IOException e) {
317 // error reading the xml file bundled into the jar
318 throw new IllegalStateException("Error while opening local resource " + resource, e);
322 static class EditAndCommitResponse {
323 private final Document editResponse, commitResponse;
325 EditAndCommitResponse(Document editResponse, Document commitResponse) {
326 this.editResponse = editResponse;
327 this.commitResponse = commitResponse;
330 public Document getEditResponse() {
334 public Document getCommitResponse() {
335 return commitResponse;
339 public String toString() {
340 return "EditAndCommitResponse{" +
341 "editResponse=" + editResponse +
342 ", commitResponse=" + commitResponse +