Merge "Fix race conditions between config-manager and persister."
[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                 } catch(ConflictingVersionException e) {
113                     closeClientAndDispatcher(netconfClient, netconfClientDispatcher);
114                     lastException = e;
115                     Thread.sleep(1000);
116                 } catch (SAXException | IOException e) {
117                     throw new IllegalStateException("Unable to load last config", e);
118                 }
119             }
120             throw new IllegalStateException("Failed to push configuration, maximum attempt count has been reached: "
121                     + maxAttempts, lastException);
122
123         } else {
124             // this ensures that netconf is initialized, this is first
125             // connection
126             // this means we can register as listener for commit
127             registerToNetconf(Collections.<String>emptySet());
128
129             logger.info("No last config provided by backend storage {}", persister);
130         }
131         registerAsJMXListener();
132     }
133
134     private synchronized long registerToNetconf(Set<String> expectedCaps) throws InterruptedException {
135
136         Set<String> currentCapabilities = Sets.newHashSet();
137
138         // TODO think about moving capability subset check to netconf client
139         // could be utilized by integration tests
140
141         long pollingStart = System.currentTimeMillis();
142         int delay = 5000;
143
144         int attempt = 0;
145
146         long deadline = pollingStart + timeout;
147         while (System.currentTimeMillis() < deadline) {
148             attempt++;
149             netconfClientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
150             try {
151                 netconfClient = new NetconfClient(this.toString(), address, delay, netconfClientDispatcher);
152             } catch (IllegalStateException e) {
153                 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
154                 netconfClientDispatcher.close();
155                 Thread.sleep(delay);
156                 continue;
157             }
158             currentCapabilities = netconfClient.getCapabilities();
159
160             if (isSubset(currentCapabilities, expectedCaps)) {
161                 logger.debug("Hello from netconf stable with {} capabilities", currentCapabilities);
162                 long currentSessionId = netconfClient.getSessionId();
163                 logger.info("Session id received from netconf server: {}", currentSessionId);
164                 return currentSessionId;
165             }
166
167
168
169             logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, currentCapabilities);
170
171             closeClientAndDispatcher(netconfClient, netconfClientDispatcher);
172
173             Thread.sleep(delay);
174         }
175         Set<String> allNotFound = new HashSet<>(expectedCaps);
176         allNotFound.removeAll(currentCapabilities);
177         logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
178                 allNotFound, expectedCaps ,currentCapabilities);
179         throw new RuntimeException("Netconf server did not provide required capabilities. Expected but not found:" + allNotFound);
180
181     }
182
183     private static void closeClientAndDispatcher(Closeable client, Closeable dispatcher) {
184         Exception fromClient = null;
185         try {
186             client.close();
187         } catch (Exception e) {
188             fromClient = e;
189         } finally {
190             try {
191                 dispatcher.close();
192             } catch (Exception e) {
193                 if (fromClient != null) {
194                     e.addSuppressed(fromClient);
195                 }
196
197                 throw new RuntimeException("Error closing temporary client ", e);
198             }
199         }
200     }
201
202     private boolean isSubset(Set<String> currentCapabilities, Set<String> expectedCaps) {
203         for (String exCap : expectedCaps) {
204             if (currentCapabilities.contains(exCap) == false)
205                 return false;
206         }
207         return true;
208     }
209
210     private void registerAsJMXListener() {
211         try {
212             mbeanServer.addNotificationListener(on, this, null, null);
213         } catch (InstanceNotFoundException | IOException e) {
214             throw new RuntimeException("Cannot register as JMX listener to netconf", e);
215         }
216     }
217
218     @Override
219     public void handleNotification(Notification notification, Object handback) {
220         if (notification instanceof NetconfJMXNotification == false)
221             return;
222
223         // Socket should not be closed at this point
224         // Activator unregisters this as JMX listener before close is called
225
226         logger.debug("Received notification {}", notification);
227         if (notification instanceof CommitJMXNotification) {
228             try {
229                 handleAfterCommitNotification((CommitJMXNotification) notification);
230             } catch (Exception e) {
231                 // TODO: notificationBroadcast support logs only DEBUG
232                 logger.warn("Exception occured during notification handling: ", e);
233                 throw e;
234             }
235         } else
236             throw new IllegalStateException("Unknown config registry notification type " + notification);
237     }
238
239     private void handleAfterCommitNotification(final CommitJMXNotification notification) {
240         try {
241             persister.persistConfig(new CapabilityStrippingConfigSnapshotHolder(notification.getConfigSnapshot(),
242                     notification.getCapabilities(), ignoredMissingCapabilityRegex));
243             logger.debug("Configuration persisted successfully");
244         } catch (IOException e) {
245             throw new RuntimeException("Unable to persist configuration snapshot", e);
246         }
247     }
248
249     private Optional<ConfigSnapshotHolder> loadLastConfig() {
250         Optional<ConfigSnapshotHolder> maybeConfigElement;
251         try {
252             maybeConfigElement = persister.loadLastConfig();
253         } catch (IOException e) {
254             throw new RuntimeException("Unable to load configuration", e);
255         }
256         return maybeConfigElement;
257     }
258
259     private synchronized void pushLastConfig(Element xmlToBePersisted) throws ConflictingVersionException {
260         logger.info("Pushing last configuration to netconf");
261         StringBuilder response = new StringBuilder("editConfig response = {");
262
263
264         NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
265
266         // sending message to netconf
267         NetconfMessage responseMessage = netconfClient.sendMessage(message, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
268
269         XmlElement element = XmlElement.fromDomDocument(responseMessage.getDocument());
270         Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
271         element = element.getOnlyChildElement();
272
273         checkIsOk(element, responseMessage);
274         response.append(XmlUtil.toString(responseMessage.getDocument()));
275         response.append("}");
276         responseMessage = netconfClient.sendMessage(getNetconfMessageFromResource("/netconfOp/commit.xml"), NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
277
278         element = XmlElement.fromDomDocument(responseMessage.getDocument());
279         Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
280         element = element.getOnlyChildElement();
281
282         checkIsOk(element, responseMessage);
283         response.append("commit response = {");
284         response.append(XmlUtil.toString(responseMessage.getDocument()));
285         response.append("}");
286         logger.info("Last configuration loaded successfully");
287         logger.trace("Detailed message {}", response);
288     }
289
290     static void checkIsOk(XmlElement element, NetconfMessage responseMessage) throws ConflictingVersionException {
291         if (element.getName().equals(XmlNetconfConstants.OK)) {
292             return;
293         }
294
295         if (element.getName().equals(XmlNetconfConstants.RPC_ERROR)) {
296             logger.warn("Can not load last configuration, operation failed");
297             // is it ConflictingVersionException ?
298             XPathExpression xPathExpression = XMLNetconfUtil.compileXPath("/netconf:rpc-reply/netconf:rpc-error/netconf:error-info/netconf:error");
299             String error = (String) XmlUtil.evaluateXPath(xPathExpression, element.getDomElement(), XPathConstants.STRING);
300             if (error!=null && error.contains(ConflictingVersionException.class.getCanonicalName())) {
301                 throw new ConflictingVersionException(error);
302             }
303             throw new IllegalStateException("Can not load last configuration, operation failed: "
304                     + XmlUtil.toString(responseMessage.getDocument()));
305         }
306
307         logger.warn("Can not load last configuration. Operation failed.");
308         throw new IllegalStateException("Can not load last configuration. Operation failed: "
309                 + XmlUtil.toString(responseMessage.getDocument()));
310     }
311
312     private static NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
313         try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcename)) {
314             Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
315
316             Document doc = XmlUtil.readXmlToDocument(stream);
317
318             doc.getDocumentElement();
319             XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
320             XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
321             editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
322             for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
323                 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
324             }
325             editConfigElement.appendChild(configWrapper.getDomElement());
326             return new NetconfMessage(doc);
327         } catch (IOException | SAXException e) {
328             throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
329         }
330     }
331
332     private NetconfMessage getNetconfMessageFromResource(String resource) {
333         try (InputStream stream = getClass().getResourceAsStream(resource)) {
334             Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
335             return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
336         } catch (SAXException | IOException e) {
337             throw new RuntimeException("Unable to parse message from resources " + resource, e);
338         }
339     }
340
341     @Override
342     public synchronized void close() {
343         // TODO persister is received from constructor, should not be closed
344         // here
345         try {
346             persister.close();
347         } catch (Exception e) {
348             logger.warn("Unable to close config persister {}", persister, e);
349         }
350
351         if (netconfClient != null) {
352             try {
353                 netconfClient.close();
354             } catch (Exception e) {
355                 logger.warn("Unable to close connection to netconf {}", netconfClient, e);
356             }
357         }
358
359         if (netconfClientDispatcher != null) {
360             try {
361                 netconfClientDispatcher.close();
362             } catch (Exception e) {
363                 logger.warn("Unable to close connection to netconf {}", netconfClientDispatcher, e);
364             }
365         }
366
367         try {
368             nettyThreadgroup.shutdownGracefully();
369         } catch (Exception e) {
370             logger.warn("Unable to close netconf client thread group {}", netconfClientDispatcher, e);
371         }
372
373         // unregister from JMX
374         try {
375             if (mbeanServer.isRegistered(on)) {
376                 mbeanServer.removeNotificationListener(on, this);
377             }
378         } catch (Exception e) {
379             logger.warn("Unable to unregister {} as listener for {}", this, on, e);
380         }
381     }
382 }