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 io.netty.channel.EventLoopGroup;
13 import java.io.IOException;
14 import java.io.InputStream;
15 import java.net.InetSocketAddress;
16 import java.util.Collections;
17 import java.util.HashSet;
18 import java.util.LinkedHashMap;
19 import java.util.List;
21 import java.util.concurrent.ExecutionException;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.TimeoutException;
25 import javax.annotation.concurrent.Immutable;
27 import org.opendaylight.controller.config.api.ConflictingVersionException;
28 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
29 import org.opendaylight.controller.netconf.api.NetconfMessage;
30 import org.opendaylight.controller.netconf.client.NetconfClient;
31 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
32 import org.opendaylight.controller.netconf.util.NetconfUtil;
33 import org.opendaylight.controller.netconf.util.messages.NetconfMessageAdditionalHeader;
34 import org.opendaylight.controller.netconf.util.xml.XmlElement;
35 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
36 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.w3c.dom.Document;
40 import org.w3c.dom.Element;
41 import org.xml.sax.SAXException;
43 import com.google.common.base.Optional;
44 import com.google.common.base.Preconditions;
47 public class ConfigPusher {
48 private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
49 private static final int NETCONF_SEND_ATTEMPT_MS_DELAY = 1000;
50 private static final int NETCONF_SEND_ATTEMPTS = 20;
52 private final InetSocketAddress address;
53 private final EventLoopGroup nettyThreadGroup;
55 // Default timeout for netconf becoming stable
56 public static final long DEFAULT_MAX_WAIT_FOR_CAPABILITIES_MILLIS = TimeUnit.MINUTES.toMillis(2);
57 public static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = 5000;
58 private final int delayMillis = 5000;
59 private final long maxWaitForCapabilitiesMillis;
60 private final long connectionTimeoutMillis;
62 public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadGroup) {
63 this(address, nettyThreadGroup, DEFAULT_MAX_WAIT_FOR_CAPABILITIES_MILLIS, DEFAULT_CONNECTION_TIMEOUT_MILLIS);
66 public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadGroup,
67 long maxWaitForCapabilitiesMillis, long connectionTimeoutMillis) {
68 this.address = address;
69 this.nettyThreadGroup = nettyThreadGroup;
70 this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
71 this.connectionTimeoutMillis = connectionTimeoutMillis;
74 public synchronized LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponseWithRetries> pushConfigs(
75 List<ConfigSnapshotHolder> configs) throws InterruptedException {
76 logger.debug("Last config snapshots to be pushed to netconf: {}", configs);
78 // first just make sure we can connect to netconf, even if nothing is being pushed
80 NetconfClient netconfClient = makeNetconfConnection(Collections.<String>emptySet());
81 Util.closeClientAndDispatcher(netconfClient);
83 LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponseWithRetries> result = new LinkedHashMap<>();
84 // start pushing snapshots:
85 for (ConfigSnapshotHolder configSnapshotHolder : configs) {
86 EditAndCommitResponseWithRetries editAndCommitResponseWithRetries = pushSnapshotWithRetries(configSnapshotHolder);
87 logger.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
88 result.put(configSnapshotHolder, editAndCommitResponseWithRetries);
90 logger.debug("All configuration snapshots have been pushed successfully.");
95 * Checks for ConflictingVersionException and retries until optimistic lock succeeds or maximal
96 * number of attempts is reached.
98 private synchronized EditAndCommitResponseWithRetries pushSnapshotWithRetries(ConfigSnapshotHolder configSnapshotHolder)
99 throws InterruptedException {
101 ConflictingVersionException lastException = null;
102 int maxAttempts = 30;
104 for (int retryAttempt = 1; retryAttempt <= maxAttempts; retryAttempt++) {
105 NetconfClient netconfClient = makeNetconfConnection(configSnapshotHolder.getCapabilities());
106 logger.trace("Pushing following xml to netconf {}", configSnapshotHolder);
108 EditAndCommitResponse editAndCommitResponse = pushLastConfig(configSnapshotHolder, netconfClient);
109 return new EditAndCommitResponseWithRetries(editAndCommitResponse, retryAttempt);
110 } catch (ConflictingVersionException e) {
113 } catch (RuntimeException e) {
114 throw new IllegalStateException("Unable to load " + configSnapshotHolder, e);
116 Util.closeClientAndDispatcher(netconfClient);
119 throw new IllegalStateException("Maximum attempt count has been reached for pushing " + configSnapshotHolder,
124 * @param expectedCaps capabilities that server hello must contain. Will retry until all are found or throws RuntimeException.
125 * If empty set is provided, will only make sure netconf client successfuly connected to the server.
126 * @return NetconfClient that has all required capabilities from server.
128 private synchronized NetconfClient makeNetconfConnection(Set<String> expectedCaps) throws InterruptedException {
130 // TODO think about moving capability subset check to netconf client
131 // could be utilized by integration tests
133 final long pollingStartNanos = System.nanoTime();
134 final long deadlineNanos = pollingStartNanos + TimeUnit.MILLISECONDS.toNanos(maxWaitForCapabilitiesMillis);
137 String additionalHeader = NetconfMessageAdditionalHeader.toString("unknown", address.getAddress().getHostAddress(),
138 Integer.toString(address.getPort()), "tcp", Optional.of("persister"));
140 Set<String> latestCapabilities = null;
141 while (System.nanoTime() < deadlineNanos) {
143 NetconfClientDispatcher netconfClientDispatcher = new NetconfClientDispatcher(nettyThreadGroup,
144 nettyThreadGroup, additionalHeader, connectionTimeoutMillis);
145 NetconfClient netconfClient;
147 netconfClient = new NetconfClient(this.toString(), address, delayMillis, netconfClientDispatcher);
148 } catch (IllegalStateException e) {
149 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
150 netconfClientDispatcher.close();
151 Thread.sleep(delayMillis);
154 latestCapabilities = netconfClient.getCapabilities();
155 if (Util.isSubset(netconfClient, expectedCaps)) {
156 logger.debug("Hello from netconf stable with {} capabilities", latestCapabilities);
157 logger.trace("Session id received from netconf server: {}", netconfClient.getClientSession());
158 return netconfClient;
160 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, latestCapabilities);
161 Util.closeClientAndDispatcher(netconfClient);
162 Thread.sleep(delayMillis);
164 if (latestCapabilities == null) {
165 logger.error("Could not connect to the server in {} ms", maxWaitForCapabilitiesMillis);
166 throw new RuntimeException("Could not connect to netconf server");
168 Set<String> allNotFound = new HashSet<>(expectedCaps);
169 allNotFound.removeAll(latestCapabilities);
170 logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
171 allNotFound, expectedCaps, latestCapabilities);
172 throw new RuntimeException("Netconf server did not provide required capabilities. Expected but not found:" + allNotFound);
177 * Sends two RPCs to the netconf server: edit-config and commit.
179 * @param configSnapshotHolder
180 * @param netconfClient
181 * @throws ConflictingVersionException if commit fails on optimistic lock failure inside of config-manager
182 * @throws java.lang.RuntimeException if edit-config or commit fails otherwise
184 private synchronized EditAndCommitResponse pushLastConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfClient netconfClient)
185 throws ConflictingVersionException {
187 Element xmlToBePersisted;
189 xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
190 } catch (SAXException | IOException e) {
191 throw new IllegalStateException("Cannot parse " + configSnapshotHolder);
193 logger.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
195 NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted);
197 // sending message to netconf
198 NetconfMessage editResponseMessage;
200 editResponseMessage = sendRequestGetResponseCheckIsOK(editConfigMessage, netconfClient);
201 } catch (IOException e) {
202 throw new IllegalStateException("Edit-config failed on " + configSnapshotHolder, e);
206 NetconfMessage commitResponseMessage;
208 commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), netconfClient);
209 } catch (IOException e) {
210 throw new IllegalStateException("Edit commit succeeded, but commit failed on " + configSnapshotHolder, e);
213 if (logger.isTraceEnabled()) {
214 StringBuilder response = new StringBuilder("editConfig response = {");
215 response.append(XmlUtil.toString(editResponseMessage.getDocument()));
216 response.append("}");
217 response.append("commit response = {");
218 response.append(XmlUtil.toString(commitResponseMessage.getDocument()));
219 response.append("}");
220 logger.trace("Last configuration loaded successfully");
221 logger.trace("Detailed message {}", response);
223 return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
227 private static NetconfMessage sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfClient netconfClient) throws IOException {
229 NetconfMessage netconfMessage = netconfClient.sendMessage(request, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
230 NetconfUtil.checkIsMessageOk(netconfMessage);
231 return netconfMessage;
232 } catch (RuntimeException | ExecutionException | InterruptedException | TimeoutException e) {
233 logger.debug("Error while executing netconf transaction {} to {}", request, netconfClient, e);
234 throw new IOException("Failed to execute netconf transaction", e);
238 // load editConfig.xml template, populate /rpc/edit-config/config with parameter
239 private static NetconfMessage createEditConfigMessage(Element dataElement) {
240 String editConfigResourcePath = "/netconfOp/editConfig.xml";
241 try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
242 Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
244 Document doc = XmlUtil.readXmlToDocument(stream);
246 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
247 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
248 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
249 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
251 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), deep));
253 editConfigElement.appendChild(configWrapper.getDomElement());
254 return new NetconfMessage(doc);
255 } catch (IOException | SAXException e) {
256 // error reading the xml file bundled into the jar
257 throw new RuntimeException("Error while opening local resource " + editConfigResourcePath, e);
261 private static NetconfMessage getCommitMessage() {
262 String resource = "/netconfOp/commit.xml";
263 try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
264 Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
265 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
266 } catch (SAXException | IOException e) {
267 // error reading the xml file bundled into the jar
268 throw new RuntimeException("Error while opening local resource " + resource, e);
272 static class EditAndCommitResponse {
273 private final NetconfMessage editResponse, commitResponse;
275 EditAndCommitResponse(NetconfMessage editResponse, NetconfMessage commitResponse) {
276 this.editResponse = editResponse;
277 this.commitResponse = commitResponse;
280 public NetconfMessage getEditResponse() {
284 public NetconfMessage getCommitResponse() {
285 return commitResponse;
289 public String toString() {
290 return "EditAndCommitResponse{" +
291 "editResponse=" + editResponse +
292 ", commitResponse=" + commitResponse +
298 static class EditAndCommitResponseWithRetries {
299 private final EditAndCommitResponse editAndCommitResponse;
300 private final int retries;
302 EditAndCommitResponseWithRetries(EditAndCommitResponse editAndCommitResponse, int retries) {
303 this.editAndCommitResponse = editAndCommitResponse;
304 this.retries = retries;
307 public int getRetries() {
311 public EditAndCommitResponse getEditAndCommitResponse() {
312 return editAndCommitResponse;
316 public String toString() {
317 return "EditAndCommitResponseWithRetries{" +
318 "editAndCommitResponse=" + editAndCommitResponse +
319 ", retries=" + retries +