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));
84 private synchronized NetconfClient pushSnapshotWithRetries(ConfigSnapshotHolder configSnapshotHolder,
85 Optional<NetconfClient> oldClientForPossibleReuse)
86 throws InterruptedException {
88 ConflictingVersionException lastException = null;
90 for(int i = 0 ; i < maxAttempts; i++) {
91 NetconfClient netconfClient = makeNetconfConnection(configSnapshotHolder.getCapabilities(), oldClientForPossibleReuse);
92 logger.trace("Pushing following xml to netconf {}", configSnapshotHolder);
94 pushLastConfig(configSnapshotHolder, netconfClient);
96 } catch(ConflictingVersionException e) {
97 Util.closeClientAndDispatcher(netconfClient);
100 } catch (SAXException | IOException e) {
101 throw new IllegalStateException("Unable to load last config", e);
104 throw new IllegalStateException("Failed to push configuration, maximum attempt count has been reached: "
105 + maxAttempts, lastException);
109 * @param expectedCaps capabilities that server hello must contain. Will retry until all are found or throws RuntimeException.
110 * If empty set is provided, will only make sure netconf client successfuly connected to the server.
111 * @param maybeOldClient if present, close it.
112 * @return NetconfClient that has all required capabilities from server.
114 private synchronized NetconfClient makeNetconfConnection(Set<String> expectedCaps,
115 Optional<NetconfClient> maybeOldClient)
116 throws InterruptedException {
118 if (maybeOldClient.isPresent()) {
119 NetconfClient oldClient = maybeOldClient.get();
120 Util.closeClientAndDispatcher(oldClient);
123 // TODO think about moving capability subset check to netconf client
124 // could be utilized by integration tests
126 final long pollingStart = System.nanoTime();
127 final long deadline = pollingStart + timeoutNanos;
130 String additionalHeader = NetconfMessageAdditionalHeader.toString("unknown", address.getAddress().getHostAddress(),
131 Integer.toString(address.getPort()), "tcp", Optional.of("persister"));
133 Set<String> latestCapabilities = new HashSet<>();
134 while (System.nanoTime() < deadline) {
136 NetconfClientDispatcher netconfClientDispatcher = new NetconfClientDispatcher(nettyThreadgroup,
137 nettyThreadgroup, additionalHeader);
138 NetconfClient netconfClient;
140 netconfClient = new NetconfClient(this.toString(), address, delayMillis, netconfClientDispatcher);
141 } catch (IllegalStateException e) {
142 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
143 netconfClientDispatcher.close();
144 Thread.sleep(delayMillis);
147 latestCapabilities = netconfClient.getCapabilities();
148 if (Util.isSubset(netconfClient, expectedCaps)) {
149 logger.debug("Hello from netconf stable with {} capabilities", latestCapabilities);
150 logger.trace("Session id received from netconf server: {}", netconfClient.getClientSession());
151 return netconfClient;
153 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, latestCapabilities);
154 Util.closeClientAndDispatcher(netconfClient);
155 Thread.sleep(delayMillis);
157 Set<String> allNotFound = new HashSet<>(expectedCaps);
158 allNotFound.removeAll(latestCapabilities);
159 logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
160 allNotFound, expectedCaps, latestCapabilities);
161 throw new RuntimeException("Netconf server did not provide required capabilities. Expected but not found:" + allNotFound);
165 private synchronized void pushLastConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfClient netconfClient)
166 throws ConflictingVersionException, IOException, SAXException {
168 Element xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
169 logger.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
170 StringBuilder response = new StringBuilder("editConfig response = {");
172 NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
174 // sending message to netconf
175 NetconfMessage responseMessage = getResponse(message, netconfClient);
177 NetconfUtil.checkIsMessageOk(responseMessage);
178 response.append(XmlUtil.toString(responseMessage.getDocument()));
179 response.append("}");
180 responseMessage = getResponse(getNetconfMessageFromResource("/netconfOp/commit.xml"), netconfClient);
184 NetconfUtil.checkIsMessageOk(responseMessage);
185 response.append("commit response = {");
186 response.append(XmlUtil.toString(responseMessage.getDocument()));
187 response.append("}");
188 logger.trace("Last configuration loaded successfully");
189 logger.trace("Detailed message {}", response);
192 private static NetconfMessage getResponse(NetconfMessage request, NetconfClient netconfClient) {
194 return netconfClient.sendMessage(request, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
195 } catch(RuntimeException e) {
196 logger.error("Error while sending message {} to {}", request, netconfClient);
201 private static NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
202 try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcename)) {
203 Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
205 Document doc = XmlUtil.readXmlToDocument(stream);
207 doc.getDocumentElement();
208 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
209 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
210 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
211 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
212 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
214 editConfigElement.appendChild(configWrapper.getDomElement());
215 return new NetconfMessage(doc);
216 } catch (IOException | SAXException e) {
217 throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
221 private static NetconfMessage getNetconfMessageFromResource(String resource) {
222 try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
223 Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
224 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
225 } catch (SAXException | IOException e) {
226 throw new RuntimeException("Unable to parse message from resources " + resource, e);