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