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.List;
38 import java.util.concurrent.TimeUnit;
41 public class ConfigPusher {
42 private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
43 private static final int NETCONF_SEND_ATTEMPT_MS_DELAY = 1000;
44 private static final int NETCONF_SEND_ATTEMPTS = 20;
46 private final InetSocketAddress address;
47 private final EventLoopGroup nettyThreadgroup;
49 // Default timeout for netconf becoming stable
50 public static final long DEFAULT_TIMEOUT_NANOS = TimeUnit.MINUTES.toNanos(2);
51 private static final long DEFAULT_CONNECTION_TIMEOUT_MILLIS = 5000;
52 private final int delayMillis = 5000;
53 private final long timeoutNanos;
54 private final long connectionTimeoutMillis;
56 public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadgroup) {
57 this(address, nettyThreadgroup, DEFAULT_TIMEOUT_NANOS, DEFAULT_CONNECTION_TIMEOUT_MILLIS);
60 public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadgroup, long timeoutNanos, long connectionTimeoutMillis) {
61 this.address = address;
62 this.nettyThreadgroup = nettyThreadgroup;
63 this.timeoutNanos = timeoutNanos;
64 this.connectionTimeoutMillis = connectionTimeoutMillis;
67 public synchronized NetconfClient init(List<ConfigSnapshotHolder> configs) throws InterruptedException {
68 logger.debug("Last config snapshots to be pushed to netconf: {}", configs);
69 return pushAllConfigs(configs);
72 private synchronized NetconfClient pushAllConfigs(List<ConfigSnapshotHolder> configs) throws InterruptedException {
73 // first just make sure we can connect to netconf, even if nothing is being pushed
74 NetconfClient netconfClient = makeNetconfConnection(Collections.<String>emptySet(), Optional.<NetconfClient>absent());
75 // start pushing snapshots:
76 for (ConfigSnapshotHolder configSnapshotHolder: configs){
77 netconfClient = pushSnapshotWithRetries(configSnapshotHolder, Optional.of(netconfClient));
78 logger.debug("Config snapshot pushed successfully: {}", configSnapshotHolder);
81 logger.debug("All configuration snapshots have been pushed successfully.");
85 private synchronized NetconfClient pushSnapshotWithRetries(ConfigSnapshotHolder configSnapshotHolder,
86 Optional<NetconfClient> oldClientForPossibleReuse)
87 throws InterruptedException {
89 Exception lastException = null;
91 for(int i = 0 ; i < maxAttempts; i++) {
92 NetconfClient netconfClient = makeNetconfConnection(configSnapshotHolder.getCapabilities(), oldClientForPossibleReuse);
93 logger.trace("Pushing following xml to netconf {}", configSnapshotHolder);
95 pushLastConfig(configSnapshotHolder, netconfClient);
97 } catch (ConflictingVersionException | IOException e) {
98 Util.closeClientAndDispatcher(netconfClient);
101 } catch (SAXException e) {
102 throw new IllegalStateException("Unable to load last config", e);
105 throw new IllegalStateException("Failed to push configuration, maximum attempt count has been reached: "
106 + maxAttempts, lastException);
110 * @param expectedCaps capabilities that server hello must contain. Will retry until all are found or throws RuntimeException.
111 * If empty set is provided, will only make sure netconf client successfuly connected to the server.
112 * @param maybeOldClient if present, close it.
113 * @return NetconfClient that has all required capabilities from server.
115 private synchronized NetconfClient makeNetconfConnection(Set<String> expectedCaps,
116 Optional<NetconfClient> maybeOldClient)
117 throws InterruptedException {
119 if (maybeOldClient.isPresent()) {
120 NetconfClient oldClient = maybeOldClient.get();
121 Util.closeClientAndDispatcher(oldClient);
124 // TODO think about moving capability subset check to netconf client
125 // could be utilized by integration tests
127 final long pollingStart = System.nanoTime();
128 final long deadline = pollingStart + timeoutNanos;
131 String additionalHeader = NetconfMessageAdditionalHeader.toString("unknown", address.getAddress().getHostAddress(),
132 Integer.toString(address.getPort()), "tcp", Optional.of("persister"));
134 Set<String> latestCapabilities = null;
135 while (System.nanoTime() < deadline) {
137 NetconfClientDispatcher netconfClientDispatcher = new NetconfClientDispatcher(nettyThreadgroup,
138 nettyThreadgroup, additionalHeader, connectionTimeoutMillis);
139 NetconfClient netconfClient;
141 netconfClient = new NetconfClient(this.toString(), address, delayMillis, netconfClientDispatcher);
142 } catch (IllegalStateException e) {
143 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
144 netconfClientDispatcher.close();
145 Thread.sleep(delayMillis);
148 latestCapabilities = netconfClient.getCapabilities();
149 if (Util.isSubset(netconfClient, expectedCaps)) {
150 logger.debug("Hello from netconf stable with {} capabilities", latestCapabilities);
151 logger.trace("Session id received from netconf server: {}", netconfClient.getClientSession());
152 return netconfClient;
154 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, latestCapabilities);
155 Util.closeClientAndDispatcher(netconfClient);
156 Thread.sleep(delayMillis);
158 if (latestCapabilities == null) {
159 logger.error("Could not connect to the server in {} ms", timeoutNanos / 1000);
160 throw new RuntimeException("Could not connect to netconf server");
162 Set<String> allNotFound = new HashSet<>(expectedCaps);
163 allNotFound.removeAll(latestCapabilities);
164 logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
165 allNotFound, expectedCaps, latestCapabilities);
166 throw new RuntimeException("Netconf server did not provide required capabilities. Expected but not found:" + allNotFound);
170 private synchronized void pushLastConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfClient netconfClient)
171 throws ConflictingVersionException, IOException, SAXException {
173 Element xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
174 logger.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
175 StringBuilder response = new StringBuilder("editConfig response = {");
177 NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
179 // sending message to netconf
180 NetconfMessage responseMessage = getResponse(message, netconfClient);
182 NetconfUtil.checkIsMessageOk(responseMessage);
183 response.append(XmlUtil.toString(responseMessage.getDocument()));
184 response.append("}");
185 responseMessage = getResponse(getNetconfMessageFromResource("/netconfOp/commit.xml"), netconfClient);
189 NetconfUtil.checkIsMessageOk(responseMessage);
190 response.append("commit response = {");
191 response.append(XmlUtil.toString(responseMessage.getDocument()));
192 response.append("}");
193 logger.trace("Last configuration loaded successfully");
194 logger.trace("Detailed message {}", response);
197 private static NetconfMessage getResponse(NetconfMessage request, NetconfClient netconfClient) throws IOException {
199 return netconfClient.sendMessage(request, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
200 } catch (RuntimeException e) {
201 logger.debug("Error while executing netconf transaction {} to {}", request, netconfClient, e);
202 throw new IOException("Failed to execute netconf transaction", e);
206 private static NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) throws IOException, SAXException {
207 try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcename)) {
208 Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
210 Document doc = XmlUtil.readXmlToDocument(stream);
212 doc.getDocumentElement();
213 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
214 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
215 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
216 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
217 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
219 editConfigElement.appendChild(configWrapper.getDomElement());
220 return new NetconfMessage(doc);
221 } catch (IOException | SAXException e) {
222 logger.debug("Failed to create edit-config message for resource {}", editConfigResourcename, e);
227 private static NetconfMessage getNetconfMessageFromResource(String resource) throws IOException, SAXException {
228 try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
229 Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
230 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
231 } catch (SAXException | IOException e) {
232 logger.debug("Failed to parse netconf message for resource {}", resource, e);