2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.persist.impl;
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;
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;
47 * Responsible for listening for notifications from netconf containing latest
48 * committed configuration that should be persisted, and also for loading last
52 public class ConfigPersisterNotificationHandler implements NotificationListener, Closeable {
54 private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
56 private final InetSocketAddress address;
57 private final NetconfClientDispatcher dispatcher;
58 private final EventLoopGroup nettyThreadgroup;
60 private NetconfClient netconfClient;
62 private final Persister persister;
63 private final MBeanServerConnection mbeanServer;
64 private Long currentSessionId;
66 private final ObjectName on = DefaultCommitOperationMXBean.objectName;
68 public static final long DEFAULT_TIMEOUT = 40000L;
69 private final long timeout;
71 public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
72 MBeanServerConnection mbeanServer) {
73 this(persister, address, mbeanServer, DEFAULT_TIMEOUT);
76 public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
77 MBeanServerConnection mbeanServer, long timeout) {
78 this.persister = persister;
79 this.address = address;
80 this.mbeanServer = mbeanServer;
81 this.timeout = timeout;
83 this.nettyThreadgroup = new NioEventLoopGroup();
84 this.dispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
87 public void init() throws InterruptedException {
88 Optional<Persister.ConfigSnapshotHolder> maybeConfig = loadLastConfig();
90 if (maybeConfig.isPresent()) {
91 logger.debug("Last config found {}", persister);
93 registerToNetconf(maybeConfig.get().getCapabilities());
95 final String configSnapshot = maybeConfig.get().getConfigSnapshot();
97 pushLastConfig(XmlUtil.readXmlToElement(configSnapshot));
98 } catch (SAXException | IOException e) {
99 throw new IllegalStateException("Unable to load last config", e);
103 // this ensures that netconf is initialized, this is first
105 // this means we can register as listener for commit
106 registerToNetconf(Collections.<String>emptySet());
108 logger.info("No last config provided by backend storage {}", persister);
110 registerAsJMXListener();
113 private synchronized long registerToNetconf(Set<String> expectedCaps) throws InterruptedException {
115 Set<String> currentCapabilities = Sets.newHashSet();
117 // TODO think about moving capability subset check to netconf client
118 // could be utilized by integration tests
120 long pollingStart = System.currentTimeMillis();
129 netconfClient = new NetconfClient(this.toString(), address, delay, dispatcher);
130 // TODO is this correct ex to catch ?
131 } catch (IllegalStateException e) {
132 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
136 currentCapabilities = netconfClient.getCapabilities();
138 if (isSubset(currentCapabilities, expectedCaps)) {
139 logger.debug("Hello from netconf stable with {} capabilities", currentCapabilities);
140 currentSessionId = netconfClient.getSessionId();
141 logger.info("Session id received from netconf server: {}", currentSessionId);
142 return currentSessionId;
145 if (System.currentTimeMillis() > pollingStart + timeout) {
149 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, currentCapabilities);
152 netconfClient.close();
153 } catch (IOException e) {
154 throw new RuntimeException("Error closing temporary client " + netconfClient);
160 throw new RuntimeException("Netconf server did not provide required capabilities " + expectedCaps
161 + " in time, provided capabilities " + currentCapabilities);
165 private boolean isSubset(Set<String> currentCapabilities, Set<String> expectedCaps) {
166 for (String exCap : expectedCaps) {
167 if (currentCapabilities.contains(exCap) == false)
173 private void registerAsJMXListener() {
175 mbeanServer.addNotificationListener(on, this, null, null);
176 } catch (InstanceNotFoundException | IOException e) {
177 throw new RuntimeException("Cannot register as JMX listener to netconf", e);
182 public void handleNotification(Notification notification, Object handback) {
183 if (notification instanceof NetconfJMXNotification == false)
186 // Socket should not be closed at this point
187 // Activator unregisters this as JMX listener before close is called
189 logger.debug("Received notification {}", notification);
190 if (notification instanceof CommitJMXNotification) {
192 handleAfterCommitNotification((CommitJMXNotification) notification);
193 } catch (Exception e) {
194 // TODO: notificationBroadcast support logs only DEBUG
195 logger.warn("Exception occured during notification handling: ", e);
199 throw new IllegalStateException("Unknown config registry notification type " + notification);
202 private void handleAfterCommitNotification(final CommitJMXNotification notification) {
204 final XmlElement configElement = XmlElement.fromDomElement(notification.getConfigSnapshot());
205 persister.persistConfig(new Persister.ConfigSnapshotHolder() {
207 public String getConfigSnapshot() {
208 return XmlUtil.toString(configElement.getDomElement());
212 public Set<String> getCapabilities() {
213 return notification.getCapabilities();
216 logger.debug("Configuration persisted successfully");
217 } catch (IOException e) {
218 throw new RuntimeException("Unable to persist configuration snapshot", e);
222 private Optional<Persister.ConfigSnapshotHolder> loadLastConfig() {
223 Optional<Persister.ConfigSnapshotHolder> maybeConfigElement;
225 maybeConfigElement = persister.loadLastConfig();
226 } catch (IOException e) {
227 throw new RuntimeException("Unable to load configuration", e);
229 return maybeConfigElement;
232 private synchronized void pushLastConfig(Element persistedConfig) {
233 StringBuilder response = new StringBuilder("editConfig response = {");
235 Element configElement = persistedConfig;
236 NetconfMessage message = createEditConfigMessage(configElement, "/netconfOp/editConfig.xml");
237 NetconfMessage responseMessage = netconfClient.sendMessage(message);
239 XmlElement element = XmlElement.fromDomDocument(responseMessage.getDocument());
240 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
241 element = element.getOnlyChildElement();
243 checkIsOk(element, responseMessage);
244 response.append(XmlUtil.toString(responseMessage.getDocument()));
245 response.append("}");
246 responseMessage = netconfClient.sendMessage(getNetconfMessageFromResource("/netconfOp/commit.xml"));
248 element = XmlElement.fromDomDocument(responseMessage.getDocument());
249 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
250 element = element.getOnlyChildElement();
252 checkIsOk(element, responseMessage);
253 response.append("commit response = {");
254 response.append(XmlUtil.toString(responseMessage.getDocument()));
255 response.append("}");
256 logger.debug("Last configuration loaded successfully");
259 private void checkIsOk(XmlElement element, NetconfMessage responseMessage) {
260 if (element.getName().equals(XmlNetconfConstants.OK)) {
263 if (element.getName().equals(XmlNetconfConstants.RPC_ERROR)) {
264 logger.warn("Can not load last configuration, operation failed");
265 throw new IllegalStateException("Can not load last configuration, operation failed: "
266 + XmlUtil.toString(responseMessage.getDocument()));
268 logger.warn("Can not load last configuration. Operation failed.");
269 throw new IllegalStateException("Can not load last configuration. Operation failed: "
270 + XmlUtil.toString(responseMessage.getDocument()));
274 private NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
275 try (InputStream stream = getClass().getResourceAsStream(editConfigResourcename)) {
276 Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
278 Document doc = XmlUtil.readXmlToDocument(stream);
280 doc.getDocumentElement();
281 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
282 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
283 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
284 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
285 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
287 editConfigElement.appendChild(configWrapper.getDomElement());
288 return new NetconfMessage(doc);
289 } catch (IOException | SAXException e) {
290 throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
294 private NetconfMessage getNetconfMessageFromResource(String resource) {
295 try (InputStream stream = getClass().getResourceAsStream(resource)) {
296 Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
297 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
298 } catch (SAXException | IOException e) {
299 throw new RuntimeException("Unable to parse message from resources " + resource, e);
304 public synchronized void close() {
305 // TODO persister is received from constructor, should not be closed
309 } catch (Exception e) {
310 logger.warn("Unable to close config persister {}", persister, e);
313 if (netconfClient != null) {
315 netconfClient.close();
316 } catch (Exception e) {
317 logger.warn("Unable to close connection to netconf {}", netconfClient, e);
322 nettyThreadgroup.shutdownGracefully();
323 } catch (Exception e) {
324 logger.warn("Unable to close netconf client thread group {}", dispatcher, e);
327 // unregister from JMX
329 if (mbeanServer.isRegistered(on)) {
330 mbeanServer.removeNotificationListener(on, this);
332 } catch (Exception e) {
333 logger.warn("Unable to unregister {} as listener for {}", this, on, e);