Merge "Gerrit contains following fixes: 1) Fix for bug 284 - Added custom ip matching...
[controller.git] / opendaylight / netconf / config-persister-impl / src / main / java / org / opendaylight / controller / netconf / persist / impl / ConfigPusher.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.netconf.persist.impl;
10
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;
29
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;
37 import java.util.Set;
38 import java.util.concurrent.TimeUnit;
39
40 @Immutable
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;
45
46     private final InetSocketAddress address;
47     private final EventLoopGroup nettyThreadgroup;
48
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;
53
54     public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadgroup) {
55         this(address, nettyThreadgroup, DEFAULT_TIMEOUT);
56     }
57
58     @Deprecated
59     public ConfigPusher(InetSocketAddress address, long timeoutMillis, EventLoopGroup nettyThreadgroup) {
60         this(address, nettyThreadgroup, TimeUnit.MILLISECONDS.toNanos(timeoutMillis));
61     }
62
63     public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadgroup, long timeoutNanos) {
64         this.address = address;
65         this.nettyThreadgroup = nettyThreadgroup;
66         this.timeoutNanos = timeoutNanos;
67     }
68
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);
72     }
73
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);
81         }
82
83         logger.debug("All configuration snapshots have been pushed successfully.");
84         return netconfClient;
85     }
86
87     private synchronized NetconfClient pushSnapshotWithRetries(ConfigSnapshotHolder configSnapshotHolder,
88                                                                Optional<NetconfClient> oldClientForPossibleReuse)
89             throws InterruptedException {
90
91         ConflictingVersionException lastException = null;
92         int maxAttempts = 30;
93         for(int i = 0 ; i < maxAttempts; i++) {
94             NetconfClient netconfClient = makeNetconfConnection(configSnapshotHolder.getCapabilities(), oldClientForPossibleReuse);
95             logger.trace("Pushing following xml to netconf {}", configSnapshotHolder);
96             try {
97                 pushLastConfig(configSnapshotHolder, netconfClient);
98                 return netconfClient;
99             } catch(ConflictingVersionException e) {
100                 Util.closeClientAndDispatcher(netconfClient);
101                 lastException = e;
102                 Thread.sleep(1000);
103             } catch (SAXException | IOException e) {
104                 throw new IllegalStateException("Unable to load last config", e);
105             }
106         }
107         throw new IllegalStateException("Failed to push configuration, maximum attempt count has been reached: "
108                 + maxAttempts, lastException);
109     }
110
111     /**
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.
116      */
117     private synchronized NetconfClient makeNetconfConnection(Set<String> expectedCaps,
118                                                              Optional<NetconfClient> maybeOldClient)
119             throws InterruptedException {
120
121         if (maybeOldClient.isPresent()) {
122             NetconfClient oldClient = maybeOldClient.get();
123             Util.closeClientAndDispatcher(oldClient);
124         }
125
126         // TODO think about moving capability subset check to netconf client
127         // could be utilized by integration tests
128
129         final long pollingStart = System.nanoTime();
130         final long deadline = pollingStart + timeoutNanos;
131         int attempt = 0;
132
133         String additionalHeader = NetconfMessageAdditionalHeader.toString("unknown", address.getAddress().getHostAddress(),
134                 Integer.toString(address.getPort()), "tcp", Optional.of("persister"));
135
136         Set<String> latestCapabilities = new HashSet<>();
137         while (System.nanoTime() < deadline) {
138             attempt++;
139             NetconfClientDispatcher netconfClientDispatcher = new NetconfClientDispatcher(nettyThreadgroup,
140                     nettyThreadgroup, additionalHeader);
141             NetconfClient netconfClient;
142             try {
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);
148                 continue;
149             }
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;
155             }
156             logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, latestCapabilities);
157             Util.closeClientAndDispatcher(netconfClient);
158             Thread.sleep(delayMillis);
159         }
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);
165     }
166
167
168     private synchronized void pushLastConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfClient netconfClient)
169             throws ConflictingVersionException, IOException, SAXException {
170
171         Element xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
172         logger.trace("Pushing last configuration to netconf: {}", configSnapshotHolder);
173         StringBuilder response = new StringBuilder("editConfig response = {");
174
175         NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
176
177         // sending message to netconf
178         NetconfMessage responseMessage = getResponse(message, netconfClient);
179
180         NetconfUtil.checkIsMessageOk(responseMessage);
181         response.append(XmlUtil.toString(responseMessage.getDocument()));
182         response.append("}");
183         responseMessage = getResponse(getNetconfMessageFromResource("/netconfOp/commit.xml"), netconfClient);
184
185
186
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);
193     }
194
195     private static NetconfMessage getResponse(NetconfMessage request, NetconfClient netconfClient) {
196         try {
197             return netconfClient.sendMessage(request, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
198         } catch(RuntimeException e) {
199             logger.error("Error while sending message {} to {}", request, netconfClient);
200             throw e;
201         }
202     }
203
204     private static NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
205         try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcename)) {
206             Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
207
208             Document doc = XmlUtil.readXmlToDocument(stream);
209
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));
216             }
217             editConfigElement.appendChild(configWrapper.getDomElement());
218             return new NetconfMessage(doc);
219         } catch (IOException | SAXException e) {
220             throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
221         }
222     }
223
224     private static NetconfMessage getNetconfMessageFromResource(String resource) {
225         try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
226             Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
227             return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
228         } catch (SAXException | IOException e) {
229             throw new RuntimeException("Unable to parse message from resources " + resource, e);
230         }
231     }
232 }