Merge "Move NetconfUtil to netconf-util."
[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
39 @Immutable
40 public class ConfigPusher {
41     private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
42     private static final int NETCONF_SEND_ATTEMPT_MS_DELAY = 1000;
43     private static final int NETCONF_SEND_ATTEMPTS = 20;
44
45     private final InetSocketAddress address;
46     private final EventLoopGroup nettyThreadgroup;
47
48
49     public static final long DEFAULT_TIMEOUT = 120000L;// 120 seconds until netconf must be stable
50     private final long timeout;
51
52     public ConfigPusher(InetSocketAddress address, EventLoopGroup nettyThreadgroup) {
53         this(address, DEFAULT_TIMEOUT, nettyThreadgroup);
54
55     }
56
57     public ConfigPusher(InetSocketAddress address, long timeout, EventLoopGroup nettyThreadgroup) {
58         this.address = address;
59         this.timeout = timeout;
60
61         this.nettyThreadgroup = nettyThreadgroup;
62     }
63
64     public synchronized NetconfClient init(List<ConfigSnapshotHolder> configs) throws InterruptedException {
65         logger.debug("Last config snapshots to be pushed to netconf: {}", configs);
66         return pushAllConfigs(configs);
67     }
68
69     private synchronized NetconfClient pushAllConfigs(List<ConfigSnapshotHolder> configs) throws InterruptedException {
70         NetconfClient netconfClient = makeNetconfConnection(Collections.<String>emptySet(), Optional.<NetconfClient>absent());
71         for (ConfigSnapshotHolder configSnapshotHolder: configs){
72             netconfClient = pushSnapshotWithRetries(configSnapshotHolder, Optional.of(netconfClient));
73         }
74         return netconfClient;
75     }
76
77     private synchronized NetconfClient pushSnapshotWithRetries(ConfigSnapshotHolder configSnapshotHolder,
78                                                                Optional<NetconfClient> oldClientForPossibleReuse)
79             throws InterruptedException {
80
81         ConflictingVersionException lastException = null;
82         int maxAttempts = 30;
83         for(int i = 0 ; i < maxAttempts; i++) {
84             NetconfClient netconfClient = makeNetconfConnection(configSnapshotHolder.getCapabilities(), oldClientForPossibleReuse);
85             logger.trace("Pushing following xml to netconf {}", configSnapshotHolder);
86             try {
87                 pushLastConfig(configSnapshotHolder, netconfClient);
88                 return netconfClient;
89             } catch(ConflictingVersionException e) {
90                 Util.closeClientAndDispatcher(netconfClient);
91                 lastException = e;
92                 Thread.sleep(1000);
93             } catch (SAXException | IOException e) {
94                 throw new IllegalStateException("Unable to load last config", e);
95             }
96         }
97         throw new IllegalStateException("Failed to push configuration, maximum attempt count has been reached: "
98                 + maxAttempts, lastException);
99     }
100
101     /**
102      * @param expectedCaps capabilities that server hello must contain. Will retry until all are found or throws RuntimeException.
103      *                     If empty set is provided, will only make sure netconf client successfuly connected to the server.
104      * @param oldClientForPossibleReuse if present, try to get expected capabilities from it before closing it and retrying with
105      *                                  new client connection.
106      * @return NetconfClient that has all required capabilities from server.
107      */
108     private synchronized NetconfClient makeNetconfConnection(Set<String> expectedCaps,
109                                                              Optional<NetconfClient> oldClientForPossibleReuse)
110             throws InterruptedException {
111
112         if (oldClientForPossibleReuse.isPresent()) {
113             NetconfClient oldClient = oldClientForPossibleReuse.get();
114             if (Util.isSubset(oldClient, expectedCaps)) {
115                 return oldClient;
116             } else {
117                 Util.closeClientAndDispatcher(oldClient);
118             }
119         }
120
121         // TODO think about moving capability subset check to netconf client
122         // could be utilized by integration tests
123
124         long pollingStart = System.currentTimeMillis();
125         int delay = 5000;
126
127         int attempt = 0;
128
129         long deadline = pollingStart + timeout;
130
131         String additionalHeader = NetconfMessageAdditionalHeader.toString("unknown", address.getAddress().getHostAddress(),
132                 Integer.toString(address.getPort()), "tcp", Optional.of("persister"));
133
134         Set<String> latestCapabilities = new HashSet<>();
135         while (System.currentTimeMillis() < deadline) {
136             attempt++;
137             NetconfClientDispatcher netconfClientDispatcher = new NetconfClientDispatcher(nettyThreadgroup,
138                     nettyThreadgroup, additionalHeader);
139             NetconfClient netconfClient;
140             try {
141                 netconfClient = new NetconfClient(this.toString(), address, delay, 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(delay);
146                 continue;
147             }
148             latestCapabilities = netconfClient.getCapabilities();
149             if (Util.isSubset(netconfClient, expectedCaps)) {
150                 logger.debug("Hello from netconf stable with {} capabilities", latestCapabilities);
151                 logger.info("Session id received from netconf server: {}", netconfClient.getClientSession());
152                 return netconfClient;
153             }
154             logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, latestCapabilities);
155             Util.closeClientAndDispatcher(netconfClient);
156             Thread.sleep(delay);
157         }
158         Set<String> allNotFound = new HashSet<>(expectedCaps);
159         allNotFound.removeAll(latestCapabilities);
160         logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
161                 allNotFound, expectedCaps, latestCapabilities);
162         throw new RuntimeException("Netconf server did not provide required capabilities. Expected but not found:" + allNotFound);
163     }
164
165
166     private synchronized void pushLastConfig(ConfigSnapshotHolder configSnapshotHolder, NetconfClient netconfClient)
167             throws ConflictingVersionException, IOException, SAXException {
168
169         Element xmlToBePersisted = XmlUtil.readXmlToElement(configSnapshotHolder.getConfigSnapshot());
170         logger.info("Pushing last configuration to netconf: {}", configSnapshotHolder);
171         StringBuilder response = new StringBuilder("editConfig response = {");
172
173         NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
174
175         // sending message to netconf
176         NetconfMessage responseMessage = getResponse(message, netconfClient);
177
178         NetconfUtil.checkIsMessageOk(responseMessage);
179         response.append(XmlUtil.toString(responseMessage.getDocument()));
180         response.append("}");
181         responseMessage = getResponse(getNetconfMessageFromResource("/netconfOp/commit.xml"), netconfClient);
182
183
184
185         NetconfUtil.checkIsMessageOk(responseMessage);
186         response.append("commit response = {");
187         response.append(XmlUtil.toString(responseMessage.getDocument()));
188         response.append("}");
189         logger.info("Last configuration loaded successfully");
190         logger.trace("Detailed message {}", response);
191     }
192
193     private static NetconfMessage getResponse(NetconfMessage request, NetconfClient netconfClient) {
194         try {
195             return netconfClient.sendMessage(request, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
196         } catch(RuntimeException e) {
197             logger.error("Error while sending message {} to {}", request, netconfClient);
198             throw e;
199         }
200     }
201
202     private static NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
203         try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcename)) {
204             Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
205
206             Document doc = XmlUtil.readXmlToDocument(stream);
207
208             doc.getDocumentElement();
209             XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
210             XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
211             editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
212             for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
213                 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
214             }
215             editConfigElement.appendChild(configWrapper.getDomElement());
216             return new NetconfMessage(doc);
217         } catch (IOException | SAXException e) {
218             throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
219         }
220     }
221
222     private static NetconfMessage getNetconfMessageFromResource(String resource) {
223         try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
224             Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
225             return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
226         } catch (SAXException | IOException e) {
227             throw new RuntimeException("Unable to parse message from resources " + resource, e);
228         }
229     }
230 }