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.TimeUnit;
27 import javax.annotation.concurrent.Immutable;
28 import org.opendaylight.controller.config.api.ConflictingVersionException;
29 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
30 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
31 import org.opendaylight.controller.netconf.api.NetconfMessage;
32 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
33 import org.opendaylight.controller.netconf.mapping.api.Capability;
34 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
35 import org.opendaylight.controller.netconf.mapping.api.NetconfOperation;
36 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
37 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
38 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
39 import org.opendaylight.controller.netconf.util.NetconfUtil;
40 import org.opendaylight.controller.netconf.util.xml.XmlElement;
41 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.w3c.dom.Document;
45 import org.w3c.dom.Element;
46 import org.xml.sax.SAXException;
49 public class ConfigPusher {
50 private static final Logger logger = LoggerFactory.getLogger(ConfigPusher.class);
52 private final long maxWaitForCapabilitiesMillis;
53 private final long conflictingVersionTimeoutMillis;
54 private final NetconfOperationServiceFactory configNetconfConnector;
56 public ConfigPusher(NetconfOperationServiceFactory configNetconfConnector, long maxWaitForCapabilitiesMillis,
57 long conflictingVersionTimeoutMillis) {
58 this.configNetconfConnector = configNetconfConnector;
59 this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
60 this.conflictingVersionTimeoutMillis = conflictingVersionTimeoutMillis;
63 public synchronized LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponse> pushConfigs(List<ConfigSnapshotHolder> configs) throws NetconfDocumentedException {
64 logger.debug("Last config snapshots to be pushed to netconf: {}", configs);
65 LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponse> result = new LinkedHashMap<>();
66 // start pushing snapshots:
67 for (ConfigSnapshotHolder configSnapshotHolder : configs) {
68 EditAndCommitResponse editAndCommitResponseWithRetries = pushConfigWithConflictingVersionRetries(configSnapshotHolder);
69 logger.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
70 result.put(configSnapshotHolder, editAndCommitResponseWithRetries);
72 logger.debug("All configuration snapshots have been pushed successfully.");
77 * First calls {@link #getOperationServiceWithRetries(java.util.Set, String)} in order to wait until
78 * expected capabilities are present, then tries to push configuration. If {@link ConflictingVersionException}
79 * is caught, whole process is retried - new service instance need to be obtained from the factory. Closes
80 * {@link NetconfOperationService} after each use.
82 private synchronized EditAndCommitResponse pushConfigWithConflictingVersionRetries(ConfigSnapshotHolder configSnapshotHolder) throws NetconfDocumentedException {
83 ConflictingVersionException lastException;
84 Stopwatch stopwatch = new Stopwatch().start();
86 String idForReporting = configSnapshotHolder.toString();
87 SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
88 "Expected capabilities must not be null - %s, check %s", idForReporting,
89 configSnapshotHolder.getClass().getName());
90 try (NetconfOperationService operationService = getOperationServiceWithRetries(expectedCapabilities, idForReporting)) {
91 return pushConfig(configSnapshotHolder, operationService);
92 } catch (ConflictingVersionException e) {
94 logger.debug("Conflicting version detected, will retry after timeout");
97 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < conflictingVersionTimeoutMillis);
98 throw new IllegalStateException("Max wait for conflicting version stabilization timeout after " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms",
102 private NetconfOperationService getOperationServiceWithRetries(Set<String> expectedCapabilities, String idForReporting) {
103 Stopwatch stopwatch = new Stopwatch().start();
104 NotEnoughCapabilitiesException lastException;
107 return getOperationService(expectedCapabilities, idForReporting);
108 } catch (NotEnoughCapabilitiesException e) {
109 logger.debug("Not enough capabilities: " + e.toString());
113 } while (stopwatch.elapsed(TimeUnit.MILLISECONDS) < maxWaitForCapabilitiesMillis);
114 throw new IllegalStateException("Max wait for capabilities reached." + lastException.getMessage(), lastException);
117 private static class NotEnoughCapabilitiesException extends Exception {
118 private static final long serialVersionUID = 1L;
120 private NotEnoughCapabilitiesException(String message, Throwable cause) {
121 super(message, cause);
124 private NotEnoughCapabilitiesException(String message) {
130 * Get NetconfOperationService iif all required capabilities are present.
132 * @param expectedCapabilities that must be provided by configNetconfConnector
133 * @param idForReporting
134 * @return service if capabilities are present, otherwise absent value
136 private NetconfOperationService getOperationService(Set<String> expectedCapabilities, String idForReporting) throws NotEnoughCapabilitiesException {
137 NetconfOperationService serviceCandidate;
139 serviceCandidate = configNetconfConnector.createService(idForReporting);
140 } catch(RuntimeException e) {
141 throw new NotEnoughCapabilitiesException("Netconf service not stable for " + idForReporting, e);
143 Set<String> notFoundDiff = computeNotFoundCapabilities(expectedCapabilities, serviceCandidate);
144 if (notFoundDiff.isEmpty()) {
145 return serviceCandidate;
147 serviceCandidate.close();
148 logger.trace("Netconf server did not provide required capabilities for {} " +
149 "Expected but not found: {}, all expected {}, current {}",
150 idForReporting, notFoundDiff, expectedCapabilities, serviceCandidate.getCapabilities()
152 throw new NotEnoughCapabilitiesException("Not enough capabilities for " + idForReporting + ". Expected but not found: " + notFoundDiff);
156 private static Set<String> computeNotFoundCapabilities(Set<String> expectedCapabilities, NetconfOperationService serviceCandidate) {
157 Collection<String> actual = Collections2.transform(serviceCandidate.getCapabilities(), new Function<Capability, String>() {
159 public String apply(Capability input) {
160 return input.getCapabilityUri();
163 Set<String> allNotFound = new HashSet<>(expectedCapabilities);
164 allNotFound.removeAll(actual);
170 private void sleep() {
173 } catch (InterruptedException e) {
174 Thread.currentThread().interrupt();
175 throw new IllegalStateException(e);
180 * Sends two RPCs to the netconf server: edit-config and commit.
182 * @param configSnapshotHolder
183 * @throws ConflictingVersionException if commit fails on optimistic lock failure inside of config-manager
184 * @throws java.lang.RuntimeException if edit-config or commit fails otherwise
186 private synchronized EditAndCommitResponse pushConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfOperationService operationService)
187 throws ConflictingVersionException, NetconfDocumentedException {
189 Element xmlToBePersisted;
191 xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
192 } catch (SAXException | IOException e) {
193 throw new IllegalStateException("Cannot parse " + configSnapshotHolder);
195 logger.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
196 Stopwatch stopwatch = new Stopwatch().start();
197 NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted);
199 Document editResponseMessage = sendRequestGetResponseCheckIsOK(editConfigMessage, operationService,
200 "edit-config", configSnapshotHolder.toString());
202 Document commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), operationService,
203 "commit", configSnapshotHolder.toString());
205 if (logger.isTraceEnabled()) {
206 StringBuilder response = new StringBuilder("editConfig response = {");
207 response.append(XmlUtil.toString(editResponseMessage));
208 response.append("}");
209 response.append("commit response = {");
210 response.append(XmlUtil.toString(commitResponseMessage));
211 response.append("}");
212 logger.trace("Last configuration loaded successfully");
213 logger.trace("Detailed message {}", response);
214 logger.trace("Total time spent {} ms", stopwatch.elapsed(TimeUnit.MILLISECONDS));
216 return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
219 private NetconfOperation findOperation(NetconfMessage request, NetconfOperationService operationService) throws NetconfDocumentedException {
220 TreeMap<HandlingPriority, NetconfOperation> allOperations = new TreeMap<>();
221 Set<NetconfOperation> netconfOperations = operationService.getNetconfOperations();
222 if (netconfOperations.isEmpty()) {
223 throw new IllegalStateException("Possible code error: no config operations");
225 for (NetconfOperation netconfOperation : netconfOperations) {
226 HandlingPriority handlingPriority = netconfOperation.canHandle(request.getDocument());
227 allOperations.put(handlingPriority, netconfOperation);
229 Entry<HandlingPriority, NetconfOperation> highestEntry = allOperations.lastEntry();
230 if (highestEntry.getKey().isCannotHandle()) {
231 throw new IllegalStateException("Possible code error: operation with highest priority is CANNOT_HANDLE");
233 return highestEntry.getValue();
236 private Document sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfOperationService operationService,
237 String operationNameForReporting, String configIdForReporting)
238 throws ConflictingVersionException, NetconfDocumentedException {
240 NetconfOperation operation = findOperation(request, operationService);
243 response = operation.handle(request.getDocument(), NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
244 } catch (NetconfDocumentedException | RuntimeException e) {
245 if (e instanceof NetconfDocumentedException && e.getCause() instanceof ConflictingVersionException) {
246 throw (ConflictingVersionException) e.getCause();
248 throw new IllegalStateException("Failed to send " + operationNameForReporting +
249 " for configuration " + configIdForReporting, e);
251 return NetconfUtil.checkIsMessageOk(response);
254 // load editConfig.xml template, populate /rpc/edit-config/config with parameter
255 private static NetconfMessage createEditConfigMessage(Element dataElement) throws NetconfDocumentedException {
256 String editConfigResourcePath = "/netconfOp/editConfig.xml";
257 try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
258 checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
260 Document doc = XmlUtil.readXmlToDocument(stream);
262 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
263 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
264 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
265 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
267 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), deep));
269 editConfigElement.appendChild(configWrapper.getDomElement());
270 return new NetconfMessage(doc);
271 } catch (IOException | SAXException e) {
272 // error reading the xml file bundled into the jar
273 throw new IllegalStateException("Error while opening local resource " + editConfigResourcePath, e);
277 private static NetconfMessage getCommitMessage() {
278 String resource = "/netconfOp/commit.xml";
279 try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
280 checkNotNull(stream, "Unable to load resource " + resource);
281 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
282 } catch (SAXException | IOException e) {
283 // error reading the xml file bundled into the jar
284 throw new IllegalStateException("Error while opening local resource " + resource, e);
288 static class EditAndCommitResponse {
289 private final Document editResponse, commitResponse;
291 EditAndCommitResponse(Document editResponse, Document commitResponse) {
292 this.editResponse = editResponse;
293 this.commitResponse = commitResponse;
296 public Document getEditResponse() {
300 public Document getCommitResponse() {
301 return commitResponse;
305 public String toString() {
306 return "EditAndCommitResponse{" +
307 "editResponse=" + editResponse +
308 ", commitResponse=" + commitResponse +