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