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 = TimeUnit.MINUTES.toNanos(2);
51 private final int delayMillis = 5000;
52 private final long timeoutNanos;
54 public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadgroup) {
55 this(address, nettyThreadgroup, DEFAULT_TIMEOUT);
59 public ConfigPusher(InetSocketAddress address, long timeoutMillis, EventLoopGroup nettyThreadgroup) {
60 this(address, nettyThreadgroup, TimeUnit.MILLISECONDS.toNanos(timeoutMillis));
63 public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadgroup, long timeoutNanos) {
64 this.address = address;
65 this.nettyThreadgroup = nettyThreadgroup;
66 this.timeoutNanos = timeoutNanos;
69 public synchronized NetconfClient init(List<ConfigSnapshotHolder> configs) throws InterruptedException {
70 logger.debug("Last config snapshots to be pushed to netconf: {}", configs);
71 return pushAllConfigs(configs);
74 private synchronized NetconfClient pushAllConfigs(List<ConfigSnapshotHolder> configs) throws InterruptedException {
75 // first just make sure we can connect to netconf, even if nothing is being pushed
76 NetconfClient netconfClient = makeNetconfConnection(Collections.<String>emptySet(), Optional.<NetconfClient>absent());
77 // start pushing snapshots:
78 for (ConfigSnapshotHolder configSnapshotHolder: configs){
79 netconfClient = pushSnapshotWithRetries(configSnapshotHolder, Optional.of(netconfClient));
80 logger.debug("Config snapshot pushed successfully: {}", configSnapshotHolder);
83 logger.debug("All configuration snapshots have been pushed successfully.");
87 private synchronized NetconfClient pushSnapshotWithRetries(ConfigSnapshotHolder configSnapshotHolder,
88 Optional<NetconfClient> oldClientForPossibleReuse)
89 throws InterruptedException {
91 Exception lastException = null;
93 for(int i = 0 ; i < maxAttempts; i++) {
94 NetconfClient netconfClient = makeNetconfConnection(configSnapshotHolder.getCapabilities(), oldClientForPossibleReuse);
95 logger.trace("Pushing following xml to netconf {}", configSnapshotHolder);
97 pushLastConfig(configSnapshotHolder, netconfClient);
99 } catch (ConflictingVersionException | IOException e) {
100 Util.closeClientAndDispatcher(netconfClient);
103 } catch (SAXException e) {
104 throw new IllegalStateException("Unable to load last config", e);
107 throw new IllegalStateException("Failed to push configuration, maximum attempt count has been reached: "
108 + maxAttempts, lastException);
112 * @param expectedCaps capabilities that server hello must contain. Will retry until all are found or throws RuntimeException.
113 * If empty set is provided, will only make sure netconf client successfuly connected to the server.
114 * @param maybeOldClient if present, close it.
115 * @return NetconfClient that has all required capabilities from server.
117 private synchronized NetconfClient makeNetconfConnection(Set<String> expectedCaps,
118 Optional<NetconfClient> maybeOldClient)
119 throws InterruptedException {
121 if (maybeOldClient.isPresent()) {
122 NetconfClient oldClient = maybeOldClient.get();
123 Util.closeClientAndDispatcher(oldClient);
126 // TODO think about moving capability subset check to netconf client
127 // could be utilized by integration tests
129 final long pollingStart = System.nanoTime();
130 final long deadline = pollingStart + timeoutNanos;
133 String additionalHeader = NetconfMessageAdditionalHeader.toString("unknown", address.getAddress().getHostAddress(),
134 Integer.toString(address.getPort()), "tcp", Optional.of("persister"));
136 Set<String> latestCapabilities = new HashSet<>();
137 while (System.nanoTime() < deadline) {
139 NetconfClientDispatcher netconfClientDispatcher = new NetconfClientDispatcher(nettyThreadgroup,
140 nettyThreadgroup, additionalHeader);
141 NetconfClient netconfClient;
143 netconfClient = new NetconfClient(this.toString(), address, delayMillis, netconfClientDispatcher);
144 } catch (IllegalStateException e) {
145 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
146 netconfClientDispatcher.close();
147 Thread.sleep(delayMillis);
150 latestCapabilities = netconfClient.getCapabilities();
151 if (Util.isSubset(netconfClient, expectedCaps)) {
152 logger.debug("Hello from netconf stable with {} capabilities", latestCapabilities);
153 logger.trace("Session id received from netconf server: {}", netconfClient.getClientSession());
154 return netconfClient;
156 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, latestCapabilities);
157 Util.closeClientAndDispatcher(netconfClient);
158 Thread.sleep(delayMillis);
160 Set<String> allNotFound = new HashSet<>(expectedCaps);
161 allNotFound.removeAll(latestCapabilities);
162 logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
163 allNotFound, expectedCaps, latestCapabilities);
164 throw new RuntimeException("Netconf server did not provide required capabilities. Expected but not found:" + allNotFound);
168 private synchronized void pushLastConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfClient netconfClient)
169 throws ConflictingVersionException, IOException, SAXException {
171 Element xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
172 logger.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
173 StringBuilder response = new StringBuilder("editConfig response = {");
175 NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
177 // sending message to netconf
178 NetconfMessage responseMessage = getResponse(message, netconfClient);
180 NetconfUtil.checkIsMessageOk(responseMessage);
181 response.append(XmlUtil.toString(responseMessage.getDocument()));
182 response.append("}");
183 responseMessage = getResponse(getNetconfMessageFromResource("/netconfOp/commit.xml"), netconfClient);
187 NetconfUtil.checkIsMessageOk(responseMessage);
188 response.append("commit response = {");
189 response.append(XmlUtil.toString(responseMessage.getDocument()));
190 response.append("}");
191 logger.trace("Last configuration loaded successfully");
192 logger.trace("Detailed message {}", response);
195 private static NetconfMessage getResponse(NetconfMessage request, NetconfClient netconfClient) throws IOException {
197 return netconfClient.sendMessage(request, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
198 } catch (RuntimeException e) {
199 logger.debug("Error while executing netconf transaction {} to {}", request, netconfClient, e);
200 throw new IOException("Failed to execute netconf transaction", e);
204 private static NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) throws IOException, SAXException {
205 try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcename)) {
206 Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
208 Document doc = XmlUtil.readXmlToDocument(stream);
210 doc.getDocumentElement();
211 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
212 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
213 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
214 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
215 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
217 editConfigElement.appendChild(configWrapper.getDomElement());
218 return new NetconfMessage(doc);
219 } catch (IOException | SAXException e) {
220 logger.debug("Failed to create edit-config message for resource {}", editConfigResourcename, e);
225 private static NetconfMessage getNetconfMessageFromResource(String resource) throws IOException, SAXException {
226 try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
227 Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
228 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
229 } catch (SAXException | IOException e) {
230 logger.debug("Failed to parse netconf message for resource {}", resource, e);