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 com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import io.netty.channel.EventLoopGroup;
14 import org.opendaylight.controller.config.api.ConflictingVersionException;
15 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
16 import org.opendaylight.controller.netconf.api.NetconfMessage;
17 import org.opendaylight.controller.netconf.client.NetconfClient;
18 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
19 import org.opendaylight.controller.netconf.util.NetconfUtil;
20 import org.opendaylight.controller.netconf.util.messages.NetconfMessageAdditionalHeader;
21 import org.opendaylight.controller.netconf.util.xml.XmlElement;
22 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
23 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26 import org.w3c.dom.Document;
27 import org.w3c.dom.Element;
28 import org.xml.sax.SAXException;
30 import javax.annotation.concurrent.Immutable;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.net.InetSocketAddress;
34 import java.util.Collections;
35 import java.util.HashSet;
36 import java.util.LinkedHashMap;
37 import java.util.List;
39 import java.util.concurrent.TimeUnit;
42 public class ConfigPusher {
43 private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
44 private static final int NETCONF_SEND_ATTEMPT_MS_DELAY = 1000;
45 private static final int NETCONF_SEND_ATTEMPTS = 20;
47 private final InetSocketAddress address;
48 private final EventLoopGroup nettyThreadGroup;
50 // Default timeout for netconf becoming stable
51 public static final long DEFAULT_MAX_WAIT_FOR_CAPABILITIES_MILLIS = TimeUnit.MINUTES.toMillis(2);
52 public static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = 5000;
53 private final int delayMillis = 5000;
54 private final long maxWaitForCapabilitiesMillis;
55 private final long connectionTimeoutMillis;
57 public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadGroup) {
58 this(address, nettyThreadGroup, DEFAULT_MAX_WAIT_FOR_CAPABILITIES_MILLIS, DEFAULT_CONNECTION_TIMEOUT_MILLIS);
61 public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadGroup,
62 long maxWaitForCapabilitiesMillis, long connectionTimeoutMillis) {
63 this.address = address;
64 this.nettyThreadGroup = nettyThreadGroup;
65 this.maxWaitForCapabilitiesMillis = maxWaitForCapabilitiesMillis;
66 this.connectionTimeoutMillis = connectionTimeoutMillis;
69 public synchronized LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponseWithRetries> pushConfigs(
70 List<ConfigSnapshotHolder> configs) throws InterruptedException {
71 logger.debug("Last config snapshots to be pushed to netconf: {}", configs);
73 // first just make sure we can connect to netconf, even if nothing is being pushed
75 NetconfClient netconfClient = makeNetconfConnection(Collections.<String>emptySet());
76 Util.closeClientAndDispatcher(netconfClient);
78 LinkedHashMap<ConfigSnapshotHolder, EditAndCommitResponseWithRetries> result = new LinkedHashMap<>();
79 // start pushing snapshots:
80 for (ConfigSnapshotHolder configSnapshotHolder : configs) {
81 EditAndCommitResponseWithRetries editAndCommitResponseWithRetries = pushSnapshotWithRetries(configSnapshotHolder);
82 logger.debug("Config snapshot pushed successfully: {}, result: {}", configSnapshotHolder, result);
83 result.put(configSnapshotHolder, editAndCommitResponseWithRetries);
85 logger.debug("All configuration snapshots have been pushed successfully.");
90 * Checks for ConflictingVersionException and retries until optimistic lock succeeds or maximal
91 * number of attempts is reached.
93 private synchronized EditAndCommitResponseWithRetries pushSnapshotWithRetries(ConfigSnapshotHolder configSnapshotHolder)
94 throws InterruptedException {
96 ConflictingVersionException lastException = null;
99 for (int retryAttempt = 1; retryAttempt <= maxAttempts; retryAttempt++) {
100 NetconfClient netconfClient = makeNetconfConnection(configSnapshotHolder.getCapabilities());
101 logger.trace("Pushing following xml to netconf {}", configSnapshotHolder);
103 EditAndCommitResponse editAndCommitResponse = pushLastConfig(configSnapshotHolder, netconfClient);
104 return new EditAndCommitResponseWithRetries(editAndCommitResponse, retryAttempt);
105 } catch (ConflictingVersionException e) {
108 } catch (RuntimeException e) {
109 throw new IllegalStateException("Unable to load " + configSnapshotHolder, e);
111 Util.closeClientAndDispatcher(netconfClient);
114 throw new IllegalStateException("Maximum attempt count has been reached for pushing " + configSnapshotHolder,
119 * @param expectedCaps capabilities that server hello must contain. Will retry until all are found or throws RuntimeException.
120 * If empty set is provided, will only make sure netconf client successfuly connected to the server.
121 * @return NetconfClient that has all required capabilities from server.
123 private synchronized NetconfClient makeNetconfConnection(Set<String> expectedCaps) throws InterruptedException {
125 // TODO think about moving capability subset check to netconf client
126 // could be utilized by integration tests
128 final long pollingStartNanos = System.nanoTime();
129 final long deadlineNanos = pollingStartNanos + TimeUnit.MILLISECONDS.toNanos(maxWaitForCapabilitiesMillis);
132 String additionalHeader = NetconfMessageAdditionalHeader.toString("unknown", address.getAddress().getHostAddress(),
133 Integer.toString(address.getPort()), "tcp", Optional.of("persister"));
135 Set<String> latestCapabilities = null;
136 while (System.nanoTime() < deadlineNanos) {
138 NetconfClientDispatcher netconfClientDispatcher = new NetconfClientDispatcher(nettyThreadGroup,
139 nettyThreadGroup, additionalHeader, connectionTimeoutMillis);
140 NetconfClient netconfClient;
142 netconfClient = new NetconfClient(this.toString(), address, delayMillis, netconfClientDispatcher);
143 } catch (IllegalStateException e) {
144 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
145 netconfClientDispatcher.close();
146 Thread.sleep(delayMillis);
149 latestCapabilities = netconfClient.getCapabilities();
150 if (Util.isSubset(netconfClient, expectedCaps)) {
151 logger.debug("Hello from netconf stable with {} capabilities", latestCapabilities);
152 logger.trace("Session id received from netconf server: {}", netconfClient.getClientSession());
153 return netconfClient;
155 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, latestCapabilities);
156 Util.closeClientAndDispatcher(netconfClient);
157 Thread.sleep(delayMillis);
159 if (latestCapabilities == null) {
160 logger.error("Could not connect to the server in {} ms", maxWaitForCapabilitiesMillis);
161 throw new RuntimeException("Could not connect to netconf server");
163 Set<String> allNotFound = new HashSet<>(expectedCaps);
164 allNotFound.removeAll(latestCapabilities);
165 logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
166 allNotFound, expectedCaps, latestCapabilities);
167 throw new RuntimeException("Netconf server did not provide required capabilities. Expected but not found:" + allNotFound);
172 * Sends two RPCs to the netconf server: edit-config and commit.
174 * @param configSnapshotHolder
175 * @param netconfClient
176 * @throws ConflictingVersionException if commit fails on optimistic lock failure inside of config-manager
177 * @throws java.lang.RuntimeException if edit-config or commit fails otherwise
179 private synchronized EditAndCommitResponse pushLastConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfClient netconfClient)
180 throws ConflictingVersionException {
182 Element xmlToBePersisted;
184 xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
185 } catch (SAXException | IOException e) {
186 throw new IllegalStateException("Cannot parse " + configSnapshotHolder);
188 logger.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
190 NetconfMessage editConfigMessage = createEditConfigMessage(xmlToBePersisted);
192 // sending message to netconf
193 NetconfMessage editResponseMessage;
195 editResponseMessage = sendRequestGetResponseCheckIsOK(editConfigMessage, netconfClient);
196 } catch (IOException e) {
197 throw new IllegalStateException("Edit-config failed on " + configSnapshotHolder, e);
201 NetconfMessage commitResponseMessage;
203 commitResponseMessage = sendRequestGetResponseCheckIsOK(getCommitMessage(), netconfClient);
204 } catch (IOException e) {
205 throw new IllegalStateException("Edit commit succeeded, but commit failed on " + configSnapshotHolder, e);
208 if (logger.isTraceEnabled()) {
209 StringBuilder response = new StringBuilder("editConfig response = {");
210 response.append(XmlUtil.toString(editResponseMessage.getDocument()));
211 response.append("}");
212 response.append("commit response = {");
213 response.append(XmlUtil.toString(commitResponseMessage.getDocument()));
214 response.append("}");
215 logger.trace("Last configuration loaded successfully");
216 logger.trace("Detailed message {}", response);
218 return new EditAndCommitResponse(editResponseMessage, commitResponseMessage);
222 private static NetconfMessage sendRequestGetResponseCheckIsOK(NetconfMessage request, NetconfClient netconfClient) throws IOException {
224 NetconfMessage netconfMessage = netconfClient.sendMessage(request, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
225 NetconfUtil.checkIsMessageOk(netconfMessage);
226 return netconfMessage;
227 } catch (RuntimeException e) { // TODO: change NetconfClient#sendMessage to throw checked exceptions
228 logger.debug("Error while executing netconf transaction {} to {}", request, netconfClient, e);
229 throw new IOException("Failed to execute netconf transaction", e);
234 // load editConfig.xml template, populate /rpc/edit-config/config with parameter
235 private static NetconfMessage createEditConfigMessage(Element dataElement) {
236 String editConfigResourcePath = "/netconfOp/editConfig.xml";
237 try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
238 Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
240 Document doc = XmlUtil.readXmlToDocument(stream);
242 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
243 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
244 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
245 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
247 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), deep));
249 editConfigElement.appendChild(configWrapper.getDomElement());
250 return new NetconfMessage(doc);
251 } catch (IOException | SAXException e) {
252 // error reading the xml file bundled into the jar
253 throw new RuntimeException("Error while opening local resource " + editConfigResourcePath, e);
257 private static NetconfMessage getCommitMessage() {
258 String resource = "/netconfOp/commit.xml";
259 try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
260 Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
261 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
262 } catch (SAXException | IOException e) {
263 // error reading the xml file bundled into the jar
264 throw new RuntimeException("Error while opening local resource " + resource, e);
268 static class EditAndCommitResponse {
269 private final NetconfMessage editResponse, commitResponse;
271 EditAndCommitResponse(NetconfMessage editResponse, NetconfMessage commitResponse) {
272 this.editResponse = editResponse;
273 this.commitResponse = commitResponse;
276 public NetconfMessage getEditResponse() {
280 public NetconfMessage getCommitResponse() {
281 return commitResponse;
285 public String toString() {
286 return "EditAndCommitResponse{" +
287 "editResponse=" + editResponse +
288 ", commitResponse=" + commitResponse +
294 static class EditAndCommitResponseWithRetries {
295 private final EditAndCommitResponse editAndCommitResponse;
296 private final int retries;
298 EditAndCommitResponseWithRetries(EditAndCommitResponse editAndCommitResponse, int retries) {
299 this.editAndCommitResponse = editAndCommitResponse;
300 this.retries = retries;
303 public int getRetries() {
307 public EditAndCommitResponse getEditAndCommitResponse() {
308 return editAndCommitResponse;
312 public String toString() {
313 return "EditAndCommitResponseWithRetries{" +
314 "editAndCommitResponse=" + editAndCommitResponse +
315 ", retries=" + retries +