Merge "Fix bug in persister causing to persist last configuration in a loop."
[controller.git] / opendaylight / netconf / config-persister-impl / src / main / java / org / opendaylight / controller / netconf / persist / impl / ConfigPersisterNotificationHandler.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 com.google.common.collect.Sets;
14 import io.netty.channel.EventLoopGroup;
15 import io.netty.channel.nio.NioEventLoopGroup;
16 import org.opendaylight.controller.config.api.ConflictingVersionException;
17 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
18 import org.opendaylight.controller.config.persist.api.Persister;
19 import org.opendaylight.controller.netconf.api.NetconfMessage;
20 import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
21 import org.opendaylight.controller.netconf.api.jmx.DefaultCommitOperationMXBean;
22 import org.opendaylight.controller.netconf.api.jmx.NetconfJMXNotification;
23 import org.opendaylight.controller.netconf.client.NetconfClient;
24 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
25 import org.opendaylight.controller.netconf.util.xml.XMLNetconfUtil;
26 import org.opendaylight.controller.netconf.util.xml.XmlElement;
27 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
28 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.w3c.dom.Document;
32 import org.w3c.dom.Element;
33 import org.xml.sax.SAXException;
34
35 import javax.annotation.concurrent.ThreadSafe;
36 import javax.management.InstanceNotFoundException;
37 import javax.management.MBeanServerConnection;
38 import javax.management.Notification;
39 import javax.management.NotificationListener;
40 import javax.management.ObjectName;
41 import javax.net.ssl.SSLContext;
42 import javax.xml.xpath.XPathConstants;
43 import javax.xml.xpath.XPathExpression;
44 import java.io.Closeable;
45 import java.io.IOException;
46 import java.io.InputStream;
47 import java.net.InetSocketAddress;
48 import java.util.Collections;
49 import java.util.HashSet;
50 import java.util.Set;
51 import java.util.regex.Pattern;
52
53 /**
54  * Responsible for listening for notifications from netconf containing latest
55  * committed configuration that should be persisted, and also for loading last
56  * configuration.
57  */
58 @ThreadSafe
59 public class ConfigPersisterNotificationHandler implements NotificationListener, Closeable {
60
61     private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
62     private static final int NETCONF_SEND_ATTEMPT_MS_DELAY = 1000;
63     private static final int NETCONF_SEND_ATTEMPTS = 20;
64
65     private final InetSocketAddress address;
66     private final EventLoopGroup nettyThreadgroup;
67
68     private NetconfClientDispatcher netconfClientDispatcher;
69     private NetconfClient netconfClient;
70
71     private final Persister persister;
72     private final MBeanServerConnection mbeanServer;
73
74
75     private final ObjectName on = DefaultCommitOperationMXBean.objectName;
76
77     public static final long DEFAULT_TIMEOUT = 120000L;// 120 seconds until netconf must be stable
78     private final long timeout;
79     private final Pattern ignoredMissingCapabilityRegex;
80
81     public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
82             MBeanServerConnection mbeanServer, Pattern ignoredMissingCapabilityRegex) {
83         this(persister, address, mbeanServer, DEFAULT_TIMEOUT, ignoredMissingCapabilityRegex);
84
85     }
86
87     public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
88             MBeanServerConnection mbeanServer, long timeout, Pattern ignoredMissingCapabilityRegex) {
89         this.persister = persister;
90         this.address = address;
91         this.mbeanServer = mbeanServer;
92         this.timeout = timeout;
93
94         this.nettyThreadgroup = new NioEventLoopGroup();
95         this.ignoredMissingCapabilityRegex = ignoredMissingCapabilityRegex;
96     }
97
98     public void init() throws InterruptedException {
99         Optional<ConfigSnapshotHolder> maybeConfig = loadLastConfig();
100
101         if (maybeConfig.isPresent()) {
102             logger.debug("Last config found {}", persister);
103             ConflictingVersionException lastException = null;
104             int maxAttempts = 30;
105             for(int i = 0 ; i < maxAttempts; i++) {
106                 registerToNetconf(maybeConfig.get().getCapabilities());
107
108                 final String configSnapshot = maybeConfig.get().getConfigSnapshot();
109                 logger.trace("Pushing following xml to netconf {}", configSnapshot);
110                 try {
111                     pushLastConfig(XmlUtil.readXmlToElement(configSnapshot));
112                     return;
113                 } catch(ConflictingVersionException e) {
114                     closeClientAndDispatcher(netconfClient, netconfClientDispatcher);
115                     lastException = e;
116                     Thread.sleep(1000);
117                 } catch (SAXException | IOException e) {
118                     throw new IllegalStateException("Unable to load last config", e);
119                 }
120             }
121             throw new IllegalStateException("Failed to push configuration, maximum attempt count has been reached: "
122                     + maxAttempts, lastException);
123
124         } else {
125             // this ensures that netconf is initialized, this is first
126             // connection
127             // this means we can register as listener for commit
128             registerToNetconf(Collections.<String>emptySet());
129
130             logger.info("No last config provided by backend storage {}", persister);
131         }
132         registerAsJMXListener();
133     }
134
135     private synchronized long registerToNetconf(Set<String> expectedCaps) throws InterruptedException {
136
137         Set<String> currentCapabilities = Sets.newHashSet();
138
139         // TODO think about moving capability subset check to netconf client
140         // could be utilized by integration tests
141
142         long pollingStart = System.currentTimeMillis();
143         int delay = 5000;
144
145         int attempt = 0;
146
147         long deadline = pollingStart + timeout;
148         while (System.currentTimeMillis() < deadline) {
149             attempt++;
150             netconfClientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
151             try {
152                 netconfClient = new NetconfClient(this.toString(), address, delay, netconfClientDispatcher);
153             } catch (IllegalStateException e) {
154                 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
155                 netconfClientDispatcher.close();
156                 Thread.sleep(delay);
157                 continue;
158             }
159             currentCapabilities = netconfClient.getCapabilities();
160
161             if (isSubset(currentCapabilities, expectedCaps)) {
162                 logger.debug("Hello from netconf stable with {} capabilities", currentCapabilities);
163                 long currentSessionId = netconfClient.getSessionId();
164                 logger.info("Session id received from netconf server: {}", currentSessionId);
165                 return currentSessionId;
166             }
167
168
169
170             logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, currentCapabilities);
171
172             closeClientAndDispatcher(netconfClient, netconfClientDispatcher);
173
174             Thread.sleep(delay);
175         }
176         Set<String> allNotFound = new HashSet<>(expectedCaps);
177         allNotFound.removeAll(currentCapabilities);
178         logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
179                 allNotFound, expectedCaps ,currentCapabilities);
180         throw new RuntimeException("Netconf server did not provide required capabilities. Expected but not found:" + allNotFound);
181
182     }
183
184     private static void closeClientAndDispatcher(Closeable client, Closeable dispatcher) {
185         Exception fromClient = null;
186         try {
187             client.close();
188         } catch (Exception e) {
189             fromClient = e;
190         } finally {
191             try {
192                 dispatcher.close();
193             } catch (Exception e) {
194                 if (fromClient != null) {
195                     e.addSuppressed(fromClient);
196                 }
197
198                 throw new RuntimeException("Error closing temporary client ", e);
199             }
200         }
201     }
202
203     private boolean isSubset(Set<String> currentCapabilities, Set<String> expectedCaps) {
204         for (String exCap : expectedCaps) {
205             if (currentCapabilities.contains(exCap) == false)
206                 return false;
207         }
208         return true;
209     }
210
211     private void registerAsJMXListener() {
212         try {
213             mbeanServer.addNotificationListener(on, this, null, null);
214         } catch (InstanceNotFoundException | IOException e) {
215             throw new RuntimeException("Cannot register as JMX listener to netconf", e);
216         }
217     }
218
219     @Override
220     public void handleNotification(Notification notification, Object handback) {
221         if (notification instanceof NetconfJMXNotification == false)
222             return;
223
224         // Socket should not be closed at this point
225         // Activator unregisters this as JMX listener before close is called
226
227         logger.debug("Received notification {}", notification);
228         if (notification instanceof CommitJMXNotification) {
229             try {
230                 handleAfterCommitNotification((CommitJMXNotification) notification);
231             } catch (Exception e) {
232                 // TODO: notificationBroadcast support logs only DEBUG
233                 logger.warn("Exception occured during notification handling: ", e);
234                 throw e;
235             }
236         } else
237             throw new IllegalStateException("Unknown config registry notification type " + notification);
238     }
239
240     private void handleAfterCommitNotification(final CommitJMXNotification notification) {
241         try {
242             persister.persistConfig(new CapabilityStrippingConfigSnapshotHolder(notification.getConfigSnapshot(),
243                     notification.getCapabilities(), ignoredMissingCapabilityRegex));
244             logger.debug("Configuration persisted successfully");
245         } catch (IOException e) {
246             throw new RuntimeException("Unable to persist configuration snapshot", e);
247         }
248     }
249
250     private Optional<ConfigSnapshotHolder> loadLastConfig() {
251         Optional<ConfigSnapshotHolder> maybeConfigElement;
252         try {
253             maybeConfigElement = persister.loadLastConfig();
254         } catch (IOException e) {
255             throw new RuntimeException("Unable to load configuration", e);
256         }
257         return maybeConfigElement;
258     }
259
260     private synchronized void pushLastConfig(Element xmlToBePersisted) throws ConflictingVersionException {
261         logger.info("Pushing last configuration to netconf");
262         StringBuilder response = new StringBuilder("editConfig response = {");
263
264
265         NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
266
267         // sending message to netconf
268         NetconfMessage responseMessage = netconfClient.sendMessage(message, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
269
270         XmlElement element = XmlElement.fromDomDocument(responseMessage.getDocument());
271         Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
272         element = element.getOnlyChildElement();
273
274         checkIsOk(element, responseMessage);
275         response.append(XmlUtil.toString(responseMessage.getDocument()));
276         response.append("}");
277         responseMessage = netconfClient.sendMessage(getNetconfMessageFromResource("/netconfOp/commit.xml"), NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
278
279         element = XmlElement.fromDomDocument(responseMessage.getDocument());
280         Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
281         element = element.getOnlyChildElement();
282
283         checkIsOk(element, responseMessage);
284         response.append("commit response = {");
285         response.append(XmlUtil.toString(responseMessage.getDocument()));
286         response.append("}");
287         logger.info("Last configuration loaded successfully");
288         logger.trace("Detailed message {}", response);
289     }
290
291     static void checkIsOk(XmlElement element, NetconfMessage responseMessage) throws ConflictingVersionException {
292         if (element.getName().equals(XmlNetconfConstants.OK)) {
293             return;
294         }
295
296         if (element.getName().equals(XmlNetconfConstants.RPC_ERROR)) {
297             logger.warn("Can not load last configuration, operation failed");
298             // is it ConflictingVersionException ?
299             XPathExpression xPathExpression = XMLNetconfUtil.compileXPath("/netconf:rpc-reply/netconf:rpc-error/netconf:error-info/netconf:error");
300             String error = (String) XmlUtil.evaluateXPath(xPathExpression, element.getDomElement(), XPathConstants.STRING);
301             if (error!=null && error.contains(ConflictingVersionException.class.getCanonicalName())) {
302                 throw new ConflictingVersionException(error);
303             }
304             throw new IllegalStateException("Can not load last configuration, operation failed: "
305                     + XmlUtil.toString(responseMessage.getDocument()));
306         }
307
308         logger.warn("Can not load last configuration. Operation failed.");
309         throw new IllegalStateException("Can not load last configuration. Operation failed: "
310                 + XmlUtil.toString(responseMessage.getDocument()));
311     }
312
313     private static NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
314         try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcename)) {
315             Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
316
317             Document doc = XmlUtil.readXmlToDocument(stream);
318
319             doc.getDocumentElement();
320             XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
321             XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
322             editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
323             for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
324                 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
325             }
326             editConfigElement.appendChild(configWrapper.getDomElement());
327             return new NetconfMessage(doc);
328         } catch (IOException | SAXException e) {
329             throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
330         }
331     }
332
333     private NetconfMessage getNetconfMessageFromResource(String resource) {
334         try (InputStream stream = getClass().getResourceAsStream(resource)) {
335             Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
336             return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
337         } catch (SAXException | IOException e) {
338             throw new RuntimeException("Unable to parse message from resources " + resource, e);
339         }
340     }
341
342     @Override
343     public synchronized void close() {
344         // TODO persister is received from constructor, should not be closed
345         // here
346         try {
347             persister.close();
348         } catch (Exception e) {
349             logger.warn("Unable to close config persister {}", persister, e);
350         }
351
352         if (netconfClient != null) {
353             try {
354                 netconfClient.close();
355             } catch (Exception e) {
356                 logger.warn("Unable to close connection to netconf {}", netconfClient, e);
357             }
358         }
359
360         if (netconfClientDispatcher != null) {
361             try {
362                 netconfClientDispatcher.close();
363             } catch (Exception e) {
364                 logger.warn("Unable to close connection to netconf {}", netconfClientDispatcher, e);
365             }
366         }
367
368         try {
369             nettyThreadgroup.shutdownGracefully();
370         } catch (Exception e) {
371             logger.warn("Unable to close netconf client thread group {}", netconfClientDispatcher, e);
372         }
373
374         // unregister from JMX
375         try {
376             if (mbeanServer.isRegistered(on)) {
377                 mbeanServer.removeNotificationListener(on, this);
378             }
379         } catch (Exception e) {
380             logger.warn("Unable to unregister {} as listener for {}", this, on, e);
381         }
382     }
383 }