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;
44 import java.util.HashSet;
46 import java.util.regex.Pattern;
49 * Responsible for listening for notifications from netconf containing latest
50 * committed configuration that should be persisted, and also for loading last
54 public class ConfigPersisterNotificationHandler implements NotificationListener, Closeable {
56 private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterNotificationHandler.class);
57 private static final int NETCONF_SEND_ATTEMPT_MS_DELAY = 1000;
58 private static final int NETCONF_SEND_ATTEMPTS = 20;
60 private final InetSocketAddress address;
61 private final EventLoopGroup nettyThreadgroup;
63 private NetconfClientDispatcher netconfClientDispatcher;
64 private NetconfClient netconfClient;
66 private final Persister persister;
67 private final MBeanServerConnection mbeanServer;
68 private Long currentSessionId;
70 private final ObjectName on = DefaultCommitOperationMXBean.objectName;
72 public static final long DEFAULT_TIMEOUT = 120000L;// 120 seconds until netconf must be stable
73 private final long timeout;
74 private final Pattern ignoredMissingCapabilityRegex;
76 public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
77 MBeanServerConnection mbeanServer, Pattern ignoredMissingCapabilityRegex) {
78 this(persister, address, mbeanServer, DEFAULT_TIMEOUT, ignoredMissingCapabilityRegex);
82 public ConfigPersisterNotificationHandler(Persister persister, InetSocketAddress address,
83 MBeanServerConnection mbeanServer, long timeout, Pattern ignoredMissingCapabilityRegex) {
84 this.persister = persister;
85 this.address = address;
86 this.mbeanServer = mbeanServer;
87 this.timeout = timeout;
89 this.nettyThreadgroup = new NioEventLoopGroup();
90 this.ignoredMissingCapabilityRegex = ignoredMissingCapabilityRegex;
93 public void init() throws InterruptedException {
94 Optional<Persister.ConfigSnapshotHolder> maybeConfig = loadLastConfig();
96 if (maybeConfig.isPresent()) {
97 logger.debug("Last config found {}", persister);
99 registerToNetconf(maybeConfig.get().getCapabilities());
101 final String configSnapshot = maybeConfig.get().getConfigSnapshot();
102 logger.trace("Pushing following xml to netconf {}", configSnapshot);
104 pushLastConfig(XmlUtil.readXmlToElement(configSnapshot));
105 } catch (SAXException | IOException e) {
106 throw new IllegalStateException("Unable to load last config", e);
110 // this ensures that netconf is initialized, this is first
112 // this means we can register as listener for commit
113 registerToNetconf(Collections.<String>emptySet());
115 logger.info("No last config provided by backend storage {}", persister);
117 registerAsJMXListener();
120 private synchronized long registerToNetconf(Set<String> expectedCaps) throws InterruptedException {
122 Set<String> currentCapabilities = Sets.newHashSet();
124 // TODO think about moving capability subset check to netconf client
125 // could be utilized by integration tests
127 long pollingStart = System.currentTimeMillis();
135 netconfClientDispatcher = new NetconfClientDispatcher(Optional.<SSLContext>absent(), nettyThreadgroup, nettyThreadgroup);
137 netconfClient = new NetconfClient(this.toString(), address, delay, netconfClientDispatcher);
138 } catch (IllegalStateException e) {
139 logger.debug("Netconf {} was not initialized or is not stable, attempt {}", address, attempt, e);
140 netconfClientDispatcher.close();
144 currentCapabilities = netconfClient.getCapabilities();
146 if (isSubset(currentCapabilities, expectedCaps)) {
147 logger.debug("Hello from netconf stable with {} capabilities", currentCapabilities);
148 currentSessionId = netconfClient.getSessionId();
149 logger.info("Session id received from netconf server: {}", currentSessionId);
150 return currentSessionId;
153 if (System.currentTimeMillis() > pollingStart + timeout) {
157 logger.debug("Polling hello from netconf, attempt {}, capabilities {}", attempt, currentCapabilities);
159 closeClientAndDispatcher(netconfClient, netconfClientDispatcher);
163 Set<String> allNotFound = new HashSet<>(expectedCaps);
164 allNotFound.removeAll(currentCapabilities);
165 logger.error("Netconf server did not provide required capabilities. Expected but not found: {}, all expected {}, current {}",
166 allNotFound, expectedCaps ,currentCapabilities);
167 throw new RuntimeException("Netconf server did not provide required capabilities. Expected but not found:" + allNotFound);
171 private static void closeClientAndDispatcher(Closeable client, Closeable dispatcher) {
172 Exception fromClient = null;
175 } catch (Exception e) {
180 } catch (Exception e) {
181 if (fromClient != null) {
182 e.addSuppressed(fromClient);
185 throw new RuntimeException("Error closing temporary client ", e);
190 private boolean isSubset(Set<String> currentCapabilities, Set<String> expectedCaps) {
191 for (String exCap : expectedCaps) {
192 if (currentCapabilities.contains(exCap) == false)
198 private void registerAsJMXListener() {
200 mbeanServer.addNotificationListener(on, this, null, null);
201 } catch (InstanceNotFoundException | IOException e) {
202 throw new RuntimeException("Cannot register as JMX listener to netconf", e);
207 public void handleNotification(Notification notification, Object handback) {
208 if (notification instanceof NetconfJMXNotification == false)
211 // Socket should not be closed at this point
212 // Activator unregisters this as JMX listener before close is called
214 logger.debug("Received notification {}", notification);
215 if (notification instanceof CommitJMXNotification) {
217 handleAfterCommitNotification((CommitJMXNotification) notification);
218 } catch (Exception e) {
219 // TODO: notificationBroadcast support logs only DEBUG
220 logger.warn("Exception occured during notification handling: ", e);
224 throw new IllegalStateException("Unknown config registry notification type " + notification);
227 private void handleAfterCommitNotification(final CommitJMXNotification notification) {
229 persister.persistConfig(new CapabilityStrippingConfigSnapshotHolder(notification.getConfigSnapshot(),
230 notification.getCapabilities(), ignoredMissingCapabilityRegex));
231 logger.debug("Configuration persisted successfully");
232 } catch (IOException e) {
233 throw new RuntimeException("Unable to persist configuration snapshot", e);
237 private Optional<Persister.ConfigSnapshotHolder> loadLastConfig() {
238 Optional<Persister.ConfigSnapshotHolder> maybeConfigElement;
240 maybeConfigElement = persister.loadLastConfig();
241 } catch (IOException e) {
242 throw new RuntimeException("Unable to load configuration", e);
244 return maybeConfigElement;
247 private synchronized void pushLastConfig(Element xmlToBePersisted) {
248 logger.info("Pushing last configuration to netconf");
249 StringBuilder response = new StringBuilder("editConfig response = {");
252 NetconfMessage message = createEditConfigMessage(xmlToBePersisted, "/netconfOp/editConfig.xml");
254 // sending message to netconf
255 NetconfMessage responseMessage = netconfClient.sendMessage(message, NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
257 XmlElement element = XmlElement.fromDomDocument(responseMessage.getDocument());
258 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
259 element = element.getOnlyChildElement();
261 checkIsOk(element, responseMessage);
262 response.append(XmlUtil.toString(responseMessage.getDocument()));
263 response.append("}");
264 responseMessage = netconfClient.sendMessage(getNetconfMessageFromResource("/netconfOp/commit.xml"), NETCONF_SEND_ATTEMPTS, NETCONF_SEND_ATTEMPT_MS_DELAY);
266 element = XmlElement.fromDomDocument(responseMessage.getDocument());
267 Preconditions.checkState(element.getName().equals(XmlNetconfConstants.RPC_REPLY_KEY));
268 element = element.getOnlyChildElement();
270 checkIsOk(element, responseMessage);
271 response.append("commit response = {");
272 response.append(XmlUtil.toString(responseMessage.getDocument()));
273 response.append("}");
274 logger.info("Last configuration loaded successfully");
275 logger.trace("Detailed message {}", response);
278 private void checkIsOk(XmlElement element, NetconfMessage responseMessage) {
279 if (element.getName().equals(XmlNetconfConstants.OK)) {
282 if (element.getName().equals(XmlNetconfConstants.RPC_ERROR)) {
283 logger.warn("Can not load last configuration, operation failed");
284 throw new IllegalStateException("Can not load last configuration, operation failed: "
285 + XmlUtil.toString(responseMessage.getDocument()));
287 logger.warn("Can not load last configuration. Operation failed.");
288 throw new IllegalStateException("Can not load last configuration. Operation failed: "
289 + XmlUtil.toString(responseMessage.getDocument()));
293 private static NetconfMessage createEditConfigMessage(Element dataElement, String editConfigResourcename) {
294 try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcename)) {
295 Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcename);
297 Document doc = XmlUtil.readXmlToDocument(stream);
299 doc.getDocumentElement();
300 XmlElement editConfigElement = XmlElement.fromDomDocument(doc).getOnlyChildElement();
301 XmlElement configWrapper = editConfigElement.getOnlyChildElement(XmlNetconfConstants.CONFIG_KEY);
302 editConfigElement.getDomElement().removeChild(configWrapper.getDomElement());
303 for (XmlElement el : XmlElement.fromDomElement(dataElement).getChildElements()) {
304 configWrapper.appendChild((Element) doc.importNode(el.getDomElement(), true));
306 editConfigElement.appendChild(configWrapper.getDomElement());
307 return new NetconfMessage(doc);
308 } catch (IOException | SAXException e) {
309 throw new RuntimeException("Unable to parse message from resources " + editConfigResourcename, e);
313 private NetconfMessage getNetconfMessageFromResource(String resource) {
314 try (InputStream stream = getClass().getResourceAsStream(resource)) {
315 Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
316 return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
317 } catch (SAXException | IOException e) {
318 throw new RuntimeException("Unable to parse message from resources " + resource, e);
323 public synchronized void close() {
324 // TODO persister is received from constructor, should not be closed
328 } catch (Exception e) {
329 logger.warn("Unable to close config persister {}", persister, e);
332 if (netconfClient != null) {
334 netconfClient.close();
335 } catch (Exception e) {
336 logger.warn("Unable to close connection to netconf {}", netconfClient, e);
340 if (netconfClientDispatcher != null) {
342 netconfClientDispatcher.close();
343 } catch (Exception e) {
344 logger.warn("Unable to close connection to netconf {}", netconfClientDispatcher, e);
349 nettyThreadgroup.shutdownGracefully();
350 } catch (Exception e) {
351 logger.warn("Unable to close netconf client thread group {}", netconfClientDispatcher, e);
354 // unregister from JMX
356 if (mbeanServer.isRegistered(on)) {
357 mbeanServer.removeNotificationListener(on, this);
359 } catch (Exception e) {
360 logger.warn("Unable to unregister {} as listener for {}", this, on, e);